Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
masking: a record keeps its request as sent, how long masking took and what the answer put back
yetone9b57261b62bf
diff --git a/internal/gateway/masked.go b/internal/gateway/masked.goindex ca4b7199f..895f303b9 100644--- a/internal/gateway/masked.go+++ b/internal/gateway/masked.go@@ -5,6 +5,7 @@ import ("slices""strconv""strings"+ "time""unicode/utf8""github.com/yetone/magpie/internal/gwmw"@@ -28,11 +29,16 @@ type Masked struct {type maskHits struct {n inthits []gwmw.Hit+ took time.Duration // how long masking took+ // key is where noteMasked puts the record's key, for the answer's+ // writer to tell it what it put back once it is done (redactedHits)+ key *int64}func (h *maskHits) add(o maskHits) {h.n += o.nh.hits = append(h.hits, o.hits...)+ h.took += o.took}// noteMasked records what masking swapped in a request that went to a@@ -49,7 +55,12 @@ func noteMasked(r *http.Request, what string, h maskHits, sent string, route int}rec.Values = valuesOf(h.hits)rec.Snips = snipsOf(sent, h.hits)+ rec.Took = h.took.Microseconds()+ rec.Sent = sentrec = maskrec.Add(rec)+ if h.key != nil {+ *h.key = rec.Key+ }m := &Masked{N: rec.N, Key: rec.Key}for _, v := range rec.Values {if v.Action == "warn" {diff --git a/internal/gateway/masked_sent_test.go b/internal/gateway/masked_sent_test.gonew file mode 100644index 000000000..a92cba014--- /dev/null+++ b/internal/gateway/masked_sent_test.go@@ -0,0 +1,59 @@+package gateway++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "regexp"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/maskrec"+ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings"+)++// A masked request's record has, in memory, the body as its vendor got+// it, how long masking took, and, once the answer is done, how many+// places of the answer had each value put back: the 脱敏 page reads them.+func TestMaskedRecordKeepsSentAndBack(t *testing.T) {+ const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"+ ph := regexp.MustCompile(`\{\{API_KEY_[0-9a-z]{8}\}\}`)+ var got []byte+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got, _ = io.ReadAll(r.Body)+ p := ph.FindString(string(got))+ b, _ := json.Marshal(p + " and " + p)+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"c1","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":`+string(b)+`},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)+ }))+ defer up.Close()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {+ t.Fatal(err)+ }+ if err := settings.Save(settings.Settings{Redact: true}); err != nil {+ t.Fatal(err)+ }+ s := New()+ rec := httptest.NewRecorder()+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","messages":[{"role":"user","content":"key `+key+`"}]}`)))+ p := ph.FindString(string(got))+ if rec.Code != 200 || p == "" || strings.Count(rec.Body.String(), key) != 2 {+ t.Fatalf("%d, sent %s, answered %s", rec.Code, got, rec.Body)+ }+ rs, _ := maskrec.List(0, 1, maskrec.Filter{})+ if len(rs) != 1 {+ t.Fatal("nothing recorded")+ }+ r, ok := maskrec.Get(rs[0].Key)+ if !ok || r.Back[p] != 2 || r.Took <= 0 {+ t.Fatalf("record: %+v", r)+ }+ sent, ok := maskrec.SentOf(r.Key)+ if !ok || !strings.Contains(sent, p) || strings.Contains(sent, key) {+ t.Fatalf("sent %q %v", sent, ok)+ }+}diff --git a/internal/gateway/redact.go b/internal/gateway/redact.goindex 32031bbf8..3052962fc 100644--- a/internal/gateway/redact.go+++ b/internal/gateway/redact.go@@ -4,9 +4,11 @@ import ("errors""fmt""net/http"+ "time""github.com/yetone/magpie/internal/gwmw""github.com/yetone/magpie/internal/masking"+ "github.com/yetone/magpie/internal/maskrec""github.com/yetone/magpie/internal/provider""github.com/yetone/magpie/internal/settings")@@ -32,6 +34,7 @@ func redactedHits(w http.ResponseWriter, body []byte) (http.ResponseWriter, []byb []byteh maskHits}+ began := time.Now()o, err := gwmw.Safely(func() out {if t, ok := m.(gwmw.Teller); ok {b, hits := t.JSONHits(body)@@ -40,6 +43,7 @@ func redactedHits(w http.ResponseWriter, body []byte) (http.ResponseWriter, []byb, n := m.JSON(body)return out{b, maskHits{n: n}}})+ o.h.took = time.Since(began)if err == nil {err = blocked(o.h)}@@ -50,9 +54,25 @@ func redactedHits(w http.ResponseWriter, body []byte) (http.ResponseWriter, []byreturn w, body, func() {}, o.h, nil}rw, done := m.Writer(w)+ done = toldBack(rw, done, &o.h)return rw, o.b, done, o.h, nil}+// toldBack is done, which then tells the request's record what rw put+// back in the answer, where rw counts it and the request was recorded.+func toldBack(rw http.ResponseWriter, done func(), h *maskHits) func() {+ c, ok := rw.(interface{ Put() map[string]int })+ if !ok {+ return done+ }+ key := new(int64)+ h.key = key+ return func() {+ done()+ maskrec.Restored(*key, c.Put())+ }+}+// redactedPrompt masks a parsed image or video prompt before any vendor// body is built, including multipart forms, and restores the reply's text.// It fails closed as redacted does.@@ -71,6 +91,7 @@ func redactedPromptHits(w http.ResponseWriter, prompt string) (http.ResponseWritreturn w, prompt, func() {}, h, nil}rw, done := m.Writer(w)+ done = toldBack(rw, done, &h)return rw, masked, done, h, nil}@@ -92,6 +113,7 @@ func maskTextHits(s string) (gwmw.Masker, string, maskHits, error) {s stringh maskHits}+ began := time.Now()o, err := gwmw.Safely(func() out {if t, ok := m.(gwmw.Teller); ok {got, hits := t.TextHits(s)@@ -100,6 +122,7 @@ func maskTextHits(s string) (gwmw.Masker, string, maskHits, error) {got, n := m.Text(s)return out{got, maskHits{n: n}}})+ o.h.took = time.Since(began)if err == nil {err = blocked(o.h)}diff --git a/internal/gui/masking.go b/internal/gui/masking.goindex 55b20ee1f..1b77ee894 100644--- a/internal/gui/masking.go+++ b/internal/gui/masking.go@@ -15,6 +15,9 @@ import (// previewMax is how much text the preview masks.const previewMax = 64 << 10+// valuesMax is how many placeholders one /api/masking/values asks for.+const valuesMax = 2000+// maskedRecord is a record as the page shows it: each value says whether// the masker still knows what it stood for, so the page offers to show it// only where it can.@@ -59,6 +62,12 @@ func shownRecord(r maskrec.Record, t gwmw.Teller) maskedRecord {// - GET /api/masking/value?p= what a placeholder stood for, while this// magpie's masker remembers it (404 after a restart: it is never on// disk);+// - GET /api/masking/sent?key= the body a record's request went to its+// vendor with, masked, while this magpie keeps it (the latest+// maskrec keeps; 404 after a restart);+// - POST /api/masking/values {ps} what each placeholder stood for, of+// those the masker still remembers, for the page to show the request+// as the agent sent it;// - POST /api/masking/preview {text} the text as a vendor would get it// under the settings now, and what was found, each told by its kind// and hint, never its value; nothing of it is remembered (#1977).@@ -129,4 +138,33 @@ func maskingRoutes(mux *http.ServeMux) {}writeJSON(rw, map[string]string{"value": v})})+ mux.HandleFunc("GET /api/masking/sent", func(rw http.ResponseWriter, r *http.Request) {+ rw.Header().Set("Cache-Control", "no-store")+ key, _ := strconv.ParseInt(r.URL.Query().Get("key"), 10, 64)+ body, ok := maskrec.SentOf(key)+ if !ok {+ http.NotFound(rw, r)+ return+ }+ writeJSON(rw, map[string]string{"body": body})+ })+ mux.HandleFunc("POST /api/masking/values", func(rw http.ResponseWriter, r *http.Request) {+ rw.Header().Set("Cache-Control", "no-store")+ var in struct {+ Ps []string `json:"ps"`+ }+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&in); err != nil {+ fail(rw, err)+ return+ }+ out := map[string]string{}+ if t, ok := teller(); ok {+ for _, p := range in.Ps[:min(len(in.Ps), valuesMax)] {+ if v, ok := t.Value(p); ok {+ out[p] = v+ }+ }+ }+ writeJSON(rw, map[string]any{"values": out})+ })}diff --git a/internal/gui/masking_test.go b/internal/gui/masking_test.goindex 94e7d71ed..f53fcea4c 100644--- a/internal/gui/masking_test.go+++ b/internal/gui/masking_test.go@@ -87,4 +87,22 @@ func TestMaskingRecordsAPI(t *testing.T) {if code := get("/api/masking/value?p="+url.QueryEscape("{{EMAIL_00000000}}"), nil); code != http.StatusNotFound {t.Fatalf("a placeholder it never made: %d", code)}++ // the request as it went, and the values to read it as it came+ body := `{"messages":[{"role":"user","content":"` + sent + `"}]}`+ whole := maskrec.Add(maskrec.Record{What: "chat", N: 1, Sent: body,+ Values: []maskrec.Value{{Placeholder: p, Kind: hits[0].Kind, By: hits[0].By, Len: hits[0].Len}}})+ var got struct{ Body string }+ if get("/api/masking/sent?key="+strconv.FormatInt(whole.Key, 10), &got); got.Body != body {+ t.Fatalf("sent %q", got.Body)+ }+ if code := get("/api/masking/sent?key="+strconv.FormatInt(rec.Key, 10), nil); code != http.StatusNotFound {+ t.Fatalf("a record kept without its body: %d", code)+ }+ rw := httptest.NewRecorder()+ srv.ServeHTTP(rw, httptest.NewRequest("POST", "/api/masking/values", strings.NewReader(`{"ps":["`+p+`","{{EMAIL_00000000}}"]}`)))+ var vs struct{ Values map[string]string }+ if err := json.Unmarshal(rw.Body.Bytes(), &vs); err != nil || len(vs.Values) != 1 || vs.Values[p] != key || rw.Header().Get("Cache-Control") != "no-store" {+ t.Fatalf("values %d %s %v", rw.Code, rw.Body, rw.Header())+ }}diff --git a/internal/maskrec/maskrec.go b/internal/maskrec/maskrec.goindex 4eec65f20..1049be6b9 100644--- a/internal/maskrec/maskrec.go+++ b/internal/maskrec/maskrec.go@@ -33,7 +33,14 @@ const (// keepSnips is how many of the latest records memory keeps, with the// text around their valueskeepSnips = 400- dayForm = "2006-01-02"+ // keepSent is how many of the latest requests memory keeps whole, as+ // the vendor got them, up to sentMax each: the 脱敏 page shows a+ // request's text from it, its values put back from the masker's+ // memory, and sentBudget in all+ keepSent = 100+ sentMax = 4 << 20+ sentBudget = 64 << 20+ dayForm = "2006-01-02")// Value is one value a request had masked, as often as it had it.@@ -67,6 +74,14 @@ type Record struct {// Snips: by placeholder, the text around its first place as the// vendor saw it; in memory onlySnips map[string]string `json:"snips,omitempty"`+ // Took is how long masking the request took, in microseconds+ Took int64 `json:"took,omitempty"`+ // Back: by placeholder, the places the answer had it put back; in+ // memory only, told once the answer is done (Restored)+ Back map[string]int `json:"back,omitempty"`+ // Sent is the request as the vendor got it; in memory only, for the+ // latest keepSent, and never in a list (SentOf)+ Sent string `json:"-"`}// Dir is where the days are kept.@@ -81,6 +96,15 @@ var store struct {pruned time.Timedays map[string]*dayAgg // a day's file → what it holds, as of its sizesnips []Record // the latest records, with their snips+ sent []kept // the records whose Sent memory keeps, oldest first+ // sentBytes is their Sent in all+ sentBytes int+}++// kept is a record whose Sent memory keeps, and its length.+type kept struct {+ key int64+ n int}// inTest says Add writes nothing: in a test binary testenv isolated, a@@ -109,15 +133,31 @@ func Add(r Record) Record {r.Key = store.last + 1}store.last = r.Key+ if len(r.Sent) > sentMax {+ r.Sent = ""+ }+ if r.Sent != "" {+ store.sent = append(store.sent, kept{r.Key, len(r.Sent)})+ store.sentBytes += len(r.Sent)+ }+ for len(store.sent) > keepSent || store.sentBytes > sentBudget {+ drop := store.sent[0]+ store.sent = store.sent[1:]+ store.sentBytes -= drop.n+ if i := at(drop.key); i >= 0 {+ store.snips[i].Sent = ""+ }+ }store.snips = append(store.snips, r)if len(store.snips) > keepSnips {store.snips = append([]Record(nil), store.snips[len(store.snips)-keepSnips:]...)}+ r.Sent = ""if inTest() {return r}disk := r- disk.Snips = nil+ disk.Snips, disk.Back = nil, nilb, err := json.Marshal(disk)if err != nil {return r@@ -240,15 +280,55 @@ func read(path string, each func(Record)) int64 {return size}-// withSnips is r with the snips memory has for it.+// at is where memory has the record of key, -1 where it hasn't.+func at(key int64) int {+ i := sort.Search(len(store.snips), func(i int) bool { return store.snips[i].Key >= key })+ if i < len(store.snips) && store.snips[i].Key == key {+ return i+ }+ return -1+}++// withSnips is r with what memory has for it: its snips and what the+// answer put back.func withSnips(r Record) Record {- i := sort.Search(len(store.snips), func(i int) bool { return store.snips[i].Key >= r.Key })- if i < len(store.snips) && store.snips[i].Key == r.Key {- r.Snips = store.snips[i].Snips+ if i := at(r.Key); i >= 0 {+ r.Snips, r.Back = store.snips[i].Snips, store.snips[i].Back}return r}+// Restored tells the record of key what its answer put back: by+// placeholder, the places. Memory only, as the snips are.+func Restored(key int64, put map[string]int) {+ if key == 0 || len(put) == 0 {+ return+ }+ store.mu.Lock()+ defer store.mu.Unlock()+ if i := at(key); i >= 0 {+ back := map[string]int{}+ for p, n := range store.snips[i].Back {+ back[p] = n+ }+ for p, n := range put {+ back[p] += n+ }+ store.snips[i].Back = back+ }+}++// SentOf is the request of key as the vendor got it, while memory keeps+// it.+func SentOf(key int64) (string, bool) {+ store.mu.Lock()+ defer store.mu.Unlock()+ if i := at(key); i >= 0 && store.snips[i].Sent != "" {+ return store.snips[i].Sent, true+ }+ return "", false+}+// Filter narrows List: by kind, by finder, by agent or provider; "" is// any.type Filter struct {@@ -316,8 +396,10 @@ func List(before int64, limit int, f Filter) ([]Record, bool) {func Get(key int64) (Record, bool) {store.mu.Lock()defer store.mu.Unlock()- if i := sort.Search(len(store.snips), func(i int) bool { return store.snips[i].Key >= key }); i < len(store.snips) && store.snips[i].Key == key {- return store.snips[i], true+ if i := at(key); i >= 0 {+ r := store.snips[i]+ r.Sent = ""+ return r, true}day := time.Unix(0, key).Local().Format(dayForm)var got Recorddiff --git a/internal/maskrec/maskrec_test.go b/internal/maskrec/maskrec_test.goindex 5f1dd7678..2837fb44c 100644--- a/internal/maskrec/maskrec_test.go+++ b/internal/maskrec/maskrec_test.go@@ -14,7 +14,7 @@ func sandbox(t *testing.T, now time.Time) string {oldDir, oldClock, oldOwn := Dir, clock, ownTestDir, clock, ownTest = func() string { return dir }, func() time.Time { return now }, truestore.mu.Lock()- store.days, store.snips, store.last, store.pruned = nil, nil, 0, time.Time{}+ store.days, store.snips, store.sent, store.sentBytes, store.last, store.pruned = nil, nil, nil, 0, 0, time.Time{}store.mu.Unlock()t.Cleanup(func() { Dir, clock, ownTest = oldDir, oldClock, oldOwn })return dirdiff --git a/internal/maskrec/sent_test.go b/internal/maskrec/sent_test.gonew file mode 100644index 000000000..5045805d2--- /dev/null+++ b/internal/maskrec/sent_test.go@@ -0,0 +1,91 @@+package maskrec++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// The body a request went with is kept in memory for the latest keepSent+// requests only, never on disk, and not past sentMax; what the answer put+// back is memory's too, added to as it is told.+func TestSentAndBackInMemory(t *testing.T) {+ now := time.Date(2026, 10, 24, 9, 0, 0, 0, time.Local)+ dir := sandbox(t, now)+ const p = "{{API_KEY_ccccdddd}}"+ body := `{"messages":[{"role":"user","content":"key ` + p + ` here"}]}`+ first := Add(Record{Time: now, What: "chat", N: 1, Took: 812, Sent: body,+ Values: []Value{{Placeholder: p, Kind: "API_KEY", By: "rule", Head: "sk-", Len: 40}}})+ if first.Sent != "" {+ t.Fatal("Add handed the body back")+ }+ if got, ok := SentOf(first.Key); !ok || got != body {+ t.Fatalf("SentOf: %q %v", got, ok)+ }+ Restored(first.Key, map[string]int{p: 2})+ Restored(first.Key, map[string]int{p: 1})+ got, ok := Get(first.Key)+ if !ok || got.Back[p] != 3 || got.Took != 812 || got.Sent != "" {+ t.Fatalf("Get: %+v", got)+ }+ b, err := os.ReadFile(filepath.Join(dir, "2026-10-24.jsonl"))+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(b), "here") || strings.Contains(string(b), `"back"`) || !strings.Contains(string(b), `"took":812`) {+ t.Fatalf("disk: %s", b)+ }++ // too large: the record is kept, its body isn't+ big := Add(Record{Time: now, What: "chat", N: 1, Sent: strings.Repeat("x", sentMax+1),+ Values: []Value{{Placeholder: p, Kind: "API_KEY", By: "rule", Len: 40}}})+ if _, ok := SentOf(big.Key); ok {+ t.Fatal("a body over sentMax was kept")+ }+ // keepSent more: the first's body goes, its record and snips stay+ for range keepSent {+ Add(Record{Time: now, What: "chat", N: 1, Sent: body,+ Values: []Value{{Placeholder: p, Kind: "API_KEY", By: "rule", Len: 40}}})+ }+ if _, ok := SentOf(first.Key); ok {+ t.Fatal("the oldest body outlived keepSent")+ }+ if got, ok := Get(first.Key); !ok || got.Back[p] != 3 {+ t.Fatalf("the record went with its body: %+v %v", got, ok)+ }+ store.mu.Lock()+ n := 0+ for _, r := range store.snips {+ if r.Sent != "" {+ n+++ }+ }+ store.mu.Unlock()+ if n != keepSent {+ t.Fatalf("%d bodies kept, want %d", n, keepSent)+ }+ // sentBudget in all: the oldest go first+ sandbox(t, now)+ var keys []int64+ for range 20 {+ r := Add(Record{Time: now, What: "chat", N: 1, Sent: strings.Repeat("y", sentMax),+ Values: []Value{{Placeholder: p, Kind: "API_KEY", By: "rule", Len: 40}}})+ keys = append(keys, r.Key)+ }+ if _, ok := SentOf(keys[len(keys)-sentBudget/sentMax-1]); ok {+ t.Fatal("bodies over sentBudget kept")+ }+ if _, ok := SentOf(keys[len(keys)-sentBudget/sentMax]); !ok {+ t.Fatal("a body within sentBudget dropped")+ }+ if store.sentBytes != sentBudget {+ t.Fatalf("sentBytes %d", store.sentBytes)+ }+ // a key nobody has+ Restored(12345, map[string]int{p: 1})+ if _, ok := SentOf(12345); ok {+ t.Fatal("SentOf an unknown key")+ }+}diff --git a/internal/redact/json.go b/internal/redact/json.goindex dc044230f..f64ca8d3e 100644--- a/internal/redact/json.go+++ b/internal/redact/json.go@@ -463,7 +463,10 @@ func asJSON(key, eventType string) bool {}// RestoreJSON puts the values back in a response body.-func RestoreJSON(body []byte) []byte {+func RestoreJSON(body []byte) []byte { return restoreJSON(body, nil) }++// restoreJSON is RestoreJSON, counting in put as restore does.+func restoreJSON(body []byte, put map[string]int) []byte {if !bytes.Contains(body, []byte("{{")) {return body}@@ -472,10 +475,10 @@ func RestoreJSON(body []byte) []byte {if path == "type" {typ = s}- return Restore(s, asJSON(key, typ))+ return restore(s, asJSON(key, typ), put)})if !ok {- return []byte(Restore(string(body), false))+ return []byte(restore(string(body), false, put))}return out}diff --git a/internal/redact/put_test.go b/internal/redact/put_test.gonew file mode 100644index 000000000..f7c80a4f6--- /dev/null+++ b/internal/redact/put_test.go@@ -0,0 +1,57 @@+package redact++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// The writer counts each place it put a value back once: a placeholder a+// stream splits across events is one place, and a whole answer's places+// are each counted.+func TestWriterPutCounts(t *testing.T) {+ pw, _ := Mask(openaiKey, Options{Secrets: true})+ event := func(s string) string {+ b, _ := json.Marshal(map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": s}})+ return "event: content_block_delta\ndata: " + string(b) + "\n\n"+ }+ all := event("use "+pw[:5]) + event(pw[5:12]) + event(pw[12:]+" and ") + event(pw+".") + "data: [DONE]\n\n"+ rec := httptest.NewRecorder()+ rec.Header().Set("Content-Type", "text/event-stream")+ w := NewWriter(rec)+ w.WriteHeader(200)+ for i := 0; i < len(all); i += 7 {+ w.Write([]byte(all[i:min(i+7, len(all))]))+ }+ w.Finish()+ if !strings.Contains(rec.Body.String(), openaiKey) {+ t.Fatalf("not put back: %s", rec.Body.String())+ }+ if got := w.Put(); len(got) != 1 || got[pw] != 2 {+ t.Fatalf("stream put %v, want %s twice", got, pw)+ }++ b, _ := json.Marshal(map[string]any{"content": []any{map[string]any{"type": "text", "text": pw + " " + pw + " " + pw}}})+ rec = httptest.NewRecorder()+ rec.Header().Set("Content-Type", "application/json")+ w = NewWriter(rec)+ w.WriteHeader(http.StatusOK)+ w.Write(b)+ w.Finish()+ if got := w.Put(); got[pw] != 3 {+ t.Fatalf("whole put %v, want 3", got)+ }++ // nothing to put back: nothing counted+ rec = httptest.NewRecorder()+ rec.Header().Set("Content-Type", "application/json")+ w = NewWriter(rec)+ w.WriteHeader(http.StatusOK)+ w.Write([]byte(`{"content":"plain"}`))+ w.Finish()+ if got := w.Put(); len(got) != 0 {+ t.Fatalf("plain put %v", got)+ }+}diff --git a/internal/redact/redact.go b/internal/redact/redact.goindex 46fbb8414..3bf909603 100644--- a/internal/redact/redact.go+++ b/internal/redact/redact.go@@ -920,7 +920,11 @@ var placeholderBody = regexp.MustCompile(`[A-Za-z][A-Za-z0-9_]*_[A-Za-z2-7]{8}`)// braces, or changes the case. Any of those is put back too when what is// left names a placeholder this magpie made: its kind and the 8 of its// hash, which no other text has by chance (shensmart on Discord).-func Restore(s string, escaped bool) string {+func Restore(s string, escaped bool) string { return restore(s, escaped, nil) }++// restore is Restore, counting in put, when it isn't nil, each+// placeholder it put a value back for.+func restore(s string, escaped bool, put map[string]int) string {if !strings.Contains(s, "_") {return s}@@ -936,7 +940,8 @@ func Restore(s string, escaped bool) string {if a < last || a > 0 && isWordByte(s[a-1]) || z < len(s) && isWordByte(s[z]) {continue}- v, ok := values[canonical(s[a:z])]+ p := canonical(s[a:z])+ v, ok := values[p]if !ok {continue}@@ -944,6 +949,9 @@ func Restore(s string, escaped bool) string {if a < last {continue}+ if put != nil {+ put[p]+++ }b.WriteString(s[last:a])if escaped {v = jsonEscape(v)diff --git a/internal/redact/writer.go b/internal/redact/writer.goindex e11510b3b..20a542c0a 100644--- a/internal/redact/writer.go+++ b/internal/redact/writer.go@@ -21,6 +21,7 @@ type Writer struct {buf bytes.Bufferpending *helddone bool+ put map[string]int // placeholders put back, each place counted}const (@@ -42,6 +43,17 @@ func NewWriter(w http.ResponseWriter) *Writer { return &Writer{w: w} }func (rw *Writer) Header() http.Header { return rw.w.Header() }+// Put is how many places of each placeholder the answer had put back,+// so far: for the record of what masking did.+func (rw *Writer) Put() map[string]int { return rw.put }++func (rw *Writer) count() map[string]int {+ if rw.put == nil {+ rw.put = map[string]int{}+ }+ return rw.put+}+// Unwrap is for http.ResponseController.func (rw *Writer) Unwrap() http.ResponseWriter { return rw.w }@@ -159,14 +171,14 @@ func (rw *Writer) Finish() {rw.done = trueswitch rw.mode {case whole:- rw.w.Write(RestoreJSON(rw.buf.Bytes()))+ rw.w.Write(restoreJSON(rw.buf.Bytes(), rw.count()))case stream:if rw.pending != nil {rw.w.Write(rw.pending.full)rw.pending = nil}if rw.buf.Len() > 0 {- rw.w.Write([]byte(Restore(rw.buf.String(), false)))+ rw.w.Write([]byte(restore(rw.buf.String(), false, rw.count())))}}rw.Flush()@@ -179,7 +191,7 @@ func (rw *Writer) event(ev []byte) error {if err := rw.release(); err != nil {return err}- _, err := rw.w.Write([]byte(Restore(string(ev), false)))+ _, err := rw.w.Write([]byte(restore(string(ev), false, rw.count())))return err}ctx := name + "|" + eventCtx(data)@@ -215,7 +227,9 @@ func (rw *Writer) event(ev []byte) error {tailPath, tail = path, s[len(s)-n:]cut = Restore(s[:len(s)-n], asJSON(key, typ))}- return Restore(s, asJSON(key, typ))+ // counted here only: cut is s again without its tail, and+ // whichever of the two goes out, the places are these+ return restore(s, asJSON(key, typ), rw.count())})full := rebuild(pre, restored, post)if tail == "" {