Skip to content

Commit 1b02641

Browse files
committed
fix(server): prevent accidental service downgrades
1 parent b21d872 commit 1b02641

6 files changed

Lines changed: 482 additions & 71 deletions

File tree

‎apps/server/src/cli/service.test.ts‎

Lines changed: 168 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,26 @@
1-
import { assert, it } from "@effect/vitest";
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { assert, expect, it } from "@effect/vitest";
3+
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
4+
import * as NetService from "@t3tools/shared/Net";
5+
import * as ConfigProvider from "effect/ConfigProvider";
6+
import * as Effect from "effect/Effect";
7+
import * as FileSystem from "effect/FileSystem";
8+
import * as Layer from "effect/Layer";
9+
import * as Terminal from "effect/Terminal";
10+
import { Command } from "effect/unstable/cli";
11+
import { afterEach, vi } from "vite-plus/test";
212

3-
import { formatServiceStatus } from "./service.ts";
13+
import packageJson from "../../package.json" with { type: "json" };
14+
import * as BootService from "../cloud/bootService.ts";
15+
import {
16+
formatServiceStatus,
17+
offerServiceDuringOnboarding,
18+
reconcileService,
19+
recoverServiceOnboardingOffer,
20+
serviceCommand,
21+
} from "./service.ts";
22+
23+
afterEach(() => vi.restoreAllMocks());
424

525
const status = {
626
supported: true,
@@ -35,3 +55,149 @@ it("explains where the service is supported", () => {
3555
"Supported on: Linux with systemd, macOS with launchd",
3656
);
3757
});
58+
59+
it("reports a newer installed service and gives an exact-version repair command", () => {
60+
const output = formatServiceStatus(
61+
{ ...status, current: false, installedVersion: "0.0.32-nightly.1" },
62+
"0.0.31",
63+
);
64+
65+
assert.include(output, "[email protected] (newer than this [email protected] CLI)");
66+
assert.include(output, "npx [email protected] service update");
67+
assert.notInclude(output, "npx t3@latest service update");
68+
});
69+
70+
const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
71+
72+
function makeTestService(serviceStatus: BootService.BootServiceStatus) {
73+
const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
74+
const service = BootService.BootService.of({
75+
status: Effect.succeed(serviceStatus),
76+
install: (options) =>
77+
Effect.sync(() => {
78+
installOptions.push(options);
79+
return {
80+
nodePath: "/test/node",
81+
launcherPath: "/test/service-launcher.mjs",
82+
baseDir: "/test/t3",
83+
unitPath: serviceStatus.unitPath,
84+
logPath: serviceStatus.logPath,
85+
};
86+
}),
87+
uninstall: Effect.succeed(false),
88+
});
89+
return { service, installOptions };
90+
}
91+
92+
it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {
93+
it.effect.each(["install", "update"] as const)(
94+
"%s refuses a downgrade before changing the service",
95+
(command) =>
96+
Effect.gen(function* () {
97+
const fs = yield* FileSystem.FileSystem;
98+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
99+
const { service, installOptions } = makeTestService(newerServiceStatus);
100+
vi.spyOn(BootService, "layer").mockReturnValue(
101+
Layer.succeed(BootService.BootService, service),
102+
);
103+
104+
const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
105+
command,
106+
"--base-dir",
107+
baseDir,
108+
]).pipe(
109+
Effect.provideService(HostProcessEnvironment, {}),
110+
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
111+
Effect.flip,
112+
);
113+
114+
expect(error).toMatchObject({
115+
_tag: "BootServiceDowngradeRefusedError",
116+
installedVersion: "999.0.0",
117+
targetVersion: packageJson.version,
118+
});
119+
expect(installOptions).toEqual([]);
120+
}),
121+
);
122+
123+
it.effect.each(["install", "update"] as const)("%s allows an explicit downgrade", (command) =>
124+
Effect.gen(function* () {
125+
const fs = yield* FileSystem.FileSystem;
126+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
127+
const { service, installOptions } = makeTestService(newerServiceStatus);
128+
vi.spyOn(BootService, "layer").mockReturnValue(
129+
Layer.succeed(BootService.BootService, service),
130+
);
131+
132+
yield* Command.runWith(serviceCommand, { version: packageJson.version })([
133+
command,
134+
"--base-dir",
135+
baseDir,
136+
"--allow-downgrade",
137+
]).pipe(
138+
Effect.provideService(HostProcessEnvironment, {}),
139+
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
140+
);
141+
142+
expect(installOptions).toEqual([{ allowDowngrade: true }]);
143+
}),
144+
);
145+
});
146+
147+
it.effect.each([
148+
{ name: "a new service", state: { ...status, installed: false, current: false } },
149+
{ name: "an older service", state: { ...status, current: false, installedVersion: "0.0.0" } },
150+
{
151+
name: "the same version",
152+
state: { ...status, current: false, installedVersion: packageJson.version },
153+
},
154+
{ name: "an unknown version", state: { ...status, current: false } },
155+
])("installs or repairs $name without an override", ({ state }) =>
156+
Effect.gen(function* () {
157+
const { service, installOptions } = makeTestService(state);
158+
159+
const result = yield* reconcileService().pipe(
160+
Effect.provideService(BootService.BootService, service),
161+
);
162+
163+
expect(result.changed).toBe(true);
164+
expect(installOptions).toEqual([undefined]);
165+
}),
166+
);
167+
168+
it.effect("leaves a newer service unchanged during onboarding without prompting", () =>
169+
Effect.gen(function* () {
170+
const { service, installOptions } = makeTestService(newerServiceStatus);
171+
const terminal = Terminal.make({
172+
columns: Effect.succeed(80),
173+
rows: Effect.succeed(24),
174+
readInput: Effect.die("Onboarding must not prompt to replace a newer service."),
175+
readLine: Effect.die("Onboarding must not prompt to replace a newer service."),
176+
display: () => Effect.die("Onboarding must not prompt to replace a newer service."),
177+
});
178+
179+
const ready = yield* offerServiceDuringOnboarding.pipe(
180+
Effect.provideService(BootService.BootService, service),
181+
Effect.provideService(Terminal.Terminal, terminal),
182+
Effect.provide(NodeServices.layer),
183+
);
184+
185+
expect(ready).toBe(false);
186+
expect(installOptions).toEqual([]);
187+
}),
188+
);
189+
190+
it.effect("keeps onboarding successful when a newer version appears before install", () =>
191+
Effect.gen(function* () {
192+
const ready = yield* recoverServiceOnboardingOffer(
193+
Effect.fail(
194+
new BootService.BootServiceDowngradeRefusedError({
195+
installedVersion: "999.0.0",
196+
targetVersion: packageJson.version,
197+
}),
198+
),
199+
);
200+
201+
expect(ready).toBe(false);
202+
}),
203+
);

