mask

package
v1.26.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mask is 脱敏 (docs/adr/0025-mask-at-cloud-egress.md): the keys, ID and card numbers in what goes to a model service off this device are replaced by placeholders, {{KIND_<12 base32>}}, and the placeholders in what comes back are restored to their values. A placeholder is an HMAC of its kind and value under the device's key, so a value always gets the same one: across turns, across restarts, and the prompt cache holds.

Index

Constants

View Source
const (
	Mask  = "mask"
	Warn  = "warn"
	Block = "block"
)

What is done with a category's values (Config.Actions): 遮住 sends placeholders; 仅警告 sends them as they are, and they are recorded; 拦截 sends nothing of the request (docs/adr/0025-mask-at-cloud-egress.md).

View Source
const (
	SourceRule       = "rule"
	SourceRecognizer = "recognizer"
)

What found a value (Hit.Source): a rule, the user's or a built-in one, or a value known before; or 识别模型 (Config.Recognizer).

View Source
const (
	Secrets   = "secrets"   // 密钥
	IDs       = "ids"       // 证件与金融号码
	Codes     = "codes"     // 验证码与一次性链接
	Phones    = "phones"    // 电话
	Emails    = "emails"    // 邮箱
	Names     = "names"     // 人名
	Addresses = "addresses" // 地址
	Accounts  = "accounts"  // 账号
)

The categories of values, as the user turns each on or off (设置 › AI › 隐私脱敏). Every kind a built-in rule or 识别模型 finds is in one (categories); only 识别模型 finds addresses and accounts.

View Source
const (
	MaxRules = 32
	MaxAllow = 200
)

How many rules and allowed values the user may have.

View Source
const MinScore = 0.8

MinScore is the score under which what a Recognizer found goes as it is: AstrLink Guard's publisher's default, fixed (ADR 0028).

View Source
const TermKind = "TERM"

TermKind is the kind of the user's words (自定义词).

Variables

View Source
var (
	ErrKind         = errors.New("a kind is a letter, then letters, digits or _, at most 24")
	ErrEmptyMatch   = errors.New("the pattern matches empty text")
	ErrReservedKind = errors.New("the kind is a built-in one's")
	ErrTooManyRules = fmt.Errorf("at most %d masking rules", MaxRules)
	ErrTooManyAllow = fmt.Errorf("at most %d values may go unmasked", MaxAllow)
)

What is wrong with a rule, besides a pattern RE2 can't compile; and with too many rules or allowed values.

Functions

func Category

func Category(kind string) string

Category is the category of a built-in kind; "" for the user's own.

func Check

func Check(c Config, kept ...Rule) error

Check says what is wrong with c, if anything: a rule's pattern that does not compile or matches empty text, a kind a placeholder can't name or that is a built-in one's (or TermKind), too many rules or allowed values. A rule in kept, saved before built-in kinds were refused, may keep one.

func Premasked

func Premasked(ctx context.Context) context.Context

Premasked says ctx's requests carry text Godwit masked itself (RequestTexts), cut into pieces after: its placeholders are not defused at the egress.

func Tag

func Tag(ctx context.Context, feature string, found *Found) context.Context

Tag says ctx's requests are for feature (总结, Wit …), as Record is told, and gathers what they find in found too, if set.

Types

type BlockedError

type BlockedError struct{ Categories []string }

BlockedError refuses a request that holds values of Categories, each set to Block: nothing of it is sent.

func (*BlockedError) Error

func (e *BlockedError) Error() string

type Config

type Config struct {
	Off                   []string
	Actions               map[string]string
	Words                 []string
	WordsCase, WordsWhole bool
	Rules                 []Rule
	Allow                 []string
	Recognizer            Recognizer
}

Config is what the user set: the categories turned Off; what is done with each category's values (Actions: Warn or Block, else Mask); their Words, matched in any case unless WordsCase, inside other words unless WordsWhole; their Rules; the values never masked (Allow, in any case); and 识别模型, if on (Recognizer).

type Found

type Found struct {
	// contains filtered or unexported fields
}

Found gathers hits, each value once for each action, in the order they were found. Safe for concurrent use; a nil Found gathers nothing.

func (*Found) Count

func (f *Found) Count(action string) int

Count is how many of f's values had action.

func (*Found) Hits

func (f *Found) Hits() []Hit

Hits is what f gathered.

type Hit

type Hit struct {
	Kind, Category, First string
	Len                   int
	Action, Source        string
	// contains filtered or unexported fields
}

Hit is a value masking found in a request, as it is recorded (脱敏记录): its kind and category, its first character and its length in characters, never the value itself; Action, what was done with it; and Source, what found it.

type Masker

type Masker struct {

	// Record, if set, is told what each Request found, with the feature
	// its context is Tagged with. Set it before the first Request.
	Record func(feature string, hits []Hit)
	// contains filtered or unexported fields
}

Masker masks text and restores it, with one table of the placeholders it made, kept in memory only: after a restart, masking the stored values again (Learn) fills it back. Safe for concurrent use; a nil Masker restores nothing.

func New

func New(key []byte) *Masker

New is a masker with key, the device's secret, on.

func (*Masker) Body

func (m *Masker) Body(body string) (string, error)

