@sentisec/sdk 0.1.0-rc.2 → 0.1.0-rc.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/CHANGELOG.md CHANGED
@@ -6,6 +6,56 @@ Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ---
8
8
 
9
+ ## [0.1.0-rc.4] — 2026-05-17
10
+
11
+ Routes the CLI binary fetch through the public Cloudflare R2 mirror
12
+ at `https://releases.sentisec.ch/cli/` instead of the GitHub Releases
13
+ URL directly. Keeps the public-facing scripts free of internal repo
14
+ URLs (per `.claude/rules/02-opacity.md`).
15
+
16
+ ### Changed
17
+
18
+ - `scripts/install-binary.js` — `RELEASES_BASE` defaults to
19
+ `https://releases.sentisec.ch/cli`; `SENTISEC_RELEASES_BASE` env
20
+ var overrides. Manifest + tarball URL layout flattened to
21
+ `/<tag>/<file>` to match the R2 bucket key prefix scheme.
22
+
23
+ The CLI tarballs themselves are unchanged — the release-cli.yml
24
+ workflow mirrors every cli-v* artifact from GitHub Releases into R2
25
+ so this URL stays in sync.
26
+
27
+ ---
28
+
29
+ ## [0.1.0-rc.3] — 2026-05-17
30
+
31
+ Adds the CLI bin wrapper + zero-dep postinstall fetcher (P-INST-04).
32
+
33
+ ### Added
34
+
35
+ - **`bin/sentisec.js`** — ESM shim that execs the platform-native
36
+ CLI binary. Resolves the binary via a `PYMINOR` marker file under
37
+ `node_modules/@sentisec/sdk/native/<platform>/<arch>/`. Prints
38
+ curl / pipx recovery hints when the binary is absent.
39
+ - **`scripts/install-binary.js`** — postinstall fetcher (zero deps,
40
+ uses `node:https` + `node:crypto` + system `tar`). Downloads the
41
+ matching `sentisec-cli-vX-<platform>-py<minor>.tar.gz` from GitHub
42
+ Releases, verifies sha256, extracts under
43
+ `node_modules/@sentisec/sdk/native/`. Soft-fails on every
44
+ non-security error (CI guard, no python3, unsupported python-minor,
45
+ manifest 404, network failure, tuple missing) so the SDK remains
46
+ installable as a JS library; only sha256 mismatch hard-fails.
47
+ - **`"bin": { "sentisec": "./bin/sentisec.js" }`** in package.json
48
+ so `npm install -g @sentisec/sdk` puts `sentisec` on PATH.
49
+ - Env overrides: `SENTISEC_SKIP_POSTINSTALL`,
50
+ `SENTISEC_NPM_FETCH_IN_CI`, `SENTISEC_CLI_VERSION_OVERRIDE`.
51
+
52
+ ### Supports
53
+
54
+ - Python 3.11, 3.12, 3.13, 3.14 on darwin-arm64 / darwin-x64 /
55
+ linux-x64 / linux-arm64.
56
+
57
+ ---
58
+
9
59
  ## [0.1.0] — 2026-04-22
10
60
 