‎apps/server/src/cli/service.ts‎

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ import * as Console from "effect/Console";
33
import * as Effect from "effect/Effect";
44
import * as Layer from "effect/Layer";
55
import * as Terminal from "effect/Terminal";
6-
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
6+
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
77

88
import packageJson from "../../package.json" with { type: "json" };
99
import * as BootService from "../cloud/bootService.ts";
10+
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
1011
import type * as ServerConfig from "../config.ts";
1112
import * as ProcessRunner from "../processRunner.ts";
1213
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -30,13 +31,25 @@ export type ServiceReconcileResult =
3031
};
3132

3233
/** Install, update, or repair the service using the CLI version running this command. */
33-
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
34+
export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
35+
readonly allowDowngrade?: boolean;
36+
}) {
3437
const service = yield* BootService.BootService;
3538
const status = yield* service.status;
3639
if (status.installed && status.current) {
3740
return { changed: false, status } satisfies ServiceReconcileResult;
3841
}
39-
const plan = yield* service.install;
42+
if (
43+
status.installedVersion !== undefined &&
44+
options?.allowDowngrade !== true &&
45+
compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
46+
) {
47+
return yield* new BootService.BootServiceDowngradeRefusedError({
48+
installedVersion: status.installedVersion,
49+
targetVersion: packageJson.version,
50+
});
51+
}
52+
const plan = yield* service.install(options);
4053
return {
4154
changed: true,
4255
previouslyInstalled: status.installed,
@@ -54,9 +67,23 @@ export function formatServiceStatus(
5467
if (!status.installed) {
5568
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
5669
}
70+
const installedVersion = status.installedVersion ?? cliVersion;
71+
if (
72+
!status.current &&
73+
status.installedVersion !== undefined &&
74+
compareExactServiceVersions(status.installedVersion, cliVersion) > 0
75+
) {
76+
return [
77+
"T3 Code service",
78+
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
79+
` Unit: ${status.unitPath}`,
80+
` Logs: ${status.logPath}`,
81+
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
82+
].join("\n");
83+
}
5784
return [
5885
"T3 Code service",
59-
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
86+
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
6087
` Unit: ${status.unitPath}`,
6188
` Logs: ${status.logPath}`,
6289
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
@@ -72,13 +99,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
7299
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
73100
});
74101

75-
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
102+
const serviceReconcileFlags = {
103+
...projectLocationFlags,
104+
allowDowngrade: Flag.boolean("allow-downgrade").pipe(
105+
Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
106+
Flag.withDefault(false),
107+
),
108+
};
109+
110+
const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
76111
Command.withDescription("Install T3 Code as a background service for this user."),
77112
Command.withHandler((flags) =>
78113
runServiceCommand(
79114
flags,
80115
Effect.gen(function* () {
81-
const result = yield* reconcileService();
116+
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
82117
if (!result.changed) {
83118
yield* Console.log(
84119
`T3 Code service is already installed with t3@${packageJson.version}.`,
@@ -93,15 +128,15 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe
93128
),
94129
);
95130

96-
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
131+
const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
97132
Command.withDescription(
98133
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
99134
),
100135
Command.withHandler((flags) =>
101136
runServiceCommand(
102137
flags,
103138
Effect.gen(function* () {
104-
const result = yield* reconcileService();
139+
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
105140
if (!result.changed) {
106141
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
107142
return;
@@ -145,14 +180,26 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
145180

146181
export const offerServiceDuringOnboarding = Effect.gen(function* () {
147182
const service = yield* BootService.BootService;
148-
const { supported, installed, current } = yield* service.status;
183+
const status = yield* service.status;
184+
const { supported, installed, current } = status;
149185
if (!supported) {
150186
return false;
151187
}
152188
if (installed && current) {
153189
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
154190
return true;
155191
}
192+
if (
193+
installed &&
194+
status.installedVersion !== undefined &&
195+
compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
196+
) {
197+
yield* Console.log(
198+
`A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
199+
);
200+
// This CLI cannot verify the newer service. Keep the manual fallback available.
201+
return false;
202+
}
156203
// A LaunchAgent starts at login and dies at logout; there is no
157204
// enable-linger equivalent on macOS. Do not promise more than that.
158205
const platform = yield* HostProcessPlatform;
@@ -194,6 +241,8 @@ export const recoverServiceOnboardingOffer = <R>(
194241
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
195242
BootServiceUpdatePendingError: (error) =>
196243
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
244+
BootServiceDowngradeRefusedError: (error) =>
245+
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
197246
}),
198247
);
199248

0 commit comments

Comments
 (0)