diff --git a/README.md b/README.md index f532732..2ca9355 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ The parts after the first come from a local copy that the first part saves for 1 A field that only comes back in JSON, such as `--jsonSchema` or `--screenshot`, needs JSON output. With `--format markdown` or `--format raw` it exits 2 and says so, where the field used to be dropped without a word. For `request`, `--body-file -` reads the body from stdin. `--body` sends its text as written, so `--body @order.json` warns when `order.json` is a file, since `--body-file order.json` was likely meant. +A page is untrusted. On a person's terminal, string strips what could take the terminal over: escape sequences, control characters other than tab and newline, and bidi controls, which can make text read differently from its bytes. Bytes that aren't text, such as a PDF from `--format raw`, are refused there with exit 2 and `use -o FILE`. Piped, or under a coding agent, output goes out byte for byte. + A bare domain works too: `string example.com` fetches `https://example.com`. When `fetch`, `request` or `sitemap submit` gets a URL with no scheme, it uses `https://` and says so on stderr. **Every API field is a flag of the same name.** A field from the [API reference](https://docs.usestring.ai/api-reference/fetch) works on the command line as written: `executeJS` is `--executeJS`, and `countryCode` is `--countryCode DE`. A boolean flag alone is true, and `=false` turns it off (`--solveCaptcha=false`). An object or array field takes JSON, or `@` and a file path (`--jsonSchema @./schema.json`). `string fetch --help`, `string search --help` and `string sitemap --help` list each command's fields. Every flag of more than one word also takes its kebab-case and snake_case spellings, so `--main-content-only` and `--main_content_only` are `--mainContentOnly`, and `--envFile` is `--env-file`. A near miss of a flag, such as `--mainContentOnyl`, gets the right name back, and so does a near miss of a command, or a word other tools use for one: `string scrape URL` answers `Did you mean fetch?` with `string fetch URL` as the next step, and exits 2 without running it. diff --git a/cmd/string/help.go b/cmd/string/help.go index 8a68de8..d3acc77 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -546,6 +546,10 @@ stdout holds the result and nothing else: integrations run status, login, trial, text for a person; --json gives one JSON object whoami, version +A page is untrusted, so on a person's terminal it loses ESC, control +characters but tab and newline, and bidi controls, and bytes that aren't +text, such as a PDF from --format raw, are refused with exit 2. Piped, or +under an agent, it goes out byte for byte. stderr holds the rest: what a wait is doing, notes, what is left of the keyless allowance, and errors. A fetched page over 16 KB says its size there first, where no person reads stdout at a terminal, so an agent sees it before diff --git a/cmd/string/run.go b/cmd/string/run.go index fa375f1..eaf87ef 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "cmp" "crypto/ed25519" "encoding/json" "errors" @@ -156,6 +157,9 @@ captureIframes, captureCookies or actions. request, search and sitemap print JSO says on stderr what it saved: the size, the tokens, a fetch's status and host, and a Markdown page's outline, each heading after its line number. A path that can't take a file fails before the request. -o - is stdout. +A page is untrusted. On a person's terminal it loses escape sequences, control +characters and bidi controls, and bytes that aren't text are refused (exit 2: +use -o FILE). Piped, or under an agent, it goes out as it came. A fetched page over 16 KB says its size on stderr first where no person reads stdout at a terminal, with what the agent keeps of it. -q, or --quiet, leaves such status lines out of stderr; errors and the keyless allowance stay. @@ -290,6 +294,9 @@ type operation struct { maxTokens, offset int // fromCopy says the page came from its local copy, not a request. fromCopy bool + // contentType is the answer's Content-Type, the site's own for --format + // raw. + contentType string } // args is a parsed command line. Every command takes --help and --input; @@ -1347,7 +1354,7 @@ func (c apiClient) call(op *operation) ([]byte, error) { if err != nil { return nil, err } - op.siteStatus = response.Header.Get("X-Status-Code") + op.siteStatus, op.contentType = response.Header.Get("X-Status-Code"), response.Header.Get("Content-Type") if op.command == "fetch" && announcing(c.rt.env) && !c.rt.quiet { if warning := siteStatusWarning(op.siteStatus, jsString(op.body["url"])); warning != "" { fmt.Fprint(c.rt.stderr, warning) @@ -1361,6 +1368,17 @@ func (c apiClient) call(op *operation) ([]byte, error) { // emit writes a response to stdout, or to the --output file. func (c apiClient) emit(op *operation, data []byte) error { + // Pages are untrusted. On a person's terminal, bytes that aren't text are + // refused, and text loses what could take the terminal over; anywhere + // else, output goes out as it came. + person := c.rt.exec.stdoutTTY && c.rt.exec.agent == "" && (op.output == "" || op.output == "-") + if person && op.binary && !textual(op.contentType, data) { + media := cmp.Or(strings.TrimSpace(strings.Split(op.contentType, ";")[0]), "no content type") + return &failure{exit: exitUsage, code: "invalid_usage", reason: "binary_on_tty", message: fmt.Sprintf("binary content (%s, %s): use -o FILE", media, sizeText(len(data))), nextStep: "run `" + commandLine(append(slices.Clone(op.line), "-o", "page.bin")) + "`"} + } + if person { + op.binary = false + } if !op.binary { text := decodeText(data) if !strings.HasSuffix(text, "\n") { @@ -1372,6 +1390,9 @@ func (c apiClient) emit(op *operation, data []byte) error { if op.maxTokens > 0 { whole := decodeText(data) part, start, end, next := page(whole, op.maxTokens, op.offset) + if person { + part = forTerminal(part) + } if !strings.HasSuffix(part, "\n") { part += "\n" } @@ -1381,6 +1402,9 @@ func (c apiClient) emit(op *operation, data []byte) error { fmt.Fprint(c.rt.stderr, pageFooter(op.line, len(whole), op.maxTokens, start, end, next, op.fromCopy)) return nil } + if person { + data = []byte(forTerminal(string(data))) + } if op.output == "" || op.output == "-" { // Where no person reads stdout at a terminal, a large page's size // comes first, before an agent's runner cuts the output. diff --git a/cmd/string/untrusted.go b/cmd/string/untrusted.go new file mode 100644 index 0000000..5d69f77 --- /dev/null +++ b/cmd/string/untrusted.go @@ -0,0 +1,42 @@ +package main + +import ( + "mime" + "strings" +) + +// forTerminal is untrusted text as it may reach a person's terminal: no ESC, +// so no escape sequence; no other control character but tab and newline; and +// no bidi override or isolate, which can make text read differently from its +// bytes. +func forTerminal(text string) string { + return strings.Map(func(r rune) rune { + switch { + case r == '\t' || r == '\n': + return r + case r < 0x20, r == 0x7f, r >= 0x80 && r <= 0x9f: + return -1 + case r >= 0x202a && r <= 0x202e, r >= 0x2066 && r <= 0x2069: + return -1 + } + return r + }, text) +} + +// textual reports whether a response of contentType is text a terminal can +// show, rather than bytes such as a PDF or an image. +func textual(contentType string, data []byte) bool { + media, _, err := mime.ParseMediaType(contentType) + if err != nil || media == "" { + return !strings.ContainsRune(string(data[:min(len(data), 8000)]), 0) + } + switch { + case strings.HasPrefix(media, "text/"), strings.HasSuffix(media, "+json"), strings.HasSuffix(media, "+xml"): + return true + } + switch media { + case "application/json", "application/xml", "application/javascript", "application/x-javascript", "application/ecmascript": + return true + } + return false +} diff --git a/cmd/string/untrusted_test.go b/cmd/string/untrusted_test.go new file mode 100644 index 0000000..98dc3e2 --- /dev/null +++ b/cmd/string/untrusted_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "io" + "net/http" + "testing" +) + +// On a person's terminal, a page loses what could take the terminal over: +// ESC, control characters but tab and newline, and bidi overrides and +// isolates. Piped, or to an agent, it goes out byte for byte. +func TestAPageCantTakeOverAPersonsTerminal(t *testing.T) { + const page = "# Title\x1b[31m red\x1b[0m ‮evil‬ ⁦iso⁩\r\nline\x07bell\u0085next\ttab\n" + contentType := "text/markdown" + base := api(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + io.WriteString(w, page) + }) + person := execCtx{stdinTTY: true, stdoutTTY: true, stderrTTY: true} + if got := runAs(base, person, "fetch", "https://example.com"); got.status != 0 || got.output != "# Title[31m red[0m evil iso\nlinebellnext\ttab\n" { + t.Errorf("a person: %q", got.output) + } + for about, exec := range map[string]execCtx{"a pipe": {stdinTTY: true, stderrTTY: true}, "an agent at a terminal": {stdinTTY: true, stdoutTTY: true, stderrTTY: true, agent: "codex"}} { + if got := runAs(base, exec, "fetch", "https://example.com"); got.status != 0 || got.output != page { + t.Errorf("%s: %q, want the page as it came", about, got.output) + } + } + // So does JSON, which stays JSON. + if got := runAs(base, person, "search", "coffee"); got.output != forTerminal(page) { + t.Errorf("search for a person: %q", got.output) + } + // A part of a page is cleaned the same way. + if got := runAs(base, person, "fetch", "https://example.com", "--max-tokens", "1000"); got.status != 0 || got.output != "# Title[31m red[0m evil iso\nlinebellnext\ttab\n" { + t.Errorf("a part for a person: %q", got.output) + } + + // Bytes that aren't text are refused on a person's terminal, with the fix. + contentType = "application/pdf" + if got := runAs(base, person, "fetch", "https://example.com/a.pdf", "--format", "raw"); got.status != exitUsage || got.output != "" || got.errors != "error: binary content (application/pdf, 63 B): use -o FILE\n\nnext: run `string fetch https://example.com/a.pdf --format raw -o page.bin`\n" { + t.Errorf("a PDF for a person: %+v", got) + } + if got := runAs(base, execCtx{stdinTTY: true, stderrTTY: true}, "fetch", "https://example.com/a.pdf", "--format", "raw"); got.status != 0 || got.output != page { + t.Errorf("a PDF piped: %+v", got) + } + // Raw text is shown, cleaned. + contentType = "text/html; charset=utf-8" + if got := runAs(base, person, "fetch", "https://example.com", "--format", "raw"); got.status != 0 || got.output != forTerminal(page) { + t.Errorf("raw HTML for a person: %+v", got) + } + if forTerminal("a⁧b⁨c‪d‫e") != "abcde" || forTerminal("\x00\x1f\x7f\u009f") != "" { + t.Errorf("forTerminal leaves bidi or control characters") + } +}