Skip to content
TypeScript

fix(server): keep sensitive values out of settings reads, startup logs and preview snapshots (#20446)

Julius Marminge8653c8f09bb6
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts
index 3b08e1c8f27..952cf23a735 100644
--- a/apps/server/src/preview/ServerBrowser.test.ts
+++ b/apps/server/src/preview/ServerBrowser.test.ts
@@ -80,7 +80,15 @@ function makeSession(frame?: ReturnType<typeof makeFrame>) {
if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } };
if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" };
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
+ // Snapshots read password fields from their own isolated world in each frame.
+ if (method === "Page.createIsolatedWorld") {
+ return {
+ executionContextId: (input as { worldName?: string }).worldName === "t3-preview" ? 1 : 7,
+ };
+ }
+ if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) {
+ return { result: { value: [] } };
+ }
if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve();
if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) {
if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy;
diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts
index 809e03a60d2..1fbf1bbf154 100644
--- a/apps/server/src/preview/ServerBrowserPage.test.ts
+++ b/apps/server/src/preview/ServerBrowserPage.test.ts
@@ -124,6 +124,60 @@ describe("server browser element refs", () => {
expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
});
+ it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
+ await page.setContent(`
+ <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
+ <input aria-label="Username" value="maria">
+ <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
+ <input type="password" role="combobox" aria-label="Code" value="role-pass">
+ <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
+ <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
+ <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
+ <iframe id="blank" src="javascript:false"></iframe>
+ <p>Order styled-pass-2</p>
+ <script>
+ // A frame that never commits a document, filled by its parent.
+ blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
+ // Page script can't change the value the snapshot sees.
+ Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
+ </script>`);
+ await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
+ await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
+ const result = await takeSnapshot();
+ const tree = String(result.accessibilityTree);
+ expect(tree).toContain('textbox "blank"');
+ expect(tree).not.toMatch(
+ /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
+ );
+ expect(result.visibleText).not.toContain("editable-pass");
+ // Page text masks the same values, so it can't be compared against the tree.
+ expect(result.visibleText).toContain("Order ••••••••-2");
+ expect(tree).toMatch(/row "password: •+"/);
+ expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
+ const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
+ expect(line).toMatch(/: •+$/);
+ await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
+ expect(await page.locator("#pw").inputValue()).toBe("next");
+ });
+
+ it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
+ await page.setContent(`
+ <input type="password" aria-label="PIN" value="123">
+ <input type="password" aria-label="Phrase" value="open&nbsp;sesame">
+ <p>PIN: 123. Code (123) id 1234</p>
+ <p>open&nbsp;sesame</p>`);
+ const text = (await takeSnapshot()).visibleText;
+ expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
+ expect(text).not.toMatch(/open|sesame/);
+ await page.setContent(`
+ <p>${"x".repeat(19_995)}long-secret</p>
+ <input type="password" aria-label="Long" value="long-secret">`);
+ const cut = (await takeSnapshot()).visibleText;
+ expect(cut.length).toBe(20_000);
+ // Masked before the cut, so no prefix of the value is left.
+ expect(cut.slice(-8)).toBe("xxx•••••");
+ });
+
it("rejects refs from another tab", async () => {
await page.setContent("<button>same label</button>");
const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts
index 8846fa07f78..908de1b6c48 100644
--- a/apps/server/src/preview/ServerBrowserPage.ts
+++ b/apps/server/src/preview/ServerBrowserPage.ts
@@ -18,7 +18,7 @@ import {
type PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { constVoid } from "effect/Function";
-import type { CDPSession, Locator, Page } from "playwright-core";
+import type { CDPSession, Frame, Locator, Page } from "playwright-core";
import * as NodeCrypto from "node:crypto";
import { BrowserControlInterrupted } from "./SessionControl.ts";
@@ -143,11 +143,236 @@ const SNAPSHOT_SCRIPT = `(() => {
url: location.href,
title: document.title,
loading: document.readyState !== "complete",
- visibleText: (document.body?.innerText || "").slice(0, ${MAX_VISIBLE_TEXT_LENGTH}),
+ visibleText: document.body?.innerText || "",
interactiveElements: [],
};
})()`;
+const MASKED_VALUE = "••••••••";
+// The broker waits 15s for the host; a snapshot, retry included, answers well before.
+const SNAPSHOT_TIMEOUT_MS = 10_000;
+// How long a frame in another process gets to answer; one that crashed never does.
+const FRAME_ANSWER_MS = 1_000;
+
+// Values the page draws as dots (password fields, and text fields whose CSS
+// draws dots), normalized like accessible text. Open shadow roots included.
+const DOTTED_SCRIPT = `(() => {
+ const values = [];
+ const visit = (root) => {
+ for (const element of root.querySelectorAll("*")) {
+ if (element.shadowRoot) visit(element.shadowRoot);
+ const field = element.localName === "input" || element.localName === "textarea";
+ if (!field && !element.isContentEditable) continue;
+ const dots = getComputedStyle(element).getPropertyValue("-webkit-text-security");
+ if (element.type !== "password" && (dots === "none" || dots === "")) continue;
+ // Raw as page text shows it, and normalized as the tree does.
+ for (const value of field ? [element.value, element.defaultValue] : [element.textContent ?? ""])
+ values.push(value, value.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " "));
+ }
+ };
+ visit(document);
+ return [...new Set(values.filter((value) => value.trim()))];
+})()`;
+
+const pageChanged = () =>
+ new ServerBrowserOperationError(
+ "PreviewAutomationExecutionError",
+ "The page changed while capturing its snapshot. Take another snapshot.",
+ );
+
+const tooBusy = () =>
+ new ServerBrowserOperationError(
+ "PreviewAutomationTimeoutError",
+ "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",
+ );
+
+const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken.";
+
+/** A frame in another process keeps one CDP session, so none pile up across snapshots. */
+const frameSessions = new WeakMap<Frame, Promise<CDPSession>>();
+
+/** The value, or undefined when it fails or takes longer than a frame may. */
+const answered = <A>(promise: Promise<A>) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const late = new Promise<undefined>((resolve) => {
+ timer = setTimeout(() => resolve(undefined), FRAME_ANSWER_MS);
+ });
+ return Promise.race([promise.catch(() => undefined), late]).finally(() => clearTimeout(timer));
+};
+
+/**
+ * Reads dotted values in isolated worlds, where page script can't change what `value`
+ * returns, through the CDP session of the process each frame renders in. A frame in
+ * another process that can't be attached, as in desktop tabs where only the page can,
+ * is read in the page's own world, where its script can change `value`. `read` gives
+ * each reader's values, or undefined for one that didn't answer, and fails when the
+ * page's own frames don't or frames came or went.
+ */
+const openReaders = async (page: Page, cdp: CDPSession) => {
+ const frames = page.frames();
+ const owners = new Map<Frame, CDPSession | null | undefined>(
+ await Promise.all(
+ frames.map(async (frame) => {
+ if (frame === page.mainFrame()) return [frame, cdp] as const;
+ const session = frameSessions.get(frame) ?? page.context().newCDPSession(frame);
+ frameSessions.set(frame, session);
+ try {
+ return [frame, await session] as const;
+ } catch (cause) {
+ frameSessions.delete(frame);
+ // CdpRelay refuses all but the page. Any other refusal reads the frame through its
+ // parent's session, which fails the read if the frame isn't there.
+ const desktop = String(cause).includes("Only this preview tab's page can be attached");
+ return [frame, desktop ? null : undefined] as const;
+ }
+ }),
+ ),
+ );
+ const ownerOf = (frame: Frame): CDPSession | null => {
+ const owner = owners.get(frame);
+ if (owner !== undefined) return owner;
+ const parent = frame.parentFrame();
+ return parent ? ownerOf(parent) : null;
+ };
+ const sessionReader = (frame: Frame, session: CDPSession) => {
+ const owned = frames.filter((each) => ownerOf(each) === session);
+ const open = async () => {
+ const { frameTree } = await session.send("Page.getFrameTree");
+ const ids = (node: typeof frameTree): Array<string> => [
+ node.frame.id,
+ ...(node.childFrames ?? []).flatMap(ids),
+ ];
+ // A frame Playwright knows but this session doesn't would go unread.
+ if (ids(frameTree).length !== owned.length) throw pageChanged();
+ return Promise.all(
+ ids(frameTree).map(async (frameId) => {
+ const world = await session.send("Page.createIsolatedWorld", {
+ frameId,
+ worldName: "t3-preview",
+ });
+ return world.executionContextId;
+ }),
+ );
+ };
+ let contexts: ReturnType<typeof open> | undefined;
+ const read = async () => {
+ const values = (contexts ??= open()).then((ids) =>
+ Promise.all(
+ ids.map(async (contextId) => {
+ const { result, exceptionDetails } = await session.send("Runtime.evaluate", {
+ contextId,
+ expression: DOTTED_SCRIPT,
+ returnByValue: true,
+ });
+ if (exceptionDetails) throw pageChanged();
+ return result.value as Array<string>;
+ }),
+ ),
+ );
+ try {
+ return (await values).flat();
+ } catch (cause) {
+ // The frame may have moved to another process; the next snapshot opens a new session.
+ if (session !== cdp) {
+ frameSessions.delete(frame);
+ void session.detach().catch(constVoid);
+ }
+ throw cause;
+ }
+ };
+ return { frames: owned, read };
+ };
+ const readers = [
+ sessionReader(page.mainFrame(), cdp),
+ ...frames.flatMap((frame) => {
+ const owner = owners.get(frame);
+ if (owner) return owner === cdp ? [] : [sessionReader(frame, owner)];
+ const own = () => frame.evaluate(DOTTED_SCRIPT) as Promise<Array<string>>;
+ return ownerOf(frame) === null ? [{ frames: [frame], read: own }] : [];
+ }),
+ ];
+ return {
+ readers,
+ /** Readers that didn't answer `before` aren't asked again. */
+ read: async (before?: ReadonlyArray<unknown>) => {
+ const now = page.frames();
+ // A frame added since the readers opened has none.
+ if (now.length !== frames.length || now.some((frame, i) => frame !== frames[i])) {
+ throw pageChanged();
+ }
+ return Promise.all(
+ readers.map((reader, i) => {
+ if (i === 0) return reader.read().catch(() => Promise.reject(pageChanged()));
+ return before && !before[i] ? undefined : answered(reader.read());
+ }),
+ );
+ },
+ };
+};
+
+/**
+ * Matches each value as the snapshot prints it: raw, as a JSON name, as a
+ * quoted value, and with '' for each quote inside a quoted key. A value under
+ * four characters only matches between non-word characters; inside other words
+ * it would mask unrelated text.
+ */
+const dottedPattern = (values: ReadonlyArray<string>) => {
+ const sources = values
+ .flatMap((value) => {
+ const json = JSON.stringify(value).slice(1, -1);
+ // Playwright writes control characters like JSON does, with \xNN for the unnamed ones.
+ const quoted = value.replace(/[\\"\p{Cc}]/gu, (char) =>
+ '\\"\b\f\n\r\t'.includes(char)
+ ? JSON.stringify(char).slice(1, -1)
+ : `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`,
+ );
+ const forms = [value, json, quoted].flatMap((form) => [form, form.replaceAll("'", "''")]);
+ return [...new Set(forms)].map((form) => ({ form, word: value.length < 4 }));
+ })
+ // Longest first, so a form inside another never leaves the rest showing.
+ .toSorted((a, b) => b.form.length - a.form.length)
+ .map(({ form, word }) => {
+ const literal = form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return word ? `(?<![\\p{L}\\p{N}_])${literal}(?![\\p{L}\\p{N}_])` : literal;
+ });
+ if (sources.length === 0) return undefined;
+ const pattern = new RegExp(sources.join("|"), "gu");
+ try {
+ // Compiles it now, for one-byte and two-byte text: one too large fails only when it
+ // first runs on each, naming every value.
+ pattern.test("");
+ pattern.test("\u2022");
+ } catch {
+ throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG);
+ }
+ return pattern;
+};
+
+// `- role "name" [attribute]...: value`, the key single-quoted when it holds ": ". A name
+// that starts and ends with "/" prints unquoted. Only Playwright's own attributes count, so
+// text around a value in a name can't pass for one.
+const TREE_LINE =
+ /^(\s*- '?[^\s"':]+)( "(?:[^"\\]|\\.)*"| \/(?:.*?\/)?)?((?: \[(?:active|checked(?:=mixed)?|disabled|expanded|level=\d+|pressed(?:=mixed)?|selected|ref=(?:f\d+)?e\d+|cursor=pointer|box=-?\d+,-?\d+,\d+,\d+)\])*'?)(:.*)?$/;
+
+/**
+ * Masks each value on a line, except one that only matches inside the role or attributes,
+ * so refs keep working. A "/.../" name has no closing mark, so a value can seem to cross it.
+ */
+const maskTree = (tree: string, dotted: RegExp) =>
+ tree
+ .split("\n")
+ .map((line) => {
+ const node = TREE_LINE.exec(line);
+ const name = node?.[1]?.length ?? 0;
+ const attributes = name + (node?.[2]?.length ?? 0);
+ const end = attributes + (node?.[3]?.length ?? 0);
+ const kept = (from: number, to: number) => to <= name || (from >= attributes && to <= end);
+ return line.replace(dotted, (match: string, offset: number) =>
+ kept(offset, offset + match.length) ? match : MASKED_VALUE,
+ );
+ })
+ .join("\n");
+
// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
export const captureViewport = async (
page: Page,
@@ -173,36 +398,64 @@ export const captureViewport = async (
return data;
};
-export const snapshot = async (input: {
+type SnapshotInput = {
readonly page: Page;
readonly cdp: CDPSession;
readonly renderScale: number;
readonly consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
-}): Promise<PreviewAutomationSnapshot> => {
+};
+
+const capture = async (
+ input: SnapshotInput,
+ deadline: number,
+): Promise<PreviewAutomationSnapshot> => {
const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale));
const state = refsFor(input.page);
invalidateRefs(input.page);
const generation = state.generation;
- const [page, tree, data] = await Promise.all([
+ const { readers, read } = await openReaders(input.page, input.cdp);
+ const before = await read();
+ // Taken between the reads, so a value that changes during either fails the comparison.
+ // Awaited after the tree: a capture that fails has finished its tree before a retry starts.
+ const pageAndScreenshot = Promise.all([
input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
Pick<
PreviewAutomationSnapshot,
"url" | "title" | "loading" | "visibleText" | "interactiveElements"
>
>,
- input.page.ariaSnapshot({ mode: "ai", boxes: true, timeout: DEFAULT_TIMEOUT_MS }),
captureViewport(input.page, input.cdp, { format: "png", scale }),
]);
- if (state.generation !== generation) {
- throw new ServerBrowserOperationError(
- "PreviewAutomationExecutionError",
- "The page changed while capturing its snapshot. Take another snapshot.",
- );
+ void pageAndScreenshot.catch(constVoid);
+ // Leaves time for the second read; a frame that never loads holds the tree until then.
+ const tree = await input.page.ariaSnapshot({
+ mode: "ai",
+ boxes: true,
+ timeout: Math.max(1, deadline - Date.now() - 2_000),
+ });
+ const after = await read(before);
+ // A value that changed meanwhile may be in the tree under neither reading.
+ if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i])))
+ throw pageChanged();
+ const dotted = dottedPattern(after.flatMap((values) => values ?? []));
+ // A frame that didn't answer both times, such as one that crashed, can only hold values the
+ // tree shows if the tree shows its content.
+ const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames));
+ const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm;
+ for (const [, ref] of unread.length ? tree.matchAll(filled) : []) {
+ const iframe = await input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 });
+ if (!iframe) throw pageChanged();
+ const frame = await iframe.contentFrame();
+ void iframe.dispose().catch(constVoid);
+ if (frame && unread.includes(frame)) throw tooBusy();
}
- const accessibilityTree = tree
+ const [page, data] = await pageAndScreenshot;
+ if (state.generation !== generation) throw pageChanged();
+ const mask = (text: string) => (dotted ? text.replace(dotted, MASKED_VALUE) : text);
+ const accessibilityTree = (dotted ? maskTree(tree, dotted) : tree)
.slice(0, MAX_VISIBLE_TEXT_LENGTH)
.replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
const ref = `t3-${generation}-${nativeRef}`;
@@ -211,6 +464,9 @@ export const snapshot = async (input: {
});
return {
...page,
+ // Text that holds a value would otherwise show where the tree masked it. Masked before
+ // the cut, so a value crossing it can't leave its start showing.
+ visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH),
accessibilityTree,
consoleEntries: [...input.consoleEntries],
networkEntries: [...input.networkEntries],
@@ -224,6 +480,36 @@ export const snapshot = async (input: {
};
};
+/** Snapshots begun per page; observers' snapshots aren't queued, so two can overlap. */
+const snapshotTurns = new WeakMap<Page, number>();
+
+export const snapshot = async (input: SnapshotInput): Promise<PreviewAutomationSnapshot> => {
+ const deadline = Date.now() + SNAPSHOT_TIMEOUT_MS;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expired = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(tooBusy()), SNAPSHOT_TIMEOUT_MS);
+ });
+ const turn = (snapshotTurns.get(input.page) ?? 0) + 1;
+ snapshotTurns.set(input.page, turn);
+ // A page that changed mid-capture, like one rotating ads, has usually settled by a second
+ // try. None starts late or after another snapshot began, since it would revoke the refs of
+ // whichever snapshot came next.
+ const captured = capture(input, deadline).catch((cause: unknown) =>
+ Date.now() < deadline &&
+ snapshotTurns.get(input.page) === turn &&
+ !(cause instanceof Error && cause.message === VALUE_TOO_LONG)
+ ? capture(input, deadline)
+ : Promise.reject(cause),
+ );
+ try {
+ return await Promise.race([captured, expired]);
+ } catch (cause) {
+ throw cause instanceof Error && cause.name === "TimeoutError" ? tooBusy() : cause;
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
/**
* A click whose handler opens a dialog does not finish until the dialog is
* resolved, so it returns as soon as the dialog opens; status then reports it.
diff --git a/apps/server/src/serverLogger.test.ts b/apps/server/src/serverLogger.test.ts
index daf96782ed7..23eb39b3f5f 100644
--- a/apps/server/src/serverLogger.test.ts
+++ b/apps/server/src/serverLogger.test.ts
@@ -1,19 +1,29 @@
import * as NodePath from "@effect/platform-node/NodePath";
import { assert, describe, it } from "@effect/vitest";
import * as NodeOS from "node:os";
+import { ExternalLauncherBrowserSpawnError } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Tracer from "effect/Tracer";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
+import * as TestConsole from "effect/testing/TestConsole";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import * as ServerConfig from "./config.ts";
+import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as ServerLogger from "./serverLogger.ts";
+import {
+ announceStartupPairingUrl,
+ logBrowserAutoOpenUnavailable,
+ maybeOpenBrowser,
+} from "./serverRuntimeStartup.ts";
interface ExportedRequest {
readonly url: string;
@@ -100,7 +110,15 @@ const logThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
return requests;
});
-const logInSpanThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
+/**
+ * Runs `program` (one log line by default) inside a span so the tracer logger
+ * has somewhere to attach an event, then reports both what the collector
+ * received and what landed on the span.
+ */
+const logInSpanThrough = (
+ overrides: Partial<ServerConfig.ServerConfig["Service"]>,
+ program: Effect.Effect<void> = Effect.log("server logger under test"),
+) =>
Effect.gen(function* () {
const requests: Array<ExportedRequest> = [];
const spans: Array<Tracer.NativeSpan> = [];
@@ -114,7 +132,7 @@ const logInSpanThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"
},
}),
);
- yield* Effect.log("server logger under test").pipe(
+ yield* program.pipe(
Effect.withSpan("server-logger-test"),
Effect.provide(
Layer.mergeAll(
@@ -222,4 +240,79 @@ describe("ServerLoggerLive", () => {
assert.lengthOf(spans[0]?.events ?? [], 0);
}),
);
+
+ describe("startup pairing URL", () => {
+ const pairingToken = "PAIRTOKEN7Q4K9";
+ const pairingUrl = `http://localhost:3773/pair#token=${pairingToken}`;
+ const announce = announceStartupPairingUrl(pairingUrl).pipe(
+ Effect.andThen(logBrowserAutoOpenUnavailable),
+ );
+
+ it.effect("prints the full URL but keeps its token out of exported log records", () =>
+ Effect.gen(function* () {
+ const { requests } = yield* logInSpanThrough(
+ { otlpLogsUrl: "https://collector.example.com/v1/logs" },
+ announce,
+ );
+
+ const body = requests.map((request) => request.body).join("\n");
+ assert.include(body, "Authentication required");
+ assert.notInclude(body, pairingToken);
+ const printed = (yield* TestConsole.logLines).map((line) =>
+ Array.isArray(line) ? line.join(" ") : String(line),
+ );
+ assert.isTrue(printed.some((line) => line.includes(`pairingUrl: ${pairingUrl}`)));
+ }).pipe(Effect.provide(TestConsole.layer)),
+ );
+
+ it.effect("keeps the token off the span events the trace file records", () =>
+ Effect.gen(function* () {
+ const { spans } = yield* logInSpanThrough({}, announce);
+
+ const events = JSON.stringify(
+ spans.flatMap((span) => span.events.map(([name, , attributes]) => [name, attributes])),
+ );
+ assert.include(events, "Authentication required");
+ assert.notInclude(events, pairingToken);
+ }).pipe(Effect.provide(TestConsole.layer)),
+ );
+
+ it.effect("keeps the token out of traces when the browser fails to open", () =>
+ Effect.gen(function* () {
+ // A failed launch records its error, which names the target, on its span.
+ const failingLaunch = maybeOpenBrowser(pairingUrl).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ layerConfig({ noBrowser: false }),
+ Layer.mock(ExternalLauncher.ExternalLauncher)({
+ launchBrowser: (target) =>
+ Effect.fail(
+ new ExternalLauncherBrowserSpawnError({
+ target,
+ command: "xdg-open",
+ args: [target],
+ cause: new Error("spawn xdg-open ENOENT"),
+ }),
+ ).pipe(Effect.withSpan("externalLauncher.launchBrowser")),
+ }),
+ ),
+ ),
+ );
+ const { spans } = yield* logInSpanThrough({}, failingLaunch);
+
+ const recorded = JSON.stringify(
+ spans.map((span) => ({
+ name: span.name,
+ events: span.events.map(([name, , attributes]) => [name, attributes]),
+ exit:
+ span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
+ ? Cause.pretty(span.status.exit.cause)
+ : null,
+ })),
+ );
+ assert.include(recorded, "browser auto-open unavailable");
+ assert.notInclude(recorded, pairingToken);
+ }),
+ );
+ });
});
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index 4927234cfa4..78d9d3f0e0b 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -325,7 +325,24 @@ const resolveStartupBrowserTarget = Effect.gen(function* () {
: yield* serverAuth.issueStartupPairingUrl(baseTarget);
});
-const maybeOpenBrowser = (target: string) =>
+/**
+ * Prints the startup pairing URL to stdout, where `t3` users and the dev runner
+ * read it. The URL carries a one-time admin token, so it skips the logger: log
+ * records also land in the trace file and any configured OTLP collector.
+ */
+export const announceStartupPairingUrl = (pairingUrl: string) =>
+ Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
+ // Indented to match the annotation line the pretty logger printed before.
+ Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
+ );
+
+// No URL here: the browser target carries the pairing token, which
+// announceStartupPairingUrl has already printed to stdout.
+export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
+ hint: "Open the pairing URL above in your browser.",
+});
+
+export const maybeOpenBrowser = (target: string) =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
if (serverConfig.noBrowser) {
@@ -334,11 +351,10 @@ const maybeOpenBrowser = (target: string) =>
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
yield* externalLauncher.launchBrowser(target).pipe(
- Effect.catch(() =>
- Effect.logInfo("browser auto-open unavailable", {
- hint: `Open ${target} in your browser.`,
- }),
- ),
+ // The target carries the pairing token, and a failed launch records its
+ // command line on the span, so this call stays out of traces.
+ Effect.withTracerEnabled(false),
+ Effect.catch(() => logBrowserAutoOpenUnavailable),
);
});
@@ -596,9 +612,7 @@ const make = (options?: StartupOptions) =>
yield* Effect.logDebug("startup phase: browser open check");
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
- yield* Effect.logInfo(
- "Authentication required. Open T3 Code using the pairing URL.",
- ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
+ yield* announceStartupPairingUrl(startupBrowserTarget);
}
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
}
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index e20b293a23b..5287c5a3dbd 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1616,7 +1616,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
);
- it.effect("moves a saved Antigravity key to the secret store when settings load", () =>
+ it.effect("moves saved provider credentials to the secret store when settings load", () =>
Effect.gen(function* () {
const service = yield* ServerSettingsModule.ServerSettingsService;
const config = yield* ServerConfig.ServerConfig;
@@ -1626,20 +1626,44 @@ it.layer(NodeServices.layer)("server settings", (it) => {
JSON.stringify({
providerInstances: {
antigravity: { driver: "antigravity", config: { apiKey: "legacy-api-key" } },
+ opencode: {
+ driver: "opencode",
+ config: { serverUrl: "http://127.0.0.1:4096", serverPassword: "legacy-password" },
+ },
},
}),
);
const saved = yield* service.getSettings;
+ const opencode = ProviderInstanceId.make("opencode");
assert.propertyVal(
saved.providerInstances[ProviderInstanceId.make("antigravity")]?.config,
"apiKey",
"legacy-api-key",
);
- assert.notInclude(yield* fs.readFileString(config.settingsPath), "legacy-api-key");
- assert.notInclude(
- JSON.stringify(ServerSettingsModule.redactServerSettingsForClient(saved)),
- "legacy-api-key",
+ assert.propertyVal(
+ saved.providerInstances[opencode]?.config,
+ "serverPassword",
+ "legacy-password",
);
+ const client = ServerSettingsModule.redactServerSettingsForClient(saved);
+ for (const value of ["legacy-api-key", "legacy-password"]) {
+ assert.notInclude(yield* fs.readFileString(config.settingsPath), value);
+ assert.notInclude(JSON.stringify(client), value);
+ }
+ // Editing another field from the client's copy keeps the saved password.
+ const clientConfig = client.providerInstances[opencode]?.config as Record<string, unknown>;
+ const edited = yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: opencode,
+ instance: {
+ ...client.providerInstances[opencode]!,
+ config: { ...clientConfig, serverUrl: "http://127.0.0.1:4097" },
+ },
+ });
+ assert.deepInclude(edited.providerInstances[opencode]?.config, {
+ serverUrl: "http://127.0.0.1:4097",
+ serverPassword: "legacy-password",
+ });
}).pipe(Effect.provide(layerServerSettings())),
);
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
index ff1de91addc..644cd7242b9 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts
+++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { ProviderDriverKind } from "@t3tools/contracts";
+import { makeProviderSettingsSchema, ProviderDriverKind, TrimmedString } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
import { providerClients } from "./providerDriverMeta";
import {
@@ -30,11 +31,24 @@ describe("ProviderSettingsForm helpers", () => {
expect(serverPassword).toMatchObject({
label: "Server password",
- description: "Stored in plain text on disk.",
+ description: "Stored separately on the host.",
control: "password",
+ secret: true,
});
});
+ it("keeps every masked field as a stored secret", () => {
+ const settingsSchema = makeProviderSettingsSchema({
+ token: TrimmedString.pipe(
+ Schema.annotateKey({ providerSettingsForm: { control: "password" } }),
+ ),
+ });
+
+ expect(deriveProviderSettingsFields({ settingsSchema })).toMatchObject([
+ { key: "token", secret: true },
+ ]);
+ });
+
it("uses a dedicated environment field instead of legacy Cursor CLI settings", () => {
const cursor = providerClients.get(ProviderDriverKind.make("cursor"));
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx
index aa2c74dd44d..7c6cb1a2f7f 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx
@@ -377,6 +377,8 @@ function ProviderSettingsFieldRow({
if (variant === "settings") {
const descriptionId = field.description ? `${inputId}-description` : undefined;
+ const secretConfigured =
+ field.secret === true && readProviderConfigString(value, field.key).length > 0;
const control =
field.control === "switch" ? (
<Switch
@@ -409,15 +411,28 @@ function ProviderSettingsFieldRow({
spellCheck={false}
/>
) : field.secret ? (
- <SecretInput
- id={inputId}
- aria-describedby={descriptionId}
- size="sm"
- className="w-full max-w-full @min-[32rem]/settings-row:w-56"
- configured={readProviderConfigString(value, field.key).length > 0}
- value=""
- onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
- />
+ <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
+ <SecretInput
+ id={inputId}
+ aria-describedby={descriptionId}
+ size="sm"
+ className="min-w-0 flex-1"
+ configured={secretConfigured}
+ value=""
+ onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
+ />
+ {secretConfigured ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost-destructive"
+ onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
+ aria-label={`Clear ${field.label}`}
+ >
+ <XIcon className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
) : (
<DraftInput
id={inputId}
diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md
index 5af00816652..5d675e6eaa7 100644
--- a/docs/user/providers-antigravity.md
+++ b/docs/user/providers-antigravity.md
@@ -43,8 +43,8 @@ Choose **Sign-in method** in the Antigravity provider settings:
| Gemini API key | API key; choose Connect without a browser |
| Agent Platform / Vertex AI | API key, or GCP project and location with Application Default Credentials on the environment |
-The Antigravity API key field is stored in plain text in settings on the
-environment. The agent uses the method and credentials selected for this instance;
+The environment stores the Antigravity API key outside its settings file, and
+clients only see whether one is saved. The agent uses the method and credentials selected for this instance;
ambient `GEMINI_API_KEY` and Google credential variables do not override them.
Changing the method stops the instance's sessions. Sign out before replacing an
account.
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 60d2aceed7c..86d5dac194f 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -525,9 +525,13 @@ export function secretSetting<S extends Schema.Top>(schema: S): S["Rebuild"] {
return schema.annotateKey({ settingsSecret: true });
}
+/** A masked form field is a credential too, so none is saved or sent to clients as plain text. */
export function isSecretSetting(schema: Schema.Top): boolean {
const annotations = Schema.resolveAnnotationsKey(schema) ?? Schema.resolveAnnotations(schema);
- return annotations?.settingsSecret === true;
+ return (
+ annotations?.settingsSecret === true ||
+ annotations?.providerSettingsForm?.control === "password"
+ );
}
export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
diff --git a/packages/provider-opencode/src/settings.ts b/packages/provider-opencode/src/settings.ts
index 8573cdb4f12..9b1c267f103 100644
--- a/packages/provider-opencode/src/settings.ts
+++ b/packages/provider-opencode/src/settings.ts
@@ -6,6 +6,7 @@ import {
CustomModelSetting,
makeBinaryPathSetting,
makeProviderSettingsSchema,
+ secretSetting,
TrimmedString,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -39,10 +40,11 @@ export const OpenCodeSettings = makeProviderSettingsSchema(
}),
),
serverPassword: TrimmedString.pipe(
+ secretSetting,
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Server password",
- description: "Stored in plain text on disk.",
+ description: "Stored separately on the host.",
providerSettingsForm: {
control: "password",
placeholder: "Optional",