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

@@ -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(