Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/fork-seams.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@
"apps/server/src/binCli.ts": 2,
"apps/server/src/binMain.ts": 6,
"apps/server/src/cli/config.ts": 2,
"apps/server/src/cli/server.ts": 37,
"apps/server/src/cli/server.ts": 17,
"apps/server/src/cloud/selfUpdate.ts": 4,
"apps/server/src/config.ts": 2,
"apps/server/src/mcp/McpHttpServer.ts": 10,
Expand Down Expand Up @@ -271,8 +271,8 @@
"gone": 1
},
"apps/server/src/cli/server.ts": {
"lines": 4,
"gone": 4
"lines": 3,
"gone": 3
},
"apps/server/src/mcp/McpHttpServer.ts": {
"lines": 1,
Expand Down
129 changes: 129 additions & 0 deletions apps/server/src/cli/forkHoldWork.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// @effect-diagnostics nodeBuiltinImport:off - the account's home comes from the passwd entry.
/**
* Fork (go-live kit): the refusals `t3 serve --hold-work` runs before config resolution, which
* claims a port and creates directories. cli/server.ts calls `refuseHoldWork` once.
*/
import * as NodeOS from "node:os";

import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as CliError from "effect/cli/CliError";

import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import { resolveBaseDir } from "../os-jank.ts";

/** The background service must never run held: its threads would silently stop working. A
* launcher context that cannot be read refuses too. */
export const refuseHoldWorkForBootService = resolveServiceLauncherMode().pipe(
Effect.map(({ managed }) => managed),
Effect.orElseSucceed(() => true),
Effect.flatMap((managed) =>
managed
? Effect.fail(
new CliError.UserError({
cause: "hold-work",
userMessage:
"--hold-work is refused for the background service. Run `t3 serve --hold-work --base-dir <copy>` by hand on a copy of a T3 home.",
}),
)
: Effect.void,
),
);

const defaultHomeRefusal = (detail: string) =>
new CliError.UserError({
cause: "hold-work",
userMessage: [
`--hold-work is refused ${detail}.`,
"A held boot writes hold-work-copy.txt in its home, and every later boot of that home then holds T3 Connect (no tunnel, no agent activity) until someone deletes the file: on the live home that ends remote access.",
"Run `t3 serve --hold-work --base-dir <copy>` on a copy of a T3 home. Nothing was started or written.",
].join("\n"),
});

/** The account's home from its passwd entry, which ignores `$HOME` (null when there is none). */
export const AccountHomeDirectory = Context.Reference<string | null>(
"t3/cli/forkHoldWork/AccountHomeDirectory",
{
defaultValue: () => {
try {
return NodeOS.userInfo().homedir || null;
} catch {
return null;
}
},
},
);

/**
* The real path of `path`, also when it does not exist yet: the deepest folder that exists is
* resolved and the rest appended, so a symlinked parent cannot hide a home not made yet.
*/
const realPathOrParent = Effect.fn("cli.forkHoldWork.realPathOrParent")(function* (path: string) {
const fs = yield* FileSystem.FileSystem;
const { basename, dirname, join } = yield* Path.Path;
const rest: Array<string> = [];
let current = path;
for (;;) {
const real = yield* fs.realPath(current).pipe(Effect.option);
if (Option.isSome(real)) return join(real.value, ...rest.toReversed());
const parent = dirname(current);
if (parent === current) return path;
rest.push(basename(current));
current = parent;
}
});

/** The same folder by identity (device and inode), for spellings and mounts a path cannot show. */
const sameFolder = Effect.fn("cli.forkHoldWork.sameFolder")(function* (a: string, b: string) {
const fs = yield* FileSystem.FileSystem;
const both = yield* Effect.all([fs.stat(a), fs.stat(b)]).pipe(Effect.option);
if (Option.isNone(both)) return false;
const [left, right] = both.value;
return (
left.dev === right.dev &&
Option.isSome(left.ino) &&
Option.isSome(right.ino) &&
left.ino.value === right.ino.value
);
});

/**
* `--hold-work` marks its home as a copy (cloud/holdWorkConnect.ts): it needs `--base-dir` (not
* just `T3CODE_HOME`) and never a default home, `$HOME/.t3` or the account's own `.t3`, since a
* scratch `$HOME` does not move the live one.
*/
export const refuseHoldWorkOnDefaultHome = Effect.fn("cli.refuseHoldWorkOnDefaultHome")(function* (
baseDirFlag: Option.Option<string>,
) {
const named = baseDirFlag.pipe(Option.filter((value) => value.trim().length > 0));
if (Option.isNone(named)) {
return yield* defaultHomeRefusal("without --base-dir: it would run on this machine's T3 home");
}
const { join } = yield* Path.Path;
const home = yield* resolveBaseDir(named.value);
const accountHome = yield* AccountHomeDirectory;
const defaultHomes = [
yield* resolveBaseDir(undefined),
...(accountHome === null ? [] : [join(accountHome, ".t3")]),
];
const realHome = yield* realPathOrParent(home);
for (const defaultHome of defaultHomes) {
// A symlink to the default home is the default home: compare real paths, then identities.
if (
home === defaultHome ||
realHome === (yield* realPathOrParent(defaultHome)) ||
(yield* sameFolder(home, defaultHome))
) {
return yield* defaultHomeRefusal(
`on the default T3 home (${defaultHome}): it is the live one on most machines`,
);
}
}
});

/** Every refusal of `serve --hold-work`, before anything is started or written. */
export const refuseHoldWork = (baseDirFlag: Option.Option<string>) =>
refuseHoldWorkForBootService.pipe(Effect.andThen(refuseHoldWorkOnDefaultHome(baseDirFlag)));
168 changes: 165 additions & 3 deletions apps/server/src/cli/server.holdWork.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths.
// Fork (go-live kit): `serve --hold-work` is refused for the background service.
// Fork (go-live kit): `serve --hold-work` is refused for the background service and on the default
// home (it would mark the live home as a copy).
import * as NodeOS from "node:os";
import * as NodePath from "node:path";

import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { Command } from "effect/cli";

import packageJson from "../../package.json" with { type: "json" };
Expand All @@ -20,7 +23,11 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
} from "../cloud/serviceProtocol.ts";
import { cli } from "../binCli.ts";
import { refuseHoldWorkForBootService } from "./server.ts";
import {
AccountHomeDirectory,
refuseHoldWorkForBootService,
refuseHoldWorkOnDefaultHome,
} from "./forkHoldWork.ts";

