/** * src/services/pii-gate-service.ts * ================================== * 0pt.pii_* — the GDPR guardrail (fail-closed). Enforced by default wherever * a SourceQueryService is constructed; consulted by workers before they * persist anything for a personal-data source. * * Owns 0pt.pii_policy.schema.v1 and the in-memory identity registry that * backs the subject rights surfaces (access/erasure, GDPR art. 15/17) and * the retention worker (GDPR art. 5(1)(e)). Every decision is emitted to * AUD0 as risk L3 events so CL0UD gets an audit trail without polling 0pt. * * Directory domains known to publish personuppgifter (ratsit.se, …) are * pre-classified as personal: until a PiiPolicy with a recorded lawful * basis exists for them, the gate REJECTS storage/query of those sources. */ import { createHash } from "node:crypto"; import type { PiiPolicy, CreatePiiPolicyInput, PiiIdentityKey, PiiErasureRequest, PiiAccessStatement, ProcessingPurpose, } from "../types/pii"; import type { Source } from "../types/source"; import { createAud0Client, type Aud0Client, type Aud0Event } from "../clients/aud0-client"; /** Domain publishes personuppgifter (directory/register listings). */ const KNOWN_DIRECTORY_DOMAINS = [ "ratsit.se", "merinfo.se", "hitta.se", "mrkoll.se", "eniro.se", "birthday.se", "upplysning.se", ]; const DECISION_TEMPLATE = "PII source %s: %s"; export class PiiPolicyExistsError extends Error {} export class PiiLegalBasisError extends Error {} export class PiiMinimisationError extends Error {} export class PiiRetentionError extends Error {} export class PiiRobotsRateError extends Error {} export class PiiEntityLinkageError extends Error {} export class PiiGateService { private policies: Map = new Map(); private registry: PiiIdentityKey[] = []; private aud0: Aud0Client; constructor(opts?: { aud0BaseUrl?: string }) { this.aud0 = createAud0Client(opts?.aud0BaseUrl); } /** True if the source either self-flags or is a known directory domain. */ classifySourcePersonal(source: Pick): boolean { if (source.touches_personal_data === true) return true; if (source.source_type !== "web" && source.source_type !== "api") return false; const host = (source.name || "").toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, ""); return KNOWN_DIRECTORY_DOMAINS.some((d) => host === d || host.endsWith("." + d)); } /* ------------------------------------------------------------------ * * Policies * ------------------------------------------------------------------ */ async createPiiPolicy(input: CreatePiiPolicyInput): Promise { if (this.policies.has(input.source_id)) { throw new Error(`PiiPolicy already exists for source ${input.source_id}`); } // Hard validation — a policy is the lawful-basis gate, so it cannot be // written with a half-legal posture. if (!input.basis_ref.trim()) throw new Error("basis_ref is required (LIA id, consent id, contract clause or legal provision)"); if (!Number.isFinite(input.retention_days) || input.retention_days < 0) { throw new Error("retention_days must be a non-negative integer (0 = fetch-and-drop)"); } if (!Array.isArray(input.field_allowlist) || input.field_allowlist.length === 0) { throw new Error("field_allowlist must contain at least one field (data minimisation)"); } // Recorded decision (Simon, 2026-08-31): legitimate interest is accepted for // BUSINESS CONTACTS — personal data only in correspondence with a company/org // entity. Enforce that posture so "B2B-kontakt, företagskopplad" cannot be // bypassed by a lazily-written policy. const purpose: ProcessingPurpose = input.purpose ?? "business_contact"; const entityLinkedOnly = input.entity_linked_only ?? input.legal_basis === "legitimate_interest"; if (input.legal_basis === "legitimate_interest") { if (purpose !== "business_contact") { throw new Error("legitimate_interest is only accepted with purpose=business_contact (recorded decision 2026-08-31)"); } if (!entityLinkedOnly) { throw new Error("legitimate_interest requires entity_linked_only=true — personal data must be bound to a company/org entity"); } } const now = new Date().toISOString(); const policy: PiiPolicy = { source_id: input.source_id, tenant_id: input.tenant_id, project_id: input.project_id, touches_personal_data: true, legal_basis: input.legal_basis, purpose, entity_linked_only: entityLinkedOnly, basis_ref: input.basis_ref, retention_days: input.retention_days, field_allowlist: [...input.field_allowlist], pseudonymize_keys: input.pseudonymize_keys ?? true, robots_and_rate_confirmed: input.robots_and_rate_confirmed ?? false, created_at: now, updated_at: null, created_by: input.created_by ?? null, }; this.policies.set(input.source_id, policy); await this.safeEmit({ event_id: `evt_0pt_pii_policy_created_${input.source_id}`, event_type: "0pt.pii_policy_created", capability_id: "0pt.pii_policy_created", tenant_id: input.tenant_id, project_id: input.project_id, actor_id: input.created_by ?? "system", resource_type: "source_pii_policy", resource_id: input.source_id, risk_level: "L3", payload: { legal_basis: input.legal_basis, purpose, entity_linked_only: entityLinkedOnly, retention_days: input.retention_days, field_count: input.field_allowlist.length, }, }); return policy; } async getPiiPolicy(sourceId: string): Promise { return this.policies.get(sourceId) ?? null; } async listPiiPolicies(tenantId?: string): Promise { const all = Array.from(this.policies.values()); return tenantId ? all.filter((p) => p.tenant_id === tenantId) : all; } /* ------------------------------------------------------------------ * * Enforcement (fail-closed) * ------------------------------------------------------------------ */ /** * Gate for a store/query of `fields` against `source`. Throws unless the * source is non-personal or a lawful, minimised, retention-bounded, * robots/rate-confirmed policy is on record. */ async assertCanStore( source: Pick, fields: string[], tenantId: string, ): Promise { if (!this.classifySourcePersonal(source)) return; const policy = this.policies.get(source.source_id); if (!policy) { throw new PiiLegalBasisError( DECISION_TEMPLATE.replace("%s", source.source_id).replace( "%s", `is a personal-data source with no PiiPolicy on record — a lawful basis (${KNOWN_DIRECTORY_DOMAINS.includes(source.name || "") ? "including robots.txt + rate limit confirmation" : "art. 6 GDPR"}) must be registered before any processing`, ), ); } if (policy.retention_days === 0 && fields.length > 0) { throw new PiiRetentionError( DECISION_TEMPLATE.replace("%s", source.source_id).replace( "%s", "policy forbids retention (retention_days = 0); no fields may be stored", ), ); } const disallowed = fields.filter((f) => !policy.field_allowlist.includes(f)); if (disallowed.length > 0) { throw new PiiMinimisationError( DECISION_TEMPLATE.replace("%s", source.source_id).replace( "%s", `field(s) outside the allowlist: ${disallowed.join(", ")} (GDPR art. 5(1)(c) minimisation)`, ), ); } if ((source.source_type === "web" || source.source_type === "api") && !policy.robots_and_rate_confirmed) { throw new PiiRobotsRateError( DECISION_TEMPLATE.replace("%s", source.source_id).replace( "%s", "robots.txt / rate-limit not confirmed — required for web & api personal-data sources; re-check the source terms (do not hardcode)", ), ); } } /* ------------------------------------------------------------------ * * Subject rights: access (art. 15) & erasure (art. 17), retention (art. 5) * ------------------------------------------------------------------ */ /** * Register that one value was stored. Only hashes are persisted; the * plaintext identity never reaches the registry. */ async recordStored(input: { source: Pick; tenantId: string; identityKey: string; subjectId: string; field: string; artifactRef?: string; /** Company/org entity the value is bound to (orgnr/rgs/LEI). REQUIRED when the policy is entity_linked_only. */ entityId?: string; }): Promise { await this.assertCanStore(input.source, [input.field], input.tenantId); const policy = this.policies.get(input.source.source_id)!; if (policy.entity_linked_only && !input.entityId) { throw new PiiEntityLinkageError( DECISION_TEMPLATE.replace("%s", input.source.source_id).replace( "%s", "policy requires entity linkage (business contact, recorded decision 2026-08-31) — pass entityId (orgnr/rgs/LEI); personal data may only be stored in correspondence with a company/org entity", ), ); } const now = Date.now(); const key: PiiIdentityKey = { key_hash: hash256(`${sourceIdSalt(input.source.source_id)}:${input.identityKey}`), subject_hash: hash256(input.subjectId), entity_hash: input.entityId ? hash256(normaliseEntity(input.entityId)) : null, source_id: input.source.source_id, tenant_id: input.tenantId, field: input.field, artifact_ref: input.artifactRef ?? null, stored_at: new Date(now).toISOString(), expires_at: new Date(now + policy.retention_days * 86_400_000).toISOString(), status: "active", }; this.registry.push(key); await this.safeEmit({ event_id: `evt_0pt_pii_retained_${input.source.source_id}_${key.key_hash.slice(0, 12)}`, event_type: "0pt.pii_data_retained", capability_id: "0pt.pii_retain_identity", tenant_id: input.tenantId, project_id: "", actor_id: "system", resource_type: "pii_identity_key", resource_id: key.key_hash, risk_level: "L3", payload: { source_id: input.source.source_id, field: input.field, expires_at: key.expires_at, entity_linked: key.entity_hash !== null, }, }); return key; } /** Right of access — everything currently held on a subject across sources. */ async accessStatement(subjectHash: string): Promise { const rows = this.registry.filter((r) => r.subject_hash === subjectHash && r.status === "active"); return { subject_hash: subjectHash, rows, generated_at: new Date().toISOString() }; } /** Right to erasure — tombstone every held row for the subject. */ async erase(request: PiiErasureRequest): Promise { let count = 0; for (const row of this.registry) { if (row.subject_hash === request.subject_hash && row.status === "active") { row.status = "erased"; count += 1; } } await this.safeEmit({ event_id: `evt_0pt_pii_erased_${request.subject_hash.slice(0, 12)}_${Date.now()}`, event_type: "0pt.pii_erased", capability_id: "0pt.pii_erase", tenant_id: "", project_id: "", actor_id: request.actor_id ?? "system", resource_type: "pii_subject", resource_id: request.subject_hash, risk_level: "L3", payload: { reason: request.reason, row_count: count }, }); return count; } /** Storage limitation — purge rows past their retention deadline. */ async enforceRetention(now: Date = new Date()): Promise<{ purged: number }> { let purged = 0; const keep: PiiIdentityKey[] = []; for (const row of this.registry) { if (row.expires_at <= now.toISOString() && row.status === "active") { row.status = "purged"; purged += 1; } else { keep.push(row); } } if (purged > 0) { await this.safeEmit({ event_id: `evt_0pt_pii_retention_${now.getTime()}`, event_type: "0pt.pii_retention_purged", capability_id: "0pt.pii_enforce_retention", tenant_id: "", project_id: "", actor_id: "system", resource_type: "pii_identity_key", resource_id: now.toISOString(), risk_level: "L3", payload: { row_count: purged }, }); } return { purged }; } /* ------------------------------------------------------------------ * * Log hygiene — no personuppgifter in logs/metrics/traces * ------------------------------------------------------------------ */ /** Scrub personnummer, e-mail and Swedish phone numbers from a log line. */ redact(line: string): string { return line .replace(/\b\d{8}[-–]\d{4}\b/g, "[PERSONNUMMER]") .replace(/\b\d{6}[-–]\d{4}\b/g, "[PERSONNUMMER]") .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[EMAIL]") .replace(/(?:\+46|0046|0)\s?[1-9][\d\s.-]{7,13}/g, "[TELEFON]"); } /* ------------------------------------------------------------------ */ private async safeEmit(event: Omit): Promise { const full: Aud0Event = { ...event, app_id: "0pt", created_at: new Date().toISOString(), }; try { await this.aud0.ingestEvent(full); } catch { // Audit is important but must never take down a compliance decision or // a retention pass. The caller's state change has already happened. } } } function sourceIdSalt(sourceId: string): string { return `0pt-pii-v1:${sourceId}`; } /** Normalise an org/rgs nummer or LEI to canonical digits/letters before hashing. */ function normaliseEntity(entityId: string): string { return entityId.replace(/[^0-9A-Za-z]/g, "").toUpperCase(); } /** sha256 hex digest — never the plaintext. */ export function hash256(value: string): string { return createHash("sha256").update(value, "utf8").digest("hex"); }