The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 19:15 UTC
refactor(server): CloudLink fails with its own errors; the connect routes map them to HTTP (#16341)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 5, 2026 at 20:46 UTC
68e50db20b3784bad69dd754165020a08f2cd42a
8 files changed
+577
-337
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+8
-11
@@ -45,7 +45,6 @@ import {
45
managedTunnelStartupAction,
46
retryManagedTunnelRegistration,
47
} from "./managedTunnelStartup.ts";
48
-import { shouldRetryCloudLink } from "./relayResponse.ts";
48
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
49
50
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
@@ -109,10 +108,7 @@ describe("reconcileDesiredCloudLink", () => {
108
const link = yield* CloudLink.CloudLink;
109
const error = yield* Effect.flip(link.reconcileDesiredLink("http://127.0.0.1:3774"));
110
112
- expect(error).toMatchObject({
113
- _tag: "EnvironmentHttpUnauthorizedError",
114
- message: "Run `t3 connect link` to authorize this environment.",
115
- });
111
+ expect(error._tag).toBe("CloudLinkAuthorizationMissingError");
112
}).pipe(
113
Effect.provide(CloudLink.layer),
114
Effect.provideService(HttpServer.HttpServer, idleHttpServer),
@@ -689,7 +685,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
685
link
686
.registerManagedTunnelRecovery(localOrigin)
687
.pipe(Effect.tapError(() => Deferred.succeed(firstFailure, undefined))),
692
- shouldRetryCloudLink,
688
+ CloudLink.shouldRetryCloudLink,
689
link
690
.startManagedTunnelIfOriginConfirmed(localOrigin, {
691
requireConfirmedOrigin: false,
@@ -1051,10 +1047,10 @@ describe("releaseManagedTunnelOnShutdown", () => {
1047
});
1048
1049
it.effect.each([
1054
- { status: 401, errorTag: "EnvironmentHttpUnauthorizedError" },
1055
- { status: 403, errorTag: "EnvironmentHttpForbiddenError" },
1056
- { status: 409, errorTag: "EnvironmentHttpBadRequestError" },
1057
- ])("preserves a permanent $status relay recovery failure", ({ status, errorTag }) => {
1050
+ { status: 401, rejection: "unauthorized" },
1051
+ { status: 403, rejection: "forbidden" },
1052
+ { status: 409, rejection: "rejected" },
1053
+ ])("preserves a permanent $status relay recovery failure", ({ status, rejection }) => {
1054
const { store } = makeMemorySecretStore([
1055
[CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1056
[RELAY_URL_SECRET, "https://relay.example.test"],
@@ -1068,7 +1064,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
1064
const link = yield* CloudLink.CloudLink;
1065
const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773"));
1066
1071
- expect(error._tag).toBe(errorTag);
1067
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection });
1068
+ expect(CloudLink.shouldRetryCloudLink(error)).toBe(false);
1069
expect(requests).toHaveLength(1);
1070
expect(applyConfigCalls).toEqual([]);
1071
}).pipe(
apps/server/src/cloud/CloudLink.test.ts
+10
-4
@@ -137,7 +137,10 @@ it.effect("puts the relay back when the local save fails", () =>
137
const error = yield* preferences
138
.update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
139
.pipe(Effect.flip);
140
- assert.equal(error._tag, "EnvironmentHttpInternalServerError");
140
+ assert.deepInclude(error, {
141
+ _tag: "CloudLinkInternalError",
142
+ operation: "persist-preferences",
143
+ });
144
assert.deepEqual(relayCalls, [true, false]);
145
assert.equal(
146
new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
@@ -153,7 +156,10 @@ it.effect("leaves the relay untouched when the activity setting can't be saved",
156
const error = yield* preferences
157
.update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
158
.pipe(Effect.flip);
156
- assert.equal(error._tag, "EnvironmentHttpInternalServerError");
159
+ assert.deepInclude(error, {
160
+ _tag: "CloudLinkInternalError",
161
+ operation: "persist-preferences",
162
+ });
163
assert.deepEqual(relayCalls, []);
164
assert.equal(
165
new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
@@ -184,7 +190,7 @@ it.effect("changes nothing when the current activity setting can't be read", ()
190
const error = yield* preferences
191
.update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
192
.pipe(Effect.flip);
187
- assert.equal(error._tag, "EnvironmentHttpInternalServerError");
193
+ assert.deepInclude(error, { _tag: "CloudLinkInternalError", operation: "read-preferences" });
194
assert.deepEqual(relayCalls, []);
195
assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
196
}),
@@ -231,7 +237,7 @@ it.effect("changes nothing when the current hold setting can't be read", () =>
237
const error = yield* preferences
238
.update({ publishAgentActivity: true, holdWebhooksWhileOffline: false })
239
.pipe(Effect.flip);
234
- assert.equal(error._tag, "EnvironmentHttpInternalServerError");
240
+ assert.deepInclude(error, { _tag: "CloudLinkInternalError", operation: "read-preferences" });
241
assert.deepEqual(relayCalls, []);
242
assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
243
}),
apps/server/src/cloud/CloudLink.ts
+302
-258
@@ -7,15 +7,9 @@
7
import * as NodeCrypto from "node:crypto";
8
import {
9
AuthStandardClientScopes,
10
- EnvironmentCloudEndpointUnavailableError,
10
type EnvironmentCloudLinkStateResult,
11
type EnvironmentCloudPreferencesRequest,
12
type EnvironmentCloudRelayConfigResult,
14
- EnvironmentHttpBadRequestError,
15
- EnvironmentHttpConflictError,
16
- type EnvironmentHttpForbiddenError,
17
- EnvironmentHttpInternalServerError,
18
- EnvironmentHttpUnauthorizedError,
13
} from "@t3tools/contracts";
14
import {
15
RelayCloudEnvironmentHealthProofPayload,
@@ -106,7 +100,12 @@ import {
100
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
101
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
102
import { relayUrlConfig } from "./publicConfig.ts";
109
-import { filterRelayResponse, relayRequestError, shouldRetryCloudLink } from "./relayResponse.ts";
103
+import {
104
+ filterRelayResponse,
105
+ relayRequestError,
106
+ type RelayRequestError,
107
+ shouldRetryRelayRequest,
108
+} from "./relayResponse.ts";
109
import {
110
CLOUD_HEALTH_JTI_PREFIX,
111
CLOUD_HEALTH_NONCE_PREFIX,
@@ -126,15 +125,187 @@ import {
125
import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
126
127
const MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT = Duration.minutes(2);
129
-const failEnvironmentCloudInternalError =
130
- (message: string) =>
131
- (cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
132
- Effect.logError(message, { cause }).pipe(
133
- Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
134
- );
128
+const RELAY_CONFIG_FIELD_MESSAGES = {
129
+ relayUrl: "Relay URL must be a secure absolute HTTPS URL.",
130
+ relayIssuer: "Relay issuer must be a secure absolute HTTPS URL.",
131
+ environmentCredential: "Relay environment credential is required.",
132
+ cloudUserId: "Cloud user id is required.",
133
+ cloudMintPublicKey: "Cloud mint public key must be a valid Ed25519 public key.",
134
+} as const;
135
+
136
+/** The relay sent a link configuration this environment cannot install. */
137
+export class CloudLinkRelayConfigInvalidError extends Schema.TaggedError<CloudLinkRelayConfigInvalidError>()(
138
+ "CloudLinkRelayConfigInvalidError",
139
+ {
140
+ field: Schema.Literals([
141
+ "relayUrl",
142
+ "relayIssuer",
143
+ "environmentCredential",
144
+ "cloudUserId",
145
+ "cloudMintPublicKey",
146
+ ]),
147
+ },
148
+) {
149
+ override get message(): string {
150
+ return RELAY_CONFIG_FIELD_MESSAGES[this.field];
151
+ }
152
+}
153
+
154
+/**
155
+ * A link was asked to point at an origin it may not serve: a link proof request
156
+ * that did not reach this server directly on loopback (`endpoint`), or a local
157
+ * origin that is not a bare http(s) origin (`local`).
158
+ */
159
+export class CloudLinkOriginInvalidError extends Schema.TaggedError<CloudLinkOriginInvalidError>()(
160
+ "CloudLinkOriginInvalidError",
161
+ { origin: Schema.Literals(["endpoint", "local"]) },
162
+) {
163
+ override get message(): string {
164
+ return this.origin === "endpoint"
165
+ ? "Invalid managed endpoint origin."
166
+ : "Could not resolve local environment origin.";
167
+ }
168
+}
169
+
170
+export class CloudLinkNotLinkedError extends Schema.TaggedError<CloudLinkNotLinkedError>()(
171
+ "CloudLinkNotLinkedError",
172
+ {},
173
+) {
174
+ override get message(): string {
175
+ return "Link this environment to T3 Connect first.";
176
+ }
177
+}
178
+
179
+export class CloudLinkAccountMismatchError extends Schema.TaggedError<CloudLinkAccountMismatchError>()(
180
+ "CloudLinkAccountMismatchError",
181
+ {},
182
+) {
183
+ override get message(): string {
184
+ return "This environment is already linked to a different cloud account. Unlink it before switching accounts.";
185
+ }
186
+}
187
+
188
+/** Linking from the CLI needs the authorization `t3 connect link` stores. */
189
+export class CloudLinkAuthorizationMissingError extends Schema.TaggedError<CloudLinkAuthorizationMissingError>()(
190
+ "CloudLinkAuthorizationMissingError",
191
+ {},
192
+) {
193
+ override get message(): string {
194
+ return "Run `t3 connect link` to authorize this environment.";
195
+ }
196
+}
197
+
198
+const SignedRelayRequest = Schema.Literals(["health", "mint"]);
199
136
-const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
137
- failEnvironmentCloudInternalError(error.message)(error);
200
+/** A signed relay request whose proof does not verify for this environment. */
201
+export class CloudLinkProofRejectedError extends Schema.TaggedError<CloudLinkProofRejectedError>()(
202
+ "CloudLinkProofRejectedError",
203
+ { request: SignedRelayRequest },
204
+) {
205
+ override get message(): string {
206
+ return `Invalid cloud ${this.request} request.`;
207
+ }
208
+}
209
+
210
+/** A signed relay request whose proof was already used once. */
211
+export class CloudLinkProofReplayedError extends Schema.TaggedError<CloudLinkProofReplayedError>()(
212
+ "CloudLinkProofReplayedError",
213
+ { request: SignedRelayRequest },
214
+) {
215
+ override get message(): string {
216
+ return `Cloud ${this.request} request was already consumed.`;
217
+ }
218
+}
219
+
220
+/** The stored tunnel changed while its registration was in flight. */
221
+export class CloudLinkTunnelSupersededError extends Schema.TaggedError<CloudLinkTunnelSupersededError>()(
222
+ "CloudLinkTunnelSupersededError",
223
+ {},
224
+) {
225
+ override get message(): string {
226
+ return "The managed tunnel configuration changed during registration.";
227
+ }
228
+}
229
+
230
+/**
231
+ * The managed tunnel is not serving: its connector did not start
232
+ * (`runtime-not-started`, with the runtime's status), or the relay never
233
+ * confirmed this server's origin (`origin-unconfirmed`).
234
+ */
235
+export class CloudLinkEndpointUnavailableError extends Schema.TaggedError<CloudLinkEndpointUnavailableError>()(
236
+ "CloudLinkEndpointUnavailableError",
237
+ {
238
+ reason: Schema.Literals(["runtime-not-started", "origin-unconfirmed"]),
239
+ endpointRuntimeStatus: Schema.Unknown,
240
+ },
241
+) {
242
+ override get message(): string {
243
+ return this.reason === "runtime-not-started"
244
+ ? "Managed endpoint runtime could not be started."
245
+ : "Managed endpoint origin could not be confirmed.";
246
+ }
247
+}
248
+
249
+const INTERNAL_OPERATION_MESSAGES = {
250
+ "relay-url-unconfigured":
251
+ "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
252
+ "generate-link-proof": "Could not generate environment link proof.",
253
+ "persist-relay-config": "Could not persist environment relay configuration.",
254
+ "register-endpoint-origin": "Could not register the managed endpoint origin.",
255
+ "resolve-server-origin": "Could not resolve the local server origin.",
256
+ "persist-desired-link": "Could not persist desired T3 Connect link state.",
257
+ "sign-recovery-proof": "Could not sign the managed tunnel recovery request.",
258
+ "unsupported-recovered-tunnel":
259
+ "T3 Connect returned an unsupported managed tunnel configuration.",
260
+ "persist-recovered-tunnel": "Could not persist the recovered managed tunnel configuration.",
261
+ "read-relay-config": "Could not read environment relay configuration.",
262
+ "remove-relay-config": "Could not remove environment relay configuration.",
263
+ "update-webhook-settings": "Could not update T3 Connect webhook settings.",
264
+ "read-preferences": "Could not read environment cloud preferences.",
265
+ "persist-preferences": "Could not persist environment cloud preferences.",
266
+ "answer-health": "Could not answer cloud health request.",
267
+ "issue-credential": "Could not issue cloud connection credential.",
268
+} as const;
269
+
270
+/** A link step failed on this machine: storage, signing, or an unexpected relay answer. */
271
+export class CloudLinkInternalError extends Schema.TaggedError<CloudLinkInternalError>()(
272
+ "CloudLinkInternalError",
273
+ {
274
+ operation: Schema.Literals(
275
+ Object.keys(INTERNAL_OPERATION_MESSAGES) as [
276
+ keyof typeof INTERNAL_OPERATION_MESSAGES,
277
+ ...Array<keyof typeof INTERNAL_OPERATION_MESSAGES>,
278
+ ],
279
+ ),
280
+ cause: Schema.optional(Schema.Defect()),
281
+ },
282
+) {
283
+ override get message(): string {
284
+ return INTERNAL_OPERATION_MESSAGES[this.operation];
285
+ }
286
+}
287
+
288
+const internalError =
289
+ (operation: CloudLinkInternalError["operation"]) =>
290
+ (cause: unknown): Effect.Effect<never, CloudLinkInternalError> =>
291
+ Effect.fail(new CloudLinkInternalError({ operation, cause }));
292
+
293
+const isPermanentLinkError = Schema.is(
294
+ Schema.Union([
295
+ CloudLinkRelayConfigInvalidError,
296
+ CloudLinkOriginInvalidError,
297
+ CloudLinkNotLinkedError,
298
+ CloudLinkAccountMismatchError,
299
+ CloudLinkAuthorizationMissingError,
300
+ CloudLinkProofRejectedError,
301
+ CloudLinkProofReplayedError,
302
+ CloudLinkTunnelSupersededError,
303
+ ]),
304
+);
305
+
306
+/** Whether a failed link step may succeed on retry: not when the relay or this server refused it. */
307
+export const shouldRetryCloudLink = (error: unknown): boolean =>
308
+ shouldRetryRelayRequest(error) && !isPermanentLinkError(error);
309
310
/** A failed rollback leaves a setting changed; it is logged, not hidden. */
311
const rollbackFailed = (cause: unknown) =>
@@ -142,10 +313,7 @@ const rollbackFailed = (cause: unknown) =>
313
314
const requireRelayUrl = relayUrlConfig.pipe(
315
Effect.mapError(
145
- () =>
146
- new EnvironmentHttpInternalServerError({
147
- message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
148
- }),
316
+ (cause) => new CloudLinkInternalError({ operation: "relay-url-unconfigured", cause }),
317
),
318
);
319
@@ -159,58 +327,37 @@ function stringToBytes(value: string): Uint8Array {
327
328
function validateCloudMintPublicKey(
329
publicKey: string,
162
-): Effect.Effect<void, EnvironmentHttpBadRequestError> {
330
+): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {
331
+ const invalid = new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" });
332
return Effect.try({
333
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
165
- catch: () =>
166
- new EnvironmentHttpBadRequestError({
167
- message: "Cloud mint public key must be a valid Ed25519 public key.",
168
- }),
334
+ catch: () => invalid,
335
}).pipe(
336
Effect.flatMap((key) =>
171
- key.asymmetricKeyType === "ed25519"
172
- ? Effect.void
173
- : Effect.fail(
174
- new EnvironmentHttpBadRequestError({
175
- message: "Cloud mint public key must be a valid Ed25519 public key.",
176
- }),
177
- ),
337
+ key.asymmetricKeyType === "ed25519" ? Effect.void : Effect.fail(invalid),
338
),
339
);
340
}
341
182
-function validateRelayConfigPayload(
342
+function invalidRelayConfigField(
343
payload: RelayEnvironmentConfigRequest,
184
-): Effect.Effect<void, EnvironmentHttpBadRequestError> {
185
- if (!isSecureRelayUrl(payload.relayUrl)) {
186
- return Effect.fail(
187
- new EnvironmentHttpBadRequestError({
188
- message: "Relay URL must be a secure absolute HTTPS URL.",
189
- }),
190
- );
191
- }
344
+): CloudLinkRelayConfigInvalidError["field"] | null {
345
+ if (!isSecureRelayUrl(payload.relayUrl)) return "relayUrl";
346
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
193
- return Effect.fail(
194
- new EnvironmentHttpBadRequestError({
195
- message: "Relay issuer must be a secure absolute HTTPS URL.",
196
- }),
197
- );
198
- }
199
- if (payload.environmentCredential.trim().length === 0) {
200
- return Effect.fail(
201
- new EnvironmentHttpBadRequestError({
202
- message: "Relay environment credential is required.",
203
- }),
204
- );
347
+ return "relayIssuer";
348
}
206
- if (payload.cloudUserId.trim().length === 0) {
207
- return Effect.fail(
208
- new EnvironmentHttpBadRequestError({
209
- message: "Cloud user id is required.",
210
- }),
211
- );
212
- }
213
- return Effect.void;
349
+ if (payload.environmentCredential.trim().length === 0) return "environmentCredential";
350
+ if (payload.cloudUserId.trim().length === 0) return "cloudUserId";
351
+ return null;
352
+}
353
+
354
+function validateRelayConfigPayload(
355
+ payload: RelayEnvironmentConfigRequest,
356
+): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {
357
+ const field = invalidRelayConfigField(payload);
358
+ return field === null
359
+ ? Effect.void
360
+ : Effect.fail(new CloudLinkRelayConfigInvalidError({ field }));
361
}
362
363
function normalizePemForSignedPayload(value: string): string {
@@ -233,13 +380,25 @@ type ManagedTunnelRecoveryProofInput = {
380
| { readonly action: "recover"; readonly origin: RelayManagedEndpointOrigin }
381
);
382
236
-/** Failures of the link work that runs outside a request: startup, recovery and shutdown. */
383
+/** Every failure CloudLink constructs itself. */
384
+export type CloudLinkError =
385
+ | CloudLinkAccountMismatchError
386
+ | CloudLinkAuthorizationMissingError
387
+ | CloudLinkEndpointUnavailableError
388
+ | CloudLinkInternalError
389
+ | CloudLinkNotLinkedError
390
+ | CloudLinkOriginInvalidError
391
+ | CloudLinkProofRejectedError
392
+ | CloudLinkProofReplayedError
393
+ | CloudLinkRelayConfigInvalidError
394
+ | CloudLinkTunnelSupersededError;
395
+
396
+/** Failures of the link work that talks to the relay: linking, recovery and shutdown. */
397
type CloudLinkBackgroundError =
238
- | EnvironmentCloudEndpointUnavailableError
239
- | EnvironmentHttpBadRequestError
240
- | EnvironmentHttpForbiddenError
241
- | EnvironmentHttpInternalServerError
242
- | EnvironmentHttpUnauthorizedError
398
+ | CloudLinkEndpointUnavailableError
399
+ | CloudLinkInternalError
400
+ | CloudLinkOriginInvalidError
401
+ | RelayRequestError
402
| ServerSecretStore.SecretStoreError
403
| Schema.SchemaError
404
| PlatformError.PlatformError;
@@ -264,29 +423,28 @@ export class CloudLink extends Context.Service<
423
httpRequest: HttpServerRequest.HttpServerRequest,
424
) => Effect.Effect<
425
RelayEnvironmentLinkProof,
267
- EnvironmentHttpBadRequestError | EnvironmentHttpInternalServerError
426
+ CloudLinkOriginInvalidError | CloudLinkInternalError | EnvironmentAuth.ServerAuthInternalError
427
>;
428
/** Installs the link the relay returned and, for a managed tunnel, confirms its origin. */
429
readonly applyRelayConfig: (
430
payload: RelayEnvironmentConfigRequest,
431
) => Effect.Effect<
432
EnvironmentCloudRelayConfigResult,
274
- | EnvironmentCloudEndpointUnavailableError
275
- | EnvironmentHttpBadRequestError
276
- | EnvironmentHttpConflictError
277
- | EnvironmentHttpForbiddenError
278
- | EnvironmentHttpInternalServerError
279
- | EnvironmentHttpUnauthorizedError
433
+ | CloudLinkAccountMismatchError
434
+ | CloudLinkEndpointUnavailableError
435
+ | CloudLinkInternalError
436
+ | CloudLinkOriginInvalidError
437
+ | CloudLinkRelayConfigInvalidError
438
+ | CloudLinkTunnelSupersededError
439
+ | EnvironmentAuth.ServerAuthInternalError
440
+ | RelayRequestError
441
>;
442
readonly linkState: () => Effect.Effect<
443
EnvironmentCloudLinkStateResult,
283
- EnvironmentHttpInternalServerError
444
+ CloudLinkInternalError
445
>;
446
/** Stops the tunnel and forgets the link, including the CLI's wish to keep it. */
286
- readonly unlink: () => Effect.Effect<
287
- EnvironmentCloudRelayConfigResult,
288
- EnvironmentHttpInternalServerError
289
- >;
447
+ readonly unlink: () => Effect.Effect<EnvironmentCloudRelayConfigResult, CloudLinkInternalError>;
448
/**
449
* Saves this environment's T3 Connect preferences, all or nothing, and
450
* returns the link state. The activity setting is saved first. Holding
@@ -298,25 +456,27 @@ export class CloudLink extends Context.Service<
456
input: EnvironmentCloudPreferencesRequest,
457
) => Effect.Effect<
458
EnvironmentCloudLinkStateResult,
301
- EnvironmentHttpBadRequestError | EnvironmentHttpInternalServerError
459
+ CloudLinkNotLinkedError | CloudLinkInternalError
460
>;
461
/** Answers the relay's signed health check once per proof. */
462
readonly answerHealthRequest: (
463
request: RelayCloudEnvironmentHealthRequest,
464
) => Effect.Effect<
465
RelayEnvironmentHealthResponse,
308
- | EnvironmentHttpConflictError
309
- | EnvironmentHttpInternalServerError
310
- | EnvironmentHttpUnauthorizedError
466
+ | CloudLinkProofRejectedError
467
+ | CloudLinkProofReplayedError
468
+ | CloudLinkInternalError
469
+ | EnvironmentAuth.ServerAuthInternalError
470
>;
471
/** Issues a short-lived pairing credential for a client the relay vouched for, once per proof. */
472
readonly mintCredential: (
473
request: RelayCloudMintCredentialRequest,
474
) => Effect.Effect<
475
RelayEnvironmentMintResponse,
317
- | EnvironmentHttpConflictError
318
- | EnvironmentHttpInternalServerError
319
- | EnvironmentHttpUnauthorizedError
476
+ | CloudLinkProofRejectedError
477
+ | CloudLinkProofReplayedError
478
+ | CloudLinkInternalError
479
+ | EnvironmentAuth.ServerAuthInternalError
480
>;
481
/** Links this environment with the stored CLI authorization and records the CLI's wish. */
482
readonly reconcileDesiredLink: (
@@ -324,9 +484,11 @@ export class CloudLink extends Context.Service<
484
) => Effect.Effect<
485
CliDesiredLinkMode,
486
| CloudLinkBackgroundError
327
- | EnvironmentHttpConflictError
487
+ | CloudLinkAccountMismatchError
488
+ | CloudLinkAuthorizationMissingError
489
+ | CloudLinkRelayConfigInvalidError
490
| EnvironmentAuth.ServerAuthInternalError
329
- | CliTokenManager.CloudCliAuthorizationDeniedError
491
+ | CliTokenManager.CloudCliTokenManagerError
492
>;
493
/** As `reconcileDesiredLink`, but returns null when the CLI no longer wants a link. */
494
readonly reconcileDesiredLinkIfStillDesired: (
@@ -334,9 +496,11 @@ export class CloudLink extends Context.Service<
496
) => Effect.Effect<
497
CliDesiredLinkMode | null,
498
| CloudLinkBackgroundError
337
- | EnvironmentHttpConflictError
499
+ | CloudLinkAccountMismatchError
500
+ | CloudLinkAuthorizationMissingError
501
+ | CloudLinkRelayConfigInvalidError
502
| EnvironmentAuth.ServerAuthInternalError
339
- | CliTokenManager.CloudCliAuthorizationDeniedError
503
+ | CliTokenManager.CloudCliTokenManagerError
504
>;
505
/** Tells the relay which local origin the stored tunnel serves, then starts it. */
506
readonly registerManagedTunnelRecovery: (
@@ -359,8 +523,8 @@ export class CloudLink extends Context.Service<
523
options?: { readonly requireConfirmedOrigin?: boolean },
524
) => Effect.Effect<
525
boolean,
362
- | EnvironmentCloudEndpointUnavailableError
363
- | EnvironmentHttpBadRequestError
526
+ | CloudLinkEndpointUnavailableError
527
+ | CloudLinkOriginInvalidError
528
| ServerSecretStore.SecretStoreError
529
>;
530
/** Deletes a CLI-managed tunnel when this server goes offline for good. */
@@ -399,7 +563,7 @@ const make = Effect.gen(function* () {
563
564
const validateLinkedCloudUser = (
565
cloudUserId: string,
402
- ): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> =>
566
+ ): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | CloudLinkAccountMismatchError> =>
567
secrets.get(CLOUD_LINKED_USER_ID).pipe(
568
Effect.mapError(
569
(cause) =>
@@ -414,12 +578,7 @@ const make = Effect.gen(function* () {
578
const existingCloudUserId = bytesToString(existing.value);
579
return existingCloudUserId === cloudUserId
580
? Effect.void
417
- : Effect.fail(
418
- new EnvironmentHttpConflictError({
419
- message:
420
- "This environment is already linked to a different cloud account. Unlink it before switching accounts.",
421
- }),
422
- );
581
+ : Effect.fail(new CloudLinkAccountMismatchError({}));
582
}),
583
);
584
@@ -450,9 +609,7 @@ const make = Effect.gen(function* () {
609
requestUrl,
610
})
611
) {
453
- return yield* new EnvironmentHttpBadRequestError({
454
- message: "Invalid managed endpoint origin.",
455
- });
612
+ return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
613
}
614
const now = yield* DateTime.now;
615
const expiresAt = DateTime.add(now, { minutes: 5 });
@@ -491,24 +648,13 @@ const make = Effect.gen(function* () {
648
function* (request: RelayLinkProofRequest, httpRequest: HttpServerRequest.HttpServerRequest) {
649
const requestUrl = requestAbsoluteUrl(httpRequest);
650
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
494
- return yield* new EnvironmentHttpBadRequestError({
495
- message: "Invalid managed endpoint origin.",
496
- });
651
+ return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
652
}
653
const proof = yield* makeCloudLinkProof(request, requestUrl);
654
return proof satisfies RelayEnvironmentLinkProof;
655
},
501
- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
502
- failEnvironmentCloudInternalError(error.message)(error),
503
- ),
504
- Effect.catchIf(
505
- ServerSecretStore.isSecretStoreError,
506
- failEnvironmentCloudInternalError("Could not generate environment link proof."),
507
- ),
508
- Effect.catchTag(
509
- "PlatformError",
510
- failEnvironmentCloudInternalError("Could not generate environment link proof."),
511
- ),
656
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")),
657
+ Effect.catchTag("PlatformError", internalError("generate-link-proof")),
658
);
659
660
const activateManagedTunnel = Effect.fn("environment.cloud.activateManagedTunnel")(
@@ -528,8 +674,8 @@ const make = Effect.gen(function* () {
674
}
675
const status = yield* endpointRuntime.applyConfig(input.config);
676
if (status.status !== "running") {
531
- return yield* new EnvironmentCloudEndpointUnavailableError({
532
- message: "Managed endpoint runtime could not be started.",
677
+ return yield* new CloudLinkEndpointUnavailableError({
678
+ reason: "runtime-not-started",
679
endpointRuntimeStatus: status,
680
});
681
}
@@ -557,7 +703,7 @@ const make = Effect.gen(function* () {
703
? activate.pipe(
704
Effect.retry({
705
while: (error) =>
560
- error._tag === "EnvironmentCloudEndpointUnavailableError" &&
706
+ error._tag === "CloudLinkEndpointUnavailableError" &&
707
ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus(
708
error.endpointRuntimeStatus,
709
),
@@ -578,10 +724,7 @@ const make = Effect.gen(function* () {
724
const requireConfirmedOrigin = options?.requireConfirmedOrigin ?? true;
725
const parsedOrigin = yield* Effect.try({
726
try: () => parseManagedEndpointLocalOrigin(localOrigin),
581
- catch: () =>
582
- new EnvironmentHttpBadRequestError({
583
- message: "Could not resolve local environment origin.",
584
- }),
727
+ catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
728
});
729
return yield* endpointRuntime.withLinkStateLock(
730
Effect.gen(function* () {
@@ -610,8 +753,8 @@ const make = Effect.gen(function* () {
753
}
754
const status = yield* endpointRuntime.applyConfig(config);
755
if (status.status !== "running") {
613
- return yield* new EnvironmentCloudEndpointUnavailableError({
614
- message: "Managed endpoint runtime could not be started.",
756
+ return yield* new CloudLinkEndpointUnavailableError({
757
+ reason: "runtime-not-started",
758
endpointRuntimeStatus: status,
759
});
760
}
@@ -637,8 +780,8 @@ const make = Effect.gen(function* () {
780
payload.endpointRuntime !== null &&
781
payload.endpointRuntime.providerKind !== "cloudflare_tunnel"
782
) {
640
- return yield* new EnvironmentCloudEndpointUnavailableError({
641
- message: "Managed endpoint runtime could not be started.",
783
+ return yield* new CloudLinkEndpointUnavailableError({
784
+ reason: "runtime-not-started",
785
endpointRuntimeStatus: {
786
status: "unsupported",
787
providerKind: payload.endpointRuntime.providerKind,
@@ -674,8 +817,8 @@ const make = Effect.gen(function* () {
817
}
818
const endpointRuntimeStatus = yield* endpointRuntime.applyConfig(payload.endpointRuntime);
819
if (endpointRuntimeStatus.status !== "running") {
677
- return yield* new EnvironmentCloudEndpointUnavailableError({
678
- message: "Managed endpoint runtime could not be started.",
820
+ return yield* new CloudLinkEndpointUnavailableError({
821
+ reason: "runtime-not-started",
822
endpointRuntimeStatus,
823
});
824
}
@@ -711,20 +854,12 @@ const make = Effect.gen(function* () {
854
function* (localOrigin: string) {
855
const parsedOrigin = yield* Effect.try({
856
try: () => parseManagedEndpointLocalOrigin(localOrigin),
714
- catch: () =>
715
- new EnvironmentHttpBadRequestError({
716
- message: "Could not resolve local environment origin.",
717
- }),
857
+ catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
858
});
859
const token = yield* cliTokenManager.getExisting.pipe(
860
Effect.flatMap(
861
Option.match({
722
- onNone: () =>
723
- Effect.fail(
724
- new EnvironmentHttpUnauthorizedError({
725
- message: "Run `t3 connect link` to authorize this environment.",
726
- }),
727
- ),
862
+ onNone: () => Effect.fail(new CloudLinkAuthorizationMissingError({})),
863
onSome: Effect.succeed,
864
}),
865
),
@@ -786,17 +921,7 @@ const make = Effect.gen(function* () {
921
// actually used, not from a value read before the relay round trip.
922
return mode;
923
},
789
- Effect.catchIf(
790
- ServerSecretStore.isSecretStoreError,
791
- failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
792
- ),
793
- Effect.catchTags({
794
- CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
795
- CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
796
- CloudCliCredentialReadError: failCloudCliTokenManagerError,
797
- CloudCliAuthorizationError: failCloudCliTokenManagerError,
798
- CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
799
- }),
924
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("persist-desired-link")),
925
);
926
927
const reconcileDesiredLink = Effect.fn("environment.cloud.reconcileDesiredLink")(function* (
@@ -853,10 +978,7 @@ const make = Effect.gen(function* () {
978
payload,
979
}).pipe(
980
Effect.mapError(
856
- () =>
857
- new EnvironmentHttpInternalServerError({
858
- message: "Could not sign the managed tunnel recovery request.",
859
- }),
981
+ (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
982
),
983
);
984
});
@@ -886,10 +1008,7 @@ const make = Effect.gen(function* () {
1008
1009
const parsedOrigin = yield* Effect.try({
1010
try: () => parseManagedEndpointLocalOrigin(localOrigin),
889
- catch: () =>
890
- new EnvironmentHttpBadRequestError({
891
- message: "Could not resolve local environment origin.",
892
- }),
1011
+ catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
1012
});
1013
if (config.tunnelId === undefined) {
1014
return { status: "recovery_required" as const, config };
@@ -967,10 +1086,7 @@ const make = Effect.gen(function* () {
1086
1087
const parsedOrigin = yield* Effect.try({
1088
try: () => parseManagedEndpointLocalOrigin(localOrigin),
970
- catch: () =>
971
- new EnvironmentHttpBadRequestError({
972
- message: "Could not resolve local environment origin.",
973
- }),
1089
+ catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
1090
});
1091
1092
const environmentId = yield* environment.getEnvironmentId;
@@ -996,17 +1112,12 @@ const make = Effect.gen(function* () {
1112
timeout: MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT,
1113
});
1114
if (recovered.endpointRuntime.providerKind !== "cloudflare_tunnel") {
999
- return yield* new EnvironmentHttpInternalServerError({
1000
- message: "T3 Connect returned an unsupported managed tunnel configuration.",
1001
- });
1115
+ return yield* new CloudLinkInternalError({ operation: "unsupported-recovered-tunnel" });
1116
}
1117
1118
const encoded = yield* encodeEndpointRuntimeConfigJson(recovered.endpointRuntime).pipe(
1119
Effect.mapError(
1006
- () =>
1007
- new EnvironmentHttpInternalServerError({
1008
- message: "Could not persist the recovered managed tunnel configuration.",
1009
- }),
1120
+ (cause) => new CloudLinkInternalError({ operation: "persist-recovered-tunnel", cause }),
1121
),
1122
);
1123
const stored = yield* endpointRuntime.withLinkStateLock(
@@ -1041,9 +1152,7 @@ const make = Effect.gen(function* () {
1152
if (payload.endpointRuntime?.providerKind === "cloudflare_tunnel") {
1153
const address = httpServer.address;
1154
if (typeof address === "string" || !("port" in address)) {
1044
- return yield* new EnvironmentHttpInternalServerError({
1045
- message: "Could not resolve the local server origin.",
1046
- });
1155
+ return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" });
1156
}
1157
const registration = yield* registerManagedTunnelRecovery(
1158
`http://127.0.0.1:${address.port}`,
@@ -1051,21 +1160,18 @@ const make = Effect.gen(function* () {
1160
Effect.retry({
1161
times: 2,
1162
while: (error) =>
1054
- shouldRetryCloudLink(error) &&
1055
- error._tag !== "EnvironmentCloudEndpointUnavailableError",
1163
+ shouldRetryCloudLink(error) && error._tag !== "CloudLinkEndpointUnavailableError",
1164
}),
1165
);
1166
if (registration.status === "superseded") {
1059
- return yield* new EnvironmentHttpConflictError({
1060
- message: "The managed tunnel configuration changed during registration.",
1061
- });
1167
+ return yield* new CloudLinkTunnelSupersededError({});
1168
}
1169
if (registration.status === "recovery_required") {
1170
yield* endpointRuntime.requestRecovery(registration.config);
1171
}
1172
if (registration.status !== "ready") {
1067
- return yield* new EnvironmentCloudEndpointUnavailableError({
1068
- message: "Managed endpoint origin could not be confirmed.",
1173
+ return yield* new CloudLinkEndpointUnavailableError({
1174
+ reason: "origin-unconfirmed",
1175
endpointRuntimeStatus: { status: "disabled" },
1176
});
1177
}
@@ -1076,20 +1182,10 @@ const make = Effect.gen(function* () {
1182
}
1183
return result;
1184
},
1079
- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
1080
- failEnvironmentCloudInternalError(error.message)(error),
1081
- ),
1082
- Effect.catchIf(
1083
- ServerSecretStore.isSecretStoreError,
1084
- failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
1085
- ),
1185
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("persist-relay-config")),
1186
Effect.catchTags({
1087
- SchemaError: failEnvironmentCloudInternalError(
1088
- "Could not persist environment relay configuration.",
1089
- ),
1090
- PlatformError: failEnvironmentCloudInternalError(
1091
- "Could not register the managed endpoint origin.",
1092
- ),
1187
+ SchemaError: internalError("persist-relay-config"),
1188
+ PlatformError: internalError("register-endpoint-origin"),
1189
}),
1190
);
1191
@@ -1216,10 +1312,7 @@ const make = Effect.gen(function* () {
1312
function* () {
1313
return yield* readCloudLinkState();
1314
},
1219
- Effect.catchIf(
1220
- ServerSecretStore.isSecretStoreError,
1221
- failEnvironmentCloudInternalError("Could not read environment relay configuration."),
1222
- ),
1315
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-relay-config")),
1316
);
1317
1318
const unlink = Effect.fn("environment.cloud.unlink")(
@@ -1246,19 +1339,14 @@ const make = Effect.gen(function* () {
1339
}),
1340
);
1341
},
1249
- Effect.catchIf(
1250
- ServerSecretStore.isSecretStoreError,
1251
- failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
1252
- ),
1342
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("remove-relay-config")),
1343
);
1344
1345
const pushHoldWebhooksWhileOffline = Effect.fn("CloudPreferences.pushHoldWebhooksWhileOffline")(
1346
function* (holdWebhooksWhileOffline: boolean) {
1347
const connection = yield* readRelayConnection.pipe(withSecrets);
1348
if (connection === null) {
1259
- return yield* new EnvironmentHttpBadRequestError({
1260
- message: "Link this environment to T3 Connect first.",
1261
- });
1349
+ return yield* new CloudLinkNotLinkedError({});
1350
}
1351
const environmentId = yield* environment.getEnvironmentId;
1352
const client = yield* makeRelayEnvironmentClient(connection);
@@ -1267,23 +1355,14 @@ const make = Effect.gen(function* () {
1355
params: { environmentId },
1356
payload: { holdWebhooksWhileOffline },
1357
})
1270
- .pipe(
1271
- Effect.timeout("10 seconds"),
1272
- Effect.catch(
1273
- failEnvironmentCloudInternalError("Could not update T3 Connect webhook settings."),
1274
- ),
1275
- );
1358
+ .pipe(Effect.timeout("10 seconds"), Effect.catch(internalError("update-webhook-settings")));
1359
},
1360
);
1361
1362
const savePreference = (name: string, value: boolean) =>
1363
secrets
1364
.set(name, stringToBytes(String(value)))
1282
- .pipe(
1283
- Effect.catch(
1284
- failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
1285
- ),
1286
- );
1365
+ .pipe(Effect.catch(internalError("persist-preferences")));
1366
1367
// One update at a time, so two requests can't each leave one setting behind.
1368
const preferencesLock = yield* Semaphore.make(1);
@@ -1295,13 +1374,7 @@ const make = Effect.gen(function* () {
1374
// current values are read up front; a failed read stops here, before
1375
// anything changes, because a guessed value would be the rollback target.
1376
const readCurrent = (name: string) =>
1298
- secrets
1299
- .get(name)
1300
- .pipe(
1301
- Effect.catch(
1302
- failEnvironmentCloudInternalError("Could not read environment cloud preferences."),
1303
- ),
1304
- );
1377
+ secrets.get(name).pipe(Effect.catch(internalError("read-preferences")));
1378
const previousActivity = yield* readCurrent(PUBLISH_AGENT_ACTIVITY_SECRET);
1379
const previousHold = yield* readCurrent(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET);
1380
yield* savePreference(PUBLISH_AGENT_ACTIVITY_SECRET, input.publishAgentActivity);
@@ -1342,10 +1415,7 @@ const make = Effect.gen(function* () {
1415
yield* savePreferences(input);
1416
return yield* readCloudLinkState();
1417
},
1345
- Effect.catchIf(
1346
- ServerSecretStore.isSecretStoreError,
1347
- failEnvironmentCloudInternalError("Could not read environment cloud preferences."),
1348
- ),
1418
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-preferences")),
1419
);
1420
1421
const answerHealthRequest = Effect.fn("environment.cloud.health")(
@@ -1397,9 +1467,7 @@ const make = Effect.gen(function* () {
1467
!hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
1468
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
1469
) {
1400
- return yield* new EnvironmentHttpUnauthorizedError({
1401
- message: "Invalid cloud health request.",
1402
- });
1470
+ return yield* new CloudLinkProofRejectedError({ request: "health" });
1471
}
1472
const proof = proofOption.value;
1473
@@ -1411,9 +1479,7 @@ const make = Effect.gen(function* () {
1479
value: stringToBytes(DateTime.formatIso(now)),
1480
});
1481
if (!consumedReplayGuards) {
1414
- return yield* new EnvironmentHttpConflictError({
1415
- message: "Cloud health request was already consumed.",
1416
- });
1482
+ return yield* new CloudLinkProofReplayedError({ request: "health" });
1483
}
1484
1485
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
@@ -1452,17 +1518,8 @@ const make = Effect.gen(function* () {
1518
proof: responseProof,
1519
} satisfies RelayEnvironmentHealthResponse;
1520
},
1455
- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
1456
- failEnvironmentCloudInternalError(error.message)(error),
1457
- ),
1458
- Effect.catchIf(
1459
- ServerSecretStore.isSecretStoreError,
1460
- failEnvironmentCloudInternalError("Could not answer cloud health request."),
1461
- ),
1462
- Effect.catchTag(
1463
- "PlatformError",
1464
- failEnvironmentCloudInternalError("Could not answer cloud health request."),
1465
- ),
1521
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("answer-health")),
1522
+ Effect.catchTag("PlatformError", internalError("answer-health")),
1523
);
1524
1525
const mintCredential = Effect.fn("environment.cloud.mintCredential")(
@@ -1515,9 +1572,7 @@ const make = Effect.gen(function* () {
1572
!hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||
1573
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
1574
) {
1518
- return yield* new EnvironmentHttpUnauthorizedError({
1519
- message: "Invalid cloud mint request.",
1520
- });
1575
+ return yield* new CloudLinkProofRejectedError({ request: "mint" });
1576
}
1577
const proof = proofOption.value;
1578
@@ -1529,9 +1584,7 @@ const make = Effect.gen(function* () {
1584
value: stringToBytes(DateTime.formatIso(now)),
1585
});
1586
if (!consumedReplayGuards) {
1532
- return yield* new EnvironmentHttpConflictError({
1533
- message: "Cloud mint request was already consumed.",
1534
- });
1587
+ return yield* new CloudLinkProofReplayedError({ request: "mint" });
1588
}
1589
1590
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
@@ -1572,17 +1625,8 @@ const make = Effect.gen(function* () {
1625
proof: responseProof,
1626
} satisfies RelayEnvironmentMintResponse;
1627
},
1575
- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
1576
- failEnvironmentCloudInternalError(error.message)(error),
1577
- ),
1578
- Effect.catchIf(
1579
- ServerSecretStore.isSecretStoreError,
1580
- failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1581
- ),
1582
- Effect.catchTag(
1583
- "PlatformError",
1584
- failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
1585
- ),
1628
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("issue-credential")),
1629
+ Effect.catchTag("PlatformError", internalError("issue-credential")),
1630
);
1631
1632
return CloudLink.of({
apps/server/src/cloud/http.test.ts
new
+98
@@ -0,0 +1,98 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { EnvironmentHttpApi } from "@t3tools/contracts";
3
+import { describe, expect, it } from "@effect/vitest";
4
+import * as Effect from "effect/Effect";
5
+import * as Layer from "effect/Layer";
6
+import * as Etag from "effect/http/Etag";
7
+import * as HttpPlatform from "effect/http/HttpPlatform";
8
+import * as HttpRouter from "effect/http/HttpRouter";
9
+import * as HttpApi from "effect/http-api/HttpApi";
10
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
11
+
12
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13
+import * as AuthHttp from "../auth/http.ts";
14
+import * as CloudLink from "./CloudLink.ts";
15
+import * as ConnectHttp from "./http.ts";
16
+
17
+class ConnectTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.connect) {}
18
+
19
+// The signed relay routes need no session, so a CloudLink that fails each
20
+// request shows how the transport answers that failure.
21
+type HealthFailure = Effect.Error<
22
+ ReturnType<CloudLink.CloudLink["Service"]["answerHealthRequest"]>
23
+>;
24
+
25
+const answerHealthWith = async (failure: HealthFailure) => {
26
+ const layerRoutes = HttpApiBuilder.layer(ConnectTestApi).pipe(
27
+ Layer.provide(ConnectHttp.layer),
28
+ Layer.provide(
29
+ Layer.mock(CloudLink.CloudLink)({
30
+ answerHealthRequest: () => Effect.fail(failure),
31
+ }),
32
+ ),
33
+ // The session-gated routes are declared too; this request never reaches them.
34
+ Layer.provide(AuthHttp.layerAuthenticatedAuth),
35
+ Layer.provide(Layer.mock(EnvironmentAuth.EnvironmentAuth)({})),
36
+ Layer.provideMerge(
37
+ HttpPlatform.layer.pipe(
38
+ Layer.provideMerge(NodeServices.layer),
39
+ Layer.provideMerge(Etag.layerWeak),
40
+ ),
41
+ ),
42
+ );
43
+ const { handler, dispose } = HttpRouter.toWebHandler(layerRoutes, {
44
+ disableLogger: true,
45
+ });
46
+ try {
47
+ const response = await handler(
48
+ new Request("http://127.0.0.1/api/t3-connect/health", {
49
+ method: "POST",
50
+ headers: { "content-type": "application/json" },
51
+ body: JSON.stringify({ proof: "proof" }),
52
+ }),
53
+ );
54
+ return { status: response.status, body: (await response.json()) as unknown };
55
+ } finally {
56
+ await dispose();
57
+ }
58
+};
59
+
60
+describe("connect routes", () => {
61
+ it.each([
62
+ {
63
+ failure: new CloudLink.CloudLinkProofRejectedError({ request: "health" }),
64
+ status: 401,
65
+ body: { _tag: "EnvironmentHttpUnauthorizedError", message: "Invalid cloud health request." },
66
+ },
67
+ {
68
+ failure: new CloudLink.CloudLinkProofReplayedError({ request: "health" }),
69
+ status: 409,
70
+ body: {
71
+ _tag: "EnvironmentHttpConflictError",
72
+ message: "Cloud health request was already consumed.",
73
+ },
74
+ },
75
+ {
76
+ failure: new CloudLink.CloudLinkInternalError({
77
+ operation: "answer-health",
78
+ cause: new Error("disk full"),
79
+ }),
80
+ status: 500,
81
+ body: {
82
+ _tag: "EnvironmentHttpInternalServerError",
83
+ message: "Could not answer cloud health request.",
84
+ },
85
+ },
86
+ {
87
+ failure: new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}),
88
+ status: 500,
89
+ body: {
90
+ _tag: "EnvironmentHttpInternalServerError",
91
+ message: "Cloud mint public key is not installed for this environment.",
92
+ },
93
+ },
94
+ ])("answers $failure._tag with HTTP $status", async ({ failure, status, body }) => {
95
+ const response = await answerHealthWith(failure);
96
+ expect(response).toEqual({ status, body });
97
+ });
98
+});
apps/server/src/cloud/http.ts
+106
-15
@@ -1,11 +1,23 @@
1
-import { AuthRelayReadScope, AuthRelayWriteScope, EnvironmentHttpApi } from "@t3tools/contracts";
1
+import {
2
+ AuthRelayReadScope,
3
+ AuthRelayWriteScope,
4
+ EnvironmentCloudEndpointUnavailableError,
5
+ EnvironmentHttpApi,
6
+ EnvironmentHttpBadRequestError,
7
+ EnvironmentHttpConflictError,
8
+ EnvironmentHttpForbiddenError,
9
+ EnvironmentHttpInternalServerError,
10
+ EnvironmentHttpUnauthorizedError,
11
+} from "@t3tools/contracts";
12
import * as Effect from "effect/Effect";
13
import * as HttpEffect from "effect/http/HttpEffect";
14
import { HttpServerRequest, HttpServerResponse } from "effect/http";
15
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
16
17
import { requireEnvironmentScope } from "../auth/http.ts";
18
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
19
import * as CloudLink from "./CloudLink.ts";
20
+import type { RelayRequestError } from "./relayResponse.ts";
21
import { traceRelayRequest } from "./traceRelayRequest.ts";
22
23
const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
@@ -18,6 +30,81 @@ const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler
30
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
31
);
32
33
+const internalServerError = (error: { readonly message: string }, cause: unknown) =>
34
+ Effect.logError(error.message, { cause }).pipe(
35
+ Effect.andThen(Effect.fail(new EnvironmentHttpInternalServerError({ message: error.message }))),
36
+ );
37
+
38
+const relayFailure = (error: RelayRequestError) => {
39
+ const message = error.message;
40
+ switch (error.rejection) {
41
+ case "unauthorized":
42
+ return Effect.fail(new EnvironmentHttpUnauthorizedError({ message }));
43
+ case "forbidden":
44
+ return Effect.fail(new EnvironmentHttpForbiddenError({ message }));
45
+ case "rejected":
46
+ return Effect.fail(new EnvironmentHttpBadRequestError({ message }));
47
+ case "unavailable":
48
+ return Effect.fail(new EnvironmentHttpInternalServerError({ message }));
49
+ }
50
+};
51
+
52
+const badRequest = (error: { readonly message: string }) =>
53
+ Effect.fail(new EnvironmentHttpBadRequestError({ message: error.message }));
54
+const unauthorized = (error: { readonly message: string }) =>
55
+ Effect.fail(new EnvironmentHttpUnauthorizedError({ message: error.message }));
56
+const conflict = (error: { readonly message: string }) =>
57
+ Effect.fail(new EnvironmentHttpConflictError({ message: error.message }));
58
+
59
+/** How a connect route answers each CloudLink failure. Messages carry through unchanged. */
60
+const connectErrorCases = {
61
+ CloudLinkRelayConfigInvalidError: badRequest,
62
+ CloudLinkOriginInvalidError: badRequest,
63
+ CloudLinkNotLinkedError: badRequest,
64
+ CloudLinkAccountMismatchError: conflict,
65
+ CloudLinkAuthorizationMissingError: unauthorized,
66
+ CloudLinkProofRejectedError: unauthorized,
67
+ CloudLinkProofReplayedError: conflict,
68
+ CloudLinkTunnelSupersededError: conflict,
69
+ CloudLinkInternalError: (error: CloudLink.CloudLinkInternalError) =>
70
+ internalServerError(error, error.cause),
71
+ RelayRequestError: relayFailure,
72
+} as const;
73
+
74
+type ConnectFailure =
75
+ | Exclude<CloudLink.CloudLinkError, CloudLink.CloudLinkEndpointUnavailableError>
76
+ | EnvironmentAuth.ServerAuthInternalError
77
+ | RelayRequestError;
78
+
79
+/** Internal failures are logged with their cause before the route answers 500. */
80
+const toHttpError = <A, R>(effect: Effect.Effect<A, ConnectFailure, R>) =>
81
+ effect.pipe(
82
+ Effect.catchTags(connectErrorCases),
83
+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
84
+ internalServerError(error, error),
85
+ ),
86
+ );
87
+
88
+/** Relay configuration is the one route that answers 503 when the tunnel cannot serve. */
89
+const toHttpErrorOrUnavailable = <A, R>(
90
+ effect: Effect.Effect<A, ConnectFailure | CloudLink.CloudLinkEndpointUnavailableError, R>,
91
+) =>
92
+ effect.pipe(
93
+ Effect.catchTags({
94
+ ...connectErrorCases,
95
+ CloudLinkEndpointUnavailableError: (error) =>
96
+ Effect.fail(
97
+ new EnvironmentCloudEndpointUnavailableError({
98
+ message: error.message,
99
+ endpointRuntimeStatus: error.endpointRuntimeStatus,
100
+ }),
101
+ ),
102
+ }),
103
+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
104
+ internalServerError(error, error),
105
+ ),
106
+ );
107
+
108
export const layer = HttpApiBuilder.group(
109
EnvironmentHttpApi,
110
"connect",
@@ -28,42 +115,46 @@ export const layer = HttpApiBuilder.group(
115
Effect.gen(function* () {
116
yield* requireEnvironmentScope(AuthRelayWriteScope);
117
const request = yield* HttpServerRequest.HttpServerRequest;
31
- const proof = yield* cloudLink.linkProof(payload, request);
118
+ const proof = yield* toHttpError(cloudLink.linkProof(payload, request));
119
yield* appendCloudCredentialResponseHeaders;
120
return proof;
121
}),
122
)
123
.handle("relayConfig", ({ payload }) =>
124
requireEnvironmentScope(AuthRelayWriteScope).pipe(
38
- Effect.andThen(cloudLink.applyRelayConfig(payload)),
125
+ Effect.andThen(toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload))),
126
),
127
)
128
.handle("linkState", () =>
42
- requireEnvironmentScope(AuthRelayReadScope).pipe(Effect.andThen(cloudLink.linkState())),
129
+ requireEnvironmentScope(AuthRelayReadScope).pipe(
130
+ Effect.andThen(toHttpError(cloudLink.linkState())),
131
+ ),
132
)
133
.handle("unlink", () =>
45
- requireEnvironmentScope(AuthRelayWriteScope).pipe(Effect.andThen(cloudLink.unlink())),
134
+ requireEnvironmentScope(AuthRelayWriteScope).pipe(
135
+ Effect.andThen(toHttpError(cloudLink.unlink())),
136
+ ),
137
)
138
.handle("preferences", ({ payload }) =>
139
requireEnvironmentScope(AuthRelayWriteScope).pipe(
49
- Effect.andThen(cloudLink.updatePreferences(payload)),
140
+ Effect.andThen(toHttpError(cloudLink.updatePreferences(payload))),
141
),
142
)
143
.handle("health", ({ payload }) =>
53
- cloudLink
54
- .answerHealthRequest(payload)
55
- .pipe(Effect.tap(() => appendCloudCredentialResponseHeaders)),
144
+ toHttpError(cloudLink.answerHealthRequest(payload)).pipe(
145
+ Effect.tap(() => appendCloudCredentialResponseHeaders),
146
+ ),
147
)
148
.handle("mintCredential", ({ payload }) =>
58
- cloudLink
59
- .mintCredential(payload)
60
- .pipe(Effect.tap(() => appendCloudCredentialResponseHeaders)),
149
+ toHttpError(cloudLink.mintCredential(payload)).pipe(
150
+ Effect.tap(() => appendCloudCredentialResponseHeaders),
151
+ ),
152
)
153
.handle("t3MintCredential", ({ payload }) =>
154
traceRelayRequest(
64
- cloudLink
65
- .mintCredential(payload)
66
- .pipe(Effect.tap(() => appendCloudCredentialResponseHeaders)),
155
+ toHttpError(cloudLink.mintCredential(payload)).pipe(
156
+ Effect.tap(() => appendCloudCredentialResponseHeaders),
157
+ ),
158
),
159
);
160
}),
apps/server/src/cloud/relayResponse.test.ts
+13
-9
@@ -3,7 +3,11 @@ import * as Effect from "effect/Effect";
3
import { HttpClientRequest, HttpClientResponse } from "effect/http";
4
import * as HttpClientError from "effect/http/HttpClientError";
5
6
-import { filterRelayResponse, relayRequestError, shouldRetryCloudLink } from "./relayResponse.ts";
6
+import {
7
+ filterRelayResponse,
8
+ relayRequestError,
9
+ shouldRetryRelayRequest,
10
+} from "./relayResponse.ts";
11
12
const response = (
13
status: number,
@@ -28,12 +32,12 @@ it("reports a transport failure category without exposing request or cause detai
32
}),
33
);
34
31
- expect(error._tag).toBe("EnvironmentHttpInternalServerError");
35
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unavailable" });
36
expect(error.message).toContain("TransportError");
37
expect(error.message).toContain("network connection");
38
expect(error.message).not.toContain("relay.example.test");
39
expect(error.message).not.toContain("private");
36
- expect(shouldRetryCloudLink(error)).toBe(true);
40
+ expect(shouldRetryRelayRequest(error)).toBe(true);
41
});
42
43
it.effect("reports the tunnel limit and relay trace instead of a generic 403", () =>
@@ -47,7 +51,7 @@ it.effect("reports the tunnel limit and relay trace instead of a generic 403", (
51
}),
52
).pipe(Effect.mapError(relayRequestError), Effect.flip);
53
50
- expect(error._tag).toBe("EnvironmentHttpForbiddenError");
54
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "forbidden" });
55
expect(error.message).toContain("at most 3 tunnels");
56
expect(error.message).toContain("Unlink an unused environment");
57
expect(error.message).toContain("Trace ID: trace-limit");
@@ -65,7 +69,7 @@ it.effect("makes revoked authorization actionable and non-retryable", () =>
69
}),
70
).pipe(Effect.mapError(relayRequestError), Effect.flip);
71
68
- expect(error._tag).toBe("EnvironmentHttpUnauthorizedError");
72
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unauthorized" });
73
expect(error.message).toContain("invalid_bearer");
74
expect(error.message).toContain("t3 connect login");
75
expect(error.message).toContain("Trace ID: trace-auth");
@@ -81,7 +85,7 @@ it.effect("reports an unrecognized access denial without printing its response b
85
}),
86
).pipe(Effect.flip);
87
84
- expect(error._tag).toBe("EnvironmentHttpForbiddenError");
88
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "forbidden" });
89
expect(error.message).toContain("HTTP 403");
90
expect(error.message).toContain("proxy or firewall");
91
expect(error.message).toContain("Cloudflare Ray ID: abcdef1234-IAD");
@@ -94,7 +98,7 @@ it.effect.each([408, 429, 500, 502, 503, 504])(
98
(status) =>
99
Effect.gen(function* () {
100
const error = yield* filterRelayResponse(response(status, "unavailable")).pipe(Effect.flip);
97
- expect(error._tag).toBe("EnvironmentHttpInternalServerError");
101
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unavailable" });
102
expect(error.message).toContain(`HTTP ${status}`);
103
}),
104
);
@@ -112,7 +116,7 @@ it.effect.each([
116
return filterRelayResponse(response(requests === 1 ? status : 200, "{}"));
117
}).pipe(
118
Effect.mapError(relayRequestError),
115
- Effect.retry({ while: shouldRetryCloudLink, times: 1 }),
119
+ Effect.retry({ while: shouldRetryRelayRequest, times: 1 }),
120
Effect.result,
121
);
122
expect(requests).toBe(attempts);
@@ -131,7 +135,7 @@ it.effect("keeps the relay failure reason and trace when tunnel cleanup fails",
135
}),
136
).pipe(Effect.flip);
137
134
- expect(error._tag).toBe("EnvironmentHttpInternalServerError");
138
+ expect(error).toMatchObject({ _tag: "RelayRequestError", rejection: "unavailable" });
139
expect(error.message).toContain("upstream_unavailable");
140
expect(error.message).toContain("Trace ID: trace-cleanup");
141
}),
apps/server/src/cloud/relayResponse.ts
+35
-34
@@ -1,10 +1,3 @@
1
-import {
2
- EnvironmentHttpBadRequestError,
3
- EnvironmentHttpConflictError,
4
- EnvironmentHttpForbiddenError,
5
- EnvironmentHttpInternalServerError,
6
- EnvironmentHttpUnauthorizedError,
7
-} from "@t3tools/contracts";
1
import { RelayProtectedError } from "@t3tools/contracts/relay";
2
import * as Effect from "effect/Effect";
3
import * as Option from "effect/Option";
@@ -12,33 +5,37 @@ import * as Schema from "effect/Schema";
5
import * as HttpClientResponse from "effect/http/HttpClientResponse";
6
import { isHttpClientError } from "effect/http/HttpClientError";
7
15
-const isRelayResponseError = Schema.is(
16
- Schema.Union([
17
- EnvironmentHttpBadRequestError,
18
- EnvironmentHttpForbiddenError,
19
- EnvironmentHttpInternalServerError,
20
- EnvironmentHttpUnauthorizedError,
21
- ]),
22
-);
8
+/**
9
+ * A relay request that did not succeed. `unavailable` means it may succeed on
10
+ * retry; the relay refused the other kinds. The description is safe to show:
11
+ * it carries the relay's own explanation and trace ID, never request details.
12
+ */
13
+export class RelayRequestError extends Schema.TaggedError<RelayRequestError>()(
14
+ "RelayRequestError",
15
+ {
16
+ rejection: Schema.Literals(["unauthorized", "forbidden", "rejected", "unavailable"]),
17
+ description: Schema.String,
18
+ },
19
+) {
20
+ override get message(): string {
21
+ return this.description;
22
+ }
23
+}
24
+
25
+const isRelayRequestError = Schema.is(RelayRequestError);
26
24
-export function relayRequestError(cause: unknown) {
25
- return isRelayResponseError(cause)
27
+export function relayRequestError(cause: unknown): RelayRequestError {
28
+ return isRelayRequestError(cause)
29
? cause
27
- : new EnvironmentHttpInternalServerError({
28
- message: `Could not complete the T3 Connect relay request. ${isHttpClientError(cause) ? `The relay request failed (${cause.reason._tag}).` : "The relay returned an unexpected response."} Check this machine's network connection and relay availability, then retry.`,
30
+ : new RelayRequestError({
31
+ rejection: "unavailable",
32
+ description: `Could not complete the T3 Connect relay request. ${isHttpClientError(cause) ? `The relay request failed (${cause.reason._tag}).` : "The relay returned an unexpected response."} Check this machine's network connection and relay availability, then retry.`,
33
});
34
}
35
32
-const isPermanentCloudLinkError = Schema.is(
33
- Schema.Union([
34
- EnvironmentHttpBadRequestError,
35
- EnvironmentHttpForbiddenError,
36
- EnvironmentHttpUnauthorizedError,
37
- EnvironmentHttpConflictError,
38
- ]),
39
-);
40
-
41
-export const shouldRetryCloudLink = (error: unknown): boolean => !isPermanentCloudLinkError(error);
36
+/** Whether a failure may succeed on retry: anything but a relay refusal. */
37
+export const shouldRetryRelayRequest = (error: unknown): boolean =>
38
+ !isRelayRequestError(error) || error.rejection === "unavailable";
39
40
function recoveryHint(error: RelayProtectedError): string {
41
switch (error._tag) {
@@ -64,19 +61,23 @@ export const filterRelayResponse = Effect.fn("cloud.filter_relay_response")(func
61
);
62
const ray = response.headers["cf-ray"];
63
const requestId = ray && /^[a-zA-Z0-9-]{1,128}$/.test(ray) ? ` Cloudflare Ray ID: ${ray}.` : "";
67
- const message = Option.isSome(decoded)
64
+ const description = Option.isSome(decoded)
65
? `T3 Connect: ${decoded.value.message}. ${recoveryHint(decoded.value)} Trace ID: ${decoded.value.traceId}.`
66
: `T3 Connect relay returned HTTP ${response.status} without a recognized error response. Check relay access and any proxy or firewall restrictions, then restart T3 Code.${requestId}`;
67
71
- if (response.status === 401) return yield* new EnvironmentHttpUnauthorizedError({ message });
72
- if (response.status === 403) return yield* new EnvironmentHttpForbiddenError({ message });
68
+ if (response.status === 401) {
69
+ return yield* new RelayRequestError({ rejection: "unauthorized", description });
70
+ }
71
+ if (response.status === 403) {
72
+ return yield* new RelayRequestError({ rejection: "forbidden", description });
73
+ }
74
if (
75
response.status >= 400 &&
76
response.status < 500 &&
77
response.status !== 408 &&
78
response.status !== 429
79
) {
79
- return yield* new EnvironmentHttpBadRequestError({ message });
80
+ return yield* new RelayRequestError({ rejection: "rejected", description });
81
}
81
- return yield* new EnvironmentHttpInternalServerError({ message });
82
+ return yield* new RelayRequestError({ rejection: "unavailable", description });
83
});
apps/server/src/server.ts
+5
-6
@@ -126,7 +126,6 @@ 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";
129
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
130
import {
131
MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER,
@@ -845,8 +844,8 @@ const layerMakeServer = Layer.unwrap(
844
),
845
Effect.retry({
846
while: (error) =>
848
- shouldRetryCloudLink(error) &&
849
- error._tag !== "EnvironmentCloudEndpointUnavailableError",
847
+ CloudLink.shouldRetryCloudLink(error) &&
848
+ error._tag !== "CloudLinkEndpointUnavailableError",
849
schedule: Schedule.exponential("1 second").pipe(
850
Schedule.modifyDelay(({ duration }) =>
851
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
@@ -931,8 +930,8 @@ const layerMakeServer = Layer.unwrap(
930
retryRuntimeFailures: true,
931
}),
932
(error) =>
934
- shouldRetryCloudLink(error) &&
935
- error._tag !== "EnvironmentCloudEndpointUnavailableError",
933
+ CloudLink.shouldRetryCloudLink(error) &&
934
+ error._tag !== "CloudLinkEndpointUnavailableError",
935
startedConfirmed ? Effect.void : startStoredManagedTunnel,
936
).pipe(
937
Effect.tap((result) =>
@@ -977,7 +976,7 @@ const layerMakeServer = Layer.unwrap(
976
.reconcileDesiredLinkIfStillDesired(localOrigin)
977
.pipe(
978
Effect.retry({
980
- while: shouldRetryCloudLink,
979
+ while: CloudLink.shouldRetryCloudLink,
980
schedule: Schedule.exponential("1 second").pipe(
981
Schedule.modifyDelay(({ duration }) =>
982
Effect.succeed(Duration.min(duration, Duration.seconds(30))),