fix(server): preserve startup reconciliation safeguards

This commit is contained in:
Theo Browne committed 2026-08-04 22:10:50 -07:00
1 parent 4e4cb07265
commit e71933771d
5 files changed
+88 -25

No files matched your search

+24
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,28 @@ 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("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
{ localPort: 5_733 },
+28 -8
View File
@@ -21,6 +21,7 @@ import {
ensureTailscaleServe,
readTailscaleStatus,
TailscaleCommandExitError,
TailscaleStderrDiagnostic,
} from "@t3tools/tailscale";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
@@ -116,16 +117,39 @@ export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesO
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
"TailscaleServeFailedError",
{ servePort: Schema.Number, cause: Schema.Defect() },
{
servePort: Schema.Number,
exitCode: Schema.optional(Schema.Number),
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
cause: Schema.Defect(),
},
) {
override get message(): string {
if (Schema.is(TailscaleCommandExitError)(this.cause)) {
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. ${this.cause.message}`;
if (this.stderrDiagnostic === "permission-denied") {
const exitDetail = this.exitCode === undefined ? "" : ` with code ${String(this.exitCode)}`;
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)
? {
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 },
@@ -414,11 +438,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\`.`,
);
+14 -10
View File
@@ -31,8 +31,7 @@ import {
isSupportedLinkProviderKind,
linkProofScopes,
managedEndpointOriginsEqual,
reconcileDesiredCloudLink,
reconcileManagedEndpointOrigin,
reconcileCloudLinkOnStartup,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
@@ -192,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({
@@ -273,7 +277,7 @@ describe("reconcileManagedEndpointOrigin", () => {
const applied: Array<unknown> = [];
return Effect.gen(function* () {
expect(yield* reconcileManagedEndpointOrigin("http://127.0.0.1:4555")).toBe(true);
expect(yield* reconcileCloudLinkOnStartup("http://127.0.0.1:4555")).toBe(true);
expect(requests).toHaveLength(1);
expect(requests[0]?.url).toBe(
+13
View File
@@ -725,6 +725,19 @@ export const reconcileManagedEndpointOrigin = Effect.fn(
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
+9 -7
View File
@@ -83,7 +83,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
reconcileManagedEndpointOrigin,
reconcileCloudLinkOnStartup,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
@@ -582,22 +582,24 @@ export const makeServerLayer = Layer.unwrap(
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileManagedEndpointOrigin(`http://127.0.0.1:${address.port}`)),
Effect.andThen(reconcileCloudLinkOnStartup(`http://127.0.0.1:${address.port}`)),
Effect.retry({
while: (error) => error._tag !== "EnvironmentHttpBadRequestError",
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
error._tag !== "EnvironmentHttpUnauthorizedError" &&
error._tag !== "EnvironmentHttpConflictError",
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.upTo({ duration: "10 minutes" }),
),
}),
Effect.tap((reconciled) =>
reconciled
? Effect.logInfo("T3 Connect managed endpoint origin reconciled on startup")
: Effect.void,
reconciled ? Effect.logInfo("T3 Connect link reconciled on startup") : Effect.void,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect managed endpoint on startup", {
Effect.logWarning("Failed to reconcile T3 Connect link on startup", {
cause,
}),
),