The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
fix(server): keep sensitive values out of settings reads, startup logs and preview snapshots (#20446)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 23:14 UTC
8653c8f09bb691e4ebdd1a2e62258f8911873ac7
11 files changed
+558
-44
apps/server/src/preview/ServerBrowser.test.ts
+9
-1
@@ -80,7 +80,15 @@ function makeSession(frame?: ReturnType<typeof makeFrame>) {
80
if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } };
81
if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" };
82
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
83
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
83
+ // Snapshots read password fields from their own isolated world in each frame.
84
+ if (method === "Page.createIsolatedWorld") {
85
+ return {
86
+ executionContextId: (input as { worldName?: string }).worldName === "t3-preview" ? 1 : 7,
87
+ };
88
+ }
89
+ if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) {
90
+ return { result: { value: [] } };
91
+ }
92
if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve();
93
if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) {
94
if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy;
apps/server/src/preview/ServerBrowserPage.test.ts
+54
@@ -124,6 +124,60 @@ describe("server browser element refs", () => {
124
expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
125
});
126
127
+ it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
128
+ await page.setContent(`
129
+ <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
130
+ <input aria-label="Username" value="maria">
131
+ <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
132
+ <input type="password" role="combobox" aria-label="Code" value="role-pass">
133
+ <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
134
+ <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
135
+ <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
136
+ <iframe id="blank" src="javascript:false"></iframe>
137
+ <p>Order styled-pass-2</p>
138
+ <script>
139
+ // A frame that never commits a document, filled by its parent.
140
+ blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
141
+ // Page script can't change the value the snapshot sees.
142
+ Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
143
+ </script>`);
144
+ await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
145
+ await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
146
+ const result = await takeSnapshot();
147
+ const tree = String(result.accessibilityTree);
148
+ expect(tree).toContain('textbox "blank"');
149
+ expect(tree).not.toMatch(
150
+ /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
151
+ );
152
+ expect(result.visibleText).not.toContain("editable-pass");
153
+ // Page text masks the same values, so it can't be compared against the tree.
154
+ expect(result.visibleText).toContain("Order ••••••••-2");
155
+ expect(tree).toMatch(/row "password: •+"/);
156
+ expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
157
+ const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
158
+ expect(line).toMatch(/: •+$/);
159
+ await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
160
+ expect(await page.locator("#pw").inputValue()).toBe("next");
161
+ });
162
+
163
+ it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
164
+ await page.setContent(`
165
+ <input type="password" aria-label="PIN" value="123">
166
+ <input type="password" aria-label="Phrase" value="open sesame">
167
+ <p>PIN: 123. Code (123) id 1234</p>
168
+ <p>open sesame</p>`);
169
+ const text = (await takeSnapshot()).visibleText;
170
+ expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
171
+ expect(text).not.toMatch(/open|sesame/);
172
+ await page.setContent(`
173
+ <p>${"x".repeat(19_995)}long-secret</p>
174
+ <input type="password" aria-label="Long" value="long-secret">`);
175
+ const cut = (await takeSnapshot()).visibleText;
176
+ expect(cut.length).toBe(20_000);
177
+ // Masked before the cut, so no prefix of the value is left.
178
+ expect(cut.slice(-8)).toBe("xxx•••••");
179
+ });
180
+
181
it("rejects refs from another tab", async () => {
182
await page.setContent("<button>same label</button>");
183
const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
apps/server/src/preview/ServerBrowserPage.ts
+298
-12
@@ -18,7 +18,7 @@ import {
18
type PreviewAutomationWaitForInput,
19
} from "@t3tools/contracts";
20
import { constVoid } from "effect/Function";
21
-import type { CDPSession, Locator, Page } from "playwright-core";
21
+import type { CDPSession, Frame, Locator, Page } from "playwright-core";
22
import * as NodeCrypto from "node:crypto";
23
import { BrowserControlInterrupted } from "./SessionControl.ts";
24
@@ -143,11 +143,236 @@ const SNAPSHOT_SCRIPT = `(() => {
143
url: location.href,
144
title: document.title,
145
loading: document.readyState !== "complete",
146
- visibleText: (document.body?.innerText || "").slice(0, ${MAX_VISIBLE_TEXT_LENGTH}),
146
+ visibleText: document.body?.innerText || "",
147
interactiveElements: [],
148
};
149
})()`;
150
151
+const MASKED_VALUE = "••••••••";
152
+// The broker waits 15s for the host; a snapshot, retry included, answers well before.
153
+const SNAPSHOT_TIMEOUT_MS = 10_000;
154
+// How long a frame in another process gets to answer; one that crashed never does.
155
+const FRAME_ANSWER_MS = 1_000;
156
+
157
+// Values the page draws as dots (password fields, and text fields whose CSS
158
+// draws dots), normalized like accessible text. Open shadow roots included.
159
+const DOTTED_SCRIPT = `(() => {
160
+ const values = [];
161
+ const visit = (root) => {
162
+ for (const element of root.querySelectorAll("*")) {
163
+ if (element.shadowRoot) visit(element.shadowRoot);
164
+ const field = element.localName === "input" || element.localName === "textarea";
165
+ if (!field && !element.isContentEditable) continue;
166
+ const dots = getComputedStyle(element).getPropertyValue("-webkit-text-security");
167
+ if (element.type !== "password" && (dots === "none" || dots === "")) continue;
168
+ // Raw as page text shows it, and normalized as the tree does.
169
+ for (const value of field ? [element.value, element.defaultValue] : [element.textContent ?? ""])
170
+ values.push(value, value.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " "));
171
+ }
172
+ };
173
+ visit(document);
174
+ return [...new Set(values.filter((value) => value.trim()))];
175
+})()`;
176
+
177
+const pageChanged = () =>
178
+ new ServerBrowserOperationError(
179
+ "PreviewAutomationExecutionError",
180
+ "The page changed while capturing its snapshot. Take another snapshot.",
181
+ );
182
+
183
+const tooBusy = () =>
184
+ new ServerBrowserOperationError(
185
+ "PreviewAutomationTimeoutError",
186
+ "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",
187
+ );
188
+
189
+const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken.";
190
+
191
+/** A frame in another process keeps one CDP session, so none pile up across snapshots. */
192
+const frameSessions = new WeakMap<Frame, Promise<CDPSession>>();
193
+
194
+/** The value, or undefined when it fails or takes longer than a frame may. */
195
+const answered = <A>(promise: Promise<A>) => {
196
+ let timer: ReturnType<typeof setTimeout> | undefined;
197
+ const late = new Promise<undefined>((resolve) => {
198
+ timer = setTimeout(() => resolve(undefined), FRAME_ANSWER_MS);
199
+ });
200
+ return Promise.race([promise.catch(() => undefined), late]).finally(() => clearTimeout(timer));
201
+};
202
+
203
+/**
204
+ * Reads dotted values in isolated worlds, where page script can't change what `value`
205
+ * returns, through the CDP session of the process each frame renders in. A frame in
206
+ * another process that can't be attached, as in desktop tabs where only the page can,
207
+ * is read in the page's own world, where its script can change `value`. `read` gives
208
+ * each reader's values, or undefined for one that didn't answer, and fails when the
209
+ * page's own frames don't or frames came or went.
210
+ */
211
+const openReaders = async (page: Page, cdp: CDPSession) => {
212
+ const frames = page.frames();
213
+ const owners = new Map<Frame, CDPSession | null | undefined>(
214
+ await Promise.all(
215
+ frames.map(async (frame) => {
216
+ if (frame === page.mainFrame()) return [frame, cdp] as const;
217
+ const session = frameSessions.get(frame) ?? page.context().newCDPSession(frame);
218
+ frameSessions.set(frame, session);
219
+ try {
220
+ return [frame, await session] as const;
221
+ } catch (cause) {
222
+ frameSessions.delete(frame);
223
+ // CdpRelay refuses all but the page. Any other refusal reads the frame through its
224
+ // parent's session, which fails the read if the frame isn't there.
225
+ const desktop = String(cause).includes("Only this preview tab's page can be attached");
226
+ return [frame, desktop ? null : undefined] as const;
227
+ }
228
+ }),
229
+ ),
230
+ );
231
+ const ownerOf = (frame: Frame): CDPSession | null => {
232
+ const owner = owners.get(frame);
233
+ if (owner !== undefined) return owner;
234
+ const parent = frame.parentFrame();
235
+ return parent ? ownerOf(parent) : null;
236
+ };
237
+ const sessionReader = (frame: Frame, session: CDPSession) => {
238
+ const owned = frames.filter((each) => ownerOf(each) === session);
239
+ const open = async () => {
240
+ const { frameTree } = await session.send("Page.getFrameTree");
241
+ const ids = (node: typeof frameTree): Array<string> => [
242
+ node.frame.id,
243
+ ...(node.childFrames ?? []).flatMap(ids),
244
+ ];
245
+ // A frame Playwright knows but this session doesn't would go unread.
246
+ if (ids(frameTree).length !== owned.length) throw pageChanged();
247
+ return Promise.all(
248
+ ids(frameTree).map(async (frameId) => {
249
+ const world = await session.send("Page.createIsolatedWorld", {
250
+ frameId,
251
+ worldName: "t3-preview",
252
+ });
253
+ return world.executionContextId;
254
+ }),
255
+ );
256
+ };
257
+ let contexts: ReturnType<typeof open> | undefined;
258
+ const read = async () => {
259
+ const values = (contexts ??= open()).then((ids) =>
260
+ Promise.all(
261
+ ids.map(async (contextId) => {
262
+ const { result, exceptionDetails } = await session.send("Runtime.evaluate", {
263
+ contextId,
264
+ expression: DOTTED_SCRIPT,
265
+ returnByValue: true,
266
+ });
267
+ if (exceptionDetails) throw pageChanged();
268
+ return result.value as Array<string>;
269
+ }),
270
+ ),
271
+ );
272
+ try {
273
+ return (await values).flat();
274
+ } catch (cause) {
275
+ // The frame may have moved to another process; the next snapshot opens a new session.
276
+ if (session !== cdp) {
277
+ frameSessions.delete(frame);
278
+ void session.detach().catch(constVoid);
279
+ }
280
+ throw cause;
281
+ }
282
+ };
283
+ return { frames: owned, read };
284
+ };
285
+ const readers = [
286
+ sessionReader(page.mainFrame(), cdp),
287
+ ...frames.flatMap((frame) => {
288
+ const owner = owners.get(frame);
289
+ if (owner) return owner === cdp ? [] : [sessionReader(frame, owner)];
290
+ const own = () => frame.evaluate(DOTTED_SCRIPT) as Promise<Array<string>>;
291
+ return ownerOf(frame) === null ? [{ frames: [frame], read: own }] : [];
292
+ }),
293
+ ];
294
+ return {
295
+ readers,
296
+ /** Readers that didn't answer `before` aren't asked again. */
297
+ read: async (before?: ReadonlyArray<unknown>) => {
298
+ const now = page.frames();
299
+ // A frame added since the readers opened has none.
300
+ if (now.length !== frames.length || now.some((frame, i) => frame !== frames[i])) {
301
+ throw pageChanged();
302
+ }
303
+ return Promise.all(
304
+ readers.map((reader, i) => {
305
+ if (i === 0) return reader.read().catch(() => Promise.reject(pageChanged()));
306
+ return before && !before[i] ? undefined : answered(reader.read());
307
+ }),
308
+ );
309
+ },
310
+ };
311
+};
312
+
313
+/**
314
+ * Matches each value as the snapshot prints it: raw, as a JSON name, as a
315
+ * quoted value, and with '' for each quote inside a quoted key. A value under
316
+ * four characters only matches between non-word characters; inside other words
317
+ * it would mask unrelated text.
318
+ */
319
+const dottedPattern = (values: ReadonlyArray<string>) => {
320
+ const sources = values
321
+ .flatMap((value) => {
322
+ const json = JSON.stringify(value).slice(1, -1);
323
+ // Playwright writes control characters like JSON does, with \xNN for the unnamed ones.
324
+ const quoted = value.replace(/[\\"\p{Cc}]/gu, (char) =>
325
+ '\\"\b\f\n\r\t'.includes(char)
326
+ ? JSON.stringify(char).slice(1, -1)
327
+ : `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`,
328
+ );
329
+ const forms = [value, json, quoted].flatMap((form) => [form, form.replaceAll("'", "''")]);
330
+ return [...new Set(forms)].map((form) => ({ form, word: value.length < 4 }));
331
+ })
332
+ // Longest first, so a form inside another never leaves the rest showing.
333
+ .toSorted((a, b) => b.form.length - a.form.length)
334
+ .map(({ form, word }) => {
335
+ const literal = form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
336
+ return word ? `(?<![\\p{L}\\p{N}_])${literal}(?![\\p{L}\\p{N}_])` : literal;
337
+ });
338
+ if (sources.length === 0) return undefined;
339
+ const pattern = new RegExp(sources.join("|"), "gu");
340
+ try {
341
+ // Compiles it now, for one-byte and two-byte text: one too large fails only when it
342
+ // first runs on each, naming every value.
343
+ pattern.test("");
344
+ pattern.test("\u2022");
345
+ } catch {
346
+ throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG);
347
+ }
348
+ return pattern;
349
+};
350
+
351
+// `- role "name" [attribute]...: value`, the key single-quoted when it holds ": ". A name
352
+// that starts and ends with "/" prints unquoted. Only Playwright's own attributes count, so
353
+// text around a value in a name can't pass for one.
354
+const TREE_LINE =
355
+ /^(\s*- '?[^\s"':]+)( "(?:[^"\\]|\\.)*"| \/(?:.*?\/)?)?((?: \[(?:active|checked(?:=mixed)?|disabled|expanded|level=\d+|pressed(?:=mixed)?|selected|ref=(?:f\d+)?e\d+|cursor=pointer|box=-?\d+,-?\d+,\d+,\d+)\])*'?)(:.*)?$/;
356
+
357
+/**
358
+ * Masks each value on a line, except one that only matches inside the role or attributes,
359
+ * so refs keep working. A "/.../" name has no closing mark, so a value can seem to cross it.
360
+ */
361
+const maskTree = (tree: string, dotted: RegExp) =>
362
+ tree
363
+ .split("\n")
364
+ .map((line) => {
365
+ const node = TREE_LINE.exec(line);
366
+ const name = node?.[1]?.length ?? 0;
367
+ const attributes = name + (node?.[2]?.length ?? 0);
368
+ const end = attributes + (node?.[3]?.length ?? 0);
369
+ const kept = (from: number, to: number) => to <= name || (from >= attributes && to <= end);
370
+ return line.replace(dotted, (match: string, offset: number) =>
371
+ kept(offset, offset + match.length) ? match : MASKED_VALUE,
372
+ );
373
+ })
374
+ .join("\n");
375
+
376
// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
377
export const captureViewport = async (
378
page: Page,
@@ -173,36 +398,64 @@ export const captureViewport = async (
398
return data;
399
};
400
176
-export const snapshot = async (input: {
401
+type SnapshotInput = {
402
readonly page: Page;
403
readonly cdp: CDPSession;
404
readonly renderScale: number;
405
readonly consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
406
readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
407
readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
183
-}): Promise<PreviewAutomationSnapshot> => {
408
+};
409
+
410
+const capture = async (
411
+ input: SnapshotInput,
412
+ deadline: number,
413
+): Promise<PreviewAutomationSnapshot> => {
414
const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
415
const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale));
416
const state = refsFor(input.page);
417
invalidateRefs(input.page);
418
const generation = state.generation;
189
- const [page, tree, data] = await Promise.all([
419
+ const { readers, read } = await openReaders(input.page, input.cdp);
420
+ const before = await read();
421
+ // Taken between the reads, so a value that changes during either fails the comparison.
422
+ // Awaited after the tree: a capture that fails has finished its tree before a retry starts.
423
+ const pageAndScreenshot = Promise.all([
424
input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
425
Pick<
426
PreviewAutomationSnapshot,
427
"url" | "title" | "loading" | "visibleText" | "interactiveElements"
428
>
429
>,
196
- input.page.ariaSnapshot({ mode: "ai", boxes: true, timeout: DEFAULT_TIMEOUT_MS }),
430
captureViewport(input.page, input.cdp, { format: "png", scale }),
431
]);
199
- if (state.generation !== generation) {
200
- throw new ServerBrowserOperationError(
201
- "PreviewAutomationExecutionError",
202
- "The page changed while capturing its snapshot. Take another snapshot.",
203
- );
432
+ void pageAndScreenshot.catch(constVoid);
433
+ // Leaves time for the second read; a frame that never loads holds the tree until then.
434
+ const tree = await input.page.ariaSnapshot({
435
+ mode: "ai",
436
+ boxes: true,
437
+ timeout: Math.max(1, deadline - Date.now() - 2_000),
438
+ });
439
+ const after = await read(before);
440
+ // A value that changed meanwhile may be in the tree under neither reading.
441
+ if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i])))
442
+ throw pageChanged();
443
+ const dotted = dottedPattern(after.flatMap((values) => values ?? []));
444
+ // A frame that didn't answer both times, such as one that crashed, can only hold values the
445
+ // tree shows if the tree shows its content.
446
+ const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames));
447
+ const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm;
448
+ for (const [, ref] of unread.length ? tree.matchAll(filled) : []) {
449
+ const iframe = await input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 });
450
+ if (!iframe) throw pageChanged();
451
+ const frame = await iframe.contentFrame();
452
+ void iframe.dispose().catch(constVoid);
453
+ if (frame && unread.includes(frame)) throw tooBusy();
454
}
205
- const accessibilityTree = tree
455
+ const [page, data] = await pageAndScreenshot;
456
+ if (state.generation !== generation) throw pageChanged();
457
+ const mask = (text: string) => (dotted ? text.replace(dotted, MASKED_VALUE) : text);
458
+ const accessibilityTree = (dotted ? maskTree(tree, dotted) : tree)
459
.slice(0, MAX_VISIBLE_TEXT_LENGTH)
460
.replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
461
const ref = `t3-${generation}-${nativeRef}`;
@@ -211,6 +464,9 @@ export const snapshot = async (input: {
464
});
465
return {
466
...page,
467
+ // Text that holds a value would otherwise show where the tree masked it. Masked before
468
+ // the cut, so a value crossing it can't leave its start showing.
469
+ visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH),
470
accessibilityTree,
471
consoleEntries: [...input.consoleEntries],
472
networkEntries: [...input.networkEntries],
@@ -224,6 +480,36 @@ export const snapshot = async (input: {
480
};
481
};
482
483
+/** Snapshots begun per page; observers' snapshots aren't queued, so two can overlap. */
484
+const snapshotTurns = new WeakMap<Page, number>();
485
+
486
+export const snapshot = async (input: SnapshotInput): Promise<PreviewAutomationSnapshot> => {
487
+ const deadline = Date.now() + SNAPSHOT_TIMEOUT_MS;
488
+ let timer: ReturnType<typeof setTimeout> | undefined;
489
+ const expired = new Promise<never>((_, reject) => {
490
+ timer = setTimeout(() => reject(tooBusy()), SNAPSHOT_TIMEOUT_MS);
491
+ });
492
+ const turn = (snapshotTurns.get(input.page) ?? 0) + 1;
493
+ snapshotTurns.set(input.page, turn);
494
+ // A page that changed mid-capture, like one rotating ads, has usually settled by a second
495
+ // try. None starts late or after another snapshot began, since it would revoke the refs of
496
+ // whichever snapshot came next.
497
+ const captured = capture(input, deadline).catch((cause: unknown) =>
498
+ Date.now() < deadline &&
499
+ snapshotTurns.get(input.page) === turn &&
500
+ !(cause instanceof Error && cause.message === VALUE_TOO_LONG)
501
+ ? capture(input, deadline)
502
+ : Promise.reject(cause),
503
+ );
504
+ try {
505
+ return await Promise.race([captured, expired]);
506
+ } catch (cause) {
507
+ throw cause instanceof Error && cause.name === "TimeoutError" ? tooBusy() : cause;
508
+ } finally {
509
+ clearTimeout(timer);
510
+ }
511
+};
512
+
513
/**
514
* A click whose handler opens a dialog does not finish until the dialog is
515
* resolved, so it returns as soon as the dialog opens; status then reports it.
apps/server/src/serverLogger.test.ts
+95
-2
@@ -1,19 +1,29 @@
1
import * as NodePath from "@effect/platform-node/NodePath";
2
import { assert, describe, it } from "@effect/vitest";
3
import * as NodeOS from "node:os";
4
+import { ExternalLauncherBrowserSpawnError } from "@t3tools/contracts";
5
+import * as Cause from "effect/Cause";
6
import * as ConfigProvider from "effect/ConfigProvider";
7
import * as Effect from "effect/Effect";
8
+import * as Exit from "effect/Exit";
9
import * as Layer from "effect/Layer";
10
import * as Path from "effect/Path";
11
import * as Tracer from "effect/Tracer";
12
import * as HttpClient from "effect/http/HttpClient";
13
import * as HttpClientResponse from "effect/http/HttpClientResponse";
14
+import * as TestConsole from "effect/testing/TestConsole";
15
16
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
17
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
18
19
import * as ServerConfig from "./config.ts";
20
+import * as ExternalLauncher from "./process/externalLauncher.ts";
21
import * as ServerLogger from "./serverLogger.ts";
22
+import {
23
+ announceStartupPairingUrl,
24
+ logBrowserAutoOpenUnavailable,
25
+ maybeOpenBrowser,
26
+} from "./serverRuntimeStartup.ts";
27
28
interface ExportedRequest {
29
readonly url: string;
@@ -100,7 +110,15 @@ const logThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
110
return requests;
111
});
112
103
-const logInSpanThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
113
+/**
114
+ * Runs `program` (one log line by default) inside a span so the tracer logger
115
+ * has somewhere to attach an event, then reports both what the collector
116
+ * received and what landed on the span.
117
+ */
118
+const logInSpanThrough = (
119
+ overrides: Partial<ServerConfig.ServerConfig["Service"]>,
120
+ program: Effect.Effect<void> = Effect.log("server logger under test"),
121
+) =>
122
Effect.gen(function* () {
123
const requests: Array<ExportedRequest> = [];
124
const spans: Array<Tracer.NativeSpan> = [];
@@ -114,7 +132,7 @@ const logInSpanThrough = (overrides: Partial<ServerConfig.ServerConfig["Service"
132
},
133
}),
134
);
117
- yield* Effect.log("server logger under test").pipe(
135
+ yield* program.pipe(
136
Effect.withSpan("server-logger-test"),
137
Effect.provide(
138
Layer.mergeAll(
@@ -222,4 +240,79 @@ describe("ServerLoggerLive", () => {
240
assert.lengthOf(spans[0]?.events ?? [], 0);
241
}),
242
);
243
+
244
+ describe("startup pairing URL", () => {
245
+ const pairingToken = "PAIRTOKEN7Q4K9";
246
+ const pairingUrl = `http://localhost:3773/pair#token=${pairingToken}`;
247
+ const announce = announceStartupPairingUrl(pairingUrl).pipe(
248
+ Effect.andThen(logBrowserAutoOpenUnavailable),
249
+ );
250
+
251
+ it.effect("prints the full URL but keeps its token out of exported log records", () =>
252
+ Effect.gen(function* () {
253
+ const { requests } = yield* logInSpanThrough(
254
+ { otlpLogsUrl: "https://collector.example.com/v1/logs" },
255
+ announce,
256
+ );
257
+
258
+ const body = requests.map((request) => request.body).join("\n");
259
+ assert.include(body, "Authentication required");
260
+ assert.notInclude(body, pairingToken);
261
+ const printed = (yield* TestConsole.logLines).map((line) =>
262
+ Array.isArray(line) ? line.join(" ") : String(line),
263
+ );
264
+ assert.isTrue(printed.some((line) => line.includes(`pairingUrl: ${pairingUrl}`)));
265
+ }).pipe(Effect.provide(TestConsole.layer)),
266
+ );
267
+
268
+ it.effect("keeps the token off the span events the trace file records", () =>
269
+ Effect.gen(function* () {
270
+ const { spans } = yield* logInSpanThrough({}, announce);
271
+
272
+ const events = JSON.stringify(
273
+ spans.flatMap((span) => span.events.map(([name, , attributes]) => [name, attributes])),
274
+ );
275
+ assert.include(events, "Authentication required");
276
+ assert.notInclude(events, pairingToken);
277
+ }).pipe(Effect.provide(TestConsole.layer)),
278
+ );
279
+
280
+ it.effect("keeps the token out of traces when the browser fails to open", () =>
281
+ Effect.gen(function* () {
282
+ // A failed launch records its error, which names the target, on its span.
283
+ const failingLaunch = maybeOpenBrowser(pairingUrl).pipe(
284
+ Effect.provide(
285
+ Layer.mergeAll(
286
+ layerConfig({ noBrowser: false }),
287
+ Layer.mock(ExternalLauncher.ExternalLauncher)({
288
+ launchBrowser: (target) =>
289
+ Effect.fail(
290
+ new ExternalLauncherBrowserSpawnError({
291
+ target,
292
+ command: "xdg-open",
293
+ args: [target],
294
+ cause: new Error("spawn xdg-open ENOENT"),
295
+ }),
296
+ ).pipe(Effect.withSpan("externalLauncher.launchBrowser")),
297
+ }),
298
+ ),
299
+ ),
300
+ );
301
+ const { spans } = yield* logInSpanThrough({}, failingLaunch);
302
+
303
+ const recorded = JSON.stringify(
304
+ spans.map((span) => ({
305
+ name: span.name,
306
+ events: span.events.map(([name, , attributes]) => [name, attributes]),
307
+ exit:
308
+ span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
309
+ ? Cause.pretty(span.status.exit.cause)
310
+ : null,
311
+ })),
312
+ );
313
+ assert.include(recorded, "browser auto-open unavailable");
314
+ assert.notInclude(recorded, pairingToken);
315
+ }),
316
+ );
317
+ });
318
});
apps/server/src/serverRuntimeStartup.ts
+23
-9
@@ -325,7 +325,24 @@ const resolveStartupBrowserTarget = Effect.gen(function* () {
325
: yield* serverAuth.issueStartupPairingUrl(baseTarget);
326
});
327
328
-const maybeOpenBrowser = (target: string) =>
328
+/**
329
+ * Prints the startup pairing URL to stdout, where `t3` users and the dev runner
330
+ * read it. The URL carries a one-time admin token, so it skips the logger: log
331
+ * records also land in the trace file and any configured OTLP collector.
332
+ */
333
+export const announceStartupPairingUrl = (pairingUrl: string) =>
334
+ Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
335
+ // Indented to match the annotation line the pretty logger printed before.
336
+ Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
337
+ );
338
+
339
+// No URL here: the browser target carries the pairing token, which
340
+// announceStartupPairingUrl has already printed to stdout.
341
+export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
342
+ hint: "Open the pairing URL above in your browser.",
343
+});
344
+
345
+export const maybeOpenBrowser = (target: string) =>
346
Effect.gen(function* () {
347
const serverConfig = yield* ServerConfig.ServerConfig;
348
if (serverConfig.noBrowser) {
@@ -334,11 +351,10 @@ const maybeOpenBrowser = (target: string) =>
351
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
352
353
yield* externalLauncher.launchBrowser(target).pipe(
337
- Effect.catch(() =>
338
- Effect.logInfo("browser auto-open unavailable", {
339
- hint: `Open ${target} in your browser.`,
340
- }),
341
- ),
354
+ // The target carries the pairing token, and a failed launch records its
355
+ // command line on the span, so this call stays out of traces.
356
+ Effect.withTracerEnabled(false),
357
+ Effect.catch(() => logBrowserAutoOpenUnavailable),
358
);
359
});
360
@@ -596,9 +612,7 @@ const make = (options?: StartupOptions) =>
612
yield* Effect.logDebug("startup phase: browser open check");
613
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
614
if (serverConfig.mode !== "desktop") {
599
- yield* Effect.logInfo(
600
- "Authentication required. Open T3 Code using the pairing URL.",
601
- ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
615
+ yield* announceStartupPairingUrl(startupBrowserTarget);
616
}
617
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
618
}
apps/server/src/serverSettings.test.ts
+29
-5
@@ -1616,7 +1616,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1616
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1617
);
1618
1619
- it.effect("moves a saved Antigravity key to the secret store when settings load", () =>
1619
+ it.effect("moves saved provider credentials to the secret store when settings load", () =>
1620
Effect.gen(function* () {
1621
const service = yield* ServerSettingsModule.ServerSettingsService;
1622
const config = yield* ServerConfig.ServerConfig;
@@ -1626,20 +1626,44 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1626
JSON.stringify({
1627
providerInstances: {
1628
antigravity: { driver: "antigravity", config: { apiKey: "legacy-api-key" } },
1629
+ opencode: {
1630
+ driver: "opencode",
1631
+ config: { serverUrl: "http://127.0.0.1:4096", serverPassword: "legacy-password" },
1632
+ },
1633
},
1634
}),
1635
);
1636
const saved = yield* service.getSettings;
1637
+ const opencode = ProviderInstanceId.make("opencode");
1638
assert.propertyVal(
1639
saved.providerInstances[ProviderInstanceId.make("antigravity")]?.config,
1640
"apiKey",
1641
"legacy-api-key",
1642
);
1638
- assert.notInclude(yield* fs.readFileString(config.settingsPath), "legacy-api-key");
1639
- assert.notInclude(
1640
- JSON.stringify(ServerSettingsModule.redactServerSettingsForClient(saved)),
1641
- "legacy-api-key",
1643
+ assert.propertyVal(
1644
+ saved.providerInstances[opencode]?.config,
1645
+ "serverPassword",
1646
+ "legacy-password",
1647
);
1648
+ const client = ServerSettingsModule.redactServerSettingsForClient(saved);
1649
+ for (const value of ["legacy-api-key", "legacy-password"]) {
1650
+ assert.notInclude(yield* fs.readFileString(config.settingsPath), value);
1651
+ assert.notInclude(JSON.stringify(client), value);
1652
+ }
1653
+ // Editing another field from the client's copy keeps the saved password.
1654
+ const clientConfig = client.providerInstances[opencode]?.config as Record<string, unknown>;
1655
+ const edited = yield* service.updateProviderInstance({
1656
+ operation: "upsert",
1657
+ instanceId: opencode,
1658
+ instance: {
1659
+ ...client.providerInstances[opencode]!,
1660
+ config: { ...clientConfig, serverUrl: "http://127.0.0.1:4097" },
1661
+ },
1662
+ });
1663
+ assert.deepInclude(edited.providerInstances[opencode]?.config, {
1664
+ serverUrl: "http://127.0.0.1:4097",
1665
+ serverPassword: "legacy-password",
1666
+ });
1667
}).pipe(Effect.provide(layerServerSettings())),
1668
);
1669
apps/web/src/components/settings/ProviderSettingsForm.test.ts
+16
-2
@@ -1,5 +1,6 @@
1
import { describe, expect, it } from "vite-plus/test";
2
-import { ProviderDriverKind } from "@t3tools/contracts";
2
+import { makeProviderSettingsSchema, ProviderDriverKind, TrimmedString } from "@t3tools/contracts";
3
+import * as Schema from "effect/Schema";
4
5
import { providerClients } from "./providerDriverMeta";
6
import {
@@ -30,11 +31,24 @@ describe("ProviderSettingsForm helpers", () => {
31
32
expect(serverPassword).toMatchObject({
33
label: "Server password",
33
- description: "Stored in plain text on disk.",
34
+ description: "Stored separately on the host.",
35
control: "password",
36
+ secret: true,
37
});
38
});
39
40
+ it("keeps every masked field as a stored secret", () => {
41
+ const settingsSchema = makeProviderSettingsSchema({
42
+ token: TrimmedString.pipe(
43
+ Schema.annotateKey({ providerSettingsForm: { control: "password" } }),
44
+ ),
45
+ });
46
+
47
+ expect(deriveProviderSettingsFields({ settingsSchema })).toMatchObject([
48
+ { key: "token", secret: true },
49
+ ]);
50
+ });
51
+
52
it("uses a dedicated environment field instead of legacy Cursor CLI settings", () => {
53
const cursor = providerClients.get(ProviderDriverKind.make("cursor"));
54
apps/web/src/components/settings/ProviderSettingsForm.tsx
+24
-9
@@ -377,6 +377,8 @@ function ProviderSettingsFieldRow({
377
378
if (variant === "settings") {
379
const descriptionId = field.description ? `${inputId}-description` : undefined;
380
+ const secretConfigured =
381
+ field.secret === true && readProviderConfigString(value, field.key).length > 0;
382
const control =
383
field.control === "switch" ? (
384
<Switch
@@ -409,15 +411,28 @@ function ProviderSettingsFieldRow({
411
spellCheck={false}
412
/>
413
) : field.secret ? (
412
- <SecretInput
413
- id={inputId}
414
- aria-describedby={descriptionId}
415
- size="sm"
416
- className="w-full max-w-full @min-[32rem]/settings-row:w-56"
417
- configured={readProviderConfigString(value, field.key).length > 0}
418
- value=""
419
- onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
420
- />
414
+ <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
415
+ <SecretInput
416
+ id={inputId}
417
+ aria-describedby={descriptionId}
418
+ size="sm"
419
+ className="min-w-0 flex-1"
420
+ configured={secretConfigured}
421
+ value=""
422
+ onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
423
+ />
424
+ {secretConfigured ? (
425
+ <Button
426
+ type="button"
427
+ size="icon-sm"
428
+ variant="ghost-destructive"
429
+ onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
430
+ aria-label={`Clear ${field.label}`}
431
+ >
432
+ <XIcon className="size-3.5" />
433
+ </Button>
434
+ ) : null}
435
+ </div>
436
) : (
437
<DraftInput
438
id={inputId}
docs/user/providers-antigravity.md
+2
-2
@@ -43,8 +43,8 @@ Choose **Sign-in method** in the Antigravity provider settings:
43
| Gemini API key | API key; choose Connect without a browser |
44
| Agent Platform / Vertex AI | API key, or GCP project and location with Application Default Credentials on the environment |
45
46
-The Antigravity API key field is stored in plain text in settings on the
47
-environment. The agent uses the method and credentials selected for this instance;
46
+The environment stores the Antigravity API key outside its settings file, and
47
+clients only see whether one is saved. The agent uses the method and credentials selected for this instance;
48
ambient `GEMINI_API_KEY` and Google credential variables do not override them.
49
Changing the method stops the instance's sessions. Sign out before replacing an
50
account.
packages/contracts/src/settings.ts
+5
-1
@@ -525,9 +525,13 @@ export function secretSetting<S extends Schema.Top>(schema: S): S["Rebuild"] {
525
return schema.annotateKey({ settingsSecret: true });
526
}
527
528
+/** A masked form field is a credential too, so none is saved or sent to clients as plain text. */
529
export function isSecretSetting(schema: Schema.Top): boolean {
530
const annotations = Schema.resolveAnnotationsKey(schema) ?? Schema.resolveAnnotations(schema);
530
- return annotations?.settingsSecret === true;
531
+ return (
532
+ annotations?.settingsSecret === true ||
533
+ annotations?.providerSettingsForm?.control === "password"
534
+ );
535
}
536
537
export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
packages/provider-opencode/src/settings.ts
+3
-1
@@ -6,6 +6,7 @@ import {
6
CustomModelSetting,
7
makeBinaryPathSetting,
8
makeProviderSettingsSchema,
9
+ secretSetting,
10
TrimmedString,
11
} from "@t3tools/contracts";
12
import * as Effect from "effect/Effect";
@@ -39,10 +40,11 @@ export const OpenCodeSettings = makeProviderSettingsSchema(
40
}),
41
),
42
serverPassword: TrimmedString.pipe(
43
+ secretSetting,
44
Schema.withDecodingDefault(Effect.succeed("")),
45
Schema.annotateKey({
46
title: "Server password",
45
- description: "Stored in plain text on disk.",
47
+ description: "Stored separately on the host.",
48
providerSettingsForm: {
49
control: "password",
50
placeholder: "Optional",