blindfold

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 22 Imported by: 0

README

Blindfold Go SDK

Official Go SDK for the Blindfold PII detection and anonymization API.

Installation

go get github.com/blindfold-dev/Blindfold/packages/go-sdk

Zero external dependencies — uses only the Go standard library.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    blindfold "github.com/blindfold-dev/Blindfold/packages/go-sdk"
)

func main() {
    // API mode
    client := blindfold.New(blindfold.WithAPIKey("your-api-key"))

    // Local mode (no API key needed)
    client = blindfold.New()

    ctx := context.Background()

    // Detect PII
    result, err := client.Detect(ctx, "Contact [email protected] or call 555-123-4567")
    if err != nil {
        log.Fatal(err)
    }
    for _, entity := range result.DetectedEntities {
        fmt.Printf("%s: %s (score: %.2f)\n", entity.Type, entity.Text, entity.Score)
    }
}

Usage

Client Configuration
// Full configuration
client := blindfold.New(
    blindfold.WithAPIKey("your-api-key"),
    blindfold.WithRegion("eu"),          // "eu" (default) or "us"
    blindfold.WithLocales([]string{"us", "eu"}),
    blindfold.WithMaxRetries(3),
    blindfold.WithTimeout(30 * time.Second),
    blindfold.WithPolicy("gdpr_eu"),
    blindfold.WithUserID("user-123"),
)
Detect
result, _ := client.Detect(ctx, text)
result, _ := client.Detect(ctx, text, blindfold.WithEntities([]string{"Email Address", "Phone Number"}))
result, _ := client.Detect(ctx, text, blindfold.WithCallPolicy("gdpr_eu"))
Tokenize
result, _ := client.Tokenize(ctx, "Email: [email protected]")
// result.Text: "Email: <Email Address_1>"
// result.Mapping: {"<Email Address_1>": "[email protected]"}
Detokenize
result := client.Detokenize(tokenizedText, mapping)
// result.Text: original text restored
Redact
result, _ := client.Redact(ctx, "Email: [email protected]")
// result.Text: "Email:"
Mask
result, _ := client.Mask(ctx, "SSN: 123-45-6789",
    blindfold.WithCharsToShow(4),
    blindfold.WithFromEnd(true),
    blindfold.WithMaskingChar("*"),
)
// result.Text: "SSN: *****-6789"
Hash
result, _ := client.Hash(ctx, "Email: [email protected]",
    blindfold.WithHashType("SHA-256"),
    blindfold.WithHashPrefix("HASH_"),
    blindfold.WithHashLength(16),
)
Encrypt
result, _ := client.Encrypt(ctx, "Email: [email protected]", "my-encryption-key-16char")
Synthesize
result, _ := client.Synthesize(ctx, "Email: [email protected]")
// result.Text: "Email: [email protected]"
Batch Operations
texts := []string{"Email: [email protected]", "SSN: 123-45-6789"}
results, _ := client.DetectBatch(ctx, texts, blindfold.WithCallPolicy("gdpr_eu"))

Policies

Built-in policies: basic, gdpr_eu, hipaa_us, pci_dss, strict.

// Use a policy
result, _ := client.Detect(ctx, text, blindfold.WithCallPolicy("gdpr_eu"))

// Load custom policies
client := blindfold.New(blindfold.WithPoliciesFile("custom-policies.json"))

Local Mode

When no API key is provided, or WithMode("local") is set, the SDK runs entirely locally using 86 regex-based detectors covering 80+ entity types across 30+ countries.

client := blindfold.New()  // local-only, zero network calls
result, _ := client.Detect(ctx, "My email is [email protected]")

Supported Entity Types

80+ entity types including:

  • Universal: Email, Credit Card, Phone, IP Address, URL, MAC Address, Date of Birth, CVV
  • US: SSN, Driver's License, Passport, Tax ID, ZIP Code, ITIN
  • UK: NI Number, NHS Number, Postcode, Passport, UTR
  • EU: IBAN, Postal Code, VAT ID
  • Germany: Personal ID, Tax ID
  • France: National ID (NIR), SIREN
  • Spain: DNI, NIE, NSS, CIF
  • Italy: Codice Fiscale, Partita IVA
  • And 50+ more across Nordics, Benelux, Eastern Europe, Baltics, Americas, and Asia-Pacific

