pii: the local models' folder is chosen under Advanced, and Move… moves them (MetalHqa on X)

On Windows both models (Privacy Filter 1.6 GB, AstrLink Guard 39 MB)
went onto the C: drive with no way to choose. Settings > Privacy now has
Advanced > Models folder: Move… picks a folder in the system's picker and
moves what is downloaded there; Move back returns it to magpie's cache.
The default is unchanged.

- settings.RedactModelDir is this computer's own (kept by KeepOwn, never
  set by a settings save).
- pii.Root() is the one place every path is made from (dir, guardRoot,
  so the model, its cache files, pf-serve, the CoreML program).
- pii.MoveTo: a rename on one disk, else a copy checked by sha256 read
  back; the setting switches after it and the old subfolders are deleted
  last (never the picked folder); a failure puts back what it moved and
  keeps the old copy. Refuses a relative path, an unwritable folder and
  one inside what is moved. A picked folder that has gone (disk
  unplugged) is not recreated by a download. Download and Remove wait
  out a move.
- GUI: pmfolder.js, loaded on first draw so the core script is no bigger;
  strings in zh, zh-TW, ja, de. Docs: gateway-routing.md, masking.html
  (en, zh, ja), site index regenerated with docs-index.mjs.

Run (mica; mote had no room, load 35/18 and 29/12):
- go test of internal/pii folder tests, internal/gui TestPrivacyModel*,
  internal/settings and settingsapi keep tests: ok. Each broken by hand
  and red: guardRoot ignoring the folder, no rollback, no missing-folder
  check, KeepOwn line removed, settingsapi line removed, folder action
  not calling MoveTo.
- Windows box (win-run): the move tests ok, TestMoveAcrossDisks on a real
  C: to D: move ok.
- GUI privacy-model.test.cjs, Chromium and WebKit, 5 languages, 1100 and
  640px: 104 of 104.
- go vet on pii, gui, settings, settingsapi for linux (nogui), windows
  and darwin: clean. node --test site/*.test.mjs: 135 of 135.

Not run before this push: the whole GUI suite, go test ./... (both
follow at the pushed head), the size-budget and i18n tests (run after the
rebase), gofmt over the whole tree (touched files only), and a real
Privacy Filter download into a picked folder on a real account.
This commit is contained in:
yetone
2026-11-20 00:12:34 +08:00
parent 83bb079dee
commit 958d4fcaf1
24 changed files with 920 additions and 29 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1725,7 +1725,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
appPageRoutes(mux)
remoteRoutes(mux, w)
}
privacyModelRoutes(mux)
privacyModelRoutes(mux, w)
maskingRoutes(mux)
builtinRoutes(mux)
mux.HandleFunc("GET /api/settings", func(rw http.ResponseWriter, r *http.Request) {
+3 -2
View File
@@ -22118,13 +22118,14 @@ function privacyModelRow(box, why) {
sr.replaceChildren(sw, sv);
if (!sr.isConnected) r.after(sr);
} else sr.remove();
import("./pmfolder.js").then(() => window.pmFolder(r, sr, m, act), () => {});
clearTimeout(pmTimer);
// a download's progress, and where pf-serve runs once it has started
const starting = m?.on && m.installed && !m.running && !m.failed && tries++ < 30;
if (pmBusy(m) || starting) pmTimer = setTimeout(load, 1000);
if (pmBusy(m) || starting || m?.moving) pmTimer = setTimeout(load, 1000);
};
const load = () => api("privacy-model").then((m) => { pmState = m; draw(m); }).catch(() => {});
const act = (doing, model, score) => { tries = 0; api("privacy-model", { do: doing, model, score }).then((m) => { pmState = m; draw(m); }).catch((e) => { statusTErr(e); load(); }); };
const act = (doing, model, score, dir) => { tries = 0; api("privacy-model", { do: doing, model, score, dir }).then((m) => { pmState = m; draw(m); }).catch((e) => { statusTErr(e); load(); }); };
draw(pmState);
load();
}
+16
View File
@@ -1767,6 +1767,10 @@ const I18N = {
"Find with a local model": "用本地模型查找",
"Delete model": "删除模型",
"Delete the model?": "删除模型?",
"Models folder": "模型文件夹",
"Moving the models: {done} of {total}": "正在移动模型:{done} / {total}",
"The move stopped: {error}": "移动已停止:{error}",
"Moved, but the old copy couldn't be deleted: {paths}": "已移动,但旧副本没能删除:{paths}",
"The local model": "本地模型",
"Confidence threshold": "置信度阈值",
"What the model is less sure of goes as written. Higher masks less, with fewer false alarms": "模型把握低于此值的内容原样发送。调高则遮得更少,误报也更少",
@@ -7275,6 +7279,10 @@ const I18N = {
"Find with a local model": "用本機模型查找",
"Delete model": "刪除模型",
"Delete the model?": "刪除模型?",
"Models folder": "模型資料夾",
"Moving the models: {done} of {total}": "正在移動模型:{done} / {total}",
"The move stopped: {error}": "移動已停止:{error}",
"Moved, but the old copy couldn't be deleted: {paths}": "已移動,但舊副本沒能刪除:{paths}",
"The local model": "本機模型",
"Confidence threshold": "信賴度門檻",
"What the model is less sure of goes as written. Higher masks less, with fewer false alarms": "模型把握低於此值的內容原樣送出。調高則遮得更少,誤報也更少",
@@ -12745,6 +12753,10 @@ const I18N = {
"Find with a local model": "ローカルモデルで検出",
"Delete model": "モデルを削除",
"Delete the model?": "モデルを削除しますか?",
"Models folder": "モデルのフォルダー",
"Moving the models: {done} of {total}": "モデルを移動中:{done} / {total}",
"The move stopped: {error}": "移動が止まりました:{error}",
"Moved, but the old copy couldn't be deleted: {paths}": "移動しましたが、古いコピーを削除できませんでした:{paths}",
"The local model": "ローカルモデル",
"Confidence threshold": "信頼度のしきい値",
"What the model is less sure of goes as written. Higher masks less, with fewer false alarms": "モデルの確信度がこれより低いものはそのまま送ります。高くするとマスクが減り、誤検出も減ります",
@@ -18258,6 +18270,10 @@ const I18N = {
"Find with a local model": "Mit lokalem Modell finden",
"Delete model": "Modell löschen",
"Delete the model?": "Modell löschen?",
"Models folder": "Modellordner",
"Moving the models: {done} of {total}": "Modelle werden verschoben: {done} von {total}",
"The move stopped: {error}": "Das Verschieben wurde angehalten: {error}",
"Moved, but the old copy couldn't be deleted: {paths}": "Verschoben, aber die alte Kopie ließ sich nicht löschen: {paths}",
"The local model": "Lokales Modell",
"Confidence threshold": "Konfidenzschwelle",
"What the model is less sure of goes as written. Higher masks less, with fewer false alarms": "Was das Modell für weniger sicher hält, geht unverändert raus. Höher maskiert weniger, mit weniger Fehlalarmen",
+34
View File
@@ -0,0 +1,34 @@
// Settings › Privacy's Models folder (MetalHqa on X: on Windows both local
// models went onto the C: drive): where they are downloaded, under an
// Advanced fold since it is set once. Move… picks a folder in the system's
// picker and the models are moved there in the background, copied and
// checked before the old ones go; Move back is magpie's cache. app.js
// imports this the first time the model row draws, so it weighs nothing on
// the core.
let pmFolderOpen = false;
window.pmFolder = function (row, score, m, act) {
// under the threshold's row, or the model's own while that is out
let box = document.getElementById("pmFolderRow");
if (!row.isConnected || !m?.folder || (!m.supported && !m.installed && !m.folderSet)) return void box?.remove();
if (!box) (box = el("div")).id = "pmFolderRow";
if (box.previousElementSibling !== (score.isConnected ? score : row)) (score.isConnected ? score : row).after(box);
let d = box.querySelector("details.pm-adv");
if (!d) {
d = el("details", "prefs-more pm-adv");
d.ontoggle = () => { pmFolderOpen = d.open; };
d.append(el("summary", "", t("Advanced")));
}
d.open = pmFolderOpen || !!m.folderSet || !!m.moving || !!m.moveError;
const r = el("div", "row pref pm-folder");
const who = el("div", "who"), val = el("div", "val");
const say = m.moving ? t("Moving the models: {done} of {total}", { done: fmtBytes(m.moveDone || 0), total: fmtBytes(m.moveTotal || 0) }) : m.folder;
who.append(el("div", "name", t("Models folder")), el("div", "sub wraps pm-folder-dir" + (m.moving ? " say" : ""), say));
if (m.moveError && !m.moving) who.append(el("div", "sub wraps bad pm-folder-said", t("The move stopped: {error}", { error: m.moveError })));
else if (m.moveLeft && !m.moving) who.append(el("div", "sub wraps pm-folder-said", t("Moved, but the old copy couldn't be deleted: {paths}", { paths: m.moveLeft })));
const btn = (label, fn) => { const b = el("button", "text", label); b.type = "button"; b.disabled = !!m.moving; b.onclick = fn; return b; };
val.append(btn(t("Move…"), () => act("folder", "", 0, "")));
if (m.folderSet) val.append(btn(t("Move back"), () => act("folder", "", 0, "default")));
r.append(who, val);
d.replaceChildren(d.firstChild, r);
if (d.parentNode !== box) box.replaceChildren(d);
};
+23 -3
View File
@@ -21,6 +21,11 @@ type privacyModelJSON struct {
// a request held back for it (masking.ModelOn)
Chosen bool `json:"chosen,omitempty"`
pii.Status
// Folder is where the models are kept (pii.Root, as ~ for the home),
// FolderSet that the user picked it
Folder string `json:"folder"`
FolderSet bool `json:"folderSet,omitempty"`
pii.Moving
MinScore float64 `json:"minScore"`
DefaultScore float64 `json:"defaultScore"`
Models []pii.Status `json:"models"`
@@ -37,6 +42,7 @@ func privacyModelState() privacyModelJSON {
for _, m := range models() {
out.Models = append(out.Models, m.Now())
}
out.Folder, out.FolderSet, out.Moving = tilde(pii.Root()), pii.Custom(), pii.MoveState()
return out
}
@@ -49,8 +55,10 @@ func privacyModelState() privacyModelJSON {
// model downloaded, or picks model: while it is on, that is turning it on
// as model (the one before masks until model is downloaded); while off,
// the pick is kept for turning it on; score keeps s as the threshold of
// model (the one masking uses, with none), 0 for its default.
func privacyModelRoutes(mux *http.ServeMux) {
// model (the one masking uses, with none), 0 for its default; folder moves
// the downloaded models to dir (the system's picker for "", magpie's cache
// for "default") in the background, which the state's moving says.
func privacyModelRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/privacy-model", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, privacyModelState())
})
@@ -59,6 +67,7 @@ func privacyModelRoutes(mux *http.ServeMux) {
Do string `json:"do"`
Model string `json:"model"`
Score float64 `json:"score"`
Dir string `json:"dir"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
@@ -82,6 +91,17 @@ func privacyModelRoutes(mux *http.ServeMux) {
default:
err = settings.SetRedactModelName(in.Model)
}
case "folder":
// "" asks with the system's picker; "default" is magpie's cache
dir := in.Dir
if dir == "" {
if dir, err = w.ChooseFolder("Choose a folder for the local models"); err != nil || dir == "" {
break // cancelled: nothing moved
}
} else if dir == "default" {
dir = ""
}
err = pii.MoveTo(dir)
case "score":
id := in.Model
if id == "" {
@@ -124,7 +144,7 @@ func privacyModelRoutes(mux *http.ServeMux) {
}
}
default:
err = fmt.Errorf("do is on, off, cancel, remove, pick or score, not %q", in.Do)
err = fmt.Errorf("do is on, off, cancel, remove, pick, folder or score, not %q", in.Do)
}
if err != nil {
fail(rw, err)
+92
View File
@@ -5,9 +5,11 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/pii"
"github.com/yetone/magpie/internal/redact"
@@ -210,3 +212,93 @@ func TestPrivacyModelPick(t *testing.T) {
t.Fatalf("remove: %+v %v", st, did)
}
}
// Models folder (MetalHqa on X: both went onto the C: drive): Move… takes
// the picker's folder and moves what is downloaded there, the state says
// where the models are and that the user picked it, Move back returns them
// to magpie's cache, and a cancelled picker moves nothing.
func TestPrivacyModelFolder(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Cleanup(func() { settings.SetRedactModelDir("") })
def := pii.Root()
held := filepath.Join(def, "astrlink-guard", "rev", "model.onnx")
if err := os.MkdirAll(filepath.Dir(held), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(held, []byte("weights"), 0o644); err != nil {
t.Fatal(err)
}
picked := filepath.Join(t.TempDir(), "models")
pick := &pickFolder{dir: picked}
srv := webPageHandler(t, folderPick{p: pick}, nil)
do := func(body string) privacyModelJSON {
t.Helper()
rec := httptest.NewRecorder()
method := "POST"
if body == "" {
method = "GET"
}
srv.ServeHTTP(rec, httptest.NewRequest(method, "/api/privacy-model", strings.NewReader(body)))
var st privacyModelJSON
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil {
t.Fatalf("%s: %d %s", body, rec.Code, rec.Body)
}
return st
}
settle := func() privacyModelJSON {
t.Helper()
for end := time.Now().Add(30 * time.Second); time.Now().Before(end); time.Sleep(10 * time.Millisecond) {
if st := do(""); !st.Moving.Moving {
return st
}
}
t.Fatal("the move never ended")
return privacyModelJSON{}
}
if st := do(""); st.FolderSet || st.Folder != tilde(def) {
t.Fatalf("before: %+v", st)
}
pick.dir = ""
do(`{"do":"folder"}`)
if st := settle(); st.FolderSet {
t.Fatalf("a cancelled picker moved: %+v", st)
}
pick.dir = picked
do(`{"do":"folder"}`)
st := settle()
if !st.FolderSet || st.Folder != tilde(picked) || st.Moving.Error != "" || settings.Load().RedactModelDir != picked {
t.Fatalf("moved: %+v", st)
}
if b, err := os.ReadFile(filepath.Join(picked, "astrlink-guard", "rev", "model.onnx")); err != nil || string(b) != "weights" {
t.Fatalf("the model isn't in the picked folder: %v", err)
}
if _, err := os.Stat(held); !os.IsNotExist(err) {
t.Fatalf("the old copy is still there: %v", err)
}
do(`{"do":"folder","dir":"default"}`)
st = settle()
if st.FolderSet || st.Folder != tilde(def) || settings.Load().RedactModelDir != "" {
t.Fatalf("back: %+v", st)
}
if _, err := os.Stat(held); err != nil {
t.Fatalf("the model didn't come back: %v", err)
}
// a folder that can't be used is an error, not a move
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("POST", "/api/privacy-model", strings.NewReader(`{"do":"folder","dir":"relative/path"}`)))
if rec.Code == http.StatusOK {
t.Fatalf("a relative folder was accepted")
}
}
// folderPick answers the picker with whatever its pointer holds now.
type folderPick struct {
folderOnly
p *pickFolder
}
func (f folderPick) ChooseFolder(s string) (string, error) { return f.p.ChooseFolder(s) }
+11 -4
View File
@@ -9,7 +9,6 @@ import (
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/pii/guard"
"github.com/yetone/magpie/internal/redact"
)
@@ -42,9 +41,9 @@ var guardBase = "https://huggingface.co/QuantumNous/astrlink-guard/resolve/"
func guardURL(f pinned) string { return guardBase + guardRev + "/" + f.path }
// guardRoot is where AstrLink Guard's files are kept, in magpie's cache
// beside Privacy Filter's folder: a folder per revision, and the found
// beside Privacy Filter's folder (Root): a folder per revision, and the found
// file (cache.go).
var guardRoot = func() string { return filepath.Join(appdir.Cache(), "astrlink-guard") }
var guardRoot = func() string { return filepath.Join(Root(), guardFolder) }
func guardDir() string { return filepath.Join(guardRoot(), guardRev[:12]) }
@@ -362,7 +361,12 @@ func (guardModel) Now() Status {
return s
}
func (guardModel) Download(done func()) error { return gdl.run(guardSize(), guardInstall, done) }
func (guardModel) Download(done func()) error {
if err := downloadable(); err != nil {
return err
}
return gdl.run(guardSize(), guardInstall, done)
}
func (guardModel) Cancel() { gdl.stop() }
@@ -386,6 +390,9 @@ func (guardModel) Stop() {
}
func (g guardModel) Remove() error {
if moving() {
return errMoving
}
g.Cancel()
g.Stop()
gdl.mu.Lock()
+3
View File
@@ -59,6 +59,9 @@ func Download(done func()) error {
if !Supported() {
return fmt.Errorf("the local masking model doesn't run on %s yet", target())
}
if err := downloadable(); err != nil {
return err
}
return dl.run(modelSize, install, done)
}
+406
View File
@@ -0,0 +1,406 @@
package pii
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
)
// The folder the models are kept in (MetalHqa on X: on Windows both went
// onto the C: drive). Each model has a folder of its own in it,
// privacy-filter and astrlink-guard, as in magpie's cache; magpie never
// deletes the folder the user picked, only those two.
//
// Every path to a model's files goes through dir and guardRoot, which go
// through Root: a download, a load, the size check, a delete, the found
// cache. The folder is read from the settings on each use, so a magpie
// serving the gateway beside the window follows a change made in it.
const (
pfFolder = "privacy-filter"
guardFolder = "astrlink-guard"
)
// Root is the folder the models are kept in: the user's (settings
// RedactModelDir), or magpie's cache.
func Root() string {
if d := settings.Shared().RedactModelDir; d != "" {
return d
}
return appdir.Cache()
}
// Custom says the user picked the folder.
func Custom() bool { return settings.Shared().RedactModelDir != "" }
// downloadable is nil when a download may start: no move is under way,
// and the folder is there.
func downloadable() error {
if moving() {
return errMoving
}
return ensureRoot()
}
// ensureRoot is for a download: a folder the user picked that isn't there
// (its disk unplugged) is no place to make again, which would fill the
// disk the drive stands for under its mount point.
func ensureRoot() error {
if !Custom() {
return nil
}
r := Root()
if fi, err := os.Stat(r); err != nil || !fi.IsDir() {
return fmt.Errorf("the models folder %s isn't there: connect its disk, or choose another folder", r)
}
return nil
}
// A move of the models to another folder, in the background, and what it
// is at.
var mv struct {
mu sync.Mutex
moving bool
done, total int64
err string
left string
}
// Moving is the state of the move: under way, how far, why the last one
// failed, and what it couldn't delete of the old folder.
type Moving struct {
Moving bool `json:"moving,omitempty"`
Done int64 `json:"moveDone,omitempty"`
Total int64 `json:"moveTotal,omitempty"`
Error string `json:"moveError,omitempty"`
Left string `json:"moveLeft,omitempty"`
}
// MoveState is the move's state.
func MoveState() Moving {
mv.mu.Lock()
defer mv.mu.Unlock()
return Moving{mv.moving, mv.done, mv.total, mv.err, mv.left}
}
func moving() bool {
mv.mu.Lock()
defer mv.mu.Unlock()
return mv.moving
}
var errMoving = errors.New("the models are being moved to another folder; wait for it to finish")
// writable is nil when files can be made in dir.
func writable(dir string) error {
f, err := os.CreateTemp(dir, ".magpie-write-*")
if err != nil {
return fmt.Errorf("can't write to %s: %w", dir, err)
}
_, err = f.Write([]byte{0})
if cerr := f.Close(); err == nil {
err = cerr
}
os.Remove(f.Name())
if err != nil {
return fmt.Errorf("can't write to %s: %w", dir, err)
}
return nil
}
// inside says p is q or under it, by the files they are (a link, a
// differently written path) and by their names.
func inside(p, q string) bool {
rel, err := filepath.Rel(q, p)
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return true
}
if rp, err := filepath.EvalSymlinks(p); err == nil {
if rq, err := filepath.EvalSymlinks(q); err == nil && (rp != p || rq != q) {
return inside(rp, rq)
}
}
return false
}
// MoveTo moves the models to the folder to ("" or magpie's cache: back to
// the default), in the background; MoveState says how it goes. What it
// moves is copied and checked before the setting names the new folder and
// before anything of the old is deleted, so a move that fails, in a
// folder that fills up or on a disk that goes, leaves the models where
// they were.
func MoveTo(to string) error {
if to == "" {
to = appdir.Cache()
}
if !filepath.IsAbs(to) {
return fmt.Errorf("the folder must be a full path, not %q", to)
}
to = filepath.Clean(to)
from := Root()
fromPF, fromGuard := dir(), guardRoot()
if sameDir(to, from) {
return nil
}
// a folder inside what is being moved is deleted with it
for _, d := range []string{fromPF, fromGuard} {
if inside(to, d) {
return fmt.Errorf("%s is inside the models' own folder %s", to, d)
}
}
if err := os.MkdirAll(to, 0o755); err != nil {
return fmt.Errorf("can't make %s: %w", to, err)
}
if err := writable(to); err != nil {
return err
}
mv.mu.Lock()
if mv.moving {
mv.mu.Unlock()
return errMoving
}
mv.moving, mv.err, mv.left, mv.done, mv.total = true, "", "", 0, 0
mv.mu.Unlock()
go func() {
left, err := moveModels(to, [][2]string{{fromPF, filepath.Join(to, pfFolder)}, {fromGuard, filepath.Join(to, guardFolder)}})
mv.mu.Lock()
mv.moving, mv.left = false, left
if err != nil {
mv.err = err.Error()
}
mv.mu.Unlock()
}()
return nil
}
func sameDir(a, b string) bool {
if filepath.Clean(a) == filepath.Clean(b) {
return true
}
fa, err := os.Stat(a)
if err != nil {
return false
}
fb, err := os.Stat(b)
return err == nil && os.SameFile(fa, fb)
}
// moveModels moves each pair's old folder to its new one, then saves to as
// the folder. left names what of the old folders couldn't be deleted.
func moveModels(to string, pairs [][2]string) (left string, err error) {
// nothing is downloading into, or running from, the old folder
Cancel()
guardModel{}.Cancel()
for i := 0; i < 100 && (dlBusy(&dl) || dlBusy(&gdl)); i++ {
time.Sleep(50 * time.Millisecond)
}
Stop()
guardModel{}.Stop()
pf.saveCache()
guardBackend.saveCache()
var total int64
for _, p := range pairs {
total += treeSize(p[0])
}
mv.mu.Lock()
mv.total = total
mv.mu.Unlock()
var undo []func()
rollback := func() {
for i := len(undo) - 1; i >= 0; i-- {
undo[i]()
}
}
var moved [][2]string // the pairs whose old folder is still to delete
for _, p := range pairs {
old, now := p[0], p[1]
if _, serr := os.Stat(old); serr != nil {
continue
}
// the same disk: one rename, nothing copied
if _, serr := os.Lstat(now); os.IsNotExist(serr) {
if os.Rename(old, now) == nil {
o, n := old, now
undo = append(undo, func() { os.Rename(n, o) })
mv.mu.Lock()
mv.done += treeSize(now)
mv.mu.Unlock()
continue
}
}
made, cerr := copyVerified(old, now, &mv.done, &mv.mu)
n := now
undo = append(undo, func() {
for i := len(made) - 1; i >= 0; i-- {
os.Remove(made[i])
}
os.Remove(n) // empty, if it was made for this
})
if cerr != nil {
rollback()
return "", fmt.Errorf("moving to %s: %w", to, cerr)
}
moved = append(moved, p)
}
save := to
if sameDir(to, appdir.Cache()) {
save = ""
}
if serr := settings.SetRedactModelDir(save); serr != nil {
rollback()
return "", fmt.Errorf("saving the folder: %w", serr)
}
// the new folder is the one in use; the old one goes only now
Stop()
guardModel{}.Stop()
var bad []string
for _, p := range moved {
if rerr := os.RemoveAll(p[0]); rerr != nil {
bad = append(bad, p[0])
}
}
return strings.Join(bad, ", "), nil
}
func dlBusy(d *dlState) bool {
d.mu.Lock()
defer d.mu.Unlock()
return d.cancel != nil
}
func treeSize(root string) int64 {
var n int64
filepath.WalkDir(root, func(_ string, e fs.DirEntry, err error) error {
if err == nil && !e.IsDir() {
if fi, err := e.Info(); err == nil {
n += fi.Size()
}
}
return nil
})
return n
}
// copyVerified copies the files under from into to, each through a
// .part file that is flushed, read back and hashed against what was read
// of the source before it takes its name. made lists the files created
// that weren't there before, for undoing a copy that stopped. A file
// already in to with the same size and hash is left as it is.
func copyVerified(from, to string, done *int64, mu *sync.Mutex) (made []string, err error) {
err = filepath.WalkDir(from, func(p string, e fs.DirEntry, werr error) error {
if werr != nil {
return werr
}
rel, _ := filepath.Rel(from, p)
dst := filepath.Join(to, rel)
if e.IsDir() {
if _, serr := os.Stat(dst); os.IsNotExist(serr) {
if merr := os.MkdirAll(dst, 0o755); merr != nil {
return merr
}
made = append(made, dst)
}
return nil
}
if !e.Type().IsRegular() {
return nil
}
_, existed := os.Stat(dst)
if err := copyOne(p, dst, done, mu); err != nil {
return err
}
if existed != nil {
made = append(made, dst)
}
return nil
})
return made, err
}
func copyOne(src, dst string, done *int64, mu *sync.Mutex) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
fi, err := in.Stat()
if err != nil {
return err
}
part := dst + ".part-move"
out, err := os.OpenFile(part, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
return err
}
h := sha256.New()
_, err = io.Copy(io.MultiWriter(out, h), progress{in, done, mu})
if err == nil {
err = out.Sync()
}
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(part)
return err
}
// read back what was written, from the disk, not what was sent
got, err := fileSHA(part)
if err == nil && got != hex.EncodeToString(h.Sum(nil)) {
err = fmt.Errorf("%s was copied wrong", filepath.Base(src))
}
if err == nil {
if pi, serr := os.Stat(part); serr != nil || pi.Size() != fi.Size() {
err = fmt.Errorf("%s was copied short", filepath.Base(src))
}
}
if err != nil {
os.Remove(part)
return err
}
if err := os.Rename(part, dst); err != nil {
os.Remove(part)
return err
}
return nil
}
type progress struct {
r io.Reader
done *int64
mu *sync.Mutex
}
func (p progress) Read(b []byte) (int, error) {
n, err := p.r.Read(b)
p.mu.Lock()
*p.done += int64(n)
p.mu.Unlock()
return n, err
}
func fileSHA(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+257
View File
@@ -0,0 +1,257 @@
package pii
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
)
// seed writes the models' files where the default folder keeps them, and
// returns what each holds by its path under the root.
func seed(t *testing.T) map[string]string {
t.Helper()
files := map[string]string{
filepath.Join(pfFolder, modelName()): strings.Repeat("model-bytes ", 5000),
filepath.Join(pfFolder, serveTag+"-x", "pf-serve"): "exe",
filepath.Join(guardFolder, guardRev[:12], "model.onnx"): strings.Repeat("g", 777),
}
for rel, body := range files {
p := filepath.Join(Root(), rel)
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() {
settings.SetRedactModelDir("")
os.RemoveAll(filepath.Join(appdir.Cache(), pfFolder))
os.RemoveAll(filepath.Join(appdir.Cache(), guardFolder))
})
return files
}
func moved(t *testing.T) Moving {
t.Helper()
for end := time.Now().Add(60 * time.Second); time.Now().Before(end); time.Sleep(10 * time.Millisecond) {
if s := MoveState(); !s.Moving {
return s
}
}
t.Fatal("the move never ended")
return Moving{}
}
func read(t *testing.T, p string) string {
t.Helper()
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// The models move to the picked folder, every path follows it, and the old
// folders are gone. One folder is moved by a rename and the other, with
// its target there already, by the copy a move to another disk makes.
func TestMoveToFollowsEveryPath(t *testing.T) {
files := seed(t)
def := Root()
to := filepath.Join(t.TempDir(), "models")
if err := os.MkdirAll(filepath.Join(to, guardFolder), 0o755); err != nil {
t.Fatal(err)
}
if err := MoveTo(to); err != nil {
t.Fatal(err)
}
if s := moved(t); s.Error != "" || s.Left != "" {
t.Fatalf("move: %+v", s)
}
if Root() != to || !Custom() {
t.Fatalf("Root = %s, want %s", Root(), to)
}
for _, p := range []string{dir(), guardRoot(), cachePath(), modelPath(), guardDir()} {
if !strings.HasPrefix(p, to) {
t.Errorf("%s isn't under %s", p, to)
}
}
for rel, body := range files {
if got := read(t, filepath.Join(to, rel)); got != body {
t.Errorf("%s changed in the move", rel)
}
}
for _, d := range []string{pfFolder, guardFolder} {
if _, err := os.Stat(filepath.Join(def, d)); !os.IsNotExist(err) {
t.Errorf("the old %s is still there: %v", d, err)
}
}
// the setting is saved, and a sync's settings keep this computer's
if settings.Load().RedactModelDir != to {
t.Error("the folder isn't saved")
}
// back to the default
if err := MoveTo(""); err != nil {
t.Fatal(err)
}
if s := moved(t); s.Error != "" {
t.Fatal(s.Error)
}
if Custom() || Root() != def || settings.Load().RedactModelDir != "" {
t.Errorf("not back to the default: %s %v", Root(), Custom())
}
for rel, body := range files {
if got := read(t, filepath.Join(def, rel)); got != body {
t.Errorf("%s lost on the way back", rel)
}
}
// the folder the user picked is theirs: never deleted
if _, err := os.Stat(to); err != nil {
t.Errorf("the picked folder was deleted: %v", err)
}
}
// A move that fails leaves every model where it was, and the setting as it
// was: the second folder can't be copied, and the first, already moved, is
// put back.
func TestFailedMoveLosesNothing(t *testing.T) {
files := seed(t)
def := Root()
to := filepath.Join(t.TempDir(), "models")
// astrlink-guard exists in the target, with a directory where a file of
// the model's would be written
block := filepath.Join(to, guardFolder, guardRev[:12], "model.onnx.part-move")
if err := os.MkdirAll(block, 0o755); err != nil {
t.Fatal(err)
}
if err := MoveTo(to); err != nil {
t.Fatal(err)
}
if s := moved(t); s.Error == "" {
t.Fatal("the move didn't fail")
}
if Custom() || Root() != def {
t.Errorf("the setting changed: %s", Root())
}
for rel, body := range files {
if got := read(t, filepath.Join(def, rel)); got != body {
t.Errorf("%s changed", rel)
}
}
if _, err := os.Stat(filepath.Join(to, pfFolder)); !os.IsNotExist(err) {
t.Errorf("the first folder's move wasn't undone: %v", err)
}
// a new move works once the cause is gone
os.Remove(block)
if err := MoveTo(to); err != nil {
t.Fatal(err)
}
if s := moved(t); s.Error != "" {
t.Fatal(s.Error)
}
if Root() != to {
t.Errorf("Root = %s", Root())
}
}
// A folder that can't be written, can't be made, or is inside what is
// moved is refused before anything is touched.
func TestMoveToRefusesBadFolders(t *testing.T) {
files := seed(t)
def := Root()
file := filepath.Join(t.TempDir(), "afile")
if err := os.WriteFile(file, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
bad := map[string]string{
"relative": "models",
"under a file": filepath.Join(file, "models"),
"inside": filepath.Join(def, pfFolder, "sub"),
}
if runtime.GOOS != "windows" && os.Getuid() != 0 {
ro := filepath.Join(t.TempDir(), "ro")
if err := os.Mkdir(ro, 0o500); err != nil {
t.Fatal(err)
}
bad["read only"] = ro
}
for name, to := range bad {
if err := MoveTo(to); err == nil {
t.Errorf("%s: %s was accepted", name, to)
}
if moving() {
t.Errorf("%s: a move started", name)
}
}
if Custom() {
t.Error("the folder was saved")
}
for rel, body := range files {
if read(t, filepath.Join(def, rel)) != body {
t.Errorf("%s changed", rel)
}
}
}
// A picked folder that isn't there (its disk is out) is not made again by
// a download, and nothing starts while a move is under way.
func TestDownloadNeedsItsFolder(t *testing.T) {
seed(t)
gone := filepath.Join(t.TempDir(), "unplugged", "models")
if err := settings.SetRedactModelDir(gone); err != nil {
t.Fatal(err)
}
if err := Download(nil); err == nil || !strings.Contains(err.Error(), "isn't there") {
t.Errorf("Download = %v", err)
}
if err := (guardModel{}).Download(nil); err == nil || !strings.Contains(err.Error(), "isn't there") {
t.Errorf("guard Download = %v", err)
}
if _, err := os.Stat(filepath.Join(gone, "..")); !os.IsNotExist(err) {
t.Errorf("the folder was made: %v", err)
}
mv.mu.Lock()
mv.moving = true
mv.mu.Unlock()
defer func() { mv.mu.Lock(); mv.moving = false; mv.mu.Unlock() }()
if err := Remove(); err != errMoving {
t.Errorf("Remove = %v", err)
}
if err := (guardModel{}).Remove(); err != errMoving {
t.Errorf("guard Remove = %v", err)
}
}
// Moving to another disk: set PII_OTHER_DISK to a folder on one (the
// Windows box's D:), where the rename can't be used and the copy is.
func TestMoveAcrossDisks(t *testing.T) {
other := os.Getenv("PII_OTHER_DISK")
if other == "" {
t.Skip("PII_OTHER_DISK names a folder on another disk")
}
files := seed(t)
def := Root()
to := filepath.Join(other, "magpie-models-test")
t.Cleanup(func() { os.RemoveAll(to) })
os.RemoveAll(to)
if err := MoveTo(to); err != nil {
t.Fatal(err)
}
if s := moved(t); s.Error != "" || s.Left != "" {
t.Fatalf("move: %+v", s)
}
for rel, body := range files {
if read(t, filepath.Join(to, rel)) != body {
t.Errorf("%s changed", rel)
}
if _, err := os.Stat(filepath.Join(def, rel)); !os.IsNotExist(err) {
t.Errorf("%s left behind", rel)
}
}
}
+8 -5
View File
@@ -40,7 +40,6 @@ import (
"runtime"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/pii/guard"
"github.com/yetone/magpie/internal/redact"
)
@@ -76,10 +75,11 @@ func Supported() bool { return serveSHA[target()] != "" }
// Size is how much turning the model on downloads.
func Size() int64 { return modelSize }
// dir is where the model and pf-serve are kept: magpie's cache, since
// either can be downloaded again, and never the settings' folder, which a
// sync carries to the user's other computers.
var dir = func() string { return filepath.Join(appdir.Cache(), "privacy-filter") }
// dir is where the model and pf-serve are kept: in Root, magpie's cache
// unless the user picked a folder (folder.go), since either can be
// downloaded again, and never the settings' folder, which a sync carries to
// the user's other computers.
var dir = func() string { return filepath.Join(Root(), pfFolder) }
func modelPath() string { return filepath.Join(dir(), modelName()) }
@@ -204,6 +204,9 @@ func Now() Status {
// Remove ends pf-serve and deletes the model and pf-serve.
func Remove() error {
if moving() {
return errMoving
}
Cancel()
Stop()
dl.mu.Lock()
+18 -3
View File
@@ -238,9 +238,14 @@ type Settings struct {
RedactModelName string `json:"redactModelName,omitempty"`
RedactModelOff bool `json:"redactModelOff,omitempty"`
RedactModelAuto bool `json:"redactModelAuto,omitempty"`
RedactPersonal bool `json:"redactPersonal,omitempty"`
RedactKinds map[string]bool `json:"redactKinds,omitempty"`
RedactWords []string `json:"redactWords,omitempty"`
// RedactModelDir is the folder the local models are downloaded into
// (pii.Root), an absolute path on this computer, so a sync never
// carries it; "" is magpie's cache, as before (MetalHqa on X: the
// models filled his C: drive).
RedactModelDir string `json:"redactModelDir,omitempty"`
RedactPersonal bool `json:"redactPersonal,omitempty"`
RedactKinds map[string]bool `json:"redactKinds,omitempty"`
RedactWords []string `json:"redactWords,omitempty"`
// RedactWordsAnyCase matches RedactWords in any case (ZoeCats on
// Discord); off, the default, a word is matched as written.
RedactWordsAnyCase bool `json:"redactWordsAnyCase,omitempty"`
@@ -1839,6 +1844,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.PanelShortcut = cur.PanelShortcut
s.RedactModel, s.RedactModelName, s.RedactModelScore = cur.RedactModel, cur.RedactModelName, cur.RedactModelScore
s.RedactModelOff, s.RedactModelAuto = cur.RedactModelOff, cur.RedactModelAuto
s.RedactModelDir = cur.RedactModelDir // a folder of this computer's
s.ClaudeRunsMost = cur.ClaudeRunsMost
s.RequestArchiveLocal, s.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB
s.AgentsHere = cur.AgentsHere
@@ -2563,6 +2569,15 @@ func UseDefaultRedactModel(name string) (bool, error) {
return true, save(s, false)
}
// SetRedactModelDir keeps dir as the folder the local models are kept in;
// "" is magpie's cache.
func SetRedactModelDir(dir string) error {
defer lockFile()()
s := load()
s.RedactModelDir = dir
return save(s, false)
}
// SetRedactModelName keeps the local model the user picked while it is
// off, for turning it on.
func SetRedactModelName(name string) error {
+22
View File
@@ -538,3 +538,25 @@ func TestDefaultTextSize(t *testing.T) {
t.Fatalf("on %s the default is %d, want %d", runtime.GOOS, orig(), want)
}
}
// The models folder is this computer's: settings that come from another
// computer's sync keep the one set here, and it is saved and cleared on its
// own.
func TestRedactModelDirKept(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := SetRedactModelDir("/models"); err != nil {
t.Fatal(err)
}
cur := Load()
if cur.RedactModelDir != "/models" {
t.Fatalf("not saved: %q", cur.RedactModelDir)
}
from := Settings{RedactModelDir: "D:\\their-disk"}
from.KeepOwn(cur)
if from.RedactModelDir != "/models" {
t.Fatalf("a sync took the folder: %q", from.RedactModelDir)
}
if err := SetRedactModelDir(""); err != nil || Load().RedactModelDir != "" {
t.Fatalf("cleared: %v %q", err, Load().RedactModelDir)
}
}
+1
View File
@@ -335,6 +335,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.RedactModelScore = cur.RedactModelScore // set on its own (privacy-model)
in.RedactModelOff = cur.RedactModelOff // set on its own (privacy-model)
in.RedactModelAuto = cur.RedactModelAuto // set on its own (masking)
in.RedactModelDir = cur.RedactModelDir // set on its own (privacy-model's folder)
in.RedactActions = cur.RedactActions // set on their own (redact-actions)
in.RedactAllow = cur.RedactAllow // set on its own (redact-allow)
in.DisabledModels = cur.DisabledModels // set on their own (disabled-models, #1867)
+14
View File
@@ -386,3 +386,17 @@ func TestImageGenAcceptsMiniMaxImageModel(t *testing.T) {
t.Error("a model it doesn't draw was taken")
}
}
// The models folder is set by Move… on the redaction page, never by a
// settings save, whatever the body says.
func TestRedactModelDirIsNotASettingsSave(t *testing.T) {
cur := settings.Defaults()
cur.RedactModelDir = "/models"
in, err := Merge([]byte(`{"theme":"dark","redactModelDir":"/elsewhere"}`), cur, false)
if err != nil {
t.Fatal(err)
}
if in.RedactModelDir != "/models" {
t.Errorf("a save changed the models folder: %q", in.RedactModelDir)
}
}
+3 -3
View File
@@ -109,7 +109,7 @@ f063a06ffc57785ad0f8f40f0b2f0bd2ae897ec9d6f290cf664bae2e12d899ed docs/ja/intent
4c58e158e2e08c7f6e21b210cc07140d1732a9cffb75643f47e6ba313389ec77 docs/ja/local-models.html
4d665a14ad50a99e6a035a6b8217a67feac0541623244f71daff2e2ce6297a00 docs/ja/lody.html
9bea8e6efdb7f57ce75fd89c239d2829af4222b1bb9917e823c1ba102e05fdb2 docs/ja/longcat.html
7b5a0c8413ba3095ce4cdbb75915de32f44abf75d13e085bacf0199279012773 docs/ja/masking.html
6002b793a902d7130528d5ed43ec4fefcaea2fa875df970fd26b0660f160ceb2 docs/ja/masking.html
f8f7c4da5a6ca001ed40006701c019543f4a162b3dc490e9f9bc0093b166efb5 docs/ja/mcp-router.html
0a1bd26af3942a3537a6006a0aa78981f7dffe12c20f11a7b830906d765f6dce docs/ja/minimax.html
a52e5907f53affdf8e3cb348886fd2520343fce404e8fbab15498fff8dcfe673 docs/ja/miniq.html
@@ -184,7 +184,7 @@ a3f7d9b772d9f1734afec293578d79f26e49dd1f28a2f0f1ae206b6138165b82 docs/kun.html
f83bd40947cc12cac5e7477e91f5531328872f6459e8ee1e31b6d2f190095e77 docs/local-models.html
bd548638edd3756c4331ee720516e2f0de897f57e691c8a78a1d414110c3bf2d docs/lody.html
eaad977724db5b88137e9be4c1734ba9065a4d45dbba3354490a876c79d55313 docs/longcat.html
0d36ee3e874cb2f7fc720a3320c9c91e7c8117a50551ec1e7a13da28d3ceaa7c docs/masking.html
d1abcca60965a83baf2dafbefd06aadcd4c7153973a6b0f1cc7dc9499ca17395 docs/masking.html
be0600229e330e3171beeac64e3932dcbd74f1f0f5406a7fc3eaf5ead9ca18ce docs/mcp-router.html
4c0629bd0c76c7ecc9bd4559991d58eebb51ac4f2bc88f3a2660036c0b9524d1 docs/minimax.html
2b377d49172ec2d3c79c8378595602f441e875af34e09d825270d11cfbdd4b91 docs/miniq.html
@@ -309,7 +309,7 @@ ae704fe7a6aaf74c1ecbe2aab1efc86db51c73424d71518baf567a28f9502b3c docs/zh/librar
02f33da03f589c855c0963c41c384aa5157958c63de9333cd55d33f20b906379 docs/zh/local-models.html
16be660a0d387ebcde497f1bdc2f645fae8158ae81592670ddffa80ed5060d12 docs/zh/lody.html
37549abe83acef720dffbc8a085227084556b0ad8ae543ad4f2ee71023a1afcc docs/zh/longcat.html
48c22c5e63678f221e3b604da134de0bc7f06b7274d6aaa2d80a793e2759ed3d docs/zh/masking.html
01a56f7d2606d87e4268c1a16d464b5fe967afc210d1ab31ae48f7a1fe2dee7f docs/zh/masking.html
fc2728e0847c7c277545ca5812ca3bef3c805b30c1838b02040ffee6e208d92c docs/zh/mcp-router.html
45a02efc89166679be0ddb321f139ccb7c285bba14948a850f3dc4371a1ac159 docs/zh/minimax.html
64e838ea41c9f8f3d493ec027b444864acfbdc4eddfd96b471d90903dada34b2 docs/zh/miniq.html
+1 -1
View File
@@ -173,7 +173,7 @@
<tr><td><span class="ui">シークレットをマスク</span></td><td>秘密鍵のブロック(<code>-----BEGIN … PRIVATE KEY-----</code>)。形で見分ける API キー:<code>sk-…</code>(OpenAI、Anthropic、OpenRouter)、<code>ghp_</code>/<code>github_pat_</code>、<code>glpat-</code>、<code>AIza…</code>、<code>xox…-</code>、<code>sk_live_</code>、<code>AKIA</code>/<code>ASIA</code>、<code>hf_</code>、<code>gsk_</code>、<code>xai-</code>、<code>npm_</code>、<code>pypi-</code>、<code>dop_v1_</code>、<code>SG.</code>、Cloudflare のもの(<code>cfut_</code>、<code>cfat_</code>、<code>cfk_</code>、<code>cfoat_</code>、Origin CA <code>v1.0-</code>、Tunnel トークン)、それに <code>oc_sk_…</code> のような中継サービスのキー。JWT。<code>user:password@host</code> のパスワード。<code>.env</code> や設定ファイルでシークレットの名前が付いたフィールドの値:<code>DB_PASSWORD=…</code>、<code>api_key: …</code>、<code>client_secret</code>、<code>token</code>、<code>credential</code>。それと自分の <span class="ui">マスクルール</span>。 ウォレットの秘密鍵も、ウォレットが書き出す形で探します:Bitcoin の WIF、BIP32 の <code>xprv</code>、Ethereum と TRON の <code>0x</code> 鍵、Solana の鍵と <code>id.json</code> のキーペア、Sui の <code>suiprivkey1…</code>、Aptos の <code>ed25519-priv-0x…</code>、Stellar のシード、NEAR の <code>ed25519:…</code>、Nostr の <code>nsec1…</code>、age の ID、Zcash の拡張支払鍵、<em>seed</em> や <em>ニーモニック</em> の後の、どの語も BIP39 の単語リストにある 12〜25 語のシードフレーズ。決まった接頭辞のない鍵は検証を通ったときだけ置き換えます:WIF と <code>xprv</code> はチェックサム、Solana の鍵は後半の公開鍵、Stellar のシードは CRC で確かめるので、Solana のトランザクション署名はそのまま送られます。<code>0x</code> 鍵はトランザクションハッシュと同じ形なので、鍵の名前の後(<code>PRIVATE_KEY=</code>、<code>--private-key</code>、<code>new Wallet(…)</code>、私钥)でだけ置き換えます。ハッシュ、ストレージスロット、sha256 の値はそのまま送られます。取引所の API キー、シークレット、<code>passphrase</code> はフィールド名で置き換えます。</td></tr>
<tr><td><span class="ui">個人情報をマスク</span></td><td>メールアドレス、中国本土の携帯番号(11 桁の ID は別:<code>order_id</code> の値や 订单号 の後ろのものはそのまま)、チェックサムの合う中国の身分証番号と銀行カード番号。既定でオンのもの:米国の社会保障番号、パスポート番号(<em>passport</em>、护照、パスポートの後)、IBAN、誕生日(<em>birthday</em>、<em>DOB</em>、生日の近くにある、一年以上前の日付。今日の日付はそのまま)、MAC アドレス、シリアル番号(<em>S/N</em> の後)。エージェントがほぼ毎回送るので、自分でオンにするまでオフのもの:ホームフォルダのユーザー名(毎回同じ仮の名前で送るので、モデルにはプレースホルダーではなく普通のフォルダに見えます)、ユーザー名とコンピュータ名(<code>user@host</code>)、パブリック IP アドレス(<code>public-ip-kvxqmrtz</code> のような名前として送るので、モデルはパブリックなアドレスだとわかったまま接続に使い、コマンドの中で本物のアドレスに戻ります)、クラウドストレージのバケット。ウォレットやコントラクトのアドレス(<code>0x</code> と 16 進 40 桁)は公開情報なのでそのまま送ります。秘密鍵は引き続きマスクします。</td></tr>
<tr><td><span class="ui">マスクする語</span></td><td>入れた語そのままを <code>{{TERM_…}}</code> に。日付(<em>1990-05-12</em> など)を入れると、同じ日のどの書き方もマスクされます:<em>1990/5/12</em>、<em>1990.05.12</em>、<em>1990年5月12日</em>、<em>19900512</em>、<em>May 12, 1990</em>。<em>13/05/1990</em> のような日が先の書き方は、日と月を取り違えようがないときだけです。別の日付や <em>1990.5.12.1</em> のようなバージョン番号はマスクされません。</td></tr>
<tr><td><span class="ui">ローカルモデルで検出</span></td><td><span class="ui">検出方法</span> の中にあります。このコンピュータで動くモデルが、ルールでは見つからない自由文中の名前や住所を見つけます。オフにしない限りオンで、最初にマスクするリクエストで AstrLink Guard をダウンロードします。ダウンロードが終わるまではルールだけでマスクします。<span class="ui">シークレットをマスク</span> か <span class="ui">個人情報をマスク</span> がオンのときに使え、見つけたものは同じスイッチに従います。横のメニューでモデルを選べます:AstrLink Guard(中国語と英語、39 MB のダウンロード、コードでの誤検出が少ない、Mac では Neural Engine で動く。既定)か OpenAI の Privacy Filter(1.6 GB、GPU を使える、コード中の普通の値も多く隠す)。その下の <span class="ui">信頼度のしきい値</span> は、値をマスクするのにモデルがどれだけ確かである必要があるかです。既定は Privacy Filter が 0.5、AstrLink Guard が公開元の 0.8。上げると普通の値のマスクは減りますが、本物の名前や住所もそのまま送られやすくなります。誤検出の多くはモデルのあとのルールが既に外すので、既定値は測った中で本物の値を最も逃さない値です。</td></tr>
<tr><td><span class="ui">ローカルモデルで検出</span></td><td><span class="ui">検出方法</span> の中にあります。このコンピュータで動くモデルが、ルールでは見つからない自由文中の名前や住所を見つけます。オフにしない限りオンで、最初にマスクするリクエストで AstrLink Guard をダウンロードします。ダウンロードが終わるまではルールだけでマスクします。<span class="ui">シークレットをマスク</span> か <span class="ui">個人情報をマスク</span> がオンのときに使え、見つけたものは同じスイッチに従います。横のメニューでモデルを選べます:AstrLink Guard(中国語と英語、39 MB のダウンロード、コードでの誤検出が少ない、Mac では Neural Engine で動く。既定)か OpenAI の Privacy Filter(1.6 GB、GPU を使える、コード中の普通の値も多く隠す)。その下の <span class="ui">信頼度のしきい値</span> は、値をマスクするのにモデルがどれだけ確かである必要があるかです。既定は Privacy Filter が 0.5、AstrLink Guard が公開元の 0.8。上げると普通の値のマスクは減りますが、本物の名前や住所もそのまま送られやすくなります。誤検出の多くはモデルのあとのルールが既に外すので、既定値は測った中で本物の値を最も逃さない値です。 モデルは既定では magpie のキャッシュフォルダーに置かれます。別の場所(Windows なら C ドライブ以外)に置くには、モデルの下の<span class="ui">詳細設定</span>を開き、<span class="ui">モデルのフォルダー</span> › <span class="ui">移動…</span>を選びます。ダウンロード済みのモデルはコピーして確認してから、元の場所のものを削除します。<span class="ui">元に戻す</span>で戻せます。</td></tr>
</table></div>
<p>プレースホルダーは「種類 + 鍵付きハッシュの 8 文字」です。同じ値はいつも同じプレースホルダーになるので、会話は毎ターン同じに読め、ベンダーのプロンプトキャッシュも有効なままです。値はメモリにだけ置かれます。</p>
+1 -1
View File
@@ -173,7 +173,7 @@
<tr><td><span class="ui">Mask secrets</span></td><td>Private key blocks (<code>-----BEGIN … PRIVATE KEY-----</code>). API keys by their shape: <code>sk-…</code> (OpenAI, Anthropic, OpenRouter), <code>ghp_</code>/<code>github_pat_</code>, <code>glpat-</code>, <code>AIza…</code>, <code>xox…-</code>, <code>sk_live_</code>, <code>AKIA</code>/<code>ASIA</code>, <code>hf_</code>, <code>gsk_</code>, <code>xai-</code>, <code>npm_</code>, <code>pypi-</code>, <code>dop_v1_</code>, <code>SG.</code>, Cloudflare's (<code>cfut_</code>, <code>cfat_</code>, <code>cfk_</code>, <code>cfoat_</code>, Origin CA <code>v1.0-</code>, tunnel tokens), and relay keys like <code>oc_sk_…</code>. JWTs. The password in <code>user:password@host</code>. The value of a field named for a secret, as <code>.env</code> files and configs have them: <code>DB_PASSWORD=…</code>, <code>api_key: …</code>, <code>client_secret</code>, <code>token</code>, <code>credential</code>. Your own <span class="ui">Masking rules</span>. Wallet private keys by the shape their wallets export: a Bitcoin WIF, a BIP32 <code>xprv</code>, an Ethereum or TRON <code>0x</code> key, a Solana key or <code>id.json</code> keypair, a Sui <code>suiprivkey1…</code>, an Aptos <code>ed25519-priv-0x…</code>, a Stellar seed, a NEAR <code>ed25519:…</code> key, a Nostr <code>nsec1…</code>, an age identity, a Zcash extended spending key, and a 12 to 25 word seed phrase after <em>seed</em> or <em>mnemonic</em> whose every word is in the BIP39 list. A key with no prefix of its own is masked only when it checks out: a WIF or <code>xprv</code> by its checksum, a Solana key by its public half, a Stellar seed by its CRC, so a Solana transaction signature goes as written. A <code>0x</code> key has the shape of a transaction hash, so it is masked only after a key&rsquo;s name (<code>PRIVATE_KEY=</code>, <code>--private-key</code>, <code>new Wallet(…)</code>, 私钥); a hash, a storage slot or a sha256 sum goes as written. An exchange&rsquo;s API key, secret and <code>passphrase</code> go by their fields&rsquo; names.</td></tr>
<tr><td><span class="ui">Mask personal data</span></td><td>Emails, mainland China mobile numbers (not an 11-digit id: one under <code>order_id</code> or after 订单号 goes as written), Chinese ID numbers and bank card numbers whose checksum adds up. Also on by default: US Social Security numbers, passport numbers (after <em>passport</em>, 护照 or パスポート), IBANs, birthdays (next to <em>birthday</em>, <em>DOB</em> or 生日, and over a year ago, so today&rsquo;s date stays), MAC addresses and serial numbers (after <em>S/N</em>). Off until you turn them on, since agents send them in nearly every request: the user name in home folders (sent as a made-up name, the same every turn, so the model reads a real folder rather than a placeholder), user and computer names (<code>user@host</code>), public IP addresses (sent as a name such as <code>public-ip-kvxqmrtz</code>, so the model still knows the address is public and connects with it, and the real address goes back into its commands) and cloud storage buckets. A wallet or contract address (<code>0x</code> and 40 hex digits) is public and goes as written; a private key is still masked.</td></tr>
<tr><td><span class="ui">Masked words</span></td><td>Each word you listed, exactly, as <code>{{TERM_…}}</code>. A date, such as <em>1990-05-12</em>, matches that day however it is written: <em>1990/5/12</em>, <em>1990.05.12</em>, <em>1990年5月12日</em>, <em>19900512</em>, <em>May 12, 1990</em>, and <em>13/05/1990</em> style only where the day can’t be read as a month. Never another date or a version like <em>1990.5.12.1</em>.</td></tr>
<tr><td><span class="ui">Find with a local model</span></td><td>Under <span class="ui">How it’s found</span>. A model on this computer finds what no rule can: a name or an address in free text. It is on unless you turned it off, and AstrLink Guard downloads with the first masked request; until it is on disk, the rules mask alone. It needs <span class="ui">Mask secrets</span> or <span class="ui">Mask personal data</span> on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). <span class="ui">Confidence threshold</span> under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost.</td></tr>
<tr><td><span class="ui">Find with a local model</span></td><td>Under <span class="ui">How it’s found</span>. A model on this computer finds what no rule can: a name or an address in free text. It is on unless you turned it off, and AstrLink Guard downloads with the first masked request; until it is on disk, the rules mask alone. It needs <span class="ui">Mask secrets</span> or <span class="ui">Mask personal data</span> on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). <span class="ui">Confidence threshold</span> under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost. The models are kept in magpie’s cache folder. To keep them elsewhere (on Windows, off the C: drive), open <span class="ui">Advanced</span> under the model and choose <span class="ui">Models folder</span> › <span class="ui">Move…</span>: what is downloaded is copied there, checked, and only then deleted from the old place; <span class="ui">Move back</span> returns it.</td></tr>
</table></div>
<p>A placeholder is the kind plus eight characters of a keyed hash. The same value gets the same placeholder every time, so the conversation reads the same turn after turn and the vendor’s prompt cache stays valid. The values are held in memory only.</p>
+1 -1
View File
@@ -173,7 +173,7 @@
<tr><td><span class="ui">脱敏密钥</span></td><td>私钥块(<code>-----BEGIN … PRIVATE KEY-----</code>)。按格式识别的 API Key:<code>sk-…</code>(OpenAI、Anthropic、OpenRouter)、<code>ghp_</code>/<code>github_pat_</code>、<code>glpat-</code>、<code>AIza…</code>、<code>xox…-</code>、<code>sk_live_</code>、<code>AKIA</code>/<code>ASIA</code>、<code>hf_</code>、<code>gsk_</code>、<code>xai-</code>、<code>npm_</code>、<code>pypi-</code>、<code>dop_v1_</code>、<code>SG.</code>、Cloudflare 的(<code>cfut_</code>、<code>cfat_</code>、<code>cfk_</code>、<code>cfoat_</code>、Origin CA <code>v1.0-</code>、Tunnel token),以及 <code>oc_sk_…</code> 这类中转站的 key。JWT。<code>user:password@host</code> 里的密码。<code>.env</code> 和配置文件里以密钥命名的字段的值:<code>DB_PASSWORD=…</code>、<code>api_key: …</code>、<code>client_secret</code>、<code>token</code>、<code>credential</code>。以及你的 <span class="ui">自定义脱敏规则</span>。 钱包私钥按钱包导出的格式匹配:比特币 WIF、BIP32 <code>xprv</code>、以太坊和 TRON 的 <code>0x</code> 私钥、Solana 私钥与 <code>id.json</code> 密钥对、Sui <code>suiprivkey1…</code>、Aptos <code>ed25519-priv-0x…</code>、Stellar 种子、NEAR <code>ed25519:…</code>、Nostr <code>nsec1…</code>、age 身份、Zcash 扩展支出密钥,以及 <em>seed</em>、<em>助记词</em> 后面、每个词都在 BIP39 词表里的 12 到 25 个单词。没有固定前缀的私钥要先通过校验才会被替换:WIF 和 <code>xprv</code> 看校验和,Solana 私钥看后半段公钥,Stellar 种子看 CRC,所以 Solana 交易签名照原样发送。<code>0x</code> 私钥和交易哈希形状相同,只在私钥的名字后面才替换(<code>PRIVATE_KEY=</code>、<code>--private-key</code>、<code>new Wallet(…)</code>、私钥);哈希、存储槽和 sha256 校验值照原样发送。交易所的 API key、secret 和 <code>passphrase</code> 按字段名替换。</td></tr>
<tr><td><span class="ui">脱敏个人信息</span></td><td>邮箱、中国大陆手机号(11 位的编号不算:在 <code>order_id</code> 下或跟在「订单号」后面的照原样发出)、校验位对得上的身份证号和银行卡号。默认也开着的:美国社会安全号、护照号(跟在 <em>passport</em>、护照或パスポート后面)、IBAN、生日(旁边有 <em>birthday</em>、<em>DOB</em> 或「生日」,且是一年以前的日期,所以今天的日期不动)、MAC 地址、序列号(跟在 <em>S/N</em> 后面)。默认关闭、需要自己打开的(Agent 几乎每个请求都会带):主目录里的用户名(以一个每轮都相同的假名发出,模型看到的是正常的文件夹,而不是占位符)、用户名和主机名(<code>user@host</code>)、公网 IP 地址(以 <code>public-ip-kvxqmrtz</code> 这样的名字发出,模型仍知道这是公网地址,照常用它连接,命令里再换回真实地址)、云存储桶。钱包或合约地址(<code>0x</code> 加 40 位十六进制)是公开的,照原样发出;私钥照样脱敏。</td></tr>
<tr><td><span class="ui">脱敏词</span></td><td>你填的每个词,精确匹配,换成 <code>{{TERM_…}}</code>。填的是日期(比如 <em>1990-05-12</em>)时,同一天的各种写法都会遮掉:<em>1990/5/12</em>、<em>1990.05.12</em>、<em>1990年5月12日</em>、<em>19900512</em>、<em>May 12, 1990</em>;<em>13/05/1990</em> 这种日在前的写法只在日和月不会混淆时才算。别的日期和 <em>1990.5.12.1</em> 这样的版本号不会被遮。</td></tr>
<tr><td><span class="ui">用本地模型查找</span></td><td>在 <span class="ui">怎么找</span> 下面。一个在这台电脑上运行的模型能找出规则找不到的东西:自由文本里的人名、地址。除非你关掉,它默认打开:第一个要脱敏的请求开始下载 AstrLink Guard,下载完成前只用规则脱敏。需要先打开 <span class="ui">脱敏密钥</span> 或 <span class="ui">脱敏个人信息</span>,找到的内容按同样的开关处理。旁边的菜单选择模型:AstrLink Guard(中英文,下载 39 MB,代码里很少误判,在 Mac 上用神经网络引擎运行;默认)或 OpenAI 的 Privacy Filter(1.6 GB,可用 GPU,代码里会遮盖更多普通值)。下面的 <span class="ui">置信度阈值</span> 是模型要多确定才遮盖一个值:Privacy Filter 默认 0.5,AstrLink Guard 默认 0.8(发布者的值)。调高会少遮一些普通值,也会让更多真实的人名、地址原样发出去;模型之后的规则已经去掉了大部分误判,所以默认值是我们测下来漏掉真实信息最少的那一档。</td></tr>
<tr><td><span class="ui">用本地模型查找</span></td><td>在 <span class="ui">怎么找</span> 下面。一个在这台电脑上运行的模型能找出规则找不到的东西:自由文本里的人名、地址。除非你关掉,它默认打开:第一个要脱敏的请求开始下载 AstrLink Guard,下载完成前只用规则脱敏。需要先打开 <span class="ui">脱敏密钥</span> 或 <span class="ui">脱敏个人信息</span>,找到的内容按同样的开关处理。旁边的菜单选择模型:AstrLink Guard(中英文,下载 39 MB,代码里很少误判,在 Mac 上用神经网络引擎运行;默认)或 OpenAI 的 Privacy Filter(1.6 GB,可用 GPU,代码里会遮盖更多普通值)。下面的 <span class="ui">置信度阈值</span> 是模型要多确定才遮盖一个值:Privacy Filter 默认 0.5,AstrLink Guard 默认 0.8(发布者的值)。调高会少遮一些普通值,也会让更多真实的人名、地址原样发出去;模型之后的规则已经去掉了大部分误判,所以默认值是我们测下来漏掉真实信息最少的那一档。 模型默认放在 magpie 的缓存文件夹。想放到别处(比如 Windows 上不占 C 盘),在模型下方展开<span class="ui">高级</span>,点<span class="ui">模型文件夹</span> › <span class="ui">移动…</span>:已下载的模型会复制过去、校验无误后才删除旧的;<span class="ui">移回</span>可放回原处。</td></tr>
</table></div>
<p>占位符是「类型 + 8 位带密钥的哈希」。同一个值每次得到同一个占位符,所以对话每一轮读起来都一样,厂商的提示词缓存也不会失效。原值只保存在内存里。</p>
+1 -1
View File
@@ -3744,7 +3744,7 @@ There is no CLI command for it. Without the window (`magpie serve`, [Docker](htt
| Mask secrets | Private key blocks (`-----BEGIN … PRIVATE KEY-----`). API keys by their shape: `sk-…` (OpenAI, Anthropic, OpenRouter), `ghp_`/`github_pat_`, `glpat-`, `AIza…`, `xox…-`, `sk_live_`, `AKIA`/`ASIA`, `hf_`, `gsk_`, `xai-`, `npm_`, `pypi-`, `dop_v1_`, `SG.`, Cloudflare's (`cfut_`, `cfat_`, `cfk_`, `cfoat_`, Origin CA `v1.0-`, tunnel tokens), and relay keys like `oc_sk_…`. JWTs. The password in `user:password@host`. The value of a field named for a secret, as `.env` files and configs have them: `DB_PASSWORD=…`, `api_key: …`, `client_secret`, `token`, `credential`. Your own Masking rules. Wallet private keys by the shape their wallets export: a Bitcoin WIF, a BIP32 `xprv`, an Ethereum or TRON `0x` key, a Solana key or `id.json` keypair, a Sui `suiprivkey1…`, an Aptos `ed25519-priv-0x…`, a Stellar seed, a NEAR `ed25519:…` key, a Nostr `nsec1…`, an age identity, a Zcash extended spending key, and a 12 to 25 word seed phrase after *seed* or *mnemonic* whose every word is in the BIP39 list. A key with no prefix of its own is masked only when it checks out: a WIF or `xprv` by its checksum, a Solana key by its public half, a Stellar seed by its CRC, so a Solana transaction signature goes as written. A `0x` key has the shape of a transaction hash, so it is masked only after a key&rsquo;s name (`PRIVATE_KEY=`, `--private-key`, `new Wallet(…)`, 私钥); a hash, a storage slot or a sha256 sum goes as written. An exchange&rsquo;s API key, secret and `passphrase` go by their fields&rsquo; names. |
| Mask personal data | Emails, mainland China mobile numbers (not an 11-digit id: one under `order_id` or after 订单号 goes as written), Chinese ID numbers and bank card numbers whose checksum adds up. Also on by default: US Social Security numbers, passport numbers (after *passport*, 护照 or パスポート), IBANs, birthdays (next to *birthday*, *DOB* or 生日, and over a year ago, so today&rsquo;s date stays), MAC addresses and serial numbers (after *S/N*). Off until you turn them on, since agents send them in nearly every request: the user name in home folders (sent as a made-up name, the same every turn, so the model reads a real folder rather than a placeholder), user and computer names (`user@host`), public IP addresses (sent as a name such as `public-ip-kvxqmrtz`, so the model still knows the address is public and connects with it, and the real address goes back into its commands) and cloud storage buckets. A wallet or contract address (`0x` and 40 hex digits) is public and goes as written; a private key is still masked. |
| Masked words | Each word you listed, exactly, as `{{TERM_…}}`. A date, such as *1990-05-12*, matches that day however it is written: *1990/5/12*, *1990.05.12*, *1990年5月12日*, *19900512*, *May 12, 1990*, and *13/05/1990* style only where the day can’t be read as a month. Never another date or a version like *1990.5.12.1*. |
| Find with a local model | Under How it’s found. A model on this computer finds what no rule can: a name or an address in free text. It is on unless you turned it off, and AstrLink Guard downloads with the first masked request; until it is on disk, the rules mask alone. It needs Mask secrets or Mask personal data on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). Confidence threshold under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost. |
| Find with a local model | Under How it’s found. A model on this computer finds what no rule can: a name or an address in free text. It is on unless you turned it off, and AstrLink Guard downloads with the first masked request; until it is on disk, the rules mask alone. It needs Mask secrets or Mask personal data on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). Confidence threshold under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost. The models are kept in magpie’s cache folder. To keep them elsewhere (on Windows, off the C: drive), open Advanced under the model and choose Models folder › Move…: what is downloaded is copied there, checked, and only then deleted from the old place; Move back returns it. |
A placeholder is the kind plus eight characters of a keyed hash. The same value gets the same placeholder every time, so the conversation reads the same turn after turn and the vendor’s prompt cache stays valid. The values are held in memory only.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long