11
61
  First public release of `@sentisec/sdk`. Ships the full Phase-1.5 TS SDK:
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ // @sentisec/sdk → bin/sentisec
3
+ // Delegates to the native Sentisec CLI binary installed by
4
+ // scripts/install-binary.js (npm postinstall) into
5
+ // node_modules/@sentisec/sdk/native/<platform>/<arch>/<pyminor>/sentisec.
6
+ //
7
+ // Soft-fail surface: if the binary is missing (e.g., the postinstall
8
+ // soft-failed because python3 was unavailable, the platform/python tuple
9
+ // wasn't published, or the user set SENTISEC_SKIP_POSTINSTALL), print a
10
+ // clear recovery message and exit 1. The library import path
11
+ // (`import { SentisecClient } from '@sentisec/sdk'`) is unaffected.
12
+
13
+ import { spawn } from "node:child_process";
14
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
15
+ import { dirname, join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = dirname(__filename);
20
+
21
+ // Map process.platform → mission's platform name. We pass `linux` / `darwin`
22
+ // straight through; everything else is unsupported.
23
+ const SUPPORTED_PLATFORMS = new Set(["darwin", "linux"]);
24
+ const SUPPORTED_ARCHES = new Set(["arm64", "x64"]);
25
+
26
+ const platform = process.platform;
27
+ const arch = process.arch;
28
+
29
+ function printRecoveryAndExit(reason) {
30
+ const lines = [
31
+ `[sentisec] ${reason}`,
32
+ `[sentisec]`,
33
+ `[sentisec] The @sentisec/sdk library still works for programmatic use:`,
34
+ `[sentisec] import { SentisecClient } from '@sentisec/sdk'`,
35
+ `[sentisec]`,
36
+ `[sentisec] To get the CLI on PATH, try one of:`,
37
+ `[sentisec] curl -fsSL https://get.sentisec.ch | bash`,
38
+ `[sentisec] pipx install sentisec-sdk`,
39
+ `[sentisec]`,
40
+ `[sentisec] Or re-run the npm postinstall after fixing the root cause:`,
41
+ `[sentisec] npm rebuild @sentisec/sdk`,
42
+ ];
43
+ process.stderr.write(lines.join("\n") + "\n");
44
+ process.exit(1);
45
+ }
46
+
47
+ if (!SUPPORTED_PLATFORMS.has(platform) || !SUPPORTED_ARCHES.has(arch)) {
48
+ printRecoveryAndExit(
49
+ `Native CLI not available for ${platform}-${arch} ` +
50
+ `(supported: darwin-arm64, darwin-x64, linux-x64, linux-arm64).`
51
+ );
52
+ }
53
+
54
+ const nativeRoot = join(__dirname, "..", "native", platform, arch);
55
+
56
+ if (!existsSync(nativeRoot)) {
57
+ printRecoveryAndExit(
58
+ `Native CLI binary directory missing at ${nativeRoot}. ` +
59
+ `The npm postinstall fetcher did not run, was disabled, or soft-failed.`
60
+ );
61
+ }
62
+
63
+ // Resolve which python-minor was installed. Prefer the PYMINOR marker file
64
+ // written by install-binary.js; fall back to the highest py-minor directory
65
+ // present (so the shim still works if a maintainer hand-dropped a binary).
66
+ function resolvePyMinor() {
67
+ const markerPath = join(nativeRoot, "PYMINOR");
68
+ if (existsSync(markerPath)) {
69
+ try {
70
+ const value = readFileSync(markerPath, "utf8").trim();
71
+ if (/^\d+\.\d+$/.test(value)) return value;
72
+ } catch {
73
+ // fall through to scan
74
+ }
75
+ }
76
+ // Scan native/<platform>/<arch>/ for `3.11` / `3.12` / `3.13` subdirs.
77
+ let candidates;
78
+ try {
79
+ candidates = readdirSync(nativeRoot).filter(
80
+ (name) =>
81
+ /^3\.\d+$/.test(name) &&
82
+ (() => {
83
+ try {
84
+ return statSync(join(nativeRoot, name)).isDirectory();
85
+ } catch {
86
+ return false;
87
+ }
88
+ })()
89
+ );
90
+ } catch {
91
+ return null;
92
+ }
93
+ if (candidates.length === 0) return null;
94
+ // Highest minor wins (e.g., 3.13 > 3.12 > 3.11).
95
+ candidates.sort((a, b) => {
96
+ const am = parseInt(a.split(".")[1], 10);
97
+ const bm = parseInt(b.split(".")[1], 10);
98
+ return bm - am;
99
+ });
100
+ return candidates[0];
101
+ }
102
+
103
+ const pyMinor = resolvePyMinor();
104
+ if (!pyMinor) {
105
+ printRecoveryAndExit(
106
+ `No installed CLI binary found under ${nativeRoot}. ` +
107
+ `The npm postinstall fetcher did not place a binary here.`
108
+ );
109
+ }
110
+
111
+ const binaryPath = join(nativeRoot, pyMinor, "sentisec");
112
+ if (!existsSync(binaryPath)) {
113
+ printRecoveryAndExit(
114
+ `Native CLI binary missing at ${binaryPath}. ` +
115
+ `The PYMINOR marker (${pyMinor}) points at a non-existent install.`
116
+ );
117
+ }
118
+
119
+ const child = spawn(binaryPath, process.argv.slice(2), { stdio: "inherit" });
120
+ child.on("error", (err) => {
121
+ process.stderr.write(`[sentisec] Failed to launch ${binaryPath}: ${err.message}\n`);
122
+ process.exit(1);
123
+ });
124
+ child.on("exit", (code, signal) => {
125
+ if (signal) {
126
+ // Mimic shell behavior: 128 + signal number is conventional.
127
+ // process.exit doesn't deliver the signal, just the conventional code.
128
+ process.exit(128);
129
+ }
130
+ process.exit(code ?? 1);
131
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentisec/sdk",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.1.0-rc.4",
4
4
  "description": "Sentisec TypeScript SDK — cognitive integrity monitoring for autonomous agents. Monitor + wrap(...) for OpenAI / Anthropic agent loops with SSE streaming support.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -33,8 +33,13 @@
33
33
  },
34
34
  "./package.json": "./package.json"
35
35
  },
36
+ "bin": {
37
+ "sentisec": "./bin/sentisec.js"
38
+ },
36
39
  "files": [
37
40
  "dist",
41
+ "bin",
42
+ "scripts/install-binary.js",
38
43
  "README.md",
39
44
  "CHANGELOG.md",
40
45
  "LICENSE"
@@ -49,6 +54,7 @@
49
54
  "test:watch": "vitest",
50
55
  "typecheck": "tsc --noEmit",
51
56
  "clean": "rimraf dist",
57
+ "postinstall": "node scripts/install-binary.js",
52
58
  "prepublishOnly": "pnpm build && pnpm typecheck"
53
59
  },
54
60
  "devDependencies": {
@@ -0,0 +1,484 @@
1
+ #!/usr/bin/env node
2
+ // @sentisec/sdk → scripts/install-binary.js
3
+ // npm postinstall fetcher for the Sentisec CLI native binary.
4
+ //
5
+ // Behavior contract (mission card P-INST-04):
6
+ // * Downloads the right tarball from GitHub Releases for the host
7
+ // (platform, arch, python-minor) triple.
8
+ // * Verifies sha256 against sha256sums.txt (mandatory).
9
+ // * Extracts to node_modules/@sentisec/sdk/native/<platform>/<arch>/<pyminor>/
10
+ // and writes a sibling PYMINOR marker file for bin/sentisec.js.
11
+ // * Zero external runtime deps. Uses node:https + node:crypto + spawned tar.
12
+ //
13
+ // Soft-fail policy (exit 0, npm install succeeds, library still usable):
14
+ // * SENTISEC_SKIP_POSTINSTALL truthy → dev override
15
+ // * CI && !SENTISEC_NPM_FETCH_IN_CI truthy → CI caches stay clean
16
+ // * unsupported platform / arch → leave SDK as library-only
17
+ // * python3 not on PATH → user can install python3 later
18
+ // * python minor not in {3.11, 3.12, 3.13, 3.14} → no binary for their python
19
+ // * network failure (DNS / timeout / 5xx) → try again next install
20
+ // * tuple missing from latest-versions.json → that cell didn't build
21
+ //
22
+ // Hard-fail policy (exit non-zero, npm install fails):
23
+ // * sha256 mismatch → tampered / corrupt artifact
24
+
25
+ import { spawnSync } from "node:child_process";
26
+ import { createHash } from "node:crypto";
27
+ import {
28
+ chmodSync,
29
+ createWriteStream,
30
+ existsSync,
31
+ mkdirSync,
32
+ readFileSync,
33
+ rmSync,
34
+ writeFileSync,
35
+ } from "node:fs";
36
+ import { tmpdir } from "node:os";
37
+ import { dirname, join } from "node:path";
38
+ import { pipeline } from "node:stream/promises";
39
+ import { fileURLToPath, URL } from "node:url";
40
+ import https from "node:https";
41
+
42
+ const __filename = fileURLToPath(import.meta.url);
43
+ const __dirname = dirname(__filename);
44
+
45
+ const LOG_PREFIX = "[sentisec]";
46
+ const log = (msg) => process.stdout.write(`${LOG_PREFIX} ${msg}\n`);
47
+ const warn = (msg) => process.stderr.write(`${LOG_PREFIX} ${msg}\n`);
48
+
49
+ const SUPPORTED_PLATFORMS = {
50
+ // node platform → mission platform name
51
+ darwin: "darwin",
52
+ linux: "linux",
53
+ };
54
+ const SUPPORTED_ARCHES = {
55
+ // node arch → mission arch name
56
+ arm64: "arm64",
57
+ x64: "x64",
58
+ };
59
+ const SUPPORTED_PY_MINORS = new Set(["3.11", "3.12", "3.13", "3.14"]);
60
+
61
+ // Public release mirror. Cloudflare R2 (sentisec-releases bucket, public,
62
+ // served by Pages at https://releases.sentisec.ch). The release-cli.yml
63
+ // workflow mirrors every cli-v* tarball + sha256sums.txt + latest-versions.json
64
+ // from GitHub Releases into s3://sentisec-releases/cli/<tag>/ so this URL
65
+ // stays in sync. Maintainers can override via SENTISEC_RELEASES_BASE for
66
+ // staging / a private mirror.
67
+ const RELEASES_BASE =
68
+ process.env.SENTISEC_RELEASES_BASE || "https://releases.sentisec.ch/cli";
69
+ const MANIFEST_URL = `${RELEASES_BASE}/latest/latest-versions.json`;
70
+
71
+ const SOFT_FAIL_RECOVERY = [
72
+ `${LOG_PREFIX} SDK library still works for programmatic use:`,
73
+ `${LOG_PREFIX} import { SentisecClient } from '@sentisec/sdk'`,
74
+ `${LOG_PREFIX}`,
75
+ `${LOG_PREFIX} To install the CLI another way:`,
76
+ `${LOG_PREFIX} curl -fsSL https://get.sentisec.ch | bash`,
77
+ `${LOG_PREFIX} pipx install sentisec-sdk`,
78
+ ].join("\n");
79
+
80
+ function softFail(reason) {
81
+ warn(reason);
82
+ process.stderr.write(SOFT_FAIL_RECOVERY + "\n");
83
+ process.exit(0);
84
+ }
85
+
86
+ function hardFail(reason) {
87
+ warn(`FATAL: ${reason}`);
88
+ process.exit(1);
89
+ }
90
+
91
+ function isTruthyEnv(name) {
92
+ const v = process.env[name];
93
+ if (!v) return false;
94
+ return !/^(0|false|no|off)$/i.test(v);
95
+ }
96
+
97
+ // --- guards --------------------------------------------------------------
98
+
99
+ if (isTruthyEnv("SENTISEC_SKIP_POSTINSTALL")) {
100
+ log("SENTISEC_SKIP_POSTINSTALL set — skipping CLI binary download.");
101
+ process.exit(0);
102
+ }
103
+
104
+ if (isTruthyEnv("CI") && !isTruthyEnv("SENTISEC_NPM_FETCH_IN_CI")) {
105
+ log(
106
+ "CI environment detected — skipping CLI binary download " +
107
+ "(set SENTISEC_NPM_FETCH_IN_CI=1 to opt in)."
108
+ );
109
+ process.exit(0);
110
+ }
111
+
112
+ const platformName = SUPPORTED_PLATFORMS[process.platform];
113
+ const archName = SUPPORTED_ARCHES[process.arch];
114
+ if (!platformName || !archName) {
115
+ softFail(
116
+ `Unsupported platform ${process.platform}-${process.arch} ` +
117
+ `(supported: darwin-arm64, darwin-x64, linux-x64, linux-arm64). ` +
118
+ `CLI not installed.`
119
+ );
120
+ }
121
+ const platformKey = `${platformName}-${archName}`;
122
+
123
+ // --- detect python3 ------------------------------------------------------
124
+
125
+ function detectPyMinor() {
126
+ const result = spawnSync(
127
+ "python3",
128
+ [
129
+ "-c",
130
+ "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')",
131
+ ],
132
+ { encoding: "utf8" }
133
+ );
134
+ if (result.error || result.status !== 0) return null;
135
+ return result.stdout.trim();
136
+ }
137
+
138
+ const pyMinor = detectPyMinor();
139
+ if (!pyMinor) {
140
+ softFail(
141
+ `python3 not found on PATH — the sentisec CLI binary requires ` +
142
+ `Python 3.11-3.14. Install python3 and re-run ` +
143
+ `'npm rebuild @sentisec/sdk' to get the CLI, OR use the SDK as a library only.`
144
+ );
145
+ }
146
+
147
+ if (!SUPPORTED_PY_MINORS.has(pyMinor)) {
148
+ softFail(
149
+ `Detected python3 ${pyMinor}; only 3.11 / 3.12 / 3.13 / 3.14 are supported. ` +
150
+ `CLI not installed. Install a supported python (e.g. 'brew install python@3.12') ` +
151
+ `and re-run 'npm rebuild @sentisec/sdk'.`
152
+ );
153
+ }
154
+
155
+ // --- resolve CLI release version -----------------------------------------
156
+ //
157
+ // The npm SDK version (e.g., 0.1.0-rc.2) and the CLI release version
158
+ // (e.g., v0.1.0a5) can diverge. Maintainers can pin via SENTISEC_CLI_VERSION_OVERRIDE
159
+ // (accepts either "v0.1.0a5" or "cli-v0.1.0a5"). Default: fetch
160
+ // latest-versions.json and use its `version` field.
161
+
162
+ function normalizeCliVersion(raw) {
163
+ // Returns { tag: "cli-vX", version: "vX" } where version starts with `v`.
164
+ let s = raw.trim();
165
+ if (s.startsWith("cli-v")) {
166
+ return { tag: s, version: s.slice("cli-".length) };
167
+ }
168
+ if (s.startsWith("v")) {
169
+ return { tag: `cli-${s}`, version: s };
170
+ }
171
+ // Bare semver-ish (e.g., "0.1.0a5")
172
+ return { tag: `cli-v${s}`, version: `v${s}` };
173
+ }
174
+
175
+ function fetchBuffer(url, redirectsLeft = 5) {
176
+ return new Promise((resolve, reject) => {
177
+ const u = new URL(url);
178
+ const req = https.get(
179
+ u,
180
+ {
181
+ headers: {
182
+ "user-agent": "sentisec-sdk-postinstall",
183
+ accept: "*/*",
184
+ },
185
+ timeout: 30_000,
186
+ },
187
+ (res) => {
188
+ const { statusCode = 0, headers } = res;
189
+ if (statusCode >= 300 && statusCode < 400 && headers.location) {
190
+ res.resume();
191
+ if (redirectsLeft <= 0) {
192
+ reject(new Error(`too many redirects fetching ${url}`));
193
+ return;
194
+ }
195
+ const next = new URL(headers.location, url).toString();
196
+ fetchBuffer(next, redirectsLeft - 1).then(resolve, reject);
197
+ return;
198
+ }
199
+ if (statusCode < 200 || statusCode >= 300) {
200
+ res.resume();
201
+ reject(new Error(`HTTP ${statusCode} fetching ${url}`));
202
+ return;
203
+ }
204
+ const chunks = [];
205
+ res.on("data", (c) => chunks.push(c));
206
+ res.on("end", () => resolve(Buffer.concat(chunks)));
207
+ res.on("error", reject);
208
+ }
209
+ );
210
+ req.on("timeout", () => {
211
+ req.destroy(new Error(`timeout fetching ${url}`));
212
+ });
213
+ req.on("error", reject);
214
+ });
215
+ }
216
+
217
+ async function fetchToFile(url, destPath, redirectsLeft = 5) {
218
+ // Streams to disk — avoids buffering ~30MB tarballs in RAM.
219
+ await new Promise((resolve, reject) => {
220
+ const u = new URL(url);
221
+ const req = https.get(
222
+ u,
223
+ {
224
+ headers: {
225
+ "user-agent": "sentisec-sdk-postinstall",
226
+ accept: "application/octet-stream, */*",
227
+ },
228
+ timeout: 120_000,
229
+ },
230
+ async (res) => {
231
+ const { statusCode = 0, headers } = res;
232
+ if (statusCode >= 300 && statusCode < 400 && headers.location) {
233
+ res.resume();
234
+ if (redirectsLeft <= 0) {
235
+ reject(new Error(`too many redirects fetching ${url}`));
236
+ return;
237
+ }
238
+ const next = new URL(headers.location, url).toString();
239
+ try {
240
+ await fetchToFile(next, destPath, redirectsLeft - 1);
241
+ resolve();
242
+ } catch (err) {
243
+ reject(err);
244
+ }
245
+ return;
246
+ }
247
+ if (statusCode < 200 || statusCode >= 300) {
248
+ res.resume();
249
+ reject(new Error(`HTTP ${statusCode} fetching ${url}`));
250
+ return;
251
+ }
252
+ try {
253
+ await pipeline(res, createWriteStream(destPath));
254
+ resolve();
255
+ } catch (err) {
256
+ reject(err);
257
+ }
258
+ }
259
+ );
260
+ req.on("timeout", () => {
261
+ req.destroy(new Error(`timeout fetching ${url}`));
262
+ });
263
+ req.on("error", reject);
264
+ });
265
+ }
266
+
267
+ function sha256OfFile(path) {
268
+ const buf = readFileSync(path);
269
+ return createHash("sha256").update(buf).digest("hex");
270
+ }
271
+
272
+ // --- resolve version + manifest -----------------------------------------
273
+
274
+ const override = process.env.SENTISEC_CLI_VERSION_OVERRIDE;
275
+ let resolved; // { tag, version, tarball }
276
+
277
+ async function loadManifest(tag) {
278
+ // If tag is provided (override), fetch the manifest for that specific tag.
279
+ // Otherwise fetch the `latest` alias.
280
+ const url = tag
281
+ ? `${RELEASES_BASE}/${tag}/latest-versions.json`
282
+ : MANIFEST_URL;
283
+ let raw;
284
+ try {
285
+ raw = await fetchBuffer(url);
286
+ } catch (err) {
287
+ throw new Error(`could not fetch manifest at ${url}: ${err.message}`);
288
+ }
289
+ let parsed;
290
+ try {
291
+ parsed = JSON.parse(raw.toString("utf8"));
292
+ } catch (err) {
293
+ throw new Error(`manifest at ${url} is not valid JSON: ${err.message}`);
294
+ }
295
+ if (!parsed || typeof parsed !== "object" || !parsed.version || !parsed.platforms) {
296
+ throw new Error(`manifest at ${url} missing required fields`);
297
+ }
298
+ return parsed;
299
+ }
300
+
301
+ async function resolveTarballName() {
302
+ if (override) {
303
+ const { tag, version } = normalizeCliVersion(override);
304
+ log(`Using SENTISEC_CLI_VERSION_OVERRIDE=${override} → tag ${tag}`);
305
+ let manifest;
306
+ try {
307
+ manifest = await loadManifest(tag);
308
+ } catch (err) {
309
+ softFail(
310
+ `Pinned CLI version ${tag} could not be resolved: ${err.message}. ` +
311
+ `CLI not installed.`
312
+ );
313
+ }
314
+ const tarball = manifest?.platforms?.[platformKey]?.[pyMinor];
315
+ if (!tarball) {
316
+ const available = Object.keys(manifest?.platforms?.[platformKey] ?? {});
317
+ softFail(
318
+ `No binary for ${platformKey} + py${pyMinor} in release ${tag}. ` +
319
+ `Available py-minors for ${platformKey}: ${
320
+ available.length ? available.join(", ") : "(none)"
321
+ }. CLI not installed.`
322
+ );
323
+ }
324
+ return { tag, version, tarball };
325
+ }
326
+
327
+ let manifest;
328
+ try {
329
+ manifest = await loadManifest(null);
330
+ } catch (err) {
331
+ softFail(
332
+ `Could not fetch latest CLI manifest: ${err.message}. CLI not installed.`
333
+ );
334
+ }
335
+ const { tag, version } = normalizeCliVersion(manifest.version);
336
+ const tarball = manifest?.platforms?.[platformKey]?.[pyMinor];
337
+ if (!tarball) {
338
+ const available = Object.keys(manifest?.platforms?.[platformKey] ?? {});
339
+ softFail(
340
+ `No binary for ${platformKey} + py${pyMinor} in latest release ` +
341
+ `(${manifest.version}). Available py-minors for ${platformKey}: ${
342
+ available.length ? available.join(", ") : "(none)"
343
+ }. CLI not installed.`
344
+ );
345
+ }
346
+ return { tag, version, tarball };
347
+ }
348
+
349
+ try {
350
+ resolved = await resolveTarballName();
351
+ } catch (err) {
352
+ // Belt-and-suspenders — resolveTarballName already soft-fails on the
353
+ // expected paths, but a thrown error here should still soft-fail rather
354
+ // than fail npm install.
355
+ softFail(`Unexpected error resolving CLI version: ${err.message}`);
356
+ }
357
+
358
+ const { tag, version, tarball } = resolved;
359
+ const tarballUrl = `${RELEASES_BASE}/${tag}/${tarball}`;
360
+ const sumsUrl = `${RELEASES_BASE}/${tag}/sha256sums.txt`;
361
+
362
+ log(
363
+ `Resolving CLI ${version} for ${platformKey} (py${pyMinor}) → ${tarball}`
364
+ );
365
+
366
+ // --- download to tempdir ------------------------------------------------
367
+
368
+ const stagingRoot = join(tmpdir(), `sentisec-sdk-postinstall-${process.pid}`);
369
+ mkdirSync(stagingRoot, { recursive: true });
370
+ const tarballPath = join(stagingRoot, tarball);
371
+ const sumsPath = join(stagingRoot, "sha256sums.txt");
372
+
373
+ function cleanupStaging() {
374
+ try {
375
+ rmSync(stagingRoot, { recursive: true, force: true });
376
+ } catch {
377
+ // best-effort
378
+ }
379
+ }
380
+
381
+ try {
382
+ await fetchToFile(tarballUrl, tarballPath);
383
+ } catch (err) {
384
+ cleanupStaging();
385
+ softFail(
386
+ `Failed to download ${tarball}: ${err.message}. CLI not installed.`
387
+ );
388
+ }
389
+
390
+ let sumsRaw;
391
+ try {
392
+ sumsRaw = (await fetchBuffer(sumsUrl)).toString("utf8");
393
+ } catch (err) {
394
+ cleanupStaging();
395
+ softFail(`Failed to download sha256sums.txt: ${err.message}. CLI not installed.`);
396
+ }
397
+ writeFileSync(sumsPath, sumsRaw);
398
+
399
+ // --- verify sha256 (HARD FAIL on mismatch) ------------------------------
400
+
401
+ function findExpectedSha(sumsText, filename) {
402
+ // Format: "<sha> <filename>" (two spaces is canonical; allow one or more).
403
+ for (const line of sumsText.split(/\r?\n/)) {
404
+ const trimmed = line.trim();
405
+ if (!trimmed || trimmed.startsWith("#")) continue;
406
+ const match = trimmed.match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
407
+ if (!match) continue;
408
+ if (match[2].trim() === filename) return match[1].toLowerCase();
409
+ }
410
+ return null;
411
+ }
412
+
413
+ const expectedSha = findExpectedSha(sumsRaw, tarball);
414
+ if (!expectedSha) {
415
+ cleanupStaging();
416
+ softFail(
417
+ `sha256sums.txt did not contain an entry for ${tarball}. ` +
418
+ `CLI not installed (cannot verify integrity).`
419
+ );
420
+ }
421
+
422
+ const actualSha = sha256OfFile(tarballPath).toLowerCase();
423
+ if (actualSha !== expectedSha) {
424
+ cleanupStaging();
425
+ hardFail(
426
+ `sha256 mismatch for ${tarball}\n` +
427
+ ` expected: ${expectedSha}\n` +
428
+ ` actual: ${actualSha}\n` +
429
+ `Refusing to install a tampered or corrupt artifact.`
430
+ );
431
+ }
432
+ log(`sha256 verified: ${actualSha.slice(0, 16)}…`);
433
+
434
+ // --- extract via system `tar` (zero npm dep) ----------------------------
435
+
436
+ const installRoot = join(__dirname, "..", "native", platformName, archName);
437
+ const installDir = join(installRoot, pyMinor);
438
+ mkdirSync(installDir, { recursive: true });
439
+
440
+ const extract = spawnSync("tar", ["-xzf", tarballPath, "-C", installDir], {
441
+ stdio: "inherit",
442
+ });
443
+ if (extract.error) {
444
+ cleanupStaging();
445
+ softFail(
446
+ `Failed to run system tar (${extract.error.message}). CLI not installed.`
447
+ );
448
+ }
449
+ if (extract.status !== 0) {
450
+ cleanupStaging();
451
+ softFail(
452
+ `tar exited with status ${extract.status}. CLI not installed.`
453
+ );
454
+ }
455
+
456
+ const binaryPath = join(installDir, "sentisec");
457
+ if (!existsSync(binaryPath)) {
458
+ cleanupStaging();
459
+ softFail(
460
+ `Extracted tarball did not contain expected 'sentisec' binary at ${binaryPath}. ` +
461
+ `CLI not installed.`
462
+ );
463
+ }
464
+
465
+ try {
466
+ chmodSync(binaryPath, 0o755);
467
+ } catch (err) {
468
+ cleanupStaging();
469
+ softFail(`Failed to chmod ${binaryPath}: ${err.message}. CLI not installed.`);
470
+ }
471
+
472
+ // Write PYMINOR marker for the bin shim to read.
473
+ try {
474
+ writeFileSync(join(installRoot, "PYMINOR"), `${pyMinor}\n`, "utf8");
475
+ } catch (err) {
476
+ cleanupStaging();
477
+ softFail(`Failed to write PYMINOR marker: ${err.message}. CLI not installed.`);
478
+ }
479
+
480
+ cleanupStaging();
481
+ log(
482
+ `CLI binary installed: native/${platformName}/${archName}/${pyMinor}/sentisec (py${pyMinor})`
483
+ );
484
+ process.exit(0);