Skip to content
7 changes: 7 additions & 0 deletions .changeset/teach-secrets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"turno-browser": patch
---

Teach mode and flow recording: a card number or expiry field named like one (`cardnumber`, `card_number`, `ccNum`, `card-expiry`) now counts as a card field without an `autocomplete` value, so a flow keeps no value for it. The vault's values are read from the secret store when teach mode or a recording starts and held in memory only, so a vault value typed by hand keeps no default before `browser_login` has run: a user name as the whole typed value (case aside), a password also inside other text when it has at least 4 characters. A vault value the page shows is kept in no locator, fingerprint or element name, and a trace pauses before a vault value is typed. A recorded `browser_navigate` step keeps its address without query string or fragment.

A taught vault sign-in now starts only at a password or one-time code input. It takes in the user name typed into the same form on that page across a box checked or a key, and no typing before a submit, so a sign-in that asks the user name first replays as shown. Later typing is taken in only into the fields it took in. The person's own submit ends the sign-in, and is dropped only when `browser_login` will submit: with the identity's policy at `"autoSubmit": false` the submit stays a step. What the person does in the sign-in's form before submitting (a box checked, Tab, a cookie banner's button) goes before `browser_login`, while Escape, a link or a step outside the form ends the sign-in; a show-password toggle is dropped, and the button of a page that signs in from script stays a step after `browser_login`. In the page, a text area or an editable element named like a secret now reports only its length, as an input does, and names are read word by word as the server reads them.
9 changes: 7 additions & 2 deletions apps/docs/content/docs/browser/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,13 @@ A refusal costs the agent one look at the page; a wrong element costs a wrong ac

Text typed into a field becomes a parameter, with what was typed as its default. A sensitive one
keeps no value: a password field, a one-time code or card field, a field named like `password`,
`otp`, `pin` or `token`, a vault value typed by hand, or any parameter the agent lists in
`sensitive` when it stops. A vault sign-in is a `browser_login` step with the site name only.
`otp`, `pin`, `token` or `cardnumber`, a vault value typed by hand, or any parameter the agent
lists in `sensitive` when it stops. The vault's values are read before the first typed step is
kept and held in memory only; a vault user name counts as the whole typed value (case aside), a
vault password also inside other text when it has at least 4 characters. A vault user name typed
outside a sign-in only loses its default. A vault sign-in is a `browser_login` step with the site
name only. A `browser_navigate` step keeps its address without query string or fragment (they
can carry tokens).
Replay needs the sensitive values again; a value written `keychain:<item>` is read from the secret
store (`turno-browser secret set <item>`), so the agent never sees it. Into a password or
one-time code field an agent's `browser_replay` types only such a value; a plain one is refused
Expand Down
33 changes: 27 additions & 6 deletions apps/docs/content/docs/browser/teach-mode.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,33 @@ The rules for values are those of `browser_record`:

