Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as Console from "effect/Console";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
9import * as CliError from "effect/cli/CliError";
10
11import packageJson from "../../package.json" with { type: "json" };
12import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
13import * as BootService from "../cloud/bootService.ts";
14import * as CliState from "../cloud/CliState.ts";
15import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/config.ts";
16import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
17import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
18import * as ServerConfig from "../config.ts";
19import * as ManagedLimits from "../policy/managedLimits.ts";
20import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
21import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
22import {
23 connectSubcommands,
24 disconnectCloud,
25 headlessFlag,
26 linkEnvironmentForConnect,
27 requireConnectAllowed,
28 runCloudCommand,
29 waitForReachability,
30} from "./connect.ts";
31import { resolveHostCliCommand } from "./invocation.ts";
32import * as CliService from "./service.ts";
33
34type Route = "connect" | "lan";
35type Routes = Readonly<Record<Route, boolean>>;
36
37/** How other devices reach this machine now. */
38interface Setup {
39 readonly service: BootService.BootServiceStatus;
40 /** Null in builds without T3 Connect. Off when T3 Connect revoked the link. */
41 readonly connect: boolean | null;
42 /** T3 Connect revoked the link; `t3 connect` links again. */
43 readonly connectRevoked: boolean;
44 readonly lan: boolean;
45 /** An installed service with no T3CODE_LAN keeps the old default: on. */
46 readonly lanFromOldDefault: boolean;
47 readonly host: string | undefined;
48}
49
50/**
51 * T3 Connect is on when this CLI asked for a managed link, or when the desktop or
52 * web app made one: that saves the tunnel config but no CLI marker. Revoked is off.
53 */
54export const connectEnabled = (link: {
55 readonly cliDesired: boolean;
56 readonly cliMode: CliState.CliDesiredLinkMode;
57 readonly managedTunnel: boolean;
58 readonly revoked: boolean;
59}) =>
60 // The server starts no tunnel for a CLI publish-only link, even with an old tunnel config.
61 !link.revoked && (link.cliDesired ? link.cliMode === "managed" : link.managedTunnel);
62
63const readSetup = Effect.fn("cli.up.read_setup")(function* () {
64 const { baseDir } = yield* ServerConfig.ServerConfig;
65 const service = yield* (yield* BootService.BootService).status;
66 const { entries } = yield* CliService.readServiceEnv(baseDir);
67 // Parsed as the server parses it.
68 const lan = yield* Config.Boolean("T3CODE_LAN")
69 .pipe(Config.option)
70 .parse(ConfigProvider.fromEnv({ env: entries }));
71 const secrets = yield* ServerSecretStore.ServerSecretStore;
72 const connectRevoked =
73 hasCloudPublicConfig && Option.isSome(yield* secrets.get(CLOUD_LINK_REVOKED));
74 const connect = hasCloudPublicConfig
75 ? connectEnabled({
76 cliDesired: yield* CliState.readCliDesiredCloudLink,
77 cliMode: yield* CliState.readCliDesiredLinkMode,
78 managedTunnel: Option.isSome(yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
79 revoked: connectRevoked,
80 })
81 : null;
82 return {
83 service,
84 connect,
85 connectRevoked,
86 lan: Option.getOrElse(lan, () => service.installed),
87 lanFromOldDefault: Option.isNone(lan) && service.installed,
88 host: entries.T3CODE_HOST,
89 } satisfies Setup;
90});
91
92/**
93 * The routes `t3 up` starts from. With no route flag it asks about every
94 * route, starting a machine with no service from T3 Connect. Any route flag
95 * means it asks nothing and keeps the routes not named as they are.
96 */
97export const planRoutes = (
98 setup: { readonly installed: boolean; readonly connect: boolean | null; readonly lan: boolean },
99 flags: { readonly connect: Option.Option<boolean>; readonly lan: Option.Option<boolean> },
100) => {
101 const ask = Option.isNone(flags.connect) && Option.isNone(flags.lan);
102 const start = {
103 connect: setup.connect === true || (ask && !setup.installed && setup.connect !== null),
104 lan: setup.lan,
105 };
106 return {
107 routes: {
108 connect: Option.getOrElse(flags.connect, () => start.connect),
109 lan: Option.getOrElse(flags.lan, () => start.lan),
110 } satisfies Routes,
111 ask: ask
112 ? (["connect", "lan"] as const).filter((r) => r !== "connect" || setup.connect !== null)
113 : [],
114 };
115};
116
117/** A running service reads T3CODE_LAN and its T3 Connect link only when it starts. */
118const needsRestart = (before: Routes, after: Routes) =>
119 after.lan !== before.lan || (after.connect && !before.connect);
120
121const CHOICES = {
122 connect: { title: "T3 Connect", description: "Creates a tunnel to control your PC." },
123 lan: { title: "Local network", description: "LAN and tailnet. Pairing code required." },
124} satisfies Record<Route, { readonly title: string; readonly description: string }>;
125
126const formatSetup = (setup: Setup) => {
127 const { service } = setup;
128 const rows: ReadonlyArray<readonly [string, string]> = [
129 [
130 "Service",
131 !service.supported
132 ? "unavailable"
133 : service.installed
134 ? `installed · t3@${service.installedVersion ?? packageJson.version}`
135 : "not installed",
136 ],
137 ...(setup.connect === null
138 ? []
139 : [
140 [
141 "T3 Connect",
142 setup.connect
143 ? "on · your T3 account"
144 : setup.connectRevoked
145 ? "off · link revoked. Run `t3 connect`."
146 : "off",
147 ] as const,
148 ]),
149 [
150 "Local network",
151 setup.host !== undefined
152 ? `overridden · T3CODE_HOST=${setup.host}`
153 : setup.lanFromOldDefault
154 ? "on · kept from an older install"
155 : setup.lan
156 ? "on · pairing code only"
157 : "off",
158 ],
159 ];
160 const notes = [
161 ...(setup.host === undefined && setup.lan
162 ? ["Anyone on your LAN or tailnet can reach the port. A pairing code is the only lock."]
163 : []),
164 ...(setup.lanFromOldDefault
165 ? ["Older installs keep LAN access on. Turn it off: `t3 up --no-lan`."]
166 : []),
167 ];
168 return [
169 ...rows.map(([label, value]) => ` ${label.padEnd(15)}${value}`),
170 ...(notes.length === 0 ? [] : ["", ...notes]),
171 ].join("\n");
172};
173
174const formatNextSteps = (routes: Routes, serviceInstalled: boolean, pairCommand: string) =>
175 [
176 ...(routes.connect
177 ? ["On your other device, sign in to T3 Connect with the same account."]
178 : []),
179 ...(routes.lan ? [`Run \`${pairCommand}\`. Use the code on your other device.`] : []),
180 ...(routes.connect || routes.lan
181 ? []
182 : [
183 serviceInstalled
184 ? "Remote access is off. T3 Code still runs here in the background."
185 : "Remote access is off. Run `t3` to use T3 Code here.",
186 ]),
187 ].join("\n");
188
189const interactiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
190
191const setUp = Effect.fn("cli.up")(function* (flags: {
192 readonly baseDir: Option.Option<string>;
193 readonly connect: Option.Option<boolean>;
194 readonly lan: Option.Option<boolean>;
195 readonly yes: boolean;
196 readonly headless: boolean;
197}) {
198 const { baseDir } = yield* ServerConfig.ServerConfig;
199 const service = yield* BootService.BootService;
200 const baseDirArgs = Option.match(flags.baseDir, {
201 onNone: () => [],
202 onSome: (dir) => ["--base-dir", dir],
203 });
204 const { command: pairCommand } = yield* resolveHostCliCommand("pair", baseDirArgs);
205 const before = yield* readSetup();
206 if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {
207 return yield* new CliError.UserError({
208 cause: "connect",
209 userMessage: "T3 Connect is unavailable in this build.",
210 });
211 }
212
213 const current = { connect: before.connect === true, lan: before.lan };
214 // A publish-only link is not "on", but a rollback must put it back.
215 const priorPublishOnly =
216 hasCloudPublicConfig &&
217 (yield* CliState.readCliDesiredCloudLink) &&
218 (yield* CliState.readCliDesiredLinkMode) === "publish_only";
219 const plan = planRoutes({ ...before, installed: before.service.installed }, flags);
220 const interactive = !flags.yes && interactiveTerminal();
221 let routes = plan.routes;
222 if (plan.ask.length > 0 && interactive) {
223 if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`);
224 const picked = yield* Prompt.run(
225 Prompt.MultiSelect({
226 message: "Allow connections through:",
227 selectAll: "Select all",
228 selectNone: "Clear all",
229 inverseSelection: "Invert selection",
230 choices: plan.ask.map((route) => ({
231 ...CHOICES[route],
232 value: route,
233 selected: plan.routes[route],
234 })),
235 }),
236 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(null) }));
237 if (picked === null) return yield* Console.log("Nothing changed.");
238 routes = { connect: picked.includes("connect"), lan: picked.includes("lan") };
239 } else if (plan.ask.length > 0 && !flags.yes && !before.service.installed) {
240 return yield* new CliError.UserError({
241 cause: "routes",
242 userMessage: `No terminal. Choose access with ${
243 before.connect === null ? "--lan" : "--connect or --lan"
244 }, or use --yes for the default. See \`t3 up --help\`.`,
245 });
246 }
247 if (routes.connect && !current.connect) yield* requireConnectAllowed;
248 if (routes.lan && !current.lan) {
249 const policy = yield* ManagedPolicy.ManagedPolicy;
250 if (!ManagedLimits.allowsRemoteClients(policy)) {
251 return yield* ManagedLimits.refuseRemoteClients(policy);
252 }
253 }
254 // Nothing to run in the background, but a route left on still gets turned off.
255 if (!before.service.installed && !routes.connect && !routes.lan) {
256 if (current.connect || before.connectRevoked) {
257 yield* disconnectCloud({ clearAuthorization: false });
258 }
259 if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
260 return yield* Console.log(formatNextSteps(routes, false, pairCommand));
261 }
262 const { installedVersion } = before.service;
263 const newer =
264 installedVersion !== undefined &&
265 compareExactServiceVersions(installedVersion, packageJson.version) > 0;
266 // Asked before anything changes, so a declined restart leaves service.env
267 // matching what the running service read when it started.
268 // A stopped service of this version is not current, so reconcile starts it;
269 // a newer one is left alone and needs this restart to start.
270 const stopped = before.service.problems?.includes("service-stopped") === true;
271 const restart =
272 before.service.installed &&
273 (before.service.current || newer) &&
274 (needsRestart(current, routes) || stopped);
275 // An older or broken service is reinstalled, which restarts it too.
276 const update = before.service.installed && !before.service.current && !newer && !stopped;
277 if ((restart || update) && interactive && !stopped) {
278 const confirmed = yield* Prompt.run(
279 Prompt.Confirm({
280 message: update
281 ? "Update and restart T3 Code? Running agent turns will stop."
282 : "Apply changes and restart? Running agent turns will stop.",
283 initial: true,
284 }),
285 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
286 if (!confirmed) return yield* Console.log("Nothing changed.");
287 }
288
289 if (routes.connect && !current.connect) {
290 const linked = yield* linkEnvironmentForConnect({
291 headless: flags.headless,
292 installRelayClient: true,
293 });
294 if (linked === null) return;
295 yield* Console.log(
296 `✓ Signed in to T3 Connect${linked.identity ? ` as ${linked.identity}` : ""}`,
297 );
298 }
299 // A running server unlinks live; when that fails, only a restart stops its tunnel.
300 const unlinkFailed =
301 !routes.connect && (current.connect || before.connectRevoked)
302 ? (yield* disconnectCloud({ clearAuthorization: false })).status === "failed"
303 : false;
304 const previousLan = (yield* CliService.readServiceEnv(baseDir)).entries.T3CODE_LAN;
305 // Also with no service manager: the file records the choice that `t3 status` shows.
306 yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });
307 // When the service step fails, an installed service still runs with the old
308 // value, so the file goes back to match it.
309 // A new T3 Connect link is undone too, with any tunnel the failed start saved, so a
310 // rerun sees it as a change and restarts. The sign-in stays.
311 const restoreServiceEnv = before.service.installed
312 ? CliService.writeServiceEnv(baseDir, { T3CODE_LAN: previousLan }).pipe(
313 Effect.andThen(
314 !routes.connect || current.connect
315 ? Effect.void
316 : priorPublishOnly
317 ? CliState.setCliDesiredCloudLink(true, "publish_only")
318 : disconnectCloud({ clearAuthorization: false }).pipe(Effect.asVoid),
319 ),
320 )
321 : Effect.void;
322 // A failed update or restart may still have started the service with the new
323 // settings, so restart it once more on the old ones.
324 const rollBack = before.service.installed
325 ? restoreServiceEnv.pipe(Effect.andThen(service.restart.pipe(Effect.ignore)))
326 : Effect.void;
327 if (before.host !== undefined) {
328 yield* Console.warn(
329 `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,
330 );
331 }
332
333 const printServeCommand = Effect.fn(function* (reason: string) {
334 const { command } = yield* resolveHostCliCommand("serve", [
335 ...baseDirArgs,
336 // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.
337 routes.lan ? "--lan" : "--no-lan",
338 ]);
339 yield* Console.log(`${reason} Keep this command running:\n ${command}`);
340 // A host wins over --lan and --no-lan, as it does in service.env.
341 const shellHost = (yield* HostProcess.Environment).T3CODE_HOST;
342 if (shellHost !== undefined) {
343 yield* Console.warn(
344 `T3CODE_HOST=${shellHost} in this shell overrides that choice. Unset it before you run the command.`,
345 );
346 }
347 });
348 let started = false;
349 if (!before.service.supported) {
350 yield* printServeCommand("Background service unavailable.");
351 } else {
352 if (newer) {
353 yield* Console.log(`Keeping installed service version t3@${installedVersion}.`);
354 }
355 if (update && !interactive) {
356 yield* Console.log("Updating T3 Code. Running agent turns will stop.");
357 }
358 const result = newer
359 ? ({ changed: false } as const)
360 : yield* CliService.reconcileService().pipe(
361 Effect.catchTags({
362 BootServicePrerequisiteError: (error) => Effect.succeed({ failed: error.message }),
363 BootServiceUnsupportedError: (error) => Effect.succeed({ failed: error.message }),
364 }),
365 Effect.tapError(() => rollBack),
366 );
367 if ("failed" in result && before.service.installed) {
368 // The old service still runs, so a foreground server would clash with it.
369 yield* restoreServiceEnv;
370 yield* Console.log(
371 `Service setup failed: ${result.failed} Fix that, then run \`t3 up\` again.`,
372 );
373 } else if ("failed" in result) {
374 yield* printServeCommand(`Service setup failed: ${result.failed}`);
375 } else if (result.changed) {
376 yield* Console.log(CliService.formatServiceChange(result));
377 started = true;
378 } else if (restart || (unlinkFailed && before.service.installed)) {
379 const confirmed =
380 restart ||
381 !interactive ||
382 (yield* Prompt.run(
383 Prompt.Confirm({
384 message:
385 "The running service still has T3 Connect on. Restart it? Running agent turns will stop.",
386 initial: true,
387 }),
388 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) })));
389 if (!confirmed) {
390 yield* Console.log("Run `t3 service restart` to turn T3 Connect off.");
391 } else {
392 if (!interactive && !stopped) {
393 yield* Console.log("Restarting T3 Code. Running agent turns will stop.");
394 }
395 const outcome = yield* service.restart.pipe(Effect.tapError(() => rollBack));
396 if (outcome === "queued") {
397 yield* Console.log("Restart queued. This session will disconnect.");
398 }
399 if (outcome === "skipped") {
400 yield* Console.log(
401 "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",
402 );
403 }
404 started = outcome === "restarted";
405 }
406 }
407 }
408 if (started && routes.connect && !current.connect) yield* waitForReachability();
409
410 const after = yield* readSetup();
411 yield* Console.log(
412 // From what took effect: a failed service step can undo a choice.
413 `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps(
414 { connect: after.connect === true, lan: after.lan },
415 after.service.installed,
416 pairCommand,
417 )}`,
418 );
419});
420
421export const upCommand = Command.make("up", {
422 ...projectLocationFlags,
423 connect: Flag.Boolean("connect").pipe(
424 Flag.withDescription(
425 "Allow access through T3 Connect with your T3 account. Turn off with --no-connect.",
426 ),
427 Flag.optional,
428 ),
429 lan: Flag.Boolean("lan").pipe(
430 Flag.withDescription(
431 "Allow LAN and tailnet connections. Anyone there can reach the port; a pairing code is the only lock. Turn off with --no-lan.",
432 ),
433 Flag.optional,
434 ),
435 yes: Flag.Boolean("yes").pipe(
436 Flag.withDescription(
437 "Ask nothing. Keep the access settings; a new machine gets T3 Connect. A restart stops running agent turns.",
438 ),
439 Flag.withDefault(false),
440 ),
441 headless: headlessFlag,
442}).pipe(
443 Command.withShortDescription("Set up remote access and the T3 Code background service."),
444 Command.withDescription(
445 "Set up remote access and the T3 Code background service. Access flags skip the question, and routes not named keep their settings. Without a terminal, a needed restart runs without asking and stops running agent turns.",
446 ),
447 Command.withExamples([
448 { command: "t3 up", description: "Choose remote access." },
449 { command: "t3 up --connect", description: "Turn on T3 Connect. Keep other settings." },
450 { command: "t3 up --lan", description: "Allow LAN access with pairing codes." },
451 { command: "t3 up --no-lan", description: "Stop LAN access." },
452 { command: "t3 up --yes", description: "Take the defaults with no questions." },
453 { command: "t3 status --json", description: "Read the settings from a script." },
454 ]),
455 Command.withHandler((flags) => runCloudCommand(flags, setUp(flags), { quietLogs: true })),
456);
457
458export const connectCommand = Command.make("connect", {
459 ...projectLocationFlags,
460 headless: headlessFlag,
461}).pipe(
462 Command.withDescription("Set up T3 Connect for this machine. Same as `t3 up --connect`."),
463 Command.withHandler((flags) =>
464 runCloudCommand(
465 flags,
466 setUp({ ...flags, connect: Option.some(true), lan: Option.none(), yes: false }),
467 { quietLogs: true },
468 ),
469 ),
470 Command.withSubcommands(connectSubcommands),
471);
472
473/** `t3 status --json`, for scripts and agents. */
474const setupJson = (setup: Setup) =>
475 JSON.stringify(
476 {
477 service: {
478 supported: setup.service.supported,
479 installed: setup.service.installed,
480 installedVersion: setup.service.installedVersion ?? null,
481 },
482 connect:
483 setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },
484 lan: {
485 enabled: setup.lan,
486 inheritedDefault: setup.lanFromOldDefault,
487 hostOverride: setup.host ?? null,
488 },
489 },
490 null,
491 2,
492 );
493
494export const statusCommand = Command.make("status", {
495 ...projectLocationFlags,
496 json: Flag.Boolean("json").pipe(
497 Flag.withDescription("Print the settings as JSON. Does not test connections."),
498 Flag.withDefault(false),
499 ),
500}).pipe(
501 Command.withDescription("Show service setup and remote access settings."),
502 Command.withExamples([
503 { command: "t3 status", description: "Show the settings." },
504 { command: "t3 status --json", description: "Print them for scripts and agents." },
505 ]),
506 Command.withHandler(
507 Effect.fn("cli.status")(function* (flags) {
508 const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel, {
509 quietLogs: flags.json,
510 });
511 // Only what readSetup reads: no database, unlike the T3 Connect commands.
512 const setup = yield* readSetup().pipe(
513 Effect.provide(
514 Layer.merge(CliService.layer(config), ServerSecretStore.layer).pipe(
515 Layer.provideMerge(ServerConfig.layer(config)),
516 ),
517 ),
518 );
519 yield* Console.log(
520 flags.json
521 ? setupJson(setup)
522 : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,
523 );
524 }),
525 ),
526);