open-privacy-protocol 0.0.0-stage → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,300 @@
1
+ // Load, validate and apply Open Privacy Protocol documents (https://openprivacyprotocol.com/spec/).
2
+ // A port of the reference Python implementation; behaviour must stay identical.
3
+ import { Ajv2020 } from "ajv/dist/2020.js";
4
+ import YAML from "yaml";
5
+ import { BASELINE_CATALOG, PRESETS_DOCUMENT, SCHEMAS } from "./data.js";
6
+ export const SPEC_VERSION = "0.1.0.dev0";
7
+ export const SENSITIVITY = ["public", "internal", "confidential", "restricted"];
8
+ export const HANDLING = ["allow", "generalize", "pseudonymize", "redact", "block"];
9
+ export const DESTINATIONS = ["internal", "partner", "external_ai", "public"];
10
+ /** Strictness order of actions (spec section 5, step 4). */
11
+ export const ACTION_ORDER = ["allow", "generalize", "pseudonymize", "redact", "review", "block"];
12
+ export const DEFAULT_RULES = {
13
+ public: { internal: "allow", partner: "allow", external_ai: "allow", public: "allow" },
14
+ internal: { internal: "allow", partner: "allow", external_ai: "allow", public: "review" },
15
+ confidential: { internal: "allow", partner: "handling", external_ai: "handling", public: "block" },
16
+ restricted: { internal: "handling", partner: "block", external_ai: "block", public: "block" },
17
+ };
18
+ /** A document is invalid; `problems` lists every issue. */
19
+ export class OppError extends Error {
20
+ problems;
21
+ constructor(problems) {
22
+ const list = Array.isArray(problems) ? problems : [problems];
23
+ super(list.join("; "));
24
+ this.name = "OppError";
25
+ this.problems = list;
26
+ }
27
+ }
28
+ const ajv = new Ajv2020({ allErrors: true, strict: false, validateFormats: false });
29
+ const validators = new Map();
30
+ /** The JSON Schema for a document kind. */
31
+ export function schema(kind) {
32
+ return SCHEMAS[kind];
33
+ }
34
+ /** A document from a YAML or JSON string, or an object. */
35
+ export function read(src) {
36
+ if (typeof src !== "string")
37
+ return src;
38
+ const doc = YAML.parse(src);
39
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc))
40
+ throw new OppError("an OPP document must be a mapping");
41
+ return doc;
42
+ }
43
+ export function kindOf(doc) {
44
+ if ("presets" in doc)
45
+ return "presets";
46
+ if ("classes" in doc)
47
+ return "catalog";
48
+ if ("catalog" in doc)
49
+ return "model";
50
+ throw new OppError("not an OPP document: no 'classes' (catalog) or 'catalog' (model) at the root");
51
+ }
52
+ export function schemaErrors(doc, kind) {
53
+ const k = kind ?? kindOf(doc);
54
+ let v = validators.get(k);
55
+ if (!v) {
56
+ v = ajv.compile(schema(k));
57
+ validators.set(k, v);
58
+ }
59
+ if (v(doc))
60
+ return [];
61
+ return (v.errors ?? [])
62
+ .map((e) => `${e.instancePath.replace(/^\//, "") || "(root)"}: ${e.message ?? "invalid"}`)
63
+ .sort();
64
+ }
65
+ const idx = (order, v) => order.indexOf(v);
66
+ export class Catalog {
67
+ doc;
68
+ name;
69
+ version;
70
+ classes;
71
+ constructor(doc) {
72
+ const errs = schemaErrors(doc, "catalog");
73
+ const groups = new Set((doc.groups ?? []).map((g) => g.id));
74
+ const sources = new Set((doc.references ?? []).map((s) => s.id));
75
+ const seen = new Set();
76
+ for (const c of doc.classes ?? []) {
77
+ if (seen.has(c.id))
78
+ errs.push(`classes: duplicate id ${c.id}`);
79
+ seen.add(c.id);
80
+ if (!groups.has(c.group))
81
+ errs.push(`classes/${c.id}: unknown group ${c.group}`);
82
+ else if (!c.id.startsWith(`${c.group}.`))
83
+ errs.push(`classes/${c.id}: id must start with its group '${c.group}.'`);
84
+ for (const r of c.refs ?? [])
85
+ if (!sources.has(r.source))
86
+ errs.push(`classes/${c.id}: unknown reference source ${r.source}`);
87
+ }
88
+ if (errs.length)
89
+ throw new OppError(errs);
90
+ this.doc = doc;
91
+ this.name = doc.name;
92
+ this.version = doc.version;
93
+ this.classes = new Map(doc.classes.map((c) => [c.id, c]));
94
+ }
95
+ has(id) {
96
+ return this.classes.has(id);
97
+ }
98
+ get(id) {
99
+ const c = this.classes.get(id);
100
+ if (!c)
101
+ throw new OppError(`unknown class ${id}`);
102
+ return c;
103
+ }
104
+ }
105
+ let baselineCache;
106
+ /** The baseline catalog that ships with this version of the standard. */
107
+ export function baseline() {
108
+ return (baselineCache ??= new Catalog(BASELINE_CATALOG));
109
+ }
110
+ function stricter(a, b, order) {
111
+ return idx(order, a) >= idx(order, b) ? a : b;
112
+ }
113
+ /** A privacy model bound to its catalog, with every id resolved. */
114
+ export class Model {
115
+ doc;
116
+ catalog;
117
+ settings = new Map();
118
+ concepts = new Map();
119
+ identifiers = new Map();
120
+ patterns = new Map();
121
+ rules;
122
+ overrides;
123
+ constructor(src, catalog) {
124
+ const doc = read(src);
125
+ const schemaProblems = schemaErrors(doc, "model");
126
+ if (schemaProblems.length)
127
+ throw new OppError(schemaProblems);
128
+ this.doc = doc;
129
+ this.catalog = catalog ?? baseline();
130
+ const errs = [];
131
+ if (doc.catalog.name !== this.catalog.name)
132
+ errs.push(`catalog: model uses '${doc.catalog.name}', loaded catalog is '${this.catalog.name}'`);
133
+ for (const st of doc.classifications ?? []) {
134
+ const cid = st.class;
135
+ if (!this.catalog.has(cid)) {
136
+ errs.push(`classifications/${cid}: not a class of the '${this.catalog.name}' catalog`);
137
+ continue;
138
+ }
139
+ if (this.settings.has(cid))
140
+ errs.push(`classifications/${cid}: listed more than once`);
141
+ const base = this.catalog.get(cid);
142
+ if ("sensitivity" in st && idx(SENSITIVITY, st.sensitivity) < idx(SENSITIVITY, base.sensitivity))
143
+ errs.push(`classifications/${cid}: sensitivity lower than the catalog's`);
144
+ if ("handling" in st && idx(HANDLING, st.handling) < idx(HANDLING, base.handling))
145
+ errs.push(`classifications/${cid}: handling less protective than the catalog's`);
146
+ this.settings.set(cid, st);
147
+ }
148
+ for (const c of doc.concepts ?? []) {
149
+ if (this.catalog.has(c.id) || this.concepts.has(c.id))
150
+ errs.push(`concepts/${c.id}: id already used`);
151
+ if (!this.catalog.has(c.extends)) {
152
+ errs.push(`concepts/${c.id}: extends unknown class ${c.extends}`);
153
+ continue;
154
+ }
155
+ const st = this.settings.get(c.extends) ?? {};
156
+ const base = { ...this.catalog.get(c.extends), ...(st.sensitivity ? { sensitivity: st.sensitivity } : {}), ...(st.handling ? { handling: st.handling } : {}) };
157
+ if ("sensitivity" in c && idx(SENSITIVITY, c.sensitivity) < idx(SENSITIVITY, base.sensitivity))
158
+ errs.push(`concepts/${c.id}: sensitivity lower than ${c.extends}`);
159
+ if ("handling" in c && idx(HANDLING, c.handling) < idx(HANDLING, base.handling))
160
+ errs.push(`concepts/${c.id}: handling less protective than ${c.extends}`);
161
+ this.concepts.set(c.id, c);
162
+ }
163
+ for (const i of doc.identifiers ?? []) {
164
+ if (!this.known(i.class))
165
+ errs.push(`identifiers/${i.id}: unknown class ${i.class}`);
166
+ try {
167
+ this.patterns.set(i.id, new RegExp(i.pattern));
168
+ }
169
+ catch (e) {
170
+ errs.push(`identifiers/${i.id}: invalid pattern (${e.message})`);
171
+ }
172
+ this.identifiers.set(i.id, i);
173
+ }
174
+ for (const t of doc.terms ?? [])
175
+ if (!this.known(t.class))
176
+ errs.push(`terms/${t.term}: unknown class ${t.class}`);
177
+ for (const s of doc.sources) {
178
+ if (/:\/\/[^/@\s]*:[^/@\s]*@/.test(s.locator))
179
+ errs.push(`sources/${s.id}: locator contains credentials`);
180
+ for (const d of s.datasets) {
181
+ for (const f of d.fields ?? []) {
182
+ for (const c of f.classes ?? [])
183
+ if (!this.known(c.class))
184
+ errs.push(`sources/${s.id}/${d.name}/${f.name}: unknown class ${c.class}`);
185
+ if ("identifier" in f && !this.identifiers.has(f.identifier))
186
+ errs.push(`sources/${s.id}/${d.name}/${f.name}: unknown identifier ${f.identifier}`);
187
+ }
188
+ for (const c of d.topics ?? [])
189
+ if (!this.known(c.class))
190
+ errs.push(`sources/${s.id}/${d.name}: unknown topic class ${c.class}`);
191
+ }
192
+ }
193
+ if (errs.length)
194
+ throw new OppError(errs);
195
+ const rules = doc.rules ?? {};
196
+ this.rules = Object.fromEntries(SENSITIVITY.map((s) => [s, { ...DEFAULT_RULES[s], ...(rules.default?.[s] ?? {}) }]));
197
+ this.overrides = rules.overrides ?? [];
198
+ }
199
+ known(id) {
200
+ return this.catalog.has(id) || this.concepts.has(id);
201
+ }
202
+ /** The catalog class behind a class or concept id. */
203
+ baseClass(id) {
204
+ const c = this.concepts.get(id);
205
+ return c ? this.catalog.get(c.extends) : this.catalog.get(id);
206
+ }
207
+ /** [sensitivity, handling] of a class or concept. */
208
+ /** [sensitivity, handling] of a class or concept, after the model's classification settings. */
209
+ profile(id) {
210
+ const base = this.baseClass(id);
211
+ const st = this.settings.get(base.id) ?? {};
212
+ const s = st.sensitivity ?? base.sensitivity;
213
+ const h = st.handling ?? base.handling;
214
+ const c = this.concepts.get(id) ?? {};
215
+ return [stricter(c.sensitivity ?? s, s, SENSITIVITY), stricter(c.handling ?? h, h, HANDLING)];
216
+ }
217
+ label(id) {
218
+ return (this.concepts.get(id) ?? this.catalog.get(id)).label;
219
+ }
220
+ /** Action for content of class or concept `id` going to `destination` (spec section 5). */
221
+ action(id, destination, opts = {}) {
222
+ if (!DESTINATIONS.includes(destination))
223
+ throw new OppError(`unknown destination ${destination}`);
224
+ const [s0, h0] = this.profile(id);
225
+ const s = opts.sensitivity ?? s0;
226
+ const h = opts.handling ?? h0;
227
+ const targets = [id, ...(opts.targetNames ?? [])];
228
+ for (const o of this.overrides) {
229
+ if (o.destination === destination && targets.includes(o.target))
230
+ return (o.action === "handling" ? h : o.action);
231
+ }
232
+ const a = this.rules[s][destination];
233
+ return (a === "handling" ? h : a);
234
+ }
235
+ /** [sensitivity, handling] of a field: its overrides, else the strictest of its classes. */
236
+ fieldProfile(field) {
237
+ let sens = "public";
238
+ let hand = "allow";
239
+ for (const c of field.classes ?? []) {
240
+ const [s, h] = this.profile(c.class);
241
+ sens = stricter(s, sens, SENSITIVITY);
242
+ hand = stricter(h, hand, HANDLING);
243
+ }
244
+ return [(field.sensitivity ?? sens), (field.handling ?? hand)];
245
+ }
246
+ }
247
+ /** The strictest of several actions ('allow' when there are none). */
248
+ export function strictestAction(actions) {
249
+ return (actions.length ? actions.reduce((a, b) => (idx(ACTION_ORDER, b) > idx(ACTION_ORDER, a) ? b : a)) : "allow");
250
+ }
251
+ function presetErrors(doc, catalog) {
252
+ const errs = schemaErrors(doc, "presets");
253
+ const cat = catalog ?? baseline();
254
+ for (const p of doc.presets ?? [])
255
+ for (const c of p.focus_classes ?? [])
256
+ if (!cat.has(c))
257
+ errs.push(`presets/${p.id}: unknown class ${c}`);
258
+ return errs;
259
+ }
260
+ let presetsCache;
261
+ /** The industry presets that ship with the standard, by id. */
262
+ export function presets() {
263
+ if (!presetsCache) {
264
+ const errs = presetErrors(PRESETS_DOCUMENT);
265
+ if (errs.length)
266
+ throw new OppError(errs);
267
+ presetsCache = new Map(PRESETS_DOCUMENT.presets.map((p) => [p.id, p]));
268
+ }
269
+ return presetsCache;
270
+ }
271
+ /** The preset whose longest NAICS prefix matches a 2- to 6-digit code, or 'generic'. */
272
+ export function presetForNaics(code) {
273
+ const c = String(code);
274
+ let best = "generic";
275
+ let length = 0;
276
+ for (const [id, p] of presets())
277
+ for (const pre of p.naics_prefixes)
278
+ if (c.startsWith(pre) && pre.length > length)
279
+ [best, length] = [id, pre.length];
280
+ return presets().get(best);
281
+ }
282
+ /** Problems in a catalog, model or presets document; empty when it conforms. */
283
+ export function validate(src, catalog) {
284
+ const doc = read(src);
285
+ try {
286
+ const kind = kindOf(doc);
287
+ if (kind === "presets")
288
+ return presetErrors(doc, catalog);
289
+ if (kind === "catalog")
290
+ new Catalog(doc);
291
+ else
292
+ new Model(doc, catalog);
293
+ }
294
+ catch (e) {
295
+ if (e instanceof OppError)
296
+ return e.problems;
297
+ throw e;
298
+ }
299
+ return [];
300
+ }