From 4e4cb07265f025421f6c1b700ab1ba58ac3387c4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 3 Aug 2026 15:35:38 -0700 Subject: [PATCH] fix: harden remote server lifecycle --- apps/server/src/cli/pair.test.ts | 7 +- apps/server/src/cli/pair.ts | 9 +- apps/server/src/cli/service.test.ts | 42 +++++- apps/server/src/cli/service.ts | 96 ++++++++++-- apps/server/src/cloud/bootService.test.ts | 5 +- apps/server/src/cloud/bootService.ts | 2 + apps/server/src/cloud/http.test.ts | 138 +++++++++++++++++- apps/server/src/cloud/http.ts | 108 +++++++++++++- apps/server/src/server.ts | 20 ++- apps/server/src/serverRuntimeStartup.ts | 16 +- apps/server/src/startupAccess.test.ts | 12 ++ apps/server/src/startupAccess.ts | 18 ++- apps/web/src/components/ChatView.tsx | 55 +++++++ apps/web/src/connection/platform.ts | 1 + apps/web/src/versionSkew.test.ts | 55 +++++++ apps/web/src/versionSkew.ts | 52 +++++++ docs/user/background-service.md | 15 ++ .../ManagedEndpointProvider.test.ts | 5 + .../environments/ManagedEndpointProvider.ts | 1 + infra/relay/src/http/Api.ts | 59 +++++++- .../src/authorization/layer.test.ts | 4 + .../src/authorization/service.ts | 7 + .../src/authorization/tokenStore.ts | 1 + .../client-runtime/src/connection/model.ts | 3 + .../src/connection/presentation.test.ts | 23 +++ .../src/connection/presentation.ts | 20 ++- .../src/connection/resolver.test.ts | 2 + .../client-runtime/src/connection/resolver.ts | 10 ++ .../client-runtime/src/rpc/session.test.ts | 27 ++++ packages/client-runtime/src/rpc/session.ts | 56 ++++++- packages/contracts/src/relay.ts | 28 +++- packages/tailscale/src/tailscale.test.ts | 2 + packages/tailscale/src/tailscale.ts | 3 + 33 files changed, 847 insertions(+), 55 deletions(-) diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts index c4f321a5a6..e210d1dd7d 100644 --- a/apps/server/src/cli/pair.test.ts +++ b/apps/server/src/cli/pair.test.ts @@ -205,7 +205,8 @@ describe("t3 pair", () => { const rendered = String( typeof error === "object" && error !== null && "cause" in error ? error.cause : error, ); - assert.include(rendered, "No running T3 Code server found."); + assert.include(rendered, "No usable T3 Code server runtime state found."); + assert.include(rendered, "--base-dir"); assert.include(rendered, "npx t3 serve"); assert.include(rendered, "npx t3 connect"); }).pipe(Effect.provide(NodeServices.layer)), @@ -236,7 +237,7 @@ describe("t3 pair", () => { const rendered = String( typeof error === "object" && error !== null && "cause" in error ? error.cause : error, ); - assert.include(rendered, "No running T3 Code server found."); + assert.include(rendered, "No usable T3 Code server runtime state found."); }), ).pipe(Effect.provide(NodeServices.layer)), ); @@ -262,7 +263,7 @@ describe("t3 pair", () => { const rendered = String( typeof error === "object" && error !== null && "cause" in error ? error.cause : error, ); - assert.include(rendered, "No running T3 Code server found."); + assert.include(rendered, "No usable T3 Code server runtime state found."); }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index 38fa3be8bb..44ac562f89 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -20,6 +20,7 @@ import { DEFAULT_TAILSCALE_SERVE_PORT, ensureTailscaleServe, readTailscaleStatus, + TailscaleCommandExitError, } from "@t3tools/tailscale"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; @@ -76,9 +77,10 @@ export class NoRunningServerError extends Schema.TaggedErrorClass ` checked ${statePath}`), - "Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.", + "If a server is running, pass its T3 home with `--base-dir`; its runtime state may be missing or stale.", + "Otherwise start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.", ].join("\n"); } } @@ -117,6 +119,9 @@ export class TailscaleServeFailedError extends Schema.TaggedErrorClass\` by hand to see why.`; } } diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index e91e10000b..4074880ac4 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -1,6 +1,6 @@ import { assert, it } from "@effect/vitest"; -import { formatServiceStatus } from "./service.ts"; +import { formatServiceStatus, serviceDowngradeRefusal } from "./service.ts"; const status = { supported: true, @@ -8,6 +8,7 @@ const status = { current: true, unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", + installedVersion: "0.0.29", } as const; it("reports the installed service version and host paths", () => { @@ -35,3 +36,42 @@ it("explains service availability without systemd", () => { "Supported on: Linux with systemd", ); }); + +it("reports a newer installed service without recommending latest", () => { + const output = formatServiceStatus( + { ...status, current: false, installedVersion: "0.0.32-nightly.1" }, + "0.0.31", + ); + + assert.include(output, "t3@0.0.32-nightly.1 (newer than this t3@0.0.31 CLI)"); + assert.include(output, "npx t3@0.0.32-nightly.1 service update"); + assert.notInclude(output, "npx t3@latest service update"); +}); + +it("refuses service downgrades unless explicitly allowed", () => { + const refusal = serviceDowngradeRefusal({ + installedVersion: "0.0.32-nightly.1", + targetVersion: "0.0.31", + allowDowngrade: false, + }); + assert.instanceOf(refusal, Error); + assert.deepInclude(refusal, { + _tag: "ServiceDowngradeRefusedError", + installedVersion: "0.0.32-nightly.1", + targetVersion: "0.0.31", + }); + assert.isNull( + serviceDowngradeRefusal({ + installedVersion: "0.0.32-nightly.1", + targetVersion: "0.0.31", + allowDowngrade: true, + }), + ); + assert.isNull( + serviceDowngradeRefusal({ + installedVersion: undefined, + targetVersion: "0.0.31", + allowDowngrade: false, + }), + ); +}); diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index d55b270f18..948385956f 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -1,11 +1,13 @@ import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; import * as Terminal from "effect/Terminal"; -import { Command, GlobalFlag, Prompt } from "effect/unstable/cli"; +import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli"; import packageJson from "../../package.json" with { type: "json" }; import * as BootService from "../cloud/bootService.ts"; +import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts"; import type * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -28,13 +30,50 @@ export type ServiceReconcileResult = readonly plan: BootService.BootServicePlan; }; +export class ServiceDowngradeRefusedError extends Schema.TaggedErrorClass()( + "ServiceDowngradeRefusedError", + { + installedVersion: Schema.String, + targetVersion: Schema.String, + }, +) { + override get message(): string { + return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Re-run with --allow-downgrade to continue.`; + } +} + +export function serviceDowngradeRefusal(input: { + readonly installedVersion: string | undefined; + readonly targetVersion: string; + readonly allowDowngrade: boolean; +}): ServiceDowngradeRefusedError | null { + return input.installedVersion !== undefined && + !input.allowDowngrade && + compareExactServiceVersions(input.targetVersion, input.installedVersion) < 0 + ? new ServiceDowngradeRefusedError({ + installedVersion: input.installedVersion, + targetVersion: input.targetVersion, + }) + : null; +} + /** Install, update, or repair the service using the CLI version running this command. */ -export const reconcileService = Effect.fn("cli.service.reconcile")(function* () { +export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: { + readonly allowDowngrade?: boolean; +}) { const service = yield* BootService.BootService; const status = yield* service.status; if (status.installed && status.current) { return { changed: false, status } satisfies ServiceReconcileResult; } + const downgradeRefusal = serviceDowngradeRefusal({ + installedVersion: status.installedVersion, + targetVersion: packageJson.version, + allowDowngrade: options?.allowDowngrade === true, + }); + if (downgradeRefusal !== null) { + return yield* downgradeRefusal; + } const plan = yield* service.install; return { changed: true, @@ -53,9 +92,23 @@ export function formatServiceStatus( if (!status.installed) { return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`."; } + const installedVersion = status.installedVersion ?? cliVersion; + if ( + !status.current && + status.installedVersion !== undefined && + compareExactServiceVersions(status.installedVersion, cliVersion) > 0 + ) { + return [ + "T3 Code service", + ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`, + ` Unit: ${status.unitPath}`, + ` Logs: ${status.logPath}`, + ` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`, + ].join("\n"); + } return [ "T3 Code service", - ` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`, + ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`, ` Unit: ${status.unitPath}`, ` Logs: ${status.logPath}`, ...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]), @@ -71,13 +124,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* ( return yield* run.pipe(Effect.provide(bootServiceLayer(config))); }); -const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe( +const serviceReconcileFlags = { + ...projectLocationFlags, + allowDowngrade: Flag.boolean("allow-downgrade").pipe( + Flag.withDescription("Allow replacing a newer installed service with this older CLI version."), + Flag.withDefault(false), + ), +}; + +const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe( Command.withDescription("Install T3 Code as a background service for this user."), Command.withHandler((flags) => runServiceCommand( flags, Effect.gen(function* () { - const result = yield* reconcileService(); + const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade }); if (!result.changed) { yield* Console.log( `T3 Code service is already installed with t3@${packageJson.version}.`, @@ -92,7 +153,7 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe ), ); -const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe( +const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe( Command.withDescription( "Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.", ), @@ -100,7 +161,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe( runServiceCommand( flags, Effect.gen(function* () { - const result = yield* reconcileService(); + const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade }); if (!result.changed) { yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`); return; @@ -144,7 +205,8 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe( export const offerServiceDuringOnboarding = Effect.gen(function* () { const service = yield* BootService.BootService; - const { supported, installed, current } = yield* service.status; + const status = yield* service.status; + const { supported, installed, current } = status; if (!supported) { return false; } @@ -152,6 +214,16 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () { yield* Console.log("T3 Code is already set up to run in the background on this machine."); return true; } + if ( + installed && + status.installedVersion !== undefined && + compareExactServiceVersions(status.installedVersion, packageJson.version) > 0 + ) { + yield* Console.log( + `T3 Code is already running newer t3@${status.installedVersion}; leaving it unchanged.`, + ); + return true; + } const wanted = yield* Prompt.run( Prompt.confirm({ message: installed @@ -174,7 +246,11 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () { }); export const recoverServiceOnboardingOffer = ( - offer: Effect.Effect, + offer: Effect.Effect< + boolean, + BootService.BootServiceError | ServiceDowngradeRefusedError | Terminal.QuitError, + R + >, ) => offer.pipe( Effect.catchTags({ @@ -187,6 +263,8 @@ export const recoverServiceOnboardingOffer = ( Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)), BootServiceUpdatePendingError: (error) => Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)), + ServiceDowngradeRefusedError: (error) => + Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)), }), ); diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index a9ae3f49f7..50d34032d7 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -105,7 +105,10 @@ it.layer(NodeServices.layer)("boot service install", (it) => { activeVersion: "1.2.3", }); expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n"); - expect((yield* service.status).current).toBe(true); + expect(yield* service.status).toMatchObject({ + current: true, + installedVersion: "1.2.3", + }); // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document. const pendingState = JSON.stringify({ protocol: SERVICE_LAUNCHER_PROTOCOL, diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index ec110cb8b6..53c7fb76ed 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -130,6 +130,7 @@ export interface BootServiceStatus { readonly supported: boolean; readonly installed: boolean; readonly current: boolean; + readonly installedVersion?: string; readonly unitPath: string; readonly logPath: string; } @@ -393,6 +394,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { return { supported: true, installed: true, + ...(state?.activeVersion === undefined ? {} : { installedVersion: state.activeVersion }), current: unit === renderBootServiceUnit(plan) && launcherExists && diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index c779c13aaf..0fcd6642a9 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -19,12 +19,20 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; import type { RelayLinkProofRequest } from "@t3tools/contracts/relay"; -import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts"; +import { + CLOUD_ENDPOINT_RUNTIME_CONFIG, + CLOUD_LINKED_USER_ID, + decodeRuntimeConfig, + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + RELAY_URL_SECRET, +} from "./config.ts"; import { consumeCloudReplayGuards, isSupportedLinkProviderKind, linkProofScopes, + managedEndpointOriginsEqual, reconcileDesiredCloudLink, + reconcileManagedEndpointOrigin, releaseManagedTunnelOnShutdown, } from "./http.ts"; import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts"; @@ -79,6 +87,18 @@ it("preserves messages surfaced by cloud 500 responses", () => { ]); }); +it("compares managed endpoint origins without hostname formatting drift", () => { + const desired = { localHttpHost: "127.0.0.1", localHttpPort: 7331 } as const; + + expect(managedEndpointOriginsEqual(undefined, desired)).toBe(false); + expect( + managedEndpointOriginsEqual({ localHttpHost: "[127.0.0.1]", localHttpPort: 7331 }, desired), + ).toBe(true); + expect( + managedEndpointOriginsEqual({ localHttpHost: "127.0.0.1", localHttpPort: 7332 }, desired), + ).toBe(false); +}); + describe("consumeCloudReplayGuards", () => { it.effect("reports already-created guards as replay conflicts", () => Effect.gen(function* () { @@ -222,6 +242,122 @@ describe("reconcileDesiredCloudLink", () => { ); }); +describe("reconcileManagedEndpointOrigin", () => { + it.effect("uses the environment credential and persists the reconciled origin", () => { + const initialSecrets: ReadonlyArray = [ + [ + CLOUD_ENDPOINT_RUNTIME_CONFIG, + JSON.stringify({ + providerKind: "cloudflare_tunnel", + connectorToken: "old-connector-token", + }), + ], + [RELAY_URL_SECRET, "https://relay.example.test"], + [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"], + [CLOUD_LINKED_USER_ID, "user_123"], + ]; + const values = new Map( + initialSecrets.map(([name, value]) => [name, new TextEncoder().encode(value)] as const), + ); + const store: ServerSecretStore.ServerSecretStore["Service"] = { + get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))), + set: (name, value) => + Effect.sync(() => { + values.set(name, value); + }), + create: unusedSecretStoreOperation, + getOrCreateRandom: unusedSecretStoreOperation, + remove: unusedSecretStoreOperation, + }; + const requests: Array = []; + const applied: Array = []; + + return Effect.gen(function* () { + expect(yield* reconcileManagedEndpointOrigin("http://127.0.0.1:4555")).toBe(true); + + expect(requests).toHaveLength(1); + expect(requests[0]?.url).toBe( + "https://relay.example.test/v1/environments/env_123/managed-endpoint/reconcile", + ); + expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential"); + expect(applied).toEqual([ + { + providerKind: "cloudflare_tunnel", + connectorToken: "fresh-connector-token", + tunnelId: "tunnel-123", + tunnelName: "tunnel-name", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 }, + }, + ]); + const persisted = decodeRuntimeConfig( + new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)), + ); + expect(Option.getOrNull(persisted)?.origin).toEqual({ + localHttpHost: "127.0.0.1", + localHttpPort: 4555, + }); + }).pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, store), + Effect.provideService( + ServerEnvironment.ServerEnvironment, + ServerEnvironment.ServerEnvironment.of({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")), + getDescriptor: unusedSecretStoreOperation(), + }), + ), + Effect.provideService( + ManagedEndpointRuntime.CloudManagedEndpointRuntime, + ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({ + applyConfig: (config) => + Effect.sync(() => { + applied.push(config); + return { + status: "running", + providerKind: "cloudflare_tunnel", + pid: 123, + } as const; + }), + }), + ), + Effect.provideService( + EnvironmentAuth.EnvironmentAuth, + EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]), + ), + Effect.provideService( + CliTokenManager.CloudCliTokenManager, + CliTokenManager.CloudCliTokenManager.of({ + get: unusedSecretStoreOperation(), + getExisting: unusedSecretStoreOperation(), + hasCredential: unusedSecretStoreOperation(), + store: unusedSecretStoreOperation, + clear: unusedSecretStoreOperation(), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + requests.push(request); + return HttpClientResponse.fromWeb( + request, + Response.json({ + endpointRuntime: { + providerKind: "cloudflare_tunnel", + connectorToken: "fresh-connector-token", + tunnelId: "tunnel-123", + tunnelName: "tunnel-name", + origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 }, + }, + }), + ); + }), + ), + ), + Effect.provide(NodeServices.layer), + ); + }); +}); + describe("releaseManagedTunnelOnShutdown", () => { const cliToken: CliTokenManager.PersistedToken = { accessToken: "cli-access-token", diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index eaf31a37f2..9dce0ad57a 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -22,6 +22,7 @@ import { RelayEnvironmentConfigRequest, RelayEnvironmentLinkChallengeResponse, RelayEnvironmentLinkResponse, + RelayManagedEndpointReconcileResponse, RelayEnvironmentMintResponseProofPayload, type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape, RelayEnvironmentLinkProof, @@ -62,6 +63,7 @@ import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINKED_USER_ID, CLOUD_MINT_PUBLIC_KEY, + decodeRuntimeConfig, encodeEndpointRuntimeConfigJson, PUBLISH_AGENT_ACTIVITY_SECRET, RELAY_ENVIRONMENT_CREDENTIAL_SECRET, @@ -627,6 +629,102 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD }, ); +function managedEndpointOriginFromLocalUrl(localUrl: URL): RelayManagedEndpointOrigin { + return { + localHttpHost: localUrl.hostname, + localHttpPort: endpointRequestPort(localUrl), + }; +} + +export function managedEndpointOriginsEqual( + left: RelayManagedEndpointOrigin | undefined, + right: RelayManagedEndpointOrigin, +): boolean { + return ( + left !== undefined && + normalizeHostname(left.localHttpHost) === normalizeHostname(right.localHttpHost) && + left.localHttpPort === right.localHttpPort + ); +} + +const reconcileManagedEndpointOriginWith = Effect.fn( + "environment.cloud.reconcileManagedEndpointOriginWith", +)(function* (dependencies: CloudHttpDependencies, localOrigin: string) { + const localUrl = yield* Effect.try({ + try: () => new URL(localOrigin), + catch: () => + new EnvironmentHttpBadRequestError({ + message: "Could not resolve local environment origin.", + }), + }); + if (localUrl.origin !== localOrigin) { + return yield* new EnvironmentHttpBadRequestError({ + message: "Could not resolve local environment origin.", + }); + } + const desiredOrigin = managedEndpointOriginFromLocalUrl(localUrl); + const storedConfigBytes = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG); + const storedConfig = Option.isSome(storedConfigBytes) + ? decodeRuntimeConfig(bytesToString(storedConfigBytes.value)) + : Option.none(); + if (Option.isSome(storedConfigBytes) && Option.isNone(storedConfig)) { + return yield* new EnvironmentHttpInternalServerError({ + message: "Stored managed endpoint runtime configuration is invalid.", + }); + } + const config = Option.getOrNull(storedConfig); + const desiredManagedLink = + (yield* readCliDesiredCloudLink) && (yield* readCliDesiredLinkMode) === "managed"; + if (config?.providerKind !== "cloudflare_tunnel" && !desiredManagedLink) { + return false; + } + if (managedEndpointOriginsEqual(config?.origin, desiredOrigin)) { + return false; + } + + const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET); + const environmentCredential = yield* dependencies.secrets.get( + RELAY_ENVIRONMENT_CREDENTIAL_SECRET, + ); + const cloudUserId = yield* dependencies.secrets.get(CLOUD_LINKED_USER_ID); + if ( + Option.isNone(relayUrl) || + Option.isNone(environmentCredential) || + Option.isNone(cloudUserId) + ) { + return yield* new EnvironmentHttpUnauthorizedError({ + message: "This managed environment is missing its T3 Connect credentials. Link it again.", + }); + } + + const environmentId = yield* dependencies.environment.getEnvironmentId; + const response = yield* relayClientRequest(dependencies, { + url: `${bytesToString(relayUrl.value)}/v1/environments/${encodeURIComponent(environmentId)}/managed-endpoint/reconcile`, + token: bytesToString(environmentCredential.value), + payload: { + cloudUserId: bytesToString(cloudUserId.value), + origin: desiredOrigin, + }, + schema: RelayManagedEndpointReconcileResponse, + }); + const status = yield* dependencies.endpointRuntime.applyConfig(response.endpointRuntime); + if (status.status !== "running") { + return yield* new EnvironmentCloudEndpointUnavailableError({ + message: "Managed endpoint runtime could not be started after origin reconciliation.", + endpointRuntimeStatus: status, + }); + } + const encoded = yield* encodeEndpointRuntimeConfigJson(response.endpointRuntime); + yield* dependencies.secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(encoded)); + return true; +}); + +export const reconcileManagedEndpointOrigin = Effect.fn( + "environment.cloud.reconcileManagedEndpointOrigin", +)(function* (localOrigin: string) { + return yield* reconcileManagedEndpointOriginWith(yield* cloudHttpDependencies, localOrigin); +}); + // Cloudflare bills per provisioned tunnel, so an environment that goes offline // must not leave its tunnel behind. Releasing deletes only the tunnel — the // relay keeps the link and its hostname reservation, and the next startup's @@ -641,11 +739,11 @@ export const releaseManagedTunnelOnShutdown = Effect.fn( if (Option.isNone(runtimeConfig)) { return false; } - // Only CLI-desired managed links release on shutdown, because the startup - // reconcile that provisions the replacement tunnel only runs for them. A - // link installed by a web/mobile client comes back after a restart by - // reapplying the stored connector token — it has no boot-time re-provision - // path — so its tunnel must survive the restart. (Unlink still deletes it.) + // Only CLI-desired managed links release on shutdown. Their desired-link + // marker lets startup re-provision after this function removes the dead + // runtime config. Web/mobile links have no equivalent marker, so they keep + // the tunnel and stored connector token across restarts. (Unlink still + // deletes it.) if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") { return false; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 534d216aad..a0c25fb96f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -83,13 +83,12 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { connectHttpApiLayer, - reconcileDesiredCloudLink, + reconcileManagedEndpointOrigin, releaseManagedTunnelOnShutdown, } from "./cloud/http.ts"; import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts"; import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts"; -import * as CloudCliState from "./cloud/CliState.ts"; import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; @@ -579,27 +578,26 @@ export const makeServerLayer = Layer.unwrap( Effect.asVoid, ), ); - if (!(yield* CloudCliState.readCliDesiredCloudLink)) return; const server = yield* HttpServer.HttpServer; const address = server.address; if (typeof address === "string" || !("port" in address)) return; yield* Effect.sleep("250 millis").pipe( - Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)), + Effect.andThen(reconcileManagedEndpointOrigin(`http://127.0.0.1:${address.port}`)), Effect.retry({ - while: (error) => - error._tag !== "EnvironmentHttpBadRequestError" && - error._tag !== "EnvironmentHttpUnauthorizedError" && - error._tag !== "EnvironmentHttpConflictError", + while: (error) => error._tag !== "EnvironmentHttpBadRequestError", schedule: Schedule.exponential("1 second").pipe( Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, Duration.seconds(30))), ), - Schedule.upTo({ duration: "10 minutes" }), ), }), - Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")), + Effect.tap((reconciled) => + reconciled + ? Effect.logInfo("T3 Connect managed endpoint origin reconciled on startup") + : Effect.void, + ), Effect.catch((cause) => - Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", { + Effect.logWarning("Failed to reconcile T3 Connect managed endpoint on startup", { cause, }), ), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 5db2b75556..7ab2ed657a 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -7,6 +7,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -36,11 +37,14 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts"; import { forkParked } from "./serverActivation.ts"; import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; +import { BOOT_SERVICE_UNIT_ENV, BOOT_SERVICE_UNIT_FILE } from "./cloud/bootService.ts"; import { formatHeadlessServeOutput, + formatManagedHeadlessServeOutput, formatHostForUrl, isWildcardHost, issueHeadlessServeAccessInfo, + resolveHeadlessServeConnectionString, } from "./startupAccess.ts"; export class ServerRuntimeStartupError extends Schema.TaggedErrorClass()( @@ -307,6 +311,9 @@ export const make = (options?: StartupOptions) => const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; const crypto = yield* Crypto.Crypto; const launcher = yield* ServiceLauncherClient.ServiceLauncherClient; + const hostEnvironment = yield* HostProcessEnvironment; + const managedServiceStartup = + launcher.managed || hostEnvironment[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE; const commandGate = yield* makeCommandGate; const httpListening = yield* Deferred.make(); @@ -406,11 +413,10 @@ export const make = (options?: StartupOptions) => Effect.ignoreCause({ log: true }), ); if (serverConfig.startupPresentation === "headless") { - const accessInfo = yield* issueHeadlessServeAccessInfo(); - yield* runStartupPhase( - "headless.output", - Console.log(formatHeadlessServeOutput(accessInfo)), - ); + const output = managedServiceStartup + ? formatManagedHeadlessServeOutput(yield* resolveHeadlessServeConnectionString) + : formatHeadlessServeOutput(yield* issueHeadlessServeAccessInfo()); + yield* runStartupPhase("headless.output", Console.log(output)); } else { const startupBrowserTarget = yield* resolveStartupBrowserTarget; if (serverConfig.mode !== "desktop") { diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 03c01170f1..3f0b56d2fa 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -3,6 +3,7 @@ import { assert, expect, it } from "@effect/vitest"; import { buildPairingUrl, formatHeadlessServeOutput, + formatManagedHeadlessServeOutput, renderTerminalQrCode, resolveHeadlessConnectionHost, resolveHeadlessConnectionString, @@ -77,3 +78,14 @@ it("formats headless serve output with the connection string, token, pairing url expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE"); assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄")); }); + +it("formats managed service output without mintable pairing material", () => { + const output = formatManagedHeadlessServeOutput("http://127.0.0.1:3773"); + + expect(output).toContain("Connection string: http://127.0.0.1:3773"); + expect(output).toContain("Run `npx t3 pair` to create a pairing URL."); + expect(output).not.toContain("Token:"); + expect(output).not.toContain("Pairing URL:"); + expect(output).not.toContain("#token="); + assert.isFalse(output.includes("█") || output.includes("▀") || output.includes("▄")); +}); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index 7df131669b..e49ab2f5b0 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -130,14 +130,26 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): "", ].join("\n"); -export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () { +export const formatManagedHeadlessServeOutput = (connectionString: string): string => + [ + "T3 Code server is ready.", + `Connection string: ${connectionString}`, + "Run `npx t3 pair` to create a pairing URL.", + "", + ].join("\n"); + +export const resolveHeadlessServeConnectionString = Effect.gen(function* () { const serverConfig = yield* ServerConfig; const httpServer = yield* HttpServer.HttpServer; - const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; - const connectionString = resolveHeadlessConnectionString( + return resolveHeadlessConnectionString( serverConfig.host, resolveListeningPort(httpServer.address, serverConfig.port), ); +}); + +export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const connectionString = yield* resolveHeadlessServeConnectionString; const issued = yield* serverAuth.issueStartupPairingCredential(); return { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ad704d9e1b..e622683026 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -299,10 +299,12 @@ import { } from "./ui/alert-dialog"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction"; +import { APP_STAGE_LABEL, APP_VERSION } from "../branding"; import { buildVersionMismatchDismissalKey, dismissVersionMismatch, isVersionMismatchDismissed, + resolveCompatibilityChannelMismatch, resolveServerConfigVersionMismatch, resolveServerSelfUpdateCapability, serverUpdateGuidance, @@ -1908,6 +1910,14 @@ function ChatViewContent(props: ChatViewProps) { unavailableConnection !== null && (unavailableConnection.phase === "connecting" || unavailableConnection.phase === "reconnecting"); + const compatibilityChannelMismatch = + unavailableConnection?.blockedReason === "unsupported" + ? resolveCompatibilityChannelMismatch({ + clientVersion: APP_VERSION, + clientStageLabel: APP_STAGE_LABEL, + serverVersion: unavailableConnection.serverVersion, + }) + : null; // Reconnecting to a version-skewed server with no update in flight // usually means the server is restarting mid-update and a refresh wiped // the in-memory update state. Fold the reconnect and version banners @@ -1934,6 +1944,51 @@ function ChatViewContent(props: ChatViewProps) { title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`, description: "It may be finishing an update. One moment.", }); + } else if (compatibilityChannelMismatch) { + items.push({ + id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`, + variant: "error", + icon: , + title: "Client and server channels differ", + description: ( +
+

Pick Stable or Nightly for both installations.

+
+ Client + + {compatibilityChannelMismatch.clientVersion} + + + {compatibilityChannelMismatch.clientChannel} + + Server + + {compatibilityChannelMismatch.serverVersion} + + + {compatibilityChannelMismatch.serverChannel} + +
+
+ ), + actions: ( + <> + + + + ), + }); } else { items.push({ id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`, diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index 56d25fa142..3019cb7128 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -295,6 +295,7 @@ const loadPrimaryConnectionRegistration = Effect.fn( label: descriptor.label, httpBaseUrl: resolved.target.httpBaseUrl, wsBaseUrl: resolved.target.wsBaseUrl, + serverVersion: descriptor.serverVersion, }), }); }); diff --git a/apps/web/src/versionSkew.test.ts b/apps/web/src/versionSkew.test.ts index da4ae1e224..2f8a088d8e 100644 --- a/apps/web/src/versionSkew.test.ts +++ b/apps/web/src/versionSkew.test.ts @@ -7,6 +7,7 @@ import { buildVersionMismatchDismissalKey, dismissVersionMismatch, isVersionMismatchDismissed, + resolveCompatibilityChannelMismatch, resolveServerConfigVersionMismatch, resolveServerSelfUpdateCapability, resolveVersionMismatch, @@ -26,6 +27,60 @@ describe("versionSkew", () => { }); }); + it("calls out a stable client connected to a nightly server", () => { + expect( + resolveCompatibilityChannelMismatch({ + clientVersion: "0.0.32", + clientStageLabel: "Latest", + serverVersion: "0.0.33-nightly.20260803.4", + }), + ).toEqual({ + clientVersion: "0.0.32", + clientChannel: "Stable", + serverVersion: "0.0.33-nightly.20260803.4", + serverChannel: "Nightly", + }); + }); + + it("calls out a nightly client connected to a stable server", () => { + expect( + resolveCompatibilityChannelMismatch({ + clientVersion: "0.0.33-nightly.20260803.4", + clientStageLabel: "Nightly", + serverVersion: "0.0.32", + }), + ).toEqual({ + clientVersion: "0.0.33-nightly.20260803.4", + clientChannel: "Nightly", + serverVersion: "0.0.32", + serverChannel: "Stable", + }); + }); + + it("keeps same-channel and development incompatibilities generic", () => { + expect( + resolveCompatibilityChannelMismatch({ + clientVersion: "0.0.32", + clientStageLabel: "Latest", + serverVersion: "0.0.31", + }), + ).toBeNull(); + expect( + resolveCompatibilityChannelMismatch({ + clientVersion: "0.0.32", + clientStageLabel: "Dev", + serverVersion: "0.0.33-nightly.20260803.4", + }), + ).toBeNull(); + expect( + resolveCompatibilityChannelMismatch({ + clientVersion: "0.0.32", + clientStageLabel: "Latest", + serverVersion: "0.0.0", + }), + ).toBeNull(); + }); + it("reads the server version from config descriptors", () => { expect( resolveServerConfigVersionMismatch({ diff --git a/apps/web/src/versionSkew.ts b/apps/web/src/versionSkew.ts index 6cf2a47426..b688044b82 100644 --- a/apps/web/src/versionSkew.ts +++ b/apps/web/src/versionSkew.ts @@ -10,6 +10,15 @@ export interface VersionMismatch { readonly hint: string; } +export type CompatibilityChannel = "Stable" | "Nightly"; + +export interface CompatibilityChannelMismatch { + readonly clientVersion: string; + readonly clientChannel: CompatibilityChannel; + readonly serverVersion: string; + readonly serverChannel: CompatibilityChannel; +} + export const VERSION_MISMATCH_DISMISSALS_STORAGE_KEY = "t3code:version-mismatch-dismissals:v1"; const VersionMismatchDismissalsSchema = Schema.Struct({ @@ -23,6 +32,49 @@ function normalizeVersion(version: string | null | undefined): string | null { return trimmed && trimmed.length > 0 ? trimmed : null; } +function compatibilityChannel( + version: string, + stageLabel?: string | null, +): CompatibilityChannel | null { + const normalizedStage = stageLabel?.trim().toLowerCase(); + if (normalizedStage === "dev" || version === "0.0.0" || /-(?:dev|test)(?:\.|$)/i.test(version)) { + return null; + } + if (normalizedStage === "nightly" || /-nightly(?:\.|$)/i.test(version)) { + return "Nightly"; + } + return "Stable"; +} + +export function resolveCompatibilityChannelMismatch({ + clientVersion, + clientStageLabel, + serverVersion, +}: { + readonly clientVersion: string | null | undefined; + readonly clientStageLabel: string | null | undefined; + readonly serverVersion: string | null | undefined; +}): CompatibilityChannelMismatch | null { + const normalizedClientVersion = normalizeVersion(clientVersion); + const normalizedServerVersion = normalizeVersion(serverVersion); + if (!normalizedClientVersion || !normalizedServerVersion) { + return null; + } + + const clientChannel = compatibilityChannel(normalizedClientVersion, clientStageLabel); + const serverChannel = compatibilityChannel(normalizedServerVersion); + if (!clientChannel || !serverChannel || clientChannel === serverChannel) { + return null; + } + + return { + clientVersion: normalizedClientVersion, + clientChannel, + serverVersion: normalizedServerVersion, + serverChannel, + }; +} + export function resolveVersionMismatch( serverVersion: string | null | undefined, ): VersionMismatch | null { diff --git a/docs/user/background-service.md b/docs/user/background-service.md index 299e3b641f..8dd74a1b2f 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -23,6 +23,21 @@ Update or repair it: npx t3@latest service update ``` +The command installs the same T3 Code version as the CLI you ran. This makes nightly and pinned +installations predictable: + +```sh +npx t3@nightly service update +npx t3@1.2.3 service update +``` + +An older CLI will not replace a newer installed service by accident. If you intentionally need to +downgrade, run the exact older version and pass `--allow-downgrade`: + +```sh +npx t3@1.2.3 service update --allow-downgrade +``` + Stop it and remove it from startup: ```sh diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 4d136658c8..b33f17f8df 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -342,6 +342,10 @@ describe("ManagedEndpointProvider", () => { }); expect(result.runtime.connectorToken).toBe("connector-token"); + expect(result.runtime.origin).toEqual({ + localHttpHost: "127.0.0.1", + localHttpPort: 3773, + }); }).pipe(Effect.provide(layer)); }); @@ -370,6 +374,7 @@ describe("ManagedEndpointProvider", () => { connectorToken: "connector-token", tunnelId: "tunnel-id", tunnelName: expectedManagedTunnelName("env_ABC"), + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, }, }); expect(dnsCalls).toEqual([ diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 9a57887484..ac3db82f82 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -851,6 +851,7 @@ export const make = Effect.gen(function* () { connectorToken, tunnelId: tunnel.id, tunnelName: tunnel.name, + origin: input.origin, }, } satisfies ManagedEndpointProvisioningResult; }), diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 50bcff665a..0adb2bfaf9 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -856,7 +856,9 @@ export const serverApi = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; - return handlers.handle( + const links = yield* EnvironmentLinks.EnvironmentLinks; + const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + const publishHandlers = handlers.handle( "publishAgentActivity", Effect.fn("relay.api.server.publishAgentActivity")( function* (args) { @@ -984,6 +986,61 @@ export const serverApi = HttpApiBuilder.group( mapRelayCommonApiErrors("not_authorized"), ), ); + return publishHandlers.handle( + "reconcileManagedEndpoint", + Effect.fn("relay.api.server.reconcileManagedEndpoint")( + function* ({ params, payload }) { + const principal = yield* RelayEnvironmentPrincipal; + if (principal.environmentId !== params.environmentId) { + return yield* new HttpApiError.Unauthorized({}); + } + const link = yield* links.getForUser({ + userId: payload.cloudUserId, + environmentId: params.environmentId, + }); + if ( + link === null || + link.environmentPublicKey !== principal.environmentPublicKey || + link.endpoint.providerKind !== "cloudflare_tunnel" + ) { + return yield* new HttpApiError.Unauthorized({}); + } + const result = yield* managedEndpointProvider.provision({ + userId: payload.cloudUserId, + environmentId: params.environmentId, + origin: payload.origin, + }); + return { endpointRuntime: result.runtime }; + }, + mapErrorTags({ + ManagedEndpointProvisioningNotConfigured: (_error, traceId) => + new RelayEnvironmentLinkUnavailableError({ + code: "environment_link_unavailable", + reason: "managed_endpoint_not_configured", + traceId, + }), + ManagedEndpointProvisioningFailed: (_error, traceId) => + new RelayEnvironmentLinkUnavailableError({ + code: "environment_link_unavailable", + reason: "managed_endpoint_provisioning_failed", + traceId, + }), + ManagedEndpointOriginNotAllowed: (_error, traceId) => + new RelayEnvironmentLinkProofInvalidError({ + code: "environment_link_proof_invalid", + reason: "origin_not_allowed", + traceId, + }), + ManagedTunnelLimitExceeded: (limitError, traceId) => + new RelayEnvironmentLinkLimitExceededError({ + code: "environment_link_limit_exceeded", + maxTunnels: limitError.maxTunnels, + traceId, + }), + }), + mapRelayCommonApiErrors("not_authorized"), + ), + ); }), ); diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts index 466a5c2dd4..8250999bbe 100644 --- a/packages/client-runtime/src/authorization/layer.test.ts +++ b/packages/client-runtime/src/authorization/layer.test.ts @@ -236,6 +236,7 @@ describe("RemoteEnvironmentAuthorization", () => { const cached = new TokenStore.RemoteDpopAccessToken({ environmentId: ENVIRONMENT_ID, label: DESCRIPTOR.label, + serverVersion: DESCRIPTOR.serverVersion, endpoint: ENDPOINT, accessToken: "cached-access-token", expiresAtEpochMs: Number.MAX_SAFE_INTEGER, @@ -255,6 +256,7 @@ describe("RemoteEnvironmentAuthorization", () => { }).pipe(Effect.provide(harness.layer)); expect(authorized.socketUrl).toContain("wsTicket=cached-ticket"); + expect(authorized.serverVersion).toBe(DESCRIPTOR.serverVersion); expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0); expect(harness.fetch.calls).toHaveLength(1); expect(String(harness.fetch.calls[0]?.[0])).toBe( @@ -291,11 +293,13 @@ describe("RemoteEnvironmentAuthorization", () => { }).pipe(Effect.provide(harness.layer)); expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket"); + expect(authorized.serverVersion).toBe(DESCRIPTOR.serverVersion); expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual( expect.objectContaining({ accessToken: "fresh-access-token", dpopThumbprint: "thumbprint-1", + serverVersion: DESCRIPTOR.serverVersion, }), ); expect(harness.fetch.calls).toHaveLength(3); diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.ts index 410c7a39dc..9fbf712014 100644 --- a/packages/client-runtime/src/authorization/service.ts +++ b/packages/client-runtime/src/authorization/service.ts @@ -33,6 +33,7 @@ export interface RelayEnvironmentAuthorization { export interface AuthorizedRemoteEnvironment { readonly environmentId: EnvironmentId; readonly label: string; + readonly serverVersion?: string; readonly httpBaseUrl: string; readonly socketUrl: string; readonly httpAuthorization: PreparedHttpAuthorization; @@ -138,6 +139,7 @@ export const make = Effect.gen(function* () { return { environmentId: descriptor.environmentId, label: descriptor.label, + serverVersion: descriptor.serverVersion, httpBaseUrl: input.httpBaseUrl, socketUrl, httpAuthorization: { @@ -215,6 +217,9 @@ export const make = Effect.gen(function* () { return { environmentId: cached.value.environmentId, label: cached.value.label, + ...(cached.value.serverVersion === undefined + ? {} + : { serverVersion: cached.value.serverVersion }), httpBaseUrl: cached.value.endpoint.httpBaseUrl, socketUrl: cachedSocket.success, httpAuthorization: { @@ -274,6 +279,7 @@ export const make = Effect.gen(function* () { const token = new TokenStore.RemoteDpopAccessToken({ environmentId: descriptor.environmentId, label: descriptor.label, + serverVersion: descriptor.serverVersion, endpoint: bootstrap.endpoint, accessToken: access.access_token, expiresAtEpochMs: issuedAt + access.expires_in * 1_000, @@ -286,6 +292,7 @@ export const make = Effect.gen(function* () { return { environmentId: descriptor.environmentId, label: descriptor.label, + serverVersion: descriptor.serverVersion, httpBaseUrl: bootstrap.endpoint.httpBaseUrl, socketUrl, httpAuthorization: { diff --git a/packages/client-runtime/src/authorization/tokenStore.ts b/packages/client-runtime/src/authorization/tokenStore.ts index c490a22da1..315a6cd9f8 100644 --- a/packages/client-runtime/src/authorization/tokenStore.ts +++ b/packages/client-runtime/src/authorization/tokenStore.ts @@ -13,6 +13,7 @@ export class RemoteDpopAccessToken extends Schema.Class( )({ environmentId: EnvironmentId, label: Schema.String, + serverVersion: Schema.optionalKey(Schema.String), endpoint: RelayManagedEndpoint, accessToken: Schema.String, expiresAtEpochMs: Schema.Number, diff --git a/packages/client-runtime/src/connection/model.ts b/packages/client-runtime/src/connection/model.ts index fbcb302ed1..355c3cedfd 100644 --- a/packages/client-runtime/src/connection/model.ts +++ b/packages/client-runtime/src/connection/model.ts @@ -12,6 +12,7 @@ export class PrimaryConnectionTarget extends Schema.TaggedClass { }); }); + it("preserves compatibility metadata for blocked connections", () => { + expect( + presentConnectionState( + supervisorState({ + phase: "blocked", + stage: null, + lastFailure: new ConnectionBlockedError({ + reason: "unsupported", + detail: "The client and server could not agree on the RPC protocol.", + serverVersion: "0.0.32-nightly.20260803.4", + }), + }), + ), + ).toEqual({ + phase: "error", + error: "The client and server could not agree on the RPC protocol.", + traceId: null, + blockedReason: "unsupported", + serverVersion: "0.0.32-nightly.20260803.4", + }); + }); + it("gives offline status precedence in global messaging", () => { expect(connectionPhaseMessage("connected", TARGET.label, "offline")).toBe("You are offline"); }); diff --git a/packages/client-runtime/src/connection/presentation.ts b/packages/client-runtime/src/connection/presentation.ts index 168443dece..fc93954f55 100644 --- a/packages/client-runtime/src/connection/presentation.ts +++ b/packages/client-runtime/src/connection/presentation.ts @@ -2,7 +2,7 @@ import type { ServerConfig } from "@t3tools/contracts"; import * as Option from "effect/Option"; import type { ConnectionCatalogEntry } from "./catalog.ts"; -import type { NetworkStatus, SupervisorConnectionState } from "./model.ts"; +import type { ConnectionBlockedReason, NetworkStatus, SupervisorConnectionState } from "./model.ts"; export type EnvironmentConnectionPhase = | "available" @@ -16,6 +16,8 @@ export interface EnvironmentConnectionPresentation { readonly phase: EnvironmentConnectionPhase; readonly error: string | null; readonly traceId: string | null; + readonly blockedReason?: ConnectionBlockedReason; + readonly serverVersion?: string; } export interface EnvironmentPresentation { @@ -46,12 +48,22 @@ export function presentConnectionState( error: state.lastFailure?.message ?? null, traceId: state.lastFailure?.traceId ?? null, }; - case "blocked": + case "blocked": { + const failure = state.lastFailure; return { phase: "error", - error: state.lastFailure?.message ?? null, - traceId: state.lastFailure?.traceId ?? null, + error: failure?.message ?? null, + traceId: failure?.traceId ?? null, + ...(failure?._tag === "ConnectionBlockedError" + ? { + blockedReason: failure.reason, + ...(failure.serverVersion === undefined + ? {} + : { serverVersion: failure.serverVersion }), + } + : {}), }; + } } } diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts index d0375e5555..8adf447d77 100644 --- a/packages/client-runtime/src/connection/resolver.test.ts +++ b/packages/client-runtime/src/connection/resolver.test.ts @@ -210,6 +210,7 @@ describe("ConnectionResolver", () => { label: "Primary", httpBaseUrl: "http://127.0.0.1:3777", wsBaseUrl: "ws://127.0.0.1:3777", + serverVersion: "0.0.32-nightly.20260803.4", }); expect(yield* broker.prepare(catalogEntry(target))).toEqual({ @@ -218,6 +219,7 @@ describe("ConnectionResolver", () => { httpBaseUrl: "http://127.0.0.1:3777", socketUrl: "ws://127.0.0.1:3777/ws", httpAuthorization: null, + serverVersion: "0.0.32-nightly.20260803.4", target, }); }), diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts index c219bde092..06a955e849 100644 --- a/packages/client-runtime/src/connection/resolver.ts +++ b/packages/client-runtime/src/connection/resolver.ts @@ -69,6 +69,7 @@ const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary httpBaseUrl: target.httpBaseUrl, socketUrl: primarySocketUrl(target), httpAuthorization: null, + ...(target.serverVersion === undefined ? {} : { serverVersion: target.serverVersion }), target, } satisfies PreparedConnection; } @@ -133,6 +134,9 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer") httpBaseUrl: authorized.httpBaseUrl, socketUrl: authorized.socketUrl, httpAuthorization: authorized.httpAuthorization, + ...(authorized.serverVersion === undefined + ? {} + : { serverVersion: authorized.serverVersion }), target, } satisfies PreparedConnection; }); @@ -178,6 +182,9 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f httpBaseUrl: authorized.httpBaseUrl, socketUrl: authorized.socketUrl, httpAuthorization: authorized.httpAuthorization, + ...(authorized.serverVersion === undefined + ? {} + : { serverVersion: authorized.serverVersion }), target, } satisfies PreparedConnection; }, @@ -236,6 +243,9 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct httpBaseUrl: authorized.httpBaseUrl, socketUrl: authorized.socketUrl, httpAuthorization: authorized.httpAuthorization, + ...(authorized.serverVersion === undefined + ? {} + : { serverVersion: authorized.serverVersion }), target, } satisfies PreparedConnection; }); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index f7868834b5..fa2beec0a8 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -14,6 +14,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as Socket from "effect/unstable/socket/Socket"; import { + ConnectionBlockedError, ConnectionTransientError, PrimaryConnectionTarget, type PreparedConnection, @@ -360,6 +361,32 @@ describe("RpcSessionFactory", () => { ), ); + it.effect("parks malformed or incompatible RPC responses as unsupported", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const serverVersion = "0.0.32-nightly.20260803.4"; + + const error = yield* Effect.scoped( + Effect.gen(function* () { + const session = yield* factory.connect({ ...PREPARED, serverVersion }); + const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket, {}); + return yield* Fiber.join(readyFiber); + }), + ); + + expect(error).toBeInstanceOf(ConnectionBlockedError); + expect(error).toMatchObject({ + reason: "unsupported", + serverVersion, + message: + "The client and server could not agree on the RPC protocol. Update the older side, then reconnect.", + }); + }), + ); + it.effect("fails readiness when the websocket never opens", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 9625effa40..a7acef7dcd 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -1,9 +1,12 @@ import { type ServerConfig, WS_METHODS } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; import * as RpcClient from "effect/unstable/rpc/RpcClient"; import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"; @@ -44,7 +47,19 @@ type InitialConfigError = Effect.Error< >; type ProbeError = Effect.Error>; -function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionAttemptError { +function unsupportedProtocolError(serverVersion: string | undefined): ConnectionBlockedError { + return new ConnectionBlockedError({ + reason: "unsupported", + detail: + "The client and server could not agree on the RPC protocol. Update the older side, then reconnect.", + ...(serverVersion === undefined ? {} : { serverVersion }), + }); +} + +function mapSessionRpcError( + error: InitialConfigError | ProbeError, + serverVersion: string | undefined, +): ConnectionAttemptError { switch (error._tag) { case "EnvironmentAuthorizationError": return new ConnectionBlockedError({ @@ -58,6 +73,9 @@ function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionA detail: error.message, }); case "RpcClientError": + if (error.reason._tag === "RpcClientDefect") { + return unsupportedProtocolError(serverVersion); + } return new ConnectionTransientErrorClass({ reason: "transport", detail: error.message, @@ -65,6 +83,21 @@ function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionA } } +function mapRpcSchemaDefect( + effect: Effect.Effect, + serverVersion: string | undefined, +): Effect.Effect { + return effect.pipe( + Effect.catchCause((cause): Effect.Effect => { + const defect = Cause.findDefect(cause); + if (Result.isSuccess(defect) && Schema.isSchemaError(defect.success)) { + return Effect.fail(unsupportedProtocolError(serverVersion)); + } + return Effect.failCause(cause); + }), + ); +} + export const make = Effect.gen(function* () { const webSocketConstructor = yield* Socket.WebSocketConstructor; @@ -116,17 +149,24 @@ export const make = Effect.gen(function* () { const client = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfig = yield* Effect.cached( client[WS_METHODS.serverGetConfig]({}).pipe( - Effect.mapError(mapSessionRpcError), + Effect.mapError((error) => mapSessionRpcError(error, connection.serverVersion)), + (effect) => mapRpcSchemaDefect(effect, connection.serverVersion), Effect.withSpan("environment.initialSync"), ), ); const probe = initialConfig.pipe( - Effect.flatMap((config) => - (config.environment.capabilities.connectionProbe === true - ? client[WS_METHODS.serverProbe]({}) - : client[WS_METHODS.serverGetConfig]({}) - ).pipe(Effect.mapError(mapSessionRpcError)), - ), + Effect.flatMap((config) => { + if (config.environment.capabilities.connectionProbe === true) { + return client[WS_METHODS.serverProbe]({}).pipe( + Effect.mapError((error) => mapSessionRpcError(error, connection.serverVersion)), + (effect) => mapRpcSchemaDefect(effect, connection.serverVersion), + ); + } + return client[WS_METHODS.serverGetConfig]({}).pipe( + Effect.mapError((error) => mapSessionRpcError(error, connection.serverVersion)), + (effect) => mapRpcSchemaDefect(effect, connection.serverVersion), + ); + }), Effect.asVoid, Effect.withSpan("clientRuntime.connection.rpcSession.probe"), ); diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 52f7d7d435..4478fc0b97 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -156,9 +156,23 @@ export const RelayManagedEndpointRuntimeConfig = Schema.Struct({ connectorToken: TrimmedNonEmptyString, tunnelId: Schema.optional(TrimmedNonEmptyString), tunnelName: Schema.optional(TrimmedNonEmptyString), + // Optional for compatibility with runtime configs persisted by older servers. + origin: Schema.optional(RelayManagedEndpointOrigin), }); export type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type; +export const RelayManagedEndpointReconcileRequest = Schema.Struct({ + cloudUserId: TrimmedNonEmptyString, + origin: RelayManagedEndpointOrigin, +}); +export type RelayManagedEndpointReconcileRequest = typeof RelayManagedEndpointReconcileRequest.Type; + +export const RelayManagedEndpointReconcileResponse = Schema.Struct({ + endpointRuntime: RelayManagedEndpointRuntimeConfig, +}); +export type RelayManagedEndpointReconcileResponse = + typeof RelayManagedEndpointReconcileResponse.Type; + export const RelayLinkProofRequest = Schema.Struct({ challenge: Schema.String, relayIssuer: Schema.String, @@ -1066,8 +1080,20 @@ export const RelayServerGroup = HttpApiGroup.make("server") error: RelayAgentActivityPublishErrors, }, ).annotate(OpenApi.Summary, "Publish agent activity"), + HttpApiEndpoint.post( + "reconcileManagedEndpoint", + "/v1/environments/:environmentId/managed-endpoint/reconcile", + { + params: Schema.Struct({ + environmentId: EnvironmentId, + }), + payload: RelayManagedEndpointReconcileRequest, + success: RelayManagedEndpointReconcileResponse, + error: RelayEnvironmentLinkErrors, + }, + ).annotate(OpenApi.Summary, "Reconcile a managed endpoint origin"), ) - .annotate(OpenApi.Description, "Environment-authenticated activity publication.") + .annotate(OpenApi.Description, "Environment-authenticated relay operations.") .middleware(RelayEnvironmentAuth); export const RelayApi = HttpApi.make("RelayApi") diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.ts index 24c22454d9..5eb227d0d2 100644 --- a/packages/tailscale/src/tailscale.test.ts +++ b/packages/tailscale/src/tailscale.test.ts @@ -314,6 +314,8 @@ describe("tailscale", () => { // The diagnostic classifies the failure without quoting stderr, so the // key cannot reach a log through it either. assert.equal(error.stderrDiagnostic, "permission-denied"); + assert.include(error.message, "exited with code 1"); + assert.include(error.message, "sudo tailscale set --operator=$USER"); assertCarriesNoSecret(error, "tskey-auth-secret-token-value"); }); }); diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts index 7260a9de11..0680080d27 100644 --- a/packages/tailscale/src/tailscale.ts +++ b/packages/tailscale/src/tailscale.ts @@ -94,6 +94,9 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass