@letterblack/lbe-core 1.3.3 → 1.3.4
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 +1 -1
- package/README.md +130 -442
- package/assets/runtime-boundary.svg +36 -36
- package/dist/cli.js +141 -0
- package/dist/index.js +52 -0
- package/{release-exec/dist → dist}/wasm.lock.json +5 -4
- package/package.json +23 -54
- package/types.d.ts +2 -175
- package/.githooks/pre-commit +0 -2
- package/.githooks/pre-push +0 -2
- package/CHANGELOG.md +0 -75
- package/Release-README.md +0 -65
- package/WORKSPACE.md +0 -422
- package/_proof.mjs +0 -246
- package/bin/lbe.js +0 -12
- package/config/identity.config.json +0 -3
- package/config/policy.default.json +0 -24
- package/dist/cli/lbe.js +0 -4274
- package/dist/hooks/register.cjs +0 -505
- package/dist/state/appendCentral.cjs +0 -87
- package/dist/state/index.cjs +0 -101
- package/exec/cli.js +0 -472
- package/exec/index.js +0 -2
- package/index.js +0 -24
- package/lbe.audit.jsonl +0 -46
- package/release/README.md +0 -216
- package/release/TRUST.md +0 -90
- package/release/exec-README.md +0 -215
- package/release/exec-types.d.ts +0 -50
- package/release-exec/LICENSE +0 -1
- package/release-exec/README.md +0 -215
- package/release-exec/assets/lbe-gates.jpg +0 -0
- package/release-exec/assets/lbe-gates.png +0 -0
- package/release-exec/assets/runtime-boundary.svg +0 -36
- package/release-exec/assets/story-allow.jpg +0 -0
- package/release-exec/assets/story-allow.png +0 -0
- package/release-exec/assets/story-deny.jpg +0 -0
- package/release-exec/assets/story-deny.png +0 -0
- package/release-exec/dist/cli.js +0 -2841
- package/release-exec/dist/index.js +0 -1835
- package/release-exec/hooks/register.cjs +0 -473
- package/release-exec/package.json +0 -35
- package/release-exec/types.d.ts +0 -50
- package/runtime/engine.js +0 -322
- package/runtime/lbe_engine.wasm +0 -0
- package/src/cli/commands/auditVerify.js +0 -36
- package/src/cli/commands/dryrun.js +0 -175
- package/src/cli/commands/health.js +0 -153
- package/src/cli/commands/init.js +0 -306
- package/src/cli/commands/integrityCheck.js +0 -57
- package/src/cli/commands/logs.js +0 -53
- package/src/cli/commands/openState.js +0 -44
- package/src/cli/commands/policyAdd.js +0 -8
- package/src/cli/commands/policyMode.js +0 -7
- package/src/cli/commands/policySign.js +0 -72
- package/src/cli/commands/proof.js +0 -122
- package/src/cli/commands/run.js +0 -342
- package/src/cli/commands/status.js +0 -73
- package/src/cli/commands/verify.js +0 -144
- package/src/cli/main.js +0 -176
- package/src/cli/parseArgs.js +0 -114
- package/src/exec/localExecutor.js +0 -289
- package/src/hooks/register.cjs +0 -505
- package/src/state/appendCentral.cjs +0 -87
- package/src/state/fileIndex.js +0 -140
- package/src/state/index.cjs +0 -101
- package/src/state/index.js +0 -65
- package/src/state/intentRegistry.js +0 -83
- package/src/state/migration.js +0 -112
- package/src/state/proofRunner.js +0 -246
- package/src/state/stateRoot.js +0 -40
- package/src/state/targetRegistry.js +0 -108
- package/src/state/workspaceId.js +0 -40
- package/src/state/workspaceRegistry.js +0 -65
- /package/{release-exec/dist → dist}/lbe_engine.wasm +0 -0
package/src/cli/main.js
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
// src/cli/main.js
|
|
2
|
-
// LetterBlack Sentinel CLI entrypoint
|
|
3
|
-
|
|
4
|
-
import fs from 'fs';
|
|
5
|
-
import path from 'path';
|
|
6
|
-
import { fileURLToPath } from 'url';
|
|
7
|
-
import { parseArgs, printHelp } from './parseArgs.js';
|
|
8
|
-
import { initCommand } from './commands/init.js';
|
|
9
|
-
import { verifyCommand } from './commands/verify.js';
|
|
10
|
-
import { dryrunCommand } from './commands/dryrun.js';
|
|
11
|
-
import { runCommand } from './commands/run.js';
|
|
12
|
-
import { auditVerifyCommand } from './commands/auditVerify.js';
|
|
13
|
-
import { integrityCheckCommand, integrityGenerateCommand } from './commands/integrityCheck.js';
|
|
14
|
-
import { performIntegrityCheck } from '../core/integrity.js';
|
|
15
|
-
import { policySignCommand } from './commands/policySign.js';
|
|
16
|
-
import { healthCommand } from './commands/health.js';
|
|
17
|
-
import { policyAddCommand } from './commands/policyAdd.js';
|
|
18
|
-
import { policyModeCommand } from './commands/policyMode.js';
|
|
19
|
-
import { statusCommand } from './commands/status.js';
|
|
20
|
-
import { logsCommand } from './commands/logs.js';
|
|
21
|
-
import { openStateCommand } from './commands/openState.js';
|
|
22
|
-
import { proofCommand } from './commands/proof.js';
|
|
23
|
-
|
|
24
|
-
function toBoolean(value, defaultValue = false) {
|
|
25
|
-
if (value === undefined) return defaultValue;
|
|
26
|
-
if (value === true || value === false) return value;
|
|
27
|
-
const normalized = String(value).trim().toLowerCase();
|
|
28
|
-
if (normalized === 'true' || normalized === '1' || normalized === 'yes') return true;
|
|
29
|
-
if (normalized === 'false' || normalized === '0' || normalized === 'no') return false;
|
|
30
|
-
return defaultValue;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
34
|
-
const packageJsonPath = path.join(__dirname, '../../package.json');
|
|
35
|
-
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
|
36
|
-
|
|
37
|
-
export async function main() {
|
|
38
|
-
const argv = process.argv.slice(2);
|
|
39
|
-
if (argv.includes('--version')) {
|
|
40
|
-
console.log(`LetterBlack Sentinel v${packageJson.version}`);
|
|
41
|
-
process.exit(0);
|
|
42
|
-
}
|
|
43
|
-
if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
|
|
44
|
-
printHelp(packageJson.version);
|
|
45
|
-
process.exit(0);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const { command, opts } = parseArgs(argv);
|
|
49
|
-
|
|
50
|
-
// Handle version flag
|
|
51
|
-
if (opts.version) {
|
|
52
|
-
console.log(`LetterBlack Sentinel v${packageJson.version}`);
|
|
53
|
-
process.exit(0);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Handle help flag or no command
|
|
57
|
-
if (opts.help || !command || command === 'help') {
|
|
58
|
-
printHelp(packageJson.version);
|
|
59
|
-
process.exit(0);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
try {
|
|
63
|
-
// Parse --pub-key-file if provided
|
|
64
|
-
if (opts['pub-key-file']) {
|
|
65
|
-
try {
|
|
66
|
-
opts['pub-key'] = fs.readFileSync(path.resolve(opts['pub-key-file']), 'utf-8').trim();
|
|
67
|
-
} catch (error) {
|
|
68
|
-
console.error(`Error reading public key file: ${error.message}`);
|
|
69
|
-
process.exit(1);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Route to command handler
|
|
74
|
-
if (['verify', 'dryrun', 'run'].includes(command)) {
|
|
75
|
-
const integrityStrict = toBoolean(opts['integrity-strict'], false);
|
|
76
|
-
const integrityManifestPath = path.resolve(opts['integrity-manifest'] || '.lbe/config/integrity.manifest.json');
|
|
77
|
-
const integrityResult = await performIntegrityCheck({
|
|
78
|
-
strict: integrityStrict,
|
|
79
|
-
manifestPath: integrityManifestPath
|
|
80
|
-
});
|
|
81
|
-
if (!integrityResult.valid) {
|
|
82
|
-
console.error(JSON.stringify({
|
|
83
|
-
status: 'error',
|
|
84
|
-
error: integrityResult.reason || 'INTEGRITY_CHECK_FAILED',
|
|
85
|
-
message: integrityResult.message
|
|
86
|
-
}, null, 2));
|
|
87
|
-
process.exit(8);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
switch (command) {
|
|
92
|
-
case 'init':
|
|
93
|
-
await initCommand(opts);
|
|
94
|
-
break;
|
|
95
|
-
|
|
96
|
-
case 'verify':
|
|
97
|
-
await verifyCommand(opts);
|
|
98
|
-
break;
|
|
99
|
-
|
|
100
|
-
case 'dryrun':
|
|
101
|
-
await dryrunCommand(opts);
|
|
102
|
-
break;
|
|
103
|
-
|
|
104
|
-
case 'run':
|
|
105
|
-
await runCommand(opts);
|
|
106
|
-
break;
|
|
107
|
-
|
|
108
|
-
case 'audit-verify':
|
|
109
|
-
await auditVerifyCommand(opts);
|
|
110
|
-
break;
|
|
111
|
-
|
|
112
|
-
case 'integrity-check':
|
|
113
|
-
await integrityCheckCommand(opts);
|
|
114
|
-
break;
|
|
115
|
-
|
|
116
|
-
case 'integrity-generate':
|
|
117
|
-
await integrityGenerateCommand(opts);
|
|
118
|
-
break;
|
|
119
|
-
|
|
120
|
-
case 'policy-sign':
|
|
121
|
-
await policySignCommand(opts);
|
|
122
|
-
break;
|
|
123
|
-
|
|
124
|
-
case 'health':
|
|
125
|
-
await healthCommand(opts);
|
|
126
|
-
break;
|
|
127
|
-
|
|
128
|
-
case 'policy-add':
|
|
129
|
-
await policyAddCommand(opts);
|
|
130
|
-
break;
|
|
131
|
-
|
|
132
|
-
case 'observe':
|
|
133
|
-
case 'enforce':
|
|
134
|
-
await policyModeCommand(command, opts);
|
|
135
|
-
break;
|
|
136
|
-
|
|
137
|
-
case 'status':
|
|
138
|
-
await statusCommand(opts);
|
|
139
|
-
break;
|
|
140
|
-
|
|
141
|
-
case 'logs':
|
|
142
|
-
await logsCommand(opts);
|
|
143
|
-
break;
|
|
144
|
-
|
|
145
|
-
case 'open-state':
|
|
146
|
-
await openStateCommand(opts);
|
|
147
|
-
break;
|
|
148
|
-
|
|
149
|
-
case 'proof':
|
|
150
|
-
await proofCommand(opts);
|
|
151
|
-
break;
|
|
152
|
-
|
|
153
|
-
default:
|
|
154
|
-
console.error(`Unknown command: ${command}`);
|
|
155
|
-
printHelp(packageJson.version);
|
|
156
|
-
process.exit(1);
|
|
157
|
-
}
|
|
158
|
-
} catch (error) {
|
|
159
|
-
console.error(JSON.stringify({
|
|
160
|
-
status: 'error',
|
|
161
|
-
error: 'INTERNAL_ERROR',
|
|
162
|
-
message: error.message,
|
|
163
|
-
stack: process.env.DEBUG ? error.stack : undefined
|
|
164
|
-
}));
|
|
165
|
-
process.exit(9);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
main().catch((error) => {
|
|
170
|
-
console.error(JSON.stringify({
|
|
171
|
-
status: 'error',
|
|
172
|
-
error: 'FATAL_ERROR',
|
|
173
|
-
message: error.message
|
|
174
|
-
}));
|
|
175
|
-
process.exit(9);
|
|
176
|
-
});
|
package/src/cli/parseArgs.js
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
// src/cli/parseArgs.js
|
|
2
|
-
// Command-line argument parser
|
|
3
|
-
|
|
4
|
-
export function parseArgs(argv) {
|
|
5
|
-
// argv should already have node and script removed
|
|
6
|
-
if (argv.length === 0) {
|
|
7
|
-
return { command: 'help', opts: {} };
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
const command = argv[0];
|
|
11
|
-
const opts = {};
|
|
12
|
-
|
|
13
|
-
for (let i = 1; i < argv.length; i++) {
|
|
14
|
-
if (argv[i].startsWith('--')) {
|
|
15
|
-
const key = argv[i].substring(2);
|
|
16
|
-
// Handle --key=value format
|
|
17
|
-
if (key.includes('=')) {
|
|
18
|
-
const [k, v] = key.split('=');
|
|
19
|
-
opts[k] = v;
|
|
20
|
-
} else {
|
|
21
|
-
const nextArg = argv[i + 1];
|
|
22
|
-
if (!nextArg || nextArg.startsWith('-')) {
|
|
23
|
-
opts[key] = true;
|
|
24
|
-
} else {
|
|
25
|
-
opts[key] = nextArg;
|
|
26
|
-
i++;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
} else if (argv[i].startsWith('-')) {
|
|
30
|
-
const key = argv[i].substring(1);
|
|
31
|
-
const nextArg = argv[i + 1];
|
|
32
|
-
if (!nextArg || nextArg.startsWith('-')) {
|
|
33
|
-
opts[key] = true;
|
|
34
|
-
} else {
|
|
35
|
-
opts[key] = nextArg;
|
|
36
|
-
i++;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
return { command, opts };
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function printHelp(version = 'unknown') {
|
|
45
|
-
console.log(`
|
|
46
|
-
╔═══════════════════════════════════════════════════════════╗
|
|
47
|
-
║ LetterBlack Sentinel — CLI Governance ║
|
|
48
|
-
║ Local-first execution governance SDK v${version.padEnd(12)}║
|
|
49
|
-
╚═══════════════════════════════════════════════════════════╝
|
|
50
|
-
|
|
51
|
-
USAGE:
|
|
52
|
-
lbe [command] [options]
|
|
53
|
-
|
|
54
|
-
COMMANDS:
|
|
55
|
-
init Initialize LetterBlack Sentinel environment
|
|
56
|
-
verify Verify a proposal (validate, don't execute)
|
|
57
|
-
dryrun Validate and simulate execution (no changes)
|
|
58
|
-
run Validate and execute a proposal
|
|
59
|
-
policy-sign Sign policy and write policy signature envelope
|
|
60
|
-
policy-add Controller-only: add a rule to lbe.policy.json
|
|
61
|
-
observe Set project-local policy to advisory mode
|
|
62
|
-
enforce Set project-local policy to blocking mode
|
|
63
|
-
health Run deployment/runtime health checks
|
|
64
|
-
integrity-check Verify controller integrity manifest
|
|
65
|
-
integrity-generate Generate controller integrity manifest
|
|
66
|
-
audit-verify Verify audit log hash-chain integrity
|
|
67
|
-
status Show central state summary for this workspace
|
|
68
|
-
logs Print recent entries from central event log
|
|
69
|
-
open-state Open the central state directory in the file manager
|
|
70
|
-
proof Show latest proof result (--json for raw JSON, --public for redacted)
|
|
71
|
-
help Show this help message
|
|
72
|
-
|
|
73
|
-
OPTIONS:
|
|
74
|
-
--in Input file (JSON proposal)
|
|
75
|
-
--config Policy config file (default: ./.lbe/config/policy.default.json)
|
|
76
|
-
--policy Alias for --config
|
|
77
|
-
--policy-sig Policy signature file (default: ./.lbe/config/policy.sig.json)
|
|
78
|
-
--policy-state Policy monotonic state file (default: ./data/policy.state.json)
|
|
79
|
-
--policy-unsigned-ok Allow unsigned policy (dev-only; default: false)
|
|
80
|
-
--policy-key-id Signer keyId for policy-sign (default: policy-signer-v1-2026Q1)
|
|
81
|
-
--secret-key-file Secret key for policy-sign (default: ./keys/secret.key)
|
|
82
|
-
--data-dir Data directory for health checks (default: ./data)
|
|
83
|
-
--nonce-db Nonce DB path for health checks
|
|
84
|
-
--rate-db Rate-limit DB path for health checks
|
|
85
|
-
--keys-store Trusted keys store (default: ./.lbe/config/keys.json)
|
|
86
|
-
--pub-key Public key for verification (Ed25519 base64)
|
|
87
|
-
--pub-key-file Legacy single-key file path (fallback mode)
|
|
88
|
-
--integrity-strict Fail verify/dryrun/run if integrity check fails
|
|
89
|
-
--integrity-manifest Integrity manifest path (default: ./.lbe/config/integrity.manifest.json)
|
|
90
|
-
--manifest Manifest path override for integrity-check
|
|
91
|
-
--out Output path for integrity-generate
|
|
92
|
-
--audit Audit log file (default: ./data/audit.log.jsonl)
|
|
93
|
-
--root Project root for local policy commands (default: cwd)
|
|
94
|
-
--effect Local rule effect: allow or deny
|
|
95
|
-
--type Local rule type: path or command
|
|
96
|
-
--pattern Local rule glob/pattern
|
|
97
|
-
--from Required human-readable rule provenance
|
|
98
|
-
--json JSON output (default: true)
|
|
99
|
-
--fail-fast Stop at first audit integrity error (default: true)
|
|
100
|
-
--max Max audit entries to process (optional)
|
|
101
|
-
--version Show version
|
|
102
|
-
--help Show this help message
|
|
103
|
-
|
|
104
|
-
EXAMPLES:
|
|
105
|
-
lbe execute --input proposal.json
|
|
106
|
-
cat proposal.json | lbe execute
|
|
107
|
-
lbe policy-sign --config ./.lbe/config/policy.default.json --policy-sig ./.lbe/config/policy.sig.json
|
|
108
|
-
lbe integrity-generate --out ./.lbe/config/integrity.manifest.json
|
|
109
|
-
lbe integrity-check --integrity-strict --manifest ./.lbe/config/integrity.manifest.json
|
|
110
|
-
lbe audit-verify --audit ./data/audit.log.jsonl
|
|
111
|
-
|
|
112
|
-
For more info, visit: https://github.com/Letterblack0306/LetterBlack-LBE-Core
|
|
113
|
-
`);
|
|
114
|
-
}
|
|
@@ -1,289 +0,0 @@
|
|
|
1
|
-
// Trusted, in-process execution controller. Agents submit simple requests;
|
|
2
|
-
// this controller creates the timestamp/nonce/signature envelope locally.
|
|
3
|
-
import crypto from 'crypto';
|
|
4
|
-
import fs from 'fs';
|
|
5
|
-
import path from 'path';
|
|
6
|
-
import { generateKeyPair, signEd25519 } from '../core/signature.js';
|
|
7
|
-
import { validateCommand } from '../core/validator.js';
|
|
8
|
-
import { executeAdapter } from '../adapters/index.js';
|
|
9
|
-
import { appendAudit, verifyAuditLogIntegrity } from '../core/auditLog.js';
|
|
10
|
-
import { addLocalPolicyRule, auditLocalPolicy, evaluateLocalPolicy, loadLocalPolicy, proposePolicyRule } from '../core/localPolicy.js';
|
|
11
|
-
|
|
12
|
-
const INTENTS = {
|
|
13
|
-
read_file: { id: 'READ_FILE', adapter: 'file', action: 'read' },
|
|
14
|
-
write_file: { id: 'WRITE_FILE', adapter: 'file', action: 'write' },
|
|
15
|
-
patch_file: { id: 'PATCH_FILE', adapter: 'file', action: 'patch' },
|
|
16
|
-
delete_file: { id: 'DELETE_FILE', adapter: 'file', action: 'delete' },
|
|
17
|
-
run_shell: { id: 'RUN_SHELL', adapter: 'shell', action: 'run' }
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
const MUTATIONS = new Set(['write_file', 'patch_file', 'delete_file']);
|
|
21
|
-
|
|
22
|
-
function error(code, message, recoverable = false) {
|
|
23
|
-
return { ok: false, decision: 'deny', executed: false, dryRun: false, error: { code, message, recoverable } };
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function commandPolicy(rootDir, actor, shell = {}) {
|
|
27
|
-
const now = new Date();
|
|
28
|
-
const expires = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000);
|
|
29
|
-
return {
|
|
30
|
-
version: 1,
|
|
31
|
-
default: 'DENY',
|
|
32
|
-
requesters: {
|
|
33
|
-
[actor]: {
|
|
34
|
-
allowCommands: Object.values(INTENTS).map(item => item.id),
|
|
35
|
-
allowAdapters: ['file', 'shell'],
|
|
36
|
-
filesystem: { roots: [rootDir], denyPatterns: [] },
|
|
37
|
-
exec: { allowCmds: shell.allowCommands || [], denyCmds: shell.denyCommands || [] },
|
|
38
|
-
rateLimit: { windowSec: 60, maxRequests: shell.maxRequests || 60 }
|
|
39
|
-
}
|
|
40
|
-
},
|
|
41
|
-
security: { maxClockSkewSec: 600, defaultRateLimit: { windowSec: 60, maxRequests: 60 } },
|
|
42
|
-
_keyWindow: { notBefore: now.toISOString(), expiresAt: expires.toISOString() }
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function physicalPath(candidate) {
|
|
47
|
-
let current = path.resolve(candidate);
|
|
48
|
-
const suffix = [];
|
|
49
|
-
while (!fs.existsSync(current)) {
|
|
50
|
-
const parent = path.dirname(current);
|
|
51
|
-
if (parent === current) break;
|
|
52
|
-
suffix.unshift(path.basename(current));
|
|
53
|
-
current = parent;
|
|
54
|
-
}
|
|
55
|
-
try { current = fs.realpathSync(current); } catch { /* lexical fallback */ }
|
|
56
|
-
return path.join(current, ...suffix);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function underRoot(candidate, root) {
|
|
60
|
-
const target = physicalPath(candidate);
|
|
61
|
-
const resolvedRoot = physicalPath(root);
|
|
62
|
-
return target === resolvedRoot || target.startsWith(resolvedRoot + path.sep);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const FORBIDDEN_CONTENT = [
|
|
66
|
-
/\beval\s*\(/i, /\bFunction\s*\(/i, /\bexec\s*\(/i,
|
|
67
|
-
/\brequire\s*\(/, /\bimport\s*\(/, /\bchild_process\b/,
|
|
68
|
-
/\b__proto__\b/, /\bconstructor\s*\[/, /evalScript/i,
|
|
69
|
-
];
|
|
70
|
-
|
|
71
|
-
function scanContent(value, fieldName) {
|
|
72
|
-
if (typeof value !== 'string') return null;
|
|
73
|
-
for (const pattern of FORBIDDEN_CONTENT) {
|
|
74
|
-
if (pattern.test(value)) {
|
|
75
|
-
return error('PAYLOAD_CONTENT_REJECTED', `Forbidden pattern in ${fieldName}: ${pattern}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function normalize(rootDir, request, shell = {}) {
|
|
82
|
-
if (!request || typeof request !== 'object') return { error: error('REQUEST_INVALID', 'request must be an object') };
|
|
83
|
-
const detail = INTENTS[request.intent];
|
|
84
|
-
if (!detail) return { error: error('INTENT_UNSUPPORTED', `Unsupported intent '${request.intent}'`) };
|
|
85
|
-
const actor = typeof request.actor === 'string' && request.actor ? request.actor : 'agent:local';
|
|
86
|
-
let target = null;
|
|
87
|
-
if (detail.adapter === 'file') {
|
|
88
|
-
if (typeof request.target !== 'string' || !request.target) return { error: error('TARGET_REQUIRED', 'target is required for file intents') };
|
|
89
|
-
target = path.resolve(rootDir, request.target);
|
|
90
|
-
if (!underRoot(target, rootDir)) return { error: error('PATH_OUTSIDE_ROOT', 'target is outside project root') };
|
|
91
|
-
if (['write_file', 'patch_file'].includes(request.intent) && typeof request.content !== 'string') {
|
|
92
|
-
return { error: error('CONTENT_REQUIRED', 'content is required for write and patch') };
|
|
93
|
-
}
|
|
94
|
-
const contentScan = scanContent(request.content, 'content');
|
|
95
|
-
if (contentScan) return { error: contentScan };
|
|
96
|
-
}
|
|
97
|
-
let command = null;
|
|
98
|
-
if (detail.adapter === 'shell') {
|
|
99
|
-
command = request.command;
|
|
100
|
-
if (!command || typeof command.cmd !== 'string' || !Array.isArray(command.args) || command.args.some(arg => typeof arg !== 'string')) {
|
|
101
|
-
return { error: error('COMMAND_INVALID', 'command requires cmd and string args') };
|
|
102
|
-
}
|
|
103
|
-
const cwd = path.resolve(rootDir, command.cwd || '.');
|
|
104
|
-
if (!underRoot(cwd, rootDir)) return { error: error('CWD_OUTSIDE_ROOT', 'command cwd is outside project root') };
|
|
105
|
-
if (!Array.isArray(shell.allowCommands) || !shell.allowCommands.includes(command.cmd)) {
|
|
106
|
-
return { error: error('SHELL_NOT_ALLOWLISTED', `command '${command.cmd}' is not explicitly allowlisted`) };
|
|
107
|
-
}
|
|
108
|
-
if (shell.denyCommands?.includes(command.cmd)) return { error: error('SHELL_DENIED', `command '${command.cmd}' is denied`) };
|
|
109
|
-
command = { ...command, cwd, timeoutMs: Math.min(Math.max(command.timeoutMs || 30000, 1), 30000), maxOutputBytes: Math.min(Math.max(command.maxOutputBytes || 1024 * 1024, 1024), 1024 * 1024) };
|
|
110
|
-
}
|
|
111
|
-
return { actor, detail, target, command, request };
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function envelope(normalized, keyId, secretKey) {
|
|
115
|
-
const { actor, detail, target, command, request } = normalized;
|
|
116
|
-
const body = {
|
|
117
|
-
id: detail.id,
|
|
118
|
-
risk: MUTATIONS.has(request.intent) ? 'MEDIUM' : 'LOW',
|
|
119
|
-
commandId: crypto.randomUUID(),
|
|
120
|
-
requesterId: actor,
|
|
121
|
-
sessionId: 'local-host',
|
|
122
|
-
timestamp: Math.floor(Date.now() / 1000),
|
|
123
|
-
nonce: crypto.randomBytes(32).toString('hex'),
|
|
124
|
-
requires: ['policy', 'signature'],
|
|
125
|
-
payload: {
|
|
126
|
-
adapter: detail.adapter,
|
|
127
|
-
action: detail.action,
|
|
128
|
-
target,
|
|
129
|
-
content: request.content,
|
|
130
|
-
cmd: command?.cmd,
|
|
131
|
-
args: command?.args,
|
|
132
|
-
timeoutMs: command?.timeoutMs,
|
|
133
|
-
maxOutputBytes: command?.maxOutputBytes,
|
|
134
|
-
cwd: command?.cwd || (target ? path.dirname(target) : process.cwd())
|
|
135
|
-
}
|
|
136
|
-
};
|
|
137
|
-
const signed = signEd25519({ payloadObj: body, secretKeyB64: secretKey });
|
|
138
|
-
if (signed.error) throw new Error(signed.error);
|
|
139
|
-
return { ...body, signature: { alg: 'ed25519', keyId, sig: signed.signature } };
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export function createLocalExecutor(options = {}) {
|
|
143
|
-
const rootDir = path.resolve(options.rootDir || process.cwd());
|
|
144
|
-
const keyId = options.keyId || 'host:local-exec';
|
|
145
|
-
const keyPair = options.keyPair || generateKeyPair();
|
|
146
|
-
const shell = options.shell || {};
|
|
147
|
-
|
|
148
|
-
function prepare(request, { recordNonce = false } = {}) {
|
|
149
|
-
const normalized = normalize(rootDir, request, shell);
|
|
150
|
-
if (normalized.error) return normalized;
|
|
151
|
-
// When no mode is passed and no policy file exists, default to enforce.
|
|
152
|
-
// Observe mode activates only when explicitly set via options.mode or via
|
|
153
|
-
// npx lbe init which writes lbe.policy.json with mode:'observe'.
|
|
154
|
-
const local = loadLocalPolicy(rootDir, options.mode || 'enforce');
|
|
155
|
-
const localDecision = evaluateLocalPolicy(local.policy, rootDir, { target: normalized.target, command: normalized.command?.cmd });
|
|
156
|
-
const localBlocked = local.policy.mode === 'enforce' && !localDecision.allowed;
|
|
157
|
-
if (localBlocked) return { error: error('LOCAL_POLICY_DENY', `Blocked by rule(s): ${localDecision.winningRules.map(rule => rule.id).join(', ')}`), local, localDecision, normalized };
|
|
158
|
-
const policy = commandPolicy(rootDir, normalized.actor, shell);
|
|
159
|
-
const keyStore = { defaultKeyId: keyId, trustedKeys: { [keyId]: { publicKey: keyPair.publicKey, notBefore: policy._keyWindow.notBefore, expiresAt: policy._keyWindow.expiresAt, deprecated: false } } };
|
|
160
|
-
delete policy._keyWindow;
|
|
161
|
-
const proposal = envelope(normalized, keyId, keyPair.secretKey);
|
|
162
|
-
const nonceDb = { entries: [] };
|
|
163
|
-
const validation = validateCommand({ commandObj: proposal, keyStore, nonceDb: recordNonce ? nonceDb : { entries: [] }, policy });
|
|
164
|
-
if (!validation.valid) return { error: error(validation.errors[0]?.type || 'VALIDATION_FAILED', validation.errors[0]?.message || 'Validation failed'), local, localDecision, normalized, proposal, policy, validation };
|
|
165
|
-
return { local, localDecision, normalized, proposal, policy, validation };
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Sync decision path — for CJS preload hooks that cannot await.
|
|
169
|
-
// Uses local policy only (no WASM, no nonce, no signature).
|
|
170
|
-
function evaluateSync(action) {
|
|
171
|
-
const local = loadLocalPolicy(rootDir, options.mode || 'observe');
|
|
172
|
-
const mode = local.policy.mode;
|
|
173
|
-
let target = null;
|
|
174
|
-
let command = null;
|
|
175
|
-
if (action.path) {
|
|
176
|
-
try {
|
|
177
|
-
target = path.resolve(rootDir, action.path);
|
|
178
|
-
if (!underRoot(target, rootDir)) {
|
|
179
|
-
return { decision: 'deny', deny: true, matchedRules: ['path:outside_root'], mode, enforced: mode === 'enforce', reason: 'PATH_OUTSIDE_ROOT' };
|
|
180
|
-
}
|
|
181
|
-
} catch (e) { /* ignore resolution errors, fall through to policy check */ }
|
|
182
|
-
}
|
|
183
|
-
if (action.cmd) command = action.cmd;
|
|
184
|
-
const localDecision = evaluateLocalPolicy(local.policy, rootDir, { target, command });
|
|
185
|
-
const isDeny = !localDecision.allowed;
|
|
186
|
-
return {
|
|
187
|
-
decision: isDeny ? 'deny' : 'allow',
|
|
188
|
-
deny: isDeny,
|
|
189
|
-
matchedRules: localDecision.winningRules.map(r => r.id),
|
|
190
|
-
mode,
|
|
191
|
-
enforced: mode === 'enforce',
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// Sync audit write to unified event log.
|
|
196
|
-
// Uses openSync/writeSync/closeSync to bypass JS wrappers and avoid recursion
|
|
197
|
-
// if the CJS preload hook has patched fs.writeFileSync in this process.
|
|
198
|
-
function auditSync(entry) {
|
|
199
|
-
const eventsPath = path.join(rootDir, '.lbe', 'events.jsonl');
|
|
200
|
-
const dir = path.dirname(eventsPath);
|
|
201
|
-
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
202
|
-
const line = JSON.stringify({ ts: Math.floor(Date.now() / 1000), ...entry }) + '\n';
|
|
203
|
-
const fd = fs.openSync(eventsPath, 'a');
|
|
204
|
-
try { fs.writeSync(fd, line); } finally { fs.closeSync(fd); }
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
async function dryRun(request) {
|
|
208
|
-
const prepared = prepare(request);
|
|
209
|
-
if (prepared.error) return { ...prepared.error, dryRun: true };
|
|
210
|
-
return {
|
|
211
|
-
ok: true,
|
|
212
|
-
decision: prepared.local.policy.mode === 'observe' ? 'observe' : 'allow',
|
|
213
|
-
executed: false,
|
|
214
|
-
dryRun: true,
|
|
215
|
-
matchedRules: prepared.localDecision.winningRules.map(rule => rule.id),
|
|
216
|
-
rollback: { available: MUTATIONS.has(prepared.normalized.request.intent), performed: false }
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
async function execute(request) {
|
|
221
|
-
const prepared = prepare(request, { recordNonce: true });
|
|
222
|
-
if (prepared.error) {
|
|
223
|
-
auditLocalPolicy(rootDir, { action: request?.intent, actor: request?.actor || 'agent:local', decision: 'deny', error: prepared.error.error.code });
|
|
224
|
-
return prepared.error;
|
|
225
|
-
}
|
|
226
|
-
// Observer mode: validate and audit but never mutate state.
|
|
227
|
-
if (prepared.local.policy.mode === 'observe') {
|
|
228
|
-
appendAudit(path.join(rootDir, '.lbe/audit.jsonl'), {
|
|
229
|
-
kind: 'local_execution', commandId: prepared.proposal.commandId, requesterId: prepared.normalized.actor,
|
|
230
|
-
intent: prepared.normalized.request.intent, decision: 'observe', status: 'observed'
|
|
231
|
-
});
|
|
232
|
-
return {
|
|
233
|
-
ok: true, decision: 'observe', executed: false, dryRun: false,
|
|
234
|
-
matchedRules: prepared.localDecision.winningRules.map(r => r.id),
|
|
235
|
-
rollback: { available: false, performed: false }
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
const requester = prepared.policy.requesters[prepared.normalized.actor];
|
|
239
|
-
const adapterResult = await executeAdapter(prepared.normalized.detail.adapter, prepared.proposal, prepared.policy, requester);
|
|
240
|
-
const ok = adapterResult.status === 'completed';
|
|
241
|
-
const audit = appendAudit(path.join(rootDir, '.lbe/audit.jsonl'), {
|
|
242
|
-
kind: 'local_execution', commandId: prepared.proposal.commandId, requesterId: prepared.normalized.actor,
|
|
243
|
-
intent: prepared.normalized.request.intent, decision: ok ? 'allow' : 'deny', status: adapterResult.status
|
|
244
|
-
});
|
|
245
|
-
return {
|
|
246
|
-
ok,
|
|
247
|
-
decision: ok ? 'allow' : 'deny',
|
|
248
|
-
executed: ok,
|
|
249
|
-
dryRun: false,
|
|
250
|
-
matchedRules: prepared.localDecision.winningRules.map(rule => rule.id),
|
|
251
|
-
auditId: audit.hash,
|
|
252
|
-
rollback: { available: MUTATIONS.has(prepared.normalized.request.intent), performed: false, backupId: adapterResult.backup?.hash },
|
|
253
|
-
...(ok ? {} : { error: { code: adapterResult.errorCode || 'EXECUTION_FAILED', message: adapterResult.error || 'Execution failed', recoverable: true } })
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
// Convenience methods — agents use these; internals stay hidden
|
|
258
|
-
const writeFile = (target, content) => execute({ intent: 'write_file', target, content });
|
|
259
|
-
const readFile = (target) => execute({ intent: 'read_file', target });
|
|
260
|
-
const patchFile = (target, content) => execute({ intent: 'patch_file', target, content });
|
|
261
|
-
const deleteFile = (target) => execute({ intent: 'delete_file', target });
|
|
262
|
-
const runShell = (cmd, args = [], opts = {}) =>
|
|
263
|
-
execute({ intent: 'run_shell', command: { cmd, args, ...opts } });
|
|
264
|
-
|
|
265
|
-
return {
|
|
266
|
-
rootDir,
|
|
267
|
-
// High-level API — use these
|
|
268
|
-
writeFile,
|
|
269
|
-
readFile,
|
|
270
|
-
patchFile,
|
|
271
|
-
deleteFile,
|
|
272
|
-
runShell,
|
|
273
|
-
// Low-level API — for advanced use
|
|
274
|
-
validate: async request => {
|
|
275
|
-
const preview = await dryRun(request);
|
|
276
|
-
return { ...preview, dryRun: false, executed: false };
|
|
277
|
-
},
|
|
278
|
-
dryRun,
|
|
279
|
-
execute,
|
|
280
|
-
policy: {
|
|
281
|
-
read: () => loadLocalPolicy(rootDir, options.mode || 'enforce').policy,
|
|
282
|
-
proposeRule: proposePolicyRule,
|
|
283
|
-
addRule: rule => addLocalPolicyRule(rootDir, rule, options.mode || 'enforce')
|
|
284
|
-
},
|
|
285
|
-
audit: { verify: () => verifyAuditLogIntegrity(path.join(rootDir, '.lbe/audit.jsonl')) },
|
|
286
|
-
evaluateSync,
|
|
287
|
-
auditSync,
|
|
288
|
-
};
|
|
289
|
-
}
|