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,437 @@
1
+ "use strict";
2
+
3
+ // Third-party script inventory + Magecart detection (browser runtime module).
4
+ //
5
+ // Pure browser code — no Node APIs. Add to a protected output to:
6
+ //
7
+ // 1. snapshot every <script> element present at DOMContentLoaded;
8
+ // 2. intercept document.createElement("script") so DOM-injected
9
+ // scripts are recorded the moment they're created (even if the
10
+ // attacker tries to remove them before they execute);
11
+ // 3. observe PerformanceObserver "resource" entries for any script
12
+ // load that bypassed createElement (e.g. <iframe>-injected,
13
+ // worker importScripts, ServiceWorker fetches);
14
+ // 4. compare each observed script against an allowlist of script
15
+ // origins + inline content hashes. Anything outside the allowlist
16
+ // is a "violation" and gets POSTed to the beacon URL together
17
+ // with the full inventory snapshot.
18
+ //
19
+ // Threat model
20
+ // ------------
21
+ // Targets the Magecart family of card-skimming attacks: an adversary
22
+ // who has gained access to one third-party dependency (CDN, tag
23
+ // manager, marketing script) and is injecting a payment-skimming
24
+ // snippet into the page. The defender has the JSO-protected core
25
+ // application; this module's job is to catch the *uninvited guest*
26
+ // (a script the build pipeline didn't sign off on) and raise an
27
+ // alarm BEFORE the user types card data.
28
+ //
29
+ // Detection signals
30
+ // -----------------
31
+ // - script `src` not in the configured `originAllowlist`;
32
+ // - inline `<script>` whose sha256 is not in `inlineContentAllowlist`;
33
+ // - script DOM-injected AFTER document.readyState === "complete"
34
+ // (deferred-injection is a common Magecart evasion pattern);
35
+ // - same script URL but the content sha256 changed between page loads
36
+ // (catches "supply-chain swap" attacks where the URL is in the
37
+ // allowlist but the upstream CDN has been compromised).
38
+ //
39
+ // What this module does NOT do
40
+ // ----------------------------
41
+ // It does not BLOCK malicious scripts. By the time we observe a
42
+ // violation the script may already be in the DOM. The module exists
43
+ // to *evidence* the attack to your on-call rotation; pair it with
44
+ // Content-Security-Policy + Subresource-Integrity for in-line
45
+ // blocking. Use jso-beacon-slack to pipe the violation events to
46
+ // Slack / Splunk / Elasticsearch.
47
+ //
48
+ // Public API (Node + browser)
49
+ // ---------------------------
50
+ // const tpi = require("jso-protector/runtime/third-party-inventory");
51
+ // const engine = tpi.createInventoryEngine({
52
+ // originAllowlist: ["https://www.example.com", "https://cdn.example.com"],
53
+ // inlineContentAllowlist: ["a3f5...", "b07e..."], // sha256 hex
54
+ // beaconUrl: "https://beacon.example.com/v1/jso/inventory",
55
+ // beaconSecret: "<HMAC-SHA256 key>", // optional
56
+ // flushIntervalMs: 15000, // 15s
57
+ // });
58
+ // // pure-data path (testable):
59
+ // engine.recordScript({ src: "...", inline: null, sha256: "..." });
60
+ // engine.recordScript({ src: null, inline: "alert(1)", sha256: "..." });
61
+ // const snapshot = engine.snapshot();
62
+ // const violations = engine.violations();
63
+ //
64
+ // // DOM-attached path (browser only):
65
+ // tpi.attach(window, { ...config });
66
+ //
67
+ // Wire format of beacon POST
68
+ // --------------------------
69
+ // Same envelope shape as the rest of the runtime-defense beacon so
70
+ // jso-beacon-slack can forward it without an adapter change:
71
+ //
72
+ // {
73
+ // v: 1,
74
+ // kind: "inventory",
75
+ // buildId: "<from window.__jsoBuildId>",
76
+ // pageHref: "https://...",
77
+ // observedAt: "2026-06-02T13:14:15Z",
78
+ // scripts: [
79
+ // {
80
+ // src, sha256, inline:bool, injectedAfterLoad:bool, allowlisted:bool,
81
+ // checkoutSurface, frameContext, frameOwner, parentPageHref, frameHref, frameOrigin
82
+ // },
83
+ // ...
84
+ // ],
85
+ // violations: [ { reason, ...row } ],
86
+ // }
87
+
88
+ const SCHEMA_VERSION = 1;
89
+ const DEFAULT_FLUSH_INTERVAL_MS = 15000;
90
+ const MAX_INVENTORY_SIZE = 500;
91
+
92
+ // ---- pure engine (Node-testable) ------------------------------------------
93
+
94
+ function createInventoryEngine(config) {
95
+ config = config || {};
96
+ const originAllowlist = Array.isArray(config.originAllowlist) ? config.originAllowlist.slice() : [];
97
+ const inlineContentAllowlist = new Set(Array.isArray(config.inlineContentAllowlist) ? config.inlineContentAllowlist : []);
98
+ const previousContentBySrc = (config.previousContentBySrc && typeof config.previousContentBySrc === "object")
99
+ ? config.previousContentBySrc
100
+ : {};
101
+
102
+ const scripts = []; // [{ src, sha256, inline, injectedAfterLoad, allowlisted, observedAt, surface metadata }]
103
+ const violations = []; // [{ reason, ...script }]
104
+ const seenKeys = new Set(); // dedup by (src || "inline:" + sha256)
105
+
106
+ function originOf(url) {
107
+ try {
108
+ const u = new URL(url, "https://example.com/");
109
+ return u.origin;
110
+ } catch (e) {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ function isOriginAllowlisted(src) {
116
+ if (!src) return true; // inline; allowlist by content not origin
117
+ const origin = originOf(src);
118
+ if (!origin) return false;
119
+ for (const allowed of originAllowlist) {
120
+ if (allowed === origin) return true;
121
+ if (allowed === "*") return true;
122
+ // Trailing-slash tolerance: "https://x.com/" matches "https://x.com"
123
+ if (allowed.replace(/\/+$/, "") === origin) return true;
124
+ }
125
+ return false;
126
+ }
127
+
128
+ function recordScript(row) {
129
+ if (!row || typeof row !== "object") return { recorded: false, allowed: false, violations: [] };
130
+ const src = row.src || null;
131
+ const sha256 = row.sha256 || null;
132
+ const inline = !src;
133
+ const injectedAfterLoad = !!row.injectedAfterLoad;
134
+
135
+ const key = src || ("inline:" + (sha256 || "no-hash"));
136
+ if (seenKeys.has(key)) return { recorded: false, allowed: true, violations: [] };
137
+ // Back-pressure: check the cap BEFORE adding to seenKeys.
138
+ // Previously seenKeys grew unbounded even when scripts was
139
+ // capped, leaving long-lived pages vulnerable to a memory DoS
140
+ // via a spray of unique attacker-controlled src URLs.
141
+ if (scripts.length >= MAX_INVENTORY_SIZE) return { recorded: false, allowed: false, violations: [{ reason: "inventory-cap-exceeded" }] };
142
+ seenKeys.add(key);
143
+ const violationStart = violations.length;
144
+
145
+ const allowlisted = inline
146
+ ? (sha256 ? inlineContentAllowlist.has(sha256) : false)
147
+ : isOriginAllowlisted(src);
148
+
149
+ const out = {
150
+ src: src,
151
+ sha256: sha256,
152
+ inline: inline,
153
+ injectedAfterLoad: injectedAfterLoad,
154
+ allowlisted: allowlisted,
155
+ observedAt: row.observedAt || null,
156
+ checkoutSurface: surfaceValue(row.checkoutSurface || row.paymentSurface || config.checkoutSurface || config.paymentSurface),
157
+ frameContext: surfaceValue(row.frameContext || config.frameContext),
158
+ frameOwner: surfaceValue(row.frameOwner || config.frameOwner),
159
+ parentPageHref: surfaceValue(row.parentPageHref || config.parentPageHref),
160
+ frameHref: surfaceValue(row.frameHref || config.frameHref),
161
+ frameOrigin: surfaceValue(row.frameOrigin || config.frameOrigin),
162
+ };
163
+ scripts.push(out);
164
+
165
+ // Violation rules
166
+ if (!allowlisted) {
167
+ violations.push(Object.assign({ reason: inline ? "unknown-inline-content" : "unknown-origin" }, out));
168
+ }
169
+ if (injectedAfterLoad && !inline && config.blockLateInjection !== false) {
170
+ violations.push(Object.assign({ reason: "injected-after-load" }, out));
171
+ }
172
+ // Use hasOwnProperty.call to defeat prototype-chain lookups.
173
+ // An attacker with control over a script src (e.g.
174
+ // <script src="toString">) used to trigger a false
175
+ // content-changed-vs-previous-deploy alarm because
176
+ // `previousContentBySrc["toString"]` resolves to the inherited
177
+ // Object.prototype.toString method.
178
+ if (src && sha256) {
179
+ const prev = Object.prototype.hasOwnProperty.call(previousContentBySrc, src)
180
+ ? previousContentBySrc[src]
181
+ : null;
182
+ if (prev && prev !== sha256) {
183
+ violations.push(Object.assign(
184
+ { reason: "content-changed-vs-previous-deploy", previousSha256: prev },
185
+ out
186
+ ));
187
+ }
188
+ }
189
+ const newViolations = violations.slice(violationStart);
190
+ return { recorded: true, allowed: newViolations.length === 0, script: out, violations: newViolations };
191
+ }
192
+
193
+ function surfaceValue(value) {
194
+ if (value == null) return null;
195
+ const text = String(value).trim();
196
+ return text || null;
197
+ }
198
+
199
+ function snapshot() {
200
+ return {
201
+ v: SCHEMA_VERSION,
202
+ kind: "inventory",
203
+ buildId: config.buildId || null,
204
+ pageHref: config.pageHref || null,
205
+ scripts: scripts.slice(),
206
+ violations: violations.slice(),
207
+ };
208
+ }
209
+
210
+ function violationsOnly() {
211
+ return violations.slice();
212
+ }
213
+
214
+ function size() {
215
+ return scripts.length;
216
+ }
217
+
218
+ function reset() {
219
+ scripts.length = 0;
220
+ violations.length = 0;
221
+ seenKeys.clear();
222
+ }
223
+
224
+ return {
225
+ SCHEMA_VERSION: SCHEMA_VERSION,
226
+ recordScript: recordScript,
227
+ snapshot: snapshot,
228
+ violations: violationsOnly,
229
+ size: size,
230
+ reset: reset,
231
+ _seenKeysForTest: function () { return new Set(seenKeys); },
232
+ };
233
+ }
234
+
235
+ // ---- browser bootstrap -----------------------------------------------------
236
+ //
237
+ // attach(window, config) wires DOM listeners + PerformanceObserver onto
238
+ // the engine. Safe to call before or after DOMContentLoaded. No-op if
239
+ // the global window already has `__jsoTpiAttached === true` (idempotent).
240
+
241
+ function attach(win, config) {
242
+ if (!win || typeof win !== "object") {
243
+ throw new Error("third-party-inventory.attach: window object required");
244
+ }
245
+ if (win.__jsoTpiAttached) return win.__jsoTpiAttached;
246
+
247
+ const engine = createInventoryEngine(config);
248
+ const doc = win.document;
249
+ const observedAt = function () {
250
+ return new Date().toISOString();
251
+ };
252
+
253
+ async function sha256Hex(text) {
254
+ if (!win.crypto || !win.crypto.subtle) return null;
255
+ const enc = new win.TextEncoder().encode(text);
256
+ const buf = await win.crypto.subtle.digest("SHA-256", enc);
257
+ const bytes = new Uint8Array(buf);
258
+ let hex = "";
259
+ for (let i = 0; i < bytes.length; i++) {
260
+ hex += bytes[i].toString(16).padStart(2, "0");
261
+ }
262
+ return hex;
263
+ }
264
+
265
+ // 1. Snapshot existing <script> elements.
266
+ function snapshotExisting() {
267
+ if (!doc || !doc.querySelectorAll) return;
268
+ const nodes = doc.querySelectorAll("script");
269
+ const promises = [];
270
+ for (let i = 0; i < nodes.length; i++) {
271
+ const s = nodes[i];
272
+ if (s.src) {
273
+ engine.recordScript({ src: s.src, sha256: null, observedAt: observedAt() });
274
+ } else if (s.textContent) {
275
+ const t = s.textContent;
276
+ promises.push(sha256Hex(t).then(function (hex) {
277
+ engine.recordScript({ src: null, sha256: hex, inline: true, observedAt: observedAt() });
278
+ }));
279
+ }
280
+ }
281
+ return Promise.all(promises);
282
+ }
283
+
284
+ // 2. Intercept document.createElement("script").
285
+ function interceptCreate() {
286
+ if (!doc || !doc.createElement) return;
287
+ const orig = doc.createElement.bind(doc);
288
+ doc.createElement = function (tag) {
289
+ const el = orig.apply(this, arguments);
290
+ if (typeof tag === "string" && tag.toLowerCase() === "script") {
291
+ // Defer reading src until the consumer sets it.
292
+ let _src = "";
293
+ let _text = "";
294
+ const srcDescriptor = Object.getOwnPropertyDescriptor(el, "src") || { set: undefined, get: undefined };
295
+ try {
296
+ Object.defineProperty(el, "src", {
297
+ configurable: true,
298
+ enumerable: true,
299
+ get: function () { return _src; },
300
+ set: function (v) {
301
+ _src = String(v);
302
+ const decision = engine.recordScript({
303
+ src: _src,
304
+ sha256: null,
305
+ injectedAfterLoad: (doc.readyState === "complete"),
306
+ observedAt: observedAt(),
307
+ });
308
+ if (config.enforcementMode === "block" && decision && !decision.allowed) {
309
+ try { el.type = "application/x-jso-blocked"; el.setAttribute("data-jso-blocked-src", _src); } catch (e) {}
310
+ if (typeof config.onBlocked === "function") { try { config.onBlocked(decision); } catch (e) {} }
311
+ try {
312
+ if (typeof win.dispatchEvent === "function" && typeof win.CustomEvent === "function") {
313
+ win.dispatchEvent(new win.CustomEvent("jso:script-blocked", { detail: decision }));
314
+ }
315
+ } catch (e) {}
316
+ return;
317
+ }
318
+ if (srcDescriptor && srcDescriptor.set) srcDescriptor.set.call(el, v);
319
+ else el.setAttribute("src", v);
320
+ },
321
+ });
322
+ } catch (e) { /* swallow; some hosts freeze prototypes */ }
323
+ // Also catch inline body via textContent setter
324
+ try {
325
+ const textDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "textContent") || {};
326
+ Object.defineProperty(el, "textContent", {
327
+ configurable: true,
328
+ enumerable: true,
329
+ get: function () { return _text; },
330
+ set: function (v) {
331
+ _text = String(v);
332
+ sha256Hex(_text).then(function (hex) {
333
+ engine.recordScript({
334
+ src: null,
335
+ sha256: hex,
336
+ inline: true,
337
+ injectedAfterLoad: (doc.readyState === "complete"),
338
+ observedAt: observedAt(),
339
+ });
340
+ }).catch(function () { /* swallow */ });
341
+ if (textDescriptor && textDescriptor.set) textDescriptor.set.call(el, v);
342
+ },
343
+ });
344
+ } catch (e) { /* swallow */ }
345
+ }
346
+ return el;
347
+ };
348
+ }
349
+
350
+ // 3. PerformanceObserver fallback for script loads that bypassed createElement.
351
+ function observeResources() {
352
+ if (typeof win.PerformanceObserver !== "function") return;
353
+ try {
354
+ const po = new win.PerformanceObserver(function (list) {
355
+ for (const entry of list.getEntries()) {
356
+ if (entry.initiatorType !== "script") continue;
357
+ engine.recordScript({
358
+ src: entry.name,
359
+ sha256: null,
360
+ injectedAfterLoad: (doc.readyState === "complete"),
361
+ observedAt: observedAt(),
362
+ });
363
+ }
364
+ });
365
+ po.observe({ entryTypes: ["resource"] });
366
+ } catch (e) { /* swallow */ }
367
+ }
368
+
369
+ // 4. Periodically flush violations to the beacon URL.
370
+ function setupBeaconFlush() {
371
+ if (!config.beaconUrl) return;
372
+ const interval = (typeof config.flushIntervalMs === "number" && config.flushIntervalMs > 0)
373
+ ? config.flushIntervalMs
374
+ : DEFAULT_FLUSH_INTERVAL_MS;
375
+ let lastSent = 0;
376
+ function flush() {
377
+ const v = engine.violations();
378
+ if (v.length === lastSent) return;
379
+ lastSent = v.length;
380
+ const body = JSON.stringify(engine.snapshot());
381
+ try {
382
+ if (typeof win.fetch === "function") {
383
+ win.fetch(config.beaconUrl, {
384
+ method: "POST",
385
+ headers: { "Content-Type": "application/json" },
386
+ body: body,
387
+ keepalive: true,
388
+ credentials: "omit",
389
+ }).catch(function () { /* swallow */ });
390
+ } else if (typeof win.navigator !== "undefined" && win.navigator.sendBeacon) {
391
+ win.navigator.sendBeacon(config.beaconUrl, body);
392
+ }
393
+ } catch (e) { /* swallow */ }
394
+ }
395
+ win.setInterval(flush, interval);
396
+ // Flush on pagehide for last-second violations.
397
+ if (typeof win.addEventListener === "function") {
398
+ win.addEventListener("pagehide", flush, false);
399
+ }
400
+ }
401
+
402
+ interceptCreate();
403
+ observeResources();
404
+ setupBeaconFlush();
405
+ // Run snapshot async to avoid blocking the page load.
406
+ Promise.resolve().then(snapshotExisting).catch(function () { /* swallow */ });
407
+
408
+ win.__jsoTpiAttached = engine;
409
+ return engine;
410
+ }
411
+
412
+ async function attachFromPolicy(win, config) {
413
+ config = config || {};
414
+ if (!win || typeof win.fetch !== "function") throw new Error("third-party-inventory.attachFromPolicy: fetch-capable window required");
415
+ if (!config.policyUrl) throw new Error("third-party-inventory.attachFromPolicy: policyUrl is required");
416
+ const response = await win.fetch(config.policyUrl, { method: "GET", credentials: "omit", cache: "no-cache" });
417
+ if (!response || response.ok === false || typeof response.json !== "function") throw new Error("third-party-inventory.attachFromPolicy: policy request failed");
418
+ const policy = await response.json();
419
+ if (!policy || policy.kind !== "managed-integrity-policy" || !policy.id || !policy.version) throw new Error("third-party-inventory.attachFromPolicy: invalid managed policy");
420
+ const merged = Object.assign({}, config, {
421
+ originAllowlist: Array.isArray(policy.allowedOrigins) ? policy.allowedOrigins : [],
422
+ inlineContentAllowlist: Array.isArray(policy.allowedInlineHashes) ? policy.allowedInlineHashes : [],
423
+ enforcementMode: policy.mode === "block" ? "block" : "monitor",
424
+ blockLateInjection: policy.blockLateInjection !== false,
425
+ policyId: policy.id,
426
+ policyVersion: policy.version,
427
+ });
428
+ delete merged.policyUrl;
429
+ return attach(win, merged);
430
+ }
431
+
432
+ module.exports = {
433
+ SCHEMA_VERSION: SCHEMA_VERSION,
434
+ createInventoryEngine: createInventoryEngine,
435
+ attach: attach,
436
+ attachFromPolicy: attachFromPolicy,
437
+ };
package/turbopack.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { ProtectionOptions, ProtectionPlan, ProtectionRunResult, ResolvedProtectionConfig } from "./index";
2
+
3
+ export interface JsoProtectorTurbopackOptions extends ProtectionOptions {}
4
+
5
+ declare function protectTurbopackBuild(options?: JsoProtectorTurbopackOptions): Promise<ProtectionRunResult>;
6
+ declare function createTurbopackProtectionConfig(options?: JsoProtectorTurbopackOptions): ResolvedProtectionConfig;
7
+ declare function planTurbopackBuild(options?: JsoProtectorTurbopackOptions): ProtectionPlan;
8
+
9
+ export { createTurbopackProtectionConfig, planTurbopackBuild, protectTurbopackBuild };
10
+ export default protectTurbopackBuild;
package/turbopack.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+
3
+ const { createProtectionConfig, planProtection, protectFiles } = require("./index.js");
4
+
5
+ function createTurbopackProtectionConfig(options = {}) {
6
+ return createProtectionConfig({
7
+ input: ".next/static",
8
+ output: ".next/static-protected",
9
+ preset: "balanced",
10
+ include: ["chunks/*.js", "chunks/**/*.js"],
11
+ exclude: ["**/*.map", "**/webpack-*.js", "**/polyfills-*.js"],
12
+ assetExclude: ["**/*.map"],
13
+ maxGrowthRatio: 8,
14
+ manifest: defaultManifestForOutput(options, ".next/static-protected/jso-manifest.json"),
15
+ ...options
16
+ });
17
+ }
18
+
19
+ function planTurbopackBuild(options = {}) {
20
+ return planProtection(createTurbopackProtectionConfig(options));
21
+ }
22
+
23
+ async function protectTurbopackBuild(options = {}) {
24
+ return protectFiles(createTurbopackProtectionConfig(options));
25
+ }
26
+
27
+ function defaultManifestForOutput(options, fallback) {
28
+ if (Object.prototype.hasOwnProperty.call(options || {}, "manifest")) {
29
+ return options.manifest;
30
+ }
31
+ if (options && options.output) {
32
+ return `${String(options.output).replace(/[\\/]$/, "")}/jso-manifest.json`;
33
+ }
34
+ return fallback;
35
+ }
36
+
37
+ module.exports = protectTurbopackBuild;
38
+ module.exports.createTurbopackProtectionConfig = createTurbopackProtectionConfig;
39
+ module.exports.planTurbopackBuild = planTurbopackBuild;
40
+ module.exports.protectTurbopackBuild = protectTurbopackBuild;
41
+ module.exports.default = protectTurbopackBuild;
package/vite.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { ProtectionOptions } from "./index";
2
+
3
+ export interface JsoProtectorPluginOptions extends ProtectionOptions {
4
+ removeSourceMaps?: boolean;
5
+ }
6
+
7
+ declare function jsoProtector(options?: JsoProtectorPluginOptions): {
8
+ name: "jso-protector";
9
+ apply: "build";
10
+ enforce: "post";
11
+ configResolved(resolvedConfig: unknown): void;
12
+ generateBundle(outputOptions: unknown, bundle: Record<string, unknown>): Promise<void>;
13
+ };
14
+
15
+ export { jsoProtector };
16
+ export default jsoProtector;
package/vite.js ADDED
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const { assertSizeBudgets, buildItemsManifest, buildProtectionItemsFromInputItems, composeProtectionItemOutput, createProtectionConfig, isExcluded, protectItems, writeManifest } = require("./index.js");
4
+
5
+ function jsoProtector(options = {}) {
6
+ let config = null;
7
+ const removeSourceMaps = options.removeSourceMaps !== false;
8
+
9
+ return {
10
+ name: "jso-protector",
11
+ apply: "build",
12
+ enforce: "post",
13
+ configResolved(resolvedConfig) {
14
+ const outDir = resolvedConfig && resolvedConfig.build && resolvedConfig.build.outDir
15
+ ? resolvedConfig.build.outDir
16
+ : "dist";
17
+ config = createProtectionConfig({
18
+ input: outDir,
19
+ output: outDir,
20
+ ...options
21
+ });
22
+ },
23
+ async generateBundle(_outputOptions, bundle) {
24
+ if (!config) {
25
+ config = createProtectionConfig(options);
26
+ }
27
+
28
+ const chunks = Object.values(bundle).filter((entry) => (
29
+ entry &&
30
+ entry.type === "chunk" &&
31
+ typeof entry.code === "string" &&
32
+ entry.fileName &&
33
+ entry.fileName.endsWith(".js") &&
34
+ shouldProtectAsset(entry.fileName, config, options)
35
+ ));
36
+
37
+ if (!chunks.length) return;
38
+
39
+ const inputItems = chunks.map((chunk) => ({
40
+ FileName: chunk.fileName,
41
+ FileCode: chunk.code
42
+ }));
43
+ const protection = buildProtectionItemsFromInputItems(config, inputItems);
44
+ const result = await protectItems(config, protection.items);
45
+ const manifest = buildItemsManifest(config, inputItems, result, (fileName) => fileName, protection.transforms);
46
+ assertSizeBudgets(manifest, config);
47
+
48
+ for (const chunk of chunks) {
49
+ chunk.code = composeProtectionItemOutput(chunk.fileName, result, protection.transforms, config);
50
+ if (removeSourceMaps) {
51
+ chunk.map = null;
52
+ delete bundle[`${chunk.fileName}.map`];
53
+ }
54
+ }
55
+
56
+ if (config.manifest) {
57
+ writeManifest(config.manifest, manifest);
58
+ }
59
+ }
60
+ };
61
+ }
62
+
63
+ function normalizeName(name) {
64
+ return String(name || "").replace(/\\/g, "/");
65
+ }
66
+
67
+ function shouldProtectAsset(fileName, config, options) {
68
+ const normalized = normalizeName(fileName);
69
+ const include = Array.isArray(config.include) && config.include.length ? config.include : options.include;
70
+ if (Array.isArray(include) && include.length && !isExcluded(normalized, include)) {
71
+ return false;
72
+ }
73
+ return !isExcluded(normalized, config.exclude || []);
74
+ }
75
+
76
+ module.exports = jsoProtector;
77
+ module.exports.jsoProtector = jsoProtector;
78
+ module.exports.default = jsoProtector;