fix(render): simplify cloud environment setup

This commit is contained in:
Shivam Sharma committed 2026-08-05 10:19:57 +05:30
1 parent 47b65e7e7b
commit 85b166df0e
8 files changed
+28 -116

No files matched your search

+2 -17
View File
@@ -1,9 +1,7 @@
import * as NodeCrypto from "node:crypto";
import {
EnvironmentHttpApi,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
EnvironmentHttpUnauthorizedError,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
@@ -20,12 +18,6 @@ const RENDER_BOOTSTRAP_RESPONSE_HEADERS = {
"x-content-type-options": "nosniff",
} as const;
export function renderSetupCodeMatches(expected: string, candidate: string): boolean {
const expectedDigest = NodeCrypto.createHash("sha256").update(expected).digest();
const candidateDigest = NodeCrypto.createHash("sha256").update(candidate).digest();
return NodeCrypto.timingSafeEqual(expectedDigest, candidateDigest);
}
const appendRenderBootstrapResponseHeaders = HttpEffect.appendPreResponseHandler(
(_request, response) =>
Effect.succeed(HttpServerResponse.setHeaders(response, RENDER_BOOTSTRAP_RESPONSE_HEADERS)),
@@ -38,25 +30,18 @@ export const renderBootstrapHttpApiLayer = HttpApiBuilder.group(
const hostEnvironment = yield* HostProcessEnvironment;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const configuredProvider = hostEnvironment.T3CODE_CLOUD_PROVIDER?.trim().toLowerCase();
const configuredSetupCode = hostEnvironment.T3CODE_RENDER_SETUP_CODE?.trim() ?? "";
const environmentLabel =
hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim() || "Render cloud environment";
delete hostEnvironment.T3CODE_RENDER_SETUP_CODE;
return handlers.handle(
"pair",
Effect.fn("environment.renderBootstrap.pair")(function* ({ payload }) {
Effect.fn("environment.renderBootstrap.pair")(function* () {
yield* appendRenderBootstrapResponseHeaders;
if (configuredProvider !== "render" || configuredSetupCode.length === 0) {
if (configuredProvider !== "render") {
return yield* new EnvironmentHttpForbiddenError({
message: "This environment is not configured for Render setup.",
});
}
if (!renderSetupCodeMatches(configuredSetupCode, payload.setupCode)) {
return yield* new EnvironmentHttpUnauthorizedError({
message: "The Render setup code is invalid.",
});
}
const issued = yield* serverAuth.issuePairingCredential({ label: "Render setup" }).pipe(
Effect.mapError(
+1 -10
View File
@@ -1398,26 +1398,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("pairs a Render environment from its setup code without reading logs", () =>
it.effect("pairs a Render environment from its service URL without reading logs", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
hostEnvironment: {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
T3CODE_RENDER_SETUP_CODE: "render-setup-code-1234",
},
});
const url = yield* getHttpServerUrl("/.well-known/t3/render/pair");
const rejected = yield* fetchEffect(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: jsonRequestBody({ setupCode: "wrong-code" }),
});
const response = yield* fetchEffect(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: jsonRequestBody({ setupCode: "render-setup-code-1234" }),
});
const body = yield* responseJsonEffect<{
readonly pairingCode: string;
@@ -1427,7 +1419,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
});
assert.equal(rejected.status, 401);
assert.equal(response.status, 200);
assert.equal(response.headers["cache-control"], "no-store");
assert.equal(response.headers["referrer-policy"], "no-referrer");
+3 -5
View File
@@ -34,7 +34,6 @@ describe("requestRenderPairing", () => {
await expect(
requestRenderPairing({
serviceUrl: "demo.onrender.com",
setupCode: "setup-code",
fetcher,
}),
).resolves.toEqual({
@@ -48,18 +47,17 @@ describe("requestRenderPairing", () => {
);
});
it("explains a mismatched setup code", async () => {
it("explains when the service is still running an older deployment", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ message: "invalid" }, { status: 401 }),
Response.json({ message: "missing" }, { status: 404 }),
);
const failure = await requestRenderPairing({
serviceUrl: "https://demo.onrender.com",
setupCode: "wrong-code",
fetcher,
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(RenderBootstrapRequestError);
expect((failure as Error).message).toContain("does not match");
expect((failure as Error).message).toContain("Deploy the latest version");
});
});
+3 -12
View File
@@ -53,22 +53,15 @@ export function maskedRenderServiceUrl(value: string): string {
export async function requestRenderPairing(input: {
readonly serviceUrl: string;
readonly setupCode: string;
readonly fetcher?: typeof globalThis.fetch;
}): Promise<{ readonly host: string; readonly pairingCode: string; readonly label: string }> {
const host = normalizeRenderServiceUrl(input.serviceUrl);
const setupCode = input.setupCode.trim();
if (setupCode.length === 0) {
throw new RenderBootstrapRequestError("Enter the setup code used during deployment.");
}
const endpoint = new URL("/.well-known/t3/render/pair", host);
let response: Response;
try {
response = await (input.fetcher ?? globalThis.fetch)(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ setupCode }),
cache: "no-store",
referrerPolicy: "no-referrer",
});
@@ -83,11 +76,9 @@ export async function requestRenderPairing(input: {
const decodedError = decodeRenderBootstrapErrorBody(responseBody);
const serverMessage = Option.isSome(decodedError) ? decodedError.value.message : null;
const message =
response.status === 401
? "The setup code does not match the Render service."
: response.status === 403 || response.status === 404
? "This service does not have in-app Render pairing yet. Deploy the latest version."
: serverMessage || `Render pairing failed with HTTP ${response.status}.`;
response.status === 403 || response.status === 404
? "This service does not have in-app Render pairing yet. Deploy the latest version."
: serverMessage || `Render pairing failed with HTTP ${response.status}.`;
throw new RenderBootstrapRequestError(message, response.status);
}
@@ -4,13 +4,7 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
CheckIcon,
CopyIcon,
ExternalLinkIcon,
LoaderCircleIcon,
RefreshCwIcon,
} from "lucide-react";
import { CheckIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { cloudEnvironmentProvider } from "~/cloud/cloudEnvironment";
@@ -19,7 +13,6 @@ import { openCommandPalette } from "~/commandPaletteBus";
import { environmentCatalog } from "~/connection/catalog";
import { connectPairing as connectPairingAtom } from "~/connection/onboarding";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { randomHex } from "~/lib/utils";
import { useAtomCommand } from "~/state/use-atom-command";
import { type EnvironmentPresentation, useEnvironments } from "~/state/environments";
import { RenderLogo } from "../RenderLogo";
@@ -34,10 +27,6 @@ const RENDER_DEPLOY_URL =
const CODEX_LOGIN_COMMAND = "codex login --device-auth";
type RenderAuthenticationMode = "api-key" | "subscription";
function newRenderSetupCode(): string {
return `t3-${randomHex(10)}`;
}
function CopyValueButton({ value, label }: { readonly value: string; readonly label: string }) {
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: label });
return (
@@ -135,7 +124,6 @@ export function CloudEnvironmentsSettings() {
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const [serviceUrl, setServiceUrl] = useState("");
const [setupCode, setSetupCode] = useState(newRenderSetupCode);
const [pairing, setPairing] = useState(false);
const [pairingStatus, setPairingStatus] = useState<string | null>(null);
const [pairError, setPairError] = useState<string | null>(null);
@@ -170,7 +158,7 @@ export function CloudEnvironmentsSettings() {
setPairing(true);
setPairingStatus("Waking the Render service…");
try {
const pairingInput = await requestRenderPairing({ serviceUrl, setupCode });
const pairingInput = await requestRenderPairing({ serviceUrl });
setServiceUrl(pairingInput.host);
setPairingStatus("Connecting T3 Code…");
const result = await connectPairing({
@@ -191,7 +179,7 @@ export function CloudEnvironmentsSettings() {
setPairing(false);
setPairingStatus(null);
}
}, [connectPairing, pairing, serviceUrl, setupCode]);
}, [connectPairing, pairing, serviceUrl]);
const handleConnect = useCallback(
async (environmentId: EnvironmentId) => {
@@ -239,8 +227,7 @@ export function CloudEnvironmentsSettings() {
<div className="min-w-0 space-y-1">
<h3 className="text-base font-semibold tracking-[-0.02em]">Powered by Render</h3>
<p className="max-w-xl text-sm leading-relaxed text-muted-foreground">
Deploy a temporary T3 Code machine, connect it here, and run agents on a public
GitHub repository.
Deploy a temporary T3 Code machine, paste its URL, and start an agent.
</p>
<div className="flex flex-wrap gap-2 pt-2 text-[11px] font-medium text-muted-foreground">
<span className="rounded-full border border-border/70 bg-background/70 px-2 py-1">
@@ -255,7 +242,7 @@ export function CloudEnvironmentsSettings() {
</div>
</SettingsSection>
<SettingsSection title="1. Deploy">
<SettingsSection title="1. Deploy to Render">
<div className="px-3 sm:px-4">
<div
role="tablist"
@@ -283,38 +270,11 @@ export function CloudEnvironmentsSettings() {
</div>
</div>
<SettingsRow
title="Setup code"
description="Copy this into T3CODE_RENDER_SETUP_CODE when Render asks. It lets this screen pair the service without reading logs."
status="Keep it private until the demo is over."
>
<div className="mt-3 flex gap-2">
<Input
value={setupCode}
onChange={(event) => setSetupCode(event.target.value)}
aria-label="Render setup code"
autoComplete="off"
spellCheck={false}
className="font-mono text-xs"
/>
<CopyValueButton value={setupCode} label="Render setup code" />
<Button
size="icon-sm"
variant="outline"
aria-label="Generate a new setup code"
disabled={pairing}
onClick={() => setSetupCode(newRenderSetupCode())}
>
<RefreshCwIcon className="size-3.5" />
</Button>
</div>
</SettingsRow>
{authenticationMode === "api-key" ? (
<div role="tabpanel">
<SettingsRow
title="OpenAI API key"
description="Render asks for OPENAI_API_KEY and the setup code. Codex is authenticated automatically when the service starts."
description="Render asks for OPENAI_API_KEY. Codex is authenticated automatically when the service starts."
status="OpenAI API usage is billed separately from Render."
control={
<Button
@@ -368,7 +328,7 @@ export function CloudEnvironmentsSettings() {
}}
/>
<Button
disabled={pairing || serviceUrl.trim().length === 0 || setupCode.trim().length === 0}
disabled={pairing || serviceUrl.trim().length === 0}
onClick={() => void handlePair()}
>
{pairing ? <LoaderCircleIcon className="size-4 animate-spin" /> : null}
+12 -14
View File
@@ -15,26 +15,24 @@ The root [`render.yaml`](../../render.yaml) creates:
- a Docker web service containing T3 Code, Codex, Claude Code, Git, and the GitHub CLI;
- an ephemeral `/data` workspace for T3 Code state, provider credentials, and repositories;
- an optional `OPENAI_API_KEY` secret prompt for automatic Codex authentication;
- a private setup-code prompt for pairing the service directly inside T3 Code;
- in-app pairing directly from the service URL;
- a health check against T3 Code's public environment descriptor.
## Deploy
1. Open **Settings → Cloud environments** in T3 Code and copy the generated setup code.
2. Choose an authentication tab, then select **Deploy on Render**.
3. Enter the generated code in Render's `T3CODE_RENDER_SETUP_CODE` secret prompt.
4. Choose an authentication method:
1. Open **Settings → Cloud environments** in T3 Code.
2. Choose an authentication method, then select **Deploy on Render**:
- **OpenAI API key:** enter `OPENAI_API_KEY` in Render's secret prompt. Startup authenticates
Codex automatically.
- **ChatGPT subscription:** skip the optional API key, then use device login after cloning.
5. Deploy the Blueprint and wait for the service health check to pass.
6. Copy the service's `.onrender.com` URL, return to T3 Code, paste it under **Connect in T3
Code**, and select **Connect environment**. T3 Code wakes the service and exchanges the setup
code for a one-time pairing credential; there is no log-copying step.
7. Select **Add project** and choose **Cloud environments → Render cloud
3. Deploy the Blueprint and wait for the service health check to pass.
4. Copy the service's `.onrender.com` URL, return to T3 Code, paste it under **Connect in T3
Code**, and select **Connect environment**. T3 Code wakes the service and requests a one-time
pairing credential; there is no log-copying step.
5. Select **Add project** and choose **Cloud environments → Render cloud
environment**. Paste a public GitHub URL. T3 Code clones it directly into the Render workspace;
there is no local destination picker.
8. API-key deployments are ready immediately. For subscription authentication, open the project
6. API-key deployments are ready immediately. For subscription authentication, open the project
terminal, run `codex login --device-auth`, complete the device login, and start an agent.
Repositories are selected after pairing rather than baked into the Blueprint. Each clone is stored
@@ -72,9 +70,9 @@ useful for machines that need its managed tunnel or account-level environment di
## Operations
- The setup code can mint one-time pairing credentials. Treat it as a secret and remove the Render
service when the demo is over. Existing paired browser sessions remain authenticated until the
ephemeral service restarts.
- Anyone with the service URL can request a standard T3 Code pairing credential. Use this setup only
for a private demo and remove the Render service afterward. Existing paired browser sessions remain
authenticated until the ephemeral service restarts.
- Render spins a Free web service down after 15 minutes without inbound HTTP or WebSocket traffic.
A later request starts a fresh instance, so pair, clone, and authenticate again.
- Do not use this Blueprint for untrusted users or repositories. Coding agents can execute commands
@@ -371,12 +371,6 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export const EnvironmentRenderBootstrapPairingRequest = Schema.Struct({
setupCode: TrimmedNonEmptyString,
});
export type EnvironmentRenderBootstrapPairingRequest =
typeof EnvironmentRenderBootstrapPairingRequest.Type;
export const EnvironmentRenderBootstrapPairingResult = Schema.Struct({
pairingCode: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
@@ -385,15 +379,12 @@ export type EnvironmentRenderBootstrapPairingResult =
typeof EnvironmentRenderBootstrapPairingResult.Type;
const EnvironmentRenderBootstrapErrors = [
EnvironmentHttpBadRequestError,
EnvironmentHttpUnauthorizedError,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
] as const;
export class EnvironmentRenderBootstrapHttpApi extends HttpApiGroup.make("renderBootstrap").add(
HttpApiEndpoint.post("pair", "/.well-known/t3/render/pair", {
payload: EnvironmentRenderBootstrapPairingRequest,
success: EnvironmentRenderBootstrapPairingResult,
error: EnvironmentRenderBootstrapErrors,
}),
-2
View File
@@ -16,7 +16,5 @@ services:
value: Render cloud environment
- key: T3CODE_WORKSPACE_DIR
value: /data/workspace
- key: T3CODE_RENDER_SETUP_CODE
sync: false
- key: OPENAI_API_KEY
sync: false