Error Handling

result, err := client.Detect(ctx, text)
if err != nil {
    var authErr *blindfold.AuthenticationError
    var apiErr *blindfold.APIError
    var netErr *blindfold.NetworkError

    switch {
    case errors.As(err, &authErr):
        // Invalid API key
    case errors.As(err, &apiErr):
        // API error with status code
    case errors.As(err, &netErr):
        // Network error
    }
}

License

MIT

Documentation

Index

Constants

View Source
const (
	// Universal
	EntityEmailAddress = "Email Address"
	EntityCreditCard   = "Credit Card Number"
	EntityPhoneNumber  = "Phone Number"
	EntityIPAddress    = "IP Address"
	EntityURL          = "URL"
	EntityMACAddress   = "MAC Address"
	EntityDateOfBirth  = "Date of Birth"
	EntityCVV          = "CVV"

	// US
	EntitySSN            = "Social Security Number"
	EntityDriversLicense = "Driver's License"
	EntityUSPassport     = "US Passport"
	EntityTaxID          = "Tax ID"
	EntityZIPCode        = "ZIP Code"
	EntityUSITIN         = "US ITIN"

	// EU
	EntityIBAN       = "IBAN"
	EntityPostalCode = "Postal Code"
	EntityVATID      = "VAT ID"

	// UK
	EntityNINumber   = "NI Number"
	EntityNHSNumber  = "NHS Number"
	EntityUKPostcode = "UK Postcode"
	EntityUKPassport = "UK Passport"
	EntityUKUTR      = "UK UTR"

	// Germany
	EntityDEPersonalID = "German Personal ID"
	EntityDETaxID      = "German Tax ID"

	// France
	EntityFRNationalID = "French National ID"
	EntityFRSIREN      = "French SIREN"

	// Spain
	EntityESDNI = "Spanish DNI"
	EntityESNIE = "Spanish NIE"
	EntityESNSS = "Spanish NSS"
	EntityESCIF = "Spanish CIF"

	// Italy
	EntityITCodiceFiscale = "Italian Codice Fiscale"
	EntityITPartitaIVA    = "Italian Partita IVA"

	// Portugal
	EntityPTNIF = "Portuguese NIF"

	// Poland
	EntityPLPESEL = "Polish PESEL"
	EntityPLNIP   = "Polish NIP"
	EntityPLREGON = "Polish REGON"

	// Czech Republic
	EntityCZBirthNumber = "Czech Birth Number"
	EntityCZICO         = "Czech ICO"
	EntityCZDIC         = "Czech DIC"
	EntityCZBankAccount = "Czech Bank Account"

	// Russia
	EntityRUINN   = "Russian INN"
	EntityRUSNILS = "Russian SNILS"

	// Netherlands
	EntityNLBSN = "Dutch BSN"

	// Romania
	EntityROCNP = "Romanian CNP"
	EntityROCUI = "Romanian CUI"

	// Slovakia
	EntitySKBirthNumber = "Slovak Birth Number"
	EntitySKICO         = "Slovak ICO"
	EntitySKDIC         = "Slovak DIC"

	// Denmark
	EntityDKCPR = "Danish CPR"
	EntityDKCVR = "Danish CVR"

	// Sweden
	EntitySEPersonnummer = "Swedish Personnummer"
	EntitySEOrgnr        = "Swedish Organisationsnummer"

	// Norway
	EntityNOBirthNumber = "Norwegian Birth Number"
	EntityNOOrgnr       = "Norwegian Organisasjonsnummer"

	// Belgium
	EntityBENational   = "Belgian National Number"
	EntityBEEnterprise = "Belgian Enterprise Number"

	// Austria
	EntityATSVNR = "Austrian SVNR"

	// Ireland
	EntityIEPPS = "Irish PPS Number"

	// Finland
	EntityFIHETU    = "Finnish HETU"
	EntityFIYtunnus = "Finnish Y-tunnus"

	// Hungary
	EntityHUTaxID = "Hungarian Tax ID"
	EntityHUTAJ   = "Hungarian TAJ"

	// Bulgaria
	EntityBGEGN = "Bulgarian EGN"

	// Croatia
	EntityHROIB = "Croatian OIB"

	// Slovenia
	EntitySIEMSO      = "Slovenian EMSO"
	EntitySITaxNumber = "Slovenian Tax Number"

	// Lithuania
	EntityLTPersonalCode = "Lithuanian Personal Code"

	// Latvia
	EntityLVPersonalCode = "Latvian Personal Code"

	// Estonia
	EntityEEPersonalCode = "Estonian Personal Code"

	// Canada
	EntityCASIN = "Canadian SIN"

	// Switzerland
	EntityCHAHV = "Swiss AHV"

	// Australia
	EntityAUTFN      = "Australian TFN"
	EntityAUMedicare = "Australian Medicare"

	// New Zealand
	EntityNZIRD = "New Zealand IRD"

	// India
	EntityINAadhaar = "Indian Aadhaar"
	EntityINPAN     = "Indian PAN"

	// Japan
	EntityJPMyNumber = "Japanese My Number"

	// South Korea
	EntityKRRRN = "Korean RRN"

	// South Africa
	EntityZAID = "South African ID"

	// Turkey
	EntityTRKimlik = "Turkish Kimlik"

	// Israel
	EntityILID = "Israeli ID"

	// Argentina
	EntityARCUIT = "Argentine CUIT"

	// Chile
	EntityCLRUT = "Chilean RUT"

	// Colombia
	EntityCONIT = "Colombian NIT"

	// Brazil
	EntityBRCPF  = "Brazilian CPF"
	EntityBRCNPJ = "Brazilian CNPJ"
)

