Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/OPERATING.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,14 @@ cuttle pw detach # optional; the browser stays up
`$XDG_STATE_HOME/cuttle/<instance>/snapshots/` (default `~/.local/state`; dir
0700, files 0600, the newest 50 kept) and rewrites the link to that path. The
daemon replaces every value its secret store holds for the session with its
`{{cuttle:NAME}}` sentinel first - exact matches only (plain or as the
snapshot quotes them), values under 4
characters (6 if all digits) left alone. The verb's own stdout, and `cuttle pw
snapshot`, are not masked. If the fetch fails the link is left pointing into
the container.
`{{cuttle:NAME}}` sentinel first, and the current value of every
`<input type=password>` on the session's open pages (same-origin iframes
included, read over CDP at fetch time) with `{{cuttle:password-field}}` -
exact matches only (plain or as the snapshot quotes them), values under 4
characters (6 if all digits) left alone. A page the daemon cannot read in
time is served masked by held values alone. The verb's own stdout, and
`cuttle pw snapshot`, are not masked. If the fetch fails the link is left
pointing into the container.
- **Driver help is per verb.** A leading `cuttle pw --help` (or `-h`) prints
cuttle's wrapper help; `cuttle pw <verb> --help` passes through and prints the
driver's own help for that verb. playwright-cli 0.1.20 has no `help` or `docs`
Expand Down
3 changes: 2 additions & 1 deletion packages/cuttle/internal/cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ cuttle downloads page.png # pull it to this host
pdf, state-save; no directory) lands in the downloads dir; `cuttle downloads
<name>` pulls it.
- **An action's `[Snapshot](...)` link is a host file.** Read it directly
instead of running `snapshot` again; held secrets show as `{{cuttle:NAME}}`.
instead of running `snapshot` again; held secrets show as `{{cuttle:NAME}}`,
and whatever a masked login input holds as `{{cuttle:password-field}}`.
- **Another instance?** `--name`/`--context` go BEFORE `pw`: `cuttle --name
scraper pw snapshot` (or set `CUTTLE_NAME`). After `pw`, every arg is the driver's.
- **One driver at a time.** While a `cuttle jev-browse` run holds the session
Expand Down
81 changes: 78 additions & 3 deletions packages/cuttle/internal/serve/downloads.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package serve

import (
"context"
"io"
"net/http"
"os"
Expand Down Expand Up @@ -108,9 +109,79 @@ func (m *multiplexer) handleDownloadsGet(w http.ResponseWriter, r *http.Request)
// "..", it can never name anything outside the driver's own snapshot dir.
var snapshotFilePattern = regexp.MustCompile(`^\.playwright-cli/page-[0-9TZ-]+\.yml$`)

// passwordPlaceholder stands in for a password field's value. Its name can never
// be a secret's (a hyphen fails secretNamePattern), so it cannot be mistaken for
// a sentinel an agent could type.
const passwordPlaceholder = sentinelPrefix + "password-field" + sentinelSuffix

// passwordReadTimeout bounds the page read behind one /snapshot. `cuttle pw`
// fetches the route with a 2s ceiling, so a slow browser must cost the field
// mask, not the whole snapshot.
const passwordReadTimeout = 1200 * time.Millisecond

// passwordFieldsJS returns the current value of every filled password field in
// the document and its same-origin iframes - the values only, never which field.
// A cross-origin iframe is a separate target and is not walked. The page cannot
// touch this function (it runs in an isolated world), but it does decide how
// many fields there are and how long their values are, so both are capped here,
// before Chrome serializes the answer: the daemon reads the reply with no frame
// size limit, and it must not be a page's choice how big that reply is.
const passwordFieldsJS = `function(){var out=[];var walk=function(d){` +
`d.querySelectorAll('input[type=password]').forEach(function(i){` +
`if(i.value&&i.value.length<=4096&&out.length<32)out.push(i.value);});` +
`d.querySelectorAll('iframe').forEach(function(f){try{if(f.contentDocument)walk(f.contentDocument);}catch(e){}});};` +
`try{walk(document);}catch(e){}return out;}`

// passwordFieldValues reads the password fields of every open page in the
// seed's browser, since the daemon cannot tell which one the driver snapshotted.
// Best effort by design: a browser that cannot be reached yields nothing, and the
// snapshot is served masked by held values alone - a value the agent typed as a
// literal was already on its side of the boundary.
func passwordFieldValues(ctx context.Context, port int) []string {
ctx, cancel := context.WithTimeout(ctx, passwordReadTimeout)
defer cancel()
var pages []struct {
ID string `json:"id"`
Type string `json:"type"`
}
if err := fetchCDP(ctx, port, "/json/list", &pages); err != nil {
return nil
}
conn, err := dialBrowser(ctx, port)
if err != nil {
return nil
}
defer conn.close() // closing the socket detaches every session it opened
var values []string
for _, p := range pages {
if p.Type != targetPage || p.ID == "" {
continue
}
sid, err := conn.attach(ctx, p.ID)
if err != nil {
continue
}
res, err := conn.callInWorld(ctx, sid, passwordFieldsJS, "", true)
if err != nil {
continue
}
result, _ := res[cdpResult].(map[string]any)
found, _ := result[cdpValue].([]any)
for _, v := range found {
if s, ok := v.(string); ok {
values = append(values, s)
}
}
}
return values
}

// handleSnapshot returns one driver snapshot with every value the seed's secret
// store holds replaced by its sentinel, so the copy `cuttle pw` leaves on the
// host never carries a secret the agent filled.
// store holds replaced by its sentinel, and every password field's current
// value by passwordPlaceholder, so the copy `cuttle pw` leaves on the host
// never carries a credential - whether the agent filled it by sentinel or typed
// it as a literal (the driver renders a password field as a plain textbox with
// its value).
func (m *multiplexer) handleSnapshot(w http.ResponseWriter, r *http.Request) {
if m.rejectUntrustedLoopback(w, r) {
return
Expand All @@ -137,7 +208,11 @@ func (m *multiplexer) handleSnapshot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, map[string]any{keyError: "no such snapshot"})
return
}
pairs := m.pool.secrets.heldPairs(seed)
for _, v := range passwordFieldValues(r.Context(), inst.cdpPort) {
pairs = append(pairs, exactPairs(v, passwordPlaceholder)...)
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
_, _ = io.WriteString(w, m.pool.secrets.maskHeld(seed, string(body))) //nolint:gosec // text/plain + nosniff: never rendered
_, _ = io.WriteString(w, maskExact(string(body), pairs)) //nolint:gosec // text/plain + nosniff: never rendered
}
103 changes: 102 additions & 1 deletion packages/cuttle/internal/serve/downloads_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
)
Expand All @@ -16,7 +17,13 @@ import (
// with files. Returns the multiplexer and the instance's download dir.
func downloadsPool(t *testing.T, files map[string]string) (*multiplexer, string) {
t.Helper()
fl := &fakeLauncher{port: 5100}
return downloadsPoolOn(t, 5100, files)
}

// downloadsPoolOn is downloadsPool with the seed's browser on a given port.
func downloadsPoolOn(t *testing.T, port int, files map[string]string) (*multiplexer, string) {
t.Helper()
fl := &fakeLauncher{port: port}
pool := newTestPool(t, serveConfig{}, fl.toLauncher())
inst, err := pool.getOrLaunch(context.Background(), connectRequest{seed: "s1"})
if err != nil {
Expand Down Expand Up @@ -275,3 +282,97 @@ func TestSnapshotServesMaskedDriverFile(t *testing.T) {
t.Errorf("missing snapshot: status=%d want 404", rec.Code)
}
}

// fakePageBrowser is a browser with one page, answering the CDP calls the
// password read makes. fields is what the page's password inputs hold; a nil
// fields makes the evaluate fail the way a page mid-navigation does.
func fakePageBrowser(t *testing.T, fields []any) int {
t.Helper()
_, wsURL := startCDPBrowser(t, func(cmd map[string]any) map[string]any {
switch cmd[cdpMethod] {
case "Target.attachToTarget":
return map[string]any{"sessionId": "S1"}
case "Page.getFrameTree":
return map[string]any{"frameTree": map[string]any{"frame": map[string]any{"id": "F1"}}}
case "Page.createIsolatedWorld":
return map[string]any{"executionContextId": 7}
case "Runtime.callFunctionOn":
if fields == nil {
return map[string]any{"exceptionDetails": map[string]any{"text": "Cannot find context with specified id"}}
}
return map[string]any{cdpResult: map[string]any{cdpValue: fields}}
}
return map[string]any{}
}, nil)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/json/version":
_, _ = w.Write([]byte(`{"webSocketDebuggerUrl":"` + wsURL + `"}`))
case "/json/list":
_, _ = w.Write([]byte(`[{"id":"1","type":"page","url":"http://x.example/login"}]`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return serverPort(t, srv)
}

// What the page's password fields hold at snapshot time is masked too: the
// driver renders a password input as a plain textbox with its value, so a
// literal the agent typed would otherwise reach the host copy in the clear.
func TestSnapshotMasksPasswordFieldValues(t *testing.T) {
t.Parallel()
const file = ".playwright-cli/page-2026-09-19T10-27-05-037Z.yml"
snap := `- textbox "User": fake-secret-value` + "\n" +
`- textbox "Pass": fake-pw-value-123` + "\n" +
`- textbox "Pin": 1234` + "\n" +
`- textbox "Quoted": "fa\"ke\\{v"`
want := `- textbox "User": {{cuttle:T}}` + "\n" +
`- textbox "Pass": ` + passwordPlaceholder + "\n" +
`- textbox "Pin": 1234` + "\n" +
`- textbox "Quoted": "` + passwordPlaceholder + `"`
heldOnly := strings.Replace(snap, "fake-secret-value", "{{cuttle:T}}", 1)
// A field holding a value the store also holds, among enough other fields
// that the longest-first sort is no longer a plain insertion sort: the held
// sentinel must still win over the generic placeholder.
heldInField := make([]any, 0, 21)
heldInField = append(heldInField, "fake-secret-value")
for i := range 20 {
heldInField = append(heldInField, "fake-filler-"+strconv.Itoa(i))
}
for name, tc := range map[string]struct {
fields []any
want string
}{
"fields masked": {[]any{"fake-pw-value-123", "1234", `fa"ke\{v`}, want},
"held value in a field": {heldInField, heldOnly},
"evaluate fails": {nil, heldOnly},
"no browser at all": {nil, heldOnly},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
port := 1 // nothing listens here
if name != "no browser at all" {
port = fakePageBrowser(t, tc.fields)
}
m, dir := downloadsPoolOn(t, port, nil)
if err := os.MkdirAll(filepath.Join(dir, ".playwright-cli"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, file), []byte(snap), 0o600); err != nil {
t.Fatal(err)
}
m.pool.secrets.put("s1", "T", []byte("fake-secret-value"), sourceStdin, secretTTLDefault)
rec := httptest.NewRecorder()
m.handleSnapshot(rec, downloadsReq("/snapshot?fingerprint=s1&file="+url.QueryEscape(file)))
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
if rec.Body.String() != tc.want {
t.Errorf("body=%q\nwant %q", rec.Body.String(), tc.want)
}
})
}
}
47 changes: 31 additions & 16 deletions packages/cuttle/internal/serve/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,30 +291,45 @@ func (s *secretStore) remove(seed, name string) bool {
// (one holding `{`, "`", ": " and the like): backslash and double quote escaped.
var yamlQuoted = strings.NewReplacer(`\`, `\\`, `"`, `\"`)

// maskHeld replaces every live value held for seed with its own sentinel - the
// text an agent would type to use it. Only the exact value is matched, longest
// first so a short value never splits a longer one, and a value under the
// masking floors is left alone rather than shredding unrelated text. The
// quoted form is masked too, or a value with a quote or backslash in it would
// survive whenever the snapshot quotes it.
func (s *secretStore) maskHeld(seed, text string) string {
// heldPairs is every live value held for seed, paired with its sentinel - the
// text an agent would type to use it.
func (s *secretStore) heldPairs(seed string) [][]string {
s.mu.Lock()
defer s.mu.Unlock()
pairs := [][]string{}
for name, e := range s.m[seed] {
val, sentinel := string(e.val), sentinelPrefix+name+sentinelSuffix
if !e.live() || !maskable(val) {
continue
}
pairs = append(pairs, []string{val, sentinel})
if quoted := yamlQuoted.Replace(val); quoted != val {
pairs = append(pairs, []string{quoted, sentinel})
if e.live() {
pairs = append(pairs, exactPairs(string(e.val), sentinelPrefix+name+sentinelSuffix)...)
}
}
s.mu.Unlock()
return pairs
}

// exactPairs maps one value to its placeholder, and its quoted form too, or a
// value with a quote or backslash in it would survive whenever the snapshot
// quotes it. A value under the masking floors yields nothing rather than
// shredding unrelated text.
func exactPairs(val, placeholder string) [][]string {
if !maskable(val) {
return nil
}
pairs := [][]string{{val, placeholder}}
if quoted := yamlQuoted.Replace(val); quoted != val {
pairs = append(pairs, []string{quoted, placeholder})
}
return pairs
}

// maskExact replaces each pair's value with its placeholder. Only the exact
// value is matched, longest first so a short value never splits a longer one.
// Among equal lengths the earlier pair wins (the sort is stable and the
// replacer takes the first match in argument order), so a held value that also
// sits in a password field keeps its own sentinel.
func maskExact(text string, pairs [][]string) string {
if len(pairs) == 0 {
return text
}
slices.SortFunc(pairs, func(a, b []string) int { return len(b[0]) - len(a[0]) })
slices.SortStableFunc(pairs, func(a, b []string) int { return len(b[0]) - len(a[0]) })
return strings.NewReplacer(slices.Concat(pairs...)...).Replace(text)
}

Expand Down
9 changes: 5 additions & 4 deletions packages/cuttle/internal/serve/secrets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1135,16 +1135,17 @@ func TestMaskHeld(t *testing.T) {
store.put(testSeed, "TINY", []byte("abc"), sourceStdin, secretTTLDefault)
store.put("other", "OTHER", []byte("elsewhere"), sourceStdin, secretTTLDefault)

got := store.maskHeld(testSeed, "hunter22 hunt 1234 abc elsewhere")
mask := func(text string) string { return maskExact(text, store.heldPairs(testSeed)) }
got := mask("hunter22 hunt 1234 abc elsewhere")
if want := "{{cuttle:LONG}} {{cuttle:SHORT}} 1234 abc elsewhere"; got != want {
t.Fatalf("maskHeld = %q, want %q", got, want)
t.Fatalf("masked = %q, want %q", got, want)
}
store.put(testSeed, "QUOTED", []byte(`fa"ke\{v`), sourceStdin, secretTTLDefault)
if got := store.maskHeld(testSeed, `- textbox: "fa\"ke\\{v"`); got != `- textbox: "{{cuttle:QUOTED}}"` {
if got := mask(`- textbox: "fa\"ke\\{v"`); got != `- textbox: "{{cuttle:QUOTED}}"` {
t.Fatalf("quoted = %q: the snapshot's escaped form of a value must mask too", got)
}
store.expireNow("LONG")
if got := store.maskHeld(testSeed, "hunter22"); got != "{{cuttle:SHORT}}er22" {
if got := mask("hunter22"); got != "{{cuttle:SHORT}}er22" {
t.Fatalf("after expiry = %q: an expired value is no longer held, so only the live one masks", got)
}
}
Loading