Body masks a model service's JSON request body, in any of the protocols pi speaks and the judge formats: only string values, and of those not the ids, names and kinds the service matches or reads as structure, nor what it sealed (signed thinking, encrypted reasoning: it goes back as the service wrote it). Of the tools, only their descriptions are masked. A string holding JSON of its own (a tool's arguments or result) is masked as that JSON, so values are found in its text as the model reads it. What has nothing to mask comes back byte for byte; a body that isn't JSON is masked as text. A category set to Block fails it (*BlockedError, naming each category that did); one set to Warn goes as it is.

func (*Masker) Configure

func (m *Masker) Configure(c Config) error

Configure masks as c says from the next text on, names too unless they are Off (SetNames); a c Check refuses leaves the masker as it was.

func (*Masker) Cut

func (m *Masker) Cut(text string) int

Cut is where text, a stream so far, may end in a placeholder the next chunk finishes; len(text) when it does not.

func (*Masker) DropCut

func (m *Masker) DropCut(text string) string

DropCut is text without the placeholder its end cut short: one in braces the model was still writing when the stream ended, which names no value. A last word without braces stays: API_KEY or PHONE_NUMBER is as likely the reply's own.

func (*Masker) Learn

func (m *Masker) Learn(text string)

Learn masks text, a stored request's or message's (JSON or not), for the placeholders alone: the values it holds restore again after a restart. A text learned before is not read again. shortcut: learned keeps a hash per text for good; a bounded cache if it is seen to matter.

func (*Masker) Left

func (m *Masker) Left(s string) bool

Left says s, about to be mailed, still holds a placeholder (its braces percent-encoded too): one in braces, or a bare one of a kind a rule, a word or the user's rules mask. Sending it would mail the placeholder, not the value.

func (*Masker) On

func (m *Masker) On() bool

On says whether what is sent is to be masked (the switch, 总开关): the callers that send ask it. Restoring goes on either way.

func (*Masker) Request

func (m *Masker) Request(ctx context.Context, body string) (string, error)

Request masks body, one request to a service off this device, as Body does, and records what it found (Record, and ctx's Found): a request that is blocked too.

func (*Masker) RequestTexts

func (m *Masker) RequestTexts(ctx context.Context, texts []string) ([]string, error)

RequestTexts masks texts, one request's, as Text does each, and records what they held as Request does.

func (*Masker) Restore

func (m *Masker) Restore(s string) string

Restore puts back the value of each placeholder in s this masker made, however the model wrote it; others are left as they are.

func (*Masker) RestoreArgs

func (m *Masker) RestoreArgs(args json.RawMessage) (out json.RawMessage, err error)

RestoreArgs is a tool call's JSON arguments with the placeholders in its strings restored. err, when one is left that names no value, refuses the call; out is still all that could be restored, for showing it.

func (*Masker) RestoreHTML

func (m *Masker) RestoreHTML(s string) string

RestoreHTML is Restore for HTML, a draft's body: each value is escaped, and a placeholder whose braces are percent-encoded, as sanitizing leaves one in an href, restores too.

func (*Masker) SetNames

func (m *Masker) SetNames(on bool)

SetNames turns the masking of names on or off. Off, names are neither learned nor masked; their placeholders still restore.

func (*Masker) SetOn

func (m *Masker) SetOn(on bool)

SetOn turns masking on or off.

func (*Masker) Text

func (m *Masker) Text(s string) (string, error)

Text masks the values found in s, text Godwit wrote: a placeholder in it (planted in mail) is defused first. A category set to Block fails it (*BlockedError); one set to Warn goes as it is.

type Recognized added in v1.21.0

type Recognized struct {
	Start, End int
	Label      string
	Score      float64
}

Recognized is a value a Recognizer found: text[Start:End], its Label and its Score, from 0 to 1.

type Recognizer added in v1.21.0

type Recognizer interface {
	Recognize(text string) ([]Recognized, error)
}

Recognizer is 识别模型 (docs/adr/0028-recognition-model-for-masking.md): the values it finds in a text, each under AstrLink Guard's label for it.

type Rule

type Rule struct{ Kind, Regex string }

Rule is one of the user's (自定义正则): Regex, in RE2 syntax, finds values of Kind, its first group that matched if it has one, else all it matches.

type RuleError

type RuleError struct {
	Index int
	Kind  string
	Err   error
}

RuleError says why the user's rule at Index can't be used.

func (*RuleError) Error

func (e *RuleError) Error() string

func (*RuleError) Unwrap

func (e *RuleError) Unwrap() error

Directories

Path Synopsis
Package guard runs AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0), a token classifier for secrets and personal data in Chinese and English text: its int8 ONNX model (37 MB) read by onnx.go and run by bert.go on the CPU in pure Go, or on a Mac by CoreML through a Swift bridge loaded with purego (coreml.go), its tokenizer by tokenizer.go.
Package guard runs AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0), a token classifier for secrets and personal data in Chinese and English text: its int8 ONNX model (37 MB) read by onnx.go and run by bert.go on the CPU in pure Go, or on a Mac by CoreML through a Swift bridge loaded with purego (coreml.go), its tokenizer by tokenizer.go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL