Compare commits

...
42 changed files with 3096 additions and 146 deletions

No files matched your search

+45 -3
View File
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { TailscaleCommandExitError } from "@t3tools/tailscale";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -22,6 +23,7 @@ import {
DevServerNotProxiableError,
resolveDirectPairingBaseUrl,
resolveTailscaleLocalTarget,
tailscaleServeFailedError,
} from "./pair.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -50,6 +52,45 @@ describe("pair base URL selection", () => {
});
describe("pair tailscale local target", () => {
it("surfaces the operator fix from safe structural error fields", () => {
const cause = new TailscaleCommandExitError({
executable: "tailscale",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
const failure = tailscaleServeFailedError(443, cause);
expect(failure).toMatchObject({
exitCode: 1,
stderrDiagnostic: "permission-denied",
cause,
});
expect(failure.message).toBe(
"tailscale serve failed with code 1 for HTTPS port 443: access denied. Run `sudo tailscale set --operator=$USER`, then retry.",
);
});
it("keeps Windows permission guidance free of Unix-only commands", () => {
const cause = new TailscaleCommandExitError({
executable: "tailscale.exe",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
const failure = tailscaleServeFailedError(443, cause);
expect(failure).toMatchObject({ executable: "tailscale.exe", cause });
expect(failure.message).toContain("Grant this Windows user permission");
expect(failure.message).not.toContain("sudo");
});
it("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
{ localPort: 5_733 },
@@ -205,7 +246,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 +278,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 +304,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)),
);
});
+38 -8
View File
@@ -20,6 +20,8 @@ import {
DEFAULT_TAILSCALE_SERVE_PORT,
ensureTailscaleServe,
readTailscaleStatus,
TailscaleCommandExitError,
TailscaleStderrDiagnostic,
} from "@t3tools/tailscale";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
@@ -76,9 +78,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");
}
}
@@ -114,13 +117,44 @@ export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesO
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
"TailscaleServeFailedError",
{ servePort: Schema.Number, cause: Schema.Defect() },
{
servePort: Schema.Number,
executable: Schema.optional(Schema.Literals(["tailscale", "tailscale.exe"])),
exitCode: Schema.optional(Schema.Number),
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
cause: Schema.Defect(),
},
) {
override get message(): string {
if (this.stderrDiagnostic === "permission-denied") {
const exitDetail = this.exitCode === undefined ? "" : ` with code ${String(this.exitCode)}`;
if (this.executable === "tailscale.exe") {
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
}
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
}
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.`;
}
}
const isTailscaleCommandExitError = Schema.is(TailscaleCommandExitError);
export function tailscaleServeFailedError(
servePort: number,
cause: unknown,
): TailscaleServeFailedError {
const exitDetails = isTailscaleCommandExitError(cause)
? {
executable: cause.executable,
exitCode: cause.exitCode,
...(cause.stderrDiagnostic === undefined
? {}
: { stderrDiagnostic: cause.stderrDiagnostic }),
}
: {};
return new TailscaleServeFailedError({ servePort, cause, ...exitDetails });
}
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
"ServePortOccupiedError",
{ servePort: Schema.Number },
@@ -409,11 +443,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
localPort: localTarget.localPort,
servePort: input.servePort,
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
}).pipe(
Effect.mapError(
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
),
);
}).pipe(Effect.mapError((cause) => tailscaleServeFailedError(input.servePort, cause)));
notes.push(
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
);
+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,
}),
);
});
+89 -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,18 @@ 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(
`A newer t3@${status.installedVersion} background service is installed; leaving it unchanged.`,
);
// This CLI cannot verify that the newer unit is healthy, so keep the
// manual `serve` fallback visible instead of claiming background readiness.
return false;
}
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
@@ -174,7 +248,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 +265,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)),
}),
);
+20 -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,
@@ -137,6 +140,22 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("reports the installed version across launcher protocol revisions", () =>
Effect.gen(function* () {
const { service, fs, statePath } = yield* makeHarness();
yield* service.install;
yield* fs.writeFileString(
statePath,
`{"protocol":${String(SERVICE_LAUNCHER_PROTOCOL + 1)},"activeVersion":"9.9.9"}`,
);
expect(yield* service.status).toMatchObject({
current: false,
installedVersion: "9.9.9",
});
}),
);
it.effect("restarts an installed service when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness();
+6
View File
@@ -21,6 +21,7 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
serviceStateActiveVersion,
serviceStateHasPendingUpdate,
type ServiceState,
} from "./serviceProtocol.ts";
@@ -130,6 +131,7 @@ export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
readonly current: boolean;
readonly installedVersion?: string;
readonly unitPath: string;
readonly logPath: string;
}
@@ -390,9 +392,13 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
fs.readFileString(statePath).pipe(Effect.option),
]);
const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
const installedVersion = Option.isSome(stateText)
? serviceStateActiveVersion(stateText.value)
: undefined;
return {
supported: true,
installed: true,
...(installedVersion === undefined ? {} : { installedVersion }),
current:
unit === renderBootServiceUnit(plan) &&
launcherExists &&
+149 -9
View File
@@ -19,12 +19,19 @@ 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,
reconcileDesiredCloudLink,
managedEndpointOriginsEqual,
reconcileCloudLinkOnStartup,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
@@ -79,6 +86,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* () {
@@ -172,20 +191,25 @@ describe("relay request tracing", () => {
);
});
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
describe("reconcileCloudLinkOnStartup", () => {
it.effect("restores a desired CLI link before attempting origin repair", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
const error = yield* Effect.flip(reconcileCloudLinkOnStartup("http://127.0.0.1:3774"));
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 connect link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(ServerSecretStore.ServerSecretStore, {
...makeSecretStore(unusedSecretStoreOperation),
get: (name) =>
Effect.succeed(
name === CLOUD_CLI_DESIRED_LINK_SECRET
? Option.some(new TextEncoder().encode("managed"))
: Option.none(),
),
}),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
@@ -222,6 +246,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* reconcileCloudLinkOnStartup("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",
+116 -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,115 @@ 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);
});
/** Restores CLI-desired links first, then repairs origin drift for links that
are owned by web or mobile and therefore have no CLI desired-link marker. */
export const reconcileCloudLinkOnStartup = Effect.fn(
"environment.cloud.reconcileCloudLinkOnStartup",
)(function* (localOrigin: string) {
const dependencies = yield* cloudHttpDependencies;
if (yield* readCliDesiredCloudLink) {
yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);
return true;
}
return yield* reconcileManagedEndpointOriginWith(dependencies, 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 +752,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;
}
+14
View File
@@ -180,6 +180,20 @@ export function serviceStateHasPendingUpdate(value: string): boolean {
}
}
/** Reads the active version across launcher protocol revisions for downgrade protection. */
export function serviceStateActiveVersion(value: string): string | undefined {
try {
const parsed: unknown = JSON.parse(value);
return isRecord(parsed) &&
typeof parsed.activeVersion === "string" &&
isExactServiceVersion(parsed.activeVersion)
? parsed.activeVersion
: undefined;
} catch {
return undefined;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
+6 -6
View File
@@ -83,13 +83,12 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
reconcileDesiredCloudLink,
reconcileCloudLinkOnStartup,
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,12 +578,11 @@ 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(reconcileCloudLinkOnStartup(`http://127.0.0.1:${address.port}`)),
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
@@ -597,9 +595,11 @@ export const makeServerLayer = Layer.unwrap(
Schedule.upTo({ duration: "10 minutes" }),
),
}),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.tap((reconciled) =>
reconciled ? Effect.logInfo("T3 Connect link 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 link 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 {
+67 -1
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,59 @@ 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>
{compatibilityChannelMismatch.newerSide === "server"
? `This client is older. Update it to match the ${compatibilityChannelMismatch.serverChannel} server.`
: compatibilityChannelMismatch.newerSide === "client"
? `The server is older. Update it to match this ${compatibilityChannelMismatch.clientChannel} client.`
: "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: (
<>
{compatibilityChannelMismatch.newerSide === "client" ? (
<ServerUpdateAction
environmentId={activeEnvironmentUnavailableState.environmentId}
serverLabel={`${activeEnvironmentUnavailableState.label} server`}
selfUpdate={null}
targetVersion={compatibilityChannelMismatch.clientVersion}
/>
) : null}
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
} else {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
@@ -1972,7 +2035,10 @@ function ChatViewContent(props: ChatViewProps) {
serverUpdateEnvironmentId &&
!reconnectingThroughVersionSkew &&
(serverUpdateState.status !== "idle" ||
(showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey))
(compatibilityChannelMismatch === null &&
showVersionMismatchBanner &&
versionMismatch &&
versionMismatchDismissKey))
) {
const updateInProgress = serverUpdateState.status === "running";
const updateFailed = serverUpdateState.status === "failed";
+11
View File
@@ -12,6 +12,7 @@ import {
canRetainCachedPlatformRegistrationAfterRefreshFailure,
canReuseCachedPlatformRegistration,
primaryRegistrationToRetainAfterTopologyRead,
primaryRegistrationRefreshAtEpochMs,
provisionDesktopSshEnvironment,
readPrimaryEnvironmentTargetResult,
secondaryRegistrationsToRetainAfterTopologyRead,
@@ -222,4 +223,14 @@ describe("primary topology cache", () => {
}),
).toBeUndefined();
});
it("periodically refreshes primary descriptor metadata", () => {
const discoveredAtEpochMs = 10_000;
const refreshAtEpochMs = primaryRegistrationRefreshAtEpochMs(discoveredAtEpochMs);
const refreshable = { ...cached, refreshAtEpochMs };
expect(refreshAtEpochMs).toBe(40_000);
expect(canReuseCachedPlatformRegistration(refreshable, cached.signature, 39_999)).toBe(true);
expect(canReuseCachedPlatformRegistration(refreshable, cached.signature, 40_000)).toBe(false);
});
});
+19 -3
View File
@@ -295,6 +295,7 @@ const loadPrimaryConnectionRegistration = Effect.fn(
label: descriptor.label,
httpBaseUrl: resolved.target.httpBaseUrl,
wsBaseUrl: resolved.target.wsBaseUrl,
serverVersion: descriptor.serverVersion,
}),
});
});
@@ -358,11 +359,17 @@ const loadSecondaryConnectionRegistration = Effect.fn(
});
// Poll cadence for the desktop bootstrap topology. There is no change event on
// the bridge, so the renderer polls; successful registrations are cached by a
// signature of their endpoint + token until bearer credentials approach expiry.
// the bridge, so the renderer polls. Primary descriptor metadata refreshes
// periodically; secondary registrations refresh before bearer credentials
// expire.
const PLATFORM_POLL_INTERVAL = "3 seconds";
const PRIMARY_REGISTRATION_REFRESH_INTERVAL_MS = 30_000;
const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
export function primaryRegistrationRefreshAtEpochMs(discoveredAtEpochMs: number): number {
return discoveredAtEpochMs + PRIMARY_REGISTRATION_REFRESH_INTERVAL_MS;
}
export function secondaryBearerExpiresAtEpochMs(
issuedAtEpochMs: number,
expiresInSeconds: number,
@@ -505,9 +512,18 @@ const platformConnectionSourceLayer = Layer.effect(
Effect.option,
);
if (Option.isSome(built)) {
const cacheEntry = { signature, registration: built.value };
const cacheEntry = {
signature,
registration: built.value,
refreshAtEpochMs: primaryRegistrationRefreshAtEpochMs(nowEpochMs),
};
next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
registrations.push(built.value);
} else if (cached?.signature === signature) {
// A descriptor refresh should not remove a live primary. Keep the
// old registration and retry on the next topology poll.
next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
registrations.push(cached.registration);
}
}
}
+81
View File
@@ -7,6 +7,7 @@ import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
isVersionMismatchDismissed,
resolveCompatibilityChannelMismatch,
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
resolveVersionMismatch,
@@ -26,6 +27,86 @@ 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",
newerSide: "server",
});
});
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",
newerSide: "client",
});
});
it("uses semver precedence when the channels differ at the same release", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Latest",
serverVersion: "0.0.32-nightly.20260803.4",
}),
).toMatchObject({
newerSide: "client",
});
});
it("does not guess which side is newer when a version cannot be compared", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "not-semver",
clientStageLabel: "Latest",
serverVersion: "0.0.33-nightly.20260803.4",
}),
).toMatchObject({
newerSide: null,
});
});
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({
+67
View File
@@ -1,4 +1,5 @@
import type { EnvironmentId, ServerConfig, ServerSelfUpdateCapability } from "@t3tools/contracts";
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
import * as Schema from "effect/Schema";
import { APP_VERSION } from "./branding";
@@ -10,6 +11,16 @@ 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;
readonly newerSide: "client" | "server" | null;
}
export const VERSION_MISMATCH_DISMISSALS_STORAGE_KEY = "t3code:version-mismatch-dismissals:v1";
const VersionMismatchDismissalsSchema = Schema.Struct({
@@ -23,6 +34,62 @@ 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";
}
function newerCompatibilitySide(
clientVersion: string,
serverVersion: string,
): CompatibilityChannelMismatch["newerSide"] {
if (!parseSemver(clientVersion) || !parseSemver(serverVersion)) {
return null;
}
const comparison = compareSemverVersions(clientVersion, serverVersion);
return comparison === 0 ? null : comparison > 0 ? "client" : "server";
}
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,
newerSide: newerCompatibilitySide(normalizedClientVersion, normalizedServerVersion),
};
}
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 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
@@ -0,0 +1,7 @@
CREATE TABLE "relay_environment_lifecycle_leases" (
"user_id" varchar(191),
"environment_id" varchar(191),
"owner_id" varchar(64) NOT NULL,
"expires_at" varchar(64) NOT NULL,
CONSTRAINT "relay_environment_lifecycle_leases_pkey" PRIMARY KEY("user_id","environment_id")
);
+82
View File
@@ -0,0 +1,82 @@
import { expect, it } from "@effect/vitest";
import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as RelayDb from "./db.ts";
import { relayEnvironmentLifecycleLeases } from "./persistence/schema.ts";
it.effect("leases lifecycle work without changing its transaction boundary", () => {
const calls: Array<string> = [];
let ownerId = "";
let insertedExpiresAt: SQL | undefined;
let updatedExpiresAt: SQL | undefined;
let leaseExpiryCondition: SQL | undefined;
const db = {
$client: {
withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.sync(() => {
calls.push("transaction");
}).pipe(Effect.andThen(effect)),
},
insert: (table: unknown) => {
expect(table).toBe(relayEnvironmentLifecycleLeases);
return {
values: (values: { readonly ownerId: string; readonly expiresAt: SQL }) => {
ownerId = values.ownerId;
insertedExpiresAt = values.expiresAt;
calls.push("acquire");
return {
onConflictDoUpdate: (config: {
readonly set: { readonly expiresAt: SQL };
readonly setWhere: SQL;
}) => {
updatedExpiresAt = config.set.expiresAt;
leaseExpiryCondition = config.setWhere;
return {
returning: () => Effect.succeed([{ ownerId }]),
};
},
};
},
};
},
delete: (table: unknown) => {
expect(table).toBe(relayEnvironmentLifecycleLeases);
return {
where: () =>
Effect.sync(() => {
calls.push("release");
}),
};
},
} as unknown as RelayDb.RelayDb["Service"];
const layer = RelayDb.RelayTransactions.layer.pipe(
Layer.provide(Layer.succeed(RelayDb.RelayDb, db)),
);
return Effect.gen(function* () {
const transactions = yield* RelayDb.RelayTransactions;
const result = yield* Effect.result(
transactions.withEnvironmentLock(
{ userId: "user-1", environmentId: "environment-1" },
Effect.sync(() => {
calls.push("work");
}).pipe(Effect.andThen(Effect.fail("expected failure" as const))),
),
);
expect(Result.isFailure(result)).toBe(true);
expect(ownerId).not.toBe("");
expect(calls).toEqual(["acquire", "work", "release"]);
const dialect = new PgDialect();
expect(dialect.sqlToQuery(insertedExpiresAt!).sql).toContain("now() + interval '30 seconds'");
expect(dialect.sqlToQuery(updatedExpiresAt!).sql).toContain("now() + interval '30 seconds'");
expect(dialect.sqlToQuery(leaseExpiryCondition!)).toEqual({
sql: '"relay_environment_lifecycle_leases"."expires_at"::timestamptz <= now()',
params: [],
});
}).pipe(Effect.provide(layer));
});
+82
View File
@@ -8,8 +8,12 @@ import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import { and, eq, sql } from "drizzle-orm";
import { relayDatabaseMode } from "./dbConfig.ts";
import { relayEnvironmentLifecycleLeases } from "./persistence/schema.ts";
export class RelayDb extends Context.Service<
RelayDb,
@@ -18,10 +22,87 @@ export class RelayDb extends Context.Service<
}
>()("t3code-relay/db/RelayDb") {}
export class EnvironmentLifecycleLeasePersistenceError extends Schema.TaggedErrorClass<EnvironmentLifecycleLeasePersistenceError>()(
"EnvironmentLifecycleLeasePersistenceError",
{
userId: Schema.String,
environmentId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to acquire the lifecycle lease for user '${this.userId}', environment '${this.environmentId}'`;
}
}
function withEnvironmentLock<A, E, R>(
db: RelayDb["Service"],
input: { readonly userId: string; readonly environmentId: string },
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | EnvironmentLifecycleLeasePersistenceError, R> {
return Effect.gen(function* () {
const ownerId = `${yield* Random.nextInt}:${yield* Random.nextInt}`;
const acquire = (): Effect.Effect<void, EnvironmentLifecycleLeasePersistenceError> =>
Effect.suspend(() =>
Effect.gen(function* () {
const expiresAt = sql<string>`to_char((now() + interval '30 seconds') at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
const rows = yield* db
.insert(relayEnvironmentLifecycleLeases)
.values({ ...input, ownerId, expiresAt })
.onConflictDoUpdate({
target: [
relayEnvironmentLifecycleLeases.userId,
relayEnvironmentLifecycleLeases.environmentId,
],
set: { ownerId, expiresAt },
setWhere: sql`${relayEnvironmentLifecycleLeases.expiresAt}::timestamptz <= now()`,
})
.returning({ ownerId: relayEnvironmentLifecycleLeases.ownerId })
.pipe(
Effect.mapError(
(cause) => new EnvironmentLifecycleLeasePersistenceError({ ...input, cause }),
),
);
if (rows[0]?.ownerId !== ownerId) {
yield* Effect.sleep("50 millis");
return yield* acquire();
}
}),
);
const release = db
.delete(relayEnvironmentLifecycleLeases)
.where(
and(
eq(relayEnvironmentLifecycleLeases.userId, input.userId),
eq(relayEnvironmentLifecycleLeases.environmentId, input.environmentId),
eq(relayEnvironmentLifecycleLeases.ownerId, ownerId),
),
)
.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to release relay environment lifecycle lease", {
...input,
ownerId,
error,
}),
),
);
// Public relay requests are capped at nine seconds. A 30-second lease keeps
// a live request fenced while guaranteeing crash recovery without manual
// connection cleanup or provider I/O inside a transaction.
yield* acquire();
return yield* effect.pipe(Effect.ensuring(release));
});
}
export class RelayTransactions extends Context.Service<
RelayTransactions,
{
readonly withTransaction: RelayDb["Service"]["$client"]["withTransaction"];
readonly withEnvironmentLock: <A, E, R>(
input: { readonly userId: string; readonly environmentId: string },
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | EnvironmentLifecycleLeasePersistenceError, R>;
}
>()("t3code-relay/db/RelayTransactions") {
static readonly layer = Layer.effect(
@@ -30,6 +111,7 @@ export class RelayTransactions extends Context.Service<
const db = yield* RelayDb;
return RelayTransactions.of({
withTransaction: db.$client.withTransaction,
withEnvironmentLock: (input, effect) => withEnvironmentLock(db, input, effect),
});
}),
);
@@ -17,6 +17,7 @@ import * as RelayTokens from "../auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as RelayConfiguration from "../Config.ts";
import * as RelayDb from "../db.ts";
import * as EnvironmentLinker from "./EnvironmentLinker.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
@@ -110,6 +111,7 @@ function testLayer(input?: {
readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"];
readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"];
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
readonly withEnvironmentLock?: RelayDb.RelayTransactions["Service"]["withEnvironmentLock"];
}) {
return EnvironmentLinker.layer.pipe(
Layer.provideMerge(RelayTokens.layer),
@@ -149,14 +151,19 @@ function testLayer(input?: {
runtime: { providerKind: "cloudflare_tunnel", connectorToken: "connector-token" },
}),
}),
Layer.succeed(RelayDb.RelayTransactions, {
withTransaction: (effect) => effect,
withEnvironmentLock: input?.withEnvironmentLock ?? ((_input, effect) => effect),
}),
),
),
);
}
describe("EnvironmentLinker", () => {
it.effect("uses verified JWT claims when linking an environment", () => {
it.effect("persists verified JWT claims while holding the environment lock", () => {
let persistedEnvironmentId: string | null = null;
let lockHeld = false;
return Effect.gen(function* () {
const { request, payload } = yield* makeRequest;
const linker = yield* EnvironmentLinker.EnvironmentLinker;
@@ -164,13 +171,26 @@ describe("EnvironmentLinker", () => {
expect(result.environmentId).toBe(payload.environmentId);
expect(result.environmentCredential).toBe("t3env_credential_secret");
expect(persistedEnvironmentId).toBe(payload.environmentId);
expect(lockHeld).toBe(false);
}).pipe(
Effect.provide(
testLayer({
upsert: (input) =>
Effect.sync(() => {
expect(lockHeld).toBe(true);
persistedEnvironmentId = input.proof.environmentId;
}),
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
lockHeld = true;
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
lockHeld = false;
}),
),
),
}),
),
);
@@ -21,6 +21,7 @@ import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
import * as RelayConfiguration from "../Config.ts";
import * as RelayDb from "../db.ts";
export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(
"EnvironmentLinkProofExpired",
@@ -68,6 +69,7 @@ export type EnvironmentLinkError =
| DpopProofs.DpopProofReplayPersistenceError
| EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
| EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
| RelayDb.EnvironmentLifecycleLeasePersistenceError
| ManagedEndpointProvider.ManagedEndpointProviderError;
export class EnvironmentLinker extends Context.Service<
@@ -142,6 +144,7 @@ const make = Effect.gen(function* () {
const proofReplay = yield* DpopProofs.DpopProofReplay;
const relayTokens = yield* RelayTokens.RelayTokens;
const config = yield* RelayConfiguration.RelayConfiguration;
const transactions = yield* RelayDb.RelayTransactions;
return EnvironmentLinker.of({
link: Effect.fn("relay.environment_linker.link")(function* (input) {
@@ -287,58 +290,63 @@ const make = Effect.gen(function* () {
stage: "validate_origin",
});
}
// Downgrading a managed link to publish-only must release the tunnel and
// DNS that were provisioned for it — nothing else cleans them up until a
// full unlink. Best effort: a cleanup failure must not block the link
// itself, and the provider treats an absent allocation as already
// deprovisioned, so retrying on every non-tunnel link is cheap.
if (!input.request.managedTunnelsEnabled) {
yield* managedEndpointProvider
.deprovision({
userId: input.userId,
environmentId: verified.environmentId,
})
.pipe(
Effect.tapError((error) =>
Effect.logWarning("managed endpoint deprovision on publish-only link failed", {
return yield* transactions.withEnvironmentLock(
{ userId: input.userId, environmentId: verified.environmentId },
Effect.gen(function* () {
// Downgrading a managed link to publish-only must release the tunnel and
// DNS that were provisioned for it — nothing else cleans them up until a
// full unlink. Best effort: a cleanup failure must not block the link
// itself, and the provider treats an absent allocation as already
// deprovisioned, so retrying on every non-tunnel link is cheap.
if (!input.request.managedTunnelsEnabled) {
yield* managedEndpointProvider
.deprovision({
userId: input.userId,
environmentId: verified.environmentId,
errorTag: error._tag,
}),
),
Effect.ignore,
);
}
const provisioned = input.request.managedTunnelsEnabled
? yield* managedEndpointProvider.provision({
userId: input.userId,
})
.pipe(
Effect.tapError((error) =>
Effect.logWarning("managed endpoint deprovision on publish-only link failed", {
environmentId: verified.environmentId,
errorTag: error._tag,
}),
),
Effect.ignore,
);
}
const provisioned = input.request.managedTunnelsEnabled
? yield* managedEndpointProvider.provision({
userId: input.userId,
environmentId: verified.environmentId,
origin: verified.origin,
})
: null;
const endpoint = provisioned?.endpoint ?? verified.endpoint;
// The secure-endpoint requirement only matters when the relay advertises
// this endpoint for other devices to reach (managed tunnel). Publish-only
// links are reached out of band (e.g. Tailscale) and their stored endpoint
// is never used for routing, so a nominal endpoint is acceptable.
if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {
return yield* new EnvironmentLinkProofInvalid({
userId: input.userId,
environmentId: verified.environmentId,
reason: "endpoint_not_secure",
stage: "validate_endpoint",
});
}
yield* links.upsert({ ...input, proof: verified, endpoint });
const environmentCredential = yield* credentials.create({
environmentId: verified.environmentId,
origin: verified.origin,
})
: null;
const endpoint = provisioned?.endpoint ?? verified.endpoint;
// The secure-endpoint requirement only matters when the relay advertises
// this endpoint for other devices to reach (managed tunnel). Publish-only
// links are reached out of band (e.g. Tailscale) and their stored endpoint
// is never used for routing, so a nominal endpoint is acceptable.
if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {
return yield* new EnvironmentLinkProofInvalid({
userId: input.userId,
environmentId: verified.environmentId,
reason: "endpoint_not_secure",
stage: "validate_endpoint",
});
}
yield* links.upsert({ ...input, proof: verified, endpoint });
const environmentCredential = yield* credentials.create({
environmentId: verified.environmentId,
environmentPublicKey: verified.environmentPublicKey,
});
return {
environmentId: verified.environmentId,
endpoint,
endpointRuntime: provisioned?.runtime ?? null,
environmentCredential,
};
environmentPublicKey: verified.environmentPublicKey,
});
return {
environmentId: verified.environmentId,
endpoint,
endpointRuntime: provisioned?.runtime ?? null,
environmentCredential,
};
}),
);
}),
});
});
@@ -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;
}),
+70 -1
View File
@@ -23,6 +23,7 @@ import {
relayDocsRedirectRoute,
relayEnvironmentAuthLayer,
relayNotFoundRoute,
reconcileManagedEndpointRecord,
revokeEnvironmentLinkRecord,
traceRelayHttpRequestWith,
unlinkEnvironmentRecord,
@@ -163,17 +164,20 @@ describe("relay environment authentication", () => {
function relayUnlinkTestLayer(input?: {
readonly withTransaction?: RelayDb.RelayTransactions["Service"]["withTransaction"];
readonly withEnvironmentLock?: RelayDb.RelayTransactions["Service"]["withEnvironmentLock"];
readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"];
readonly revokeForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["revokeForUser"];
readonly revokeCredential?: EnvironmentCredentials.EnvironmentCredentials["Service"]["revokeForEnvironmentPublicKey"];
readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"];
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
readonly provision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["provision"];
}) {
return Layer.mergeAll(
Layer.succeed(
RelayDb.RelayTransactions,
RelayDb.RelayTransactions.of({
withTransaction: input?.withTransaction ?? ((effect) => effect),
withEnvironmentLock: input?.withEnvironmentLock ?? ((_input, effect) => effect),
}),
),
Layer.succeed(
@@ -199,7 +203,7 @@ function relayUnlinkTestLayer(input?: {
Layer.succeed(
ManagedEndpointProvider.ManagedEndpointProvider,
ManagedEndpointProvider.ManagedEndpointProvider.of({
provision: () => Effect.die("unused provision"),
provision: input?.provision ?? (() => Effect.die("unused provision")),
prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)),
deprovision: input?.deprovision ?? (() => Effect.void),
release: () => Effect.die("unused release"),
@@ -275,16 +279,29 @@ describe("relay environment unlink", () => {
}),
).toBe(true);
expect(calls).toEqual([
"lock",
"prepare",
"lookup",
"transaction",
"link",
"credential",
"unlock",
"deprovision",
]);
}).pipe(
Effect.provide(
relayUnlinkTestLayer({
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
calls.push("lock");
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
calls.push("unlock");
}),
),
),
withTransaction: (effect) => {
calls.push("transaction");
return effect;
@@ -395,6 +412,58 @@ describe("relay environment unlink", () => {
});
});
describe("managed endpoint reconciliation", () => {
it.effect("holds the environment lock across authorization and provisioning", () => {
const calls: Array<string> = [];
return Effect.gen(function* () {
const result = yield* reconcileManagedEndpointRecord({
userId: "user-1",
environmentId: "environment-1",
environmentPublicKey: "public-key",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
expect(result.runtime.connectorToken).toBe("connector-token");
expect(calls).toEqual(["lock", "lookup", "provision", "unlock"]);
}).pipe(
Effect.provide(
relayUnlinkTestLayer({
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
calls.push("lock");
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
calls.push("unlock");
}),
),
),
getForUser: () =>
Effect.sync(() => {
calls.push("lookup");
return linkedEnvironmentRecord;
}),
provision: ({ origin }) =>
Effect.sync(() => {
calls.push("provision");
return {
endpoint: linkedEnvironmentRecord.endpoint,
runtime: {
providerKind: "cloudflare_tunnel" as const,
connectorToken: "connector-token",
tunnelId: "tunnel-1",
tunnelName: "environment-1-tunnel",
origin,
},
};
}),
}),
),
);
});
});
describe("relay request tracing", () => {
it.effect(
"does not parent endpoint spans to an ambient parent captured while building handlers",
+96 -24
View File
@@ -47,6 +47,7 @@ import {
RelayEnvironmentPrincipal,
type RelayEnvironmentConnectRequest,
type RelayDpopAccessTokenScope,
type RelayManagedEndpointOrigin,
RelayInternalError,
} from "@t3tools/contracts/relay";
import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
@@ -432,38 +433,63 @@ export const revokeEnvironmentLinkRecord = Effect.fn(
export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnvironmentRecord")(
function* (input: { readonly userId: string; readonly environmentId: string }) {
const transactions = yield* RelayDb.RelayTransactions;
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision({
userId: input.userId,
environmentId: input.environmentId,
});
const link = yield* links.getForUser({
userId: input.userId,
environmentId: input.environmentId,
});
const unlinked =
link === null
? false
: yield* revokeEnvironmentLinkRecord({
userId: input.userId,
environmentId: link.environmentId,
environmentPublicKey: link.environmentPublicKey,
});
// External teardown cannot share the SQL transaction. Run it only after
// revocation commits so a database failure leaves a fully usable active
// link. Still run teardown when the link is already revoked, allowing a
// retry to finish cleanup after an earlier Cloudflare failure.
const { deprovisionTarget, unlinked } = yield* transactions.withEnvironmentLock(
input,
Effect.gen(function* () {
const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision(input);
const link = yield* links.getForUser(input);
const unlinked =
link === null
? false
: yield* revokeEnvironmentLinkRecord({
userId: input.userId,
environmentId: link.environmentId,
environmentPublicKey: link.environmentPublicKey,
});
return { deprovisionTarget, unlinked };
}),
);
// External teardown runs after revocation commits and releases the lock.
// Its captured allocation generation keeps a concurrent relink safe while
// still allowing a retry to finish an earlier incomplete cleanup.
yield* managedEndpointProvider.deprovision({
userId: input.userId,
environmentId: input.environmentId,
...input,
target: deprovisionTarget,
});
return unlinked;
},
);
export const reconcileManagedEndpointRecord = Effect.fn(
"relay.api.server.reconcileManagedEndpointRecord",
)(function* (input: {
readonly userId: string;
readonly environmentId: string;
readonly environmentPublicKey: string;
readonly origin: RelayManagedEndpointOrigin;
}) {
const transactions = yield* RelayDb.RelayTransactions;
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
return yield* transactions.withEnvironmentLock(
input,
Effect.gen(function* () {
const link = yield* links.getForUser(input);
if (
link === null ||
link.environmentPublicKey !== input.environmentPublicKey ||
link.endpoint.providerKind !== "cloudflare_tunnel"
) {
return yield* new HttpApiError.Unauthorized({});
}
return yield* managedEndpointProvider.provision(input);
}),
);
});
export const mobileApi = HttpApiBuilder.group(
RelayApi,
"mobile",
@@ -856,7 +882,7 @@ export const serverApi = HttpApiBuilder.group(
Effect.fnUntraced(function* (handlers) {
const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;
return handlers.handle(
const publishHandlers = handlers.handle(
"publishAgentActivity",
Effect.fn("relay.api.server.publishAgentActivity")(
function* (args) {
@@ -984,6 +1010,51 @@ 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 result = yield* reconcileManagedEndpointRecord({
userId: payload.cloudUserId,
environmentId: params.environmentId,
environmentPublicKey: principal.environmentPublicKey,
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"),
),
);
}),
);
@@ -1025,6 +1096,7 @@ const RelayCommonPersistenceError = Schema.Union([
AgentActivityRows.AgentActivityRowListPersistenceError,
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
RelayDb.EnvironmentLifecycleLeasePersistenceError,
]);
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
+11
View File
@@ -83,6 +83,17 @@ export const relayEnvironmentLinks = pgTable(
],
);
export const relayEnvironmentLifecycleLeases = pgTable(
"relay_environment_lifecycle_leases",
{
userId: varchar("user_id", { length: 191 }).notNull(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
ownerId: varchar("owner_id", { length: 64 }).notNull(),
expiresAt: varchar("expires_at", { length: 64 }).notNull(),
},
(table) => [primaryKey({ columns: [table.userId, table.environmentId] })],
);
export const relayManagedEndpointAllocations = pgTable(
"relay_managed_endpoint_allocations",
{
@@ -231,8 +231,9 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
it.effect("reuses a valid persisted environment token without contacting the relay", () =>
it.effect("refreshes the descriptor while reusing a valid environment token", () =>
Effect.gen(function* () {
const refreshedServerVersion = "0.0.1";
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
label: DESCRIPTOR.label,
@@ -243,7 +244,10 @@ describe("RemoteEnvironmentAuthorization", () => {
});
const harness = yield* makeHarness({
initialToken: cached,
responses: [websocketTicket("cached-ticket")],
responses: [
websocketTicket("cached-ticket"),
Response.json({ ...DESCRIPTOR, serverVersion: refreshedServerVersion }),
],
});
const authorized = yield* Effect.gen(function* () {
@@ -255,11 +259,15 @@ describe("RemoteEnvironmentAuthorization", () => {
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
expect(authorized.serverVersion).toBe(refreshedServerVersion);
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
expect(harness.fetch.calls).toHaveLength(1);
expect(harness.fetch.calls).toHaveLength(2);
expect(String(harness.fetch.calls[0]?.[0])).toBe(
"https://environment.example.test/api/auth/websocket-ticket",
);
expect(String(harness.fetch.calls[1]?.[0])).toBe(
"https://environment.example.test/.well-known/t3/environment",
);
}),
);
@@ -291,6 +299,7 @@ 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({
@@ -380,6 +389,44 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
it.effect("keeps a valid cached token when descriptor refresh fails transiently", () =>
Effect.gen(function* () {
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "cached-access-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
dpopThumbprint: "thumbprint-1",
});
const harness = yield* makeHarness({
initialToken: cached,
responses: [
websocketTicket("cached-ticket"),
new Response("endpoint unavailable", { status: 503 }),
],
});
const authorized = yield* Effect.gen(function* () {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
expect(authorized.serverVersion).toBeUndefined();
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
expect.objectContaining({
accessToken: "cached-access-token",
}),
);
expect(harness.fetch.calls).toHaveLength(2);
}),
);
it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
@@ -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: {
@@ -212,6 +214,33 @@ export const make = Effect.gen(function* () {
CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
).pipe(Effect.result);
if (Result.isSuccess(cachedSocket)) {
const cachedDescriptor = yield* fetchDescriptor(cached.value.endpoint.httpBaseUrl).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.result,
);
if (Result.isSuccess(cachedDescriptor)) {
const descriptor = cachedDescriptor.success;
if (descriptor.environmentId !== input.expectedEnvironmentId) {
return yield* environmentMismatchError({
expected: input.expectedEnvironmentId,
actual: descriptor.environmentId,
});
}
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
serverVersion: descriptor.serverVersion,
httpBaseUrl: cached.value.endpoint.httpBaseUrl,
socketUrl: cachedSocket.success,
httpAuthorization: {
_tag: "Dpop" as const,
accessToken: cached.value.accessToken,
},
};
}
if (cachedDescriptor.failure._tag === "ConnectionBlockedError") {
return yield* cachedDescriptor.failure;
}
return {
environmentId: cached.value.environmentId,
label: cached.value.label,
@@ -222,8 +251,7 @@ export const make = Effect.gen(function* () {
accessToken: cached.value.accessToken,
},
};
}
if (cachedSocket.failure._tag === "ConnectionBlockedError") {
} else if (cachedSocket.failure._tag === "ConnectionBlockedError") {
return yield* mapDpopSocketError(cachedSocket.failure);
}
yield* tokenStore
@@ -286,6 +314,7 @@ export const make = Effect.gen(function* () {
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
serverVersion: descriptor.serverVersion,
httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
socketUrl,
httpAuthorization: {
@@ -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,53 @@ 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("treats malformed RPC transport messages as retryable", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const error = yield* Effect.scoped(
Effect.gen(function* () {
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready));
const socket = yield* awaitSocket(sockets);
socket.open();
yield* awaitRequest(socket);
socket.serverMessage("not-json");
return yield* Fiber.join(readyFiber);
}),
);
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error).toMatchObject({ reason: "transport" });
}),
);
it.effect("fails readiness when the websocket never opens", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
+40 -6
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,6 +47,15 @@ type InitialConfigError = Effect.Error<
>;
type ProbeError = Effect.Error<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
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): ConnectionAttemptError {
switch (error._tag) {
case "EnvironmentAuthorizationError":
@@ -65,6 +77,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;
@@ -117,16 +144,23 @@ export const make = Effect.gen(function* () {
const initialConfig = yield* Effect.cached(
client[WS_METHODS.serverGetConfig]({}).pipe(
Effect.mapError(mapSessionRpcError),
(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(mapSessionRpcError),
(effect) => mapRpcSchemaDefect(effect, connection.serverVersion),
);
}
return client[WS_METHODS.serverGetConfig]({}).pipe(
Effect.mapError(mapSessionRpcError),
(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")
+16
View File
@@ -314,10 +314,26 @@ 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");
});
});
it("does not suggest a Unix permission command on Windows", () => {
const error = new TailscaleCommandExitError({
executable: "tailscale.exe",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
assert.include(error.message, "Grant this Windows user permission");
assert.notInclude(error.message, "sudo");
});
it.effect("disables tailscale serve through the process spawner service", () => {
const commands: {
readonly command: string;
+6
View File
@@ -94,6 +94,12 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
},
) {
override get message(): string {
if (this.stderrDiagnostic === "permission-denied" && this.subcommand === "serve") {
if (this.executable === "tailscale.exe") {
return `tailscale serve exited with code ${this.exitCode}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
}
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}.`;
}
}