@sdkurjnk/blackshell 0.1.0 → 0.2.1

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/README.md CHANGED
@@ -15,66 +15,65 @@ threat model, and theory.
15
15
 
16
16
  ## Status
17
17
 
18
- Early **proof of concept (v0.1.0)**. This is an LLVM-free *working skeleton*:
19
- the whole pipeline runs end to end on a toy IR with **dummy passes** (an
20
- accept-all gate and identity L1–L3 noising), so the layer contracts are locked
21
- and real passes can drop in without touching call sites.
18
+ **Working skeleton.** The pipeline runs end to end — real `clang`/`llc` compile a
19
+ source unit to an object file — but the three IP stages (eligibility **gate**,
20
+ **noising** L1–L3, equivalence **harness**) are **dummies** (accept-all gate,
21
+ identity noising), so the layer contracts are locked and real passes drop in
22
+ without touching call sites. Dummy output is correct-but-unprotecting — **do not
23
+ treat it as sealed.**
22
24
 
23
- What is **not** implemented yet (roadmap): the real eligibility gate (§5), real
24
- noising L1–L3 incl. carry-sensitive MBA, and raising the pipeline to LLVM for
25
- native, multi-target output. Dummy passes are correct-but-unprotecting — do not
26
- treat current output as sealed.
25
+ Roadmap: real eligibility gate (§5), real noising L1–L3 incl. carry-sensitive MBA.
27
26
 
28
27
  ## Requirements
29
28
 
30
- - **Node.js ≥ 20** — the CLI front door.
31
- - **Python 3** — the PoC engine runs behind the CLI. (`blackshell --version`
32
- works without it; every other command needs Python on `PATH`.)
29
+ - **Node.js ≥ 20** — the CLI (TS Launcher).
30
+ - **clang + llc on `PATH`** — the C++ engine shells out to them (source → LLVM IR → object), at runtime.
31
+ - **g++ (C++17)** — only to build the engine from a clone. The published npm package ships a
32
+ prebuilt engine for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`.
33
33
 
34
- > The internal engine is Python only for the PoC; production moves it behind a
35
- > C-ABI native boundary. See [`docs/interfaces/`](docs/interfaces/).
36
-
37
- ## Install
34
+ ## Build & run (from a clone)
38
35
 
39
36
  ```sh
40
- npm install -g @sdkurjnk/blackshell
37
+ npm install
38
+ npm run build # g++ engine + tsc launcher
39
+ node dist/cli.js --version
40
+ npm test # full test suite
41
41
  ```
42
42
 
43
- Or run from a clone without installing: `node bin/blackshell.js <command>`.
43
+ `npm link` (or a global install) exposes the `blackshell` command; otherwise use
44
+ `node dist/cli.js <command>`.
44
45
 
45
46
  ## Usage
46
47
 
47
- Units are toy IR files (JSON, see [`docs/interfaces/03-ir-model.md`](docs/interfaces/03-ir-model.md)).
48
- Sealing follows a git-style staging model — stage units, then seal the set.
48
+ Units are **source files**. git-style staging — stage units, then seal the set.
49
49
 
50
50
  ```sh
51
- blackshell check <ir-file> # preview: is this region eligible? (gate only)
52
- blackshell add <ir-file> --level L1,L3 # stage a unit for sealing
53
- blackshell list # show staged units and levels
54
- blackshell drop <ir-file> # unstage
55
- blackshell enshell --verify # seal all staged units -> artifacts
56
- blackshell run <ir-file> --input a=40 # (dev) run a unit in the toy interpreter
51
+ blackshell check <source> # preview: is this region eligible? (gate only)
52
+ blackshell add <source> --level L1,L3 # stage a unit (default level: L3)
53
+ blackshell list # show staged units and levels
54
+ blackshell drop <source> # unstage
55
+ blackshell enshell # seal all staged units -> object files
57
56
  ```
58
57
 
59
58
  Example:
60
59
 
61
60
  ```sh
