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

connect.ts

729 lines26.2 KB

1import {
2 AuthRelayWriteScope,
3 EnvironmentHttpApi,
4 type RelayClientInstallProgressEvent,
5 type RelayClientInstallProgressStage,
6} from "@t3tools/contracts";
7import { RelayOkResponse } from "@t3tools/contracts/relay";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as RelayClient from "@t3tools/shared/relayClient";
10import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
11import * as Cause from "effect/Cause";
12import * as Config from "effect/Config";
13import * as Console from "effect/Console";
14import * as Crypto from "effect/Crypto";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as References from "effect/References";
22import * as Schema from "effect/Schema";
23import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
24import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25import * as HttpApiClient from "effect/http-api/HttpApiClient";
26​
27import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
28import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
29import * as BootService from "../cloud/bootService.ts";
30import * as CliState from "../cloud/CliState.ts";
31import * as CliTokenManager from "../cloud/CliTokenManager.ts";
32import { filterRelayResponse } from "../cloud/relayResponse.ts";
33import {
34 CLOUD_LINK_REVOKED,
35 CLOUD_LINKED_USER_ID,
36 isAgentActivityPublishingEnabledValue,
37 PUBLISH_AGENT_ACTIVITY_SECRET,
38 RELAY_URL_SECRET,
39} from "../cloud/config.ts";
40import { relayUrlConfig } from "../cloud/publicConfig.ts";
41import * as RelayTracing from "../cloud/relayTracing.ts";
42import * as ServerConfig from "../config.ts";
43import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
44import * as ExternalLauncher from "../process/externalLauncher.ts";
45import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
46import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
47import { resolveCliCommand } from "./invocation.ts";
48import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";
49import * as CliService from "./service.ts";
50​
51const jsonFlag = Flag.Boolean("json").pipe(
52 Flag.withDescription("Emit JSON instead of human-readable output."),
53 Flag.withDefault(false),
54);
55​
56const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
57​
58const headlessFlag = Flag.Boolean("headless").pipe(
59 Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
60 Flag.withDefault(false),
61);
62​
63/**
64 * Inside an SSH session there is no local browser to complete the loopback
65 * OAuth callback, so the device authorization grant is the only flow that
66 * can work.
67 */
68export const headlessSessionConfig = Config.all({
69 sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option),
70 sshTty: Config.String("SSH_TTY").pipe(Config.option),
71}).pipe(
72 Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
73);
74​
75const showDeviceAuthorizationPrompt = (prompt: CliTokenManager.DeviceAuthorizationPrompt) =>
76 Console.log(formatDeviceAuthorizationPrompt(prompt));
77​
78function formatDeviceAuthorizationPrompt(
79 prompt: CliTokenManager.DeviceAuthorizationPrompt,
80): string {
81 const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
82 return [
83 "Headless authorization",
84 "Open this URL on a device with a browser:",
85 ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
86 "",
87 `Confirm this code when asked: ${prompt.userCode}`,
88 "",
89 `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
90 ].join("\n");
92​
93const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
94 readonly headless: boolean;
95}) {
96 const tokens = yield* CliTokenManager.CloudCliTokenManager;
97 const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
98 if (!useOutOfBandOAuth) {
99 const authorization = yield* tokens.get;
100 if (authorization._tag === "Authorized") {
101 return authorization.token.identity ?? null;
102 }
103 yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
104 }
105 const existing = yield* tokens.getExisting.pipe(
106 Effect.catchTags({
107 CloudCliCredentialRefreshError: () =>
108 Console.log(
109 "The stored T3 Connect credential could not be refreshed; signing in again.",
110 ).pipe(Effect.as(Option.none())),
111 }),
112 );
113 if (Option.isSome(existing)) {
114 return existing.value.identity ?? null;
115 }
116 const { token, identity } = yield* CliTokenManager.deviceAuthorizationLogin(
117 showDeviceAuthorizationPrompt,
118 ).pipe(
119 Effect.mapError((cause) =>
120 isCloudCliTokenManagerError(cause)
121 ? cause
122 : new CliTokenManager.CloudCliAuthorizationError({ cause }),
123 ),
124 );
125 yield* tokens.store(token);
126 return identity;
127});
128​
129function bytesToString(value: Uint8Array): string {
130 return new TextDecoder().decode(value);
132​
133function stringToBytes(value: string): Uint8Array {
134 return new TextEncoder().encode(value);
136​
137interface CloudCliStatus {
138 readonly desired: boolean;
139 readonly authenticated: boolean;
140 readonly linked: boolean;
141 readonly revoked: boolean;
142 readonly cloudUserId: string | null;
143 readonly relayUrl: string | null;
144 readonly publishAgentActivity: boolean;
145 readonly relayClient: RelayClient.RelayClientStatus;
147​
148function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
149 switch (executable.status) {
150 case "available": {
151 const source =
152 executable.source === "path"
153 ? "PATH"
154 : executable.source === "managed"
155 ? "managed install"
156 : "configured override";
157 return [
158 ` Relay client: available via ${source}`,
159 ` Path: ${executable.executablePath}`,
160 ` Version: ${executable.version}`,
161 ];
162 }
163 case "missing":
164 return [" Relay client: not installed"];
165 case "unsupported":
166 return [
167 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
168 ` Managed version: ${executable.version}`,
169 ];
170 }
172​
173function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
174 if (options?.json) {
175 return JSON.stringify(status, null, 2);
176 }
177​
178 const provisioned = status.revoked
179 ? "removed from T3 Connect"
180 : status.linked
181 ? "provisioned"
182 : status.desired && status.authenticated
183 ? "pending server startup"
184 : "not provisioned";
185 const nextStep = !status.authenticated
186 ? "Run `t3 connect link` to authorize and enable T3 Connect."
187 : status.revoked
188 ? "Run `t3 connect link` to link this environment again."
189 : !status.desired
190 ? "Run `t3 connect link` to enable T3 Connect."
191 : !status.linked
192 ? "Start T3 to provision the environment link and launch its managed tunnel."
193 : undefined;
194​
195 return [
196 "T3 Connect",
197 ` Exposure: ${status.desired ? "enabled" : "disabled"}`,
198 ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
199 ` Environment link: ${provisioned}`,
200 ` Relay: ${status.relayUrl ?? "not provisioned"}`,
201 ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
202 ...formatRelayClientStatus(status.relayClient),
203 "",
204 "This is saved setup, not a live connection check. Check the background service with `t3 service status`.",
205 ...(nextStep ? ["", `Next: ${nextStep}`] : []),
206 ].join("\n");
208​
209const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
210​
211const confirmRelayClientInstall = (version: string) =>
212 Prompt.run(
213 Prompt.Confirm({
214 message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
215 initial: false,
216 }),
217 );
218​
219function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
220 switch (stage) {
221 case "checking":
222 return "Checking existing installation";
223 case "waiting_for_lock":
224 return "Waiting for installation lock";
225 case "downloading":
226 return "Downloading";
227 case "verifying":
228 return "Verifying download";
229 case "installing":
230 return "Installing";
231 case "validating":
232 return "Validating executable";
233 case "activating":
234 return "Activating installation";
235 }
237​
238const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
239 event.type === "progress"
240 ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
241 : Effect.void;
242​
243export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
244 function* <ConfirmError, ConfirmContext>(
245 relayClient: RelayClient.RelayClient["Service"],
246 confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
247 reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
248 ) {
249 const executable = yield* relayClient.resolve;
250 if (executable.status === "available") {
251 return Option.some(executable);
252 }
253 if (executable.status === "unsupported") {
254 return Option.some(yield* relayClient.installWithProgress(reportProgress));
255 }
256 if (!(yield* confirmInstall(executable.version))) {
257 return Option.none();
258 }
259 return Option.some(yield* relayClient.installWithProgress(reportProgress));
260 },
261);
262​
263const withCloudCliSessionToken = <A, E, R>(
264 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
265 run: (token: string) => Effect.Effect<A, E, R>,
266) =>
267 Effect.acquireUseRelease(
268 environmentAuth.issueSession({
269 scopes: [AuthRelayWriteScope],
270 subject: "cloud-cli",
271 label: "t3 connect cli",
272 }),
273 (issued) => run(issued.token),
274 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
275 );
276​
277type LiveCloudActionResult =
278 | { readonly status: "not-running" }
279 | { readonly status: "succeeded" }
280 | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
281​
282const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
283 const config = yield* ServerConfig.ServerConfig;
284 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
285 if (Option.isNone(runtimeState)) {
286 return { status: "not-running" } satisfies LiveCloudActionResult;
287 }
288​
289 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
290 const result = yield* Effect.exit(
291 withCloudCliSessionToken(environmentAuth, (token) =>
292 HttpApiClient.make(EnvironmentHttpApi, {
293 baseUrl: runtimeState.value.origin,
294 }).pipe(
295 Effect.flatMap((client) =>
296 client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
297 ),
298 Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
299 ),
300 ),
301 );
302 return Exit.isSuccess(result)
303 ? ({ status: "succeeded" } satisfies LiveCloudActionResult)
304 : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
305});
306​
307type RelayUnlinkResult =
308 | { readonly status: "not-authenticated" }
309 | { readonly status: "revoked" }
310 | { readonly status: "not-linked" };
311​
312type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
313​
314const logCloudDisconnectFailure = (
315 operation: CloudDisconnectOperation,
316 clearAuthorization: boolean,
317 cause: Cause.Cause<unknown>,
318) =>
319 Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
320 Effect.annotateLogs({
321 operation,
322 clearAuthorization,
323 cause: Cause.pretty(cause),
324 }),
325 );
326​
327const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
328 const tokens = yield* CliTokenManager.CloudCliTokenManager;
329 const token = yield* tokens.getExisting;
330 if (Option.isNone(token)) {
331 return { status: "not-authenticated" } satisfies RelayUnlinkResult;
332 }
333​
334 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
335 const environmentId = yield* environment.getEnvironmentId;
336 const relayUrl = yield* relayUrlConfig;
337 const httpClient = yield* HttpClient.HttpClient;
338 const response = yield* HttpClientRequest.delete(
339 `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
340 ).pipe(
341 HttpClientRequest.bearerToken(token.value.accessToken),
342 httpClient.execute,
343 Effect.flatMap(filterRelayResponse),
344 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
345 withRelayClientTracing,
346 );
347 return response.ok
348 ? ({ status: "revoked" } satisfies RelayUnlinkResult)
349 : ({ status: "not-linked" } satisfies RelayUnlinkResult);
350});
351​
352/**
353 * Prints the local disconnect outcome, then whether the relay record was revoked.
354 * A missing CLI login or a failed relay DELETE leaves that record registered, so
355 * those outcomes warn to deregister it from the T3 Connect account page.
356 */
357export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
358 function* (input: {
359 readonly clearAuthorization: boolean;
360 readonly liveResult: LiveCloudActionResult;
361 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
362 }) {
363 if (input.liveResult.status === "failed") {
364 yield* logCloudDisconnectFailure(
365 "live-server-unlink",
366 input.clearAuthorization,
367 input.liveResult.cause,
368 );
369 yield* Console.warn(
370 "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
371 );
372 } else {
373 yield* Console.log("T3 Connect is disabled locally.");
374 }
375​
376 if (Exit.isFailure(input.relayResult)) {
377 yield* logCloudDisconnectFailure(
378 "relay-environment-unlink",
379 input.clearAuthorization,
380 input.relayResult.cause,
381 );
382 yield* Console.warn(
383 input.clearAuthorization
384 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
385 : "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable, or deregister it from the T3 Connect page of your T3 account.",
386 );
387 } else if (input.relayResult.value.status === "not-authenticated") {
388 yield* Console.warn(
389 "The relay-side environment record was not revoked.\nDeregister it from the T3 Connect page of your T3 account, or run `t3 connect login` and retry.",
390 );
391 } else if (input.relayResult.value.status === "revoked") {
392 yield* Console.log("Revoked the relay-side environment record.");
393 }
394 },
395);
396​
397const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
398 readonly clearAuthorization: boolean;
399}) {
400 yield* CliState.setCliDesiredCloudLink(false);
401 const liveResult = yield* runLiveCloudUnlink();
402 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
403 yield* CliState.clearPersistedCloudLink;
404​
405 if (options.clearAuthorization) {
406 const tokens = yield* CliTokenManager.CloudCliTokenManager;
407 yield* tokens.clear;
408 }
409​
410 yield* reportCloudDisconnectResults({
411 clearAuthorization: options.clearAuthorization,
412 liveResult,
413 relayResult,
414 });
415​
416 if (options.clearAuthorization) {
417 yield* Console.log(
418 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
419 );
420 }
421});
422​
423const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
424 flags: { readonly baseDir: Option.Option<string> },
425 run: Effect.Effect<
426 A,
427 E,
428 | ServerSecretStore.ServerSecretStore
429 | CliTokenManager.CloudCliTokenManager
430 | RelayClient.RelayClient
431 | EnvironmentAuth.EnvironmentAuth
432 | BootService.BootService
433 | Crypto.Crypto
434 | FileSystem.FileSystem
435 | HttpClient.HttpClient
436 | Prompt.Environment
437 | ServerConfig.ServerConfig
438 | ServerEnvironment.ServerEnvironmentIdentity
439 >,
440 options?: {
441 readonly quietLogs?: boolean;
442 },
443) {
444 const logLevel = yield* GlobalFlag.LogLevel;
445 const config = yield* resolveCliAuthConfig(flags, logLevel);
446 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
447 const layerRuntime = Layer.mergeAll(
448 ServerSecretStore.layer,
449 CliTokenManager.layer.pipe(
450 Layer.provide(ServerSecretStore.layer),
451 Layer.provide(ExternalLauncher.layer),
452 ),
453 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
454 EnvironmentAuth.layerRuntime,
455 CliService.layer(config),
456 RelayTracing.layerHeadlessRelayClient,
457 ).pipe(
458 Layer.provideMerge(FetchHttpClient.layer),
459 Layer.provideMerge(ServerConfig.layer(config)),
460 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
461 );
462 return yield* run.pipe(Effect.provide(layerRuntime));
463});
464​
465const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
466​
467function formatRelayClientReady(version: string): string {
468 return `✓ Relay client ready · cloudflared ${version}`;
470​
471const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
472 readonly headless: boolean;
473 readonly publishOnly?: boolean;
474}) {
475 const publishOnly = options.publishOnly ?? false;
476 if (!publishOnly) {
477 const relayClient = yield* RelayClient.RelayClient;
478 const installed = yield* acquireRelayClientForLink(
479 relayClient,
480 confirmRelayClientInstall,
481 reportRelayClientInstallProgress,
482 );
483 if (Option.isNone(installed)) {
484 yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
485 return null;
486 }
487 yield* Console.log(formatRelayClientReady(installed.value.version));
488 }
489​
490 const identity = yield* authorizeCli(options);
491 yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
492 if (yield* CliState.dropRevokedCloudLink) {
493 yield* Console.log(
494 "Removed the link T3 Connect no longer accepts. The next start links this environment again.",
495 );
496 }
497 if (publishOnly) {
498 const secrets = yield* ServerSecretStore.ServerSecretStore;
499 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
500 }
501 return { identity } as const;
502});
503​
504const connectLoginCommand = Command.make("login", {
505 ...projectLocationFlags,
506 headless: headlessFlag,
507}).pipe(
508 Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
509 Command.withHandler((flags) =>
510 runCloudCommand(
511 flags,
512 Effect.gen(function* () {
513 yield* Console.log("T3 Connect\n");
514 const identity = yield* authorizeCli(flags);
515 yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
516 }),
517 ),
518 ),
519);
520​
521const connectLinkCommand = Command.make("link", {
522 ...projectLocationFlags,
523 headless: headlessFlag,
524 publishOnly: Flag.Boolean("publish-only").pipe(
525 Flag.withDescription(
526 "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
527 ),
528 Flag.withDefault(false),
529 ),
530}).pipe(
531 Command.withDescription("Authorize this environment for T3 Connect on next start."),
532 Command.withHandler((flags) =>
533 runCloudCommand(
534 flags,
535 Effect.gen(function* () {
536 yield* Console.log("T3 Connect\n");
537 const linked = yield* linkEnvironmentForConnect(flags);
538 if (linked) {
539 const serveCommand = yield* resolveCliCommand("serve");
540 yield* Console.log(
541 flags.publishOnly
542 ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
543 : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
544 );
545 }
546 }),
547 ),
548 ),
549);
550​
551const connectStatusCommand = Command.make("status", {
552 ...projectLocationFlags,
553 json: jsonFlag,
554}).pipe(
555 Command.withDescription("Show persisted T3 Connect and relay client state."),
556 Command.withHandler((flags) =>
557 runCloudCommand(
558 flags,
559 Effect.gen(function* () {
560 const secrets = yield* ServerSecretStore.ServerSecretStore;
561 const relayClient = yield* RelayClient.RelayClient;
562 const tokens = yield* CliTokenManager.CloudCliTokenManager;
563 const [
564 desired,
565 authenticated,
566 cloudUserId,
567 relayUrl,
568 publishAgentActivity,
569 revoked,
570 executable,
571 ] = yield* Effect.all(
572 [
573 CliState.readCliDesiredCloudLink,
574 tokens.hasCredential,
575 secrets.get(CLOUD_LINKED_USER_ID),
576 secrets.get(RELAY_URL_SECRET),
577 secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
578 secrets.get(CLOUD_LINK_REVOKED),
579 relayClient.resolve,
580 ],
581 { concurrency: "unbounded" },
582 );
583 const status: CloudCliStatus = {
584 desired,
585 authenticated,
586 linked: Option.isSome(cloudUserId),
587 revoked: Option.isSome(cloudUserId) && Option.isSome(revoked),
588 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
589 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
590 publishAgentActivity: isAgentActivityPublishingEnabledValue(
591 Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
592 ),
593 relayClient: executable,
594 };
595 yield* Console.log(formatCloudStatus(status, { json: flags.json }));
596 }),
597 {
598 quietLogs: flags.json,
599 },
600 ),
601 ),
602);
603​
604const connectPublishCommand = Command.make("publish", {
605 ...projectLocationFlags,
606 disable: Flag.Boolean("disable").pipe(
607 Flag.withDescription("Stop publishing agent activity to your mobile clients."),
608 Flag.withDefault(false),
609 ),
610}).pipe(
611 Command.withDescription(
612 "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
613 ),
614 Command.withHandler((flags) =>
615 runCloudCommand(
616 flags,
617 Effect.gen(function* () {
618 const secrets = yield* ServerSecretStore.ServerSecretStore;
619 const tokens = yield* CliTokenManager.CloudCliTokenManager;
620 const enabled = !flags.disable;
621 yield* secrets.set(
622 PUBLISH_AGENT_ACTIVITY_SECRET,
623 stringToBytes(enabled ? "true" : "false"),
624 );
625 if (!enabled) {
626 // If enabling scheduled a publish-only link that hasn't been
627 // provisioned yet, disabling must cancel it too — otherwise the next
628 // start still links an environment whose only purpose was publishing.
629 // A pending managed link is left alone; it exists for the tunnel.
630 const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
631 if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
632 yield* CliState.setCliDesiredCloudLink(false);
633 yield* Console.log("Cancelled the pending publish-only T3 Connect link.");
634 }
635 yield* Console.log("Publishing agent activity disabled.");
636 return;
637 }
638​
639 yield* Console.log("Publishing agent activity enabled.");
640 const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
641 if (linked) {
642 return;
643 }
644​
645 if (!(yield* tokens.hasCredential)) {
646 yield* Console.log(
647 "Run `t3 connect login` first so this environment can be authorized to publish.",
648 );
649 return;
650 }
651 // A link may already be desired (e.g. `t3 connect link` before the
652 // server's first start). Never downgrade it: a desired managed link
653 // also covers publishing, so only request a publish-only link when no
654 // link is pending at all.
655 if (yield* CliState.readCliDesiredCloudLink) {
656 yield* Console.log(
657 "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",
658 );
659 return;
660 }
661 yield* CliState.setCliDesiredCloudLink(true, "publish_only");
662 yield* Console.log(
663 "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",
664 );
665 }),
666 ),
667 ),
668);
669​
670const connectUnlinkCommand = Command.make("unlink", {
671 ...projectLocationFlags,
672}).pipe(
673 Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
674 Command.withHandler((flags) =>
675 runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
676 ),
677);
678​
679const connectLogoutCommand = Command.make("logout", {
680 ...projectLocationFlags,
681}).pipe(
682 Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
683 Command.withHandler((flags) =>
684 runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
685 ),
686);
687​
688export const connectCommand = Command.make("connect", {
689 ...projectLocationFlags,
690 headless: headlessFlag,
691}).pipe(
692 Command.withDescription("Set up T3 Connect for this machine."),
693 Command.withHandler((flags) =>
694 runCloudCommand(
695 flags,
696 Effect.gen(function* () {
697 yield* Console.log("T3 Connect\n");
698 const linked = yield* linkEnvironmentForConnect(flags);
699 if (!linked) {
700 return;
701 }
702 yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
703​
704 const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
705 if (background) {
706 const platform = yield* HostProcess.Platform;
707 yield* Console.log(
708 platform === "darwin"
709 ? "\n✓ Background service ready\n\nT3 Code is set to run while you are logged in to this Mac. The server establishes the T3 Connect link on startup."
710 : "\n✓ Background service ready\n\nT3 Code is set to keep running after you log out. The server establishes the T3 Connect link on startup.",
711 );
712 return;
713 }
714 const serveCommand = yield* resolveCliCommand("serve");
715 yield* Console.log(
716 `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
717 );
718 }),
719 ),
720 ),
721 Command.withSubcommands([
722 connectLoginCommand,
723 connectLinkCommand,
724 connectPublishCommand,
725 connectStatusCommand,
726 connectUnlinkCommand,
727 connectLogoutCommand,
728 ]),
729);