Entity type constants matching the API's Title Case format.

Variables

This section is empty.

Functions

func RegisterRegion

func RegisterRegion(locale string, factory detectorFactory)

RegisterRegion registers a detector factory for a specific locale.

func RegisterUniversal

func RegisterUniversal(factory detectorFactory)

RegisterUniversal registers a detector factory that applies to all locales.

func SynthesizeValue

func SynthesizeValue(entityType, originalText string) string

SynthesizeValue generates a fake replacement for the given entity type.

Types

type APIError

type APIError struct {
	BlindfoldError
}

APIError indicates a non-retryable API error.

type AuthenticationError

type AuthenticationError struct {
	BlindfoldError
}

AuthenticationError indicates an invalid API key (401).

type BatchResponse

type BatchResponse[T any] struct {
	Results   []T `json:"results"`
	Total     int `json:"total"`
	Succeeded int `json:"succeeded"`
	Failed    int `json:"failed"`
}

BatchResponse wraps batch results for any operation type.

type BlindfoldError

type BlindfoldError struct {
	Message    string
	StatusCode int
	Err        error
}

BlindfoldError is the base error type for all SDK errors.

func (*BlindfoldError) Error

func (e *BlindfoldError) Error() string

func (*BlindfoldError) Unwrap

func (e *BlindfoldError) Unwrap() error

type CallOption

type CallOption func(*callConfig)

CallOption configures a single method call.

func WithCallPolicy

func WithCallPolicy(policy string) CallOption

WithCallPolicy sets the policy for this call.

func WithCharsToShow

func WithCharsToShow(n int) CallOption

WithCharsToShow sets how many characters remain visible when masking.

func WithEntities

func WithEntities(entities []string) CallOption

WithEntities filters detection to specific entity types.

func WithFromEnd

func WithFromEnd(b bool) CallOption

WithFromEnd shows characters from the end when masking.

func WithHashLength

func WithHashLength(n int) CallOption

WithHashLength sets the length of the hash output.

func WithHashPrefix

func WithHashPrefix(p string) CallOption

WithHashPrefix sets the prefix for hashed replacements.

func WithHashType

func WithHashType(t string) CallOption

WithHashType sets the hash algorithm (e.g., "SHA-256").

func WithLanguage

func WithLanguage(lang string) CallOption

WithLanguage sets the language for synthesize.

func WithMaskingChar

func WithMaskingChar(ch string) CallOption

WithMaskingChar sets the masking character.

type Client

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

Client is the Blindfold PII detection client.

func New

func New(opts ...Option) *Client

New creates a new Blindfold client with the given options.

func (*Client) Detect

