Files
ARTEX/chatbridge/outbound.go
BaaRai a70c0d74f9 Drop nested code fences whole in chat bridge excerpts
SafeText paired any run of three backticks or tildes with the next run of
either kind, so a longer fence quoting markdown was closed at its first inner
run and the rest of the quoted evidence reached the chat provider as prose.

Fences now follow the CommonMark rules: a fence line has at most three spaces
before its run, and its block ends only on a line holding a run of the same
character at least as long and nothing else; an unclosed fence drops to the
end. Other runs (after text, inside a blockquote or list item, in text
collapsed to one line) are dropped up to the latest end a code span or a
container fence could have, and a fence line met first starts its own block.
Ambiguous markdown errs toward dropping.
2026-12-04 01:51:11 +01:00

233 lines
8.5 KiB
Go

package chatbridge
import (
"regexp"
"strings"
"unicode/utf8"
)
// A chat app is an external data surface: messages leave the deployment,
// sit on the chat provider's servers and on every member's phone. What the
// bridge sends is therefore fixed wording, titles, statuses, counts and links
// by default (issue #5). Free-form text, such as a main-agent answer, goes
// out only when the operator turns on excerpts for the bridge, and then only
// through SafeText. SafeText is deliberately blunt:
//
// - Code is dropped: fenced blocks (``` and ~~~, nested fences included)
// and indented blocks. Agents put requests, responses, tool output and
// payloads there, which is exactly the evidence that stays in ARTEX.
// - Known secrets passed by the caller (the task's stored credentials) are
// replaced wherever they appear.
// - Common credential shapes are masked: private key blocks, credentials in
// URLs, Authorization and Cookie headers, bearer tokens, JWTs, well-known
// API key formats, curl -u, session cookies and key=value pairs whose key
// names a password, secret, token or key, quoted values included.
//
// Pattern masking cannot know every shape a credential takes. That is why
// excerpts are an opt-in and the full text stays in ARTEX.
// Redacted replaces a masked value.
const Redacted = "[redacted]"
// CodeOmitted replaces a dropped code block.
const CodeOmitted = "[code block omitted, open ARTEX to see it]"
const secretKey = `[a-z0-9_.-]*(?:password|passwd|passphrase|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|client[_-]?secret|credential|sessid|session[_-]?id|auth)[a-z0-9_.-]*`
var (
indentedCodeRe = regexp.MustCompile(`(?m)(?:^(?: {4}|\t)[^\n]*(?:\n|$))+`)
privateKeyRe = regexp.MustCompile(`(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(-----END [A-Z0-9 ]*PRIVATE KEY-----|$)`)
urlUserinfoRe = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://)[^\s/?#@]+@`)
authHeaderRe = regexp.MustCompile(`(?im)\b((?:proxy-)?authorization|cookie|set-cookie|x-api-key|x-auth-token)(\s*:\s*)[^\r\n]+`)
bearerRe = regexp.MustCompile(`(?i)\b(bearer|basic)(\s+)[A-Za-z0-9._~+/=-]{8,}`)
curlUserRe = regexp.MustCompile(`(?i)((?:^|\s)(?:-u|--user|--proxy-user)(?:\s+|=))(?:"[^"\n]*"|'[^'\n]*'|\S+)`)
jwtRe = regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}`)
apiKeyRe = regexp.MustCompile(`\b(?:(?:AKIA|ASIA)[0-9A-Z]{16}|(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|xox[abposr]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})`)
sessionIDRe = regexp.MustCompile(`(?i)\b((?:[a-z0-9_-]+\.)?sid|[a-z0-9_]*sess[a-z0-9_]*)(\s*=\s*)[^\s"',;&]+`)
secretKVRe = regexp.MustCompile(`(?i)\b(` + secretKey + `)(["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|[^\s"',;&]+)`)
)
// containerPrefix holds the characters that may stand before a fence inside a
// blockquote or a list item.
const containerPrefix = " \t>-*+.)0123456789"
// dropFencedCode replaces fenced code with CodeOmitted. It follows the
// CommonMark fence rules and, where markdown is ambiguous, drops more:
//
// - A fence line has at most three spaces, then a run of three or more
// backticks or tildes (a backtick run's info string holds no backtick).
// Its block ends only on a line holding, after at most three spaces, a run
// of the same character at least as long and nothing else but spaces or
// tabs. Runs of the other character, shorter runs and runs followed by
// text are content, so a longer fence quoting markdown keeps its inner
// fences inside.
// - Any other run of three or more (after text, inside a blockquote or a
// list item, in text collapsed to one line) may open a code span, which
// ends at the next run of exactly its length, or, when only container
// marks stand before it, a fence inside the container. The later of the
// possible ends is used, and a fence line met first ends it, since that
// line opens a block of its own.
// - What is never closed is dropped to the end of the text.
func dropFencedCode(s string) string {
var b strings.Builder
i := 0
for i < len(s) {
p, n := nextFenceRun(s, i)
if p < 0 {
b.WriteString(s[i:])
break
}
b.WriteString(s[i:p])
b.WriteString(CodeOmitted)
i = fencedCodeEnd(s, p, n)
}
return b.String()
}
// nextFenceRun returns the start and length of the first run of three or more
// backticks or tildes at or after i, or -1.
func nextFenceRun(s string, i int) (int, int) {
for i < len(s) {
j := strings.IndexAny(s[i:], "`~")
if j < 0 {
return -1, 0
}
p := i + j
n := runLen(s, p)
if n >= 3 {
return p, n
}
i = p + n
}
return -1, 0
}
// fencedCodeEnd returns where the code opened by the run of n characters at p
// ends (see dropFencedCode).
func fencedCodeEnd(s string, p, n int) int {
c := s[p]
ls := strings.LastIndexByte(s[:p], '\n') + 1
if fp, ok := fenceLine(s, ls); ok && fp == p {
for l := lineEnd(s, p); l < len(s); l = lineEnd(s, l+1) {
if e, ok := closingLine(s, l+1, c, n, " ", 3); ok {
return e
}
}
return len(s)
}
container := strings.Trim(s[ls:p], containerPrefix) == "" &&
(c != '`' || strings.IndexByte(s[p+n:lineEnd(s, p)], '`') < 0)
span := -1
for k := p + n; k < len(s); {
if s[k] == '\n' {
if !container {
// Inside a paragraph, a fence line starts a block of its own. In
// a list item or a blockquote it is content of the fence that is
// already open: a list item's continuation lines are indented two
// or three spaces, so they would otherwise end a longer fence at
// its first inner block. Only a closing line of the same
// character and at least the same length ends it.
if _, ok := fenceLine(s, k+1); ok {
return k
}
} else if e, ok := closingLine(s, k+1, c, n, containerPrefix, len(s)); ok {
return e
}
k++
} else if s[k] == c {
m := runLen(s, k)
if m == n && span < 0 {
span = k + m
}
k += m
} else {
k++
}
if span >= 0 && !container {
return span
}
}
return len(s)
}
// fenceLine reports whether the line starting at ls is a fence line, and where
// its run starts.
func fenceLine(s string, ls int) (int, bool) {
p := ls
for p < len(s) && p-ls < 3 && s[p] == ' ' {
p++
}
if p >= len(s) || (s[p] != '`' && s[p] != '~') {
return 0, false
}
n := runLen(s, p)
if n < 3 || (s[p] == '`' && strings.IndexByte(s[p+n:lineEnd(s, p)], '`') >= 0) {
return 0, false
}
return p, true
}
// closingLine reports whether the line starting at ls closes a fence of n c's:
// after at most maxPrefix characters from prefix, a run of c at least n long
// and only spaces or tabs. It returns the end of that line.
func closingLine(s string, ls int, c byte, n int, prefix string, maxPrefix int) (int, bool) {
p := ls
for p < len(s) && p-ls < maxPrefix && strings.IndexByte(prefix, s[p]) >= 0 {
p++
}
if p >= len(s) || s[p] != c {
return 0, false
}
m := runLen(s, p)
e := lineEnd(s, p)
if m < n || strings.Trim(s[p+m:e], " \t") != "" {
return 0, false
}
return e, true
}
func runLen(s string, p int) int {
n := 1
for p+n < len(s) && s[p+n] == s[p] {
n++
}
return n
}
func lineEnd(s string, p int) int {
if e := strings.IndexByte(s[p:], '\n'); e >= 0 {
return p + e
}
return len(s)
}
// SafeText prepares untrusted text for a chat message: it drops code, masks
// secrets and cuts the result to maxRunes runes (0 = no cut), marking a cut
// with an ellipsis.
func SafeText(text string, secrets []string, maxRunes int) string {
out := strings.ReplaceAll(text, "\r\n", "\n")
out = dropFencedCode(out)
out = indentedCodeRe.ReplaceAllString(out, CodeOmitted+"\n")
out = privateKeyRe.ReplaceAllString(out, Redacted)
for _, s := range secrets {
// Very short values (a PIN, "admin") would mask ordinary words.
if s = strings.TrimSpace(s); utf8.RuneCountInString(s) >= 4 {
out = strings.ReplaceAll(out, s, Redacted)
}
}
out = urlUserinfoRe.ReplaceAllString(out, "${1}"+Redacted+"@")
out = authHeaderRe.ReplaceAllString(out, "${1}${2}"+Redacted)
out = bearerRe.ReplaceAllString(out, "${1}${2}"+Redacted)
out = curlUserRe.ReplaceAllString(out, "${1}"+Redacted)
out = jwtRe.ReplaceAllString(out, Redacted)
out = apiKeyRe.ReplaceAllString(out, Redacted)
out = sessionIDRe.ReplaceAllString(out, "${1}${2}"+Redacted)
out = secretKVRe.ReplaceAllString(out, "${1}${2}"+Redacted)
out = strings.TrimSpace(out)
if maxRunes > 0 && utf8.RuneCountInString(out) > maxRunes {
r := []rune(out)
out = strings.TrimSpace(string(r[:maxRunes-1])) + "…"
}
return out
}