@soverenia/agent-guard 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted by You for inclusion in the Work
132
+ by You shall be under the terms and conditions of this License,
133
+ without any additional terms or conditions. Notwithstanding the above,
134
+ nothing herein shall supersede or modify the terms of any separate
135
+ license agreement you may have executed with Licensor regarding
136
+ such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 Soverenia
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -43,11 +43,21 @@ Other agents (Cursor, Codex, GitHub Copilot CLI, Mistral Vibe CLI), the manual H
43
43
 
44
44
  ```bash
45
45
  SOVEREENIA_API_KEY=sov_… soverenia-scan package-lock.json # exit 1 on AVOID
46
-
47
- Env vars: `SOVEREENIA_API_KEY`, `SOVEREENIA_BASE_URL`, and `SOVEREENIA_TIMEOUT_MS` (HTTP connect/read timeout, default 60000 — raise it on slow networks e.g. WSL, where the TLS handshake can exceed undici's default 10s connect timeout).
48
46
  SOVEREENIA_API_KEY=sov_… soverenia-scan requirements.txt
47
+
48
+ # full usage:
49
+ # soverenia-scan [lockfile] [--policy strict|balanced|quiet] [--fail-on avoid|upgrade]
50
+ # [--json] [--sbom auto|always|never] [--sbom-threshold N]
51
+ # lockfile (default package-lock.json): package-lock.json (npm) or requirements.txt (name==version, PyPI)
52
+ # exit codes: 0 clean · 1 fail condition (AVOID, or UPGRADE with --fail-on upgrade) · 2 scan error
53
+ # lockfiles with >= 30 deps (--sbom auto, --sbom-threshold N) go as ONE check_sbom request (Pro plan;
54
+ # on a free key or on failure the CLI falls back to per-package check_package calls)
49
55
  ```
50
56
 
