A client-side PII redactor still ships its detection patterns

Iniciado por joomlamz, Hoje at 03:25

Respostas: 1   |   Visualizações: 4

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações a toda a comunidade de webmasters e profissionais de TI em Moçambique.

Analisei o tópico sobre a implementação de redatores de PII (Informação Pessoal Identificável) que, por serem baseados no lado do cliente (*client-side*), acabam por expor os seus padrões de deteção no código-fonte. Este é um tema crítico para quem gere aplicações que lidam com dados sensíveis.

### Análise Técnica: O Problema da Segurança no Client-Side

O ponto central da discussão é a **falsa sensação de segurança** ao tentar ocultar PII através de JavaScript no lado do cliente. Se o redator de PII envia os padrões de deteção (como expressões regulares ou lógica de validação) para o navegador do utilizador, qualquer pessoa com acesso às ferramentas de desenvolvimento (*DevTools*) pode facilmente realizar engenharia reversa e descobrir como o sistema identifica os dados.

Os pontos principais a considerar são:

1.  **Exposição de Lógica:** Ao enviar padrões de deteção para o cliente, estamos, na prática, a fornecer o "mapa" de como o nosso sistema processa dados sensíveis. Se um atacante souber como o redator deteta um número de cartão de crédito ou uma identificação nacional, ele pode manipular os dados de entrada para contornar a segurança ou extrair informações que não deveriam estar expostas.
2.  **Segurança por Obscuridade:** Tentar esconder lógica no JavaScript não é uma medida de segurança robusta. A regra de ouro é: **nunca confie no cliente**. Qualquer processamento crítico que envolva PII deve ocorrer no lado do servidor (*server-side*), onde o código é executado num ambiente controlado e inacessível ao utilizador final.
3.  **Complexidade na Manutenção:** Manter atualizações constantes de padrões de deteção no lado do cliente obriga a *deploys* frequentes e aumenta a superfície de ataque sempre que uma nova biblioteca ou script é injetado.

**Como podemos debater isto melhor no [webmastersmz.com](https://webmastersmz.com)?**
Sugiro que levemos esta discussão para o nosso fórum focando nos seguintes pontos:
*   Como têm implementado a sanitização de dados nos vossos projetos web?
*   Alguém aqui já teve experiências com bibliotecas de redação *open source* que permitem processamento híbrido (cliente/servidor)?
*   Quais são as melhores práticas que adotam para garantir que dados sensíveis não cheguem ao *browser* do utilizador?

Convido todos os membros do fórum a partilharem os seus casos de estudo e desafios técnicos. A segurança dos nossos utilizadores é a nossa prioridade número um.

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

A client-side PII redactor still ships its detection patterns



Tópico: A client-side PII redactor still ships its detection patterns
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
Privacy tooling often ships a "redact before you paste" widget: drop in a log, a support ticket, or a CSV, and the page blacks out emails, phone numbers, card PANs, and medical IDs. When that detector runs entirely in the browser, the patterns, checksums, and exception lists that make it accurate are in the JavaScript bundle.

That is convenient for "your data never leaves the device". It is also a map of what you catch — and, just as useful to an attacker, what you do not.



What actually ships


A typical client-side redactor includes:

•
Detectors — regexes and checksums for email, phone, IBAN, national IDs, and Luhn-checked card numbers, including the formats you added for one customer.

•
Context rules — "this looks like a date, not a PAN", or "skip anything after example.com".

•
Replacement policies — mask vs. hash vs. drop, and the stable-tokenization scheme you use so the same email always becomes the same token.

•
Custom dictionaries — employee names, project codenames, and internal hostnames a tenant uploaded... if you bundled them into the page.

•
Confidence thresholds — the cutoffs that decide whether a match is painted red or left alone.

If the token scheme is reversible, or the dictionary is a tenant's employee list, you have a bigger problem than a copied regex.



How it gets lifted


People search the bundle for luhn, iban, redact, or a test string like a fake PAN.

const PATTERNS = {
email: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,
pan: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})\b/g,
phone: /\+?[0-9]{1,3}[\s.-]?\(?[0-9]{3}\)?[\s.-]?[0-9]{3}[\s.-]?[0-9]{4}/g,
};

export function redact(text, policy) {
let out = text;
for (const [kind, re] of Object.entries(PATTERNS)) {
out = out.replace(re, (m) =>
luhnOk(m) || kind !== "pan" ? tokenOrMask(m, kind, policy) : m
);
}
return applyDictionary(out, policy.names); // sometimes a tenant list
}

A competitor now has your detectors and your tokenization idea. A malicious insider who wants data to slip through a "client-only" pipeline can hook redact and return the original string, or study the patterns to write values your regex will miss — then send that "redacted" file to a vendor.



What actually protects you




Be honest about the trust boundary


•
"Never leaves the device" is a real product. In that mode, tell users the detector is local and therefore inspectable, and keep tenant dictionaries in memory from a file they chose, not from your CDN.

•
Pipelines that feed a vendor, a ticket system, or your own backend need a second, authoritative pass on a server you control. The browser pass is a preview.

•
Stable tokens that must not be reversible belong in a server-side vault, not in a client hash with a shipped salt.



Protect the detector you still ship


Offline preview still needs a local engine. For that chunk:

• Bundle detectors separately from the form UI.

• Apply stronger-than-mangling protection (control-flow flattening or VM-based compilation) to checksums, pattern packs, and tokenization.

• Do not embed tenant name lists in a public bundle; load them from a user-selected file or an authenticated, short-lived blob.

• Leave source maps off the public CDN.

• Add a few harmless canary patterns so a copied pack is recognizable.



Do not treat the client as a compliance control


If a ticket is accepted because the widget returned "0 PII matches", anyone can hook the function. Compliance logs should record a server-side scan, or an explicit user attestation, not a boolean from the page.



Practical checklist


• [ ] Any file that leaves the device is scanned again on a server, not only in the widget.

• [ ] Tenant dictionaries and name lists are not baked into the public JavaScript.

• [ ] Tokenization that must be irreversible and consistent is not keyed by a shipped salt.

• [ ] The detector chunk is split from the UI and protected with stronger-than-Terser obfuscation.

• [ ] Source maps for the detector are not on the public CDN.

• [ ] Hooking redact cannot mark a dirty file as clean for a downstream system you control.

• [ ] Users of a true on-device mode are told the rules are inspectable.

• [ ] Canary patterns exist so a lifted pack can be recognized.



Honest limits


Regex-based PII detection is always incomplete, even on a server. Obfuscation does not fix missed formats; it only slows copying of the pack you do ship. If a pattern or a tenant list cannot be public, it cannot live in JavaScript you send to every browser.



Summary


A client-side redactor ships the work that makes it useful: the detectors, the exceptions, and sometimes the dictionaries. Use it as a preview, protect that chunk, and never let a hooked redact function be the only control that keeps personal data out of a ticket or a vendor feed.

Disclosure: I work on VEILVM, a JavaScript VM-protection service. Free browser tier (3 runs/day, up to 5 KB) and a Pro plan at $9/month or $79/year with API access. Try the playground at vm.ldvmp.com.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: