jso-protector 0.2.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.
Files changed (119) hide show
  1. package/CHANGELOG.md +960 -0
  2. package/LICENSE +90 -0
  3. package/MIGRATION.md +207 -0
  4. package/README.md +1477 -0
  5. package/RELEASE.md +82 -0
  6. package/SECURITY.md +71 -0
  7. package/ai-cli.js +392 -0
  8. package/ai.js +176 -0
  9. package/bin/jso-protector.js +12066 -0
  10. package/browserify.d.ts +10 -0
  11. package/browserify.js +88 -0
  12. package/bun.d.ts +10 -0
  13. package/bun.js +41 -0
  14. package/ci/Jenkinsfile +82 -0
  15. package/ci/argo-workflows.yaml +121 -0
  16. package/ci/azure-pipelines.yml +56 -0
  17. package/ci/bitbucket-pipelines.yml +43 -0
  18. package/ci/buildkite.yml +50 -0
  19. package/ci/circleci.yml +60 -0
  20. package/ci/drone.yml +67 -0
  21. package/ci/github-actions.yml +51 -0
  22. package/ci/gitlab-ci.yml +39 -0
  23. package/ci/gocd.yaml +79 -0
  24. package/ci/teamcity.kts +79 -0
  25. package/ci/tekton.yaml +106 -0
  26. package/ci/verify-package.js +748 -0
  27. package/ci/verify-publish-metadata.js +147 -0
  28. package/ci/verify-templates.js +195 -0
  29. package/ci/woodpecker.yml +53 -0
  30. package/compliance/cli.js +204 -0
  31. package/compliance/evidence-forwarder.js +209 -0
  32. package/compliance/pci-dss-v4/controls.json +75 -0
  33. package/compliance/pci-dss-v4/index.js +2613 -0
  34. package/config/named-sets.js +185 -0
  35. package/esbuild.d.ts +16 -0
  36. package/esbuild.js +190 -0
  37. package/examples/README.md +78 -0
  38. package/examples/browserify/build.js +20 -0
  39. package/examples/bun/package.json +13 -0
  40. package/examples/bun/scripts/protect-release.js +28 -0
  41. package/examples/cli-basic/jso.config.cjs +23 -0
  42. package/examples/cli-basic/jso.config.json +15 -0
  43. package/examples/cli-basic/package.json +14 -0
  44. package/examples/cli-basic/scripts/build.js +10 -0
  45. package/examples/curl/README.md +55 -0
  46. package/examples/curl/protect.sh +106 -0
  47. package/examples/esbuild/build.js +19 -0
  48. package/examples/grunt/Gruntfile.js +29 -0
  49. package/examples/gulp/gulpfile.js +19 -0
  50. package/examples/helm/Chart.yaml +27 -0
  51. package/examples/helm/README.md +69 -0
  52. package/examples/helm/templates/_helpers.tpl +23 -0
  53. package/examples/helm/templates/_podtemplate.tpl +64 -0
  54. package/examples/helm/templates/job.yaml +39 -0
  55. package/examples/helm/templates/secret.yaml +17 -0
  56. package/examples/helm/values.yaml +54 -0
  57. package/examples/kubernetes/job.yaml +123 -0
  58. package/examples/metro.config.js +11 -0
  59. package/examples/nextjs/next.config.js +11 -0
  60. package/examples/node-api/protect-release.js +28 -0
  61. package/examples/node-api/release-summary.js +59 -0
  62. package/examples/parcel/package.json +13 -0
  63. package/examples/parcel/scripts/protect-release.js +28 -0
  64. package/examples/payment-page-script-inventory.json +62 -0
  65. package/examples/payment-page-security-headers.json +46 -0
  66. package/examples/pre-commit/.pre-commit-config.yaml +33 -0
  67. package/examples/pre-commit/README.md +45 -0
  68. package/examples/react-native/README.md +208 -0
  69. package/examples/react-native/metro.config.js +11 -0
  70. package/examples/rollup/rollup.config.js +20 -0
  71. package/examples/rspack/rspack.config.js +28 -0
  72. package/examples/turbopack/package.json +13 -0
  73. package/examples/turbopack/scripts/protect-release.js +28 -0
  74. package/examples/vite/vite.config.js +18 -0
  75. package/examples/webpack/webpack.config.js +21 -0
  76. package/examples/webpack-loader/webpack.config.js +22 -0
  77. package/governance/index.d.ts +18 -0
  78. package/governance/index.js +309 -0
  79. package/grunt.d.ts +4 -0
  80. package/grunt.js +111 -0
  81. package/gulp.d.ts +10 -0
  82. package/gulp.js +106 -0
  83. package/index.d.ts +879 -0
  84. package/index.js +607 -0
  85. package/jso.config.example.json +29 -0
  86. package/jso.config.schema.json +548 -0
  87. package/metro.d.ts +43 -0
  88. package/metro.js +117 -0
  89. package/next.d.ts +24 -0
  90. package/next.js +64 -0
  91. package/package.json +241 -0
  92. package/parcel.d.ts +10 -0
  93. package/parcel.js +40 -0
  94. package/react-native.d.ts +2 -0
  95. package/react-native.js +3 -0
  96. package/release-signer.js +245 -0
  97. package/rollup.d.ts +13 -0
  98. package/rollup.js +71 -0
  99. package/rspack-loader.d.ts +13 -0
  100. package/rspack-loader.js +11 -0
  101. package/rspack.d.ts +11 -0
  102. package/rspack.js +9 -0
  103. package/runtime/ai-script-governance.js +379 -0
  104. package/runtime/countermeasures.js +0 -0
  105. package/runtime/data-exfiltration-guard.d.ts +7 -0
  106. package/runtime/data-exfiltration-guard.js +161 -0
  107. package/runtime/environment-integrity.js +389 -0
  108. package/runtime/managed-integrity.d.ts +4 -0
  109. package/runtime/managed-integrity.js +108 -0
  110. package/runtime/third-party-inventory.js +437 -0
  111. package/turbopack.d.ts +10 -0
  112. package/turbopack.js +41 -0
  113. package/vite.d.ts +16 -0
  114. package/vite.js +78 -0
  115. package/watermark.js +126 -0
  116. package/webpack-loader.d.ts +15 -0
  117. package/webpack-loader.js +97 -0
  118. package/webpack.d.ts +13 -0
  119. package/webpack.js +143 -0
@@ -0,0 +1,389 @@
1
+ "use strict";
2
+
3
+ // Environment-integrity checks (browser runtime module).
4
+ //
5
+ // The other runtime modules answer "has my *code* been altered?"
6
+ // (managed-integrity) and "is my page talking to somewhere it should
7
+ // not?" (data-exfiltration-guard). This module answers a third
8
+ // question: **has the JavaScript environment itself been instrumented
9
+ // underneath my code?**
10
+ //
11
+ // That is the precondition for most automated analysis. A tracing
12
+ // harness -- hand-rolled or LLM-driven -- typically replaces a few
13
+ // builtins (`Function.prototype.call`, `Object.defineProperty`,
14
+ // `JSON.parse`) so it can watch arguments and return values without
15
+ // touching the protected bundle at all. Integrity hashing of the
16
+ // bundle cannot see that, because the bundle is untouched.
17
+ //
18
+ // Three checks, in descending order of confidence:
19
+ //
20
+ // "hookedBuiltins" - compare each watched builtin against the
21
+ // `[native code]` shape that `Function.prototype
22
+ // .toString` produces for un-replaced natives.
23
+ // Cheap, synchronous, no DOM needed.
24
+ // "crossRealm" - build a throwaway same-origin iframe (a
25
+ // pristine realm), and diff the main realm's
26
+ // builtins against it. Catches a hook that also
27
+ // spoofed its own `toString`, which defeats
28
+ // check 1 on its own.
29
+ // "automation" - look for driver/headless markers
30
+ // (`navigator.webdriver`, PhantomJS and Selenium
31
+ // leftovers, CDP `cdc_` properties).
32
+ //
33
+ // HONEST SCOPING -- please read before quoting this in a datasheet.
34
+ // ------------------------------------------------------------------
35
+ // These checks raise the cost of automated analysis. They do not make
36
+ // anything irreversible, and they are bypassable by an attacker who
37
+ // controls the runtime: every check here is itself JavaScript running
38
+ // in the attacker's browser, so a sufficiently patient attacker can
39
+ // neutralise it. In particular:
40
+ //
41
+ // * Check 1 trusts `Function.prototype.toString`. If *that* is
42
+ // hooked, a hook can return a fake `[native code]` string. We
43
+ // therefore probe it first and report `toStringUnreliable`, which
44
+ // downgrades the confidence of every other finding in the report.
45
+ // * Check 2 needs same-origin iframes. A strict CSP
46
+ // (`frame-src 'none'`) or a sandboxed context will block it; we
47
+ // report `unavailable` rather than `ok`, because "could not look"
48
+ // is not "nothing there".
49
+ // * Check 3 is heuristic. `navigator.webdriver` is a one-line patch,
50
+ // and a tuned headless browser leaves none of these markers. Treat
51
+ // automation findings as signals, never as proof.
52
+ //
53
+ // Deliberately conservative defaults
54
+ // ----------------------------------
55
+ // `console.*` is NOT watched by default. Analytics, logging, and error
56
+ // reporting libraries legitimately wrap console methods, so watching
57
+ // them produces false positives on ordinary production pages. Opt in
58
+ // with `watch: ["console.log"]` if your build has no such library.
59
+ //
60
+ // Public API
61
+ // ----------
62
+ // const ei = require("jso-protector/runtime/environment-integrity");
63
+ // const probe = ei.createEnvironmentIntegrityPolicy({
64
+ // checks: ["hookedBuiltins", "crossRealm", "automation"],
65
+ // watch: ["Function.prototype.call", "JSON.parse"],
66
+ // });
67
+ // const report = probe.inspect(window);
68
+ // if (!report.ok) { countermeasurePolicy.react(window, report.violation); }
69
+ //
70
+ // `inspect()` is read-only apart from the iframe the crossRealm check
71
+ // creates and removes. The policy is pure data until you call it, so it
72
+ // unit-tests against a stub `win` with no DOM.
73
+
74
+ const ALL_CHECKS = ["hookedBuiltins", "crossRealm", "automation"];
75
+
76
+ // Builtins worth watching by default: each is a plausible interception
77
+ // point for a tracing harness, and none is commonly re-wrapped by
78
+ // ordinary libraries. `Function.prototype.toString` leads because every
79
+ // other hookedBuiltins result depends on it.
80
+ const DEFAULT_WATCH = [
81
+ "Function.prototype.toString",
82
+ "Function.prototype.call",
83
+ "Function.prototype.apply",
84
+ "Function.prototype.bind",
85
+ "Object.defineProperty",
86
+ "Object.getOwnPropertyDescriptor",
87
+ "JSON.parse",
88
+ "JSON.stringify",
89
+ ];
90
+
91
+ // Engines differ in spacing and in the function name they echo back, so
92
+ // match the shape rather than an exact string.
93
+ const NATIVE_CODE = /\{\s*\[native code\]\s*\}/;
94
+
95
+ // Automation leftovers. Each is a global that a driver injects and does
96
+ // not always clean up. Absence proves nothing.
97
+ const AUTOMATION_GLOBALS = [
98
+ "_phantom", "__phantomas", "callPhantom",
99
+ "__nightmare",
100
+ "__selenium_unwrapped", "__selenium_evaluate", "__webdriver_evaluate",
101
+ "__driver_evaluate", "__fxdriver_evaluate", "__webdriver_script_fn",
102
+ "domAutomation", "domAutomationController",
103
+ ];
104
+
105
+ function resolvePath(root, path) {
106
+ // "Function.prototype.call" -> the function object, or undefined if
107
+ // any hop is missing. Never throws: a missing global is a normal
108
+ // outcome in a non-browser or trimmed environment.
109
+ const parts = String(path).split(".");
110
+ let cur = root;
111
+ for (let i = 0; i < parts.length; i++) {
112
+ if (cur === null || cur === undefined) return undefined;
113
+ try {
114
+ cur = cur[parts[i]];
115
+ } catch (e) {
116
+ return undefined;
117
+ }
118
+ }
119
+ return cur;
120
+ }
121
+
122
+ function looksNative(toStringFn, fn) {
123
+ // Returns true / false / null, where null means "could not tell".
124
+ if (typeof fn !== "function") return null;
125
+ let text;
126
+ try {
127
+ text = toStringFn.call(fn);
128
+ } catch (e) {
129
+ return null;
130
+ }
131
+ if (typeof text !== "string") return null;
132
+ return NATIVE_CODE.test(text);
133
+ }
134
+
135
+ function createEnvironmentIntegrityPolicy(config) {
136
+ const cfg = config || {};
137
+
138
+ let checks = cfg.checks === undefined ? ALL_CHECKS.slice() : cfg.checks;
139
+ if (typeof checks === "string") checks = [checks];
140
+ if (!Array.isArray(checks)) {
141
+ throw new TypeError("environment-integrity: checks must be a string or an array");
142
+ }
143
+ checks = checks.slice();
144
+ for (let i = 0; i < checks.length; i++) {
145
+ if (ALL_CHECKS.indexOf(checks[i]) === -1) {
146
+ throw new Error("environment-integrity: unknown check '" + checks[i] + "'");
147
+ }
148
+ }
149
+
150
+ let watch = cfg.watch === undefined ? DEFAULT_WATCH.slice() : cfg.watch;
151
+ if (typeof watch === "string") watch = [watch];
152
+ if (!Array.isArray(watch)) {
153
+ throw new TypeError("environment-integrity: watch must be a string or an array");
154
+ }
155
+ watch = watch.slice();
156
+
157
+ function checkHookedBuiltins(win, findings) {
158
+ const toStringFn = resolvePath(win, "Function.prototype.toString");
159
+ if (typeof toStringFn !== "function") {
160
+ findings.push({
161
+ check: "hookedBuiltins",
162
+ marker: "toStringMissing",
163
+ severity: "unavailable",
164
+ detail: "Function.prototype.toString is not a function; cannot inspect builtins.",
165
+ });
166
+ return;
167
+ }
168
+
169
+ // Probe the prober. A hook that spoofs its own toString will
170
+ // pass here, which is exactly why crossRealm exists.
171
+ if (looksNative(toStringFn, toStringFn) === false) {
172
+ findings.push({
173
+ check: "hookedBuiltins",
174
+ marker: "toStringUnreliable",
175
+ severity: "high",
176
+ detail: "Function.prototype.toString does not report as native; every other " +
177
+ "hookedBuiltins result is untrustworthy. Prefer the crossRealm check here.",
178
+ });
179
+ // Stop here on purpose. A stringifier that misreports itself
180
+ // misreports everything, so continuing would flag every watched
181
+ // builtin as hooked -- a false-positive storm that buries the one
182
+ // finding that matters. (Seen for real when toString resolves to
183
+ // Object.prototype.toString, which returns "[object Object]".)
184
+ // crossRealm is the check that can still get a truthful answer.
185
+ return;
186
+ }
187
+
188
+ for (let i = 0; i < watch.length; i++) {
189
+ const path = watch[i];
190
+ const fn = resolvePath(win, path);
191
+ if (fn === undefined) continue; // absent is not suspicious
192
+ const native = looksNative(toStringFn, fn);
193
+ if (native === false) {
194
+ findings.push({
195
+ check: "hookedBuiltins",
196
+ marker: path,
197
+ severity: "high",
198
+ detail: path + " is not reporting as native code, which means it has been " +
199
+ "replaced or wrapped.",
200
+ });
201
+ } else if (native === null) {
202
+ findings.push({
203
+ check: "hookedBuiltins",
204
+ marker: path,
205
+ severity: "unavailable",
206
+ detail: "Could not stringify " + path + " to compare it against native code.",
207
+ });
208
+ }
209
+ }
210
+ }
211
+
212
+ function checkCrossRealm(win, findings) {
213
+ // A pristine realm gives us a second opinion that a same-realm
214
+ // hook cannot forge. Needs a DOM and same-origin iframes.
215
+ const doc = win && win.document;
216
+ if (!doc || typeof doc.createElement !== "function" || !doc.body) {
217
+ findings.push({
218
+ check: "crossRealm",
219
+ marker: "noDocument",
220
+ severity: "unavailable",
221
+ detail: "No usable document; cannot build a pristine realm.",
222
+ });
223
+ return;
224
+ }
225
+
226
+ let frame = null;
227
+ try {
228
+ frame = doc.createElement("iframe");
229
+ frame.setAttribute("aria-hidden", "true");
230
+ frame.style.display = "none";
231
+ doc.body.appendChild(frame);
232
+
233
+ const other = frame.contentWindow;
234
+ const pristineToString = resolvePath(other, "Function.prototype.toString");
235
+ if (typeof pristineToString !== "function") {
236
+ findings.push({
237
+ check: "crossRealm",
238
+ marker: "realmUnavailable",
239
+ severity: "unavailable",
240
+ detail: "Pristine realm produced no Function.prototype.toString; a CSP " +
241
+ "(frame-src) or sandbox probably blocked the iframe. Could not look " +
242
+ "is not the same as nothing found.",
243
+ });
244
+ return;
245
+ }
246
+
247
+ for (let i = 0; i < watch.length; i++) {
248
+ const path = watch[i];
249
+ const mine = resolvePath(win, path);
250
+ if (typeof mine !== "function") continue;
251
+ // Ask the *pristine* realm's toString about our function.
252
+ if (looksNative(pristineToString, mine) === false) {
253
+ findings.push({
254
+ check: "crossRealm",
255
+ marker: path,
256
+ severity: "high",
257
+ detail: path + " fails the pristine-realm native check. This survives a " +
258
+ "hook that spoofs its own toString in the main realm.",
259
+ });
260
+ }
261
+ }
262
+ } catch (e) {
263
+ findings.push({
264
+ check: "crossRealm",
265
+ marker: "realmError",
266
+ severity: "unavailable",
267
+ detail: "Building the pristine realm threw: " + (e && e.message ? e.message : String(e)),
268
+ });
269
+ } finally {
270
+ // Always clean up; leaving the probe iframe attached would
271
+ // itself be an observable side effect.
272
+ try {
273
+ if (frame && frame.parentNode) frame.parentNode.removeChild(frame);
274
+ } catch (e) { /* nothing useful to do */ }
275
+ }
276
+ }
277
+
278
+ function checkAutomation(win, findings) {
279
+ const nav = win && win.navigator;
280
+
281
+ if (nav && nav.webdriver === true) {
282
+ findings.push({
283
+ check: "automation",
284
+ marker: "navigator.webdriver",
285
+ severity: "signal",
286
+ detail: "navigator.webdriver is true, i.e. the page reports being driven. " +
287
+ "Trivially patchable, so treat as a signal rather than proof.",
288
+ });
289
+ }
290
+
291
+ for (let i = 0; i < AUTOMATION_GLOBALS.length; i++) {
292
+ const name = AUTOMATION_GLOBALS[i];
293
+ let present = false;
294
+ try {
295
+ present = win ? (name in win) : false;
296
+ } catch (e) {
297
+ present = false;
298
+ }
299
+ if (present) {
300
+ findings.push({
301
+ check: "automation",
302
+ marker: name,
303
+ severity: "signal",
304
+ detail: "Automation global '" + name + "' is present, which a driver " +
305
+ "injected and did not clean up.",
306
+ });
307
+ }
308
+ }
309
+
310
+ // Chrome DevTools Protocol drivers leave `cdc_`-prefixed keys on
311
+ // window and document.
312
+ const cdcHosts = [["window", win], ["document", win && win.document]];
313
+ for (let h = 0; h < cdcHosts.length; h++) {
314
+ const host = cdcHosts[h][1];
315
+ if (!host) continue;
316
+ let keys = [];
317
+ try {
318
+ keys = Object.getOwnPropertyNames(host);
319
+ } catch (e) {
320
+ keys = [];
321
+ }
322
+ for (let k = 0; k < keys.length; k++) {
323
+ if (keys[k].indexOf("cdc_") === 0) {
324
+ findings.push({
325
+ check: "automation",
326
+ marker: cdcHosts[h][0] + "." + keys[k],
327
+ severity: "signal",
328
+ detail: "A cdc_-prefixed property indicates a ChromeDriver-family tool.",
329
+ });
330
+ break; // one per host is enough evidence
331
+ }
332
+ }
333
+ }
334
+ }
335
+
336
+ function inspect(win) {
337
+ const findings = [];
338
+ if (checks.indexOf("hookedBuiltins") !== -1) checkHookedBuiltins(win, findings);
339
+ if (checks.indexOf("crossRealm") !== -1) checkCrossRealm(win, findings);
340
+ if (checks.indexOf("automation") !== -1) checkAutomation(win, findings);
341
+
342
+ let high = 0, signal = 0, unavailable = 0;
343
+ for (let i = 0; i < findings.length; i++) {
344
+ if (findings[i].severity === "high") high++;
345
+ else if (findings[i].severity === "signal") signal++;
346
+ else unavailable++;
347
+ }
348
+
349
+ // `ok` means "found nothing actionable". Unavailable checks do
350
+ // NOT clear the report on their own, so a caller that only looks
351
+ // at `ok` still learns that something could not be verified.
352
+ const report = {
353
+ ok: high === 0 && signal === 0,
354
+ counts: { high: high, signal: signal, unavailable: unavailable },
355
+ complete: unavailable === 0,
356
+ findings: findings,
357
+ };
358
+
359
+ // Shaped for countermeasures.react(win, violation).
360
+ report.violation = {
361
+ reason: high > 0 ? "environment-hooked"
362
+ : signal > 0 ? "automation-signal"
363
+ : "environment-unverified",
364
+ src: "environment-integrity",
365
+ findings: findings,
366
+ };
367
+ return report;
368
+ }
369
+
370
+ function describe() {
371
+ return {
372
+ checks: checks.slice(),
373
+ watch: watch.slice(),
374
+ };
375
+ }
376
+
377
+ return {
378
+ ALL_CHECKS: ALL_CHECKS.slice(),
379
+ inspect: inspect,
380
+ describe: describe,
381
+ };
382
+ }
383
+
384
+ module.exports = {
385
+ ALL_CHECKS: ALL_CHECKS.slice(),
386
+ DEFAULT_WATCH: DEFAULT_WATCH.slice(),
387
+ AUTOMATION_GLOBALS: AUTOMATION_GLOBALS.slice(),
388
+ createEnvironmentIntegrityPolicy: createEnvironmentIntegrityPolicy,
389
+ };
@@ -0,0 +1,4 @@
1
+ export interface ManagedIntegrityPolicy { id: string; version: string; mode: "monitor" | "block"; allowedOrigins: readonly string[]; allowedInlineHashes: readonly string[]; expectedContentBySrc: Readonly<Record<string, string>>; blockLateInjection: boolean; effectiveAt: string; }
2
+ export declare function createManagedIntegrityPolicy(input: { id: string; version: string; mode?: "monitor" | "block"; allowedOrigins?: string[]; allowedInlineHashes?: string[]; expectedContentBySrc?: Record<string, string>; blockLateInjection?: boolean; effectiveAt?: string | Date }): ManagedIntegrityPolicy;
3
+ export declare function evaluateSnapshot(policy: ManagedIntegrityPolicy, snapshot: { buildId?: string; pageHref?: string; scripts: object[] }): { v: 1; kind: "managed-integrity-decision"; verdict: "clean" | "violation"; action: "monitor" | "block"; violations: object[]; };
4
+ export declare function createIntegrityOperations(config?: { now?: () => string }): { ingest(decision: object): object[]; transition(id: string, status: "open" | "reviewing" | "resolved" | "ignored", metadata?: { assignee?: string; resolution?: string }): object | null; list(status?: string): object[]; exportJson(): string; };
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ // Versioned policy evaluation and incident operations for managed browser
4
+ // integrity. The browser sensor remains third-party-inventory.js; this module
5
+ // supplies the control-plane contract used by a hosted worker or an on-prem
6
+ // collector without coupling policy decisions to a particular database.
7
+
8
+ const VALID_MODES = Object.freeze(["monitor", "block"]);
9
+ const VALID_STATUSES = Object.freeze(["open", "reviewing", "resolved", "ignored"]);
10
+
11
+ function normalizeOrigin(value) {
12
+ const parsed = new URL(String(value));
13
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new Error("managed-integrity: origins must use http(s)");
14
+ return parsed.origin;
15
+ }
16
+
17
+ function createManagedIntegrityPolicy(input) {
18
+ input = input || {};
19
+ if (!input.id || !input.version) throw new Error("managed-integrity: policy id and version are required");
20
+ const mode = String(input.mode || "monitor").toLowerCase();
21
+ if (!VALID_MODES.includes(mode)) throw new Error("managed-integrity: mode must be monitor or block");
22
+ const origins = Array.from(new Set((input.allowedOrigins || []).map(normalizeOrigin))).sort();
23
+ const hashes = Array.from(new Set((input.allowedInlineHashes || []).map((value) => String(value).toLowerCase()))).sort();
24
+ const expectedContent = Object.freeze(Object.assign({}, input.expectedContentBySrc || {}));
25
+ return Object.freeze({
26
+ id: String(input.id), version: String(input.version), mode,
27
+ allowedOrigins: Object.freeze(origins),
28
+ allowedInlineHashes: Object.freeze(hashes),
29
+ expectedContentBySrc: expectedContent,
30
+ blockLateInjection: input.blockLateInjection !== false,
31
+ effectiveAt: new Date(input.effectiveAt || Date.now()).toISOString()
32
+ });
33
+ }
34
+
35
+ function evaluateSnapshot(policy, snapshot) {
36
+ if (!policy || !snapshot || !Array.isArray(snapshot.scripts)) throw new Error("managed-integrity: policy and inventory snapshot are required");
37
+ const violations = [];
38
+ for (const script of snapshot.scripts) {
39
+ const row = Object.assign({}, script);
40
+ if (row.inline) {
41
+ if (!row.sha256 || !policy.allowedInlineHashes.includes(String(row.sha256).toLowerCase())) violations.push(Object.assign({ reason: "unknown-inline-content" }, row));
42
+ } else {
43
+ let origin = null;
44
+ try { origin = normalizeOrigin(row.src); } catch (_) {}
45
+ if (!origin || !policy.allowedOrigins.includes(origin)) violations.push(Object.assign({ reason: "unknown-origin" }, row));
46
+ const expected = row.src && policy.expectedContentBySrc[row.src];
47
+ if (expected && row.sha256 && expected !== row.sha256) violations.push(Object.assign({ reason: "content-hash-mismatch", expectedSha256: expected }, row));
48
+ if (policy.blockLateInjection && row.injectedAfterLoad) violations.push(Object.assign({ reason: "late-script-injection" }, row));
49
+ }
50
+ }
51
+ const unique = [];
52
+ const seen = new Set();
53
+ for (const violation of violations) {
54
+ const key = [violation.reason, violation.src || "inline", violation.sha256 || ""].join("|");
55
+ if (!seen.has(key)) { seen.add(key); unique.push(violation); }
56
+ }
57
+ return {
58
+ v: 1, kind: "managed-integrity-decision", policyId: policy.id, policyVersion: policy.version,
59
+ buildId: snapshot.buildId || null, pageHref: snapshot.pageHref || null,
60
+ verdict: unique.length ? "violation" : "clean",
61
+ action: unique.length && policy.mode === "block" ? "block" : "monitor",
62
+ violations: unique
63
+ };
64
+ }
65
+
66
+ function createIntegrityOperations(config) {
67
+ config = config || {};
68
+ const incidents = new Map();
69
+ let sequence = 0;
70
+ const now = typeof config.now === "function" ? config.now : () => new Date().toISOString();
71
+
72
+ function ingest(decision) {
73
+ if (!decision || decision.verdict !== "violation") return [];
74
+ const touched = [];
75
+ for (const violation of decision.violations || []) {
76
+ const fingerprint = [decision.policyId, decision.buildId || "", decision.pageHref || "", violation.reason, violation.src || violation.sha256 || "unknown"].join("|");
77
+ let incident = incidents.get(fingerprint);
78
+ if (incident && incident.status !== "resolved" && incident.status !== "ignored") {
79
+ incident.count++; incident.lastSeenAt = now();
80
+ } else {
81
+ incident = { id: "wpi-" + (++sequence), fingerprint, policyId: decision.policyId, policyVersion: decision.policyVersion, buildId: decision.buildId, pageHref: decision.pageHref, reason: violation.reason, src: violation.src || null, sha256: violation.sha256 || null, action: decision.action, status: "open", count: 1, firstSeenAt: now(), lastSeenAt: now(), assignee: null, resolution: null };
82
+ incidents.set(fingerprint, incident);
83
+ }
84
+ touched.push(Object.assign({}, incident));
85
+ }
86
+ return touched;
87
+ }
88
+
89
+ function transition(id, status, metadata) {
90
+ status = String(status || "").toLowerCase();
91
+ if (!VALID_STATUSES.includes(status)) throw new Error("managed-integrity: invalid incident status");
92
+ const incident = Array.from(incidents.values()).find((row) => row.id === String(id));
93
+ if (!incident) return null;
94
+ incident.status = status;
95
+ incident.assignee = metadata && metadata.assignee != null ? String(metadata.assignee) : incident.assignee;
96
+ incident.resolution = metadata && metadata.resolution != null ? String(metadata.resolution) : incident.resolution;
97
+ incident.updatedAt = now();
98
+ return Object.assign({}, incident);
99
+ }
100
+
101
+ return {
102
+ ingest, transition,
103
+ list: (status) => Array.from(incidents.values()).filter((row) => !status || row.status === status).map((row) => Object.assign({}, row)),
104
+ exportJson: () => JSON.stringify({ v: 1, kind: "managed-integrity-incidents", incidents: Array.from(incidents.values()) }, null, 2)
105
+ };
106
+ }
107
+
108
+ module.exports = { VALID_MODES, VALID_STATUSES, createManagedIntegrityPolicy, evaluateSnapshot, createIntegrityOperations };