func (c *Client) Detect(ctx context.Context, text string, opts ...CallOption) (*DetectResponse, error)

Detect finds PII entities in text.

func (*Client) DetectBatch

func (c *Client) DetectBatch(ctx context.Context, texts []string, opts ...CallOption) (*BatchResponse[DetectResponse], error)

DetectBatch runs detect on multiple texts.

func (*Client) Detokenize

func (c *Client) Detokenize(text string, mapping map[string]string) *DetokenizeResponse

Detokenize restores tokenized text using a mapping. This is client-side only.

func (*Client) Encrypt

func (c *Client) Encrypt(ctx context.Context, text, encryptionKey string, opts ...CallOption) (*EncryptResponse, error)

Encrypt replaces PII with AES-encrypted values.

func (*Client) Hash

func (c *Client) Hash(ctx context.Context, text string, opts ...CallOption) (*HashResponse, error)

Hash replaces PII with hash values.

func (*Client) Mask

func (c *Client) Mask(ctx context.Context, text string, opts ...CallOption) (*MaskResponse, error)

Mask partially hides PII in text.

func (*Client) Redact

func (c *Client) Redact(ctx context.Context, text string, opts ...CallOption) (*RedactResponse, error)

Redact removes PII from text.

func (*Client) Synthesize

func (c *Client) Synthesize(ctx context.Context, text string, opts ...CallOption) (*SynthesizeResponse, error)

Synthesize replaces PII with realistic fake data.

func (*Client) Tokenize

func (c *Client) Tokenize(ctx context.Context, text string, opts ...CallOption) (*TokenizeResponse, error)

Tokenize replaces PII with tokens and returns a mapping.

func (*Client) TokenizeBatch

func (c *Client) TokenizeBatch(ctx context.Context, texts []string, opts ...CallOption) (*BatchResponse[TokenizeResponse], error)

TokenizeBatch runs tokenize on multiple texts.

type DetectResponse

