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
package/RELEASE.md ADDED
@@ -0,0 +1,82 @@
1
+ # Local Package Guide
2
+
3
+ This package is intentionally local-only. Keep `"private": true` and `"license": "UNLICENSED"` in `package.json` unless the product owner explicitly approves a public npm release later.
4
+
5
+ ## Local Metadata Policy
6
+
7
+ | Field | Required local value | Reason |
8
+ | --- | --- | --- |
9
+ | npm name | `jso-protector` | Local workspace/package name only; not reserved or published on npm. |
10
+ | registry access | `"private": true` | Blocks accidental `npm publish`. |
11
+ | license | `UNLICENSED` | Makes the package private/internal by default. |
12
+ | credentials | Environment variables only | Keeps API credentials out of package files and logs. |
13
+ | payment enforcement | Hosted API only | Keeps billing, account status, credits, and plan limits on the server. |
14
+
15
+ ## Payment Model
16
+
17
+ Use npm only as the local developer workflow. Users still need a paid JavaScript Obfuscator account because protection calls go to the hosted HTTP API with dashboard credentials.
18
+
19
+ Do not add billing logic, shared API keys, account secrets, or plan-limit decisions to this package. The server must reject unpaid, expired, disabled, or over-limit accounts.
20
+
21
+ ## Local Verification
22
+
23
+ Use the package from another local project with either a workspace path:
24
+
25
+ ```bash
26
+ npm install --save-dev ../packages/jso-protector
27
+ ```
28
+
29
+ or a `file:` dependency:
30
+
31
+ ```json
32
+ {
33
+ "devDependencies": {
34
+ "jso-protector": "file:../packages/jso-protector"
35
+ }
36
+ }
37
+ ```
38
+
39
+ For internal handoff, create a tarball and install it directly in the consuming app:
40
+
41
+ ```bash
42
+ npm pack --json
43
+ npm install --save-dev path/to/jso-protector-0.2.0.tgz
44
+ ```
45
+
46
+ Run the offline test suite:
47
+
48
+ ```bash
49
+ npm test
50
+ ```
51
+
52
+ Run the package smoke check:
53
+
54
+ ```bash
55
+ npm run smoke
56
+ npm run verify:package
57
+ ```
58
+
59
+ Run the local-only metadata check:
60
+
61
+ ```bash
62
+ npm run verify:publish-metadata
63
+ ```
64
+
65
+ Run everything:
66
+
67
+ ```bash
68
+ npm run verify
69
+ ```
70
+
71
+ With test credentials only, run the live API preflight:
72
+
73
+ ```bash
74
+ npm run smoke:api
75
+ jso-protector --config jso.config.example.json --doctor --check-api --json
76
+ ```
77
+
78
+ ## Publish Guard
79
+
80
+ The `prepublishOnly` script runs `ci/verify-publish-metadata.js` without the local-only allowance and blocks `npm publish`. `npm run verify:publish-ready` should fail while this package remains local-only.
81
+
82
+ If a public npm release is ever approved, treat that as a separate product decision: choose a final package name/scope, approve a public license, add repository and support metadata, remove `private:true`, and rerun `npm run verify:publish-ready`.
package/SECURITY.md ADDED
@@ -0,0 +1,71 @@
1
+ # Security and Processing Notes
2
+
3
+ `jso-protector` is a workflow wrapper around the JavaScript Obfuscator HTTP API.
4
+
5
+ ## Workflow Matrix
6
+
7
+ | Workflow | Sends source to hosted API | Typical use | Notes |
8
+ | --- | --- | --- | --- |
9
+ | `--dry-run` | No | CI file-list and config checks | Prints matched files and config summary only. |
10
+ | `--validate-config` | No | Static config validation | Checks config shape, paths, budgets, and option names without API calls. |
11
+ | `--doctor` | No | Release preflight | Checks credentials presence, path readiness, matched files, and output readiness. |
12
+ | `--release-check` | No | Combined release preflight | Runs validation, dry-run planning, and doctor checks as one report. |
13
+ | `--release-check --strict` | No | Strict release gate | Treats validation warnings as release-check failures. |
14
+ | `--competitor-gap-report` | No | Migration parity review | Reports covered, partial, and gap areas for common competitor migration surfaces. |
15
+ | `--doctor --check-api` | Yes, generated sample only | Endpoint and credential smoke test | Sends a tiny generated `jso-doctor.js` sample, not project source. |
16
+ | `--local-only` | No | Source-handling policy check | Prints the local/offline path and exits without reading project source. |
17
+ | CLI protection | Yes | Protect built JavaScript files | Sends matched JavaScript file contents to `endpoint`. |
18
+ | Node API | Yes | Custom build scripts | Sends provided source strings or matched files to `endpoint`. |
19
+ | Bundle plugins | Yes | Vite, Rollup, Webpack, esbuild, Browserify, Gulp, Grunt | Sends selected emitted JavaScript chunks or stream files to `endpoint`. |
20
+ | Desktop workflow | Yes | GUI batch and mixed-file projects | Sends selected JavaScript to the hosted service; surrounding mixed-file content stays local. |
21
+
22
+ ## Source Processing
23
+
24
+ - CLI protection sends matched JavaScript file contents to the configured `endpoint`.
25
+ - `--parse-html` sends only marked inline `<script data-javascript-obfuscator>` blocks from HTML files to the API. Unmarked inline scripts, external scripts, and module scripts are preserved locally.
26
+ - Conditional markers fail by default. Passing `--honor-conditional-comments` sends enabled regions to the API and preserves disabled `javascript-obfuscator:disable` regions locally.
27
+ - Bundle plugins send emitted JavaScript chunks to the configured `endpoint`.
28
+ - `--release-check` and `--doctor` do not send source code unless `--check-api` is also provided.
29
+ - `--competitor-gap-report` reads config metadata and migration fields only; it does not read or send project source.
30
+ - `--check-api` sends a tiny generated sample named `jso-doctor.js`.
31
+ - `--dry-run` does not call the API.
32
+ - `--print-config --json` redacts API credentials as `[set]` or `[missing]`.
33
+ - Release manifests contain file names, source/output paths, byte counts, SHA-256 hashes, and processing metadata for virtual API items. Treat manifests as release metadata.
34
+ - `--verify-manifest` checks protected output against those recorded hashes and can verify a relocated artifact tree with `--verify-root`.
35
+
36
+ Use `jso-protector --local-only --json` in package scripts or onboarding docs when users need the source-handling decision in the terminal. It exits without reading project source and identifies the available local preflight checks. Current protection workflows, including desktop, send selected JavaScript to the hosted service and do not meet a policy that forbids source transfer.
37
+
38
+ ## Credentials
39
+
40
+ - Prefer `JSO_API_KEY` and `JSO_API_PASSWORD` environment variables or CI secrets.
41
+ - Do not commit dashboard credentials to `jso.config.json`.
42
+ - `--validate-config` warns when `apiKey`, `apiPassword`, `--api-key`, or `--api-password` contain inline values instead of environment references.
43
+ - Rotate credentials if they are pasted into logs, tickets, chat, or build output.
44
+ - Use the short environment names for new automation. Long aliases are accepted for compatibility: `JAVASCRIPT_OBFUSCATOR_API_KEY`, `JAVASCRIPT_OBFUSCATOR_API_PASSWORD`, and `JAVASCRIPT_OBFUSCATOR_ENDPOINT`.
45
+
46
+ ## Payment and Entitlements
47
+
48
+ The npm package is a local client only. It must not contain billing rules, plan limits, shared service credentials, or payment bypass logic. Paid access is enforced by the hosted JavaScript Obfuscator API after the CLI sends the user's dashboard API key and password.
49
+
50
+ Server-side checks should validate account status, plan/credit limits, endpoint access, and request size before protection work runs. Unpaid, expired, disabled, or over-limit accounts should be rejected by the API regardless of how the local npm client was installed.
51
+
52
+ Client-side API error messages should help users find the dashboard credential or account issue without echoing secrets. The CLI redacts API key and password values from hosted API error messages before printing them.
53
+
54
+ ## Source Maps
55
+
56
+ The CLI and bundle plugins exclude or remove JavaScript source maps by default because source maps can reveal original source. Keep this behavior for protected release artifacts unless another secure build step handles maps. Use `--source-map-evidence dist-protected/jso-manifest.json --source-map-evidence-output reports/source-map-evidence.md` when a reviewer needs a source-free handoff proving the protected artifact has no `.map` files or `sourceMappingURL` comments.
57
+
58
+ ## Vendor Code
59
+
60
+ Use `include` and `exclude` to protect first-party release chunks and skip vendor bundles, polyfills, framework runtime files, and generated code that should not be transformed.
61
+
62
+ ## CI Practices
63
+
64
+ - Run `jso-protector --config jso.config.json --release-check --json` before sending source code.
65
+ - Run `jso-protector --config jso.config.json --competitor-gap-report --json` for migrated competitor configs so runtime-defense mapping, source-map policy, and other manual-review items stay visible.
66
+ - Run `jso-protector --verify-manifest dist-protected/jso-manifest.json` after packaging or artifact download when release integrity needs a local proof step.
67
+ - Run `jso-protector --source-map-evidence dist-protected/jso-manifest.json --source-map-evidence-output reports/source-map-evidence.md` before publishing protected artifacts that must prove source maps are absent.
68
+ - Store API credentials as encrypted CI secrets.
69
+ - Keep protected output in a separate directory such as `dist-protected`.
70
+ - Publish protected artifacts, not the unprotected build folder.
71
+ - Store release manifests with build artifacts only when your release process allows path and hash metadata.
package/ai-cli.js ADDED
@@ -0,0 +1,392 @@
1
+ "use strict";
2
+
3
+ // `jso ai <subcommand>` CLI.
4
+ //
5
+ // The main jso-protector.js CLI intercepts argv[0] === "ai" at the top of
6
+ // main() and delegates here. Keeps the AI surface out of the giant
7
+ // parseArgs switch and lets each subcommand have its own flag set.
8
+ //
9
+ // Subcommands:
10
+ // jso ai usage # current-month quota counters
11
+ // jso ai preset-suggest <description...> # describe app → jso.config
12
+ // jso ai compat-check <file> # scan a JS file
13
+ // jso ai explain-error <error...> # diagnose a runtime error
14
+ //
15
+ // All output is JSON by default (machine-friendly, easy to pipe to jq).
16
+ // `--pretty` re-renders the same data in a human-readable form for the
17
+ // terminal.
18
+ //
19
+ // Exit codes:
20
+ // 0 -- ok (request succeeded, no business-logic error)
21
+ // 1 -- business-logic error (ok: false) or HTTP error
22
+ // 2 -- argument / usage error
23
+
24
+ const fs = require("node:fs");
25
+ const path = require("node:path");
26
+ const ai = require("./ai.js");
27
+
28
+ function printHelp(stream = process.stdout) {
29
+ stream.write(
30
+ `jso ai <subcommand> [options]
31
+
32
+ Subcommands:
33
+ usage Current-month AI quota counters.
34
+ preset-suggest <description...> Generate jso.config from a description.
35
+ compat-check <file> [--framework F] Scan a single JS file for obfuscation pitfalls.
36
+ compat-scan [--config jso.config] Pre-obfuscation gate: AI-scan every input
37
+ file in your jso.config. Exits non-zero on
38
+ errors. Drop into CI before jso-protector.
39
+ explain-error <error...> Diagnose a protected-output runtime error.
40
+
41
+ Authentication:
42
+ Either pass --api-key / --api-password, or set the JSO_API_KEY and
43
+ JSO_API_PASSWORD environment variables. Same credentials as the
44
+ obfuscation API.
45
+
46
+ Options (all subcommands):
47
+ --api-key VALUE Base64 APIKey from /dashboard/apikeys.aspx.
48
+ --api-password VALUE Base64 APIPwd from /dashboard/apikeys.aspx.
49
+ --endpoint URL Override the JSO base URL (default: production).
50
+ --pretty Human-readable output instead of JSON.
51
+ --timeout MS Request timeout in milliseconds (default: 30000).
52
+ -h, --help Show this help.
53
+
54
+ Examples:
55
+ jso ai usage --pretty
56
+ jso ai preset-suggest "React SaaS, balanced, lock to example.com" > jso.config.json
57
+ jso ai compat-check src/app.js --framework react --pretty
58
+ jso ai explain-error "Uncaught TypeError: api.charge is not a function"
59
+ `);
60
+ }
61
+
62
+ function parseFlags(argv) {
63
+ const opts = {};
64
+ const positional = [];
65
+ for (let i = 0; i < argv.length; i++) {
66
+ const a = argv[i];
67
+ switch (a) {
68
+ case "--api-key": opts.apiKey = argv[++i]; break;
69
+ case "--api-password": opts.apiPassword = argv[++i]; break;
70
+ case "--endpoint": opts.endpoint = argv[++i]; break;
71
+ case "--framework": opts.framework = argv[++i]; break;
72
+ case "--timeout": opts.timeoutMs = parseInt(argv[++i], 10); break;
73
+ case "--pretty": opts.pretty = true; break;
74
+ case "--config": opts.config = argv[++i]; break;
75
+ case "--max-files": opts.maxFiles = parseInt(argv[++i], 10); break;
76
+ case "--fail-on": opts.failOn = argv[++i]; break; // "error" (default) | "warning" | "never"
77
+ case "-h": case "--help": opts.help = true; break;
78
+ default:
79
+ if (a.startsWith("--")) {
80
+ throw Object.assign(new Error("Unknown flag: " + a), { exitCode: 2 });
81
+ }
82
+ positional.push(a);
83
+ }
84
+ }
85
+ return { opts, positional };
86
+ }
87
+
88
+ function jsonOut(value) {
89
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
90
+ }
91
+
92
+ // Per-subcommand "pretty" formatters. Each receives the parsed envelope.
93
+
94
+ function prettyProviderKeyHealth(providerKey) {
95
+ if (!providerKey || typeof providerKey !== "object") return "";
96
+ const status = providerKey.status ? " [" + providerKey.status + "]" : "";
97
+ const provider = providerKey.provider ? " (" + providerKey.provider + ")" : "";
98
+ let s = "";
99
+ s += "AI key health: " + (providerKey.label || providerKey.status || "Unknown") + provider + status + "\n";
100
+ if (providerKey.nextTestDueUtc) s += "next key test: " + providerKey.nextTestDueUtc + "\n";
101
+ if (providerKey.rotationDueUtc) s += "rotation review: " + providerKey.rotationDueUtc + "\n";
102
+ if (providerKey.recommendedAction) s += "key action: " + providerKey.recommendedAction + "\n";
103
+ return s;
104
+ }
105
+
106
+ function prettyUsage(r) {
107
+ if (!r.ok) return "[" + r.error + "] " + r.message + "\n";
108
+ let s = "";
109
+ s += "tier: " + r.tier + (r.previewMode ? " (preview mode)" : "") + "\n";
110
+ s += "billing month: " + r.billingMonth + "\n";
111
+ s += "actions: " + r.actionsUsed + " / " + r.actionsCap + " (" + r.actionsRemaining + " remaining)\n";
112
+ s += "tokens: " + r.tokensUsed + " / " + r.tokensCap + " (" + r.tokensRemaining + " remaining)\n";
113
+ s += "cost (cents): " + r.approxCostCents + " / " + r.costCapCents + " (" + r.costRemainingCents + " remaining)\n";
114
+ s += "quota rejections: " + r.quotaRejections + "\n";
115
+ s += prettyProviderKeyHealth(r.providerKey);
116
+ s += "as of: " + r.asOfUtc + "\n";
117
+ return s;
118
+ }
119
+
120
+ function prettyPreset(r) {
121
+ if (!r.ok) return "[" + r.error + "] " + r.message + "\n";
122
+ let s = "";
123
+ s += "# Signals\n";
124
+ for (const sig of r.suggestion.signals) s += " - " + sig + "\n";
125
+ s += "\n# Suggested jso.config.json\n";
126
+ s += JSON.stringify(r.suggestion.config, null, 2) + "\n";
127
+ return s;
128
+ }
129
+
130
+ function prettyCompat(r) {
131
+ if (!r.ok) return "[" + r.error + "] " + r.message + "\n";
132
+ const sum = r.report.summary;
133
+ let s = "Summary: " + sum.errors + " error(s) " + sum.warnings + " warning(s) " + sum.infos + " info(s)\n\n";
134
+ for (const f of r.report.findings) {
135
+ s += "[" + f.severity.toUpperCase() + "] " + f.category + " at line " + f.line + ":" + f.column + "\n";
136
+ s += " " + f.message + "\n";
137
+ s += " fix: " + f.suggestedFix + "\n\n";
138
+ }
139
+ return s;
140
+ }
141
+
142
+ function prettyExplain(r) {
143
+ if (!r.ok) return "[" + r.error + "] " + r.message + "\n";
144
+ const e = r.explanation;
145
+ let s = "";
146
+ s += "Cause: " + e.cause + " (confidence: " + e.confidence + ")\n";
147
+ s += "Transform: " + e.transform + "\n\n";
148
+ s += "What happened:\n " + e.explanation + "\n\n";
149
+ s += "Fix:\n " + e.fix + "\n\n";
150
+ s += "Docs: " + e.docsUrl + "\n";
151
+ return s;
152
+ }
153
+
154
+ // Subcommand runners. Each resolves to the envelope; main() handles
155
+ // JSON/pretty + exit-code based on the envelope's `ok` field.
156
+
157
+ async function runUsage(opts) {
158
+ return ai.usage({
159
+ apiKey: opts.apiKey, apiPassword: opts.apiPassword,
160
+ endpoint: opts.endpoint, timeoutMs: opts.timeoutMs,
161
+ });
162
+ }
163
+
164
+ async function runPresetSuggest(opts, positional) {
165
+ if (positional.length === 0) {
166
+ throw Object.assign(new Error("preset-suggest: description is required"), { exitCode: 2 });
167
+ }
168
+ return ai.presetSuggest({
169
+ apiKey: opts.apiKey, apiPassword: opts.apiPassword,
170
+ endpoint: opts.endpoint, timeoutMs: opts.timeoutMs,
171
+ description: positional.join(" "),
172
+ });
173
+ }
174
+
175
+ async function runCompatCheck(opts, positional) {
176
+ if (positional.length === 0) {
177
+ throw Object.assign(new Error("compat-check: <file> is required"), { exitCode: 2 });
178
+ }
179
+ const file = positional[0];
180
+ if (!fs.existsSync(file)) {
181
+ throw Object.assign(new Error("compat-check: file not found: " + file), { exitCode: 2 });
182
+ }
183
+ const source = fs.readFileSync(file, "utf8");
184
+ return ai.compatCheck({
185
+ apiKey: opts.apiKey, apiPassword: opts.apiPassword,
186
+ endpoint: opts.endpoint, timeoutMs: opts.timeoutMs,
187
+ source: source,
188
+ framework: opts.framework,
189
+ });
190
+ }
191
+
192
+ // compat-scan: read jso.config.json, run ai.compatCheck on every input file,
193
+ // aggregate findings, exit non-zero per --fail-on. Designed as a CI gate to
194
+ // run before `jso-protector` so customers catch obfuscation pitfalls (eval,
195
+ // Function-constructor, this-binding tricks, framework reflection) before
196
+ // they ship a broken protected build.
197
+ async function runCompatScan(opts, _positional) {
198
+ const configPath = path.resolve(opts.config || "jso.config.json");
199
+ if (!fs.existsSync(configPath)) {
200
+ throw Object.assign(new Error("compat-scan: config not found: " + configPath), { exitCode: 2 });
201
+ }
202
+ let config;
203
+ try {
204
+ config = JSON.parse(fs.readFileSync(configPath, "utf8"));
205
+ } catch (e) {
206
+ throw Object.assign(new Error("compat-scan: invalid JSON in " + configPath + ": " + e.message), { exitCode: 2 });
207
+ }
208
+
209
+ // Resolve input files. Honor either `files: [...]` (explicit list) or
210
+ // `input: <dir>` + `extensions: [".js"]` (directory walk). Exclusions
211
+ // match by substring against the relative path.
212
+ const baseDir = path.dirname(configPath);
213
+ const exts = (config.extensions && config.extensions.length) ? config.extensions : [".js", ".mjs", ".cjs"];
214
+ const excludes = config.exclude || [];
215
+ function isExcluded(rel) {
216
+ return excludes.some(p => rel.includes(p));
217
+ }
218
+ function walk(dir, out) {
219
+ for (const name of fs.readdirSync(dir)) {
220
+ const full = path.join(dir, name);
221
+ const stat = fs.statSync(full);
222
+ if (stat.isDirectory()) {
223
+ if (name === "node_modules" || name === ".git") continue;
224
+ walk(full, out);
225
+ } else if (exts.some(e => name.endsWith(e))) {
226
+ out.push(full);
227
+ }
228
+ }
229
+ }
230
+
231
+ let files = [];
232
+ if (Array.isArray(config.files) && config.files.length) {
233
+ files = config.files.map(f => path.resolve(baseDir, f));
234
+ } else if (config.input) {
235
+ const inDir = path.resolve(baseDir, config.input);
236
+ if (!fs.existsSync(inDir)) {
237
+ throw Object.assign(new Error("compat-scan: input dir not found: " + inDir), { exitCode: 2 });
238
+ }
239
+ walk(inDir, files);
240
+ } else {
241
+ throw Object.assign(new Error("compat-scan: jso.config must have `files` or `input`"), { exitCode: 2 });
242
+ }
243
+
244
+ files = files
245
+ .map(f => ({ abs: f, rel: path.relative(baseDir, f) }))
246
+ .filter(f => !isExcluded(f.rel));
247
+
248
+ if (opts.maxFiles && files.length > opts.maxFiles) {
249
+ files = files.slice(0, opts.maxFiles);
250
+ }
251
+
252
+ const framework = opts.framework || config.framework;
253
+ const results = [];
254
+ let totErr = 0, totWarn = 0, totInfo = 0;
255
+ let firstErrorEnvelope = null;
256
+
257
+ for (const f of files) {
258
+ const source = fs.readFileSync(f.abs, "utf8");
259
+ let env;
260
+ try {
261
+ env = await ai.compatCheck({
262
+ apiKey: opts.apiKey, apiPassword: opts.apiPassword,
263
+ endpoint: opts.endpoint, timeoutMs: opts.timeoutMs,
264
+ source: source, framework: framework,
265
+ });
266
+ } catch (err) {
267
+ // Network / HTTP / auth — abort the whole scan; one bad call
268
+ // usually means all subsequent will fail too.
269
+ if (!firstErrorEnvelope) firstErrorEnvelope = err;
270
+ results.push({ file: f.rel, ok: false, error: err.code || "internal_error", message: err.message });
271
+ break;
272
+ }
273
+ if (!env.ok) {
274
+ results.push({ file: f.rel, ok: false, error: env.error, message: env.message });
275
+ continue;
276
+ }
277
+ const sum = env.report.summary;
278
+ totErr += sum.errors || 0;
279
+ totWarn += sum.warnings || 0;
280
+ totInfo += sum.infos || 0;
281
+ results.push({ file: f.rel, ok: true, summary: sum, findings: env.report.findings });
282
+ }
283
+
284
+ const failOn = (opts.failOn || "error").toLowerCase();
285
+ let gateOk = true;
286
+ if (failOn === "error" && totErr > 0) gateOk = false;
287
+ if (failOn === "warning" && (totErr + totWarn) > 0) gateOk = false;
288
+ // failOn === "never" → always ok
289
+
290
+ return {
291
+ ok: gateOk && !firstErrorEnvelope,
292
+ summary: { files: files.length, errors: totErr, warnings: totWarn, infos: totInfo, failOn: failOn },
293
+ results: results,
294
+ };
295
+ }
296
+
297
+ function prettyCompatScan(r) {
298
+ let s = "";
299
+ s += "Scanned " + r.summary.files + " file(s): "
300
+ + r.summary.errors + " error(s) "
301
+ + r.summary.warnings + " warning(s) "
302
+ + r.summary.infos + " info(s) (gate: fail-on=" + r.summary.failOn + ")\n\n";
303
+ for (const res of r.results) {
304
+ if (!res.ok) {
305
+ s += "[ERR] " + res.file + ": [" + res.error + "] " + res.message + "\n";
306
+ continue;
307
+ }
308
+ const sum = res.summary;
309
+ if ((sum.errors + sum.warnings + sum.infos) === 0) {
310
+ s += "[OK] " + res.file + "\n";
311
+ continue;
312
+ }
313
+ s += "[" + (sum.errors > 0 ? "FAIL" : "WARN") + "] " + res.file
314
+ + " (" + sum.errors + "e " + sum.warnings + "w " + sum.infos + "i)\n";
315
+ for (const f of res.findings) {
316
+ s += " [" + f.severity.toUpperCase() + "] " + f.category
317
+ + " at " + f.line + ":" + f.column + " — " + f.message + "\n";
318
+ if (f.suggestedFix) s += " fix: " + f.suggestedFix + "\n";
319
+ }
320
+ }
321
+ s += "\nGate: " + (r.ok ? "PASS" : "FAIL") + "\n";
322
+ return s;
323
+ }
324
+
325
+ async function runExplainError(opts, positional) {
326
+ if (positional.length === 0) {
327
+ throw Object.assign(new Error("explain-error: error message is required"), { exitCode: 2 });
328
+ }
329
+ return ai.explainError({
330
+ apiKey: opts.apiKey, apiPassword: opts.apiPassword,
331
+ endpoint: opts.endpoint, timeoutMs: opts.timeoutMs,
332
+ error: positional.join(" "),
333
+ });
334
+ }
335
+
336
+ const SUBCOMMANDS = {
337
+ "usage": { run: runUsage, pretty: prettyUsage },
338
+ "preset-suggest": { run: runPresetSuggest, pretty: prettyPreset },
339
+ "compat-check": { run: runCompatCheck, pretty: prettyCompat },
340
+ "compat-scan": { run: runCompatScan, pretty: prettyCompatScan },
341
+ "explain-error": { run: runExplainError, pretty: prettyExplain },
342
+ };
343
+
344
+ async function main(argv) {
345
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
346
+ printHelp();
347
+ return 0;
348
+ }
349
+ const sub = argv[0];
350
+ const def = SUBCOMMANDS[sub];
351
+ if (!def) {
352
+ process.stderr.write("Unknown subcommand: " + sub + "\n\n");
353
+ printHelp(process.stderr);
354
+ return 2;
355
+ }
356
+ let parsed;
357
+ try {
358
+ parsed = parseFlags(argv.slice(1));
359
+ } catch (err) {
360
+ process.stderr.write(err.message + "\n");
361
+ return err.exitCode || 2;
362
+ }
363
+ if (parsed.opts.help) {
364
+ printHelp();
365
+ return 0;
366
+ }
367
+ let envelope;
368
+ try {
369
+ envelope = await def.run(parsed.opts, parsed.positional);
370
+ } catch (err) {
371
+ // auth_missing / input_invalid / network errors / HTTP 4xx
372
+ // (HTTP 4xx carries .status and .body).
373
+ const out = { ok: false, error: err.code || "internal_error", message: err.message };
374
+ if (err.status) out.httpStatus = err.status;
375
+ if (err.body) out.body = err.body;
376
+ if (parsed.opts.pretty) {
377
+ process.stderr.write("[" + out.error + "] " + out.message + "\n");
378
+ } else {
379
+ process.stdout.write(JSON.stringify(out, null, 2) + "\n");
380
+ }
381
+ return err.exitCode || 1;
382
+ }
383
+
384
+ if (parsed.opts.pretty) {
385
+ process.stdout.write(def.pretty(envelope));
386
+ } else {
387
+ jsonOut(envelope);
388
+ }
389
+ return envelope.ok ? 0 : 1;
390
+ }
391
+
392
+ module.exports = { main };