@tupik/openapi 0.0.0-stage → 1.1.0
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/LICENSE +21 -0
- package/README.md +106 -2
- package/bin/contract-cli.mjs +4 -0
- package/bin/tupik.mjs +4 -0
- package/dist/cli.d.mts +68 -0
- package/dist/cli.d.ts +68 -0
- package/dist/cli.mjs +299 -0
- package/dist/index.d.mts +164 -0
- package/dist/index.d.ts +164 -0
- package/dist/index.mjs +223 -0
- package/dist/shared/openapi.B3aGIYpz.mjs +544 -0
- package/dist/shared/openapi.BCSoJoZR.d.mts +246 -0
- package/dist/shared/openapi.BCSoJoZR.d.ts +246 -0
- package/package.json +66 -3
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { schemaDataClasses, createModule } from '@tupik/core';
|
|
2
|
+
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
function ownJsonSchema(schema, direction) {
|
|
7
|
+
const own = schema.jsonSchema;
|
|
8
|
+
if (isRecord(own)) return own;
|
|
9
|
+
const standard = schema["~standard"];
|
|
10
|
+
const converted = standard.jsonSchema?.[direction]?.({ target: "draft-2020-12" });
|
|
11
|
+
return isRecord(converted) ? converted : void 0;
|
|
12
|
+
}
|
|
13
|
+
function jsonSchemaOf(schema, direction, converter) {
|
|
14
|
+
return converter === void 0 ? ownJsonSchema(schema, direction) : converter(schema);
|
|
15
|
+
}
|
|
16
|
+
const BRANCH_KEYS = ["anyOf", "oneOf", "allOf"];
|
|
17
|
+
function childNodes(node, segment) {
|
|
18
|
+
if (isRecord(node["items"])) return childNodes(node["items"], segment);
|
|
19
|
+
const branches = BRANCH_KEYS.flatMap((key) => {
|
|
20
|
+
const value = node[key];
|
|
21
|
+
return Array.isArray(value) ? value.filter(isRecord) : [];
|
|
22
|
+
});
|
|
23
|
+
if (branches.length > 0) return branches.flatMap((branch) => childNodes(branch, segment));
|
|
24
|
+
const properties = node["properties"];
|
|
25
|
+
const child = isRecord(properties) ? properties[segment] : void 0;
|
|
26
|
+
return isRecord(child) ? [child] : [];
|
|
27
|
+
}
|
|
28
|
+
function markPath(root, path, dataClass) {
|
|
29
|
+
let nodes = [root];
|
|
30
|
+
for (const segment of path.split(".")) nodes = nodes.flatMap((node) => childNodes(node, segment));
|
|
31
|
+
for (const node of nodes) node["x-data-class"] = dataClass;
|
|
32
|
+
}
|
|
33
|
+
function annotateDataClasses(json, classes) {
|
|
34
|
+
const entries = Object.entries(classes);
|
|
35
|
+
if (entries.length === 0) return json;
|
|
36
|
+
const copy = structuredClone(json);
|
|
37
|
+
for (const [dataClass, paths] of entries) {
|
|
38
|
+
for (const path of paths) markPath(copy, path, dataClass);
|
|
39
|
+
}
|
|
40
|
+
return copy;
|
|
41
|
+
}
|
|
42
|
+
function classifiedJsonSchema(schema, direction, converter) {
|
|
43
|
+
const json = jsonSchemaOf(schema, direction, converter);
|
|
44
|
+
return json === void 0 ? void 0 : annotateDataClasses(json, schemaDataClasses(schema));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const REQUEST_PARTS = ["body", "query", "params", "headers"];
|
|
48
|
+
const SEVERITY = {
|
|
49
|
+
"route-removed": "breaking",
|
|
50
|
+
"route-added": "compatible",
|
|
51
|
+
"response-removed": "breaking",
|
|
52
|
+
"response-added": "compatible",
|
|
53
|
+
// New requirements break callers that do not send them; removing auth does not.
|
|
54
|
+
"security-changed": "breaking",
|
|
55
|
+
// Callers must now send a part that previously was not validated at all.
|
|
56
|
+
"request-schema-added": "breaking",
|
|
57
|
+
"request-schema-removed": "compatible",
|
|
58
|
+
"method-removed": "breaking",
|
|
59
|
+
"method-added": "compatible",
|
|
60
|
+
// Stricter auth breaks callers; looser auth is reported as a warning (data may now be exposed).
|
|
61
|
+
"access-changed": "breaking",
|
|
62
|
+
// A response field newly classified as pii/health/secret is new sensitive output.
|
|
63
|
+
"data-class-added": "warning",
|
|
64
|
+
"data-class-removed": "compatible",
|
|
65
|
+
"required-field-added": "breaking",
|
|
66
|
+
"required-field-removed": "compatible"
|
|
67
|
+
};
|
|
68
|
+
const AUTH_RANK = { none: 0, optional: 1, required: 2 };
|
|
69
|
+
const ACCESS_KINDS = ["public", "authenticated", "policy", "owner"];
|
|
70
|
+
function classEntries(prefix, paths) {
|
|
71
|
+
return Object.entries(paths ?? {}).flatMap(([dataClass, list]) => (list ?? []).map((path) => `${prefix}.${path}:${dataClass}`));
|
|
72
|
+
}
|
|
73
|
+
function flattenDataClasses(classes) {
|
|
74
|
+
const entries = [
|
|
75
|
+
...["body", "query", "params", "headers"].flatMap((slot) => classEntries(slot, classes[slot])),
|
|
76
|
+
...Object.entries(classes.response ?? {}).flatMap(([status, paths]) => classEntries(`response.${status}`, paths))
|
|
77
|
+
];
|
|
78
|
+
return entries.sort();
|
|
79
|
+
}
|
|
80
|
+
function requiredBodyOf(schema, converter) {
|
|
81
|
+
if (schema?.body === void 0) return void 0;
|
|
82
|
+
const json = jsonSchemaOf(schema.body, "input", converter);
|
|
83
|
+
if (json === void 0) return void 0;
|
|
84
|
+
const required = json["required"];
|
|
85
|
+
return Array.isArray(required) ? required.filter((name) => typeof name === "string").sort() : [];
|
|
86
|
+
}
|
|
87
|
+
function compareStrings(a, b) {
|
|
88
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
89
|
+
}
|
|
90
|
+
function compareRoutes(a, b) {
|
|
91
|
+
return compareStrings(a.path, b.path) || compareStrings(a.method, b.method);
|
|
92
|
+
}
|
|
93
|
+
function routeKey(method, path) {
|
|
94
|
+
return `${method} ${path}`;
|
|
95
|
+
}
|
|
96
|
+
function securityNames(requirements) {
|
|
97
|
+
const names = requirements.map((requirement) => Object.keys(requirement).sort().join("+") || "(none)");
|
|
98
|
+
return [...new Set(names)].sort();
|
|
99
|
+
}
|
|
100
|
+
function formatSecurity(security) {
|
|
101
|
+
return security.length === 0 ? "(none)" : security.join(" | ");
|
|
102
|
+
}
|
|
103
|
+
function snapshotContract(app, options = {}) {
|
|
104
|
+
const routes = app.routes.map((r) => {
|
|
105
|
+
const schema = r.schema;
|
|
106
|
+
const responses = schema?.response === void 0 ? [] : Object.keys(schema.response).map(Number).filter((code) => Number.isInteger(code)).sort((a, b) => a - b);
|
|
107
|
+
const route = {
|
|
108
|
+
method: r.method,
|
|
109
|
+
path: r.path,
|
|
110
|
+
request: {
|
|
111
|
+
body: schema?.body !== void 0,
|
|
112
|
+
query: schema?.query !== void 0,
|
|
113
|
+
params: schema?.params !== void 0,
|
|
114
|
+
headers: schema?.headers !== void 0
|
|
115
|
+
},
|
|
116
|
+
responses
|
|
117
|
+
};
|
|
118
|
+
if (options.security !== void 0) route.security = securityNames(options.security(r) ?? []);
|
|
119
|
+
if (r.meta !== void 0) {
|
|
120
|
+
route.access = r.meta.access;
|
|
121
|
+
route.auth = r.meta.auth;
|
|
122
|
+
route.dataClasses = flattenDataClasses(r.meta.dataClasses);
|
|
123
|
+
}
|
|
124
|
+
const requiredBody = requiredBodyOf(schema, options.schemaConverter);
|
|
125
|
+
if (requiredBody !== void 0) route.requiredBody = requiredBody;
|
|
126
|
+
return route;
|
|
127
|
+
});
|
|
128
|
+
routes.sort(compareRoutes);
|
|
129
|
+
return { version: 1, generatedWith: options.generatedWith ?? "@tupik/openapi", routes };
|
|
130
|
+
}
|
|
131
|
+
function indexRoutes(snapshot) {
|
|
132
|
+
const map = /* @__PURE__ */ new Map();
|
|
133
|
+
for (const r of snapshot.routes) {
|
|
134
|
+
const key = routeKey(r.method, r.path);
|
|
135
|
+
if (!map.has(key)) map.set(key, r);
|
|
136
|
+
}
|
|
137
|
+
return map;
|
|
138
|
+
}
|
|
139
|
+
function pathsOf(routes) {
|
|
140
|
+
const set = /* @__PURE__ */ new Set();
|
|
141
|
+
for (const r of routes.values()) set.add(r.path);
|
|
142
|
+
return set;
|
|
143
|
+
}
|
|
144
|
+
const KIND_ORDER = [
|
|
145
|
+
"route-removed",
|
|
146
|
+
"route-added",
|
|
147
|
+
"method-removed",
|
|
148
|
+
"method-added",
|
|
149
|
+
"request-schema-added",
|
|
150
|
+
"request-schema-removed",
|
|
151
|
+
"response-removed",
|
|
152
|
+
"response-added",
|
|
153
|
+
"security-changed",
|
|
154
|
+
"access-changed",
|
|
155
|
+
"required-field-added",
|
|
156
|
+
"required-field-removed",
|
|
157
|
+
"data-class-added",
|
|
158
|
+
"data-class-removed"
|
|
159
|
+
];
|
|
160
|
+
function compareChanges(a, b) {
|
|
161
|
+
return compareRoutes(a, b) || compareStrings(a.detail ?? "", b.detail ?? "") || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind);
|
|
162
|
+
}
|
|
163
|
+
function diffContracts(previous, current) {
|
|
164
|
+
const prev = indexRoutes(previous);
|
|
165
|
+
const curr = indexRoutes(current);
|
|
166
|
+
const prevPaths = pathsOf(prev);
|
|
167
|
+
const currPaths = pathsOf(curr);
|
|
168
|
+
const out = /* @__PURE__ */ new Map();
|
|
169
|
+
const push = (kind, method, path, detail, severity = SEVERITY[kind]) => {
|
|
170
|
+
const change = detail === void 0 ? { kind, severity, method, path } : { kind, severity, method, path, detail };
|
|
171
|
+
out.set(`${kind}\0${method}\0${path}\0${detail ?? ""}`, change);
|
|
172
|
+
};
|
|
173
|
+
for (const [key, before] of prev) {
|
|
174
|
+
const after = curr.get(key);
|
|
175
|
+
if (after === void 0) {
|
|
176
|
+
push(currPaths.has(before.path) ? "method-removed" : "route-removed", before.method, before.path);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
for (const part of REQUEST_PARTS) {
|
|
180
|
+
if (!before.request[part] && after.request[part]) push("request-schema-added", after.method, after.path, part);
|
|
181
|
+
if (before.request[part] && !after.request[part]) push("request-schema-removed", after.method, after.path, part);
|
|
182
|
+
}
|
|
183
|
+
const beforeCodes = new Set(before.responses);
|
|
184
|
+
const afterCodes = new Set(after.responses);
|
|
185
|
+
for (const code of beforeCodes) {
|
|
186
|
+
if (!afterCodes.has(code)) push("response-removed", after.method, after.path, String(code));
|
|
187
|
+
}
|
|
188
|
+
for (const code of afterCodes) {
|
|
189
|
+
if (!beforeCodes.has(code)) push("response-added", after.method, after.path, String(code), code >= 400 ? "warning" : "compatible");
|
|
190
|
+
}
|
|
191
|
+
if (before.security !== void 0) {
|
|
192
|
+
const afterSecurity = after.security ?? [];
|
|
193
|
+
if (formatSecurity(before.security) !== formatSecurity(afterSecurity)) {
|
|
194
|
+
const detail = `${formatSecurity(before.security)} -> ${formatSecurity(afterSecurity)}`;
|
|
195
|
+
push("security-changed", after.method, after.path, detail, afterSecurity.length === 0 ? "compatible" : "breaking");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
diffMetaFacts(before, after, push);
|
|
199
|
+
}
|
|
200
|
+
for (const [key, after] of curr) {
|
|
201
|
+
if (!prev.has(key)) push(prevPaths.has(after.path) ? "method-added" : "route-added", after.method, after.path);
|
|
202
|
+
}
|
|
203
|
+
return [...out.values()].sort(compareChanges);
|
|
204
|
+
}
|
|
205
|
+
function diffLists(before, after, onAdded, onRemoved) {
|
|
206
|
+
if (before === void 0 || after === void 0) return;
|
|
207
|
+
for (const item of after) if (!before.includes(item)) onAdded(item);
|
|
208
|
+
for (const item of before) if (!after.includes(item)) onRemoved(item);
|
|
209
|
+
}
|
|
210
|
+
function diffMetaFacts(before, after, push) {
|
|
211
|
+
const { method, path } = after;
|
|
212
|
+
if (before.auth !== void 0 && after.auth !== void 0 && (before.access !== after.access || before.auth !== after.auth)) {
|
|
213
|
+
const severity = AUTH_RANK[after.auth] > AUTH_RANK[before.auth] ? "breaking" : "warning";
|
|
214
|
+
push("access-changed", method, path, `${before.access ?? "?"}/${before.auth} -> ${after.access ?? "?"}/${after.auth}`, severity);
|
|
215
|
+
}
|
|
216
|
+
diffLists(
|
|
217
|
+
before.dataClasses,
|
|
218
|
+
after.dataClasses,
|
|
219
|
+
(entry) => push("data-class-added", method, path, entry, entry.startsWith("response.") ? "warning" : "compatible"),
|
|
220
|
+
(entry) => push("data-class-removed", method, path, entry)
|
|
221
|
+
);
|
|
222
|
+
diffLists(
|
|
223
|
+
before.requiredBody,
|
|
224
|
+
after.requiredBody,
|
|
225
|
+
(field) => push("required-field-added", method, path, `body.${field}`),
|
|
226
|
+
(field) => push("required-field-removed", method, path, `body.${field}`)
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
function hasBreakingChanges(changes) {
|
|
230
|
+
return changes.some((c) => c.severity === "breaking");
|
|
231
|
+
}
|
|
232
|
+
const SEVERITY_LABEL = { breaking: "BREAKING", warning: "WARNING", compatible: "ok" };
|
|
233
|
+
function formatContractChanges(changes) {
|
|
234
|
+
if (changes.length === 0) return "no changes";
|
|
235
|
+
return changes.map((c) => `${SEVERITY_LABEL[c.severity]} ${c.kind} ${c.method} ${c.path}${c.detail === void 0 ? "" : ` (${c.detail})`}`).join("\n");
|
|
236
|
+
}
|
|
237
|
+
function isRoute(value) {
|
|
238
|
+
if (!isRecord(value)) return false;
|
|
239
|
+
const request = value["request"];
|
|
240
|
+
const responses = value["responses"];
|
|
241
|
+
return typeof value["method"] === "string" && typeof value["path"] === "string" && isRecord(request) && REQUEST_PARTS.every((part) => typeof request[part] === "boolean") && Array.isArray(responses) && responses.every((code) => typeof code === "number" && Number.isInteger(code)) && optionalStrings(value["security"]) && optionalStrings(value["dataClasses"]) && optionalStrings(value["requiredBody"]) && (value["access"] === void 0 || ACCESS_KINDS.includes(value["access"])) && (value["auth"] === void 0 || Object.hasOwn(AUTH_RANK, value["auth"]));
|
|
242
|
+
}
|
|
243
|
+
function optionalStrings(value) {
|
|
244
|
+
return value === void 0 || Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
245
|
+
}
|
|
246
|
+
const OPTIONAL_FACTS = ["security", "access", "auth", "dataClasses", "requiredBody"];
|
|
247
|
+
function parseContractSnapshot(value) {
|
|
248
|
+
if (!isRecord(value)) throw new Error("invalid baseline: expected a JSON object");
|
|
249
|
+
if (value["version"] !== 1) throw new Error(`invalid baseline: unsupported version ${JSON.stringify(value["version"])} (expected 1)`);
|
|
250
|
+
const routes = value["routes"];
|
|
251
|
+
if (!Array.isArray(routes)) throw new Error('invalid baseline: "routes" must be an array');
|
|
252
|
+
const parsed = [];
|
|
253
|
+
routes.forEach((r, i) => {
|
|
254
|
+
if (!isRoute(r)) throw new Error(`invalid baseline: routes[${i}] is malformed`);
|
|
255
|
+
const route = {
|
|
256
|
+
method: r.method,
|
|
257
|
+
path: r.path,
|
|
258
|
+
request: { body: r.request.body, query: r.request.query, params: r.request.params, headers: r.request.headers },
|
|
259
|
+
responses: [...r.responses]
|
|
260
|
+
};
|
|
261
|
+
for (const fact of OPTIONAL_FACTS) {
|
|
262
|
+
const value2 = r[fact];
|
|
263
|
+
if (value2 !== void 0) Object.assign(route, { [fact]: Array.isArray(value2) ? [...value2] : value2 });
|
|
264
|
+
}
|
|
265
|
+
parsed.push(route);
|
|
266
|
+
});
|
|
267
|
+
const generatedWith = value["generatedWith"];
|
|
268
|
+
return { version: 1, generatedWith: typeof generatedWith === "string" ? generatedWith : "unknown", routes: parsed };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const AUDIT_RULES = {
|
|
272
|
+
"public-sensitive-data": { severity: "error", description: "A public route receives or returns pii/health data." },
|
|
273
|
+
"sensitive-data": { severity: "warning", description: "A route receives or returns pii/health data (LGPD/GDPR inventory)." },
|
|
274
|
+
"write-without-rate-limit": { severity: "warning", description: "A POST/PUT/PATCH/DELETE route has no rate-limit middleware." },
|
|
275
|
+
"id-without-owner": { severity: "warning", description: "A route with an id parameter has no owner rule nor policy (BOLA risk)." },
|
|
276
|
+
"public-route": { severity: "note", description: "The route is public: anyone may call it." },
|
|
277
|
+
"breaking-change": { severity: "error", description: "The route contract changed in a way that breaks clients." },
|
|
278
|
+
"contract-warning": { severity: "warning", description: "The route contract changed in a way clients or reviewers should notice." }
|
|
279
|
+
};
|
|
280
|
+
const SEVERITY_ORDER = ["error", "warning", "note"];
|
|
281
|
+
const RULE_ORDER = Object.keys(AUDIT_RULES);
|
|
282
|
+
const WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
283
|
+
const SENSITIVE = ["pii", "health"];
|
|
284
|
+
const ACCEPT_PREFIX = "audit-accept:";
|
|
285
|
+
function acceptAudit(rule, reason) {
|
|
286
|
+
if (reason.trim() === "") throw new TypeError(`acceptAudit: give the reason for accepting '${rule}'`);
|
|
287
|
+
return `${ACCEPT_PREFIX}${rule}=${reason.trim()}`;
|
|
288
|
+
}
|
|
289
|
+
function acceptanceOf(tags, rule) {
|
|
290
|
+
for (const tag of tags) {
|
|
291
|
+
if (!tag.startsWith(ACCEPT_PREFIX + rule)) continue;
|
|
292
|
+
const rest = tag.slice(ACCEPT_PREFIX.length + rule.length);
|
|
293
|
+
const reason = rest.startsWith("=") ? rest.slice(1).trim() : "";
|
|
294
|
+
if (rest === "" || rest.startsWith("=")) return reason === "" ? { ignored: true } : { accepted: reason };
|
|
295
|
+
}
|
|
296
|
+
return {};
|
|
297
|
+
}
|
|
298
|
+
const DEFAULT_ID_PARAM = /^(id|.+Id|.+_id)$/;
|
|
299
|
+
function label(route) {
|
|
300
|
+
return `${route.method} ${route.path}`;
|
|
301
|
+
}
|
|
302
|
+
function sensitivePaths(paths, prefix) {
|
|
303
|
+
return SENSITIVE.flatMap((dataClass) => (paths?.[dataClass] ?? []).map((path) => `${prefix}${path} (${dataClass})`));
|
|
304
|
+
}
|
|
305
|
+
function describeSensitiveData(meta) {
|
|
306
|
+
const classes = meta.dataClasses;
|
|
307
|
+
const inputs = ["body", "query", "params", "headers"].flatMap((slot) => sensitivePaths(classes[slot], `${slot}.`));
|
|
308
|
+
const outputs = Object.entries(classes.response ?? {}).map(([status, paths]) => [status, sensitivePaths(paths, "")]).filter(([, list]) => list.length > 0).map(([status, list]) => `response ${status}: ${list.join(", ")}`);
|
|
309
|
+
return [...inputs.length > 0 ? [inputs.join(", ")] : [], ...outputs].join("; ");
|
|
310
|
+
}
|
|
311
|
+
function idParams(path, pattern) {
|
|
312
|
+
return path.split("/").filter((segment) => segment.startsWith(":") && pattern.test(segment.slice(1)));
|
|
313
|
+
}
|
|
314
|
+
const CHECKS = [
|
|
315
|
+
(route) => {
|
|
316
|
+
const data = describeSensitiveData(route.meta);
|
|
317
|
+
if (data === "") return [];
|
|
318
|
+
return route.meta.access === "public" ? [["public-sensitive-data", `${label(route)} is public and handles ${data}: require a principal (access: 'authenticated', owner or a policy) or stop sending the data`]] : [["sensitive-data", `${label(route)} handles ${data}: record its purpose and legal basis in the data map (tupik data-map --config)`]];
|
|
319
|
+
},
|
|
320
|
+
(route, options) => WRITE_METHODS.has(route.method) && !route.meta.tags.has(options.rateLimitTag) ? [["write-without-rate-limit", `${label(route)} writes without rate limiting: add a rate limit middleware tagged '${options.rateLimitTag}' (withTags(rateLimit(...), '${options.rateLimitTag}'))`]] : [],
|
|
321
|
+
(route, options) => {
|
|
322
|
+
if (route.meta.access === "owner" || route.meta.access === "policy") return [];
|
|
323
|
+
const params = idParams(route.path, options.idParam);
|
|
324
|
+
return params.length === 0 ? [] : [["id-without-owner", `${label(route)} reads ${params.join(", ")} without checking who owns the record: use access: { owner: (ctx) => <owner id of the record> } or a policy`]];
|
|
325
|
+
},
|
|
326
|
+
(route) => route.meta.access === "public" ? [["public-route", `${label(route)} is public: anyone may call it`]] : []
|
|
327
|
+
];
|
|
328
|
+
function contractFinding(change) {
|
|
329
|
+
if (change.severity === "compatible") return void 0;
|
|
330
|
+
const rule = change.severity === "breaking" ? "breaking-change" : "contract-warning";
|
|
331
|
+
const detail = change.detail === void 0 ? "" : ` (${change.detail})`;
|
|
332
|
+
return { rule, severity: AUDIT_RULES[rule].severity, method: change.method, path: change.path, message: `${change.kind}${detail}` };
|
|
333
|
+
}
|
|
334
|
+
function auditApp(app, options = {}) {
|
|
335
|
+
const resolved = { rateLimitTag: options.rateLimitTag ?? "rate-limited", idParam: options.idParam ?? DEFAULT_ID_PARAM };
|
|
336
|
+
const disabled = new Set(options.disable ?? []);
|
|
337
|
+
const findings = [];
|
|
338
|
+
const routes = app.routes;
|
|
339
|
+
routes.forEach((route, order) => {
|
|
340
|
+
const meta = route.meta;
|
|
341
|
+
if (meta === void 0) return;
|
|
342
|
+
for (const check of CHECKS) {
|
|
343
|
+
for (const [rule, message] of check({ ...route, meta }, resolved)) {
|
|
344
|
+
const { accepted, ignored } = acceptanceOf(meta.tags, rule);
|
|
345
|
+
const base = { rule, method: route.method, path: route.path, order };
|
|
346
|
+
findings.push(accepted === void 0 ? { ...base, severity: AUDIT_RULES[rule].severity, message: ignored ? `${message} (acceptance ignored: it has no reason; use acceptAudit(rule, reason))` : message } : { ...base, severity: "note", message, accepted });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
if (options.baseline !== void 0) {
|
|
351
|
+
const current = options.schemaConverter === void 0 ? snapshotContract(app) : snapshotContract(app, { schemaConverter: options.schemaConverter });
|
|
352
|
+
diffContracts(options.baseline, current).forEach((change, index) => {
|
|
353
|
+
const finding = contractFinding(change);
|
|
354
|
+
if (finding !== void 0) findings.push({ ...finding, order: routes.length + index });
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
const kept = findings.filter((finding) => !disabled.has(finding.rule)).sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || a.order - b.order || RULE_ORDER.indexOf(a.rule) - RULE_ORDER.indexOf(b.rule)).map(({ order: _order, ...finding }) => finding);
|
|
358
|
+
const counts = { error: 0, warning: 0, note: 0 };
|
|
359
|
+
for (const finding of kept) counts[finding.severity] += 1;
|
|
360
|
+
return { routes: routes.length, findings: kept, counts };
|
|
361
|
+
}
|
|
362
|
+
function shouldFail(report, failOn) {
|
|
363
|
+
if (failOn === "none") return false;
|
|
364
|
+
const threshold = SEVERITY_ORDER.indexOf(failOn);
|
|
365
|
+
return report.findings.some((finding) => SEVERITY_ORDER.indexOf(finding.severity) <= threshold);
|
|
366
|
+
}
|
|
367
|
+
function plural(count, word) {
|
|
368
|
+
return `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
369
|
+
}
|
|
370
|
+
function formatAuditText(report) {
|
|
371
|
+
const ruleWidth = Math.max(0, ...report.findings.map((finding) => finding.rule.length)) + 2;
|
|
372
|
+
const lines = report.findings.flatMap((finding) => [
|
|
373
|
+
`${finding.severity.toUpperCase().padEnd(9)}${finding.rule.padEnd(ruleWidth)}${finding.method} ${finding.path}`,
|
|
374
|
+
`${" ".repeat(9)}${finding.message}`,
|
|
375
|
+
...finding.accepted === void 0 ? [] : [`${" ".repeat(9)}accepted: ${finding.accepted}`]
|
|
376
|
+
]);
|
|
377
|
+
const { error, warning, note } = report.counts;
|
|
378
|
+
const summary = report.findings.length === 0 ? "no findings" : [plural(error, "error"), plural(warning, "warning"), plural(note, "note")].join(", ");
|
|
379
|
+
return [...lines, `${plural(report.routes, "route")}: ${summary}`].join("\n");
|
|
380
|
+
}
|
|
381
|
+
function auditToSarif(report, options = {}) {
|
|
382
|
+
const uri = options.uri ?? "app";
|
|
383
|
+
return {
|
|
384
|
+
version: "2.1.0",
|
|
385
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
386
|
+
runs: [{
|
|
387
|
+
tool: {
|
|
388
|
+
driver: {
|
|
389
|
+
name: "tupik-audit",
|
|
390
|
+
informationUri: "https://github.com/CodeHamper/tupikjs/tree/main/packages/openapi#readme",
|
|
391
|
+
rules: RULE_ORDER.map((id) => ({ id, shortDescription: { text: AUDIT_RULES[id].description }, defaultConfiguration: { level: AUDIT_RULES[id].severity } }))
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
results: report.findings.map((finding) => ({
|
|
395
|
+
...finding.accepted === void 0 ? {} : { suppressions: [{ kind: "inSource", justification: finding.accepted }] },
|
|
396
|
+
ruleId: finding.rule,
|
|
397
|
+
level: finding.severity,
|
|
398
|
+
message: { text: finding.message },
|
|
399
|
+
locations: [{
|
|
400
|
+
physicalLocation: { artifactLocation: { uri }, region: { startLine: 1 } },
|
|
401
|
+
logicalLocations: [{ name: label(finding), kind: "function" }]
|
|
402
|
+
}]
|
|
403
|
+
}))
|
|
404
|
+
}]
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const SUBJECT_REQUEST_TAGS = {
|
|
409
|
+
export: "subject-request:export",
|
|
410
|
+
erase: "subject-request:erase"
|
|
411
|
+
};
|
|
412
|
+
function principalSubject(ctx) {
|
|
413
|
+
const principal = ctx.principal;
|
|
414
|
+
const id = typeof principal === "object" && principal !== null ? principal.id : principal;
|
|
415
|
+
if (typeof id !== "string" || id === "") {
|
|
416
|
+
throw new TypeError("defineSubjectRequests: the principal has no string id; return { id } from authenticate or pass subjectId: (ctx) => ...");
|
|
417
|
+
}
|
|
418
|
+
return id;
|
|
419
|
+
}
|
|
420
|
+
function defineSubjectRequests(options) {
|
|
421
|
+
const access = options.access ?? "authenticated";
|
|
422
|
+
if (access === "public") {
|
|
423
|
+
throw new TypeError("defineSubjectRequests: access 'public' would let anyone export or erase personal data; use 'authenticated' or a policy");
|
|
424
|
+
}
|
|
425
|
+
const subjectOf = options.subjectId ?? principalSubject;
|
|
426
|
+
return createModule(options.prefix ?? "/privacy").access(access).get("/export", {
|
|
427
|
+
tags: [SUBJECT_REQUEST_TAGS.export],
|
|
428
|
+
handler: async (ctx) => {
|
|
429
|
+
const subjectId = subjectOf(ctx);
|
|
430
|
+
const data = await options.export(subjectId, ctx);
|
|
431
|
+
return ctx.header("cache-control", "no-store").json({ subjectId, exportedAt: (/* @__PURE__ */ new Date()).toISOString(), data });
|
|
432
|
+
}
|
|
433
|
+
}).delete("/data", {
|
|
434
|
+
tags: [SUBJECT_REQUEST_TAGS.erase],
|
|
435
|
+
handler: async (ctx) => {
|
|
436
|
+
const subjectId = subjectOf(ctx);
|
|
437
|
+
await options.erase(subjectId, ctx);
|
|
438
|
+
return ctx.status(202).json({ subjectId, requestedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const ANNOTATION_KEYS = ["purpose", "legalBasis", "retention", "notes"];
|
|
444
|
+
const CLASS_ORDER = ["pii", "health", "secret"];
|
|
445
|
+
const INPUT_SLOTS = ["body", "query", "params", "headers"];
|
|
446
|
+
function parseAnnotation(value, where) {
|
|
447
|
+
if (!isRecord(value)) throw new Error(`invalid data map config: ${where} must be an object`);
|
|
448
|
+
const annotation = {};
|
|
449
|
+
for (const [key, text] of Object.entries(value)) {
|
|
450
|
+
if (!ANNOTATION_KEYS.includes(key)) {
|
|
451
|
+
throw new Error(`invalid data map config: unknown key "${key}" in ${where} (use ${ANNOTATION_KEYS.join(", ")})`);
|
|
452
|
+
}
|
|
453
|
+
if (typeof text !== "string") throw new Error(`invalid data map config: ${where}.${key} must be a string`);
|
|
454
|
+
annotation[key] = text;
|
|
455
|
+
}
|
|
456
|
+
return annotation;
|
|
457
|
+
}
|
|
458
|
+
function parseDataMapConfig(value) {
|
|
459
|
+
if (!isRecord(value)) throw new Error("invalid data map config: expected a JSON object");
|
|
460
|
+
const config = {};
|
|
461
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
462
|
+
if (key === "defaults") config.defaults = parseAnnotation(entry, "defaults");
|
|
463
|
+
else if (key === "routes") {
|
|
464
|
+
if (!isRecord(entry)) throw new Error('invalid data map config: routes must be an object keyed by "METHOD /path"');
|
|
465
|
+
config.routes = Object.fromEntries(Object.entries(entry).map(([route, annotation]) => [route, parseAnnotation(annotation, `routes[${JSON.stringify(route)}]`)]));
|
|
466
|
+
} else throw new Error(`invalid data map config: unknown key "${key}" (use defaults, routes)`);
|
|
467
|
+
}
|
|
468
|
+
return config;
|
|
469
|
+
}
|
|
470
|
+
function prefixed(paths, prefix) {
|
|
471
|
+
const out = {};
|
|
472
|
+
for (const dataClass of CLASS_ORDER) {
|
|
473
|
+
const list = paths?.[dataClass];
|
|
474
|
+
if (list !== void 0 && list.length > 0) out[dataClass] = list.map((path) => prefix + path);
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
function receivesOf(meta) {
|
|
479
|
+
const merged = {};
|
|
480
|
+
for (const slot of INPUT_SLOTS) {
|
|
481
|
+
for (const [dataClass, list] of Object.entries(prefixed(meta.dataClasses[slot], `${slot}.`))) {
|
|
482
|
+
(merged[dataClass] ??= []).push(...list);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return merged;
|
|
486
|
+
}
|
|
487
|
+
function returnsOf(meta) {
|
|
488
|
+
return Object.fromEntries(Object.entries(meta.dataClasses.response ?? {}).map(([status, paths]) => [Number(status), prefixed(paths, "")]));
|
|
489
|
+
}
|
|
490
|
+
function subjectKind(meta) {
|
|
491
|
+
return Object.keys(SUBJECT_REQUEST_TAGS).find((kind) => meta.tags.has(SUBJECT_REQUEST_TAGS[kind]));
|
|
492
|
+
}
|
|
493
|
+
function buildDataMap(app, config = {}) {
|
|
494
|
+
const routes = [];
|
|
495
|
+
const subjectRequests = {};
|
|
496
|
+
const unannotated = [];
|
|
497
|
+
for (const route of app.routes) {
|
|
498
|
+
const meta = route.meta;
|
|
499
|
+
if (meta === void 0) continue;
|
|
500
|
+
const key = `${route.method} ${route.path}`;
|
|
501
|
+
const kind = subjectKind(meta);
|
|
502
|
+
if (kind !== void 0) subjectRequests[kind] = key;
|
|
503
|
+
const receives = receivesOf(meta);
|
|
504
|
+
const returns = returnsOf(meta);
|
|
505
|
+
if (Object.keys(receives).length === 0 && Object.keys(returns).length === 0) continue;
|
|
506
|
+
const annotation = { ...config.defaults, ...config.routes?.[key] };
|
|
507
|
+
routes.push({ method: route.method, path: route.path, access: meta.access, receives, returns, ...annotation });
|
|
508
|
+
if (annotation.purpose === void 0 || annotation.legalBasis === void 0) unannotated.push(key);
|
|
509
|
+
}
|
|
510
|
+
return { routes, subjectRequests, unannotated };
|
|
511
|
+
}
|
|
512
|
+
function listFields(fields) {
|
|
513
|
+
return CLASS_ORDER.flatMap((dataClass) => (fields[dataClass] ?? []).map((path) => `${path} (${dataClass})`)).join(", ");
|
|
514
|
+
}
|
|
515
|
+
function cell(text) {
|
|
516
|
+
return text === void 0 || text === "" ? "\u2014" : text.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
517
|
+
}
|
|
518
|
+
function formatDataMapMarkdown(map) {
|
|
519
|
+
const rows = map.routes.map((entry) => {
|
|
520
|
+
const returns = Object.entries(entry.returns).map(([status, fields]) => `${status}: ${listFields(fields)}`).join("; ");
|
|
521
|
+
return `| ${entry.method} ${entry.path} | ${entry.access} | ${cell(listFields(entry.receives))} | ${cell(returns)} | ${cell(entry.purpose)} | ${cell(entry.legalBasis)} |`;
|
|
522
|
+
});
|
|
523
|
+
const requests = Object.entries(map.subjectRequests).map(([kind, route]) => `- ${kind === "export" ? "Export" : "Erase"}: \`${route}\``);
|
|
524
|
+
return [
|
|
525
|
+
"# Personal data map",
|
|
526
|
+
"",
|
|
527
|
+
"Generated by `tupik data-map` from the route metadata (`classify`). Purpose and legal basis come from the config file.",
|
|
528
|
+
"",
|
|
529
|
+
"| Route | Access | Receives | Returns | Purpose | Legal basis |",
|
|
530
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
531
|
+
...rows.length === 0 ? ["| \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |"] : rows,
|
|
532
|
+
"",
|
|
533
|
+
"## Data subject requests",
|
|
534
|
+
"",
|
|
535
|
+
...requests.length === 0 ? ["No subject request routes: add `defineSubjectRequests({ export, erase })`."] : requests,
|
|
536
|
+
"",
|
|
537
|
+
"## Missing purpose or legal basis",
|
|
538
|
+
"",
|
|
539
|
+
...map.unannotated.length === 0 ? ["None."] : map.unannotated.map((route) => `- \`${route}\``),
|
|
540
|
+
""
|
|
541
|
+
].join("\n");
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export { AUDIT_RULES as A, SUBJECT_REQUEST_TAGS as S, parseDataMapConfig as a, buildDataMap as b, formatDataMapMarkdown as c, diffContracts as d, auditApp as e, formatContractChanges as f, shouldFail as g, hasBreakingChanges as h, auditToSarif as i, formatAuditText as j, classifiedJsonSchema as k, isRecord as l, acceptAudit as m, annotateDataClasses as n, defineSubjectRequests as o, parseContractSnapshot as p, describeSensitiveData as q, flattenDataClasses as r, snapshotContract as s, jsonSchemaOf as t, ownJsonSchema as u };
|