57
+ Config: env `SOVEREENIA_API_KEY` / `SOVEREENIA_BASE_URL` (default `https://www.soverenia.com`) win over
58
+ `~/.soverenia.json` (`{"apiKey":"sov_…","baseUrl":"…"}`); `SOVEREENIA_TIMEOUT_MS` sets the HTTP timeout
59
+ (default 60000 — raise it on slow networks e.g. WSL, where the TLS handshake can exceed undici's default 10s connect timeout).
60
+
51
61
  ## SDK
52
62
 
53
63
  ```typescript
@@ -64,7 +74,7 @@ guard.setLocalRelevance(reach.relevance); // "reachable" | "unreachable" | "unkn
64
74
  const final = guard.buildResponse(res); // authoritative is frozen+signed; the agent only writes local_context
65
75
  ```
66
76
 
67
- Tools exposed over MCP: `check_package`, `check_install_plan` — proxied to the Soverenia engine with anti-replay headers (`X-Sovereignia-Timestamp`, `X-Sovereignia-Nonce`).
77
+ Tools exposed over MCP: `check_package`, `check_install_plan`, `check_sbom` (pro plan) — proxied to the Soverenia engine with anti-replay headers (`X-Sovereignia-Timestamp`, `X-Sovereignia-Nonce`) on `/mcp/tools` + `/mcp/call`.
68
78
 
69
79
  ## Docs
70
80
 
@@ -74,4 +84,8 @@ Tools exposed over MCP: `check_package`, `check_install_plan` — proxied to the
74
84
 
75
85
  ## License
76
86
 
77
- Apache-2.0 © Soverenia
87
+ Apache-2.0 © Soverenia — full text in [LICENSE](LICENSE) in this package.
88
+
89
+ (Note: only this client package is open source. The Soverenia Verdict Engine,
90
+ server and verdict rules are proprietary Non-OSS — see the root `LICENSE` of
91
+ the soverenia repository.)
package/dist/index.d.ts CHANGED
@@ -1,16 +1,20 @@
1
- import type { CheckPackageRequest, CheckPackageResponse, LocalContext } from "./types.js";
1
+ import type { CheckPackageRequest, CheckPackageResponse, CheckSbomRequest, LocalContext, SbomCheckResult } from "./types.js";
2
2
  export type { CheckPackageRequest, CheckPackageResponse } from "./types.js";
3
3
  export type LocalRelevance = LocalContext["local_relevance"];
4
4
  /**
5
5
  * MCP klient — volá check_package přes HTTP nebo stdio (REQ-059, REQ-061)
6
6
  */
7
7
  export interface McpTransport {
8
- callTool(name: string, args: CheckPackageRequest): Promise<CheckPackageResponse>;
8
+ callTool(name: string, args: unknown): Promise<unknown>;
9
9
  listTools(): Promise<Array<{
10
10
  name: string;
11
11
  inputSchema: unknown;
12
12
  }>>;
13
13
  }
14
+ export declare function loadConfig(): {
15
+ apiKey: string;
16
+ baseUrl?: string;
17
+ };
14
18
  export declare class HttpMcpTransport implements McpTransport {
15
19
  constructor(baseUrl?: string, apiKey?: string);
16
20
  private baseUrl;
@@ -21,7 +25,7 @@ export declare class HttpMcpTransport implements McpTransport {
21
25
  name: string;
22
26
  inputSchema: unknown;
23
27
  }[]>;
24
- callTool(name: string, args: CheckPackageRequest): Promise<CheckPackageResponse>;
28
+ callTool(name: string, args: unknown): Promise<unknown>;
25
29
  }
26
30
  /**
27
31
  * AgentGuard — hlavní třída SDK.
@@ -37,6 +41,11 @@ export declare class AgentGuard {
37
41
  * Zavolá check_package přes MCP a vrátí odpověď s zmrazeným authoritative blokem.
38
42
  */
39
43
  checkPackage(req: CheckPackageRequest): Promise<CheckPackageResponse>;
44
+ /**
45
+ * REQ-148/158: hromadný verdikt přes SBOM (CycloneDX/SPDX) přes MCP tool check_sbom.
46
+ * Jeden request místo N — vhodné pro CI nad velkým lockfilem.
47
+ */
48
+ checkSbom(req: CheckSbomRequest): Promise<SbomCheckResult>;
40
49
  /**
41
50
  * REQ-060: agent smí zapsat jen local_relevance. Žádná metoda na změnu verdiktu neexistuje.
42
51
  */
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import { join } from "node:path";
10
10
  import { readFileSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  // Konfigurace: 1) SOVEREENIA_API_KEY env, 2) ~/.soverenia.json {"apiKey":"sov_…","baseUrl":"…"}
13
- function loadConfig() {
13
+ export function loadConfig() {
14
14
  try {
15
15
  const cfg = JSON.parse(readFileSync(join(homedir(), ".soverenia.json"), "utf8"));
16
16
  return { apiKey: typeof cfg.apiKey === "string" ? cfg.apiKey : "", baseUrl: typeof cfg.baseUrl === "string" ? cfg.baseUrl : undefined };
@@ -74,7 +74,7 @@ export class AgentGuard {
74
74
  * Zavolá check_package přes MCP a vrátí odpověď s zmrazeným authoritative blokem.
75
75
  */
76
76
  async checkPackage(req) {
77
- const response = await this.transport.callTool("check_package", req);
77
+ const response = (await this.transport.callTool("check_package", req));
78
78
  // Zmrazíme authoritative — agent ho nesmí měnit (REQ-009)
79
79
  if (response.authoritative) {
80
80
  Object.freeze(response.authoritative);
@@ -82,6 +82,13 @@ export class AgentGuard {
82
82
  }
83
83
  return response;
84
84
  }
85
+ /**
86
+ * REQ-148/158: hromadný verdikt přes SBOM (CycloneDX/SPDX) přes MCP tool check_sbom.
87
+ * Jeden request místo N — vhodné pro CI nad velkým lockfilem.
88
+ */
89
+ async checkSbom(req) {
90
+ return (await this.transport.callTool("check_sbom", req));
91
+ }
85
92
  /**
86
93
  * REQ-060: agent smí zapsat jen local_relevance. Žádná metoda na změnu verdiktu neexistuje.
87
94
  */
@@ -3,9 +3,11 @@
3
3
  // JSON-RPC 2.0 přes stdio: initialize / tools/list / tools/call → forward na https://www.soverenia.com/mcp.
4
4
  // Auth: SOVEREENIA_API_KEY env (Bearer). Bez závislostí.
5
5
  import { createInterface } from "node:readline";
6
- import { HttpMcpTransport } from "./index.js";
7
- const BASE = process.env.SOVEREENIA_BASE_URL ?? "https://www.soverenia.com";
8
- const transport = new HttpMcpTransport(BASE, process.env.SOVEREENIA_API_KEY);
6
+ import { HttpMcpTransport, loadConfig } from "./index.js";
7
+ // 2026-11-23 docs: stejná konfigurace jako SDK/scan — 1) SOVEREENIA_API_KEY env, 2) ~/.soverenia.json
8
+ const cfg = loadConfig();
9
+ const BASE = process.env.SOVEREENIA_BASE_URL ?? cfg.baseUrl ?? "https://www.soverenia.com";
10
+ const transport = new HttpMcpTransport(BASE, process.env.SOVEREENIA_API_KEY ?? cfg.apiKey);
9
11
  const SERVER_INFO = { name: "@soverenia/agent-guard", version: "1.0.0" };
10
12
  async function handle(msg) {
11
13
  switch (msg.method) {
@@ -1,73 +1,119 @@
1
1
  #!/usr/bin/env node
2
- // soverenia-scan — CI gate: просканuje lockfile (package-lock.json / requirements.txt),
3
- // zavolá check_package pro každou závislost a skončí exit 1 при AVOID. REQ-088/102.
4
- // Env: SOVEREENIA_API_KEY (povinné), SOVEREENIA_BASE_URL (default https://www.soverenia.com).
5
- import { readFileSync } from "node:fs";
6
- import { AgentGuard, HttpMcpTransport } from "./index.js";
7
- const BASE = process.env.SOVEREENIA_BASE_URL ?? "https://www.soverenia.com";
8
- const file = process.argv[2] ?? "package-lock.json";
2
+ // soverenia-scan — CI gate (REQ-088/102, REQ-158): proskenuje lockfile a skončí exit 1 při AVOID
3
+ // (nebo při UPGRADE s --fail-on upgrade). Velký lockfile (>= --sbom-threshold, default 30 deps)
4
+ // jde jako jeden check_sbom request (server-side cache, 1 request místo N); při selhání
5
+ // nebo --sbom never → fallback na per-package check_package loop.
6
+ // Env: SOVEREENIA_API_KEY (povinné v produkci), SOVEREENIA_BASE_URL (default https://www.soverenia.com).
7
+ import { AgentGuard, HttpMcpTransport, loadConfig } from "./index.js";
8
+ import { loadDeps, depsToCycloneDx, ecosystemOf, parseArgs, decideExit } from "./scan.js";
9
+ // 2026-11-23: stejná konfigurace jako mcp-server/SDK — 1) SOVEREENIA_BASE_URL env, 2) ~/.soverenia.json baseUrl
10
+ const cfg0 = loadConfig();
11
+ const BASE = process.env.SOVEREENIA_BASE_URL ?? cfg0.baseUrl ?? "https://www.soverenia.com";
12
+ let args;
13
+ try {
14
+ args = parseArgs(process.argv.slice(2));
15
+ }
16
+ catch (e) {
17
+ console.error(String(e.message));
18
+ process.exit(2);
19
+ }
9
20
  const guard = new AgentGuard(new HttpMcpTransport(BASE), BASE);
10
- function loadDeps(path) {
11
- const content = readFileSync(path, "utf8");
12
- if (path.endsWith(".json")) {
13
- const lock = JSON.parse(content);
14
- const out = [];
15
- for (const [k, v] of Object.entries(lock.packages ?? {})) {
16
- if (!k.startsWith("node_modules/"))
17
- continue;
18
- const name = k.replace(/^node_modules\//, "").replace(/^node_modules\//, "");
19
- const version = v.version;
20
- if (name && version)
21
- out.push({ purl: `pkg:npm/${name}@${version}`, version });
22
- }
23
- return out;
24
- }
25
- // requirements.txt: name==version
26
- return content
27
- .split("\n")
28
- .map((l) => l.trim())
29
- .filter((l) => l && !l.startsWith("#"))
30
- .map((l) => {
31
- const m = l.match(/^([A-Za-z0-9._-]+)==([A-Za-z0-9._-]+)$/);
32
- return m ? { purl: `pkg:pypi/${m[1].toLowerCase()}@${m[2]}`, version: m[2] } : null;
33
- })
34
- .filter((x) => x !== null);
21
+ let deps;
22
+ try {
23
+ deps = loadDeps(args.file);
24
+ }
25
+ catch (e) {
26
+ console.error(`cannot read lockfile ${args.file}: ${e.message}`);
27
+ process.exit(2);
35
28
  }
36
- const deps = loadDeps(file);
37
29
  if (deps.length === 0) {
38
- console.error(`no dependencies found in ${file}`);
30
+ console.error(`no dependencies found in ${args.file}`);
39
31
  process.exit(2);
40
32
  }
41
- console.log(`scanning ${deps.length} dependencies from ${file} via ${BASE} …`);
42
- let avoid = 0;
43
- let upgrade = 0;
44
- let errors = 0;
45
- for (const d of deps) {
46
- let v = null;
47
- for (let attempt = 0; attempt < 2 && !v; attempt++) {
48
- try {
49
- v = await guard.checkPackage({ purl: d.purl, version: d.version });
33
+ const summary = { SAFE: 0, UPGRADE: 0, AVOID: 0, error: 0 };
34
+ const rows = [];
35
+ // --- 1) check_sbom přes MCP tool (výchozí pro velké lockfile) ---
36
+ const wantSbom = args.sbom === "always" || (args.sbom === "auto" && deps.length >= args.sbomThreshold);
37
+ let usedSbom = false;
38
+ if (wantSbom) {
39
+ try {
40
+ console.error(`scanning ${deps.length} dependencies from ${args.file} via check_sbom (${BASE}) …`);
41
+ const result = (await guard.checkSbom({ sbom: depsToCycloneDx(deps), policy: args.policy, ecosystem: ecosystemOf(args.file) }));
42
+ // gating (403 PLAN_REQUIRED přes MCP isError) i nevalidní odpověď → fallback
43
+ if (!result || !result.summary || result.error) {
44
+ throw new Error(result?.error ? `${result.error.code}: ${result.error.message ?? ""}` : "invalid check_sbom response");
50
45
  }
51
- catch (e) {
52
- if (attempt === 1) {
53
- errors++;
54
- console.error(`ERROR ${d.purl}: ${String(e)}`);
46
+ usedSbom = true;
47
+ summary.SAFE = result.summary.SAFE;
48
+ summary.UPGRADE = result.summary.UPGRADE;
49
+ summary.AVOID = result.summary.AVOID;
50
+ summary.error = result.summary.error;
51
+ for (const v of result.verdicts) {
52
+ const icon = v.verdict === "AVOID" ? "AVOID " : v.verdict === "UPGRADE" ? "UPGRADE" : v.error ? "ERROR " : "SAFE ";
53
+ rows.push({
54
+ purl: v.purl.includes("@") ? v.purl : `${v.purl}@${v.version}`,
55
+ icon,
56
+ detail: v.error ? v.error.code : `${v.rule_id ?? "?"}${v.upgrade_to ? ` → ${v.upgrade_to}` : ""}`,
57
+ });
58
+ }
59
+ }
60
+ catch (e) {
61
+ console.error(`check_sbom unavailable (${String(e)}) — falling back to per-package check_package`);
62
+ }
63
+ }
64
+ // --- 2) fallback: per-package check_package loop ---
65
+ if (!usedSbom) {
66
+ console.error(`scanning ${deps.length} dependencies from ${args.file} via check_package (${BASE}) …`);
67
+ for (const d of deps) {
68
+ let v = null;
69
+ for (let attempt = 0; attempt < 2 && !v; attempt++) {
70
+ try {
71
+ v = await guard.checkPackage({ purl: d.purl, version: d.version, policy: args.policy });
55
72
  }
56
- else {
57
- await new Promise((r) => setTimeout(r, 1500)); // cold cache / 504 → retry
73
+ catch (e) {
74
+ if (attempt === 1) {
75
+ summary.error++;
76
+ rows.push({ purl: d.purl.includes("@") ? d.purl : `${d.purl}@${d.version}`, icon: "ERROR ", detail: String(e) });
77
+ }
78
+ else {
79
+ await new Promise((r) => setTimeout(r, 1500)); // cold cache / 504 → retry
80
+ }
58
81
  }
59
82
  }
83
+ if (!v)
84
+ continue;
85
+ if (!v.authoritative) {
86
+ // chybová odpověď (např. PACKAGE_NOT_FOUND) — "neznámý" není SAFE: počítáme jako ERROR (exit 2)
87
+ summary.error++;
88
+ rows.push({ purl: d.purl.includes("@") ? d.purl : `${d.purl}@${d.version}`, icon: "ERROR ", detail: v.error?.code ?? "no verdict" });
89
+ continue;
90
+ }
91
+ const a = v.authoritative;
92
+ const icon = a.verdict === "AVOID" ? "AVOID " : a.verdict === "UPGRADE" ? "UPGRADE" : "SAFE ";
93
+ if (a.verdict === "AVOID")
94
+ summary.AVOID++;
95
+ else if (a.verdict === "UPGRADE")
96
+ summary.UPGRADE++;
97
+ else
98
+ summary.SAFE++;
99
+ rows.push({ purl: d.purl.includes("@") ? d.purl : `${d.purl}@${d.version}`, icon, detail: `${a.rule_id}${a.upgrade_to ? ` → ${a.upgrade_to}` : ""}` });
60
100
  }
61
- if (!v)
62
- continue;
63
- const a = v.authoritative;
64
- const icon = a.verdict === "AVOID" ? "AVOID " : a.verdict === "UPGRADE" ? "UPGRADE" : "SAFE ";
65
- if (a.verdict === "AVOID")
66
- avoid++;
67
- if (a.verdict === "UPGRADE")
68
- upgrade++;
69
- console.log(`${icon} ${d.purl} (${a.rule_id}${a.upgrade_to ? ` → ${a.upgrade_to}` : ""})`);
70
101
  }
71
- const safe = deps.length - avoid - upgrade - errors;
72
- console.log(`\n${deps.length} scanned — SAFE ${safe}, UPGRADE ${upgrade}, AVOID ${avoid}, ERROR ${errors}`);
73
- process.exit(avoid > 0 ? 1 : errors > 0 ? 2 : 0);
102
+ // --- výstup ---
103
+ if (args.json) {
104
+ console.log(JSON.stringify({
105
+ file: args.file,
106
+ via: usedSbom ? "check_sbom" : "check_package",
107
+ policy: args.policy,
108
+ fail_on: args.failOn,
109
+ total: deps.length,
110
+ summary,
111
+ verdicts: rows,
112
+ }, null, 2));
113
+ }
114
+ else {
115
+ for (const r of rows)
116
+ console.log(`${r.icon} ${r.purl} (${r.detail})`);
117
+ console.log(`\n${deps.length} scanned via ${usedSbom ? "check_sbom" : "check_package"} — SAFE ${summary.SAFE}, UPGRADE ${summary.UPGRADE}, AVOID ${summary.AVOID}, ERROR ${summary.error}`);
118
+ }
119
+ process.exit(decideExit(summary, args.failOn, deps.length));
package/dist/scan.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Policy } from "./types.js";
2
+ export interface Dep {
3
+ purl: string;
4
+ version: string;
5
+ name: string;
6
+ ecosystem: string;
7
+ }
8
+ /** package-lock.json (npm, `packages` mapa vč. vnořených node_modules) nebo requirements.txt (`name==version`) */
9
+ export declare function loadDeps(path: string): Dep[];
10
+ /** ekosystém podle typu lockfile — fallback pro komponenty bez purl při check_sbom */
11
+ export declare function ecosystemOf(path: string): string;
12
+ /** Deps → CycloneDX 1.5 SBOM (komponenty s purl) */
13
+ export declare function depsToCycloneDx(deps: Dep[]): Record<string, unknown>;
14
+ export interface ScanArgs {
15
+ file: string;
16
+ policy: Policy;
17
+ failOn: "avoid" | "upgrade";
18
+ json: boolean;
19
+ sbom: "auto" | "always" | "never";
20
+ sbomThreshold: number;
21
+ }
22
+ export declare const SBOM_AUTO_THRESHOLD = 30;
23
+ export declare function parseArgs(argv: string[]): ScanArgs;
24
+ export interface ScanSummary {
25
+ SAFE: number;
26
+ UPGRADE: number;
27
+ AVOID: number;
28
+ error: number;
29
+ }
30
+ /**
31
+ * Exit kód CI gate: 1 = fail podmínka (AVOID vždy; UPGRADE při --fail-on upgrade),
32
+ * 2 = chyby (žádné deps / error při scanu), 0 = OK.
33
+ */
34
+ export declare function decideExit(summary: ScanSummary, failOn: "avoid" | "upgrade", total: number): number;
package/dist/scan.js ADDED
@@ -0,0 +1,118 @@
1
+ // Sdílené jádro pro `soverenia-scan` (CI gate) — čisté funkce, testovatelné bez spuštění procesu.
2
+ // REQ-088/102 + REQ-158 (2026-11-22): --policy/--fail-on/--json, velké lockfile přes check_sbom.
3
+ import { readFileSync } from "node:fs";
4
+ /** package-lock.json (npm, `packages` mapa vč. vnořených node_modules) nebo requirements.txt (`name==version`) */
5
+ export function loadDeps(path) {
6
+ const content = readFileSync(path, "utf8");
7
+ if (path.endsWith(".json")) {
8
+ const lock = JSON.parse(content);
9
+ const out = [];
10
+ for (const [k, v] of Object.entries(lock.packages ?? {})) {
11
+ if (!k.startsWith("node_modules/"))
12
+ continue;
13
+ // vnořené cesty (node_modules/a/node_modules/b) → jméno až za posledním node_modules/
14
+ const name = k.slice(k.lastIndexOf("node_modules/") + "node_modules/".length);
15
+ const version = v.version;
16
+ if (name && version)
17
+ out.push({ purl: `pkg:npm/${name}@${version}`, version, name, ecosystem: "npm" });
18
+ }
19
+ return out;
20
+ }
21
+ // requirements.txt: name==version (poznámky přeskočeny, jméno lowercased dle PEP 503)
22
+ return content
23
+ .split("\n")
24
+ .map((l) => l.trim())
25
+ .filter((l) => l && !l.startsWith("#"))
26
+ .map((l) => {
27
+ const m = l.match(/^([A-Za-z0-9._-]+)==([A-Za-z0-9._-]+)$/);
28
+ if (!m)
29
+ return null;
30
+ const name = m[1].toLowerCase();
31
+ return { purl: `pkg:pypi/${name}@${m[2]}`, version: m[2], name, ecosystem: "pypi" };
32
+ })
33
+ .filter((x) => x !== null);
34
+ }
35
+ /** ekosystém podle typu lockfile — fallback pro komponenty bez purl při check_sbom */
36
+ export function ecosystemOf(path) {
37
+ if (path.endsWith(".json"))
38
+ return "npm";
39
+ return "pypi";
40
+ }
41
+ /** Deps → CycloneDX 1.5 SBOM (komponenty s purl) */
42
+ export function depsToCycloneDx(deps) {
43
+ return {
44
+ bomFormat: "CycloneDX",
45
+ specVersion: "1.5",
46
+ version: 1,
47
+ components: deps.map((d) => ({ type: "library", name: d.name, version: d.version, purl: d.purl })),
48
+ };
49
+ }
50
+ export const SBOM_AUTO_THRESHOLD = 30;
51
+ const USAGE = "usage: soverenia-scan [lockfile] [--policy strict|balanced|quiet] [--fail-on avoid|upgrade] [--json] [--sbom auto|always|never] [--sbom-threshold N]";
52
+ export function parseArgs(argv) {
53
+ const args = { file: "package-lock.json", policy: "balanced", failOn: "avoid", json: false, sbom: "auto", sbomThreshold: SBOM_AUTO_THRESHOLD };
54
+ for (let i = 0; i < argv.length; i++) {
55
+ const a = argv[i];
56
+ const next = () => {
57
+ const v = argv[++i];
58
+ if (v === undefined)
59
+ throw new Error(`missing value for ${a}\n${USAGE}`);
60
+ return v;
61
+ };
62
+ switch (a) {
63
+ case "--policy": {
64
+ const v = next();
65
+ if (v !== "strict" && v !== "balanced" && v !== "quiet")
66
+ throw new Error(`invalid --policy "${v}" (strict|balanced|quiet)\n${USAGE}`);
67
+ args.policy = v;
68
+ break;
69
+ }
70
+ case "--fail-on": {
71
+ const v = next();
72
+ if (v !== "avoid" && v !== "upgrade")
73
+ throw new Error(`invalid --fail-on "${v}" (avoid|upgrade)\n${USAGE}`);
74
+ args.failOn = v;
75
+ break;
76
+ }
77
+ case "--json":
78
+ args.json = true;
79
+ break;
80
+ case "--sbom": {
81
+ const v = next();
82
+ if (v !== "auto" && v !== "always" && v !== "never")
83
+ throw new Error(`invalid --sbom "${v}" (auto|always|never)\n${USAGE}`);
84
+ args.sbom = v;
85
+ break;
86
+ }
87
+ case "--sbom-threshold": {
88
+ const v = Number(next());
89
+ if (!Number.isFinite(v) || v < 1)
90
+ throw new Error(`invalid --sbom-threshold\n${USAGE}`);
91
+ args.sbomThreshold = Math.floor(v);
92
+ break;
93
+ }
94
+ case "--help":
95
+ case "-h": throw new Error(USAGE);
96
+ default:
97
+ if (a.startsWith("--"))
98
+ throw new Error(`unknown flag ${a}\n${USAGE}`);
99
+ args.file = a;
100
+ }
101
+ }
102
+ return args;
103
+ }
104
+ /**
105
+ * Exit kód CI gate: 1 = fail podmínka (AVOID vždy; UPGRADE při --fail-on upgrade),
106
+ * 2 = chyby (žádné deps / error při scanu), 0 = OK.
107
+ */
108
+ export function decideExit(summary, failOn, total) {
109
+ if (total === 0)
110
+ return 2;
111
+ if (summary.AVOID > 0)
112
+ return 1;
113
+ if (failOn === "upgrade" && summary.UPGRADE > 0)
114
+ return 1;
115
+ if (summary.error > 0)
116
+ return 2;
117
+ return 0;
118
+ }
package/dist/types.d.ts CHANGED
@@ -26,10 +26,51 @@ export interface LocalContext {
26
26
  }
27
27
  export interface CheckPackageResponse {
28
28
  schema_version: string;
29
- authoritative: AuthoritativeBlock;
29
+ authoritative: AuthoritativeBlock | null;
30
30
  signature: string;
31
31
  key_id: string;
32
32
  signature_alg: string;
33
33
  local_context: LocalContext;
34
34
  sources?: unknown[];
35
+ error?: {
36
+ code: string;
37
+ message: string;
38
+ };
39
+ }
40
+ export interface CheckSbomRequest {
41
+ sbom: unknown;
42
+ policy?: Policy;
43
+ ecosystem?: string;
44
+ }
45
+ export interface SbomVerdictEntry {
46
+ purl: string;
47
+ version: string;
48
+ verdict?: Verdict;
49
+ rule_id?: string;
50
+ rule_version?: string;
51
+ upgrade_to?: string;
52
+ error?: {
53
+ code: string;
54
+ message: string;
55
+ };
56
+ }
57
+ export interface SbomCheckResult {
58
+ schema_version: string;
59
+ sbom: {
60
+ format: string;
61
+ total: number;
62
+ checked: number;
63
+ skipped: Array<{
64
+ name?: string;
65
+ reason: string;
66
+ }>;
67
+ };
68
+ policy: Policy;
69
+ summary: {
70
+ SAFE: number;
71
+ UPGRADE: number;
72
+ AVOID: number;
73
+ error: number;
74
+ };
75
+ verdicts: SbomVerdictEntry[];
35
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soverenia/agent-guard",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Agent Guard for Soverenia — deterministic SAFE/UPGRADE/AVOID verdicts for every package your AI agent installs (MCP stdio server + SDK + lockfile scanner)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",