feat: add headless t3 connect setup for SSH hosts (#3749)

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-07-19 18:59:23 +02:00
1 parent 53e3c98a55
commit 7a820abfdd
35 files changed
+3018 -145

No files matched your search

+4
View File
@@ -18,6 +18,10 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
+257
View File
@@ -0,0 +1,257 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plan: seamless `npx t3 connect` for remote boxes</title>
<style>
:root {
--bg: #000;
--fg: #fff;
--muted: #a3a3a3;
--surface: #121212;
--surface2: #1a1a1a;
--border: #2a2a2a;
--accent: #7c9cff;
--green: #4ade80;
--amber: #fbbf24;
--red: #f87171;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--fg);
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
h1 { font-size: 30px; line-height: 1.25; margin: 0 0 8px; }
h2 { font-size: 21px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--border); }
h3 { font-size: 16px; margin: 24px 0 8px; }
p, li { color: #e5e5e5; }
.sub { color: var(--muted); margin: 0 0 24px; }
code, pre {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 13.5px;
}
code { background: var(--surface2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }
pre {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 16px;
overflow-x: auto;
line-height: 1.5;
}
pre code { background: none; border: none; padding: 0; }
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 18px 20px;
margin: 16px 0;
}
.card h3 { margin-top: 0; }
table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14.5px; }
th, td { text-align: left; padding: 8px 12px; border: 1px solid var(--border); vertical-align: top; }
th { background: var(--surface2); font-weight: 600; }
td code { white-space: nowrap; }
.pill {
display: inline-block; font-size: 12px; font-weight: 600; border-radius: 999px;
padding: 2px 10px; margin-right: 6px; vertical-align: 2px;
}
.pill.core { background: #1e2a4a; color: var(--accent); }
.pill.new { background: #14301e; color: var(--green); }
.pill.later { background: #33270e; color: var(--amber); }
.ok { color: var(--green); }
.warn { color: var(--amber); }
.no { color: var(--red); }
ul { padding-left: 22px; }
li { margin: 4px 0; }
.terminal {
background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px;
padding: 16px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 13.5px; line-height: 1.65; color: #d4d4d4; overflow-x: auto;
}
.terminal .dim { color: #737373; }
.terminal .g { color: var(--green); }
.terminal .b { color: var(--accent); }
figure { margin: 24px 0; }
figcaption { color: var(--muted); font-size: 13px; margin-top: 8px; text-align: center; }
svg text { font-family: -apple-system, "Segoe UI", sans-serif; }
a { color: var(--accent); }
.kv { color: var(--muted); font-size: 13.5px; }
</style>
</head>
<body>
<main>
<h1>Seamless <code>npx t3 connect</code> for remote boxes</h1>
<p class="sub">Design principle: <strong>the smallest diff that ships the UX.</strong> No relay/infra changes, no new backend surface, no new auth primitives &mdash; every step reuses code that already exists. One PR, built as four phases with clear commit boundaries &mdash; each phase compiles, passes tests, and leaves the product working, so the PR reviews commit-by-commit. (Phase 4, web-triggered update, is an optional follow-up PR.)</p>
<div class="terminal">
$ npx t3 connect<br><br>
To set up T3 Connect, open this URL and sign in:<br>
&nbsp;&nbsp;<span class="b">https://app.t3.codes/connect#B64URL_STATE_AND_CHALLENGE</span><br><br>
Enter your authentication code: <span class="dim">[code]</span><br><br>
<span class="g">Connected as [email protected]!</span><br><br>
Run T3 Code in the background whenever this machine boots? (y/n): y<br><br>
<span class="g">T3 Code is set up and ready to go.</span>
</div>
<h2>Why this is a small change</h2>
<p>The entire <code>t3 connect</code> data plane already works: Clerk PKCE token exchange, encrypted secret store, cloudflared relay-client install, relay environment linking, DPoP tokens. The <em>only</em> broken piece on an SSH box is the redirect: <code>CliTokenManager.login()</code> hardcodes a loopback callback (<code>http://127.0.0.1:34338/callback</code>) that requires a browser on the same machine.</p>
<p>We swap that one leg for a hosted out-of-band authorization page and keep everything else. Because PKCE's <code>code_verifier</code> never leaves the box, the displayed one-time code is useless to anyone who sees it &mdash; no new token-minting or storage is needed anywhere.</p>
<div class="card">
<h3>Reused as-is (zero changes)</h3>
<ul>
<li><code>exchangeToken()</code> PKCE exchange &mdash; <code>apps/server/src/cloud/CliTokenManager.ts:147</code></li>
<li>Token persistence in <code>ServerSecretStore</code> (<code>cloud-cli-oauth-token</code>)</li>
<li><code>acquireRelayClientForLink()</code> cloudflared install + progress &mdash; <code>cli/connect.ts:146</code></li>
<li><code>CliState.setCliDesiredCloudLink()</code> + server-side provisioning on start</li>
<li>All relay endpoints (<code>infra/relay</code>) and contracts &mdash; <strong>untouched</strong></li>
<li>Existing subcommands <code>login/link/status/unlink/logout</code> &mdash; semantics unchanged</li>
<li>Web app Clerk session + hosted-page precedent (<code>routes/pair.tsx</code>, <code>hostedPairing.ts</code>)</li>
</ul>
</div>
<h2>Auth flow (hosted out-of-band OAuth, Clerk PKCE)</h2>
<figure>
<svg viewBox="0 0 820 470" width="100%" role="img" aria-label="Sequence diagram of the out-of-band OAuth flow">
<!-- lanes -->
<rect x="20" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<rect x="300" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<rect x="580" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
<text x="130" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Remote box &#8212; t3 CLI</text>
<text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop &#8212; app.t3.codes</text>
<text x="690" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Clerk</text>
<line x1="130" y1="60" x2="130" y2="450" stroke="#2a2a2a"/>
<line x1="410" y1="60" x2="410" y2="450" stroke="#2a2a2a"/>
<line x1="690" y1="60" x2="690" y2="450" stroke="#2a2a2a"/>
<!-- 1: generate + print -->
<rect x="30" y="80" width="200" height="34" rx="6" fill="#1e2a4a"/>
<text x="130" y="101" fill="#7c9cff" font-size="12.5" text-anchor="middle">1. gen verifier + challenge + state</text>
<!-- 2: user opens URL -->
<line x1="130" y1="140" x2="404" y2="140" stroke="#7c9cff" stroke-dasharray="5 4"/>
<polygon points="404,140 394,135 394,145" fill="#7c9cff"/>
<text x="267" y="132" fill="#a3a3a3" font-size="12.5" text-anchor="middle">2. user opens /connect#&#123;state,challenge&#125;</text>
<!-- 3: redirect to clerk -->
<line x1="410" y1="185" x2="684" y2="185" stroke="#e5e5e5"/>
<polygon points="684,185 674,180 674,190" fill="#e5e5e5"/>
<text x="547" y="177" fill="#a3a3a3" font-size="12.5" text-anchor="middle">3. sign in &#8594; /oauth/authorize (PKCE)</text>
<!-- 4: redirect back with code -->
<line x1="690" y1="230" x2="416" y2="230" stroke="#e5e5e5"/>
<polygon points="416,230 426,225 426,235" fill="#e5e5e5"/>
<text x="553" y="222" fill="#a3a3a3" font-size="12.5" text-anchor="middle">4. redirect /connect/callback?code&amp;state</text>
<!-- 5: page shows code -->
<rect x="310" y="252" width="200" height="34" rx="6" fill="#14301e"/>
<text x="410" y="273" fill="#4ade80" font-size="12.5" text-anchor="middle">5. shows account + authorization code</text>
<!-- 6: user enters code -->
<line x1="410" y1="316" x2="136" y2="316" stroke="#7c9cff" stroke-dasharray="5 4"/>
<polygon points="136,316 146,311 146,321" fill="#7c9cff"/>
<text x="273" y="308" fill="#a3a3a3" font-size="12.5" text-anchor="middle">6. user enters code in terminal</text>
<!-- 7: token exchange -->
<line x1="130" y1="360" x2="684" y2="360" stroke="#e5e5e5"/>
<polygon points="684,360 674,355 674,365" fill="#e5e5e5"/>
<text x="407" y="352" fill="#a3a3a3" font-size="12.5" text-anchor="middle">7. POST /oauth/token &#123;code + verifier&#125; &#8594; access/refresh tokens</text>
<!-- 8: done -->
<rect x="30" y="392" width="200" height="46" rx="6" fill="#14301e"/>
<text x="130" y="411" fill="#4ade80" font-size="12.5" text-anchor="middle">8. store token, set desired link,</text>
<text x="130" y="427" fill="#4ade80" font-size="12.5" text-anchor="middle">install relay client &#8594; Connected!</text>
</svg>
<figcaption>The verifier never leaves the box (steps 1&#8594;7), so the authorization code is worthless if observed. state/challenge ride the URL fragment &mdash; they are not secrets.</figcaption>
</figure>
<div class="card">
<h3>Details that keep it simple</h3>
<ul>
<li><strong>Stateless URL, no short-link service.</strong> The <code>/connect</code> page reads <code>state</code> + <code>code_challenge</code> from the URL fragment and builds the Clerk authorize URL client-side. ~100-char URL &mdash; fine to transfer into an SSH session.</li>
<li><strong>State check without a backend:</strong> the callback page displays one authorization blob of <code>code.state</code>; the CLI splits it and verifies <code>state</code> matches what it generated. One line on each side, preserves the loopback flow's CSRF check.</li>
<li><strong>Phishing is addressed with copy, not code:</strong> the callback page shows <em>which account</em> is being connected ("Connecting as theo@&hellip;") and warns: <em>"Only enter this code in a terminal session you started yourself."</em> No mechanism needed.</li>
<li><strong>Code expiry is a non-issue:</strong> Clerk auth codes live 10 minutes &mdash; the same timeout the existing loopback flow already uses. Wrong/expired code &#8594; friendly retry that reprints the URL.</li>
<li><strong>One external config step:</strong> register <code>https://app.t3.codes/connect/callback</code> as an allowed redirect URI on the existing Clerk CLI OAuth client. No new client, no new scopes.</li>
</ul>
</div>
<h2>The phases (one PR, one commit each)</h2>
<p class="kv">Ordering is dependency order: each phase is independently revertable and the tree is green at every boundary. Phases 1&ndash;3 are the PR; phase 4 ships separately later.</p>
<table>
<tr><th style="width:1%">Phase</th><th>Scope</th><th>Files</th><th style="width:1%">~LOC</th></tr>
<tr>
<td><span class="pill core">1</span></td>
<td><strong>Hosted code page</strong> (web-only, purely additive, zero risk). Two static routes modeled on <code>pair.tsx</code>: <code>/connect</code> (ensure Clerk session, then client-side redirect to authorize &mdash; it's a static SPA, no server 302) and <code>/connect/callback</code> (validate params, show account + copyable code + safety warning). Both routes guard against non-hosted deployments &mdash; redirect to <code>/</code> unless <code>isHostedStaticApp()</code>, same pattern as <code>pair.tsx</code>, since this bundle also ships in local instances. Plus the Clerk dashboard redirect-URI entry.</td>
<td><code>apps/web/src/routes/connect.tsx</code><br><code>apps/web/src/routes/connect.callback.tsx</code></td>
<td>~200</td>
</tr>
<tr>
<td><span class="pill core">2</span></td>
<td><strong>CLI out-of-band OAuth flow + single command.</strong> Add an out-of-band OAuth login path to <code>CliTokenManager</code> (print URL, <code>Prompt.text</code> for the code, reuse <code>exchangeToken</code>). Make bare <code>t3 connect</code> a handler = login + link (subcommands untouched). Auto-pick headless mode inside SSH sessions (<code>SSH_CONNECTION</code>/<code>SSH_TTY</code> &mdash; nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop &mdash; no regression.</td>
<td><code>cloud/CliTokenManager.ts</code> (+60)<br><code>cloud/publicConfig.ts</code> (+10)<br><code>cli/connect.ts</code> (+60)</td>
<td>~150</td>
</tr>
<tr>
<td><span class="pill new">3</span></td>
<td><strong>Background on boot &mdash; Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/&lt;v&gt;</code> + <code>current</code> symlink, systemd <em>user</em> unit with absolute node/t3 paths, <code>enable-linger</code>. y/n prompt at the end of <code>connect</code>; teardown in <code>logout</code>. Install and service-start failures must land in a log file (under <code>~/.t3/userdata/logs/</code>) whose path is printed at connect time &mdash; systemd user units fail invisibly otherwise. Unit-file generation is pure string-building &#8594; trivially testable. macOS launchd / Windows follow as 3b/3c only if wanted.</td>
<td><code>cloud/bootService.ts</code> (new)<br><code>cli/connect.ts</code> (+prompt/teardown)</td>
<td>~250</td>
</tr>
<tr>
<td><span class="pill later">4</span></td>
<td><strong>Web-triggered update</strong> (optional follow-up PR; not part of this one, not needed for the core UX). Web detects <code>daemon version &lt; latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command &mdash; client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified &mdash; that would be RCE). Stage install &#8594; verify &#8594; atomic symlink swap &#8594; <code>systemctl --user restart</code>. Progress streams reuse the <code>RelayClientInstallProgressEvent</code> pattern.</td>
<td>web banner + one control command + daemon update routine</td>
<td>later</td>
</tr>
</table>
<h3>Runtime layout (phase 3)</h3>
<pre><code>~/.t3/runtime/
├── versions/0.0.27/ &larr; npm install --prefix (gets native deps right: node-pty etc.)
└── current -> versions/0.0.27
~/.config/systemd/user/t3code.service &larr; ExecStart=/abs/path/node .../current/.../t3 serve
loginctl enable-linger $USER &larr; survives SSH logout / reboot</code></pre>
<p class="kv">Why a real <code>npm install</code> and not "reuse the npx binary": the npx cache is ephemeral and <code>t3</code> ships native deps (<code>node-pty</code>, <code>@ff-labs/fff-node</code>) that need per-platform prebuilds. Why pinned and not <code>npx t3@latest</code> in the unit: a boot-time registry fetch means the box may simply not come up (network down, PATH-less systemd env, nvm). Deterministic boot; updates happen out-of-band (phase 4 follow-up) or by re-running <code>npx t3 connect</code>.</p>
<h2>Explicitly not doing</h2>
<ul>
<li><span class="no">&#10007;</span> Relay / <code>infra</code> / contracts changes &mdash; none, in any phase</li>
<li><span class="no">&#10007;</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) &mdash; only matters for hand-typing; revisit if ever needed</li>
<li><span class="no">&#10007;</span> RFC 8628 device grant &mdash; wrong UX direction, unverified Clerk support</li>
<li><span class="no">&#10007;</span> Auto-update loop in the daemon &mdash; web-triggered only (phase 4 follow-up), user stays in control</li>
<li><span class="no">&#10007;</span> Project auto-registration &mdash; workspace assumed set up; the web UI handles the rest</li>
<li><span class="no">&#10007;</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
</ul>
<h2>Risks &amp; checks</h2>
<ul>
<li><span class="warn">&#9888;</span> <strong>Clerk redirect URI:</strong> confirm the CLI OAuth client accepts the hosted redirect and that the token endpoint honors PKCE exchange for codes issued to it. Verify in staging before the phase 2 commit. <em>(Only external dependency in the plan.)</em></li>
<li><span class="warn">&#9888;</span> <strong>systemd user env is minimal:</strong> always write absolute paths for node + t3 into the unit; never rely on PATH. Service failures are invisible by default &mdash; hence the phase 3 requirement to log to a printed file path.</li>
<li><span class="warn">&#9888;</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on &mdash; that's the feature, but say it.</li>
<li><span class="ok">&#10003;</span> Re-running <code>connect</code> when linked &#8594; idempotent: refresh token, re-confirm service, done.</li>
</ul>
<h2>Decision log</h2>
<ul class="kv">
<li>Auth: hosted out-of-band OAuth redirect on Clerk PKCE (not relay-brokered pairing, not device grant) &mdash; chosen for minimal new surface.</li>
<li>URL: stateless static page, no backend short-link.</li>
<li>Service: real per-user login service (systemd user + linger first); detect + offer install, never silent.</li>
<li>Binary: pinned managed runtime under <code>~/.t3</code>; interactive <code>npx</code> usage untouched.</li>
<li>Updates: not always-latest; web UI surfaces available updates with one-click trigger (phase 4 follow-up).</li>
<li>Delivery: one PR with a commit per phase (green tree at every boundary), not separate PRs.</li>
<li>Workspace: assumed already set up; no auto-registration.</li>
</ul>
</main>
</body>
</html>
+3 -3
View File
@@ -236,7 +236,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("logs in to headless connect without enabling access", () =>
it.effect("accepts the --headless login override without enabling access", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
@@ -254,7 +254,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
);
const login = yield* captureStdout(
runConnectCli(["connect", "login", "--base-dir", baseDir]),
runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),
);
const status = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
@@ -265,7 +265,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
readonly authenticated: boolean;
};
assert.equal(login.output, "Signed in to T3 Connect.");
assert.equal(login.output, "✓ Signed in");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
+42
View File
@@ -1,19 +1,45 @@
import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Terminal from "effect/Terminal";
import {
acquireRelayClientForLink,
formatHeadlessAuthorizationPrompt,
formatRelayClientReady,
headlessSessionConfig,
isPublishAgentActivityEnabledValue,
recoverBootServiceOffer,
reportCloudDisconnectResults,
} from "./connect.ts";
it("explains how to complete headless authorization", () => {
assert.equal(
formatHeadlessAuthorizationPrompt("https://example.test/connect"),
[
"Headless authorization",
"Open this URL on a device with a browser:",
" https://example.test/connect",
"",
"After signing in, return here and enter the code shown in your browser.",
].join("\n"),
);
});
it("formats relay readiness without printing its installation path", () => {
assert.equal(formatRelayClientReady("2026.5.2"), "✓ Relay client ready · cloudflared 2026.5.2");
});
const readHeadlessSessionConfig = (env: Record<string, string>) =>
headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));
const managedExecutable = {
status: "available",
executablePath: "/tmp/cloudflared",
@@ -21,6 +47,22 @@ const managedExecutable = {
version: RelayClient.CLOUDFLARED_VERSION,
} as const;
it.effect("detects headless operation from individual SSH config values", () =>
Effect.gen(function* () {
assert.isFalse(yield* readHeadlessSessionConfig({}));
assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" }));
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" }));
assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" }));
}),
);
it.effect("treats cancelling optional background setup as a successful skip", () =>
Effect.gen(function* () {
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
assert.isFalse(result);
}),
);
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
+245 -56
View File
@@ -6,9 +6,12 @@ import {
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Terminal from "effect/Terminal";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -16,6 +19,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
@@ -25,8 +29,10 @@ import {
} from "effect/unstable/http";
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import packageJson from "../../package.json" with { type: "json" };
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as BootService from "../cloud/bootService.ts";
import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import {
@@ -38,6 +44,8 @@ import { relayUrlConfig } from "../cloud/publicConfig.ts";
import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import * as ProcessRunner from "../processRunner.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -46,6 +54,81 @@ const jsonFlag = Flag.boolean("json").pipe(
Flag.withDefault(false),
);
const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
const headlessFlag = Flag.boolean("headless").pipe(
Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
Flag.withDefault(false),
);
/**
* Inside an SSH session there is no local browser to complete the loopback
* OAuth callback, so out-of-band OAuth is the only flow that can work.
*/
export const headlessSessionConfig = Config.all({
sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
sshTty: Config.string("SSH_TTY").pipe(Config.option),
}).pipe(
Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
);
const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
},
);
export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
return [
"Headless authorization",
"Open this URL on a device with a browser:",
` ${authorizeUrl}`,
"",
"After signing in, return here and enter the code shown in your browser.",
].join("\n");
}
/** Returns the connected account identity, if the flow could determine one. */
const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
readonly headless: boolean;
}) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
if (!useOutOfBandOAuth) {
const authorization = yield* tokens.get;
if (authorization._tag === "Authorized") {
return authorization.token.identity ?? null;
}
yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
}
// A stored credential whose refresh fails (revoked, expired grant) must
// fall through to a fresh out-of-band authorization, not dead-end the command.
const existing = yield* tokens.getExisting.pipe(
Effect.catchTag("CloudCliCredentialRefreshError", () =>
Console.log(
"The stored T3 Connect credential could not be refreshed; signing in again.",
).pipe(Effect.as(Option.none())),
),
);
if (Option.isSome(existing)) {
return existing.value.identity ?? null;
}
const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
promptForOutOfBandOAuthCode,
).pipe(
Effect.mapError((cause) =>
// Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
// cancels quietly instead of dumping an authorization error.
Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
? cause
: new CliTokenManager.CloudCliAuthorizationError({ cause }),
),
);
yield* tokens.store(token);
return identity;
});
function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
@@ -313,6 +396,21 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (options.clearAuthorization) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.clear;
// uninstall itself no-ops when nothing is installed (and on non-Linux),
// so no status pre-check that could mask a real removal failure.
const bootService = yield* BootService.BootService;
yield* bootService.uninstall.pipe(
Effect.tap((removed) =>
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
),
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
Effect.catch((error) =>
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
Effect.as(false),
),
),
);
}
yield* reportCloudDisconnectResults({
@@ -326,7 +424,7 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
}
});
const runCloudCommand = <A, E>(
const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
flags: { readonly baseDir: Option.Option<string> },
run: Effect.Effect<
A,
@@ -335,6 +433,8 @@ const runCloudCommand = <A, E>(
| CliTokenManager.CloudCliTokenManager
| RelayClient.RelayClient
| EnvironmentAuth.EnvironmentAuth
| BootService.BootService
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Prompt.Environment
@@ -344,37 +444,79 @@ const runCloudCommand = <A, E>(
options?: {
readonly quietLogs?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
const runtimeLayer = Layer.mergeAll(
ServerSecretStore.layer,
CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
const runtimeLayer = Layer.mergeAll(
ServerSecretStore.layer,
CliTokenManager.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ExternalLauncher.layer),
),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
BootService.layer({
baseDir: config.baseDir,
logsDir: config.logsDir,
cliVersion: packageJson.version,
}).pipe(Layer.provide(ProcessRunner.layer)),
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
);
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
export function formatRelayClientReady(version: string): string {
return `✓ Relay client ready · cloudflared ${version}`;
}
const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
readonly headless: boolean;
readonly publishOnly?: boolean;
}) {
const publishOnly = options.publishOnly ?? false;
if (!publishOnly) {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
confirmRelayClientInstall,
reportRelayClientInstallProgress,
);
return yield* run.pipe(Effect.provide(runtimeLayer));
});
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return null;
}
yield* Console.log(formatRelayClientReady(installed.value.version));
}
const identity = yield* authorizeCli(options);
yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
if (publishOnly) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
}
return { identity } as const;
});
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
headless: headlessFlag,
}).pipe(
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Connect.");
yield* Console.log("T3 Connect\n");
const identity = yield* authorizeCli(flags);
yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
}),
),
),
@@ -382,6 +524,7 @@ const connectLoginCommand = Command.make("login", {
const connectLinkCommand = Command.make("link", {
...projectLocationFlags,
headless: headlessFlag,
publishOnly: Flag.boolean("publish-only").pipe(
Flag.withDescription(
"Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
@@ -394,41 +537,15 @@ const connectLinkCommand = Command.make("link", {
runCloudCommand(
flags,
Effect.gen(function* () {
// A publish-only link needs no Cloudflare tunnel, so skip installing the
// relay client entirely.
if (!flags.publishOnly) {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
confirmRelayClientInstall,
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return;
}
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
yield* Console.log(
`Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
flags.publishOnly
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`,
);
}
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(
true,
flags.publishOnly ? "publish_only" : "managed",
);
if (flags.publishOnly) {
// A publish-only link exists solely to publish; without the publish
// flag the link would be inert and the success message a lie.
const secrets = yield* ServerSecretStore.ServerSecretStore;
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
}
yield* Console.log(
flags.publishOnly
? "This environment will publish agent activity to your mobile clients the next time T3 starts (no managed tunnel)."
: "This T3 environment will be available through T3 Connect the next time T3 starts.",
);
}),
),
),
@@ -566,8 +683,80 @@ const connectLogoutCommand = Command.make("logout", {
),
);
export const connectCommand = Command.make("connect").pipe(
Command.withDescription("Manage headless T3 Connect access."),
const offerBootService = Effect.gen(function* () {
const bootService = yield* BootService.BootService;
const { supported, installed, current } = yield* bootService.status;
if (!supported) {
// Don't prompt for something that can only fail; background setup is
// Linux/systemd-only for now.
return false;
}
if (installed && current) {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code background service is from an older setup. Update it now?"
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
if (!wanted) {
return false;
}
const plan = yield* bootService.install;
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
return true;
});
export const recoverBootServiceOffer = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
) =>
offer.pipe(
Effect.catchTags({
QuitError: () => Effect.succeed(false),
BootServiceUnsupportedError: (error) =>
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
BootServiceCommandError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
export const connectCommand = Command.make("connect", {
...projectLocationFlags,
headless: headlessFlag,
}).pipe(
Command.withDescription("Set up T3 Connect for this machine."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (!linked) {
return;
}
// Show which account was linked so an unexpected identity (an
// authorization code for a different account) is visible before the
// machine is brought online.
yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`);
// Connect itself already succeeded; a boot-service failure must not
// fail the command, just tell the user what happened and move on.
const background = yield* recoverBootServiceOffer(offerBootService);
yield* Console.log(
background
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
: "\nNext\n Start the server with `t3 serve` to make this machine reachable.",
);
}),
),
),
Command.withSubcommands([
connectLoginCommand,
connectLinkCommand,
@@ -0,0 +1,264 @@
import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as CliTokenManager from "./CliTokenManager.ts";
import type { OutOfBandOAuthPromptInput } from "./CliTokenManager.ts";
// pk_test_<base64 of "clerk.example.test$">
const TEST_ENV = {
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test",
T3CODE_HOSTED_APP_URL: "https://hosted.example.test",
};
interface RecordedTokenRequest {
readonly url: string;
readonly params: URLSearchParams;
}
// A JWT whose payload claims { email: "[email protected]" } (signature is not
// verified — the CLI only reads the claim to display the connected account).
const TestIdTokenHeaderJson = Schema.fromJsonString(Schema.Struct({ alg: Schema.Literal("none") }));
const TestIdTokenPayloadJson = Schema.fromJsonString(Schema.Struct({ email: Schema.String }));
const encodeTestIdTokenHeader = Schema.encodeSync(TestIdTokenHeaderJson);
const encodeTestIdTokenPayload = Schema.encodeSync(TestIdTokenPayloadJson);
const idTokenWithEmail = (() => {
const header = Encoding.encodeBase64Url(encodeTestIdTokenHeader({ alg: "none" }));
const payload = Encoding.encodeBase64Url(
encodeTestIdTokenPayload({ email: "[email protected]" }),
);
return `${header}.${payload}.`;
})();
const TestTokenResponseJson = Schema.fromJsonString(
Schema.Struct({
access_token: Schema.String,
refresh_token: Schema.String,
id_token: Schema.String,
expires_in: Schema.Number,
token_type: Schema.String,
}),
);
const encodeTestTokenResponse = Schema.encodeSync(TestTokenResponseJson);
const makeTokenEndpointLayer = (
requests: Array<RecordedTokenRequest>,
options?: { readonly idToken?: string },
) =>
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.sync(() => {
const body =
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
requests.push({ url: request.url, params: new URLSearchParams(body) });
return HttpClientResponse.fromWeb(
request,
new Response(
encodeTestTokenResponse({
access_token: "access-token-1",
refresh_token: "refresh-token-1",
id_token: options?.idToken ?? idTokenWithEmail,
expires_in: 3600,
token_type: "bearer",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}),
),
);
const provideTestEnv = Effect.provide(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV })),
);
const isAuthorizationError = Schema.is(CliTokenManager.CloudCliAuthorizationError);
class PromptRejectedError extends Schema.TaggedErrorClass<PromptRejectedError>()(
"PromptRejectedError",
{ message: Schema.String },
) {}
it("formats loopback authorization with a headless-host fallback", () => {
assert.equal(
CliTokenManager.formatLoopbackAuthorizationPrompt("https://clerk.example.test/authorize"),
[
"Open this URL to authorize T3 Connect:",
" https://clerk.example.test/authorize",
"",
"Press \u001b[1mEnter\u001b[22m to open it in your browser.",
"No browser on this device? Press \u001b[1mH\u001b[22m to switch to headless mode.",
].join("\n"),
);
});
const makeTestTerminal = (queue: Queue.Queue<Terminal.UserInput>) =>
Terminal.make({
columns: Effect.succeed(80),
rows: Effect.succeed(24),
readInput: Effect.succeed(Queue.asDequeue(queue)),
readLine: Effect.never,
display: () => Effect.void,
});
const userInput = (name: string): Terminal.UserInput => ({
input: Option.some(name),
key: { name, ctrl: false, meta: false, shift: name !== name.toLowerCase() },
});
it.effect("opens the browser on Enter and switches the active flow on H", () =>
Effect.gen(function* () {
const queue = yield* Queue.make<Terminal.UserInput>();
yield* Queue.offerAll(queue, [userInput("enter"), userInput("H")]);
const opened: Array<string> = [];
const result = yield* CliTokenManager.waitForLoopbackAuthorization({
authorizationUrl: "https://clerk.example.test/authorize",
callback: Effect.never,
terminal: makeTestTerminal(queue),
launchBrowser: (url) =>
Effect.sync(() => {
opened.push(url);
}),
});
assert.deepEqual(opened, ["https://clerk.example.test/authorize"]);
assert.deepEqual(result, { _tag: "HeadlessRequested" });
}),
);
it.effect("finishes normally when the browser callback wins", () =>
Effect.gen(function* () {
const queue = yield* Queue.make<Terminal.UserInput>();
const callback = yield* Deferred.make<string>();
yield* Deferred.succeed(callback, "clerk-code-123");
const result = yield* CliTokenManager.waitForLoopbackAuthorization({
authorizationUrl: "https://clerk.example.test/authorize",
callback: Deferred.await(callback),
terminal: makeTestTerminal(queue),
launchBrowser: () => Effect.die("browser launch should not run"),
});
assert.deepEqual(result, { _tag: "AuthorizationCode", code: "clerk-code-123" });
}),
);
it.layer(NodeServices.layer)("CliTokenManager.outOfBandOAuthLogin", (it) => {
it.effect("prints a hosted authorize URL and exchanges the out-of-band code with PKCE", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
let seenAuthorizeUrl = "";
const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
({ authorizeUrl, validate }: OutOfBandOAuthPromptInput) =>
Effect.gen(function* () {
seenAuthorizeUrl = authorizeUrl;
const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
assert.isNotNull(request);
return yield* validate(`clerk-code-123.${request!.state}`).pipe(
Effect.mapError((message) => new PromptRejectedError({ message })),
);
}),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv);
const authorizeUrl = new URL(seenAuthorizeUrl);
assert.equal(authorizeUrl.origin, "https://hosted.example.test");
assert.equal(authorizeUrl.pathname, "/connect");
const request = readConnectAuthorizeRequest(authorizeUrl);
assert.isNotNull(request);
assert.match(request!.state, /^[A-Za-z0-9_-]{22}$/);
assert.equal(token.accessToken, "access-token-1");
assert.equal(token.refreshToken, "refresh-token-1");
assert.equal(token.identity, "[email protected]");
// The id_token's email claim is surfaced so connect can show the account.
assert.equal(identity, "[email protected]");
assert.lengthOf(requests, 1);
const exchange = requests[0]!;
assert.equal(exchange.url, "https://clerk.example.test/oauth/token");
assert.equal(exchange.params.get("grant_type"), "authorization_code");
assert.equal(exchange.params.get("code"), "clerk-code-123");
assert.equal(
exchange.params.get("redirect_uri"),
"https://hosted.example.test/connect/callback",
);
assert.equal(exchange.params.get("client_id"), "oauth_client_test");
// The verifier must hash to the challenge advertised in the authorize URL.
const verifier = exchange.params.get("code_verifier");
assert.isNotNull(verifier);
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier!));
assert.equal(Encoding.encodeBase64Url(digest), request!.challenge);
}),
);
it.effect("rejects out-of-band codes whose state does not match the request", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const validationErrors: Array<string> = [];
const result = yield* CliTokenManager.outOfBandOAuthLogin(
({ validate }: OutOfBandOAuthPromptInput) =>
validate("clerk-code-123.wrong-state").pipe(
Effect.tapError((message) => Effect.sync(() => validationErrors.push(message))),
Effect.mapError((message) => new PromptRejectedError({ message })),
),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
assert.lengthOf(requests, 0);
assert.lengthOf(validationErrors, 1);
assert.include(validationErrors[0], "different connect request");
assert.instanceOf(result, PromptRejectedError);
}),
);
it.effect("ignores an id_token whose claims are not valid JSON", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const malformedIdToken = `header.${Encoding.encodeBase64Url("not-json")}.signature`;
const { identity } = yield* CliTokenManager.outOfBandOAuthLogin(
({ authorizeUrl }: OutOfBandOAuthPromptInput) => {
const request = readConnectAuthorizeRequest(new URL(authorizeUrl));
assert.isNotNull(request);
return Effect.succeed(`clerk-code-123.${request!.state}`);
},
).pipe(
Effect.provide(makeTokenEndpointLayer(requests, { idToken: malformedIdToken })),
provideTestEnv,
);
assert.isNull(identity);
assert.lengthOf(requests, 1);
}),
);
it.effect("fails without touching the token endpoint when the prompt returns garbage", () =>
Effect.gen(function* () {
const requests: Array<RecordedTokenRequest> = [];
const result = yield* CliTokenManager.outOfBandOAuthLogin(() =>
Effect.succeed("not-a-connect-code"),
).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);
assert.lengthOf(requests, 0);
assert.isTrue(isAuthorizationError(result));
}),
);
});
+284 -69
View File
@@ -3,6 +3,7 @@ import * as NodeHttp from "node:http";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as Clock from "effect/Clock";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -12,8 +13,10 @@ import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Terminal from "effect/Terminal";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
@@ -21,19 +24,105 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import {
cloudCliOAuthConfig,
hostedAppUrlConfig,
type CloudCliOAuthConfig,
} from "./publicConfig.ts";
import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;
export function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {
return [
"Open this URL to authorize T3 Connect:",
` ${authorizationUrl}`,
"",
`Press ${boldTerminalText("Enter")} to open it in your browser.`,
`No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,
].join("\n");
}
export type LoopbackAuthorizationResult =
| { readonly _tag: "AuthorizationCode"; readonly code: string }
| { readonly _tag: "HeadlessRequested" };
const readLoopbackAuthorizationAction = Effect.fn(
"cloud.cli_token.read_loopback_authorization_action",
)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {
while (true) {
const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));
const keyName = event.key.name.toLowerCase();
if (!event.key.ctrl && !event.key.meta && keyName === "h") {
return "headless" as const;
}
if (keyName === "enter" || keyName === "return") {
return "open-browser" as const;
}
}
});
export const waitForLoopbackAuthorization = Effect.fn(
"cloud.cli_token.wait_for_loopback_authorization",
)(function* <E, R>(input: {
readonly authorizationUrl: string;
readonly callback: Effect.Effect<string, E, R>;
readonly terminal: Terminal.Terminal;
readonly launchBrowser: (
url: string,
) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;
}) {
return yield* Effect.scoped(
Effect.gen(function* () {
const terminalInput = yield* input.terminal.readInput;
while (true) {
const result = yield* Effect.raceFirst(
input.callback.pipe(
Effect.map(
(code): LoopbackAuthorizationResult => ({ _tag: "AuthorizationCode", code }),
),
),
readLoopbackAuthorizationAction(terminalInput),
);
if (typeof result !== "string") {
return result;
}
if (result === "headless") {
return { _tag: "HeadlessRequested" } as const;
}
yield* input
.launchBrowser(input.authorizationUrl)
.pipe(
Effect.catch(() =>
Console.warn(
`Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,
),
),
);
}
}),
);
});
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
refreshToken: Schema.String,
expiresAtEpochMs: Schema.Number,
identity: Schema.optional(Schema.String),
});
type PersistedToken = typeof PersistedToken.Type;
export type PersistedToken = typeof PersistedToken.Type;
const PersistedTokenJson = Schema.fromJsonString(PersistedToken);
const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);
@@ -42,10 +131,39 @@ const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);
const OAuthTokenResponse = Schema.Struct({
access_token: Schema.String,
refresh_token: Schema.optional(Schema.String),
id_token: Schema.optional(Schema.String),
expires_in: Schema.Number,
token_type: Schema.String,
});
const OidcIdentityClaimsJson = Schema.fromJsonString(
Schema.Struct({
email: Schema.optional(Schema.String),
preferred_username: Schema.optional(Schema.String),
sub: Schema.optional(Schema.String),
}),
);
const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);
/**
* Best-effort read of the `email` (or fallback) claim from an OIDC id_token.
* Only used to show the operator which account they linked, so a malformed
* token degrades to "no identity" rather than an error.
*/
function idTokenIdentity(idToken: string | undefined): string | null {
if (!idToken) return null;
const payload = idToken.split(".")[1];
if (!payload) return null;
const decoded = Encoding.decodeBase64UrlString(payload);
if (decoded._tag !== "Success") return null;
const claims = decodeOidcIdentityClaimsJson(decoded.success);
if (Option.isNone(claims)) return null;
for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {
if (typeof value === "string" && value.length > 0) return value;
}
return null;
}
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{ cause: Schema.Defect() },
@@ -103,18 +221,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly get: Effect.Effect<
| { readonly _tag: "Authorized"; readonly token: PersistedToken }
| { readonly _tag: "HeadlessRequested" },
CloudCliTokenManagerError | Terminal.QuitError
>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
}
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
const wrapError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -123,10 +241,101 @@ function bytesToString(value: Uint8Array): string {
return new TextDecoder().decode(value);
}
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
params: Record<string, string>,
) {
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
);
const now = yield* Clock.currentTimeMillis;
const identity = idTokenIdentity(response.id_token);
return {
token: {
accessToken: response.access_token,
refreshToken: response.refresh_token ?? params.refresh_token ?? "",
expiresAtEpochMs: now + response.expires_in * 1_000,
...(identity === null ? {} : { identity }),
} satisfies PersistedToken,
identity,
};
});
const makePkceRequest = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16));
return { verifier, challenge, state };
});
export interface OutOfBandOAuthPromptInput {
readonly authorizeUrl: string;
readonly validate: (value: string) => Effect.Effect<string, string>;
}
/**
* Out-of-band OAuth for machines without a local browser (SSH). The user
* opens the hosted /connect URL elsewhere, signs in, and enters the displayed
* code in this terminal. The PKCE verifier never leaves this process, so the
* authorization code is useless to an observer, and the state bundled into
* the blob preserves the loopback flow's CSRF check.
*/
export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* <
E,
R,
>(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const authorizationCode = yield* promptForCode({
authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),
validate: (value) => {
const checked = checkConnectAuthCode(value, state);
return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value);
},
}).pipe(
// Clerk authorization codes expire on this horizon anyway; matching the
// loopback flow's timeout turns an abandoned prompt into a clear error.
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
);
// promptForCode is caller-supplied, so re-check the returned value rather
// than trusting that the prompt ran validate.
const authCode = checkConnectAuthCode(authorizationCode, state);
if (typeof authCode === "string") {
return yield* new CloudCliAuthorizationError({ cause: authCode });
}
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code: authCode.code,
redirect_uri: connectCallbackUrl(hostedAppUrl),
client_id: metadata.clientId,
code_verifier: verifier,
});
});
export const make = Effect.gen(function* () {
// Capture exactly the services the login/refresh flows need at build time
// (matching the behavior before the out-of-band flow captured the instances), not
// the whole ambient context.
const crypto = yield* Crypto.Crypto;
const httpClient = yield* HttpClient.HttpClient;
const services = Context.make(Crypto.Crypto, crypto).pipe(
Context.add(HttpClient.HttpClient, httpClient),
);
const secrets = yield* ServerSecretStore.ServerSecretStore;
const terminal = yield* Terminal.Terminal;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const semaphore = yield* Semaphore.make(1);
const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
const encoded = yield* encodePersistedToken(token);
@@ -136,7 +345,7 @@ export const make = Effect.gen(function* () {
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
.pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -144,39 +353,21 @@ export const make = Effect.gen(function* () {
return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));
});
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
metadata: CloudCliOAuthConfig,
params: Record<string, string>,
) {
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),
);
const now = yield* Clock.currentTimeMillis;
return {
accessToken: response.access_token,
refreshToken: response.refresh_token ?? params.refresh_token ?? "",
expiresAtEpochMs: now + response.expires_in * 1_000,
} satisfies PersistedToken;
});
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
const metadata = yield* cloudCliOAuthConfig;
return yield* exchangeToken(metadata, {
const { token: refreshed } = yield* exchangeToken(metadata, {
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: metadata.clientId,
});
return refreshed.identity === undefined && token.identity !== undefined
? { ...refreshed, identity: token.identity }
: refreshed;
});
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
"GET",
@@ -191,14 +382,7 @@ export const make = Effect.gen(function* () {
});
}
yield* Deferred.succeed(callback, code);
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Connect authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
`;
return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());
}),
);
yield* HttpRouter.serve(callbackRoute, {
@@ -214,32 +398,37 @@ export const make = Effect.gen(function* () {
),
Layer.build,
);
const authorizationUrl = new URL(metadata.authorizationEndpoint);
authorizationUrl.searchParams.set("client_id", metadata.clientId);
authorizationUrl.searchParams.set("redirect_uri", metadata.redirectUri);
authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("scope", metadata.scopes.join(" "));
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(
new CloudCliAuthorizationTimeoutError({
cause,
}),
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
state,
challenge,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
authorizationUrl,
callback: Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
),
);
return yield* exchangeToken(metadata, {
terminal,
launchBrowser: externalLauncher.launchBrowser,
});
if (authorization._tag === "HeadlessRequested") {
return authorization;
}
const { token } = yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code,
code: authorization.code,
redirect_uri: metadata.redirectUri,
client_id: metadata.clientId,
code_verifier: verifier,
});
return { _tag: "Authorized", token } as const;
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
@@ -253,24 +442,50 @@ export const make = Effect.gen(function* () {
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
getExistingNoLock().pipe(
Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
Effect.provide(services),
),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),
),
);
const get = semaphore.withPermits(1)(
Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
// A stored credential that can't be read or refreshed (corrupt, revoked,
// expired grant) must fall through to a fresh login rather than dead-end
// the command — authorizeCli applies the same fallback to out-of-band
// authorization.
const token = yield* getExistingNoLock().pipe(
Effect.orElseSucceed(() => Option.none<PersistedToken>()),
);
if (Option.isSome(token)) {
return { _tag: "Authorized", token: token.value } as const;
}
const authorization = yield* Effect.scoped(login());
return authorization._tag === "Authorized"
? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)
: authorization;
}).pipe(
Effect.mapError((cause) =>
Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),
),
Effect.provide(services),
),
);
const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {
yield* semaphore.withPermits(1)(
persist(token).pipe(
Effect.asVoid,
Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),
),
);
});
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });
});
export const layer = Layer.effect(CloudCliTokenManager, make);
+529
View File
@@ -0,0 +1,529 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
const isUnsupportedError = Schema.is(BootService.BootServiceUnsupportedError);
const isCommandError = Schema.is(BootService.BootServiceCommandError);
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeRecordingRunnerLayer = (
commands: Array<RecordedCommand>,
options?: {
readonly failCommand?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
},
) =>
Layer.succeed(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
assert.isUndefined(input.env);
commands.push({ command: input.command, args: input.args });
const failed =
input.command === options?.failCommand ||
options?.failWhen?.(input.command, input.args) === true;
return {
stdout: "",
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
);
const makeHost = (entry: string): BootService.BootServiceHost => ({
execPath: "/usr/local/bin/node",
cliEntryPath: entry,
});
const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
const makeTestContext = Effect.fn("test.makeTestContext")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
// A real file for the stable-entry cases so status can confirm the entry
// point exists.
const stableEntry = path.join(root, "bin.mjs");
yield* fs.writeFileString(stableEntry, "#!/usr/bin/env node\n");
return {
fs,
path,
dirs: {
home: root,
baseDir: path.join(root, ".t3"),
logsDir: path.join(root, ".t3", "userdata", "logs"),
stableEntry,
},
};
});
it("renders a systemd unit with absolute paths and append-mode logging", () => {
const unit = BootService.renderBootServiceUnit({
nodePath: "/usr/local/bin/node",
t3EntryPath: "/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
baseDir: "/home/theo/.t3",
logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/home/theo/.config/systemd/user/t3code.service",
});
assert.equal(
unit,
[
"[Unit]",
"Description=T3 Code server (T3 Connect)",
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
"[Service]",
"Type=simple",
"WorkingDirectory=%h",
"Environment=T3CODE_HOME=/home/theo/.t3",
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
"Restart=always",
"RestartSec=5",
"StandardOutput=append:/home/theo/.t3/userdata/logs/boot-service.log",
"StandardError=append:/home/theo/.t3/userdata/logs/boot-service.log",
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n"),
);
});
it("quotes systemd values containing spaces and escapes percent specifiers", () => {
assert.equal(BootService.quoteSystemdValue("/plain/path"), "/plain/path");
assert.equal(BootService.quoteSystemdValue("/home/me/T3 Data"), '"/home/me/T3 Data"');
assert.equal(BootService.quoteSystemdValue("/opt/100%cpu"), "/opt/100%%cpu");
const unit = BootService.renderBootServiceUnit({
nodePath: "/home/me/my tools/node",
t3EntryPath: "/home/me/T3 Data/bin.mjs",
baseDir: "/home/me/T3 Data",
logPath: "/home/me/100%logs/boot.log",
unitPath: "/home/me/.config/systemd/user/t3code.service",
});
assert.include(unit, 'ExecStart="/home/me/my tools/node" "/home/me/T3 Data/bin.mjs" serve');
assert.include(unit, 'Environment=T3CODE_HOME="/home/me/T3 Data"');
// append: paths take the rest of the line literally (spaces are fine,
// quoting is not), but % still goes through specifier expansion.
assert.include(unit, "StandardOutput=append:/home/me/100%%logs/boot.log");
assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
});
it("flags package-manager cache entry points as ephemeral", () => {
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("C:\\Users\\theo\\AppData\\npm-cache\\_npx\\abc\\bin.mjs"),
);
assert.isTrue(
BootService.isEphemeralCacheEntry(
"/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs",
),
);
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.bun/install/cache/[email protected]/dist/bin.mjs"),
);
assert.isFalse(BootService.isEphemeralCacheEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/dev/pnpm/dlx-tools/t3/node_modules/t3/dist/bin.mjs",
),
);
assert.isFalse(
BootService.isEphemeralCacheEntry(
"/home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs",
),
);
});
it.layer(NodeServices.layer)("BootService", (it) => {
it.effect("installs the unit, enables the service, and enables linger", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
// A stable entry point is reused directly — no npm install.
assert.equal(plan.t3EntryPath, dirs.stableEntry);
assert.deepEqual(
commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
"systemctl --user daemon-reload",
"systemctl --user enable t3code.service",
// restart (not enable --now) so repairing a stale unit replaces a
// running process instead of leaving the old one until reboot.
"systemctl --user restart t3code.service",
"loginctl enable-linger",
],
);
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const unit = yield* fs.readFileString(unitPath);
assert.include(unit, `ExecStart=/usr/local/bin/node ${dirs.stableEntry} serve`);
assert.include(unit, `Environment=T3CODE_HOME=${dirs.baseDir}`);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isTrue(status.current);
const removed = yield* service.uninstall;
assert.isTrue(removed);
assert.isFalse(yield* fs.exists(unitPath));
const statusAfter = yield* service.status;
assert.isFalse(statusAfter.installed);
const removedAgain = yield* service.uninstall;
assert.isFalse(removedAgain);
}),
);
it.effect("pins a runtime via npm install when running from the npx cache", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
assert.equal(
plan.t3EntryPath,
path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
);
assert.deepEqual(commands[0], {
command: "npm",
args: ["install", "--prefix", runtimeDir, "--no-fund", "--no-audit", "[email protected]"],
});
// Success is recorded via a sentinel so interrupted installs re-run.
assert.isTrue(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reinstalls a pinned runtime when its entry point is missing", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const plan = yield* service.install;
yield* fs.makeDirectory(path.dirname(plan.t3EntryPath), { recursive: true });
yield* fs.writeFileString(plan.t3EntryPath, "#!/usr/bin/env node\n");
yield* fs.remove(plan.t3EntryPath);
commands.length = 0;
yield* service.install;
assert.isTrue(commands.some(({ command }) => command === "npm"));
}),
);
it.effect("reads executable metadata from host process references", () =>
Effect.gen(function* () {
const { dirs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home),
Effect.provideService(HostProcessExecutablePath, "/opt/node/bin/node"),
Effect.provideService(HostProcessArguments, ["/opt/node/bin/node", dirs.stableEntry]),
);
const plan = yield* service.install;
assert.equal(plan.nodePath, "/opt/node/bin/node");
assert.equal(plan.t3EntryPath, dirs.stableEntry);
}),
);
it.effect("cleans up and fails when the pinned runtime install fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "npm" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
// The half-installed tree must not be reused by the next attempt.
assert.isFalse(yield* fs.exists(runtimeDir));
assert.isFalse(yield* fs.exists(path.join(runtimeDir, ".install-complete")));
}),
);
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const unitDir = path.join(dirs.home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
"[Service]\nExecStart=/old/node /old/t3 serve\n",
);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isFalse(status.current);
}),
);
it.effect("reports a current unit as stale when its entry point is gone", () =>
Effect.gen(function* () {
const { dirs, fs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
yield* service.install;
assert.isTrue((yield* service.status).current);
// The pinned runtime (or global bin) was deleted to reclaim space; the
// unit still matches byte-for-byte but would crashloop at boot.
yield* fs.remove(dirs.stableEntry);
const status = yield* service.status;
assert.isTrue(status.installed);
assert.isFalse(status.current);
}),
);
it.effect("fails on non-Linux platforms without touching the filesystem", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home, "darwin"),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isUnsupportedError(error));
assert.lengthOf(commands, 0);
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.supported);
assert.isFalse(status.installed);
}),
);
it.effect("removes the unit file when an activation step fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
// A leftover unit would make the next connect report "already set up"
// even though linger never happened.
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
const status = yield* service.status;
assert.isFalse(status.installed);
assert.isTrue(
commands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user disable --now t3code.service",
),
);
}),
);
it.effect("restores the previous unit when a repair cannot activate", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const initialCommands: Array<RecordedCommand> = [];
const initialService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(initialCommands)),
provideHostRefs(dirs.home),
);
yield* initialService.install;
const unitPath = path.join(dirs.home, ".config", "systemd", "user", "t3code.service");
const previousUnit = yield* fs.readFileString(unitPath);
const replacementEntry = path.join(dirs.home, "replacement-bin.mjs");
yield* fs.writeFileString(replacementEntry, "#!/usr/bin/env node\n");
const repairCommands: Array<RecordedCommand> = [];
const repairService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.28",
host: makeHost(replacementEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(repairCommands, { failCommand: "loginctl" })),
provideHostRefs(dirs.home),
);
const error = yield* repairService.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.equal(yield* fs.readFileString(unitPath), previousUnit);
assert.isTrue(
repairCommands.some(
({ command, args }) =>
command === "systemctl" && args.join(" ") === "--user restart t3code.service",
),
);
}),
);
it.effect("keeps the unit when stopping it during uninstall fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const installCommands: Array<RecordedCommand> = [];
const installedService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(installCommands)),
provideHostRefs(dirs.home),
);
yield* installedService.install;
const uninstallCommands: Array<RecordedCommand> = [];
const failingService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(
makeRecordingRunnerLayer(uninstallCommands, {
failWhen: (command, args) =>
command === "systemctl" && args.includes("disable") && args.includes("--now"),
}),
),
provideHostRefs(dirs.home),
);
const error = yield* failingService.uninstall.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.isTrue(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
}),
);
it.effect("appends failed steps to the boot-service log", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands, { failCommand: "systemctl" })),
provideHostRefs(dirs.home),
);
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
if (!isCommandError(error)) return;
assert.equal(error.exitCode, 1);
assert.equal(error.stderrLength, "systemctl exploded".length);
const logPath = path.join(dirs.logsDir, "boot-service.log");
assert.isTrue(yield* fs.exists(logPath));
assert.include(yield* fs.readFileString(logPath), "exit code 1");
}),
);
});
+452
View File
@@ -0,0 +1,452 @@
import * as Context from "effect/Context";
import * as Config from "effect/Config";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
/**
* Installs T3 Code as a per-user boot service so a connected machine stays
* reachable through T3 Connect after the SSH session ends. Linux-only for
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
* ephemeral and whose registry fetch at boot would make startup depend on
* the network.
*/
const BOOT_SERVICE_NAME = "t3code";
const BOOT_RUNTIME_DIR = "runtime";
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
"\\_npx\\",
"/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx)
"/.pnpm/dlx/",
"/.bun/install/cache/", // bunx
];
/**
* `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager
* caches that can be evicted at any time — a boot service must never point
* there. Global installs, repo checkouts, and the pinned runtime below are
* all stable.
*/
export function isEphemeralCacheEntry(entryPath: string): boolean {
return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment));
}
/**
* systemd expands `%` specifiers in most directive values, including the
* `append:` file paths, which take the rest of the line literally and must
* NOT be quoted.
*/
export function escapeSystemdSpecifiers(value: string): string {
return value.replaceAll("%", "%%");
}
/**
* systemd word-splits ExecStart and Environment values and expands `%`
* specifiers, so paths with spaces or percents must be quoted and escaped.
*/
export function quoteSystemdValue(value: string): string {
const escaped = escapeSystemdSpecifiers(value);
return /[\s"'\\]/.test(escaped)
? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
: escaped;
}
export interface BootServicePlan {
/** Absolute path of the node binary running this CLI. */
readonly nodePath: string;
/** Absolute path of the pinned t3 entry point the unit will run. */
readonly t3EntryPath: string;
readonly baseDir: string;
readonly logPath: string;
readonly unitPath: string;
}
/**
* Pure so it is testable byte-for-byte. systemd user units run with a
* minimal environment: every path must be absolute, and the service must
* not rely on PATH, nvm shims, or shell profiles. Failures land in
* `logPath` because `systemctl --user` failures are otherwise invisible.
*/
export function renderBootServiceUnit(plan: BootServicePlan): string {
// No After=network-online.target: it does not exist in the systemd *user*
// manager, so ordering on it is silently ignored. The server retries its
// relay connection, and Restart=always covers early-boot failures.
return [
"[Unit]",
"Description=T3 Code server (T3 Connect)",
// Give up after 5 crashes in 5 minutes so a persistently broken install
// (deleted runtime, broken workspace) stops instead of restarting every
// 5s forever and growing the unrotated append log without bound.
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
"[Service]",
"Type=simple",
"WorkingDirectory=%h",
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
`StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
"",
"[Install]",
"WantedBy=default.target",
"",
].join("\n");
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
}
}
export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
"BootServiceCommandError",
{
step: Schema.String,
exitCode: Schema.optional(Schema.Number),
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return this.exitCode === undefined
? `Background setup failed while ${this.step}.`
: `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
}
}
export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
"BootServiceInstallError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not set up the T3 Code background service.";
}
}
export type BootServiceError =
| BootServiceUnsupportedError
| BootServiceCommandError
| BootServiceInstallError;
export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
/** False when the installed unit no longer matches what install would write. */
readonly current: boolean;
readonly unitPath: string;
readonly logPath: string;
}
export class BootService extends Context.Service<
BootService,
{
/** Installs the pinned runtime + unit, enables linger, starts the service. */
readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
/**
* Stops and removes the unit; leaves the pinned runtime for reuse.
* Returns whether a unit was actually removed.
*/
readonly uninstall: Effect.Effect<boolean, BootServiceError>;
readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
}
>()("t3/cloud/bootService") {}
export interface BootServiceHost {
readonly execPath: string;
readonly cliEntryPath: string;
}
export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
readonly baseDir: string;
readonly logsDir: string;
readonly cliVersion: string;
readonly host?: BootServiceHost;
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const host = input.host ?? {
execPath: hostExecPath,
// When running the packed CLI this is dist/bin.mjs; when stable (global
// install, repo checkout) the boot service runs this same artifact.
cliEntryPath: hostArguments[1] ?? "",
};
const platform = yield* HostProcessPlatform;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const runtimeVersionDir = path.join(
input.baseDir,
BOOT_RUNTIME_DIR,
"versions",
input.cliVersion,
);
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return yield* new BootServiceUnsupportedError({ platform });
}
});
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
step: string,
command: string,
args: ReadonlyArray<string>,
options?: { readonly timeout?: Duration.Input },
) {
return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
new BootServiceCommandError({
step,
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
),
Effect.tapError((error) =>
DateTime.now.pipe(
Effect.flatMap((now) =>
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
flag: "a",
}),
),
Effect.ignore,
),
),
);
});
/**
* Ensures plannedEntryPath exists before the unit points at it. A stable
* install (global bin, repo checkout) is used as-is; an ephemeral cache
* entry is replaced by `npm install --prefix`-ing the exact running
* version into <baseDir>/runtime/versions/<v>. A real install (not a copy
* of bin.mjs) because t3 ships native deps like node-pty.
*/
const ensurePinnedRuntime = Effect.gen(function* () {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
// The sentinel is written only after npm exits 0. Checking the entry
// file alone is not enough: npm extracts files before running native
// builds (node-pty), so a killed install leaves a plausible-looking but
// broken tree behind.
const alreadyPinned = yield* Effect.all([
fs.exists(runtimeSentinelPath),
fs.exists(runtimeEntryPath),
]).pipe(
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
if (alreadyPinned) {
return;
}
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
yield* runStep(
"installing the pinned t3 runtime (this can take a few minutes)",
"npm",
[
"install",
"--prefix",
runtimeVersionDir,
"--no-fund",
"--no-audit",
`t3@${input.cliVersion}`,
],
// Native deps (node-pty) can compile from source on slow boxes; the
// ProcessRunner default of 60s would kill a healthy install.
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
).pipe(
Effect.tapError(() =>
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
),
);
yield* fs
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
});
// Where the unit will point: derivable without touching the network, so
// status can compare units purely; install materializes it first.
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
? runtimeEntryPath
: host.cliEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
t3EntryPath: plannedEntryPath,
baseDir: input.baseDir,
logPath,
unitPath,
};
const install: BootService["Service"]["install"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* ensurePinnedRuntime;
const previousUnit = yield* fs.exists(unitPath).pipe(
Effect.flatMap((exists) =>
exists
? fs.readFileString(unitPath).pipe(Effect.map(Option.some))
: Effect.succeed(Option.none<string>()),
),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
// If any activation step fails, remove the unit again: a leftover file
// would make the next `t3 connect` report the service as already set up
// even though it was never enabled or lingered.
yield* Effect.gen(function* () {
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
// restart rather than enable --now: --now does not replace an already
// running process, so repairing a stale unit would leave the old
// server running until reboot. restart also starts a stopped service.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
// Linger keeps the user manager (and this service) running without an
// open session — the whole point on a box reached over SSH. No
// username argument: loginctl defaults to the calling user, which is
// always right, while $USER can be stale (su without -l) or unset.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
}).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
// If activation fails partway (e.g. enable succeeds but restart/linger
// fails), leave nothing behind: disable removes the enable symlink, remove
// deletes the file, daemon-reload clears the stale definition — otherwise a
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
// next connect misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
) {
if (Option.isSome(previousUnit)) {
yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
} else {
yield* runStep("cleaning up the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
yield* fs.remove(unitPath).pipe(Effect.ignore);
}
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe(
Effect.ignore,
);
if (Option.isSome(previousUnit)) {
yield* runStep("restoring the previous service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore);
}
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
return false;
}
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
return true;
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
const unitExists = yield* fs.exists(unitPath);
if (!unitExists) {
return { supported: true, installed: false, current: false, unitPath, logPath };
}
const unit = yield* fs.readFileString(unitPath);
// A unit is current only if it matches what install would write now (an
// older CLI wrote a different runtime/node path) AND the entry point it
// references still exists (a pinned runtime under ~/.t3 can be deleted to
// reclaim space). Either mismatch makes connect offer a repair.
const entryExists = yield* fs.exists(plannedEntryPath);
const current = unit === renderBootServiceUnit(plan) && entryExists;
return { supported: true, installed: true, current, unitPath, logPath };
}).pipe(
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
Effect.withSpan("cloud.boot_service.status"),
);
return BootService.of({ install, uninstall, status });
});
export const layer = (input: {
readonly baseDir: string;
readonly logsDir: string;
readonly cliVersion: string;
readonly host?: BootServiceHost;
}) => Layer.effect(BootService, make(input));
+13
View File
@@ -0,0 +1,13 @@
import { expect, it } from "@effect/vitest";
import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";
it("renders the branded loopback authorization completion page", () => {
const html = renderLoopbackAuthorizationCompleteHtml();
expect(html).toContain("T3 Code");
expect(html).not.toContain("Secure terminal handoff");
expect(html).toContain("You're connected");
expect(html).toContain("return to the terminal");
expect(html).toContain('name="viewport"');
});
+140
View File
@@ -0,0 +1,140 @@
export function renderLoopbackAuthorizationCompleteHtml(): string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>T3 Connect authorization complete</title>
<style>
:root {
color-scheme: light dark;
font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f7f9;
color: #17191f;
}
* { box-sizing: border-box; }
body {
min-height: 100vh;
margin: 0;
display: grid;
place-items: center;
padding: 32px 16px;
background:
radial-gradient(48rem 22rem at 50% -8rem, rgba(47, 119, 235, 0.15), transparent),
#f6f7f9;
}
main {
width: min(100%, 576px);
overflow: hidden;
border: 1px solid rgba(23, 25, 31, 0.1);
border-radius: 20px;
background: rgba(255, 255, 255, 0.94);
box-shadow: 0 24px 64px rgba(16, 24, 40, 0.16);
}
.stage {
position: relative;
height: 96px;
overflow: hidden;
padding: 22px 24px;
color: white;
background: linear-gradient(145deg, #5ab8fa 0%, #347ff8 46%, #1939bd 100%);
}
.stage::before {
content: "";
position: absolute;
inset: 0;
opacity: 0.42;
background-image:
linear-gradient(rgba(234, 246, 255, 0.25) 1px, transparent 1px),
linear-gradient(90deg, rgba(234, 246, 255, 0.25) 1px, transparent 1px),
linear-gradient(rgba(234, 246, 255, 0.12) 1px, transparent 1px),
linear-gradient(90deg, rgba(234, 246, 255, 0.12) 1px, transparent 1px);
background-size: 32px 32px, 32px 32px, 8px 8px, 8px 8px;
}
.stage::after {
content: "";
position: absolute;
inset: 0;
background:
radial-gradient(circle at 78% 20%, rgba(210, 255, 255, 0.36), transparent 34%),
linear-gradient(to bottom, transparent 24%, rgba(8, 28, 89, 0.38));
}
.stage-content {
position: relative;
z-index: 1;
}
.brand {
margin: 0;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.brand { color: rgba(255, 255, 255, 0.82); }
.content { padding: 30px 32px 34px; }
.status {
width: 42px;
height: 42px;
display: grid;
place-items: center;
margin-top: -52px;
margin-bottom: 22px;
border: 4px solid white;
border-radius: 50%;
background: #2065df;
color: white;
font-size: 22px;
font-weight: 700;
box-shadow: 0 8px 22px rgba(25, 72, 177, 0.3);
}
.eyebrow {
margin: 0 0 8px;
color: #2866cc;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 { margin: 0; font-size: clamp(26px, 5vw, 34px); line-height: 1.12; letter-spacing: -0.035em; }
.description { margin: 12px 0 0; color: #646975; font-size: 15px; line-height: 1.6; }
.next {
margin-top: 24px;
padding: 14px 16px;
border: 1px solid rgba(23, 25, 31, 0.1);
border-radius: 12px;
background: #f7f8fa;
color: #454a55;
font-size: 13px;
}
.next strong { color: #17191f; }
@media (prefers-color-scheme: dark) {
:root { background: #101115; color: #f1f3f7; }
body { background: radial-gradient(48rem 22rem at 50% -8rem, rgba(55, 102, 210, 0.2), transparent), #101115; }
main { border-color: rgba(255, 255, 255, 0.1); background: rgba(25, 27, 33, 0.96); }
.status { border-color: #191b21; }
.eyebrow { color: #77a8ff; }
.description { color: #a8adb8; }
.next { border-color: rgba(255, 255, 255, 0.1); background: #20232a; color: #b9bec8; }
.next strong { color: #f1f3f7; }
}
</style>
</head>
<body>
<main>
<header class="stage">
<div class="stage-content">
<p class="brand">T3 Code</p>
</div>
</header>
<section class="content">
<div class="status" aria-hidden="true">✓</div>
<p class="eyebrow">Browser authorization complete</p>
<h1>You're connected</h1>
<p class="description">The authorization code was delivered securely to your waiting terminal.</p>
<div class="next"><strong>Next:</strong> return to the terminal to finish T3 Connect setup. You can close this window.</div>
</section>
</main>
</body>
</html>`;
}
+1
View File
@@ -200,6 +200,7 @@ describe("reconcileDesiredCloudLink", () => {
get: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
store: () => unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import {
hostedAppUrlConfig,
makeCloudCliOAuthConfig,
makeRelayUrlConfig,
resolveRelayClientTracingConfig,
@@ -47,6 +48,40 @@ it.effect("rejects an injected relay URL with a non-origin path", () =>
makeRelayUrlConfig("https://embedded.example.test/path").pipe(provideEnv({}), Effect.flip),
);
it.effect("normalizes the hosted app URL to an absolute origin", () =>
Effect.gen(function* () {
assert.equal(
yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: "https://nightly.app.t3.codes" }),
),
"https://nightly.app.t3.codes",
);
assert.equal(
yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: "http://localhost:5733" }),
),
"http://localhost:5733",
);
}),
);
it.effect("rejects malformed or insecure hosted app URLs", () =>
Effect.gen(function* () {
for (const value of [
"app.t3.codes",
"http://app.t3.codes",
"https://app.t3.codes/nested",
"https://app.t3.codes?alias=true",
]) {
const result = yield* hostedAppUrlConfig.pipe(
provideEnv({ T3CODE_HOSTED_APP_URL: value }),
Effect.result,
);
assert.isTrue(Result.isFailure(result), value);
}
}),
);
it.effect("derives direct Clerk OAuth endpoints from statically injected public config", () =>
Effect.gen(function* () {
const config = yield* makeCloudCliOAuthConfig({
+40 -1
View File
@@ -1,3 +1,4 @@
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -15,7 +16,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefi
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
const relayUrl = normalizeSecureRelayUrl(value);
@@ -100,6 +101,44 @@ export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
export const relayUrlConfig = makeRelayUrlConfig();
/**
* Hosted app origin used for out-of-band OAuth on headless
* machines. Overridable so staging/nightly builds can point their CLIs at a
* matching hosted deployment.
*/
export const hostedAppUrlConfig = makePublicValueConfig(
"T3CODE_HOSTED_APP_URL",
DEFAULT_HOSTED_APP_URL,
).pipe(Config.mapOrFail(validateHostedAppUrl));
function validateHostedAppUrl(value: string) {
try {
const url = new URL(value);
const isLoopbackHttp =
url.protocol === "http:" &&
(url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
if (
(url.protocol !== "https:" && !isLoopbackHttp) ||
url.pathname !== "/" ||
url.search !== "" ||
url.hash !== ""
) {
throw new Error("invalid hosted app origin");
}
return Effect.succeed(url.origin);
} catch {
return Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
}),
),
),
);
}
}
function makePublicValueConfig(name: string, fallback: string) {
const runtimeConfig = Config.nonEmptyString(name);
return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(
+4 -8
View File
@@ -123,15 +123,11 @@ export interface RunMigrationsOptions {
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
yield* migrations.length === 0
? Effect.logDebug("Database schema is current")
: Effect.log("Migrations ran successfully").pipe(Effect.annotateLogs({ migrations }));
return executedMigrations;
});
+4 -1
View File
@@ -322,7 +322,10 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(
Layer.mergeAll(
CloudCliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
CloudCliTokenManager.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ExternalLauncher.layer),
),
CloudManagedEndpointRuntimeLive,
),
),
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
buildConnectCliClerkAuthorizeUrl,
hasConnectCliAuthConfig,
readConnectCliCallbackResult,
} from "./connectCliAuth";
// Any pk_test_* key decodes to <base64 hostname>.clerk.accounts.dev.
const TEST_PUBLISHABLE_KEY = `pk_test_${btoa("witty-mole-42.clerk.accounts.dev$")}`;
describe("connectCliAuth", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("requires both the publishable key and the CLI OAuth client id", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");
vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.com");
expect(hasConnectCliAuthConfig()).toBe(false);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
expect(hasConnectCliAuthConfig()).toBe(true);
});
it("builds the Clerk authorize URL with the configured hosted origin's callback", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
vi.stubEnv("VITE_HOSTED_APP_URL", "https://nightly.app.t3.codes");
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
state: "state-1",
challenge: "challenge-1",
});
expect(authorizeUrl).not.toBeNull();
const url = new URL(authorizeUrl!);
expect(url.hostname).toBe("witty-mole-42.clerk.accounts.dev");
expect(url.pathname).toBe("/oauth/authorize");
expect(url.searchParams.get("redirect_uri")).toBe(
"https://nightly.app.t3.codes/connect/callback",
);
expect(url.searchParams.get("state")).toBe("state-1");
expect(url.searchParams.get("code_challenge")).toBe("challenge-1");
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("returns null when the CLI OAuth client id is not configured", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
expect(
buildConnectCliClerkAuthorizeUrl({ state: "state-1", challenge: "challenge-1" }),
).toBeNull();
});
it("reads the code and state Clerk echoes back to the callback", () => {
expect(
readConnectCliCallbackResult(
new URL("https://app.t3.codes/connect/callback?code=abc&state=state-1"),
),
).toEqual({ code: "abc", state: "state-1" });
expect(
readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?code=abc")),
).toBeNull();
expect(
readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?state=s")),
).toBeNull();
});
});
+91
View File
@@ -0,0 +1,91 @@
import {
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing";
import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";
const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state";
export function resolveConnectCliOAuthClientId(): string | null {
return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);
}
export function hasConnectCliAuthConfig(): boolean {
return Boolean(
resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),
);
}
/**
* Gate for the /connect routes: the CLI handshake only exists on the hosted
* deployment (the same bundle ships inside local instances) and needs the
* Clerk CLI OAuth client configured at build time.
*/
export function connectCliAuthRoutesEnabled(): boolean {
return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig();
}
/**
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
* state is mirrored into sessionStorage so the callback page can verify the
* response matches a request this browser actually started.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
const clientId = resolveConnectCliOAuthClientId();
if (!clerkPublishableKey || !clientId) {
return null;
}
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
});
}
export function rememberConnectCliAuthState(state: string): void {
try {
window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state);
} catch {
// Session storage can be unavailable (e.g. blocked). The callback page
// then falls back to trusting the state Clerk echoed back.
}
}
/**
* Read-only on purpose: this runs during render, where a removal would be
* consumed by React's double-invoked/discarded renders (StrictMode) and
* silently disable the state check. The value is not a secret and is
* overwritten by the next /connect visit.
*/
export function readConnectCliAuthState(): string | null {
try {
return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY);
} catch {
return null;
}
}
export interface ConnectCliCallbackResult {
readonly code: string;
readonly state: string;
}
export function readConnectCliCallbackResult(
url: URL = new URL(window.location.href),
): ConnectCliCallbackResult | null {
const code = url.searchParams.get("code")?.trim() ?? "";
const state = url.searchParams.get("state")?.trim() ?? "";
if (!code || !state) {
return null;
}
return { code, state };
}
+1 -1
View File
@@ -24,7 +24,7 @@ export interface CloudPublicConfig {
};
}
function trimNonEmpty(value: string | undefined): string | null {
export function trimNonEmpty(value: string | undefined): string | null {
return value?.trim() || null;
}
@@ -38,11 +38,15 @@ export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdro
aria-hidden
className="sidebar-stage-backdrop pointer-events-none absolute inset-x-0 top-0 z-0 h-20 select-none overflow-hidden"
>
{variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />}
<StageBackdropArt variant={variant} />
</div>
);
}
export function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVariant }) {
return variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />;
}
const NIGHTLY_STARS: ReadonlyArray<{
cx: number;
cy: number;
@@ -0,0 +1,44 @@
import type { ReactNode } from "react";
import { APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../../branding";
import { resolveSidebarStageBackdropVariant, StageBackdropArt } from "../SidebarStageBackdrop";
/**
* Full-screen card for standalone auth pages, mirroring the pairing surface's
* treatment. Used by the CLI-connect authorize and callback surfaces.
*/
export function AuthSurfaceShell({ children }: { readonly children: ReactNode }) {
const stageVariant = resolveSidebarStageBackdropVariant(APP_STAGE_LABEL);
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-72 bg-[radial-gradient(48rem_20rem_at_top,color-mix(in_srgb,var(--color-blue-500)_12%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_94%,var(--color-black))_0%,var(--background)_62%)]" />
</div>
<section className="relative w-full max-w-xl overflow-hidden rounded-2xl border border-border/80 bg-card/94 shadow-2xl shadow-black/20 backdrop-blur-md">
<header className="relative h-24 overflow-hidden bg-[linear-gradient(135deg,#1e61de,#17348e)] text-white">
{stageVariant ? (
<div className="absolute inset-0" aria-hidden>
<StageBackdropArt variant={stageVariant} />
</div>
) : (
<div
aria-hidden
className="absolute inset-0 bg-[radial-gradient(circle_at_75%_25%,rgba(136,204,255,0.5),transparent_38%),linear-gradient(135deg,#2468df,#172f82)]"
/>
)}
<div className="absolute inset-0 bg-[linear-gradient(to_bottom,transparent_20%,rgba(7,18,55,0.46)_100%)]" />
<div className="relative h-full p-5 sm:p-6">
<p className="text-[10px] font-semibold tracking-[0.2em] text-white/80 uppercase">
{APP_DISPLAY_NAME}
</p>
</div>
</header>
<div className="p-6 sm:p-8">{children}</div>
</section>
</div>
);
}
@@ -0,0 +1,188 @@
import { useAuth, useClerk, useUser } from "@clerk/react";
import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
import { useEffect, useRef, useState } from "react";
import {
buildConnectCliClerkAuthorizeUrl,
readConnectCliAuthState,
readConnectCliCallbackResult,
rememberConnectCliAuthState,
} from "../../cloud/connectCliAuth";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";
import { Button } from "../ui/button";
function ConnectCliAuthMessage({
eyebrow,
title,
description,
}: {
readonly eyebrow?: string;
readonly title: string;
readonly description: string;
}) {
return (
<>
{eyebrow ? (
<p className="text-[10px] font-semibold tracking-[0.18em] text-blue-600 uppercase dark:text-blue-400">
{eyebrow}
</p>
) : null}
<h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
</>
);
}
const invalidLinkMessage = {
eyebrow: "Authorization request",
title: "This connect link is incomplete",
description:
"The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",
} as const;
/**
* /connect: the URL a headless CLI prints. Waits for a Clerk session, then
* forwards the CLI's PKCE request to Clerk's authorize endpoint.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
const clerk = useClerk();
const { isLoaded, isSignedIn } = useAuth();
const signInOpened = useRef(false);
const redirecting = useRef(false);
useEffect(() => {
if (!request || !isLoaded || redirecting.current) {
return;
}
if (!isSignedIn) {
if (!signInOpened.current) {
signInOpened.current = true;
clerk.openSignIn({ forceRedirectUrl: window.location.href });
}
return;
}
const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
if (!authorizeUrl) {
return;
}
redirecting.current = true;
rememberConnectCliAuthState(request.state);
window.location.assign(authorizeUrl);
}, [clerk, isLoaded, isSignedIn, request]);
if (!request) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage {...invalidLinkMessage} />
</AuthSurfaceShell>
);
}
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 1 of 2 · Browser authorization"
title="Connecting your terminal"
description={
isSignedIn
? "Redirecting to authorize T3 Connect for your CLI…"
: "Sign in to continue authorizing T3 Connect for your CLI."
}
/>
{isLoaded && !isSignedIn ? (
<div className="mt-6">
<Button
type="button"
onClick={() => clerk.openSignIn({ forceRedirectUrl: window.location.href })}
>
Sign in
</Button>
</div>
) : null}
</AuthSurfaceShell>
);
}
/**
* /connect/callback: Clerk's redirect target. Shows the one-time code the
* user enters in the waiting terminal.
*/
export function ConnectCliCallbackSurface() {
const [result] = useState(readConnectCliCallbackResult);
const [expectedState] = useState(readConnectCliAuthState);
const { user } = useUser();
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "authentication code" });
if (!result) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="Authorization did not complete"
description="No authorization code was returned. Re-run `t3 connect` in your terminal and try again."
/>
</AuthSurfaceShell>
);
}
// Fail closed: the legitimate callback always lands in the same browser
// that visited /connect (which recorded the state), so a missing or
// mismatched state means this page was reached some other way — the CSRF
// shape the state parameter exists to stop. Refuse to display a code.
if (expectedState === null || expectedState !== result.state) {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="This code belongs to a different request"
description="This authorization response does not match a connect request started in this browser. Re-run `t3 connect` in your terminal and open the freshly printed URL in this browser."
/>
</AuthSurfaceShell>
);
}
const accountLabel = user?.primaryEmailAddress?.emailAddress ?? user?.username ?? null;
const authCode = encodeConnectAuthCode(result);
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 2 of 2 · Terminal handoff"
title="Almost connected"
description={
accountLabel
? `Enter this code in your waiting terminal to connect it as ${accountLabel}.`
: "Enter this code in your waiting terminal to finish connecting."
}
/>
<div className="mt-6 overflow-hidden rounded-xl border border-border/80 bg-background/65">
<div className="flex items-center justify-between border-b border-border/70 px-4 py-2.5">
<span className="text-[10px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
One-time authorization code
</span>
<span className="font-mono text-[10px] text-muted-foreground">expires shortly</span>
</div>
<code
className="block p-4 font-mono text-sm leading-relaxed break-all select-all"
data-testid="connect-auth-code"
>
{authCode}
</code>
</div>
<div className="mt-4 flex items-center gap-3">
<Button type="button" onClick={() => copyToClipboard(authCode)}>
{isCopied ? "Copied!" : "Copy authorization code"}
</Button>
</div>
<p className="mt-6 text-xs leading-relaxed text-muted-foreground">
Only enter this code in a terminal session you started yourself. Anyone holding it can link
their machine to your T3 Connect account while it is valid.
</p>
</AuthSurfaceShell>
);
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
export interface HostedPairingRequest {
readonly host: string;
+42
View File
@@ -11,6 +11,7 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
@@ -20,6 +21,7 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -33,6 +35,11 @@ const PairRoute = PairRouteImport.update({
path: '/pair',
getParentRoute: () => rootRouteImport,
} as any)
const ConnectRoute = ConnectRouteImport.update({
id: '/connect',
path: '/connect',
getParentRoute: () => rootRouteImport,
} as any)
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
getParentRoute: () => rootRouteImport,
@@ -77,6 +84,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
id: '/connect_/callback',
path: '/connect/callback',
getParentRoute: () => rootRouteImport,
} as any)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -91,8 +103,10 @@ const ChatEnvironmentIdThreadIdRoute =
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -104,8 +118,10 @@ export interface FileRoutesByFullPath {
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -120,8 +136,10 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/connect_/callback': typeof ConnectCallbackRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -137,8 +155,10 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
| '/connect'
| '/pair'
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -150,8 +170,10 @@ export interface FileRouteTypes {
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
to:
| '/connect'
| '/pair'
| '/settings'
| '/connect/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -165,8 +187,10 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/_chat'
| '/connect'
| '/pair'
| '/settings'
| '/connect_/callback'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -181,8 +205,10 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
ConnectRoute: typeof ConnectRoute
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
ConnectCallbackRoute: typeof ConnectCallbackRoute
}
declare module '@tanstack/react-router' {
@@ -201,6 +227,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PairRouteImport
parentRoute: typeof rootRouteImport
}
'/connect': {
id: '/connect'
path: '/connect'
fullPath: '/connect'
preLoaderRoute: typeof ConnectRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat': {
id: '/_chat'
path: ''
@@ -264,6 +297,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/connect_/callback': {
id: '/connect_/callback'
path: '/connect/callback'
fullPath: '/connect/callback'
preLoaderRoute: typeof ConnectCallbackRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -321,8 +361,10 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
ConnectRoute: ConnectRoute,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
ConnectCallbackRoute: ConnectCallbackRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
+1 -1
View File
@@ -97,7 +97,7 @@ function RootRouteView() {
};
}, [pathname]);
if (pathname === "/pair") {
if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
return (
<>
<DocumentTitleSync />
+13
View File
@@ -0,0 +1,13 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";
import { ConnectCliAuthorizeSurface } from "../components/cloud/ConnectCliAuthSurface";
export const Route = createFileRoute("/connect")({
beforeLoad: () => {
if (!connectCliAuthRoutesEnabled()) {
throw redirect({ to: "/", replace: true });
}
},
component: ConnectCliAuthorizeSurface,
});
+13
View File
@@ -0,0 +1,13 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";
import { ConnectCliCallbackSurface } from "../components/cloud/ConnectCliAuthSurface";
export const Route = createFileRoute("/connect_/callback")({
beforeLoad: () => {
if (!connectCliAuthRoutesEnabled()) {
throw redirect({ to: "/", replace: true });
}
},
component: ConnectCliCallbackSurface,
});
+1
View File
@@ -9,6 +9,7 @@ interface ImportMetaEnv {
readonly VITE_HOSTED_APP_CHANNEL: string;
readonly VITE_CLERK_PUBLISHABLE_KEY: string;
readonly VITE_CLERK_JWT_TEMPLATE: string;
readonly VITE_CLERK_CLI_OAUTH_CLIENT_ID: string;
readonly VITE_RELAY_OTLP_TRACES_URL: string;
readonly VITE_RELAY_OTLP_TRACES_DATASET: string;
readonly VITE_RELAY_OTLP_TRACES_TOKEN: string;
+4
View File
@@ -18,6 +18,7 @@ const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";
const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
@@ -121,6 +122,9 @@ export default defineConfig(() => {
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
"import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(
configuredClerkCliOAuthClientId,
),
"import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
"import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
configuredRelayTracingDataset,
+4
View File
@@ -135,6 +135,10 @@
"types": "./src/cliArgs.ts",
"import": "./src/cliArgs.ts"
},
"./connectAuth": {
"types": "./src/connectAuth.ts",
"import": "./src/connectAuth.ts"
},
"./path": {
"types": "./src/path.ts",
"import": "./src/path.ts"
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
encodeConnectAuthCode,
parseConnectAuthCode,
readConnectAuthorizeRequest,
} from "./connectAuth.ts";
describe("connectAuth", () => {
it("round-trips state and challenge through the authorize URL fragment", () => {
const url = buildConnectAuthorizeRequestUrl({
hostedAppUrl: "https://app.t3.codes",
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
});
const parsed = new URL(url);
expect(parsed.origin).toBe("https://app.t3.codes");
expect(parsed.pathname).toBe("/connect");
expect(parsed.search).toBe("");
expect(readConnectAuthorizeRequest(parsed)).toEqual({
state: "q7mK9xV2pL4nR8sT6wYzAQ",
challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
});
});
it("rejects authorize requests missing state or challenge", () => {
expect(readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect"))).toBeNull();
expect(
readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc")),
).toBeNull();
expect(
readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#challenge=abc")),
).toBeNull();
});
it("builds a PKCE authorize URL against the Clerk endpoint", () => {
const url = new URL(
buildConnectClerkAuthorizeUrl({
authorizationEndpoint: "https://clerk.t3.codes/oauth/authorize",
clientId: "oauthapp_123",
redirectUri: connectCallbackUrl("https://app.t3.codes"),
scopes: ["openid", "profile", "email"],
state: "state-1",
challenge: "challenge-1",
}),
);
expect(url.origin).toBe("https://clerk.t3.codes");
expect(url.pathname).toBe("/oauth/authorize");
expect(url.searchParams.get("client_id")).toBe("oauthapp_123");
expect(url.searchParams.get("redirect_uri")).toBe("https://app.t3.codes/connect/callback");
expect(url.searchParams.get("response_type")).toBe("code");
expect(url.searchParams.get("scope")).toBe("openid profile email");
expect(url.searchParams.get("state")).toBe("state-1");
expect(url.searchParams.get("code_challenge")).toBe("challenge-1");
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("round-trips the out-of-band authorization code and preserves dots inside it", () => {
const blob = encodeConnectAuthCode({ code: "az9.code.chunk", state: "state-uuid" });
expect(parseConnectAuthCode(blob)).toEqual({ code: "az9.code.chunk", state: "state-uuid" });
expect(parseConnectAuthCode(` ${blob}\n`)).toEqual({
code: "az9.code.chunk",
state: "state-uuid",
});
});
it("rejects malformed out-of-band authorization codes", () => {
expect(parseConnectAuthCode("")).toBeNull();
expect(parseConnectAuthCode("no-separator")).toBeNull();
expect(parseConnectAuthCode(".leading")).toBeNull();
expect(parseConnectAuthCode("trailing.")).toBeNull();
});
});
+124
View File
@@ -0,0 +1,124 @@
import { readHashParams } from "./remote.ts";
const CONNECT_AUTH_STATE_PARAM = "state";
const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
const CONNECT_AUTH_CODE_SEPARATOR = ".";
const CONNECT_AUTHORIZE_PATH = "/connect";
const CONNECT_CALLBACK_PATH = "/connect/callback";
/**
* The CLI prints URLs against this origin and the web bundle uses it to
* decide whether it is the hosted deployment — the two must agree, so the
* default lives here.
*/
export const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
/**
* Requested at authorize time by the hosted page and honored by the CLI's
* token exchange; keep both sides on this single definition.
*/
export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
export interface ConnectAuthorizeRequest {
readonly state: string;
readonly challenge: string;
}
/**
* The URL a headless CLI prints for the user to open on a machine with a
* browser. `state` and `code_challenge` ride the fragment so they never reach
* the hosted app's server or CDN logs; neither is a secret.
*/
export function buildConnectAuthorizeRequestUrl(input: {
readonly hostedAppUrl: string;
readonly state: string;
readonly challenge: string;
}): string {
const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);
url.hash = new URLSearchParams([
[CONNECT_AUTH_STATE_PARAM, input.state],
[CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],
]).toString();
return url.toString();
}
export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest | null {
const params = readHashParams(url);
const state = params.get(CONNECT_AUTH_STATE_PARAM)?.trim() ?? "";
const challenge = params.get(CONNECT_AUTH_CHALLENGE_PARAM)?.trim() ?? "";
if (!state || !challenge) {
return null;
}
return { state, challenge };
}
export function connectCallbackUrl(hostedAppUrl: string): string {
return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();
}
export function buildConnectClerkAuthorizeUrl(input: {
readonly authorizationEndpoint: string;
readonly clientId: string;
readonly redirectUri: string;
readonly scopes: ReadonlyArray<string>;
readonly state: string;
readonly challenge: string;
}): string {
const url = new URL(input.authorizationEndpoint);
url.searchParams.set("client_id", input.clientId);
url.searchParams.set("redirect_uri", input.redirectUri);
url.searchParams.set("response_type", "code");
url.searchParams.set("scope", input.scopes.join(" "));
url.searchParams.set("state", input.state);
url.searchParams.set("code_challenge", input.challenge);
url.searchParams.set("code_challenge_method", "S256");
return url.toString();
}
export interface ConnectAuthCode {
readonly code: string;
readonly state: string;
}
/**
* The single blob the hosted callback page displays and the CLI accepts.
* Bundling `state` with the authorization code lets the CLI keep the loopback
* flow's CSRF check without any backend: it verifies the returned state
* matches the one it generated. Clerk authorization codes and the CLI's
* base64url states never contain ".".
*/
export function encodeConnectAuthCode(input: ConnectAuthCode): string {
return `${input.code}${CONNECT_AUTH_CODE_SEPARATOR}${input.state}`;
}
/**
* Validates an out-of-band authorization code against the state of the request this process
* generated. Returns the parsed code or a user-facing error message; both
* the prompt's live validation and the authoritative post-prompt check go
* through here so they cannot drift.
*/
export function checkConnectAuthCode(
blob: string,
expectedState: string,
): ConnectAuthCode | string {
const parsed = parseConnectAuthCode(blob);
if (parsed === null) {
return "That does not look like a T3 Connect code. Copy the full code.";
}
if (parsed.state !== expectedState) {
return "That code belongs to a different connect request. Open the URL above and try again.";
}
return parsed;
}
export function parseConnectAuthCode(blob: string): ConnectAuthCode | null {
const trimmed = blob.trim();
const separatorIndex = trimmed.lastIndexOf(CONNECT_AUTH_CODE_SEPARATOR);
if (separatorIndex <= 0 || separatorIndex === trimmed.length - 1) {
return null;
}
const code = trimmed.slice(0, separatorIndex);
const state = trimmed.slice(separatorIndex + 1);
return { code, state };
}
+14
View File
@@ -30,4 +30,18 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(
},
);
export const HostProcessExecutablePath = Context.Reference<string>(
"@t3tools/shared/hostProcess/HostProcessExecutablePath",
{
defaultValue: () => process.execPath,
},
);
export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(
"@t3tools/shared/hostProcess/HostProcessArguments",
{
defaultValue: () => process.argv,
},
);
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");
+1 -1
View File
@@ -5,7 +5,7 @@ const HOSTED_PAIRING_HOST_PARAM = "host";
const HOSTED_PAIRING_LABEL_PARAM = "label";
const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
const readHashParams = (url: URL): URLSearchParams =>
export const readHashParams = (url: URL): URLSearchParams =>
new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
export class RemoteBackendUrlMissingError extends Schema.TaggedErrorClass<RemoteBackendUrlMissingError>()(
+6 -1
View File
@@ -55,6 +55,7 @@ export function loadRepoEnv({
...(config.clerkCliOAuthClientId
? {
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: config.clerkCliOAuthClientId,
VITE_CLERK_CLI_OAUTH_CLIENT_ID: config.clerkCliOAuthClientId,
}
: {}),
...(config.relayUrl
@@ -116,7 +117,11 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
"VITE_CLERK_JWT_TEMPLATE",
"EXPO_PUBLIC_CLERK_JWT_TEMPLATE",
),
clerkCliOAuthClientId: firstNonEmpty(sources, "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID"),
clerkCliOAuthClientId: firstNonEmpty(
sources,
"T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",
"VITE_CLERK_CLI_OAUTH_CLIENT_ID",
),
relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),
mobileOtlpTracesUrl: firstNonEmpty(
sources,