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.
- package/CHANGELOG.md +960 -0
- package/LICENSE +90 -0
- package/MIGRATION.md +207 -0
- package/README.md +1477 -0
- package/RELEASE.md +82 -0
- package/SECURITY.md +71 -0
- package/ai-cli.js +392 -0
- package/ai.js +176 -0
- package/bin/jso-protector.js +12066 -0
- package/browserify.d.ts +10 -0
- package/browserify.js +88 -0
- package/bun.d.ts +10 -0
- package/bun.js +41 -0
- package/ci/Jenkinsfile +82 -0
- package/ci/argo-workflows.yaml +121 -0
- package/ci/azure-pipelines.yml +56 -0
- package/ci/bitbucket-pipelines.yml +43 -0
- package/ci/buildkite.yml +50 -0
- package/ci/circleci.yml +60 -0
- package/ci/drone.yml +67 -0
- package/ci/github-actions.yml +51 -0
- package/ci/gitlab-ci.yml +39 -0
- package/ci/gocd.yaml +79 -0
- package/ci/teamcity.kts +79 -0
- package/ci/tekton.yaml +106 -0
- package/ci/verify-package.js +748 -0
- package/ci/verify-publish-metadata.js +147 -0
- package/ci/verify-templates.js +195 -0
- package/ci/woodpecker.yml +53 -0
- package/compliance/cli.js +204 -0
- package/compliance/evidence-forwarder.js +209 -0
- package/compliance/pci-dss-v4/controls.json +75 -0
- package/compliance/pci-dss-v4/index.js +2613 -0
- package/config/named-sets.js +185 -0
- package/esbuild.d.ts +16 -0
- package/esbuild.js +190 -0
- package/examples/README.md +78 -0
- package/examples/browserify/build.js +20 -0
- package/examples/bun/package.json +13 -0
- package/examples/bun/scripts/protect-release.js +28 -0
- package/examples/cli-basic/jso.config.cjs +23 -0
- package/examples/cli-basic/jso.config.json +15 -0
- package/examples/cli-basic/package.json +14 -0
- package/examples/cli-basic/scripts/build.js +10 -0
- package/examples/curl/README.md +55 -0
- package/examples/curl/protect.sh +106 -0
- package/examples/esbuild/build.js +19 -0
- package/examples/grunt/Gruntfile.js +29 -0
- package/examples/gulp/gulpfile.js +19 -0
- package/examples/helm/Chart.yaml +27 -0
- package/examples/helm/README.md +69 -0
- package/examples/helm/templates/_helpers.tpl +23 -0
- package/examples/helm/templates/_podtemplate.tpl +64 -0
- package/examples/helm/templates/job.yaml +39 -0
- package/examples/helm/templates/secret.yaml +17 -0
- package/examples/helm/values.yaml +54 -0
- package/examples/kubernetes/job.yaml +123 -0
- package/examples/metro.config.js +11 -0
- package/examples/nextjs/next.config.js +11 -0
- package/examples/node-api/protect-release.js +28 -0
- package/examples/node-api/release-summary.js +59 -0
- package/examples/parcel/package.json +13 -0
- package/examples/parcel/scripts/protect-release.js +28 -0
- package/examples/payment-page-script-inventory.json +62 -0
- package/examples/payment-page-security-headers.json +46 -0
- package/examples/pre-commit/.pre-commit-config.yaml +33 -0
- package/examples/pre-commit/README.md +45 -0
- package/examples/react-native/README.md +208 -0
- package/examples/react-native/metro.config.js +11 -0
- package/examples/rollup/rollup.config.js +20 -0
- package/examples/rspack/rspack.config.js +28 -0
- package/examples/turbopack/package.json +13 -0
- package/examples/turbopack/scripts/protect-release.js +28 -0
- package/examples/vite/vite.config.js +18 -0
- package/examples/webpack/webpack.config.js +21 -0
- package/examples/webpack-loader/webpack.config.js +22 -0
- package/governance/index.d.ts +18 -0
- package/governance/index.js +309 -0
- package/grunt.d.ts +4 -0
- package/grunt.js +111 -0
- package/gulp.d.ts +10 -0
- package/gulp.js +106 -0
- package/index.d.ts +879 -0
- package/index.js +607 -0
- package/jso.config.example.json +29 -0
- package/jso.config.schema.json +548 -0
- package/metro.d.ts +43 -0
- package/metro.js +117 -0
- package/next.d.ts +24 -0
- package/next.js +64 -0
- package/package.json +241 -0
- package/parcel.d.ts +10 -0
- package/parcel.js +40 -0
- package/react-native.d.ts +2 -0
- package/react-native.js +3 -0
- package/release-signer.js +245 -0
- package/rollup.d.ts +13 -0
- package/rollup.js +71 -0
- package/rspack-loader.d.ts +13 -0
- package/rspack-loader.js +11 -0
- package/rspack.d.ts +11 -0
- package/rspack.js +9 -0
- package/runtime/ai-script-governance.js +379 -0
- package/runtime/countermeasures.js +0 -0
- package/runtime/data-exfiltration-guard.d.ts +7 -0
- package/runtime/data-exfiltration-guard.js +161 -0
- package/runtime/environment-integrity.js +389 -0
- package/runtime/managed-integrity.d.ts +4 -0
- package/runtime/managed-integrity.js +108 -0
- package/runtime/third-party-inventory.js +437 -0
- package/turbopack.d.ts +10 -0
- package/turbopack.js +41 -0
- package/vite.d.ts +16 -0
- package/vite.js +78 -0
- package/watermark.js +126 -0
- package/webpack-loader.d.ts +15 -0
- package/webpack-loader.js +97 -0
- package/webpack.d.ts +13 -0
- package/webpack.js +143 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// AI script data governance (browser runtime module).
|
|
4
|
+
//
|
|
5
|
+
// Watches outbound fetch / XHR / WebSocket traffic for requests that
|
|
6
|
+
// hit a known LLM provider endpoint, classifies them, records the
|
|
7
|
+
// destination + payload size + sha256, and routes the event through
|
|
8
|
+
// the same beacon channel as third-party-inventory and the runtime
|
|
9
|
+
// defense suite. Two modes:
|
|
10
|
+
//
|
|
11
|
+
// "log" -- record only, request proceeds (default, safe to
|
|
12
|
+
// deploy on a live payment page without breaking
|
|
13
|
+
// legitimate copilot widgets).
|
|
14
|
+
// "block" -- record + reject. fetch() returns a synthetic 451
|
|
15
|
+
// Response; XHR transitions to readyState=4 with
|
|
16
|
+
// status=0; WebSocket constructor throws.
|
|
17
|
+
//
|
|
18
|
+
// Compose with jso-beacon-slack's SIEM adapters (Splunk HEC,
|
|
19
|
+
// Elasticsearch, signed webhook) to land AI-bound traffic in the
|
|
20
|
+
// same on-call view as Magecart-style violations.
|
|
21
|
+
//
|
|
22
|
+
// Threat model
|
|
23
|
+
// ------------
|
|
24
|
+
// Three concrete attacks this catches:
|
|
25
|
+
// 1. A Magecart-style script that exfiltrates form data to an
|
|
26
|
+
// attacker-controlled LLM (eg. "summarize this credit-card
|
|
27
|
+
// number"). The destination matches a known LLM endpoint and
|
|
28
|
+
// the payload size is non-trivial.
|
|
29
|
+
// 2. A legitimate-but-untrusted third-party widget that quietly
|
|
30
|
+
// streams page contents to its own AI backend. The customer
|
|
31
|
+
// may not have approved this data flow.
|
|
32
|
+
// 3. A compromised CI/CD dep injecting a prompt-stealer that POSTs
|
|
33
|
+
// conversation history to a side-channel.
|
|
34
|
+
//
|
|
35
|
+
// What this module does NOT do
|
|
36
|
+
// ----------------------------
|
|
37
|
+
// It cannot stop a server-side proxy (eg. an attacker who pipes
|
|
38
|
+
// page data through their own backend before forwarding to OpenAI);
|
|
39
|
+
// it only sees direct browser-to-provider traffic. It also cannot
|
|
40
|
+
// classify a request whose URL is the attacker's own domain
|
|
41
|
+
// fronting an LLM API; the allowlist is destination-host based, not
|
|
42
|
+
// behavior based. Pair with the third-party-inventory module
|
|
43
|
+
// (which alerts on unknown origins outright) for full coverage.
|
|
44
|
+
//
|
|
45
|
+
// Public API
|
|
46
|
+
// ----------
|
|
47
|
+
// const aig = require("jso-protector/runtime/ai-script-governance");
|
|
48
|
+
// const engine = aig.createGovernanceEngine({
|
|
49
|
+
// mode: "log", // "log" | "block"
|
|
50
|
+
// additionalKnownLLMHosts: ["my-llm.example.com"],
|
|
51
|
+
// beaconUrl: "https://beacon.example.com/v1/jso/ai-gov",
|
|
52
|
+
// flushIntervalMs: 15000,
|
|
53
|
+
// buildId: window.__jsoBuildId,
|
|
54
|
+
// });
|
|
55
|
+
// engine.observe({ method: "POST", url: "https://api.openai.com/v1/chat/completions", bodyBytes: 1024, bodySha256: "...", caller: "checkout.js:42" });
|
|
56
|
+
// const events = engine.events();
|
|
57
|
+
// const violations = engine.violations();
|
|
58
|
+
// // DOM-attach (browser only):
|
|
59
|
+
// aig.attach(window, { ...config });
|
|
60
|
+
|
|
61
|
+
const SCHEMA_VERSION = 1;
|
|
62
|
+
const DEFAULT_FLUSH_INTERVAL_MS = 15000;
|
|
63
|
+
const MAX_EVENT_LOG = 500;
|
|
64
|
+
|
|
65
|
+
// Known LLM provider hosts as of 2026-06. Add via
|
|
66
|
+
// config.additionalKnownLLMHosts to extend without forking. Matched
|
|
67
|
+
// via endsWith() against the request URL's host, so subdomain
|
|
68
|
+
// patterns like "openai.azure.com" cover "<tenant>.openai.azure.com".
|
|
69
|
+
const DEFAULT_LLM_HOSTS = [
|
|
70
|
+
// OpenAI
|
|
71
|
+
"api.openai.com",
|
|
72
|
+
".openai.azure.com",
|
|
73
|
+
// Anthropic
|
|
74
|
+
"api.anthropic.com",
|
|
75
|
+
// Google
|
|
76
|
+
"generativelanguage.googleapis.com",
|
|
77
|
+
"aiplatform.googleapis.com",
|
|
78
|
+
// Groq
|
|
79
|
+
"api.groq.com",
|
|
80
|
+
// Together
|
|
81
|
+
"api.together.xyz",
|
|
82
|
+
"api.together.ai",
|
|
83
|
+
// Mistral
|
|
84
|
+
"api.mistral.ai",
|
|
85
|
+
"codestral.mistral.ai",
|
|
86
|
+
// AWS Bedrock (region-prefixed). Trailing-dot rule = host startsWith.
|
|
87
|
+
"bedrock-runtime.",
|
|
88
|
+
"bedrock-runtime-fips.",
|
|
89
|
+
// Cohere
|
|
90
|
+
"api.cohere.com",
|
|
91
|
+
"api.cohere.ai",
|
|
92
|
+
// Perplexity
|
|
93
|
+
"api.perplexity.ai",
|
|
94
|
+
// xAI
|
|
95
|
+
"api.x.ai",
|
|
96
|
+
// DeepSeek
|
|
97
|
+
"api.deepseek.com",
|
|
98
|
+
// Replicate
|
|
99
|
+
"api.replicate.com",
|
|
100
|
+
// Hugging Face Inference
|
|
101
|
+
"api-inference.huggingface.co",
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
function createGovernanceEngine(config) {
|
|
105
|
+
config = config || {};
|
|
106
|
+
const mode = config.mode === "block" ? "block" : "log";
|
|
107
|
+
const extras = Array.isArray(config.additionalKnownLLMHosts) ? config.additionalKnownLLMHosts.slice() : [];
|
|
108
|
+
const knownHosts = DEFAULT_LLM_HOSTS.concat(extras);
|
|
109
|
+
|
|
110
|
+
const events = [];
|
|
111
|
+
const violations = []; // populated only in block mode, or always for AI hits
|
|
112
|
+
let seq = 0;
|
|
113
|
+
|
|
114
|
+
function classify(url) {
|
|
115
|
+
if (!url || typeof url !== "string") return { isLLM: false, host: null, matchedRule: null };
|
|
116
|
+
let host = null;
|
|
117
|
+
try {
|
|
118
|
+
const u = new URL(url, "https://example.com/");
|
|
119
|
+
host = (u.host || "").toLowerCase();
|
|
120
|
+
} catch (e) { return { isLLM: false, host: null, matchedRule: null }; }
|
|
121
|
+
const lowerUrl = url.toLowerCase();
|
|
122
|
+
for (const rule of knownHosts) {
|
|
123
|
+
const r = rule.toLowerCase();
|
|
124
|
+
// Four matching shapes:
|
|
125
|
+
// - exact host match "api.openai.com" == host
|
|
126
|
+
// - subdomain suffix (leading dot) ".openai.azure.com" endsWith host
|
|
127
|
+
// - host prefix (trailing dot) "bedrock-runtime." host startsWith
|
|
128
|
+
// - URL-substring (any slash) "/v1/foo" match in lowerUrl
|
|
129
|
+
if (r.indexOf("/") >= 0) {
|
|
130
|
+
if (lowerUrl.indexOf(r) >= 0) return { isLLM: true, host: host, matchedRule: rule };
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (r.charAt(0) === ".") {
|
|
134
|
+
if (host.endsWith(r) || host === r.substring(1)) return { isLLM: true, host: host, matchedRule: rule };
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (r.charAt(r.length - 1) === ".") {
|
|
138
|
+
if (host.indexOf(r) === 0) return { isLLM: true, host: host, matchedRule: rule };
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (host === r) return { isLLM: true, host: host, matchedRule: rule };
|
|
142
|
+
}
|
|
143
|
+
return { isLLM: false, host: host, matchedRule: null };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function observe(row) {
|
|
147
|
+
if (!row || typeof row !== "object") return { acted: false, classification: null };
|
|
148
|
+
const url = row.url || "";
|
|
149
|
+
const cls = classify(url);
|
|
150
|
+
if (!cls.isLLM) return { acted: false, classification: cls };
|
|
151
|
+
|
|
152
|
+
if (events.length >= MAX_EVENT_LOG) return { acted: false, classification: cls, dropped: true };
|
|
153
|
+
|
|
154
|
+
const event = {
|
|
155
|
+
seq: ++seq,
|
|
156
|
+
transport: row.transport || "unknown", // "fetch" | "xhr" | "websocket"
|
|
157
|
+
method: row.method || null,
|
|
158
|
+
url: url,
|
|
159
|
+
host: cls.host,
|
|
160
|
+
matchedRule: cls.matchedRule,
|
|
161
|
+
bodyBytes: typeof row.bodyBytes === "number" ? row.bodyBytes : null,
|
|
162
|
+
bodySha256: row.bodySha256 || null,
|
|
163
|
+
caller: row.caller || null,
|
|
164
|
+
observedAt: row.observedAt || null,
|
|
165
|
+
mode: mode,
|
|
166
|
+
blocked: false,
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
if (mode === "block") {
|
|
170
|
+
event.blocked = true;
|
|
171
|
+
events.push(event);
|
|
172
|
+
violations.push(event);
|
|
173
|
+
return { acted: true, classification: cls, blocked: true };
|
|
174
|
+
}
|
|
175
|
+
// log mode: still treat every AI hit as a "violation" for the
|
|
176
|
+
// beacon flush -- the customer asked to see them.
|
|
177
|
+
events.push(event);
|
|
178
|
+
violations.push(event);
|
|
179
|
+
return { acted: true, classification: cls, blocked: false };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function snapshot() {
|
|
183
|
+
return {
|
|
184
|
+
v: SCHEMA_VERSION,
|
|
185
|
+
kind: "ai-data-access",
|
|
186
|
+
mode: mode,
|
|
187
|
+
buildId: config.buildId || null,
|
|
188
|
+
pageHref: config.pageHref || null,
|
|
189
|
+
events: events.slice(),
|
|
190
|
+
violations: violations.slice(),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function eventsOnly() { return events.slice(); }
|
|
195
|
+
function violationsOnly() { return violations.slice(); }
|
|
196
|
+
function size() { return events.length; }
|
|
197
|
+
function reset() {
|
|
198
|
+
events.length = 0;
|
|
199
|
+
violations.length = 0;
|
|
200
|
+
seq = 0;
|
|
201
|
+
}
|
|
202
|
+
function isKnownLLMHost(url) { return classify(url).isLLM; }
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
SCHEMA_VERSION: SCHEMA_VERSION,
|
|
206
|
+
DEFAULT_LLM_HOSTS: DEFAULT_LLM_HOSTS.slice(),
|
|
207
|
+
mode: mode,
|
|
208
|
+
observe: observe,
|
|
209
|
+
snapshot: snapshot,
|
|
210
|
+
events: eventsOnly,
|
|
211
|
+
violations: violationsOnly,
|
|
212
|
+
size: size,
|
|
213
|
+
reset: reset,
|
|
214
|
+
classify: classify,
|
|
215
|
+
isKnownLLMHost: isKnownLLMHost,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- browser bootstrap -----------------------------------------------------
|
|
220
|
+
|
|
221
|
+
function attach(win, config) {
|
|
222
|
+
if (!win || typeof win !== "object") throw new Error("ai-script-governance.attach: window object required");
|
|
223
|
+
if (win.__jsoAiGovAttached) return win.__jsoAiGovAttached;
|
|
224
|
+
|
|
225
|
+
const engine = createGovernanceEngine(config);
|
|
226
|
+
const mode = engine.mode;
|
|
227
|
+
const observedAt = function () { return new Date().toISOString(); };
|
|
228
|
+
|
|
229
|
+
async function sha256Hex(buf) {
|
|
230
|
+
try {
|
|
231
|
+
if (!win.crypto || !win.crypto.subtle) return null;
|
|
232
|
+
const h = await win.crypto.subtle.digest("SHA-256", buf);
|
|
233
|
+
const bytes = new Uint8Array(h);
|
|
234
|
+
let hex = "";
|
|
235
|
+
for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
|
|
236
|
+
return hex;
|
|
237
|
+
} catch (e) { return null; }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function callerFrame() {
|
|
241
|
+
try {
|
|
242
|
+
const e = new Error();
|
|
243
|
+
if (!e.stack) return null;
|
|
244
|
+
// Pop the top three frames (this fn, the trap, the caller's wrapping)
|
|
245
|
+
const lines = e.stack.split("\n");
|
|
246
|
+
return (lines[3] || lines[2] || lines[1] || "").trim() || null;
|
|
247
|
+
} catch (x) { return null; }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 1. fetch() hook
|
|
251
|
+
if (typeof win.fetch === "function") {
|
|
252
|
+
const origFetch = win.fetch.bind(win);
|
|
253
|
+
win.fetch = function (input, init) {
|
|
254
|
+
const url = (typeof input === "string" ? input : (input && input.url)) || "";
|
|
255
|
+
const method = (init && init.method) || (input && input.method) || "GET";
|
|
256
|
+
const bodyBytes = init && init.body && typeof init.body.length === "number" ? init.body.length : null;
|
|
257
|
+
const verdict = engine.observe({
|
|
258
|
+
transport: "fetch", method: method, url: url,
|
|
259
|
+
bodyBytes: bodyBytes, bodySha256: null,
|
|
260
|
+
caller: callerFrame(), observedAt: observedAt(),
|
|
261
|
+
});
|
|
262
|
+
if (verdict.blocked) {
|
|
263
|
+
return Promise.resolve(new win.Response(
|
|
264
|
+
JSON.stringify({ ok: false, error: "ai_data_access_blocked", host: verdict.classification.host }),
|
|
265
|
+
{ status: 451, statusText: "Unavailable For Legal Reasons", headers: { "Content-Type": "application/json" } }
|
|
266
|
+
));
|
|
267
|
+
}
|
|
268
|
+
return origFetch(input, init);
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// 2. XMLHttpRequest hook
|
|
273
|
+
if (typeof win.XMLHttpRequest === "function") {
|
|
274
|
+
const Orig = win.XMLHttpRequest;
|
|
275
|
+
function PatchedXHR() {
|
|
276
|
+
const x = new Orig();
|
|
277
|
+
let _url = null, _method = null;
|
|
278
|
+
const origOpen = x.open;
|
|
279
|
+
x.open = function (m, u) {
|
|
280
|
+
_method = m; _url = u;
|
|
281
|
+
return origOpen.apply(x, arguments);
|
|
282
|
+
};
|
|
283
|
+
const origSend = x.send;
|
|
284
|
+
x.send = function (body) {
|
|
285
|
+
const bodyBytes = body && typeof body.length === "number" ? body.length : null;
|
|
286
|
+
const verdict = engine.observe({
|
|
287
|
+
transport: "xhr", method: _method, url: _url,
|
|
288
|
+
bodyBytes: bodyBytes, bodySha256: null,
|
|
289
|
+
caller: callerFrame(), observedAt: observedAt(),
|
|
290
|
+
});
|
|
291
|
+
if (verdict.blocked) {
|
|
292
|
+
// Synthesize an abort that looks like a network failure.
|
|
293
|
+
try { x.abort(); } catch (e) {}
|
|
294
|
+
setTimeout(function () {
|
|
295
|
+
try {
|
|
296
|
+
if (typeof x.onreadystatechange === "function") {
|
|
297
|
+
Object.defineProperty(x, "readyState", { value: 4, configurable: true });
|
|
298
|
+
Object.defineProperty(x, "status", { value: 0, configurable: true });
|
|
299
|
+
x.onreadystatechange();
|
|
300
|
+
}
|
|
301
|
+
} catch (e) {}
|
|
302
|
+
}, 0);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
return origSend.apply(x, arguments);
|
|
306
|
+
};
|
|
307
|
+
return x;
|
|
308
|
+
}
|
|
309
|
+
try { PatchedXHR.prototype = Orig.prototype; } catch (e) {}
|
|
310
|
+
win.XMLHttpRequest = PatchedXHR;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 3. WebSocket hook
|
|
314
|
+
if (typeof win.WebSocket === "function") {
|
|
315
|
+
const OrigWS = win.WebSocket;
|
|
316
|
+
function PatchedWS(url, protocols) {
|
|
317
|
+
const verdict = engine.observe({
|
|
318
|
+
transport: "websocket", method: "WS", url: url,
|
|
319
|
+
bodyBytes: null, bodySha256: null,
|
|
320
|
+
caller: callerFrame(), observedAt: observedAt(),
|
|
321
|
+
});
|
|
322
|
+
if (verdict.blocked) {
|
|
323
|
+
throw new Error("ai_data_access_blocked: WebSocket to " + verdict.classification.host + " refused by jso-ai-script-governance.");
|
|
324
|
+
}
|
|
325
|
+
return new OrigWS(url, protocols);
|
|
326
|
+
}
|
|
327
|
+
try { PatchedWS.prototype = OrigWS.prototype; } catch (e) {}
|
|
328
|
+
win.WebSocket = PatchedWS;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 4. Beacon flush -- same shape as third-party-inventory so the
|
|
332
|
+
// SIEM adapters can route both event kinds without an adapter
|
|
333
|
+
// change. Flushes deltas every flushIntervalMs.
|
|
334
|
+
function setupBeaconFlush() {
|
|
335
|
+
if (!config.beaconUrl) return;
|
|
336
|
+
const interval = (typeof config.flushIntervalMs === "number" && config.flushIntervalMs > 0)
|
|
337
|
+
? config.flushIntervalMs
|
|
338
|
+
: DEFAULT_FLUSH_INTERVAL_MS;
|
|
339
|
+
let lastSent = 0;
|
|
340
|
+
function flush() {
|
|
341
|
+
const v = engine.violations();
|
|
342
|
+
if (v.length === lastSent) return;
|
|
343
|
+
lastSent = v.length;
|
|
344
|
+
const body = JSON.stringify(engine.snapshot());
|
|
345
|
+
try {
|
|
346
|
+
if (typeof win.fetch === "function") {
|
|
347
|
+
// NOTE: we call the ORIGINAL fetch via __jsoOriginalFetch
|
|
348
|
+
// would loop forever as we just patched fetch above and
|
|
349
|
+
// the beacon URL isn't an LLM host -- the observe()
|
|
350
|
+
// call returns acted=false, so this is harmless. Kept
|
|
351
|
+
// explicit comment so future edits don't add an LLM
|
|
352
|
+
// host that overlaps the beacon URL.
|
|
353
|
+
win.fetch(config.beaconUrl, {
|
|
354
|
+
method: "POST",
|
|
355
|
+
headers: { "Content-Type": "application/json" },
|
|
356
|
+
body: body,
|
|
357
|
+
keepalive: true,
|
|
358
|
+
credentials: "omit",
|
|
359
|
+
}).catch(function () {});
|
|
360
|
+
} else if (typeof win.navigator !== "undefined" && win.navigator.sendBeacon) {
|
|
361
|
+
win.navigator.sendBeacon(config.beaconUrl, body);
|
|
362
|
+
}
|
|
363
|
+
} catch (e) {}
|
|
364
|
+
}
|
|
365
|
+
win.setInterval(flush, interval);
|
|
366
|
+
if (typeof win.addEventListener === "function") win.addEventListener("pagehide", flush, false);
|
|
367
|
+
}
|
|
368
|
+
setupBeaconFlush();
|
|
369
|
+
|
|
370
|
+
win.__jsoAiGovAttached = engine;
|
|
371
|
+
return engine;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
module.exports = {
|
|
375
|
+
SCHEMA_VERSION: SCHEMA_VERSION,
|
|
376
|
+
DEFAULT_LLM_HOSTS: DEFAULT_LLM_HOSTS.slice(),
|
|
377
|
+
createGovernanceEngine: createGovernanceEngine,
|
|
378
|
+
attach: attach,
|
|
379
|
+
};
|
|
Binary file
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface DataExfiltrationPolicyInput { id?: string; version?: string; mode?: "monitor" | "block"; pageOrigin?: string; allowedOrigins?: string[]; protectedSelectors?: string[]; protectedFieldNames?: string[]; allowSameOrigin?: boolean; }
|
|
2
|
+
export interface DataExfiltrationEvent { seq: number; reason: string; transport: string; method: string | null; destinationOrigin: string | null; protectedFieldNames: readonly string[]; protectedFieldCount: number; protectedValueCount: number; protectedForm: boolean; blocked: boolean; observedAt: string; }
|
|
3
|
+
export declare const SCHEMA_VERSION: 1;
|
|
4
|
+
export declare const DEFAULT_SELECTORS: readonly string[];
|
|
5
|
+
export declare function createPolicy(input?: DataExfiltrationPolicyInput): object;
|
|
6
|
+
export declare function createGuard(input?: DataExfiltrationPolicyInput | object): { policy: object; inspect(row: object): object; events(): DataExfiltrationEvent[]; reset(): void; snapshot(): object; detach?: () => void; };
|
|
7
|
+
export declare function attach(win: Window, input?: DataExfiltrationPolicyInput): ReturnType<typeof createGuard>;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Browser-side protected-field egress control. Values are inspected in memory
|
|
4
|
+
// only; snapshots contain field names/counts, never field values or bodies.
|
|
5
|
+
|
|
6
|
+
const SCHEMA_VERSION = 1;
|
|
7
|
+
const MAX_EVENTS = 500;
|
|
8
|
+
const DEFAULT_SELECTORS = Object.freeze([
|
|
9
|
+
"input[type=password]", "input[autocomplete=current-password]",
|
|
10
|
+
"input[autocomplete=new-password]", "input[autocomplete=cc-number]",
|
|
11
|
+
"input[autocomplete=cc-csc]", "input[autocomplete=cc-exp]"
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
function normalizeOrigin(value, base) {
|
|
15
|
+
try {
|
|
16
|
+
const url = new URL(String(value), base || undefined);
|
|
17
|
+
if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) return null;
|
|
18
|
+
return url.origin.replace(/^ws/, "http");
|
|
19
|
+
} catch (_) { return null; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function createPolicy(input) {
|
|
23
|
+
input = input || {};
|
|
24
|
+
const mode = String(input.mode || "monitor").toLowerCase();
|
|
25
|
+
if (mode !== "monitor" && mode !== "block") throw new Error("data-exfiltration-guard: mode must be monitor or block");
|
|
26
|
+
const pageOrigin = input.pageOrigin ? normalizeOrigin(input.pageOrigin) : null;
|
|
27
|
+
const allowed = (input.allowedOrigins || []).map((v) => normalizeOrigin(v, pageOrigin || undefined)).filter(Boolean);
|
|
28
|
+
if (input.allowSameOrigin !== false && pageOrigin) allowed.push(pageOrigin);
|
|
29
|
+
return Object.freeze({
|
|
30
|
+
id: String(input.id || "default"), version: String(input.version || "1"), mode,
|
|
31
|
+
pageOrigin, allowedOrigins: Object.freeze(Array.from(new Set(allowed)).sort()),
|
|
32
|
+
protectedSelectors: Object.freeze((input.protectedSelectors || DEFAULT_SELECTORS).map(String)),
|
|
33
|
+
protectedFieldNames: Object.freeze(Array.from(new Set((input.protectedFieldNames || []).map(String).filter(Boolean)))),
|
|
34
|
+
allowSameOrigin: input.allowSameOrigin !== false
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function createGuard(input) {
|
|
39
|
+
const policy = input && input.allowedOrigins && Object.isFrozen(input) ? input : createPolicy(input);
|
|
40
|
+
const events = [];
|
|
41
|
+
let sequence = 0;
|
|
42
|
+
function inspect(row) {
|
|
43
|
+
row = row || {};
|
|
44
|
+
const destinationOrigin = normalizeOrigin(row.url, policy.pageOrigin || undefined);
|
|
45
|
+
const names = Array.from(new Set((row.protectedFieldNames || []).map(String).filter(Boolean))).sort();
|
|
46
|
+
const valueCount = Math.max(0, Number(row.protectedValueCount) || 0);
|
|
47
|
+
const containsProtectedData = names.length > 0 || valueCount > 0 || row.protectedForm === true;
|
|
48
|
+
const allowed = !!destinationOrigin && policy.allowedOrigins.includes(destinationOrigin);
|
|
49
|
+
if (!containsProtectedData || allowed) return { acted: false, blocked: false, allowed, destinationOrigin };
|
|
50
|
+
if (events.length >= MAX_EVENTS) return { acted: false, blocked: false, dropped: true, allowed, destinationOrigin };
|
|
51
|
+
const blocked = policy.mode === "block";
|
|
52
|
+
const event = Object.freeze({
|
|
53
|
+
seq: ++sequence, reason: destinationOrigin ? "protected-data-to-unapproved-origin" : "protected-data-to-invalid-destination",
|
|
54
|
+
transport: String(row.transport || "unknown"), method: row.method ? String(row.method) : null,
|
|
55
|
+
destinationOrigin, protectedFieldNames: Object.freeze(names), protectedFieldCount: names.length,
|
|
56
|
+
protectedValueCount: valueCount, protectedForm: row.protectedForm === true, blocked,
|
|
57
|
+
observedAt: row.observedAt || new Date().toISOString()
|
|
58
|
+
});
|
|
59
|
+
events.push(event);
|
|
60
|
+
return { acted: true, blocked, allowed: false, destinationOrigin, event };
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
policy, inspect, events: () => events.slice(),
|
|
64
|
+
reset: () => { events.length = 0; sequence = 0; },
|
|
65
|
+
snapshot: () => ({ v: SCHEMA_VERSION, kind: "protected-data-egress", policyId: policy.id, policyVersion: policy.version, mode: policy.mode, events: events.slice() })
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function attach(win, input) {
|
|
70
|
+
if (!win || !win.document) throw new Error("data-exfiltration-guard.attach: browser window required");
|
|
71
|
+
if (win.__jsoDataExfiltrationGuard) return win.__jsoDataExfiltrationGuard;
|
|
72
|
+
input = Object.assign({}, input || {});
|
|
73
|
+
if (!input.pageOrigin && win.location) input.pageOrigin = win.location.origin;
|
|
74
|
+
const guard = createGuard(input);
|
|
75
|
+
function fields() {
|
|
76
|
+
const result = [];
|
|
77
|
+
for (const selector of guard.policy.protectedSelectors) {
|
|
78
|
+
let nodes = [];
|
|
79
|
+
try { nodes = win.document.querySelectorAll(selector); } catch (_) {}
|
|
80
|
+
for (let i = 0; i < nodes.length; i++) if (!result.includes(nodes[i])) result.push(nodes[i]);
|
|
81
|
+
}
|
|
82
|
+
if (guard.policy.protectedFieldNames.length) {
|
|
83
|
+
let nodes = [];
|
|
84
|
+
try { nodes = win.document.querySelectorAll("input[name],textarea[name],select[name]"); } catch (_) {}
|
|
85
|
+
for (let i = 0; i < nodes.length; i++) if (guard.policy.protectedFieldNames.includes(nodes[i].name) && !result.includes(nodes[i])) result.push(nodes[i]);
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
function bodyText(body) {
|
|
90
|
+
if (typeof body === "string") return body;
|
|
91
|
+
if (win.URLSearchParams && body instanceof win.URLSearchParams) return body.toString();
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
function inspectBody(transport, method, url, body, form) {
|
|
95
|
+
const names = []; let valueCount = 0; const text = bodyText(body);
|
|
96
|
+
for (const field of fields()) {
|
|
97
|
+
const name = String(field.name || field.id || "protected-field");
|
|
98
|
+
const value = field.value == null ? "" : String(field.value);
|
|
99
|
+
let matched = !!form && field.form === form;
|
|
100
|
+
if (win.FormData && body instanceof win.FormData && field.name) { try { matched = body.has(field.name); } catch (_) {} }
|
|
101
|
+
if (text && ((field.name && (text.includes(encodeURIComponent(field.name) + "=") || text.includes('"' + field.name + '"'))) || (value.length >= 3 && text.includes(value)))) matched = true;
|
|
102
|
+
if (matched) { names.push(name); if (value.length >= 3 && text && text.includes(value)) valueCount++; }
|
|
103
|
+
}
|
|
104
|
+
return guard.inspect({ transport, method, url, protectedFieldNames: names, protectedValueCount: valueCount, protectedForm: !!form && names.length > 0 });
|
|
105
|
+
}
|
|
106
|
+
const originals = {};
|
|
107
|
+
if (typeof win.fetch === "function") {
|
|
108
|
+
originals.fetch = win.fetch.bind(win);
|
|
109
|
+
win.fetch = function (request, init) {
|
|
110
|
+
const url = typeof request === "string" ? request : request && request.url;
|
|
111
|
+
const verdict = inspectBody("fetch", (init && init.method) || "GET", url, init && init.body, null);
|
|
112
|
+
if (verdict.blocked) return Promise.resolve(new win.Response(JSON.stringify({ ok: false, error: "protected_data_egress_blocked" }), { status: 451, headers: { "Content-Type": "application/json" } }));
|
|
113
|
+
return originals.fetch(request, init);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (typeof win.XMLHttpRequest === "function") {
|
|
117
|
+
originals.XMLHttpRequest = win.XMLHttpRequest;
|
|
118
|
+
const OriginalXHR = win.XMLHttpRequest;
|
|
119
|
+
function GuardedXHR() {
|
|
120
|
+
const xhr = new OriginalXHR(); let url = "", method = "GET";
|
|
121
|
+
const open = xhr.open; const send = xhr.send;
|
|
122
|
+
xhr.open = function (m, u) { method = m; url = u; return open.apply(xhr, arguments); };
|
|
123
|
+
xhr.send = function (body) { const verdict = inspectBody("xhr", method, url, body, null); if (verdict.blocked) { try { xhr.abort(); } catch (_) {} return; } return send.apply(xhr, arguments); };
|
|
124
|
+
return xhr;
|
|
125
|
+
}
|
|
126
|
+
try { GuardedXHR.prototype = OriginalXHR.prototype; } catch (_) {}
|
|
127
|
+
win.XMLHttpRequest = GuardedXHR;
|
|
128
|
+
}
|
|
129
|
+
if (win.navigator && typeof win.navigator.sendBeacon === "function") {
|
|
130
|
+
originals.sendBeacon = win.navigator.sendBeacon.bind(win.navigator);
|
|
131
|
+
win.navigator.sendBeacon = function (url, body) { const verdict = inspectBody("beacon", "POST", url, body, null); return verdict.blocked ? false : originals.sendBeacon(url, body); };
|
|
132
|
+
}
|
|
133
|
+
if (typeof win.WebSocket === "function") {
|
|
134
|
+
originals.WebSocket = win.WebSocket;
|
|
135
|
+
const OriginalWebSocket = win.WebSocket;
|
|
136
|
+
function GuardedWebSocket(url, protocols) { const socket = new OriginalWebSocket(url, protocols); const send = socket.send; socket.send = function (body) { const verdict = inspectBody("websocket", "WS", url, body, null); if (verdict.blocked) throw new Error("protected_data_egress_blocked"); return send.apply(socket, arguments); }; return socket; }
|
|
137
|
+
try { GuardedWebSocket.prototype = OriginalWebSocket.prototype; } catch (_) {}
|
|
138
|
+
win.WebSocket = GuardedWebSocket;
|
|
139
|
+
}
|
|
140
|
+
if (win.HTMLFormElement && win.HTMLFormElement.prototype) {
|
|
141
|
+
for (const methodName of ["submit", "requestSubmit"]) {
|
|
142
|
+
const original = win.HTMLFormElement.prototype[methodName];
|
|
143
|
+
if (typeof original !== "function") continue;
|
|
144
|
+
originals[methodName] = original;
|
|
145
|
+
win.HTMLFormElement.prototype[methodName] = function () { const verdict = inspectBody("form", String(this.method || "GET").toUpperCase(), this.action || (win.location && win.location.href), null, this); if (verdict.blocked) throw new Error("protected_data_egress_blocked"); return original.apply(this, arguments); };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
guard.detach = function () {
|
|
149
|
+
if (originals.fetch) win.fetch = originals.fetch;
|
|
150
|
+
if (originals.XMLHttpRequest) win.XMLHttpRequest = originals.XMLHttpRequest;
|
|
151
|
+
if (originals.sendBeacon) win.navigator.sendBeacon = originals.sendBeacon;
|
|
152
|
+
if (originals.WebSocket) win.WebSocket = originals.WebSocket;
|
|
153
|
+
if (originals.submit) win.HTMLFormElement.prototype.submit = originals.submit;
|
|
154
|
+
if (originals.requestSubmit) win.HTMLFormElement.prototype.requestSubmit = originals.requestSubmit;
|
|
155
|
+
delete win.__jsoDataExfiltrationGuard;
|
|
156
|
+
};
|
|
157
|
+
win.__jsoDataExfiltrationGuard = guard;
|
|
158
|
+
return guard;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
module.exports = { SCHEMA_VERSION, DEFAULT_SELECTORS, createPolicy, createGuard, attach };
|