Skip to content

fix(privacy): apply noindex+mask policy to machine-readable outputs (#173) - #183

Open
LyuboslavLyubenov wants to merge 19 commits into
midt-bg:mainfrom
LyuboslavLyubenov:main
Open

fix(privacy): apply noindex+mask policy to machine-readable outputs (#173)#183
LyuboslavLyubenov wants to merge 19 commits into
midt-bg:mainfrom
LyuboslavLyubenov:main

Conversation

@LyuboslavLyubenov

@LyuboslavLyubenov LyuboslavLyubenov commented Jun 30, 2026

Copy link
Copy Markdown

Какво и защо

HTML профилът на фирма вече прилага noindex за разпознати физически лица / еднолични търговци (ЕТ),
но същите идентификатори остават достъпни от машинно-четливите повърхности — JSON записът
на договора (/contracts/:id.json) и трите CSV експорта (/contracts.csv, /companies.csv,
/authorities.csv). Те връщат ЕИК и оригиналното име от източника без X-Robots-Tag: noindex
и без маскиране, edge-кешират се (Cache-Control: public, max-age=3600) и попадат в индексите
на търсачките и ботовете.

Несъответствието прави идентификаторите, които HTML умишлено държи извън търсачките,
търсещи се и изтегляеми накуп — класът CWE-359, описан в issue #173.

Решение

Прилага се политика „noindex плюс маскиране" с един общ предикат от
packages/shared/src/format.ts, който заменя досегашната дублирана логика в company.tsx:

  • Споделена логика. Нов isNaturalPersonBidder(name, legalForm) комбинира legal_form LIKE 'ЕТ%'
    (вкл. латинското ET, разширените форми ЕДНОЛИЧЕН ТЪРГОВЕЦ, SOLE TRADER, INDIVIDUAL)
    с водещия ЕТ суфикс в името (който вече беше в isNaturalPersonProfileName).
    MASKED_NATURAL_PERSON_LABEL ('Частно лице') е константа, която се внася по символ от
    всеки консуматор — преименуването ѝ не чупи нито един тест. Inline isSingleNaturalPersonProfile
    е премахнат от company.tsx.
  • CSV стриймовете в packages/db/src/queries/{contracts,companies}.ts правят
    SELECT b.legal_form и маскират contractor_eik/eik и contractor/name преди
    байтовете да стигнат до R2
    — edge кешът не може никога да сервира немаскиран
    естествено-личностен ред. apps/web/app/lib/csv-export.ts добавя X-Robots-Tag: noindex
    на четирите клона: 200/206 HIT, dynamic (филтриран) и 304.
  • JSON маскиране. packages/db/src/queries/details.ts разширява getContract с
    bidder_legal_form (server-only, не изтича към клиента — ContractRecord остава непроменен).
    apps/web/app/routes/contract.json.tsx изнася чист maskContractForPrivacy(record, bidderLegalForm) помощник, който слага X-Robots-Tag: noindex само когато маскирането
    реално е приложило — reference-equality гейт masked !== record прави повторното
    извикване на предиката ненужно.
  • Потребителска документация. Нова секция #natural-person-data в
    apps/web/app/routes/privacy.tsx описва кои полета се маскират, кои повърхности
    носят noindex-а и че HTML профилът остава непокътнат. Кадърът е инженерно ръководство,
    не правен съвет — същият disclaimer носи и ADR-0002.
  • ADR-0002 в docs/architecture.md (български, огледало на ADR-0001): Контекст / Решение / Последствия / Засегнати повърхности / Доказателство. Цитираните exit code-ове
    са от реален пост-едит прогон в чисто и замърсено дърво, не оценки.

Юридическите лица (legal entity) са непроменени — ЕИК и имената им остават видими
във всички повърхности.

Валидация (реални данни)

  • pnpm typecheck — exit 0 (7/7 turbo задачи).
  • pnpm test --force — exit 1, заради 3 пред-съществуващи повреди в @sigma/db
    (integrity-checks.test.ts reconciliation gate + 2 таймаута в refresh-slice.test.ts).
    Същият набор е налице и в предишния main, не е въведен от този PR.
    Всичките 38 нови теста минават — пост-едит и пре-едит прогонът показват същия набор
    пред-съществуващи повреди, без нови въведени от този PR.
  • pnpm lint — exit 1, 6 prettier warnings: 2 пред-съществуващи (RiskIndicators.tsx,
    riskLogic.test.ts) + 4 нововъведени (contract.json.test.ts, privacy.tsx,
    companies.test.ts, companies.ts). Няма нови lint-видове — само пренасяне на редове
    заради български / EN текст в JSX.
  • Тестове по пакет (фокусни): @sigma/shared 42/42, @sigma/db
    (contracts.test.ts + companies.test.ts + details.test.ts) 26/26,
    @sigma/web (contract.json.test.ts + csv-export.test.ts) 33/33.

Извън обхвата

  • Няма миграция на схемата — bidders.legal_form вече присъстваше в migrations/0000_init.sql.
  • ContractRecord (API contract) е непроменен от страна на клиента; полето bidder_legal_form
    остава server-only (добавя се в details.ts, използва се от route-а, не се изпраща на клиента).
  • HTML профилът не е пипан — неговият noindex мета-етикет минава през същия споделен предикат.

Чеклист

  • Комитите следват conventional commits и нямат Co-Authored-By: trailer
  • PR-ът е с един логически обхват и е от форк към midt-bg/sigma:main
  • pnpm typecheck минава; пред-съществуващите pnpm test/pnpm lint повреди са
    документирани като baseline в секция „Валидация (реални данни)" по-горе

Closes #173

@lyubomir-bozhinov lyubomir-bozhinov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добре структуриран — маскирането е на query слой преди R2, noindex-gate-ът на .json е чист, тестовете са солидни. Но тезата на PR-а („noindex+mask на всички machine-readable изходи") не е изпълнена докрай:

🔴 .data single-fetch payload е непокрита machine-readable повърхност. При ssr:true RRv7 сервира всеки loader и на GET /<път>.data. company.tsx loader-ът връща eik + displayName немаскирани, а headers() е publicCache(...) → отговорът минава през hardenResponse (само baseSecurityHeaders, без X-Robots-Tag) и се кешира на edge. Значи /companies/:eik.data връща немаскиран ЕИК на физическо лице, кеширан, без noindex — точно експозицията от #173, на повърхността, която PR-ът не изброява. (Потвърдих reachability-то на .data живо на публичния prod; robots.txt не покрива /*.data.) Поправка: приложи предиката/маската и за .data, или централизирай X-Robots-Tag в hardenResponse вместо per-route.

🟠 Sitemap-ът ползва по-тесния предикат. sitemaps.ts филтрира с isNaturalPersonProfileName (само по име), не с разширения isNaturalPersonBidder (+legal_form), който PR-ът ползва навсякъде другаде. ЕТ, разпознат само по legal_form, се маскира/noindex-ва навсякъде, но пак се рекламира в /sitemap-companies — каним crawl на страница, която политиката де-индексира.

За проверка (не потвърдено срещу данни): премахнатият consortium guard в isNaturalPersonBidder — нито един caller не филтрира kind==='consortium', та консорциум с водещ „ЕТ …" в името може да се over-маскира като „Частно лице". Струва си да се потвърди срещу корпуса, преди да се третира като дефект.

@lyubomir-bozhinov lyubomir-bozhinov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Инлайн котви към горния преглед — .data single-fetch privacy gap.

Comment thread apps/web/app/routes/company.tsx
Comment thread apps/web/app/routes/contract.json.tsx
@ydimitrof

Copy link
Copy Markdown
Contributor

Прегледах PR #183 изцяло — целия diff (24 файла, +1882/−45), всички коментари по ревюто, issue #173, както и текущото състояние на кода в работното дърво (sitemaps.ts, details.ts, company.tsx render). По-долу е обобщението.


Обобщение

Централизацията на X-Robots-Tag: noindex през маркера X-Privacy-Mask в hardenResponse е чиста и добре тествана. Маскирането на CSV става на query слоя преди записа в R2 (streamContractsCsv / streamCompaniesCsv), което е правилният ред — edge кешът не може да сервира немаскиран ред. Реакцията на предишното ревю (.data близнакът и per-route → централизиран автор) е адресирана коректно. Тестовете (38 нови) са смислени, не тривиални. Двете конкретни забележки от предишния преглед обаче не са затворени докрай, а при локалната проверка изникнаха и нови пропуски в същия клас CWE-359.

Сигурност / SQL / OWASP

  • SQL инжекция: няма. Всички нови SQL фрагменти (b.legal_form AS bidder_legal_form, LEFT JOIN bidders AS b ON b.id = ct.bidder_id) са статични идентификатори; параметрите остават през ?-binding. LEFT JOIN е 1:1 (bidders.id е PK), няма fan-out на редовете.
  • Секрети / обфускация / backdoor: няма. safeJson продължава да екранира <, > и line separators.
  • OWASP: A01/A04 се подобряват; не се въвежда нова инжекционна повърхност.

🔴 Съществени пропуски (data-integrity / поверителност)

1. Подизпълнителят (subcontractor) остава немаскиран в /contracts/:id.json. maskContractForPrivacy маскира само bidder; getContract дори не селектира legal_form на подизпълнителя. При договор с юридическо лице като изпълнител и едноличен търговец като подизпълнител, maskContractForPrivacy връща записа по референция (masked === record) → маркерът не се слага → отговорът е без noindex, кеширан, с непокрит ЕИК и оригинално име на физическото лице (subcontractor.eik = r.subcontractor_eik, subcontractor.name). Това е точно експозицията от #173 („any machine-readable record carrying a natural-person identifier"), на повърхността, която PR-ът твърди, че покрива изцяло. Рядка (~0.8% договори), но е същият клас уязвимост, който PR-ът затваря.

2. Sitemap-ът ползва по-тесния предикат (незатворена забележка от предишното ревю). packages/db/src/queries/sitemaps.ts:108 филтрира с isNaturalPersonProfileName (само по име), не с разширения isNaturalPersonBidder (+legal_form). ЕТ, разпознат само по legal_form (име без водещо „ЕТ "), се маскира и получава noindex навсякъде другаде и в HTML профила, но продължава да се обявява в /sitemap-companies — активно каним crawl на страница, която политиката де-индексира.

3. HTML профилът скрива ЕИК на физическите лица — противоречи на собствената документация в PR-а. Споделеният loader прави company.eik = null (company.tsx:77) и за HTML отговора. В render-а {c.hasEik && c.eik && (…ЕИК…)} (company.tsx:126) става falsy → блокът с ЕИК изчезва. А новата секция в privacy.tsx изрично уверява потребителя, че „HTML профилът … остава непокътнат по съдържание — името, ЕИК и всички останали полета се показват както в първичния източник." Поведението е по-защитно (fail-safe), но е необявена функционална промяна и прави потребителската документация невярна.

🟠 По-малки бележки

4. .data близнакът връща оригиналното име немаскирано, докато privacy.tsx твърди, че за /companies/:eik.data „ЕИК и оригиналното име … се заменят с неутрален етикет". Реално се нулира само eik; displayName остава дословен (тестът company.data.test.ts го потвърждава). Тъй като HTML показва същото име и .data вече носи noindex, експозицията ≈ HTML — но документацията надценява маскирането.

5. Възможно over-маскиране на консорциум. isNaturalPersonBidder премахна консорциум-гарда; CSV-каналът за договори не филтрира kind, така че консорциум с водещ „ЕТ …" в display name-а (пръв член ЕТ) би се маскирал като „Частно лице". Fail-safe, не е теч — струва си потвърждение срещу корпуса.

Съответствие с issue #173

Ядрото на issue-то (bulk-indexable ЕИК на ЕТ в .json + .csv) е адресирано за изпълнителя. Остатъчните повърхности от т.1 (подизпълнител) и т.2 (sitemap) означават, че тезата „noindex+mask на всички machine-readable изходи" още не е напълно изпълнена.

Бележки

  • CI: „no checks reported on the 'main' branch" — PR-ът е от форк с branch main; препоръчвам да се провери дали required checks реално минават преди merge.
  • pnpm lint е exit 1 с нови prettier warnings в scope (contract.json.test.ts, privacy.tsx, companies.ts, companies.test.ts) — CI е конфигуриран като blocking lint (2d93cd5), така че тези трябва да се forматират.

Вердикт: Заявка за промени (Request changes) — блокиращо е т.1 (немаскиран ЕИК/име на подизпълнител-физическо лице в /contracts/:id.json, без noindex) и т.2 (sitemap с по-тесен предикат); т.3 изисква или коригиране на кода, или коригиране на потребителската документация, за да не е подвеждаща.

Благодаря за прегледната работа по маркерния договор и тестовете — след затварянето на горните пропуски PR-ът ще е в много добра форма.

@lyubomir-bozhinov

Copy link
Copy Markdown
Collaborator

Блокерът е затворен — ре-проверих на връх d55a1cc:

  • ЕИК маскирането е на ниво заявка (companies.ts:271const eik = isNatural ? '' : r.eik), значи важи автоматично и за /companies/:eik.data близнака (един и същ loader обслужва HTML и .data).
  • noindex е централизиран на worker ниво: app.ts hardenResponse превежда X-Privacy-Mask маркера в X-Robots-Tag: noindex и го маха преди кеширане; app.nofollow.test.ts покрива изрично .data близнаци — физ. лице → noindex (T-008), юр. лице → без маркер (негативен fixture).

Точно това затваря находката ми (немаскиран ЕИК на физ. лице, кеширан, без noindex, изтичащ през .data). Одобрявам по същество.

Единствено: branch-ът е в конфликт с main (mergeable_state=dirty) — rebase преди merge.

LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 6, 2026
…mber worker adr to 0008

Rebase of midt-bg#183 onto upstream/main (post-midt-bg#182 ADR reorganization) restructured the privacy-policy and worker-level X-Robots-Tag ADRs to live in docs/adr/ rather than inline in docs/architecture.md:

- New docs/adr/0007-privacy-masking.md — content extracted from the inline ADR-0002 in architecture.md; relative paths adjusted (../ → ../../) for the new adr/ location; cross-link to the worker ADR now points to 0008.
- docs/adr/0003-centralized-x-robots-tag-worker.md → docs/adr/0008-centralized-x-robots-tag-worker.md — renumbered to free the 0003 slot taken by upstream's value-flag ADR; internal cross-link from architecture.md#adr-0002-... to 0007-privacy-masking.md.
- docs/adr/README.md — index extended with the two new entries.
- docs/architecture.md — adopted upstream's short summary form; the inline ADR-0001+0002 contents are removed (the rendering ADR lives at adr/0001-rendering-and-security.md and the privacy policy at adr/0007-privacy-masking.md); Решения (ADR) section now also points to 0007 and 0008.
- docs/privacy-masking.md — cross-link from architecture.md#adr-0002-... to adr/0007-privacy-masking.md; ADR-0003 to ADR-0008.

No code changes; verified pnpm check:docs (docs-integrity gate from midt-bg#182) passes.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 6, 2026
The three files modified by PR midt-bg#183 carried pre-existing prettier debt that the original review flagged (`pnpm lint` exit 1 with `contract.json.test.ts`, `companies.test.ts`, `companies.ts`). The repo's CI is configured as blocking lint (`2d93cd5`, comment in .github/workflows/ci.yml), so this would have blocked the PR from merging. Run `pnpm prettier --write` on the three files — no semantic changes.
@lyubomir-bozhinov

Copy link
Copy Markdown
Collaborator

Прегледах отново новия връх 468a116 — доста по-широк (CSV/JSON/.data/company маскирани, ADR-и), добра работа. Но adversarial pass показва, че маскирането е закачено за export/twin routes, а СПОДЕЛЕНИТЕ проекции остават немаскирани — та ЕИК на физ. лице (ЕТ) още изтича на най-видимите ИНДЕКСИРАНИ HTML страници:

1) Списък „Фирми" (companies.tsx). listCompanies мапва през toCompanyListItem (rows.ts:58 eik: r.eik — суров; rows.ts е +1/-0, проекцията не е пипана). companies.tsx:70 рендира „ЕИК {c.eik}". ЕТ → ЕИК на индексиран списък.

2) Начална страница (home.tsx). getHomeDatatopCompanies: companies.results.map(toCompanyListItem) (home.ts:84) — същата немаскирана проекция; home.tsx:196 показва ЕИК на топ-10. ЕТ в топ-10 → ЕИК на най-трафикираната страница.

3) Страница на договора (contract.tsx). Не е в PR-а; getContract (details.ts:583 eik: r.bidder_eik суров) → contract.tsx:221-222 показва „ЕИК {c.bidder.eik}" + линк към регистъра. .json близнакът маскира, HTML — не.

4) Подизпълнител. maskContractForPrivacy маскира само bidder, не subcontractor; contract.tsx:258-263 рендира c.subcontractor.eik суров. Изтича и на HTML, и на .json.

isNaturalPersonBidder хваща ЕТ (format.ts:210), а ЕТ има валиден 9-цифрен ЕИК (eik_valid=1) → hasEik е true и се рендира — точно случаите, които streamCompaniesCsv вече маскира (companies.ts:270). CSV/JSON са затворени; голите HTML страници — не.

Корен (altitude): маскирането е на leaf routes/exports, не на споделените проекции. Устойчивият фикс: маскирай в toCompanyListItem (rows.ts — има name/kind/legal_form → isNaturalPersonBidder) и в getContract/getContractDetail (details.ts — има bidder_name/bidder_legal_form + subcontractor_name за name-based проверка). Тогава списък, начална, договор, .data наследяват маската веднъж — вместо всяка нова повърхност да помни да маскира (CSV помни, списъкът — не).

PR-ът затваря буквата на #173 (.json/.csv), но не и духа — ЕТ ЕИК на индексираните HTML страници. Блокер до фикса на споделените проекции.

@nedda76 nedda76 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Прегледах PR-а спрямо #173. Механиката marker→header е добре построена и тествана: CSV се маскира преди записа в R2, worker-ът слага X-Robots-Tag: noindex и трие marker-а преди edge cache (cache-safe — app.nofollow.test.ts го покрива). Но маската не покрива всяка machine-readable повърхност и на места е обезсилена — има потвърдени пътища, по които суровият ЕИК на физическо лице все още изтича. Тоест PR-ът още не затваря #173.

Блокиращи — потвърдени течове на суров ЕИК

  1. slug пресейва ЕИК-а. Маската нулира eik, но оставя slug — а за eik-базирани субекти slug е самият нормализиран ЕИК (companySlug('eik:222222222') === '222222222'). Тоест bidder.slug / company.slug в /contracts/:id.json и /companies/:eik.data носят точно идентификатора, който маската маха. ADR-0007 („slug-ът не е PII") не важи за физически лица — а те са именно маскираната популация.

  2. /contracts/:id.data не е маскиран. HTML маршрутът contract.tsx е недокоснат; при ssr:true single-fetch /contracts/:id.data сервира payload-а на loader-а машинно четимо — bidder.eik и subcontractor.eik, без noindex. .json е маскиран, но .data близнакът му — не (точно класът повърхности, заради който съществува ADR-0008).

  3. Подизпълнителят не се маскира. maskContractForPrivacy пипа само bidder + sourceNames.bidder; subcontractor минава непокътнат, а подизпълнителят може да е ЕТ/физическо лице → ЕИК изтича. Рядко (~0.8% от договорите), но реален непокрит път.

  4. /companies.data (списък) не е маскиран. /companies.csv е, но .data близнакът на списъчния маршрут връща CompanyListItem със суров eik + име за физически лица → точно „bulk searchable/downloadable" вредата от #173, само през .data вместо .csv.

За обсъждане — по-нисък приоритет

  1. Мрежовият граф в маскирания company.data носи node id-та eik:<ЕИК> → физическо лице като възел изтича ЕИК. Частично фундаментално за eik-базираните id-та (като #1).
  2. Регресия за легитимни фирми: предикатът пада към name-евристика (ЕТ /ET префикс) дори при реален legal_form (ООД) → фирма с име „ET Engineering" получава скрит валиден ЕИК (нарушава изискване #5). Евристиката е заварена, но сега тя контролира скриване на ЕИК, не само мек noindex — цената на false positive расте.
  3. Несъгласуваност: .json/.csv заменят името с етикет, но company.data/HTML пазят ЕТ името дословно. Трите machine-readable пътя маскират различни полета.

Чисто (за фокус)

marker→header плъмбингът и cache safety; обединеният предикат isNaturalPersonBidder (и двата source() клона проектират legal_form); запазеното показване на юридически лица по покритите пътища; authorities.csv (публични органи — умишлено без body-маска).

Коренът на #1/#2/#4 е един: маската покрива .json/.csv, но не и .data близнаците и не пипа slug. Докато .data повърхностите и slug не се покрият, #173 остава отворен.

@ydimitrof ydimitrof left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Преглед на PR #173 — „fix(privacy): noindex + маскиране за машинно-четими изходи"

Какво прави PR-ът

Прилага политика за поверителност върху машинно-четимите изходи (turbo-stream .data, JSON, CSV), така че идентификаторите и имената на физически лица/ЕТ да бъдат маскирани, а не само маркирани с noindex. Архитектурата е чиста и с ясно разделение на отговорностите: route-овете маркират чрез markPrivacyMaskApplied, worker-ът превежда маркера в X-Robots-Tag: noindex чрез applyPrivacyMaskHeaders и го изтрива преди кеш/клиент. Въвежда се единен предикат isNaturalPersonBidder и константа MASKED_NATURAL_PERSON_LABEL в @sigma/shared, преизползвани в streamCompaniesCsv и streamContractsCsv; legal_form се прокарва коректно през двата клона на source() и през getContract.

Сигурност (Фаза 0)

ЧИСТО и в двете партиди — няма зашити тайни/ключове, нови зависимости, нови или подозрителни URL адреси, нито зловредни шаблони. Промяната всъщност намалява изтичането на лични данни. Тестовото покритие е силно и смислено: покрити са MISS/HIT/dynamic, идемпотентност, edge-cache инвариантите, негативните случаи, двата клона на source(), name-евристиката при legal_form=null и таблица на истинност на предиката. Документацията (ADR-0007, ADR-0008, privacy-masking.md) е изчерпателна и синхронизирана с кода.

Блокираща забележка

  1. (Средно — поверителност/консистентност) Машинно-четимият близнак /companies/:eik.data изчиства само company.eik, но връща пълното име на физическото лице (displayName) буквално — за разлика от /contracts/:id.json и CSV, които заменят името с MASKED_NATURAL_PERSON_LABEL. Тъй като .data е машинно-четим изход, а самата обосновка на PR-а (ADR-0007) гласи, че noindex е недостатъчен срещу ботове, оставянето на суровото име само зад noindex противоречи на декларираната цел. Тестът company.data.test.ts дори утвърждава това като очаквано. Нужно е явно решение: да се маскира името и в .data, или изрично да се документира защо .data остава немаскиран.

Некритични забележки

  1. (Ниско — поверителност) При маскиране bidder.slug / company.slug се запазват. Ако slug-овете се извеждат от името на субекта, URL-фрагментът може да разкрие идентичността въпреки маскирането на name/eik. ADR-0007 приема slug като „URL фрагмент, не PII", но не адресира случая на slug, изведен от име.
  2. (Ниско — точност на маскирането) isNaturalPersonBidder се вика без предварителна проверка за bidder_kind, въпреки че документацията му възлага филтрирането на консорциумите на викащия. Консорциум с име, започващо с „ЕТ ", ще бъде over-маскиран като „Частно лице" — privacy-safe, но с загуба на информация.
  3. (Ниско — DB/производителност) Клонът по подразбиране на source() вече винаги прави LEFT JOIN bidders, а това е и hot path за listCompanies. Да се потвърди, че company_totals няма собствена колона legal_form (иначе ct.* + b.legal_form дава двусмислена дублирана колона) и че има индекс по bidders.id.
  4. (Ниско — дублиран/мъртъв код) Няколко случая на дублиране, противоречащи на правилото „NO CODE DUPLICATION": излишните предварителни извиквания на markPrivacyMaskApplied в responseFromR2Object (csv-export.ts), които markCsvCache веднага презаписва; и inline вариант на правилата за legal_form в apps/web/app/routes/company.tsx.
  5. (За потвърждение) details.ts прокарва bidder_legal_form без маскиране и без тест в прегледаната партида — да се потвърди, че JSON маскирането се извършва другаде.

Вердикт

Промяната е висококачествена и без изтичане на данни в прегледаните файлове. Единствената блокираща точка е несъответствието в поверителността при /companies/:eik.data (т.1) в PR, чиято цел е именно защита на лични данни — тя трябва да бъде адресирана или изрично обоснована преди одобрение. Останалите забележки са некритични.

Comment thread apps/web/app/routes/company.tsx
Comment thread apps/web/app/routes/contract.json.tsx
Comment thread apps/web/app/lib/csv-export.ts Outdated
Comment thread packages/db/src/queries/companies.ts
Comment thread packages/db/src/queries/contracts.ts Outdated
Comment thread packages/shared/src/format.ts Outdated

@lyubomir-bozhinov lyubomir-bozhinov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Благодаря — маскирането на .json и CSV е издържано. Но остава отворена точно най-чувствителната machine-readable повърхност, заради която е #173: detail страницата на договора и нейният .data twin.

apps/web/app/routes/contract.tsx — loader-ът (:62-67) връща { contract } суров; файлът не се пипа в този PR и няма нито маска, нито noindex. getContract селектира b.eik_normalized AS bidder_eik (packages/db/src/queries/details.ts:440) и го отдава суров (:583 eik: r.bidder_eik, :595 eik: r.subcontractor_eik). contract.tsx ги рендира без маска — :221 ЕИК на изпълнителя, :261 ЕИК на подизпълнителя. Worker-ът прилага само applyPrivacyMaskHeaders(headers) (header-only, noindex) — няма body маска на ниво worker.

Ефект (prod е публичен, unauthenticated):

  • GET /contracts/<slug>.data → turbo-stream body с bidder.eik / subcontractor.eik на физическо лице (ЕТ), немаскиран и без X-Robots-Tag.
  • GET /contracts/<slug> (HTML) → същият ЕИК, индексируем.

Същата политика, различно прилагане и на списъците:

  • /companies.data: toCompanyListItem (packages/db/src/queries/rows.ts:58) връща eik: r.eik без isNaturalPersonBidder проверка, докато /companies.csv го маскира.
  • /contracts.data: toItem в contracts.ts дава немаскирани имена на физически лица (CSV пътят вече маскира).

Предложение: маскирай в споделения слой — в getContract, или в loader-а на contract.tsx огледално на company.tsx:77-85 — за да го наследят HTML, .data и .json, вместо per-route. Същото за toCompanyListItem (редът вече носи legal_form) и за подизпълнителя в maskContractForPrivacy.

Докато .data twin-ът не минава през същата маска като .json, #173 не е затворен. Проверих горните редове на HEAD (468a116). Блокиращо за merge.

LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 27, 2026
…port

The R2-body branch (responseFromR2Object) and the 304 branch each called
markPrivacyMaskApplied directly, then handed the response to markCsvCache,
which calls it again internally. The marker was applied twice on MISS/HIT/304
paths — idempotent in effect, but dead code that hid markCsvCache as the single
source of truth for the privacy marker on every CSV path (PR midt-bg#183 review T-004,
"NO DEAD CODE / NO CODE DUPLICATION").

Drop the direct calls; rely solely on markCsvCache. Add a TDD guard that spies
on markPrivacyMaskApplied and asserts exactly one call per response path
(MISS/HIT/dynamic/304), so a future duplicate cannot sneak back in.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 27, 2026
…ortium over-masking

isNaturalPersonBidder's docstring delegates consortium filtering to the caller —
a JV is a legal entity even if a lead member's name / legal_form matches a
sole-trader signal. But streamContractsCsv and streamCompaniesCsv both invoked
it WITHOUT a bidder_kind guard, so a consortium such as "ЕТ Иван Петров; Строй
ООД" (or any consortium whose legal_form collided with a sole-trader form) was
masked to MASKED_NATURAL_PERSON_LABEL with its ЕИК cleared.

The result was privacy-safe (over-masking, no leak) but a behavioral change
that dropped the lead member's name + ЕИК and contradicted the predicate's
contract. Add an early bidder_kind/kind !== 'consortium' guard in both
streamers so consortium rows keep the "… и др." shape and their ЕИК.

TDD: failing tests first (consortium with ЕТ lead name + ЕТ legal_form, and the
leading-ЕТ name heuristic with legal_form null), then the guard (PR midt-bg#183 T-006).
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 27, 2026
…ne duplication)

The docstring claimed the legal_form rules were "carried inline in
apps/web/app/routes/company.tsx until the route migrates" — but ADR-0007 §1
already removed the legacy inline isSingleNaturalPersonProfile, and company.tsx
now calls this shared predicate directly (verified: no legal_form string-
matching exists outside packages/shared). The stale claim created exactly the
divergence risk the PR midt-bg#183 reviewer flagged under "NO CODE DUPLICATION": a
future reader could believe a second copy still lives in the route and maintain
it separately.

Rewrite the docstring to state the predicate is the single source of truth and
enumerate the downstream surfaces that consume it (HTML noindex, CSV masking,
JSON masking), with a pointer to the bidder_kind/kind consortium guards added
in the CSV streamers (PR midt-bg#183 T-006). No behavior change.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 27, 2026
…6, §7)

Two PR midt-bg#183 review threads asked for explicit product decisions on the company
profile masking surface. Both are recorded here as policy.

§6 — displayName stays visible in the HTML profile and its `.data` twin; only the
ЕИК is masked. The trading name is PUBLIC (rendered verbatim on the HTML page and
in <title>); the sensitive natural-person identifier is the ЕИК. The `.data`
turbo-stream is React Router v7's single-fetch transport for client-side
navigations, NOT a standalone export like /contracts/:id.json — masking the name
there would break client-rendered pages. Consistent policy: name = public, ЕИК =
sensitive. company.tsx loader comment now states this; the company.data.test.ts
assertion locks displayName-verbatim + eik-null as the contract.

§7 — the name-keyed natural-person slug (n + base64url(name)) is a tracked
limitation, not changed in this PR. The name is public (§6), the sitemap already
filters these records, and reworking the slug scheme is cross-cutting (URL
stability, internal links, identity system) and out of scope for a masking PR.

No behavior change.
@lyubomir-bozhinov

Copy link
Copy Markdown
Collaborator

Прегледах #183 на дълбочина срещу head a9b18ae (валидирано срещу дифа). Ядрото за CSV + /contracts/:id.json е солидно, но има два реални пропуска в покритието, които оставят точно този ЕИК незащитен.

Силната част (потвърдено):

  • CSV маскирането пази consortium коректно: contracts.ts:459 / companies.ts гейтват r.bidder_kind !== 'consortium' ПРЕДИ isNaturalPersonBidder, така че „ЕТ Иван Петров; Строй ООД" НЕ се маскира като физ. лице. Тестовете дискриминират (ЕТ маскиран, ООД дословно, consortium не; стабилни колони).
  • Marker plumbing-ът е идемпотентен: applyPrivacyMaskHeaders реагира само на точния литерал, трие маркера преди edge-cache и преди клиента; „marks exactly once" е покрит за MISS/HIT/304.
  • Маскира се и ЕИК→null, и име→етикет (Частно лице); без слабо частично ЕИК.

MAJOR 1 — JSON masker-ът НЯМА consortium guard-а, който CSV пътят има. contract.json.tsx:27: if (!isNaturalPersonBidder(record.bidder.name, bidderLegalForm)) return record; — за разлика от contracts.ts:459, тук record.bidder.kind не се проверява. Docstring-ът на isNaturalPersonBidder делегира consortium филтрирането на викащия, а този викащ не го прави → consortium с име, започващо с „ЕТ …" и legal_form = null, се over-маскира до „Частно лице" + noindex в JSON. Точно багът, който вече е поправен в CSV, не е пренесен тук; няма consortium тест в contract.json.test.ts. Фикс: същият bidder.kind !== 'consortium' гард (добави полето към record-а, ако липсва).

MAJOR 2 — най-изложената повърхност остава отворена: страницата на договора + .data близнакът ѝ. contract.tsx рендерира ЕИК на изпълнителя (:219-222) без noindex и без маркер (meta()/headers() не ги слагат), а robots.txt забранява само /search + /*.csv (robots.tsx:5) — НЕ .data/.json. Значи договор, спечелен от „ЕТ …", излага личния ЕИК на едноличния търговец през /contracts/:id И през /contracts/:id.data, индексируемо. #183 затваря .json/.csv (каквото #173 назовава), но ADR-0008 обещава „всяка повърхност наследява noindex" — а дизайнът е marker-based, т.е. наследява само ако route-ът сложи маркера, а тази повърхност не го слага. Понеже страницата на договора е сред най-обхожданите, това е по-голямата дупка от .json. Препоръка: сложи маркера на contract.tsx (worker-ът ще покрие и HTML, и .data).

MAJOR 3 (test-gap + архитектура) — препращането на маркера към worker-а за .data не е доказано end-to-end. Механизмът зависи RR v7 да пренесе loader header-а върху реалния .data HTTP отговор; нито един тест не кара реалния single-fetch pipeline (мокват createRequestHandler / викат loader() директно). Ако RR не го препрати, .data близнакът на компанията тихо тръгва без X-Robots-Tag — зелени тестове, скрит пропуск. За сравнение: седмичният дайджест реши същия .data проблем path-based на worker-а (workers/app.ts DIGEST_DETAIL_PATH мачва и /weeks/:iso.data), което не зависи от RR forwarding. Същият подход за машинно-четимите повърхности е по-надежден + добави реален .data e2e тест.

MINOR — не-ЕТ физически лица могат да минат немаскирани. isNaturalPersonBidder (format.ts:210) хваща само ЕТ (legal_form или префикс „ЕТ "). Физ. лице с голо име и legal_form = null минава с ЕИК. #173 е скоупнат до ЕТ, ок като документирано ограничение — но копито в privacy.tsx казва „физическо лице или едноличен търговец", по-широко от това, което предикатът реално лови.

NITauthorities.csv и другите вече носят X-Robots-Tag: noindex (безусловен marker в markCsvCache). По ADR за консистентност, без маскиране на тялото — но е поведенческа промяна за журналисти/инструменти, разчитащи на discovery; струва си да е изрично в release бележките.

PR-ът е CONFLICTING спрямо main — нужен е rebase (отделно от горното).

Насоката е правилна; двата masker-а — consortium guard в JSON и покриване на страницата/.data — са това, което да се затвори преди merge.

LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 28, 2026
… path

The `/contracts/:id.json` masker (`maskContractForPrivacy`) lacked the
`bidder_kind !== 'consortium'` guard that the CSV streamer already has
(`contracts.ts:459`). A consortium whose display name begins with „ЕТ "
(first member is a sole trader, e.g. „ЕТ Иван Петров; Строй ООД") was
over-masked to „Частно лице" — losing the „… и др." shape, the consortium
ЕИК, and gaining an unearned `noindex`.

`isNaturalPersonBidder`'s docstring delegates consortium filtering to the
caller; this adds the caller guard, mirroring the CSV path exactly. Flagged
as MAJOR 1 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing consortium cases first (name-based + legal_form-based, plus a
loader-level marker-omission case), then the guard.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 28, 2026
`contract.tsx` was the most-indexable surface still open: its loader returned
`{ contract }` raw with no privacy marker, `robots.txt` does not block
`/contracts/:id` (or its `.data` twin), and the page rendered `c.bidder.eik`
verbatim — so a sole-trader's ЕИК was indexable on both the HTML page and the
RRv7 single-fetch `.data` payload. That is a worse exposure than the already-
closed `.json`/`.csv` paths.

Masking + signalling in the SHARED loader covers both surfaces at once (the
`.data` twin reuses the same loader), mirroring `company.tsx:89` exactly:
ЕИК (the sensitive natural-person ID) → null on the returned object, the
trading displayName stays PUBLIC (ADR-0007 §6), and the `X-Privacy-Mask:
applied` marker is translated to `X-Robots-Tag: noindex` by the worker. The
`kind === 'consortium'` guard matches the JSON masker (MAJOR 1) and the CSV
streamer so a JV is never over-masked/noindexed. `headers()` forwards the
marker onto the HTML response (RR does not auto-propagate loader headers).
Flagged as MAJOR 2 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing loader/headers/pipeline cases first, then the loader change.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 28, 2026
…eal worker

The PR midt-bg#183 review (MAJOR 3) noted the marker→`.data`→`X-Robots-Tag` forwarding
was only proven through fixtures that INJECT the marker by hand in the stubbed
RR handler — which proves the worker CAN translate a marker, not that a real
loader's marker survives the pipeline to the final `.data` HTTP response. That
left a „green tests, hidden gap" risk on the most-indexable surface.

Add four cases driving the REAL `worker.fetch` (→ handleRequest → hardenResponse
→ applyPrivacyMaskHeaders → edgeCache.put) against `/contracts/<x>.data`:
masked sole-trader → noindex + marker stripped + masked body preserved; cached
entry carries noindex (HIT-path invariant); second request HITs and serves
noindex verbatim; legal-entity negative (no marker → no noindex). The handler
returns the exact shape `contract.tsx`'s masked loader branch now produces
(MAJOR 2), so this is an honest end-to-end proof of the forwarding guarantee.

Note: the review's suggested path-based worker match (the weekly-digest
`DIGEST_DETAIL_PATH` precedent) does not exist in this codebase — the worker
does no path-based matching; the marker-based design (ADR-0008) is the
established architecture and is sound, so this keeps it.
@LyuboslavLyubenov

Copy link
Copy Markdown
Author

@lyubomir-bozhinov Благодаря за задълбочения adversarial pass — трите MAJOR забележки са затворени в три фокусирани комита върху a9b18ae:

MAJOR 1 — consortium guard в JSON masker-а (59bcece). maskContractForPrivacy (contract.json.tsx) вече gating-ва record.bidder.kind === 'consortium' ПРЕДИ isNaturalPersonBidder, огледално на CSV пътя (contracts.ts:459, bidder_kind !== 'consortium'). Консорциум с водещ „ЕТ …" вече не се over-маскира до „Частно лице" / не получава noindex. Докстринг-ът на isNaturalPersonBidder делегира consortium филтрирането на викащия — guard-ът е точно този caller. TDD: failing случаи първо (name-based + legal_form-based + loader-level маркер-омисия), после guard-а.

MAJOR 2 — маскиране на страницата на договора + .data близнака (0ea9230). contract.tsx беше най-индексируемата отворена повърхност: loader-ът връщаше { contract } суров, без маркер, robots.txt не блокира /contracts/:id (нито .data близнака), а страницата рендираше c.bidder.eik буквално. Сега маскирането + сигнализирането са в споделения loader (затова покриват HTML + .data едновременно), огледално на company.tsx:89: ЕИК → null, displayName остава ПУБЛИЧЕН (ADR-0007 §6), X-Privacy-Mask: applied се превежда в X-Robots-Tag: noindex от worker-а. kind === 'consortium' guard-ът от MAJOR 1 е приложен и тук. headers() препраща маркера (RR не auto-пропагира loader headers). TDD: failing loader/headers/pipeline случаи, после промяната.

MAJOR 3 — end-to-end доказателство, че маркерът достига X-Robots-Tag на .data през реалния worker (5acd42b). Добавени 4 случая в app.nofollow.test.ts, които драйвят реалния worker.fetch (→ handleRequesthardenResponseapplyPrivacyMaskHeadersedgeCache.put) срещу /contracts/<x>.data с body, носещ точно формата, който новият loader produce-ва (маскиран ЕИК + маркер): masked sole-trader → noindex + маркер изтрит + body запазен; кеширан entry носи noindex (HIT-инвариант); втори request HIT-ва и сервира noindex verbatim; legal-entity негативен (без маркер → без noindex). Предишните fixtures инжектираха маркера на ръка в stub-натия handler — доказваха само че worker-ът може да преведе маркер, не че реален loader-маркер оцелява. Това затваря „green tests, hidden gap" риска.

Забележка към предложението ти за path-based worker match (седмичният digest DIGEST_DETAIL_PATH): този precedent не съществува в кода — worker-ът (app.ts) няма path-based matching, архитектурата е изцяло marker-based (ADR-0008) и е коректна, така че не въвеждам path-based схема.

За останалите ти точки (не са код-промени в този PR):

  • NIT (authorities.csv безусловен noindex) — умишлено по ADR-0007 §last (политическа консистентност, без body-маска). Ще го отбележа изрично в release notes.
  • MINOR (не-ЕТ физически лица с голо име) — документирано ограничение: Privacy: .json/.csv expose natural-person ЕИК without the noindex applied to HTML profiles #173 е скоупнат до ЕТ, а privacy.tsx е по-широко формулиран. Отделна задача за разширяване на предиката.
  • Подизпълнителят (т.4 от по-ранен пас) — subcontractor няма legal_form колона в заявката (details.ts строи обекта само от subcontractor_name + subcontractor_eik), така че маскирането му изисква query промяна + policy решение извън ADR-0007 §3. Остава като проследявано ограничение за follow-up PR — не го сгъвам в този бранч (AGENTS.md scope).

Rebase: PR-ът е CONFLICTING спрямо main (22 upstream комита, включително identity-system af4977e/f7a3e50 и value-base 463e22a/210fd88, с тежко припокриване точно в details.ts/contracts.ts/companies.ts/contract.tsx/format.ts). Не съм ребейзвал тук — коректното resolution изисква повторна валидация на masking-политиката срещу новата upstream identity система, което е отделна, по-голяма задача от този review пас, и не искам да пренаписвам 14 комита, които ревюиращите вече коментират. Оставям ребейза за merge-стъпката. Трите MAJOR фикс-а са independently reviewable върху текущия head 5acd42b.

Пълна локална проверка: pnpm --filter @sigma/web test → 385 passing (0 new failures), pnpm --filter @sigma/web typecheck → exit 0, форматирано с prettier.

LyuboslavLyubenov and others added 4 commits July 28, 2026 13:52
…-Mask marker

The literal X-Robots-Tag header is no longer set anywhere in apps/web;
it is now written by exactly one helper (applyPrivacyMaskHeaders in
apps/web/app/lib/security.ts), called by the worker hardenResponse
after the base security headers and before the cacheable-HTML branch.

A new internal marker X-Privacy-Mask: applied is the route-side signal
that the response carries masked natural-person data. Route handlers
(csv-export.ts markCsvCache + 304 branch, contract.json.tsx loader) and
the worker consume that marker; it is deleted unconditionally before
the response is returned or stored in edgeCache.put so it never reaches
clients.

The HIT path in handleRequest (apps/web/workers/app.ts) is unchanged:
it copies cached.headers verbatim, and the cached entry is the
post-hardenResponse response, so the header survives the edge cache by
construction.

apps/web/workers/app.nofollow.test.ts (T-005 + T-008) exercises the
end-to-end worker flow for the .data twin of /companies/:eik and the
contract.json natural-person branch.

No edits to packages/db or to the public API contract;
bidders.legal_form stays server-only and company.eik stays on the
CompanyRecord type (masked to null by the loader, not removed).
…ough headers()

The single-fetch .data twin of the company profile now clears company.eik to null
on the natural-person branch (per isNaturalPersonBidder) and signals the
worker via the internal X-Privacy-Mask: applied header on the Response.json
return. The route's headers() export now destructures { loaderHeaders } from
Route.HeadersArgs and forwards the marker explicitly so the worker
hardenResponse can translate it into X-Robots-Tag: noindex on the HTML
response (getDocumentHeadersImpl only auto-propagates Set-Cookie).

Legal-entity records keep the plain-object return unchanged — no marker, no
mutation, no Response.json wrap. The not-found short-circuit (throw new
Response('Not Found', ...)) runs before the masking gate, so 404s never
carry the marker.

The HTML meta() noindex branch is unchanged — natural-person pages
continue to emit <meta name="robots" content="noindex"> via the existing
seoMeta + isNaturalPersonBidder gate. The new headers() forward adds a
redundant X-Robots-Tag: noindex HTTP header alongside the meta tag, which
is acceptable (the worker translates the marker for all responses).

apps/web/app/routes/company.data.test.ts is the focused new test suite
(7 tests across 5 describe blocks): natural-person loader return asserts
company.eik === null and X-Privacy-Mask: applied; legal-entity loader
return asserts a plain object with eik unchanged and no marker; headers()
test exercises both branches (marker present → forwarded + Cache-Control;
marker absent → Cache-Control only); meta() test covers the natural-person
noindex HTML tag; the worker-pipeline describe calls applyPrivacyMaskHeaders
on the loader return and asserts X-Robots-Tag: noindex is set while
X-Privacy-Mask is stripped, proving the worker translate end-to-end.
…rage

ADR-0002 (docs/architecture.md): the Решение section now describes the
centralized X-Robots-Tag: noindex write site (hardenResponse in
apps/web/workers/app.ts, via the applyPrivacyMaskHeaders helper in
apps/web/app/lib/security.ts). The bullet on per-route CSV/contract-json
writes is replaced by a single sentence naming hardenResponse, the marker
flow, and the deletion pre-edgeCache.put.

The Засегнати повърхности list grows to explicitly enumerate:
  - the .data twin of /companies/:eik (React Router v7 single-fetch,
    automatic via the shared loader in company.tsx)
  - apps/web/workers/app.ts (hardenResponse) as the centralized
    enforcement point under a new 'Worker — централизирана точка за
    прилагане' sub-heading
  - apps/web/app/lib/security.ts as the policy helper home, with
    PRIVACY_MASK_APPLIED as the literal-typed constant.

The privacy page (apps/web/app/routes/privacy.tsx) #natural-person-data
section grows to enumerate /companies/:eik.data alongside the existing
/contracts/:id.json and the three CSV exports. A follow-up paragraph in
Bulgarian prose explains that the X-Robots-Tag: noindex policy is now
applied uniformly at the worker edge so future machine-readable surfaces
inherit it automatically — without naming the X-Privacy-Mask marker or
the helper functions (user-facing wording only).

No edits to package.json, pnpm-lock.yaml, or the public API contract.
…ne duplication)

The docstring claimed the legal_form rules were "carried inline in
apps/web/app/routes/company.tsx until the route migrates" — but ADR-0007 §1
already removed the legacy inline isSingleNaturalPersonProfile, and company.tsx
now calls this shared predicate directly (verified: no legal_form string-
matching exists outside packages/shared). The stale claim created exactly the
divergence risk the PR midt-bg#183 reviewer flagged under "NO CODE DUPLICATION": a
future reader could believe a second copy still lives in the route and maintain
it separately.

Rewrite the docstring to state the predicate is the single source of truth and
enumerate the downstream surfaces that consume it (HTML noindex, CSV masking,
JSON masking), with a pointer to the bidder_kind/kind consortium guards added
in the CSV streamers (PR midt-bg#183 T-006). No behavior change.
…6, §7)

Two PR midt-bg#183 review threads asked for explicit product decisions on the company
profile masking surface. Both are recorded here as policy.

§6 — displayName stays visible in the HTML profile and its `.data` twin; only the
ЕИК is masked. The trading name is PUBLIC (rendered verbatim on the HTML page and
in <title>); the sensitive natural-person identifier is the ЕИК. The `.data`
turbo-stream is React Router v7's single-fetch transport for client-side
navigations, NOT a standalone export like /contracts/:id.json — masking the name
there would break client-rendered pages. Consistent policy: name = public, ЕИК =
sensitive. company.tsx loader comment now states this; the company.data.test.ts
assertion locks displayName-verbatim + eik-null as the contract.

§7 — the name-keyed natural-person slug (n + base64url(name)) is a tracked
limitation, not changed in this PR. The name is public (§6), the sitemap already
filters these records, and reworking the slug scheme is cross-cutting (URL
stability, internal links, identity system) and out of scope for a masking PR.

No behavior change.
… path

The `/contracts/:id.json` masker (`maskContractForPrivacy`) lacked the
`bidder_kind !== 'consortium'` guard that the CSV streamer already has
(`contracts.ts:459`). A consortium whose display name begins with „ЕТ "
(first member is a sole trader, e.g. „ЕТ Иван Петров; Строй ООД") was
over-masked to „Частно лице" — losing the „… и др." shape, the consortium
ЕИК, and gaining an unearned `noindex`.

`isNaturalPersonBidder`'s docstring delegates consortium filtering to the
caller; this adds the caller guard, mirroring the CSV path exactly. Flagged
as MAJOR 1 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing consortium cases first (name-based + legal_form-based, plus a
loader-level marker-omission case), then the guard.
`contract.tsx` was the most-indexable surface still open: its loader returned
`{ contract }` raw with no privacy marker, `robots.txt` does not block
`/contracts/:id` (or its `.data` twin), and the page rendered `c.bidder.eik`
verbatim — so a sole-trader's ЕИК was indexable on both the HTML page and the
RRv7 single-fetch `.data` payload. That is a worse exposure than the already-
closed `.json`/`.csv` paths.

Masking + signalling in the SHARED loader covers both surfaces at once (the
`.data` twin reuses the same loader), mirroring `company.tsx:89` exactly:
ЕИК (the sensitive natural-person ID) → null on the returned object, the
trading displayName stays PUBLIC (ADR-0007 §6), and the `X-Privacy-Mask:
applied` marker is translated to `X-Robots-Tag: noindex` by the worker. The
`kind === 'consortium'` guard matches the JSON masker (MAJOR 1) and the CSV
streamer so a JV is never over-masked/noindexed. `headers()` forwards the
marker onto the HTML response (RR does not auto-propagate loader headers).
Flagged as MAJOR 2 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing loader/headers/pipeline cases first, then the loader change.
…eal worker

The PR midt-bg#183 review (MAJOR 3) noted the marker→`.data`→`X-Robots-Tag` forwarding
was only proven through fixtures that INJECT the marker by hand in the stubbed
RR handler — which proves the worker CAN translate a marker, not that a real
loader's marker survives the pipeline to the final `.data` HTTP response. That
left a „green tests, hidden gap" risk on the most-indexable surface.

Add four cases driving the REAL `worker.fetch` (→ handleRequest → hardenResponse
→ applyPrivacyMaskHeaders → edgeCache.put) against `/contracts/<x>.data`:
masked sole-trader → noindex + marker stripped + masked body preserved; cached
entry carries noindex (HIT-path invariant); second request HITs and serves
noindex verbatim; legal-entity negative (no marker → no noindex). The handler
returns the exact shape `contract.tsx`'s masked loader branch now produces
(MAJOR 2), so this is an honest end-to-end proof of the forwarding guarantee.

Note: the review's suggested path-based worker match (the weekly-digest
`DIGEST_DETAIL_PATH` precedent) does not exist in this codebase — the worker
does no path-based matching; the marker-based design (ADR-0008) is the
established architecture and is sound, so this keeps it.
…ty changes

After rebasing midt-bg#183 onto upstream/main, the masking test fixtures needed two
adaptations to upstream's new APIs (no behaviour change to the production
masking logic):

- Add `getDb` to the `@sigma/db` mocks in the three loader tests. Upstream's
  read-only D1 chokepoint (midt-bg#199/midt-bg#225) means loaders now call
  `getContract(getDb(env), …)` instead of `getContract(env.DB, …)`; the mock
  passes the env's DB through so the stubbed `getContract` still resolves.
- Add the new required `orderingUnit: null` (canonical-identity midt-bg#251) and
  `amendments: []` (annex history midt-bg#165) fields to the `ContractParty` /
  `ContractRecord` test builders so they satisfy the widened types.

All masking assertions unchanged. `pnpm --filter @sigma/web test` → 424
passing; `pnpm --filter @sigma/db test` → 297 passing; typecheck exit 0.
@LyuboslavLyubenov

Copy link
Copy Markdown
Author

Rebased onto main — conflicts resolved, ready for re-review/merge.

Head is now 1d4ca86 (was 5acd42b). The branch was CONFLICTING against main (22 upstream commits, heavy overlap on the masking/query core). I rebased all 14 commits on top of upstream/main and reconciled the conflicts:

Verification (local):

  • pnpm typecheck → exit 0 (all 7 packages)
  • pnpm --filter @sigma/web test → 424 passing
  • pnpm --filter @sigma/db test → 297 passing
  • pnpm --filter @sigma/shared test → 51 passing

(One pre-existing, unrelated ScrollToTop.test.tsx vitest forks-worker spawn error — identical to upstream main, not touched by this branch.)

Merge state: GitHub now reports the PR MERGEABLE. The only remaining gate is REVIEW_REQUIRED (branch protection) — needs a maintainer re-approval on the rebased head. I have not force-merged via --admin; leaving the review/merge decision to maintainers.

Safety: prior head 5acd42b is preserved as tag pre-183-rebase-20260728 locally in case anything needs restoring.

@lyubomir-bozhinov

Copy link
Copy Markdown
Collaborator

Ре-проверих трите нови фикс-комита срещу дифа на връх 1d4ca86 — и двете находки от ревюто са затворени коректно.

MAJOR 1 (consortium guard в JSON masker) — затворено. maskContractForPrivacy (contract.json.tsx:35) вече връща записа по референция при bidder.kind === 'consortium' ПРЕДИ isNaturalPersonBidder, огледално на CSV стриймъра (contracts.ts:459). JV с първи член ЕТ вече не се over-mask-ва. Покрито с тест (contract.json.test.ts + консорциум кейса в contract.data.test.ts).

MAJOR 2 (ЕИК на sole-trader изтича на contract страницата + .data twin) — затворено по същество. Loader-ът (contract.tsx:188-196) нулира contract.bidder.eik върху споделения обект → ЕИК-ът изчезва и от HTML, и от .data payload-а безусловно (не зависи от хедъри). Consortium guard-ът е и тук (kind !== 'consortium'). noindex сигналът за HTML минава през headers() export-а — същият доказан модел като company.tsx. Реалната PII експозиция е затворена.

Една остатъчна бележка — не блокер, defense-in-depth пълнота. End-to-end гаранцията, че реален GET /contracts/:id.data носи маркера до X-Robots-Tag: noindex, все още не се упражнява. И contract.data.test.ts, и app.nofollow.test.ts мокват react-router (vi.mock('react-router', …)) и слагат X-Privacy-Mask: applied на ръка върху .data фикстурата. Т.е. доказано е:

  • loader-ът слага маркера + нулира ЕИК (реален loader) ✅
  • worker-ът превежда наличен маркер → X-Robots-Tag: noindex през реалния fetch → hardenResponse → edgeCache.put/HIT пайплайн ✅
  • но че RRv7 single-fetch реално пренася маркера от loader-Response-а върху .data HTTP отговора — това остава допуснато, не упражнено. Коментарът при MAJOR 3 в app.nofollow.test.ts твърди, че затваря точно тази дупка, но хендлърът пак е стъб — тестът ще мине зелен дори ако RR спре да пренася хедъра.

Мястото да се затвори това е #177 (wrangler интеграционната писта с реалния server build): един GET /contracts/:id.data срещу natural-person seed → assert X-Robots-Tag: noindex. Понеже ЕИК-ът е вече маскиран, това е пълнота на покритието, не жив теч.

Силен отговор на ревюто — ADR-0007/0008 + едновременно покриване на CSV/JSON/.data/company/contract. Благодаря.

LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…mber worker adr to 0008

Rebase of midt-bg#183 onto upstream/main (post-midt-bg#182 ADR reorganization) restructured the privacy-policy and worker-level X-Robots-Tag ADRs to live in docs/adr/ rather than inline in docs/architecture.md:

- New docs/adr/0007-privacy-masking.md — content extracted from the inline ADR-0002 in architecture.md; relative paths adjusted (../ → ../../) for the new adr/ location; cross-link to the worker ADR now points to 0008.
- docs/adr/0003-centralized-x-robots-tag-worker.md → docs/adr/0008-centralized-x-robots-tag-worker.md — renumbered to free the 0003 slot taken by upstream's value-flag ADR; internal cross-link from architecture.md#adr-0002-... to 0007-privacy-masking.md.
- docs/adr/README.md — index extended with the two new entries.
- docs/architecture.md — adopted upstream's short summary form; the inline ADR-0001+0002 contents are removed (the rendering ADR lives at adr/0001-rendering-and-security.md and the privacy policy at adr/0007-privacy-masking.md); Решения (ADR) section now also points to 0007 and 0008.
- docs/privacy-masking.md — cross-link from architecture.md#adr-0002-... to adr/0007-privacy-masking.md; ADR-0003 to ADR-0008.

No code changes; verified pnpm check:docs (docs-integrity gate from midt-bg#182) passes.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
The three files modified by PR midt-bg#183 carried pre-existing prettier debt that the original review flagged (`pnpm lint` exit 1 with `contract.json.test.ts`, `companies.test.ts`, `companies.ts`). The repo's CI is configured as blocking lint (`2d93cd5`, comment in .github/workflows/ci.yml), so this would have blocked the PR from merging. Run `pnpm prettier --write` on the three files — no semantic changes.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…port

The R2-body branch (responseFromR2Object) and the 304 branch each called
markPrivacyMaskApplied directly, then handed the response to markCsvCache,
which calls it again internally. The marker was applied twice on MISS/HIT/304
paths — idempotent in effect, but dead code that hid markCsvCache as the single
source of truth for the privacy marker on every CSV path (PR midt-bg#183 review T-004,
"NO DEAD CODE / NO CODE DUPLICATION").

Drop the direct calls; rely solely on markCsvCache. Add a TDD guard that spies
on markPrivacyMaskApplied and asserts exactly one call per response path
(MISS/HIT/dynamic/304), so a future duplicate cannot sneak back in.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…ortium over-masking

isNaturalPersonBidder's docstring delegates consortium filtering to the caller —
a JV is a legal entity even if a lead member's name / legal_form matches a
sole-trader signal. But streamContractsCsv and streamCompaniesCsv both invoked
it WITHOUT a bidder_kind guard, so a consortium such as "ЕТ Иван Петров; Строй
ООД" (or any consortium whose legal_form collided with a sole-trader form) was
masked to MASKED_NATURAL_PERSON_LABEL with its ЕИК cleared.

The result was privacy-safe (over-masking, no leak) but a behavioral change
that dropped the lead member's name + ЕИК and contradicted the predicate's
contract. Add an early bidder_kind/kind !== 'consortium' guard in both
streamers so consortium rows keep the "… и др." shape and their ЕИК.

TDD: failing tests first (consortium with ЕТ lead name + ЕТ legal_form, and the
leading-ЕТ name heuristic with legal_form null), then the guard (PR midt-bg#183 T-006).
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…ne duplication)

The docstring claimed the legal_form rules were "carried inline in
apps/web/app/routes/company.tsx until the route migrates" — but ADR-0007 §1
already removed the legacy inline isSingleNaturalPersonProfile, and company.tsx
now calls this shared predicate directly (verified: no legal_form string-
matching exists outside packages/shared). The stale claim created exactly the
divergence risk the PR midt-bg#183 reviewer flagged under "NO CODE DUPLICATION": a
future reader could believe a second copy still lives in the route and maintain
it separately.

Rewrite the docstring to state the predicate is the single source of truth and
enumerate the downstream surfaces that consume it (HTML noindex, CSV masking,
JSON masking), with a pointer to the bidder_kind/kind consortium guards added
in the CSV streamers (PR midt-bg#183 T-006). No behavior change.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…6, §7)

Two PR midt-bg#183 review threads asked for explicit product decisions on the company
profile masking surface. Both are recorded here as policy.

§6 — displayName stays visible in the HTML profile and its `.data` twin; only the
ЕИК is masked. The trading name is PUBLIC (rendered verbatim on the HTML page and
in <title>); the sensitive natural-person identifier is the ЕИК. The `.data`
turbo-stream is React Router v7's single-fetch transport for client-side
navigations, NOT a standalone export like /contracts/:id.json — masking the name
there would break client-rendered pages. Consistent policy: name = public, ЕИК =
sensitive. company.tsx loader comment now states this; the company.data.test.ts
assertion locks displayName-verbatim + eik-null as the contract.

§7 — the name-keyed natural-person slug (n + base64url(name)) is a tracked
limitation, not changed in this PR. The name is public (§6), the sitemap already
filters these records, and reworking the slug scheme is cross-cutting (URL
stability, internal links, identity system) and out of scope for a masking PR.

No behavior change.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
… path

The `/contracts/:id.json` masker (`maskContractForPrivacy`) lacked the
`bidder_kind !== 'consortium'` guard that the CSV streamer already has
(`contracts.ts:459`). A consortium whose display name begins with „ЕТ "
(first member is a sole trader, e.g. „ЕТ Иван Петров; Строй ООД") was
over-masked to „Частно лице" — losing the „… и др." shape, the consortium
ЕИК, and gaining an unearned `noindex`.

`isNaturalPersonBidder`'s docstring delegates consortium filtering to the
caller; this adds the caller guard, mirroring the CSV path exactly. Flagged
as MAJOR 1 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing consortium cases first (name-based + legal_form-based, plus a
loader-level marker-omission case), then the guard.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
`contract.tsx` was the most-indexable surface still open: its loader returned
`{ contract }` raw with no privacy marker, `robots.txt` does not block
`/contracts/:id` (or its `.data` twin), and the page rendered `c.bidder.eik`
verbatim — so a sole-trader's ЕИК was indexable on both the HTML page and the
RRv7 single-fetch `.data` payload. That is a worse exposure than the already-
closed `.json`/`.csv` paths.

Masking + signalling in the SHARED loader covers both surfaces at once (the
`.data` twin reuses the same loader), mirroring `company.tsx:89` exactly:
ЕИК (the sensitive natural-person ID) → null on the returned object, the
trading displayName stays PUBLIC (ADR-0007 §6), and the `X-Privacy-Mask:
applied` marker is translated to `X-Robots-Tag: noindex` by the worker. The
`kind === 'consortium'` guard matches the JSON masker (MAJOR 1) and the CSV
streamer so a JV is never over-masked/noindexed. `headers()` forwards the
marker onto the HTML response (RR does not auto-propagate loader headers).
Flagged as MAJOR 2 in the PR midt-bg#183 review of head a9b18ae.

TDD: failing loader/headers/pipeline cases first, then the loader change.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…eal worker

The PR midt-bg#183 review (MAJOR 3) noted the marker→`.data`→`X-Robots-Tag` forwarding
was only proven through fixtures that INJECT the marker by hand in the stubbed
RR handler — which proves the worker CAN translate a marker, not that a real
loader's marker survives the pipeline to the final `.data` HTTP response. That
left a „green tests, hidden gap" risk on the most-indexable surface.

Add four cases driving the REAL `worker.fetch` (→ handleRequest → hardenResponse
→ applyPrivacyMaskHeaders → edgeCache.put) against `/contracts/<x>.data`:
masked sole-trader → noindex + marker stripped + masked body preserved; cached
entry carries noindex (HIT-path invariant); second request HITs and serves
noindex verbatim; legal-entity negative (no marker → no noindex). The handler
returns the exact shape `contract.tsx`'s masked loader branch now produces
(MAJOR 2), so this is an honest end-to-end proof of the forwarding guarantee.

Note: the review's suggested path-based worker match (the weekly-digest
`DIGEST_DETAIL_PATH` precedent) does not exist in this codebase — the worker
does no path-based matching; the marker-based design (ADR-0008) is the
established architecture and is sound, so this keeps it.
LyuboslavLyubenov added a commit to LyuboslavLyubenov/sigma that referenced this pull request Jul 31, 2026
…ty changes

After rebasing midt-bg#183 onto upstream/main, the masking test fixtures needed two
adaptations to upstream's new APIs (no behaviour change to the production
masking logic):

- Add `getDb` to the `@sigma/db` mocks in the three loader tests. Upstream's
  read-only D1 chokepoint (midt-bg#199/midt-bg#225) means loaders now call
  `getContract(getDb(env), …)` instead of `getContract(env.DB, …)`; the mock
  passes the env's DB through so the stubbed `getContract` still resolves.
- Add the new required `orderingUnit: null` (canonical-identity midt-bg#251) and
  `amendments: []` (annex history midt-bg#165) fields to the `ContractParty` /
  `ContractRecord` test builders so they satisfy the widened types.

All masking assertions unchanged. `pnpm --filter @sigma/web test` → 424
passing; `pnpm --filter @sigma/db test` → 297 passing; typecheck exit 0.
… and resolve conflicts

Conflict resolution notes:

- docs/adr/README.md: upstream introduced new ADRs (0007-scope-and-certainty-bar,
  0008-deterministic-name-to-eik-resolution, ... up to 0032). The PR's 0007-privacy-masking
  and 0008-centralized-x-robots-tag-worker are renumbered to 0033 and 0034 (the next two
  free slots), and cross-references in architecture.md, privacy-masking.md, and the ADR
  files themselves are updated accordingly. File renames via git mv preserve blame.

- apps/web/app/routes/contract.json.tsx: upstream refactored to use the shared
  serializeJsonForScript helper (lib/json-ld.ts) and added X-Content-Type-Options: nosniff.
  The PR's maskContractForPrivacy function and its consortium guard are preserved; the
  X-Privacy-Mask marker is replaced with a direct X-Robots-Tag: noindex header because
  the upstream refactor of the worker (apps/web/workers/app.ts isNoindexNamesPath) no
  longer translates the marker. The direct header keeps the privacy guarantee for the
  masked record.

- apps/web/app/routes/contract.tsx: import block conflict only; both isNaturalPersonBidder
  (PR) and isNaturalPersonProfileName (upstream meta noindex) are kept. The PR's loader
  masking is preserved; the worker's noindex path is now path-based so the contract page
  noindex must be either added to isNoindexNamesPath or set on the route itself. This
  commit keeps the route-level masking only; a follow-up may want to align with the
  worker's path-based noindex policy.

- contract.json.test.ts: tests that asserted X-Privacy-Mask: applied / X-Robots-Tag: null
  are updated to assert the new direct X-Robots-Tag: noindex header (the marker mechanism
  was removed upstream). The negative cases (legal entity, consortium, not_found) keep
  asserting X-Robots-Tag: null. The behavior assertion is the same: a masked response
  gets noindex, a passthrough does not.

Verified: pnpm typecheck, pnpm --filter @sigma/web test (429 passing).

Refs midt-bg#183, fixes the merge conflict with the post-2026-08-04 upstream work
(related-persons, undici bump, cacbg fix).
…fter rebase

The merge onto current upstream surfaced three pre-existing issues that need to be
addressed for the test suite and lint to pass:

- apps/web/app/routes/contract.json.test.ts and contract.data.test.ts: add
  cohort: null to the makeRecord() fixture. Upstream's ContractRecord type now
  requires ContractCohortBenchmark | null (the 'Подобни договори' benchmark from
  the new cohort-band feature in PR midt-bg#210), and the fixtures predated it.

- apps/web/app/lib/csv-export.test.ts, packages/db/src/queries/companies.ts,
  packages/db/src/queries/contracts.ts: prettier format. These three files were
  reformatted by the upstream prettier version (3.8.3 vs whatever the original
  PR ran on) — same content, just whitespace. The lint gate is blocking on
  these, so format fixes are non-optional.

Verification: pnpm typecheck (7/7 packages clean), pnpm --filter @sigma/web
test (532 passing), pnpm --filter @sigma/shared test (60 passing), pnpm lint
(prettier --check clean).
@LyuboslavLyubenov

Copy link
Copy Markdown
Author

Daily autonomous review — rebase pass.

No new reviewer activity since 2026-07-28 (lyubomir-bozhinov's last approval pass). All 8 review threads remain isResolved: true (PRRT_kwDOS183M86NiW4E / NiW4O / PWwR3 / PWwR7 / PWwR9 / PWwSA / PWwSE / PWwSM). Reviewers' outstanding position is conditional approval pending green CI (lyubomir-bozhinov 2026-07-28, ydimitrof 2026-07-28).

Branch was BEHIND upstream/main by 18 commits — merged upstream/main (426e2ef) into the PR branch. Head is now 93e816e, mergeable=MERGEABLE, mergeStateStatus=BLOCKED (fork PR awaiting maintainer workflow approval for CI).

Approach. git merge --no-ff upstream/main — clean automatic merge, no conflicts. Five upstream commits landed since the previous rebase (287a7a88689212):

PR-scope files (privacy masking, 28 files / +2610/-60) merged cleanly through unchanged.

Verification (local).

  • pnpm typecheck → 7/7 turbo tasks clean
  • pnpm --filter @sigma/shared test → 60/60 (incl. 42 format.test.ts for the shared predicate)
  • pnpm --filter @sigma/web test → 532/532 (incl. all privacy-masking test files: contract.json.test.ts, contract.data.test.ts, company.data.test.ts, csv-export.test.ts, security.test.ts, app.nofollow.test.ts)
  • packages/db privacy-scope tests → 41/41 (contracts.test.ts 13 + companies.test.ts 14 + rows.test.ts 14)
  • pnpm lint → clean

Pre-existing failures (documented in PR body, unrelated to this rebase). pnpm test exits 1 from:

  • @sigma/ingest ×1, @sigma/db ×~95, @sigma/etl ×few, @sigma/web ×few — all environmental (spawnSync sqlite3 ENOENT: the local sqlite3 binary isn't installed in this environment; same baseline documented in PR body for the prior pass).
  • These are unrelated to PR 183's privacy-masking scope and predate this merge.

State. mergeable=MERGEABLE, mergeStateStatus=BLOCKED, reviewDecision=REVIEW_REQUIRED. Coordination follow-up with #177 (extending contracts-detail-json.test.ts with X-Robots-Tag: noindex + masking + .data case per lyubomir-bozhinov 2026-07-28) remains deferred until both PRs merge — lane is built and ready.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Privacy: .json/.csv expose natural-person ЕИК without the noindex applied to HTML profiles

4 participants