Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

up.ts

520 lines20.5 KB

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;
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) =>
175 [
176 ...(routes.connect
177 ? ["On your other device, sign in to T3 Connect with the same account."]
178 : []),
179 ...(routes.lan ? ["Run `t3 pair`. 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 before = yield* readSetup();
201 if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {
202 return yield* new CliError.UserError({
203 cause: "connect",
204 userMessage: "T3 Connect is unavailable in this build.",
205 });
206 }
207​
208 const current = { connect: before.connect === true, lan: before.lan };
209 // A publish-only link is not "on", but a rollback must put it back.
210 const priorPublishOnly =
211 hasCloudPublicConfig &&
212 (yield* CliState.readCliDesiredCloudLink) &&
213 (yield* CliState.readCliDesiredLinkMode) === "publish_only";
214 const plan = planRoutes({ ...before, installed: before.service.installed }, flags);
215 const interactive = !flags.yes && interactiveTerminal();
216 let routes = plan.routes;
217 if (plan.ask.length > 0 && interactive) {
218 if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`);
219 const picked = yield* Prompt.run(
220 Prompt.MultiSelect({
221 message: "Allow connections through:",
222 selectAll: "Select all",
223 selectNone: "Clear all",
224 inverseSelection: "Invert selection",
225 choices: plan.ask.map((route) => ({
226 ...CHOICES[route],
227 value: route,
228 selected: plan.routes[route],
229 })),
230 }),
231 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(null) }));
232 if (picked === null) return yield* Console.log("Nothing changed.");
233 routes = { connect: picked.includes("connect"), lan: picked.includes("lan") };
234 } else if (plan.ask.length > 0 && !flags.yes && !before.service.installed) {
235 return yield* new CliError.UserError({
236 cause: "routes",
237 userMessage: `No terminal. Choose access with ${
238 before.connect === null ? "--lan" : "--connect or --lan"
239 }, or use --yes for the default. See \`t3 up --help\`.`,
240 });
241 }
242 if (routes.connect && !current.connect) yield* requireConnectAllowed;
243 if (routes.lan && !current.lan) {
244 const policy = yield* ManagedPolicy.ManagedPolicy;
245 if (!ManagedLimits.allowsRemoteClients(policy)) {
246 return yield* ManagedLimits.refuseRemoteClients(policy);
247 }
248 }
249 // Nothing to run in the background, but a route left on still gets turned off.
250 if (!before.service.installed && !routes.connect && !routes.lan) {
251 if (current.connect || before.connectRevoked) {
252 yield* disconnectCloud({ clearAuthorization: false });
253 }
254 if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
255 return yield* Console.log(formatNextSteps(routes, false));
256 }
257 const { installedVersion } = before.service;
258 const newer =
259 installedVersion !== undefined &&
260 compareExactServiceVersions(installedVersion, packageJson.version) > 0;
261 // Asked before anything changes, so a declined restart leaves service.env
262 // matching what the running service read when it started.
263 // A stopped service of this version is not current, so reconcile starts it;
264 // a newer one is left alone and needs this restart to start.
265 const stopped = before.service.problems?.includes("service-stopped") === true;
266 const restart =
267 before.service.installed &&
268 (before.service.current || newer) &&
269 (needsRestart(current, routes) || stopped);
270 // An older or broken service is reinstalled, which restarts it too.
271 const update = before.service.installed && !before.service.current && !newer && !stopped;
272 if ((restart || update) && interactive && !stopped) {
273 const confirmed = yield* Prompt.run(
274 Prompt.Confirm({
275 message: update
276 ? "Update and restart T3 Code? Running agent turns will stop."
277 : "Apply changes and restart? Running agent turns will stop.",
278 initial: true,
279 }),
280 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
281 if (!confirmed) return yield* Console.log("Nothing changed.");
282 }
283​
284 if (routes.connect && !current.connect) {
285 const linked = yield* linkEnvironmentForConnect({
286 headless: flags.headless,
287 installRelayClient: true,
288 });
289 if (linked === null) return;
290 yield* Console.log(
291 `✓ Signed in to T3 Connect${linked.identity ? ` as ${linked.identity}` : ""}`,
292 );
293 }
294 // A running server unlinks live; when that fails, only a restart stops its tunnel.
295 const unlinkFailed =
296 !routes.connect && (current.connect || before.connectRevoked)
297 ? (yield* disconnectCloud({ clearAuthorization: false })).status === "failed"
298 : false;
299 const previousLan = (yield* CliService.readServiceEnv(baseDir)).entries.T3CODE_LAN;
300 // Also with no service manager: the file records the choice that `t3 status` shows.
301 yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });
302 // When the service step fails, an installed service still runs with the old
303 // value, so the file goes back to match it.
304 // A new T3 Connect link is undone too, with any tunnel the failed start saved, so a
305 // rerun sees it as a change and restarts. The sign-in stays.
306 const restoreServiceEnv = before.service.installed
307 ? CliService.writeServiceEnv(baseDir, { T3CODE_LAN: previousLan }).pipe(
308 Effect.andThen(
309 !routes.connect || current.connect
310 ? Effect.void
311 : priorPublishOnly
312 ? CliState.setCliDesiredCloudLink(true, "publish_only")
313 : disconnectCloud({ clearAuthorization: false }).pipe(Effect.asVoid),
314 ),
315 )
316 : Effect.void;
317 // A failed update or restart may still have started the service with the new
318 // settings, so restart it once more on the old ones.
319 const rollBack = before.service.installed
320 ? restoreServiceEnv.pipe(Effect.andThen(service.restart.pipe(Effect.ignore)))
321 : Effect.void;
322 if (before.host !== undefined) {
323 yield* Console.warn(
324 `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,
325 );
326 }
327​
328 const printServeCommand = Effect.fn(function* (reason: string) {
329 const { command } = yield* resolveHostCliCommand("serve", [
330 ...Option.match(flags.baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
331 // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.
332 routes.lan ? "--lan" : "--no-lan",
333 ]);
334 yield* Console.log(`${reason} Keep this command running:\n ${command}`);
335 // A host wins over --lan and --no-lan, as it does in service.env.
336 const shellHost = (yield* HostProcess.Environment).T3CODE_HOST;
337 if (shellHost !== undefined) {
338 yield* Console.warn(
339 `T3CODE_HOST=${shellHost} in this shell overrides that choice. Unset it before you run the command.`,
340 );
341 }
342 });
343 let started = false;
344 if (!before.service.supported) {
345 yield* printServeCommand("Background service unavailable.");
346 } else {
347 if (newer) {
348 yield* Console.log(`Keeping installed service version t3@${installedVersion}.`);
349 }
350 if (update && !interactive) {
351 yield* Console.log("Updating T3 Code. Running agent turns will stop.");
352 }
353 const result = newer
354 ? ({ changed: false } as const)
355 : yield* CliService.reconcileService().pipe(
356 Effect.catchTags({
357 BootServicePrerequisiteError: (error) => Effect.succeed({ failed: error.message }),
358 BootServiceUnsupportedError: (error) => Effect.succeed({ failed: error.message }),
359 }),
360 Effect.tapError(() => rollBack),
361 );
362 if ("failed" in result && before.service.installed) {
363 // The old service still runs, so a foreground server would clash with it.
364 yield* restoreServiceEnv;
365 yield* Console.log(
366 `Service setup failed: ${result.failed} Fix that, then run \`t3 up\` again.`,
367 );
368 } else if ("failed" in result) {
369 yield* printServeCommand(`Service setup failed: ${result.failed}`);
370 } else if (result.changed) {
371 yield* Console.log(CliService.formatServiceChange(result));
372 started = true;
373 } else if (restart || (unlinkFailed && before.service.installed)) {
374 const confirmed =
375 restart ||
376 !interactive ||
377 (yield* Prompt.run(
378 Prompt.Confirm({
379 message:
380 "The running service still has T3 Connect on. Restart it? Running agent turns will stop.",
381 initial: true,
382 }),
383 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) })));
384 if (!confirmed) {
385 yield* Console.log("Run `t3 service restart` to turn T3 Connect off.");
386 } else {
387 if (!interactive && !stopped) {
388 yield* Console.log("Restarting T3 Code. Running agent turns will stop.");
389 }
390 const outcome = yield* service.restart.pipe(Effect.tapError(() => rollBack));
391 if (outcome === "queued") {
392 yield* Console.log("Restart queued. This session will disconnect.");
393 }
394 if (outcome === "skipped") {
395 yield* Console.log(
396 "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",
397 );
398 }
399 started = outcome === "restarted";
400 }
401 }
402 }
403 if (started && routes.connect && !current.connect) yield* waitForReachability();
404​
405 const after = yield* readSetup();
406 yield* Console.log(
407 // From what took effect: a failed service step can undo a choice.
408 `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps(
409 { connect: after.connect === true, lan: after.lan },
410 after.service.installed,
411 )}`,
412 );
413});
414​
415export const upCommand = Command.make("up", {
416 ...projectLocationFlags,
417 connect: Flag.Boolean("connect").pipe(
418 Flag.withDescription(
419 "Allow access through T3 Connect with your T3 account. Turn off with --no-connect.",
420 ),
421 Flag.optional,
422 ),
423 lan: Flag.Boolean("lan").pipe(
424 Flag.withDescription(
425 "Allow LAN and tailnet connections. Anyone there can reach the port; a pairing code is the only lock. Turn off with --no-lan.",
426 ),
427 Flag.optional,
428 ),
429 yes: Flag.Boolean("yes").pipe(
430 Flag.withDescription(
431 "Ask nothing. Keep the access settings; a new machine gets T3 Connect. A restart stops running agent turns.",
432 ),
433 Flag.withDefault(false),
434 ),
435 headless: headlessFlag,
436}).pipe(
437 Command.withShortDescription("Set up remote access and the T3 Code background service."),
438 Command.withDescription(
439 "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.",
440 ),
441 Command.withExamples([
442 { command: "t3 up", description: "Choose remote access." },
443 { command: "t3 up --connect", description: "Turn on T3 Connect. Keep other settings." },
444 { command: "t3 up --lan", description: "Allow LAN access with pairing codes." },
445 { command: "t3 up --no-lan", description: "Stop LAN access." },
446 { command: "t3 up --yes", description: "Take the defaults with no questions." },
447 { command: "t3 status --json", description: "Read the settings from a script." },
448 ]),
449 Command.withHandler((flags) => runCloudCommand(flags, setUp(flags), { quietLogs: true })),
450);
451​
452export const connectCommand = Command.make("connect", {
453 ...projectLocationFlags,
454 headless: headlessFlag,
455}).pipe(
456 Command.withDescription("Set up T3 Connect for this machine. Same as `t3 up --connect`."),
457 Command.withHandler((flags) =>
458 runCloudCommand(
459 flags,
460 setUp({ ...flags, connect: Option.some(true), lan: Option.none(), yes: false }),
461 { quietLogs: true },
462 ),
463 ),
464 Command.withSubcommands(connectSubcommands),
465);
466​
467/** `t3 status --json`, for scripts and agents. */
468const setupJson = (setup: Setup) =>
469 JSON.stringify(
470 {
471 service: {
472 supported: setup.service.supported,
473 installed: setup.service.installed,
474 installedVersion: setup.service.installedVersion ?? null,
475 },
476 connect:
477 setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },
478 lan: {
479 enabled: setup.lan,
480 inheritedDefault: setup.lanFromOldDefault,
481 hostOverride: setup.host ?? null,
482 },
483 },
484 null,
485 2,
486 );
487​
488export const statusCommand = Command.make("status", {
489 ...projectLocationFlags,
490 json: Flag.Boolean("json").pipe(
491 Flag.withDescription("Print the settings as JSON. Does not test connections."),
492 Flag.withDefault(false),
493 ),
494}).pipe(
495 Command.withDescription("Show service setup and remote access settings."),
496 Command.withExamples([
497 { command: "t3 status", description: "Show the settings." },
498 { command: "t3 status --json", description: "Print them for scripts and agents." },
499 ]),
500 Command.withHandler(
501 Effect.fn("cli.status")(function* (flags) {
502 const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel, {
503 quietLogs: flags.json,
504 });
505 // Only what readSetup reads: no database, unlike the T3 Connect commands.
506 const setup = yield* readSetup().pipe(
507 Effect.provide(
508 Layer.merge(CliService.layer(config), ServerSecretStore.layer).pipe(
509 Layer.provideMerge(ServerConfig.layer(config)),
510 ),
511 ),
512 );
513 yield* Console.log(
514 flags.json
515 ? setupJson(setup)
516 : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,
517 );
518 }),
519 ),
520);