- What you type is a parameter, with what you typed as its default. The review can make it a
fixed value instead, or a parameter with no value kept.
- A password, a one-time code (also a field named only `code` in a sign-in form), a card number,
a field named like one, or a value of the
[vault](/docs/browser/vault) never keeps its value: the flow asks for it at each run, and the
review cannot make it fixed.
- A sign-in on a site of the vault is one `browser_login` step with the site's name: the fields you
typed into become that step, and your own submit is dropped when the vault submits.
- A password, a one-time code (also a field named only `code` in a sign-in form), a card number
or expiry (by its `autocomplete` or by a name such as `cardnumber` or `card_number`), a field
named like one, or a value of the [vault](/docs/browser/vault) never keeps its value: the flow
asks for it at each run, and the review cannot make it fixed. The vault's values are read when
teach mode starts and held in memory only, so one you type by hand is known from the first
step. A vault user name counts only as the whole of what you typed (case aside); a vault
password also counts inside other text when it has at least 4 characters.
- A vault value on the page (a signed-in user's name on a button, in any case) is kept in no
locator, fingerprint or element name of the flow.
- A sign-in on a site of the vault is one `browser_login` step with the site's name. It starts
when you type into a password or one-time code field on a page of that site. The user name you
typed into the same form on that page becomes part of it too, across a box checked, a key (Tab,
Escape) or a button that submits nothing (a show-password toggle), and so does typing into the
same fields afterwards. Typing before a submit (a click on a submit button, or Enter in that
form), another field of the form, and typing on an earlier page stay steps of their own, so a
sign-in that asks the user name first replays as you did it. A vault user name typed outside a
sign-in (an email at checkout) only loses its default.
- Your own submit (the click on the sign-in button, or Enter) ends the sign-in. It is dropped
when `browser_login` submits the form itself.
- The sign-in stays open until your submit, a new page, Escape outside its fields, a link, or a
step outside its form (without a form: any click, or typing outside its fields). When
`browser_login` submits, what you do in the form meanwhile (a box checked, a choice, Tab, a
cookie banner's button) goes before the `browser_login` step, which sends the form. A user name
field of the form you type into first after the password becomes part of the sign-in too. A
click on a button that submits nothing waits: a show-password toggle is dropped, and another one
goes before `browser_login` too. When the sign-in ends without your submit, the last such click
(the button of a page that signs in from script) goes after it, since it is how you signed in.
- Addresses keep no query string or fragment (they can carry tokens).

## Review and save
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/fingerprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export async function fingerprintOf(locator: Locator, url: string): Promise<Fing
}

/** A fingerprint with every text the redactor hides replaced by its mark. */
export function redactFingerprint(fp: Fingerprint, redactor: Redactor): Fingerprint {
export function redactFingerprint(fp: Fingerprint, redactor: Pick<Redactor, "text">): Fingerprint {
const r = (t: string) => redactor.text(t);
return {
role: fp.role,
Expand Down
13 changes: 10 additions & 3 deletions packages/browser/src/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,12 @@ class SessionBackend extends EventEmitter implements ServerBackend {
const key = session ?? DIRECT_SESSION;
let recorder = this.recorders.get(key);
if (!recorder) {
recorder = new FlowRecorder(identity, this.host.redactor, () => this.recordSettings?.flows === true);
recorder = new FlowRecorder(
identity,
this.host.redactor,
() => this.recordSettings?.flows === true,
this.host.vaultStore,
);
this.recorders.set(key, recorder);
}
return recorder;
Expand Down Expand Up @@ -1649,7 +1654,7 @@ class SessionBackend extends EventEmitter implements ServerBackend {
const result = await tool.handle(context, parsed.params);
if (stock) this.watch.follow(session ?? DIRECT_SESSION, stock.currentPage());
if (name === "browser_login") {
if (!result.isError) recorder?.record("browser_login", { site: parsed.params.site });
if (!result.isError) await recorder?.record("browser_login", { site: parsed.params.site });
await recording?.afterStep({ tool: name, ok: !result.isError, screenshot: false });
}
return unchosenNow ? this.withUserTabNote(result, unchosenNow(), json) : result;
Expand Down Expand Up @@ -1889,7 +1894,8 @@ class SessionBackend extends EventEmitter implements ServerBackend {
const pending = recorder?.active ? await recorder.capture(name, args, page).catch(() => undefined) : undefined;
const secretHook = this.secretHook(recording);
if (secretHook && page && (name === "browser_type" || name === "browser_fill_form")) {
const secrets = await secretValues(page, name, args);
const vault = await recorder?.vaultValues();
const secrets = await secretValues(page, name, args, vault && ((v) => vault.holds(v)));
if (secrets.length) {
for (const v of secrets) this.host.redactor.add(v, "sensitive value");
await secretHook(page);
Expand Down Expand Up @@ -2808,6 +2814,7 @@ function liveServerFor(
policy,
guard,
redactor,
...(options.vaultStore ? { vaultStore: options.vaultStore } : {}),
headless: options.config.browser.launchOptions?.headless === true,
// Before a launch, the engine identity.json and the flags would pick.
viewRefusal: (engine) => {
Expand Down
12 changes: 11 additions & 1 deletion packages/browser/src/live-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { replaceFileSync } from "turno-core/paths";
import type { SecretStore } from "turno-core/secrets";
import type { BrowserContext, CDPSession, Page } from "patchright-core";
import type { IdentityRef } from "./engine.js";
import {
Expand Down Expand Up @@ -118,6 +119,8 @@ export interface LiveServerOptions {
policy: LivePolicy;
guard: VaultGuard;
redactor: Redactor;
/** The secret store teach mode reads the vault's values from (tests inject a fake); default: this machine's. */
vaultStore?: SecretStore;
headless: boolean;
/** Why the engine shows no pixels; `engine` is the running one, undefined before a launch. */
viewRefusal(engine: string | undefined): string | undefined;
Expand Down Expand Up @@ -912,7 +915,14 @@ export class LiveServer implements BrowserWatch {
} finally {
this.teachStarting = false;
}
const session = new TeachSession(b.context, this.o.identity, this.o.redactor, name, () => this.pushTeach());
const session = new TeachSession(
b.context,
this.o.identity,
this.o.redactor,
name,
() => this.pushTeach(),
this.o.vaultStore,
);
// `overwrite` given at the start holds for the save, which the panel or Enter asks for later.
this.teaching = { session, phase: "teaching", held, overwrite };
try {
Expand Down
70 changes: 59 additions & 11 deletions packages/browser/src/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ import {
writeFlow,
} from "./flows.js";
import { existsSync } from "node:fs";
import type { SecretStore } from "turno-core/secrets";
import { ActionCache, actionCachePath, differences, fingerprintOf, redactFingerprint, refusal } from "./fingerprint.js";
import type { Redactor } from "./redact.js";
import { secretField } from "./sensitive.js";
import { VaultValues, vaultValues } from "./vault.js";
import type { TurnoTool } from "./tools.js";
import { type ToolSchema, upstream } from "./upstream.js";

Expand All @@ -35,9 +37,10 @@ import { type ToolSchema, upstream } from "./upstream.js";
*
* - Typed text is always a parameter. It keeps what was typed as its default only when the
* field is not sensitive: a password field, an `autocomplete` of a password, a one-time code
* or a card, a field named like one (`password`, `otp`, `pin`, `cvv`, `token`...), or a value
* that is one of this server's vault values. The agent can mark more parameters sensitive
* when it stops a named recording, which is held in memory until then.
* or a card, a field named like one (`password`, `otp`, `pin`, `cvv`, `token`, `cardnumber`...),
* or a value of the identity's vault. The vault's values are read from the secret store before
* the first typed step is kept, and held in memory only. The agent can mark more parameters
* sensitive when it stops a named recording, which is held in memory until then.
* - `browser_login` is recorded as its site name; the values are read from the vault again
* at replay.
* - Nothing else of a page (snapshots, results, values of other fields) is stored.
Expand Down Expand Up @@ -332,6 +335,8 @@ export class FlowRecorder {
private overwrite = false;
private auto: Draft | undefined;
private suspended = 0;
/** The vault's values, read once per named recording (and once for the identity's own). */
private vaultLoad: Promise<VaultValues> | undefined;

/** The fingerprints of what the identity's actions worked on (`fingerprint.ts`). */
readonly cache: ActionCache;
Expand All @@ -341,6 +346,8 @@ export class FlowRecorder {
private readonly redactor: Redactor,
/** identity.json `record.flows`: record every session as `auto-<time>`. */
private readonly autoFlows: () => boolean,
/** The secret store the vault's values are read from (tests pass one); default: this machine's. */
private readonly store?: SecretStore,
) {
this.cache = ActionCache.for(actionCachePath(identity.id, identity.env), redactor);
}
Expand All @@ -364,6 +371,22 @@ export class FlowRecorder {
throw new FlowError(`flow "${name}" exists; pass overwrite: true to replace it, or pick another name`);
this.named = new Draft(name, description);
this.overwrite = overwrite;
// Read again for this recording: a site added to the vault since counts.
this.vaultLoad = undefined;
}

/** The vault's values; none when the vault is empty or its store cannot be read. */
vaultValues(): Promise<VaultValues> {
this.vaultLoad ??= vaultValues(this.identity.id, {
env: this.identity.env,
...(this.store ? { store: this.store } : {}),
}).catch(() => VaultValues.none);
return this.vaultLoad;
}

/** True when a typed value must keep no default: a vault value, or one the redactor hides. */
private secretValue(value: string, vault: VaultValues): boolean {
return value !== "" && (vault.holds(value) || this.redactor.covers(value));
}

/** Saves the named flow, with `sensitive` parameters' values dropped. */
Expand All @@ -388,12 +411,15 @@ export class FlowRecorder {
throw new FlowError(`flow "${flow.name}" was saved by someone else meanwhile; stop with another name`);
const file = writeFlow(this.identity.id, flow, this.identity.env);
this.named = undefined;
// Not held past the recording: the next one (or the identity's own) reads them again.
this.vaultLoad = undefined;
return { flow, file };
}

cancel(): boolean {
const had = this.named !== undefined;
this.named = undefined;
this.vaultLoad = undefined;
return had;
}

Expand All @@ -413,6 +439,11 @@ export class FlowRecorder {
const { element: _element, startElement: _start, endElement: _end, ...rest } = args;
const step: FlowStep = { tool, args: structuredClone(rest) };
const slots: Slot[] = [];
// A browser_navigate step keeps its address without query or fragment (they can carry tokens).
if (tool === "browser_navigate" && typeof args.url === "string") {
const plain = plainUrl(args.url);
if (plain) step.args.url = plain;
}
const paths =
tool === "browser_fill_form" && Array.isArray(args.fields)
? (args.fields as unknown[]).map((_, i) => `fields.${i}.target`)
Expand All @@ -424,6 +455,13 @@ export class FlowRecorder {
};
const infos: Record<string, { info?: ElementInfo; label?: string }> = {};
let refused: string | undefined;
const types =
tool === "browser_type" ||
tool === "browser_fill_form" ||
(tool === "browser_handle_dialog" && typeof args.promptText === "string");
const vault = types || paths.length ? await this.vaultValues() : VaultValues.none;
/** A name or selector that shows a vault value: the server's, or one read for this recording. */
const shows = (text: string) => this.redactor.covers(text) || vault.shows(text);
for (const path of paths) {
const value = getPath(args, path);
if (typeof value !== "string" || !page) return undefined;
Expand All @@ -433,10 +471,12 @@ export class FlowRecorder {
const captured = await captureTarget(page, value, describedBy[path] ?? fieldName);
if (!captured) return undefined;
const fp = captured.target.fingerprint;
if (fp) captured.target.fingerprint = redactFingerprint(fp, this.redactor);
if (fp) captured.target.fingerprint = redactFingerprint(redactFingerprint(fp, this.redactor), vault);
// A locator that names the element by a vault value (a signed-in user's name on a button)
// is not kept: the flow and the action cache never hold one.
captured.target.locators = captured.target.locators.filter((l) => !this.redactor.covers(l.selector));
// is not kept: the flow and the action cache never hold one, nor a name that shows one.
captured.target.locators = captured.target.locators.filter((l) => !shows(l.selector));
if (captured.target.description && shows(captured.target.description)) delete captured.target.description;
if (captured.label && shows(captured.label)) delete captured.label;
// A selector the agent wrote (a repeated step from a batch or a shell): the element it
// finds now must be the one the cache saw an action work on under that selector.
const known = REF.test(value) ? undefined : this.cache.get(page.url(), value);
Expand All @@ -447,7 +487,8 @@ export class FlowRecorder {
}
step.targets ??= {};
step.targets[path] = captured.target;
infos[path] = { ...(captured.info ? { info: captured.info } : {}), label: fieldName ?? captured.label };
const named = fieldName && !shows(fieldName) ? fieldName : undefined;
infos[path] = { ...(captured.info ? { info: captured.info } : {}), label: named ?? captured.label };
}
// Drop the emptied target keys so the step's args are only what replay passes again.
for (const path of paths) {
Expand All @@ -458,7 +499,7 @@ export class FlowRecorder {
const typed = (path: string, value: unknown, at: string) => {
if (typeof value !== "string") return;
const meta = infos[at];
const sensitive = (meta?.info ? secretField(meta.info) : false) || this.redactor.covers(value);
const sensitive = (meta?.info ? secretField(meta.info) : false) || this.secretValue(value, vault);
slots.push({
path,
value,
Expand All @@ -472,7 +513,7 @@ export class FlowRecorder {
slots.push({
path: "promptText",
value: args.promptText,
sensitive: this.redactor.covers(args.promptText),
sensitive: this.secretValue(args.promptText, vault),
label: "prompt",
});
}
Expand Down Expand Up @@ -505,8 +546,15 @@ export class FlowRecorder {
}

/** A turno tool as a step: `browser_login` (site only) or `browser_replay` (its flow and parameters). */
record(tool: "browser_login" | "browser_replay", args: Record<string, unknown>, slots: Slot[] = []): void {
this.commit({ step: { tool, args: structuredClone(args) }, slots });
async record(
tool: "browser_login" | "browser_replay",
args: Record<string, unknown>,
slots: Slot[] = [],
): Promise<void> {
if (!this.active) return;
const vault = slots.length ? await this.vaultValues() : VaultValues.none;
const kept = slots.map((s) => (!s.sensitive && this.secretValue(s.value, vault) ? { ...s, sensitive: true } : s));
this.commit({ step: { tool, args: structuredClone(args) }, slots: kept });
}

private commitAuto(pending: PendingStep): void {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export function replayTool(): TurnoTool {
label: p.name,
};
});
ctx.recorder.record(
await ctx.recorder.record(
"browser_replay",
{ flow: flow.name, params: Object.fromEntries(flow.params.map((p) => [p.name, ""])) },
slots,
Expand Down
Loading
Loading