type DetectResponse struct {
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

DetectResponse is the result of a detect operation.

type DetectedEntity

type DetectedEntity struct {
	Type  string  `json:"type"`
	Text  string  `json:"text"`
	Start int     `json:"start"`
	End   int     `json:"end"`
	Score float64 `json:"score"`
}

DetectedEntity represents a single PII entity found in text.

type Detector

type Detector interface {
	EntityType() string
	NeedsDigit() bool
	IterMatches(text, textLower string) []PIIMatch
}

Detector is the interface for all PII detectors.

type DetectorRegistry

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

DetectorRegistry builds the detector list for given locales.

func NewDetectorRegistry

func NewDetectorRegistry(locales []string) *DetectorRegistry

NewDetectorRegistry creates a registry with detectors for the given locales.

func (*DetectorRegistry) Detectors

func (r *DetectorRegistry) Detectors() []Detector

Detectors returns all registered detectors.

type DetokenizeResponse

type DetokenizeResponse struct {
	Text             string `json:"text"`
	ReplacementsMade int    `json:"replacements_made"`
}

DetokenizeResponse is the result of a detokenize operation.

type EncryptResponse

type EncryptResponse struct {
	Text             string           `json:"text"`
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

EncryptResponse is the result of an encrypt operation.

type HashResponse

type HashResponse struct {
	Text             string           `json:"text"`
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

HashResponse is the result of a hash operation.

type MaskResponse

type MaskResponse struct {
	Text             string           `json:"text"`
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

MaskResponse is the result of a mask operation.

type NetworkError

type NetworkError struct {
	BlindfoldError
}

NetworkError indicates a network-level failure.

type Option

type Option func(*config)

Option configures the Client at construction time.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key for authenticated requests.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the default API endpoint.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient provides a custom http.Client.

func WithLocales

func WithLocales(locales []string) Option

WithLocales sets the locale list for detector selection (e.g., "us", "eu", "uk").

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retry attempts.

func WithMode

func WithMode(mode string) Option

WithMode sets the operating mode ("local" or "api").

func WithPoliciesFile

func WithPoliciesFile(path string) Option

WithPoliciesFile loads additional policies from a JSON file.

func WithPolicy

func WithPolicy(name string) Option

WithPolicy sets the default policy name.

func WithRegion

func WithRegion(region string) Option

WithRegion sets the API region ("eu" or "us").

func WithRetryDelay

func WithRetryDelay(d time.Duration) Option

WithRetryDelay sets the base delay between retries.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP request timeout.

func WithUserID

func WithUserID(id string) Option

WithUserID sets the X-Blindfold-User-Id header.

type PIIMatch

type PIIMatch struct {
	EntityType string
	Text       string
	Start      int
	End        int
	Score      float64
}

PIIMatch represents a single detected PII entity.

type PIIScanner

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

PIIScanner performs local PII detection and transformation.

func NewPIIScanner

func NewPIIScanner(locales []string) *PIIScanner

NewPIIScanner creates a scanner with detectors for the given locales.

func (*PIIScanner) Detect

func (s *PIIScanner) Detect(text string, entities []string) []PIIMatch

Detect finds PII in text, optionally filtered to specific entities.

func (*PIIScanner) Detokenize

func (s *PIIScanner) Detokenize(text string, mapping map[string]string) string

Detokenize restores tokenized text using a mapping.

func (*PIIScanner) Encrypt

func (s *PIIScanner) Encrypt(text, encryptionKey string, entities []string) (TextResult, error)

Encrypt replaces PII with AES-CBC encrypted values.

func (*PIIScanner) Hash

func (s *PIIScanner) Hash(text, hashType, hashPrefix string, hashLength int, entities []string) TextResult

Hash replaces PII with hash values.

func (*PIIScanner) Mask

func (s *PIIScanner) Mask(text string, charsToShow int, fromEnd bool, maskingChar string, entities []string) TextResult

Mask partially hides PII in text.

func (*PIIScanner) Redact

func (s *PIIScanner) Redact(text string, entities []string) TextResult

Redact removes PII from text.

func (*PIIScanner) Synthesize

func (s *PIIScanner) Synthesize(text, language string, entities []string) TextResult

Synthesize replaces PII with realistic fake data.

func (*PIIScanner) Tokenize

func (s *PIIScanner) Tokenize(text string, entities []string) TokenizeResult

Tokenize replaces PII with tokens like <Entity Type_1>.

type RedactResponse

type RedactResponse struct {
	Text             string           `json:"text"`
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

RedactResponse is the result of a redact operation.

type RegexDetector

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

RegexDetector is a configurable regex-based detector.

func NewRegexDetector

func NewRegexDetector(cfg RegexDetectorConfig) *RegexDetector

NewRegexDetector creates a RegexDetector from config.

func (*RegexDetector) EntityType

func (d *RegexDetector) EntityType() string

func (*RegexDetector) IterMatches

func (d *RegexDetector) IterMatches(text, textLower string) []PIIMatch

func (*RegexDetector) NeedsDigit

func (d *RegexDetector) NeedsDigit() bool

type RegexDetectorConfig

type RegexDetectorConfig struct {
	EntityType      string
	Pattern         *regexp.Regexp
	Score           float64
	BaseScore       *float64
	NeedsDigit      bool
	ContextRequired bool
	ContextKeywords []string
	ContextWindow   int
	Validator       func(string) bool
	PreCheck        func(string) bool
}

RegexDetectorConfig holds configuration for building a RegexDetector.

type SynthesizeResponse

type SynthesizeResponse struct {
	Text             string           `json:"text"`
	DetectedEntities []DetectedEntity `json:"detected_entities"`
	EntitiesCount    int              `json:"entities_count"`
}

SynthesizeResponse is the result of a synthesize operation.

type TextResult

type TextResult struct {
	Text    string
	Matches []PIIMatch
}

TextResult holds results with transformed text.

type TokenizeResponse

type TokenizeResponse struct {
	Text             string            `json:"text"`
	Mapping          map[string]string `json:"mapping"`
	DetectedEntities []DetectedEntity  `json:"detected_entities"`
	EntitiesCount    int               `json:"entities_count"`
}

TokenizeResponse is the result of a tokenize operation.

type TokenizeResult

type TokenizeResult struct {
	Text    string
	Mapping map[string]string
	Matches []PIIMatch
}

TokenizeResult holds tokenization output.

Jump to

Keyboard shortcuts

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