fix: harden remote server lifecycle

This commit is contained in:
Theo Browne committed 2026-08-04 22:10:50 -07:00
1 parent 41ebf22eea
commit 4e4cb07265
33 files changed
+847 -55

No files matched your search

+4 -3
View File
@@ -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)),
);
});
+7 -2
View File
@@ -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<NoRunningServe
) {
override get message(): string {
return [
"No running T3 Code server found.",
"No usable T3 Code server runtime state found.",
...this.checkedStatePaths.map((statePath) => ` 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<Tailscale
{ servePort: Schema.Number, cause: Schema.Defect() },
) {
override get message(): string {
if (Schema.is(TailscaleCommandExitError)(this.cause)) {
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. ${this.cause.message}`;
}
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
}
}
+41 -1
View File
@@ -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, "[email protected] (newer than this [email protected] CLI)");
assert.include(output, "npx [email protected] 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,
}),
);
});
+87 -9
View File
@@ -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>()(
"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* <A, E>(
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 = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
offer: Effect.Effect<
boolean,
BootService.BootServiceError | ServiceDowngradeRefusedError | Terminal.QuitError,
R
>,
) =>
offer.pipe(
Effect.catchTags({
@@ -187,6 +263,8 @@ export const recoverServiceOnboardingOffer = <R>(
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)),
}),
);
+4 -1
View File
@@ -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,
+2
View File
@@ -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 &&
+137 -1
View File
@@ -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<readonly [string, string]> = [
[
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<string, Uint8Array>(
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<HttpClientRequest.HttpClientRequest> = [];
const applied: Array<unknown> = [];
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",
+103 -5
View File
@@ -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;
}
+9 -11
View File
@@ -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,
}),
),
+11 -5
View File
@@ -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<ServerRuntimeStartupError>()(
@@ -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<void>();
@@ -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") {
+12
View File
@@ -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("▄"));
});
+15 -3
View File
@@ -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 {
+55
View File
@@ -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: <TriangleAlertIcon />,
title: "Client and server channels differ",
description: (
<div className="mt-1 min-w-0 space-y-2">
<p>Pick Stable or Nightly for both installations.</p>
<div className="grid grid-cols-[3rem_minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 border-y border-current/15 py-2 text-xs">
<span className="text-muted-foreground">Client</span>
<code className="truncate text-foreground">
{compatibilityChannelMismatch.clientVersion}
</code>
<span className="font-medium text-foreground">
{compatibilityChannelMismatch.clientChannel}
</span>
<span className="text-muted-foreground">Server</span>
<code className="truncate text-foreground">
{compatibilityChannelMismatch.serverVersion}
</code>
<span className="font-medium text-foreground">
{compatibilityChannelMismatch.serverChannel}
</span>
</div>
</div>
),
actions: (
<>
<ServerUpdateAction
environmentId={activeEnvironmentUnavailableState.environmentId}
serverLabel={`${activeEnvironmentUnavailableState.label} server`}
selfUpdate={null}
targetVersion={compatibilityChannelMismatch.clientVersion}
/>
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
} else {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
+1
View File
@@ -295,6 +295,7 @@ const loadPrimaryConnectionRegistration = Effect.fn(
label: descriptor.label,
httpBaseUrl: resolved.target.httpBaseUrl,
wsBaseUrl: resolved.target.wsBaseUrl,
serverVersion: descriptor.serverVersion,
}),
});
});
+55
View File
@@ -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({
+52
View File
@@ -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 {
+15
View File
@@ -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 [email protected] 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 [email protected] service update --allow-downgrade
```
Stop it and remove it from startup:
```sh
@@ -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([
@@ -851,6 +851,7 @@ export const make = Effect.gen(function* () {
connectorToken,
tunnelId: tunnel.id,
tunnelName: tunnel.name,
origin: input.origin,
},
} satisfies ManagedEndpointProvisioningResult;
}),
+58 -1
View File
@@ -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"),
),
);
}),
);
@@ -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);
@@ -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: {
@@ -13,6 +13,7 @@ export class RemoteDpopAccessToken extends Schema.Class<RemoteDpopAccessToken>(
)({
environmentId: EnvironmentId,
label: Schema.String,
serverVersion: Schema.optionalKey(Schema.String),
endpoint: RelayManagedEndpoint,
accessToken: Schema.String,
expiresAtEpochMs: Schema.Number,
@@ -12,6 +12,7 @@ export class PrimaryConnectionTarget extends Schema.TaggedClass<PrimaryConnectio
...ConnectionTargetBase,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
serverVersion: Schema.optionalKey(Schema.String),
},
) {}
@@ -94,6 +95,7 @@ export class ConnectionBlockedError extends Schema.TaggedErrorClass<ConnectionBl
reason: ConnectionBlockedReason,
detail: Schema.String,
traceId: Schema.optionalKey(Schema.String),
serverVersion: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {
@@ -119,6 +121,7 @@ export interface PreparedConnection {
readonly httpBaseUrl: string;
readonly socketUrl: string;
readonly httpAuthorization: PreparedHttpAuthorization | null;
readonly serverVersion?: string;
readonly target: ConnectionTarget;
}
@@ -5,6 +5,7 @@ import * as Option from "effect/Option";
import { BearerConnectionProfile, type ConnectionCatalogEntry } from "./catalog.ts";
import {
BearerConnectionTarget,
ConnectionBlockedError,
ConnectionTransientError,
type SupervisorConnectionState,
} from "./model.ts";
@@ -119,6 +120,28 @@ describe("connection presentation", () => {
});
});
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");
});
@@ -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 }),
}
: {}),
};
}
}
}
@@ -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,
});
}),
@@ -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;
});
@@ -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();
+48 -8
View File
@@ -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<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
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<A, E, R>(
effect: Effect.Effect<A, E, R>,
serverVersion: string | undefined,
): Effect.Effect<A, E | ConnectionBlockedError, R> {
return effect.pipe(
Effect.catchCause((cause): Effect.Effect<never, E | ConnectionBlockedError> => {
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"),
);
+27 -1
View File
@@ -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")
+2
View File
@@ -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");
});
});
+3
View File
@@ -94,6 +94,9 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
},
) {
override get message(): string {
if (this.stderrDiagnostic === "permission-denied" && this.subcommand === "serve") {
return `tailscale serve exited with code ${this.exitCode}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
}
return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
}
}