const launcher = (input: { readonly connected: boolean; readonly context?: string }) => ({
host: {
Expand Down Expand Up @@ -94,3 +101,158 @@ it.effect("parses serve --hold-work and refuses it under the launcher before cre
assert.isFalse(yield* fs.exists(baseDir));
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
);

describe("serve --hold-work needs a home named with --base-dir, never the default one", () => {
/** A temp folder stands in for the user's home folder, so `~/.t3` is `<root>/.t3`. */
const onHome = <A, E, R>(body: (root: string) => Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-hold-work-home-" });
return yield* body(root).pipe(Effect.provideService(HostProcess.HomeDirectory, root));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));

const refusal = (flag: Option.Option<string>) =>
refuseHoldWorkOnDefaultHome(flag).pipe(
Effect.flip,
Effect.map((error) => error.message),
);

it.effect("refuses no --base-dir, or a blank one, and says what to run", () =>
onHome(() =>
Effect.gen(function* () {
for (const flag of [Option.none(), Option.some(""), Option.some(" ")]) {
const message = yield* refusal(flag);
expect(message).toContain("--hold-work is refused without --base-dir");
expect(message).toContain("--base-dir <copy>");
expect(message).toContain("hold-work-copy.txt");
}
}),
),
);

it.effect("refuses the default home however it is spelled, or a symlink to it", () =>
onHome((root) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const defaultHome = NodePath.join(root, ".t3");
yield* fs.makeDirectory(defaultHome);
yield* fs.symlink(defaultHome, NodePath.join(root, "live-link"));
for (const flag of [
defaultHome,
`${defaultHome}/`,
"~/.t3",
NodePath.join(root, "x", "..", ".t3"),
NodePath.join(root, "live-link"),
]) {
const message = yield* refusal(Option.some(flag));
expect(message).toContain(
`--hold-work is refused on the default T3 home (${defaultHome})`,
);
}
}),
),
);

it.effect("refuses the account's own T3 home when $HOME points somewhere else", () =>
onHome(() =>
Effect.gen(function* () {
// `HOME=/scratch t3 serve --hold-work --base-dir /home/<user>/.t3`: $HOME moved, the live
// home did not. The account's home comes from the passwd entry, which ignores $HOME.
const accountHome = NodePath.join(NodeOS.userInfo().homedir, ".t3");
const message = yield* refusal(Option.some(accountHome));
expect(message).toContain(`--hold-work is refused on the default T3 home (${accountHome})`);
}),
),
);

it.effect("refuses the account home's .t3, made or not, and nothing beside it", () =>
onHome((root) =>
Effect.gen(function* () {
const accountHome = NodePath.join(root, "account");
const live = NodePath.join(accountHome, ".t3");
const message = yield* refusal(Option.some(live)).pipe(
Effect.provideService(AccountHomeDirectory, accountHome),
);
expect(message).toContain(`--hold-work is refused on the default T3 home (${live})`);
yield* refuseHoldWorkOnDefaultHome(Option.some(`${live}-copy`)).pipe(
Effect.provideService(AccountHomeDirectory, accountHome),
);
}),
),
);

it.effect("refuses the same folder under another spelling the path check cannot see", () =>
onHome((root) =>
Effect.gen(function* () {
// A case-insensitive disk (or a second mount): `<root>/.T3` is `<root>/.t3`, and realPath
// keeps the spelling it was given. Only the folder's identity (dev+ino) shows it.
const fs = yield* FileSystem.FileSystem;
const defaultHome = NodePath.join(root, ".t3");
yield* fs.makeDirectory(defaultHome);
const upper = NodePath.join(root, ".T3");
const fold = (path: string) => (path === upper ? defaultHome : path);
const caseInsensitive: FileSystem.FileSystem = {
...fs,
exists: (path) => fs.exists(fold(path)),
stat: (path) => fs.stat(fold(path)),
realPath: (path) =>
fs.realPath(fold(path)).pipe(Effect.as(path === upper ? upper : path)),
};
const message = yield* refusal(Option.some(upper)).pipe(
Effect.provideService(FileSystem.FileSystem, caseInsensitive),
);
expect(message).toContain(`--hold-work is refused on the default T3 home (${defaultHome})`);
}),
),
);

it.effect("refuses a default home not made yet, reached through a symlinked parent", () =>
onHome((root) =>
Effect.gen(function* () {
// No `<root>/.t3` yet: the server would create it through the alias and mark it.
const fs = yield* FileSystem.FileSystem;
yield* fs.symlink(root, NodePath.join(root, "alias"));
const message = yield* refusal(Option.some(NodePath.join(root, "alias", ".t3")));
expect(message).toContain("--hold-work is refused on the default T3 home");
assert.isFalse(yield* fs.exists(NodePath.join(root, ".t3")));
}),
),
);

it.effect("lets a named copy through, made or not", () =>
onHome((root) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* refuseHoldWorkOnDefaultHome(Option.some(NodePath.join(root, "copy", "home")));
yield* fs.makeDirectory(NodePath.join(root, "made"));
yield* refuseHoldWorkOnDefaultHome(Option.some(NodePath.join(root, "made")));
// Beside the default home, not the default home itself.
yield* refuseHoldWorkOnDefaultHome(Option.some("~/.t3-copy"));
}),
),
);

it.effect("serve --hold-work with no --base-dir is refused before the default home is made", () =>
onHome((root) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { host, env } = launcher({ connected: false });
const exit = yield* Command.runWith(cli, { version: "0.0.0" })([
"serve",
"--hold-work",
]).pipe(
Effect.provideService(ServiceLauncherHostProcess, host),
Effect.provideService(HostProcess.Environment, env),
Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer)),
Effect.exit,
);
assert.isTrue(Exit.isFailure(exit));
assert.include(
String(Exit.isFailure(exit) ? exit.cause : ""),
"--hold-work is refused without --base-dir",
);
assert.isFalse(yield* fs.exists(NodePath.join(root, ".t3")));
}).pipe(Effect.provide(NodeCrypto.layer)),
),
);
});
Loading
Loading