62
- blackshell add src/engine/examples/add2.ir.json --level L1,L3
63
- blackshell enshell --verify --emit-ir out
61
+ blackshell add src/engine/examples/add2.c --level L1,L3
62
+ blackshell enshell
64
63
  ```
65
64
 
66
65
  ## How it works
67
66
 
68
67
  ```
69
- [external] JS CLI ──argv──▶ [internal] engine
70
- bin/ + src/cli/ src/engine/ (Python, PoC)
71
- packaging · version gate → noising (L1–L3) → emit
72
- equivalence harness verifies every pass
68
+ [Launcher] TS / npm argv [Engine] C++ binary
69
+ src/launcher/cli.ts ───────────────▶ src/engine/
70
+ CLI · staging · render token · exit clang → gate → noising → harness → llc → .o
73
71
  ```
74
72
 
75
- The external/internal split and every layer contract (CLI seam, driver, IR
76
- model, pass contract, verification harness) are documented in
77
- [`docs/interfaces/`](docs/interfaces/). Contributing follows GitFlow —
73
+ The Launcher owns the CLI (parsing, staging, rendering); the engine runs the seal
74
+ pipeline per unit and returns a structured token. Layer contracts and the full
75
+ architecture are in [`docs/interfaces/`](docs/interfaces/) and
76
+ [`docs/Architecture.md`](docs/Architecture.md). Contributing follows GitFlow —
78
77
  see [`docs/contributing-gitflow.md`](docs/contributing-gitflow.md).
79
78
 
80
79
  ## License
package/dist/cli.js ADDED
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+ // BlackShell Launcher (TS). Owns the CLI: parsing, the command set, the staging
3
+ // index and message rendering (docs/Architecture.md §5 hybrid). The C++ engine
4
+ // exposes per-unit primitives (check, enshell); the Launcher composes them — e.g.
5
+ // `enshell` seals every staged unit by calling the engine's enshell per unit.
6
+ import { spawnSync } from "node:child_process";
7
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ const here = (p) => fileURLToPath(new URL(p, import.meta.url));
10
+ const pkg = JSON.parse(readFileSync(here("../package.json"), "utf8"));
11
+ const USAGE = `blackshell <command> [options]
12
+
13
+ check <source> Gate verdict only (dummy: accept-all)
14
+ add <source> [--level L] Stage a unit for sealing (L = e.g. L1,L2; default L3)
15
+ drop <source> Unstage a unit
16
+ list Show staged units and their levels
17
+ enshell Seal every staged unit -> object files
18
+ help | -h Show this help
19
+ -v | --version Show the version`;
20
+ // --- staging index (.blackshell/stage.json in the working dir, git-index-like) ---
21
+ const STAGE_FILE = ".blackshell/stage.json";
22
+ export function readStage() {
23
+ if (!existsSync(STAGE_FILE)) {
24
+ return [];
25
+ }
26
+ return JSON.parse(readFileSync(STAGE_FILE, "utf8"));
27
+ }
28
+ export function writeStage(units) {
29
+ mkdirSync(".blackshell", { recursive: true });
30
+ writeFileSync(STAGE_FILE, JSON.stringify(units, null, 2) + "\n");
31
+ }
32
+ export function showLevels(levels) {
33
+ if (levels.length === 0) {
34
+ return "L0 (identity)";
35
+ }
36
+ return levels.join(",");
37
+ }
38
+ // Resolve the engine binary: the published package ships a per-platform prebuilt
39
+ // under vendor/<platform>-<arch>/; a local dev build lands in build/.
40
+ function enginePath() {
41
+ const exe = process.platform === "win32" ? "blackshell-engine.exe" : "blackshell-engine";
42
+ const vendored = here(`../vendor/${process.platform}-${process.arch}/${exe}`);
43
+ return existsSync(vendored) ? vendored : here(`../build/${exe}`);
44
+ }
45
+ // --- engine (C++) per-unit primitive call; returns the structured token line ---
46
+ function engine(args) {
47
+ const bin = enginePath();
48
+ const res = spawnSync(bin, args, { encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
49
+ if (res.error) {
50
+ console.error("error: engine not found (build it: npm run build:engine)");
51
+ return { token: "", status: 127 };
52
+ }
53
+ const token = (res.stdout ?? "").trim().split("\n").pop() ?? "";
54
+ return { token, status: res.status ?? 1 };
55
+ }
56
+ // engine token -> rendered message. The engine never renders.
57
+ export function render(token) {
58
+ const [key, ...a] = token.split(" ");
59
+ switch (key) {
60
+ case "gate.ok": {
61
+ return { line: `pass: ${a[0]} is eligible`, err: false };
62
+ }
63
+ case "gate.reject": {
64
+ return { line: `reject: ${a[0]} — ineligible`, err: true };
65
+ }
66
+ case "sealed": {
67
+ return { line: `sealed: ${a[0]} -> ${a[1]}`, err: false };
68
+ }
69
+ case "frontend.failed": {
70
+ return { line: `error: clang (frontend) failed on ${a[0]}`, err: true };
71
+ }
72
+ case "backend.failed": {
73
+ return { line: `error: llc (backend) failed on ${a[0]}`, err: true };
74
+ }
75
+ case "verify.broken": {
76
+ return { line: `error: noising broke equivalence on ${a[0]}`, err: true };
77
+ }
78
+ case "arg.one_positional": {
79
+ return { line: `error: expected exactly one <source> argument`, err: true };
80
+ }
81
+ case "cmd.unknown": {
82
+ return { line: `error: unknown command: ${a[0]}`, err: true };
83
+ }
84
+ default: {
85
+ return { line: token, err: true };
86
+ }
87
+ }
88
+ }
89
+ function emit(token) {
90
+ if (!token) {
91
+ return;
92
+ }
93
+ const { line, err } = render(token);
94
+ if (err) {
95
+ console.error(line);
96
+ }
97
+ else {
98
+ console.log(line);
99
+ }
100
+ }
101
+ // --- arg helpers ---
102
+ export function popOption(rest, name) {
103
+ const i = rest.indexOf(name);
104
+ if (i === -1) {
105
+ return { value: undefined, rest };
106
+ }
107
+ return { value: rest[i + 1], rest: rest.slice(0, i).concat(rest.slice(i + 2)) };
108
+ }
109
+ export function onePositional(rest) {
110
+ const positionals = rest.filter((a) => !a.startsWith("--"));
111
+ if (positionals.length !== 1) {
112
+ return undefined;
113
+ }
114
+ return positionals[0];
115
+ }
116
+ // --- commands ---
117
+ function cmdCheck(rest) {
118
+ const src = onePositional(rest);
119
+ if (src === undefined) {
120
+ console.error("error: expected exactly one <source> argument");
121
+ return 1;
122
+ }
123
+ const { token, status } = engine(["check", src]);
124
+ emit(token);
125
+ return status;
126
+ }
127
+ function cmdAdd(rest) {
128
+ const opt = popOption(rest, "--level");
129
+ const src = onePositional(opt.rest);
130
+ if (src === undefined) {
131
+ console.error("error: expected exactly one <source> argument");
132
+ return 1;
133
+ }
134
+ if (!existsSync(src)) {
135
+ console.error(`error: file not found: ${src}`);
136
+ return 1;
137
+ }
138
+ const levels = opt.value ? opt.value.split(",").map((s) => s.trim()).filter(Boolean) : ["L3"];
139
+ const units = readStage().filter((u) => u.path !== src);
140
+ units.push({ path: src, levels });
141
+ writeStage(units);
142
+ console.log(`staged: ${src} [${showLevels(levels)}]`);
143
+ return 0;
144
+ }
145
+ function cmdDrop(rest) {
146
+ const src = onePositional(rest);
147
+ if (src === undefined) {
148
+ console.error("error: expected exactly one <source> argument");
149
+ return 1;
150
+ }
151
+ const units = readStage();
152
+ const kept = units.filter((u) => u.path !== src);
153
+ if (kept.length === units.length) {
154
+ console.error(`error: not staged: ${src}`);
155
+ return 1;
156
+ }
157
+ writeStage(kept);
158
+ console.log(`dropped: ${src}`);
159
+ return 0;
160
+ }
161
+ function cmdList() {
162
+ const units = readStage();
163
+ if (units.length === 0) {
164
+ console.log("nothing staged");
165
+ return 0;
166
+ }
167
+ for (const u of units) {
168
+ console.log(` ${u.path} [${showLevels(u.levels)}]`);
169
+ }
170
+ return 0;
171
+ }
172
+ function cmdEnshell() {
173
+ const units = readStage();
174
+ if (units.length === 0) {
175
+ console.log("nothing staged");
176
+ return 0;
177
+ }
178
+ let code = 0;
179
+ for (const u of units) {
180
+ const { token, status } = engine(["enshell", u.path]);
181
+ emit(token);
182
+ if (status !== 0) {
183
+ code = status;
184
+ }
185
+ }
186
+ writeStage([]); // 1-shot: staging is consumed by enshell
187
+ console.log(`enshell complete: ${units.length} unit(s); staging cleared`);
188
+ return code;
189
+ }
190
+ function main(argv) {
191
+ const [cmd, ...rest] = argv;
192
+ if (cmd === "-v" || cmd === "--version" || cmd === "version") {
193
+ console.log(pkg.version);
194
+ return 0;
195
+ }
196
+ if (cmd === undefined || cmd === "help" || cmd === "-h" || cmd === "--help") {
197
+ console.log(USAGE);
198
+ return 0;
199
+ }
200
+ switch (cmd) {
201
+ case "check": {
202
+ return cmdCheck(rest);
203
+ }
204
+ case "add": {
205
+ return cmdAdd(rest);
206
+ }
207
+ case "drop": {
208
+ return cmdDrop(rest);
209
+ }
210
+ case "list": {
211
+ return cmdList();
212
+ }
213
+ case "enshell": {
214
+ return cmdEnshell();
215
+ }
216
+ default: {
217
+ console.error(`error: unknown command: ${cmd}`);
218
+ console.error(USAGE);
219
+ return 1;
220
+ }
221
+ }
222
+ }
223
+ // Run only when invoked directly (not when imported by tests).
224
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
225
+ process.exit(main(process.argv.slice(2)));
226
+ }
package/package.json CHANGED
@@ -1,20 +1,23 @@
1
1
  {
2
2
  "name": "@sdkurjnk/blackshell",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Build-stage protection tool that seals critical code regions at the compiler IR level, communicating with the outside only by value.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "blackshell": "bin/blackshell.js"
7
+ "blackshell": "dist/cli.js"
8
8
  },
9
9
  "files": [
10
- "bin/",
11
- "src/cli/",
12
- "src/engine/blackshell_engine/",
13
- "src/engine/examples/"
10
+ "dist/",
11
+ "src/",
12
+ "vendor/"
14
13
  ],
15
14
  "scripts": {
16
- "test": "node --test",
17
- "test:engine": "python -m unittest discover -s src/engine/tests -t src/engine -p \"test_*.py\""
15
+ "build:engine": "node -e \"require('fs').mkdirSync('build',{recursive:true})\" && g++ -std=c++17 -O2 -o build/blackshell-engine src/engine/main.cpp src/engine/driver.cpp src/engine/frontend.cpp src/engine/gate.cpp src/engine/noising.cpp src/engine/harness.cpp src/engine/backend.cpp",
16
+ "build:engine-test": "node -e \"require('fs').mkdirSync('build',{recursive:true})\" && g++ -std=c++17 -O2 -I src/engine -o build/blackshell-engine-test test/engine/engine_test.cpp src/engine/driver.cpp src/engine/frontend.cpp src/engine/gate.cpp src/engine/noising.cpp src/engine/harness.cpp src/engine/backend.cpp",
17
+ "build:ts": "tsc",
18
+ "build": "npm run build:engine && npm run build:ts",
19
+ "pretest": "npm run build && npm run build:engine-test",
20
+ "test": "node --test"
18
21
  },
19
22
  "engines": {
20
23
  "node": ">=20"
@@ -38,5 +41,9 @@
38
41
  "publishConfig": {
39
42
  "access": "public",
40
43
  "provenance": true
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^26.6.6",
47
+ "typescript": "^7.0.2"
41
48
  }
42
49
  }
@@ -0,0 +1,9 @@
1
+ #include "engine.hpp"
2
+ #include <cstdlib>
3
+
4
+ // Backend (LLVM / llc): compile LLVM IR to an object file. BLACK BOX — real LLVM.
5
+ // shortcut: std::system with naive quoting; upgrade to argv exec if needed.
6
+ bool backend_emit(const std::string& ir, const std::string& obj_out) {
7
+ const std::string cmd = "llc -filetype=obj \"" + ir + "\" -o \"" + obj_out + "\"";
8
+ return std::system(cmd.c_str()) == 0;
9
+ }
@@ -0,0 +1,33 @@
1
+ #include "engine.hpp"
2
+ #include <cstdio>
3
+ #include <string>
4
+
5
+ static std::string stem(const std::string& path) {
6
+ const size_t s = path.find_last_of("/\\");
7
+ const std::string base = (s == std::string::npos) ? path : path.substr(s + 1);
8
+ const size_t d = base.find_last_of('.');
9
+ return (d == std::string::npos) ? base : base.substr(0, d);
10
+ }
11
+
12
+ // Gate verdict only (preview before staging). Dummy gate accepts everything.
13
+ int driver_check(const std::string& src) {
14
+ if (!gate_check(src)) { std::printf("gate.reject %s\n", src.c_str()); return EXIT_REJECT; }
15
+ std::printf("gate.ok %s\n", src.c_str());
16
+ return EXIT_OK;
17
+ }
18
+
19
+ // Enshell pipeline: frontend -> gate -> noising -> backend -> artifact. Emits
20
+ // structured tokens on stdout; the Launcher renders them.
21
+ int driver_enshell(const std::string& src) {
22
+ const std::string base = stem(src), ir = base + ".ll", obj = base + ".o";
23
+ if (!frontend_compile(src, ir)) { std::printf("frontend.failed %s\n", src.c_str()); return EXIT_ERR; }
24
+ if (!gate_check(ir)) { std::remove(ir.c_str()); std::printf("gate.reject %s\n", src.c_str()); return EXIT_REJECT; }
25
+ if (!noising_apply(ir)) { std::remove(ir.c_str()); std::printf("noising.failed %s\n", src.c_str()); return EXIT_ERR; }
26
+ // baseline == transformed here (identity noising in place); real noising
27
+ // yields a distinct transformed IR while the baseline is the L0 (pre-noise) IR.
28
+ if (!harness_verify(ir, ir)) { std::remove(ir.c_str()); std::printf("verify.broken %s\n", src.c_str()); return EXIT_ERR; }
29
+ if (!backend_emit(ir, obj)) { std::remove(ir.c_str()); std::printf("backend.failed %s\n", src.c_str()); return EXIT_ERR; }
30
+ std::remove(ir.c_str());
31
+ std::printf("sealed %s %s\n", src.c_str(), obj.c_str());
32
+ return EXIT_OK;
33
+ }
@@ -0,0 +1,24 @@
1
+ #pragma once
2
+ #include <string>
3
+
4
+ // BlackShell engine — contract shared across the enshell pipeline.
5
+ // The Driver sequences orthogonal primitives (load -> gate -> noise -> emit).
6
+ // Each primitive lives in its own translation unit so a real implementation
7
+ // drops in without touching the others (docs/Architecture.md §5).
8
+ //
9
+ // IR is handed between stages as a file path for now (clang/llc run as
10
+ // subprocesses). shortcut: file-path handoff; upgrade to an in-memory IR handle
11
+ // when the passes link libLLVM in-process.
12
+
13
+ enum ExitCode { EXIT_OK = 0, EXIT_ERR = 1, EXIT_REJECT = 2 };
14
+
15
+ // --- primitives (orthogonal; see frontend/gate/noising/backend .cpp) ---
16
+ bool frontend_compile(const std::string& src, const std::string& ir_out); // clang: source -> IR
17
+ bool gate_check(const std::string& ir); // §5 cond.1; dummy accept-all
18
+ bool noising_apply(const std::string& ir); // L1-L3; dummy identity
19
+ bool harness_verify(const std::string& baseline_ir, const std::string& transformed_ir); // EquivalenceHarness: L0 vs transformed; dummy = equivalent
20
+ bool backend_emit(const std::string& ir, const std::string& obj_out); // llc: IR -> object
21
+
22
+ // --- driver (sequences the primitives) ---
23
+ int driver_check(const std::string& src); // gate verdict only
24
+ int driver_enshell(const std::string& src); // full enshell pipeline
@@ -0,0 +1 @@
1
+ int add2(int a, int b) { return a + b; }
@@ -0,0 +1,10 @@
1
+ #include "engine.hpp"
2
+ #include <cstdlib>
3
+
4
+ // Frontend (LLVM / clang): compile source to LLVM IR. BLACK BOX — real LLVM.
5
+ // shortcut: std::system with naive quoting (local dev tool, user's own files);
6
+ // upgrade to CreateProcess/argv exec if quoting/injection matters.
7
+ bool frontend_compile(const std::string& src, const std::string& ir_out) {
8
+ const std::string cmd = "clang -S -emit-llvm \"" + src + "\" -o \"" + ir_out + "\"";
9
+ return std::system(cmd.c_str()) == 0;
10
+ }
@@ -0,0 +1,5 @@
1
+ #include "engine.hpp"
2
+
3
+ // Gate (our IP): §5 condition 1 isolation check (no external memory sharing).
4
+ // DUMMY: accept-all. Real static analysis over the IR drops in here.
5
+ bool gate_check(const std::string& /*ir*/) { return true; }
@@ -0,0 +1,6 @@
1
+ #include "engine.hpp"
2
+
3
+ // EquivalenceHarness (our IP · safety net): compile+run the baseline (L0) and
4
+ // the transformed IR, compare observable outputs. DUMMY: always equivalent
5
+ // (identity noising can't break anything yet). The real harness drops in here.
6
+ bool harness_verify(const std::string& /*baseline_ir*/, const std::string& /*transformed_ir*/) { return true; }
@@ -0,0 +1,17 @@
1
+ #include "engine.hpp"
2
+ #include <cstdio>
3
+ #include <string>
4
+
5
+ // Entry point: parse the command and hand it to the Driver. The TS Launcher
6
+ // owns real CLI parsing and message rendering; this is the engine's thin
7
+ // dispatch, returning structured tokens on stdout (docs/Architecture.md §5).
8
+ int main(int argc, char** argv) {
9
+ if (argc < 2) { std::printf("usage\n"); return EXIT_OK; }
10
+ const std::string cmd = argv[1];
11
+ if (cmd == "check" || cmd == "enshell") {
12
+ if (argc < 3) { std::printf("arg.one_positional\n"); return EXIT_ERR; }
13
+ return (cmd == "check") ? driver_check(argv[2]) : driver_enshell(argv[2]);
14
+ }
15
+ std::printf("cmd.unknown %s\n", cmd.c_str());
16
+ return EXIT_ERR;
17
+ }
@@ -0,0 +1,6 @@
1
+ #include "engine.hpp"
2
+
3
+ // Noising (our IP): L1/L2 (OLLVM fork) + L3 (carry-sensitive MBA).
4
+ // DUMMY: identity — the IR passes through untouched. Real passes link libLLVM
5
+ // and transform the Module in place.
6
+ bool noising_apply(const std::string& /*ir*/) { return true; }