536 lines
21 KiB
TypeScript
536 lines
21 KiB
TypeScript
import type { CatalogColumn, CatalogTable, WorkspaceDatabase } from "./types.js";
|
|
import { findPhoneNumbersInText } from "libphonenumber-js/max";
|
|
import validator from "validator";
|
|
|
|
export type SensitivityAssessment = "sensitive" | "non_sensitive";
|
|
|
|
export interface SensitivityEvidence {
|
|
kind: "metadata" | "content" | "length" | "ner" | "coverage" | "type";
|
|
ruleId: string;
|
|
label?: string;
|
|
confidence?: number;
|
|
}
|
|
|
|
export interface SensitivityValueObservation {
|
|
columnId: string;
|
|
value: string | null;
|
|
characterLength: number | null;
|
|
}
|
|
|
|
export interface SensitivityScanCoverage {
|
|
kind: "complete" | "sampled";
|
|
observedValues: number;
|
|
}
|
|
|
|
export interface SensitivityTableScan {
|
|
batches: readonly (readonly SensitivityValueObservation[])[];
|
|
coverage: SensitivityScanCoverage;
|
|
}
|
|
|
|
export interface SensitivityScanRequest {
|
|
database: WorkspaceDatabase;
|
|
table: CatalogTable;
|
|
columns: readonly CatalogColumn[];
|
|
valuesPerColumn: number;
|
|
sampleOffset: number;
|
|
sampleSeed: number;
|
|
queryTimeoutMs: number;
|
|
fullScanThreshold?: number;
|
|
}
|
|
|
|
export interface SensitivityValueSource {
|
|
scanTable(
|
|
request: SensitivityScanRequest,
|
|
consume: (batch: readonly SensitivityValueObservation[]) => void | Promise<void>,
|
|
signal: AbortSignal,
|
|
): Promise<SensitivityScanCoverage>;
|
|
}
|
|
|
|
export interface LocalNerCandidate {
|
|
columnId: string;
|
|
text: string;
|
|
}
|
|
|
|
export interface LocalNerEvidence {
|
|
columnId: string;
|
|
label: string;
|
|
confidence: number;
|
|
}
|
|
|
|
export interface SensitivityNerBudget {
|
|
remainingMs: number;
|
|
}
|
|
|
|
/** Optional local detector. It returns evidence only; it never decides a column assessment. */
|
|
export interface LocalNerDetector {
|
|
warmup?(): Promise<void>;
|
|
isReady?(): boolean;
|
|
detect(
|
|
candidates: readonly LocalNerCandidate[],
|
|
signal: AbortSignal,
|
|
deadline: number,
|
|
): Promise<readonly LocalNerEvidence[]>;
|
|
close?(): Promise<void>;
|
|
}
|
|
|
|
export interface SensitivityColumnAssessment {
|
|
columnId: string;
|
|
assessment: SensitivityAssessment;
|
|
proposedSensitive: boolean;
|
|
evidence: readonly SensitivityEvidence[];
|
|
observedValues: number;
|
|
coverage: "metadata" | "complete" | "sampled" | "no_values";
|
|
}
|
|
|
|
export interface SensitivityTableTarget {
|
|
database: WorkspaceDatabase;
|
|
table: CatalogTable;
|
|
columns: readonly CatalogColumn[];
|
|
}
|
|
|
|
const EMAIL = /(?<![\p{L}\p{N}._%+-])[\p{L}\p{N}._%+-]+@[\p{L}\p{N}.-]+\.[\p{L}]{2,63}(?![\p{L}\p{N}._%+-])/giu;
|
|
const DIRECT_IDENTIFIER_NAMES = new Set([
|
|
"address", "birth_date", "codice_fiscale", "date_of_birth", "dob", "email", "e_mail",
|
|
"bic", "first_name", "fiscal_code", "full_name", "iban", "indirizzo", "last_name", "mobile",
|
|
"nome", "passport", "phone", "surname", "swift", "swift_code", "tax_id", "telefono",
|
|
]);
|
|
const CREDENTIAL_NAME = /(?:^|_)(?:api_key|credential|password|passwd|private_key|pwd|secret|token)(?:_|$)/u;
|
|
const HEALTH_NAME = /(?:^|_)(?:anamnesi|clinical|diagnos(?:i|is)|health|medical|patient|patologia|therapy|terapia)(?:_|$)/u;
|
|
const CLINICAL_TERM = /(?:^|[^\p{L}])(?:allergi[ae]|anamnesi|carcinoma|chemioterapia|diabete|diagnos[ei]|epatite|farmac[io]|gravidanza|hiv|metastasi|neoplasia|patologia|radioterapia|referto|terapia|tumore)(?:$|[^\p{L}])/iu;
|
|
const UNSUPPORTED_BINARY_TYPE = /(?:^|\s)(?:binary|blob|bytea|image|varbinary)(?:\s|$|\()/iu;
|
|
const DEEP_TEXT_TYPE = /(?:^|\s)(?:char|character|citext|clob|json|jsonb|nchar|nvarchar|string|text|varchar|xml)(?:\s|$|\()/iu;
|
|
const MAX_NER_CANDIDATES_PER_REQUEST = 128;
|
|
const MAX_CONCURRENT_TABLE_SCANS = 2;
|
|
|
|
export const SENSITIVITY_SAMPLE_PHASES = [
|
|
{ targetValuesPerColumn: 300, additionalValuesPerColumn: 300, sampleSeed: 37, deepTextOnly: false },
|
|
{ targetValuesPerColumn: 1_000, additionalValuesPerColumn: 700, sampleSeed: 73, deepTextOnly: false },
|
|
{ targetValuesPerColumn: 3_000, additionalValuesPerColumn: 2_000, sampleSeed: 109, deepTextOnly: true },
|
|
] as const;
|
|
|
|
function normalizedName(value: string): string {
|
|
return value.normalize("NFKD")
|
|
.replace(/[\u0300-\u036f]/g, "")
|
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
.toLocaleLowerCase("en-US")
|
|
.replace(/[^a-z0-9]+/g, "_")
|
|
.replace(/^_+|_+$/g, "");
|
|
}
|
|
|
|
function boundedCount(value: number | undefined, fallback: number, maximum: number): number {
|
|
return value === undefined || !Number.isSafeInteger(value)
|
|
? fallback
|
|
: Math.max(1, Math.min(value, maximum));
|
|
}
|
|
|
|
function metadataEvidence(column: CatalogColumn): SensitivityEvidence | undefined {
|
|
const ruleId = sensitiveNameRule(column.name);
|
|
return ruleId ? { kind: "metadata", ruleId } : undefined;
|
|
}
|
|
|
|
function nonSensitiveStructuralEvidence(column: CatalogColumn): SensitivityEvidence | undefined {
|
|
if (column.dataType.trim().toLowerCase() !== "bigint") return undefined;
|
|
if (column.isPrimaryKey || column.primaryKeyPosition !== null) {
|
|
return {
|
|
kind: "type",
|
|
ruleId: "type.bigint_primary_key_non_informative",
|
|
label: "non-informative bigint primary key",
|
|
};
|
|
}
|
|
if (normalizedName(column.name) === "pk") {
|
|
return {
|
|
kind: "metadata",
|
|
ruleId: "metadata.bigint_pk_identifier_non_informative",
|
|
label: "non-informative conventional bigint primary-key identifier",
|
|
};
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function sensitiveNameRule(value: string): string | undefined {
|
|
const name = normalizedName(value);
|
|
if (DIRECT_IDENTIFIER_NAMES.has(name)) {
|
|
return "metadata.direct_identifier";
|
|
}
|
|
if (CREDENTIAL_NAME.test(name)) {
|
|
return "metadata.credential";
|
|
}
|
|
if (HEALTH_NAME.test(name)) {
|
|
return "metadata.health";
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
const ITALIAN_FISCAL_CODE = /(?<![A-Z0-9])[A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST][0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z](?![A-Z0-9])/giu;
|
|
const FISCAL_ODD: Record<string, number> = {
|
|
"0": 1, "1": 0, "2": 5, "3": 7, "4": 9, "5": 13, "6": 15, "7": 17, "8": 19, "9": 21,
|
|
A: 1, B: 0, C: 5, D: 7, E: 9, F: 13, G: 15, H: 17, I: 19, J: 21,
|
|
K: 2, L: 4, M: 18, N: 20, O: 11, P: 3, Q: 6, R: 8, S: 12, T: 14,
|
|
U: 16, V: 10, W: 22, X: 25, Y: 24, Z: 23,
|
|
};
|
|
|
|
function validItalianFiscalCode(candidate: string): boolean {
|
|
const value = candidate.toUpperCase();
|
|
if (value.length !== 16) return false;
|
|
let sum = 0;
|
|
for (let index = 0; index < 15; index += 1) {
|
|
const character = value[index]!;
|
|
if (index % 2 === 0) sum += FISCAL_ODD[character] ?? -1000;
|
|
else sum += /\d/u.test(character) ? Number(character) : character.charCodeAt(0) - 65;
|
|
}
|
|
return String.fromCharCode(65 + (sum % 26)) === value[15];
|
|
}
|
|
|
|
function validIban(candidate: string): boolean {
|
|
const value = candidate.replace(/\s+/gu, "").toUpperCase();
|
|
if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/u.test(value)) return false;
|
|
const rearranged = value.slice(4) + value.slice(0, 4);
|
|
let remainder = 0;
|
|
for (const character of rearranged) {
|
|
const digits = /\d/u.test(character) ? character : String(character.charCodeAt(0) - 55);
|
|
for (const digit of digits) remainder = (remainder * 10 + Number(digit)) % 97;
|
|
}
|
|
return remainder === 1;
|
|
}
|
|
|
|
function validPaymentCard(candidate: string): boolean {
|
|
const digits = candidate.replace(/[ -]/gu, "");
|
|
if (!/^\d{13,19}$/u.test(digits) || /^(\d)\1+$/u.test(digits)) return false;
|
|
let sum = 0;
|
|
let double = false;
|
|
for (let index = digits.length - 1; index >= 0; index -= 1) {
|
|
let digit = Number(digits[index]);
|
|
if (double) {
|
|
digit *= 2;
|
|
if (digit > 9) digit -= 9;
|
|
}
|
|
sum += digit;
|
|
double = !double;
|
|
}
|
|
return sum % 10 === 0;
|
|
}
|
|
|
|
function jsonHasSensitiveKey(value: string): boolean {
|
|
const trimmed = value.trim();
|
|
if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) return false;
|
|
try {
|
|
const pending: Array<{ value: unknown; depth: number }> = [{ value: JSON.parse(trimmed), depth: 0 }];
|
|
let visited = 0;
|
|
while (pending.length > 0 && visited < 1_000) {
|
|
const item = pending.pop()!;
|
|
visited += 1;
|
|
if (item.depth > 8 || item.value === null || typeof item.value !== "object") continue;
|
|
if (Array.isArray(item.value)) {
|
|
for (const child of item.value) pending.push({ value: child, depth: item.depth + 1 });
|
|
continue;
|
|
}
|
|
for (const [key, child] of Object.entries(item.value)) {
|
|
if (sensitiveNameRule(key)) return true;
|
|
pending.push({ value: child, depth: item.depth + 1 });
|
|
}
|
|
}
|
|
} catch {
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function contentEvidence(value: string): SensitivityEvidence | undefined {
|
|
if (/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/u.test(value)) {
|
|
return { kind: "content", ruleId: "credential.private_key" };
|
|
}
|
|
if (/(?:^|[^A-Z0-9])AKIA[A-Z0-9]{16}(?![A-Z0-9])/u.test(value)
|
|
|| /(?:^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9_]{30,}(?![A-Za-z0-9_])/u.test(value)
|
|
|| /(?:^|[^A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?![A-Za-z0-9_-])/u.test(value)) {
|
|
return { kind: "content", ruleId: "credential.access_key" };
|
|
}
|
|
if (/(?:^|[^\p{L}\p{N}_])(?:api[_ -]?key|access[_ -]?token|password|passwd|pwd|secret)\s*[:=]\s*[^\s,;]{4,}/iu.test(value)) {
|
|
return { kind: "content", ruleId: "credential.key_value" };
|
|
}
|
|
if (CLINICAL_TERM.test(value)) return { kind: "content", ruleId: "health.clinical_term" };
|
|
for (const match of value.matchAll(EMAIL)) {
|
|
if (validator.isEmail(match[0])) return { kind: "content", ruleId: "pii.email" };
|
|
}
|
|
for (const match of value.matchAll(ITALIAN_FISCAL_CODE)) {
|
|
if (validItalianFiscalCode(match[0])) {
|
|
return { kind: "content", ruleId: "pii.italian_fiscal_code" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/\b(?:passaporto|passport)(?:\s+(?:numero|number|n\.?))?\s*[:#-]?\s*([A-Z0-9]{9})\b/giu)) {
|
|
if (validator.isPassportNumber(match[1]!, "IT")) {
|
|
return { kind: "content", ruleId: "pii.passport_number" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/\bC[A-Z]\d{5}[A-Z]{2}\b/giu)) {
|
|
if (validator.isIdentityCard(match[0], "IT")) {
|
|
return { kind: "content", ruleId: "pii.identity_card" };
|
|
}
|
|
}
|
|
if (/\b(?:patente(?:\s+di\s+guida)?|driving\s+licen[cs]e)(?:\s+(?:numero|number|n\.?))?\s*[:#-]?\s*[A-Z0-9]{8,12}\b/iu.test(value)) {
|
|
return { kind: "content", ruleId: "pii.drivers_license_number" };
|
|
}
|
|
for (const match of value.matchAll(/(?<![A-Z0-9])[A-Z]{2}\d{2}(?:\s?[A-Z0-9]){11,30}(?![A-Z0-9])/giu)) {
|
|
if (validIban(match[0])) return { kind: "content", ruleId: "financial.iban" };
|
|
}
|
|
for (const match of value.matchAll(/(?<!\d)(?:\d[ -]?){13,19}(?!\d)/gu)) {
|
|
if (validPaymentCard(match[0])) {
|
|
return { kind: "content", ruleId: "financial.payment_card" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/(?<![A-Z0-9])[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?(?![A-Z0-9])/giu)) {
|
|
const before = value.slice(Math.max(0, (match.index ?? 0) - 24), match.index ?? 0);
|
|
if (/\b(?:bic|swift)\s*[:=-]?\s*$/iu.test(before) && validator.isBIC(match[0])) {
|
|
return { kind: "content", ruleId: "financial.bic" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/(?<!\d)(?:IT[ .-]?)?\d{11}(?!\d)/giu)) {
|
|
const candidate = match[0].replace(/[ .-]/gu, "");
|
|
if (validator.isVAT(candidate.replace(/^IT/iu, ""), "IT")) {
|
|
return { kind: "content", ruleId: "pii.italian_vat" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/(?<![A-F0-9])(?:[A-F0-9]{2}[:-]){5}[A-F0-9]{2}(?![A-F0-9])/giu)) {
|
|
if (validator.isMACAddress(match[0])) {
|
|
return { kind: "content", ruleId: "network.mac_address" };
|
|
}
|
|
}
|
|
for (const match of value.matchAll(/(?<![A-F0-9:.])[A-F0-9:.]{3,45}(?![A-F0-9:.])/giu)) {
|
|
if (validator.isIP(match[0])) return { kind: "content", ruleId: "network.ip_address" };
|
|
}
|
|
for (const match of value.matchAll(/(?<![A-F0-9-])[0-9A-F]{8}-[0-9A-F]{4}-[1-8][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}(?![A-F0-9-])/giu)) {
|
|
if (validator.isUUID(match[0])) return { kind: "content", ruleId: "pii.uuid" };
|
|
}
|
|
for (const match of value.matchAll(/\b(?:https?|ftp):\/\/[^\s<>"']+/giu)) {
|
|
const candidate = match[0].replace(/[.,;:!?\])}]+$/u, "");
|
|
if (validator.isURL(candidate, { require_protocol: true })) {
|
|
return { kind: "content", ruleId: "network.url" };
|
|
}
|
|
}
|
|
if (findPhoneNumbersInText(value, "IT").some((match) => match.number.isValid())) {
|
|
return { kind: "content", ruleId: "pii.phone_number" };
|
|
}
|
|
if (jsonHasSensitiveKey(value)) {
|
|
return { kind: "content", ruleId: "pii.json_sensitive_key" };
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
interface ColumnState {
|
|
column: CatalogColumn;
|
|
evidence: SensitivityEvidence[];
|
|
nonSensitiveEvidence?: SensitivityEvidence;
|
|
observedValues: number;
|
|
nerCandidates: string[];
|
|
coverage: "metadata" | "complete" | "sampled" | "no_values";
|
|
sampledTarget: number;
|
|
}
|
|
|
|
/** Sole decision module for local column-level sensitivity assessments. */
|
|
export class SensitivityClassifier {
|
|
constructor(
|
|
private readonly values: SensitivityValueSource,
|
|
private readonly detector?: LocalNerDetector,
|
|
private readonly options: {
|
|
queryTimeoutMs?: number;
|
|
nerConfidenceThreshold?: number;
|
|
maxNerValuesPerColumn?: number;
|
|
maxNerCandidatesPerTable?: number;
|
|
now?: () => number;
|
|
} = {},
|
|
) {}
|
|
|
|
async assess(
|
|
targets: readonly SensitivityTableTarget[],
|
|
signal: AbortSignal,
|
|
sharedNerBudget?: SensitivityNerBudget,
|
|
onActivity?: (message: string) => void | Promise<void>,
|
|
): Promise<readonly SensitivityColumnAssessment[]> {
|
|
const now = this.options.now ?? Date.now;
|
|
const maxNerValuesPerColumn = boundedCount(this.options.maxNerValuesPerColumn, 8, 8);
|
|
const states = new Map<string, ColumnState>();
|
|
for (const target of targets) {
|
|
for (const column of target.columns) {
|
|
const nonSensitiveEvidence = nonSensitiveStructuralEvidence(column);
|
|
const metadataMatch = nonSensitiveEvidence ? undefined : metadataEvidence(column);
|
|
const binary = !nonSensitiveEvidence && UNSUPPORTED_BINARY_TYPE.test(column.dataType);
|
|
states.set(column.id, {
|
|
column,
|
|
evidence: metadataMatch
|
|
? [metadataMatch]
|
|
: binary
|
|
? [{ kind: "type", ruleId: "type.binary_uninspectable" }]
|
|
: [],
|
|
...(nonSensitiveEvidence ? { nonSensitiveEvidence } : {}),
|
|
observedValues: 0,
|
|
nerCandidates: [],
|
|
coverage: nonSensitiveEvidence || metadataMatch || binary ? "metadata" : "no_values",
|
|
sampledTarget: 0,
|
|
});
|
|
}
|
|
}
|
|
|
|
const completeTables = new Set<string>();
|
|
for (const [phaseIndex, phase] of SENSITIVITY_SAMPLE_PHASES.entries()) {
|
|
for (let offset = 0; offset < targets.length; offset += MAX_CONCURRENT_TABLE_SCANS) {
|
|
signal.throwIfAborted();
|
|
const batchNumber = Math.floor(offset / MAX_CONCURRENT_TABLE_SCANS) + 1;
|
|
const batchCount = Math.ceil(targets.length / MAX_CONCURRENT_TABLE_SCANS);
|
|
await onActivity?.(
|
|
`Scanning source data: pass ${phaseIndex + 1} of ${SENSITIVITY_SAMPLE_PHASES.length}, table batch ${batchNumber} of ${batchCount}.`,
|
|
);
|
|
signal.throwIfAborted();
|
|
const peerController = new AbortController();
|
|
const scanSignal = AbortSignal.any([signal, peerController.signal]);
|
|
try {
|
|
await Promise.all(targets.slice(offset, offset + MAX_CONCURRENT_TABLE_SCANS).map(async (target) => {
|
|
if (completeTables.has(target.table.id)) return;
|
|
const columns = target.columns.filter((column) => {
|
|
const state = states.get(column.id)!;
|
|
return state.evidence.length === 0 && !state.nonSensitiveEvidence
|
|
&& (!phase.deepTextOnly || DEEP_TEXT_TYPE.test(column.dataType));
|
|
});
|
|
if (columns.length === 0) return;
|
|
const coverage = await this.values.scanTable({
|
|
...target,
|
|
columns,
|
|
valuesPerColumn: phase.additionalValuesPerColumn,
|
|
sampleOffset: phase.targetValuesPerColumn - phase.additionalValuesPerColumn,
|
|
sampleSeed: phase.sampleSeed,
|
|
queryTimeoutMs: this.options.queryTimeoutMs ?? 5_000,
|
|
...(phaseIndex === 0 ? { fullScanThreshold: 1_000 } : {}),
|
|
}, (batch) => {
|
|
for (const item of batch) {
|
|
if (item.value === null) continue;
|
|
const state = states.get(item.columnId);
|
|
if (!state || state.evidence.length > 0) continue;
|
|
state.observedValues += 1;
|
|
if ((item.characterLength ?? item.value.length) > 500) {
|
|
state.evidence.push({ kind: "length", ruleId: "text.over_500_characters" });
|
|
continue;
|
|
}
|
|
const match = contentEvidence(item.value);
|
|
if (match) {
|
|
state.evidence.push(match);
|
|
continue;
|
|
}
|
|
if (state.nerCandidates.length < maxNerValuesPerColumn
|
|
&& !state.nerCandidates.includes(item.value)) {
|
|
state.nerCandidates.push(item.value);
|
|
}
|
|
}
|
|
}, scanSignal);
|
|
for (const column of columns) {
|
|
const state = states.get(column.id)!;
|
|
state.sampledTarget = Math.max(state.sampledTarget, phase.targetValuesPerColumn);
|
|
state.coverage = coverage.kind === "complete"
|
|
? "complete"
|
|
: state.observedValues === 0 ? "no_values" : "sampled";
|
|
}
|
|
if (coverage.kind === "complete") completeTables.add(target.table.id);
|
|
}));
|
|
} catch (error) {
|
|
peerController.abort(error);
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
const nerBudget = sharedNerBudget ?? { remainingMs: 10_000 };
|
|
if (this.detector && (this.detector.isReady?.() ?? true) && !signal.aborted
|
|
&& nerBudget.remainingMs > 0) {
|
|
const maxCandidates = boundedCount(this.options.maxNerCandidatesPerTable, 2, 1_024);
|
|
const threshold = this.options.nerConfidenceThreshold ?? 0.8;
|
|
for (const [targetIndex, target] of targets.entries()) {
|
|
signal.throwIfAborted();
|
|
if (nerBudget.remainingMs <= 0) break;
|
|
const candidates: LocalNerCandidate[] = [];
|
|
candidateSelection: for (let valueIndex = 0; valueIndex < maxNerValuesPerColumn; valueIndex += 1) {
|
|
for (const column of target.columns) {
|
|
const state = states.get(column.id)!;
|
|
if (state.evidence.length > 0 || state.nonSensitiveEvidence) continue;
|
|
const text = state.nerCandidates[valueIndex];
|
|
if (text === undefined) continue;
|
|
candidates.push({ columnId: column.id, text });
|
|
if (candidates.length >= maxCandidates) break candidateSelection;
|
|
}
|
|
}
|
|
if (candidates.length === 0) continue;
|
|
await onActivity?.(
|
|
`Running local entity detection: table ${targetIndex + 1} of ${targets.length}.`,
|
|
);
|
|
signal.throwIfAborted();
|
|
const startedAt = now();
|
|
const deadline = startedAt + nerBudget.remainingMs;
|
|
try {
|
|
for (let offset = 0; offset < candidates.length; offset += MAX_NER_CANDIDATES_PER_REQUEST) {
|
|
if (signal.aborted || now() >= deadline) break;
|
|
try {
|
|
const detected = await this.detector.detect(
|
|
candidates.slice(offset, offset + MAX_NER_CANDIDATES_PER_REQUEST),
|
|
signal,
|
|
deadline,
|
|
);
|
|
for (const item of detected) {
|
|
const state = states.get(item.columnId);
|
|
if (!state || state.evidence.length > 0 || !Number.isFinite(item.confidence)
|
|
|| item.confidence < threshold || item.confidence > 1) continue;
|
|
const label = normalizedName(item.label).slice(0, 80);
|
|
if (!label) continue;
|
|
state.evidence.push({
|
|
kind: "ner",
|
|
ruleId: "ner.entity",
|
|
label,
|
|
confidence: item.confidence,
|
|
});
|
|
}
|
|
} catch {
|
|
// NER is optional: deterministic findings and scan coverage remain authoritative.
|
|
break;
|
|
}
|
|
}
|
|
} finally {
|
|
nerBudget.remainingMs = Math.max(0, nerBudget.remainingMs - Math.max(1, now() - startedAt));
|
|
}
|
|
}
|
|
}
|
|
|
|
return targets.flatMap((target) => target.columns.map((column) => {
|
|
const state = states.get(column.id)!;
|
|
const sensitive = state.evidence.length > 0;
|
|
const coverage = state.nonSensitiveEvidence
|
|
? "metadata"
|
|
: state.observedValues === 0 && !sensitive ? "no_values" : state.coverage;
|
|
const coverageEvidence: SensitivityEvidence[] = sensitive
|
|
? state.evidence
|
|
: state.nonSensitiveEvidence
|
|
? [state.nonSensitiveEvidence]
|
|
: [{
|
|
kind: "coverage",
|
|
ruleId: coverage === "complete"
|
|
? "coverage.complete"
|
|
: coverage === "no_values"
|
|
? "coverage.no_values"
|
|
: `coverage.sampled_${state.sampledTarget}`,
|
|
}];
|
|
return {
|
|
columnId: column.id,
|
|
assessment: sensitive ? "sensitive" : "non_sensitive",
|
|
proposedSensitive: sensitive,
|
|
evidence: coverageEvidence,
|
|
observedValues: state.observedValues,
|
|
coverage,
|
|
};
|
|
}));
|
|
}
|
|
|
|
/** Convenience for focused callers and rule-level tests. Production orchestration uses assess(). */
|
|
async assessTable(
|
|
target: SensitivityTableTarget,
|
|
signal: AbortSignal,
|
|
_retiredRunDeadline?: number,
|
|
nerBudget?: SensitivityNerBudget,
|
|
): Promise<readonly SensitivityColumnAssessment[]> {
|
|
return await this.assess([target], signal, nerBudget);
|
|
}
|
|
}
|