@sentisec/sdk 0.1.0-rc.2 → 0.1.0-rc.5

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,96 @@ Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ---
8
8
 
9
+ ## [Unreleased]
10
+
11
+ Closes the endpoint trap S1-FU-05 found on the Python side. A reader
12
+ running a local or self-hosted control plane had no way to say so:
13
+ `new Monitor({...})` always resolved to `https://api.sentisec.ch`, and
14
+ `wrap()` rewrote the client's `baseURL` unconditionally — so their
15
+ prompts left the machine. Python already had `Monitor(endpoint=...)`;
16
+ this brings the TypeScript SDK to parity.
17
+
18
+ ### Added
19
+
20
+ - `MonitorConfig.endpoint` — the control-plane HOST (e.g.
21
+ `http://localhost:8080`); `wrap()` appends `/ws/<workspace>/v1`.
22
+ Same field and semantics as the Python SDK's `Monitor(endpoint=...)`.
23
+ - `SENTISEC_ENDPOINT` env var support, matching the Python SDK.
24
+ - Exported `DEFAULT_ENDPOINT`, `ENV_ENDPOINT`, `WORKSPACE_PROXY_PATH`,
25
+ and `resolveProxyBaseUrl`.
26
+ - A one-line stderr warning when `wrap()` discards a base URL the caller
27
+ had deliberately set (anything that is not a stock provider URL), so a
28
+ client already pointed at Azure or a local vLLM is not silently
29
+ redirected. Naming the remedy in the message beats leaving it to be
30
+ found in a network trace.
31
+ - `tests/endpoint_resolution.test.ts` — 13 cases covering the
32
+ precedence chain, both vendors, and the warning's quiet cases.
33
+
34
+ ### Changed
35
+
36
+ - `resolveProxyBaseUrl(workspace, opts?, endpoint?)` takes a third
37
+ argument. Precedence is `opts.baseUrl` -> `endpoint` -> env -> hosted
38
+ default; the first two steps are unchanged for existing callers.
39
+ - README: the two non-streaming quickstarts pass `endpoint` explicitly,
40
+ with a warning that an unset endpoint means production and a note that
41
+ `wrap()` replaces the client's `baseURL`.
42
+
43
+ Behaviour with no endpoint set anywhere is deliberately unchanged — it
44
+ still resolves to the hosted plane. The fix is that an override now
45
+ exists and the docs stop implying one is unnecessary.
46
+
47
+ ---
48
+
49
+ ## [0.1.0-rc.4] — 2026-05-17
50
+
51
+ Routes the CLI binary fetch through the public Cloudflare R2 mirror
52
+ at `https://releases.sentisec.ch/cli/` instead of the GitHub Releases
53
+ URL directly. Keeps the public-facing scripts free of internal repo
54
+ URLs (per `.claude/rules/02-opacity.md`).
55
+
56
+ ### Changed
57
+
58
+ - `scripts/install-binary.js` — `RELEASES_BASE` defaults to
59
+ `https://releases.sentisec.ch/cli`; `SENTISEC_RELEASES_BASE` env
60
+ var overrides. Manifest + tarball URL layout flattened to
61
+ `/<tag>/<file>` to match the R2 bucket key prefix scheme.
62
+
63
+ The CLI tarballs themselves are unchanged — the release-cli.yml
64
+ workflow mirrors every cli-v* artifact from GitHub Releases into R2
65
+ so this URL stays in sync.
66
+
67
+ ---
68
+
69
+ ## [0.1.0-rc.3] — 2026-05-17
70
+
71
+ Adds the CLI bin wrapper + zero-dep postinstall fetcher (P-INST-04).
72
+
73
+ ### Added
74
+
75
+ - **`bin/sentisec.js`** — ESM shim that execs the platform-native
76
+ CLI binary. Resolves the binary via a `PYMINOR` marker file under
77
+ `node_modules/@sentisec/sdk/native/<platform>/<arch>/`. Prints
78
+ curl / pipx recovery hints when the binary is absent.
79
+ - **`scripts/install-binary.js`** — postinstall fetcher (zero deps,
80
+ uses `node:https` + `node:crypto` + system `tar`). Downloads the
81
+ matching `sentisec-cli-vX-<platform>-py<minor>.tar.gz` from GitHub
82
+ Releases, verifies sha256, extracts under
83
+ `node_modules/@sentisec/sdk/native/`. Soft-fails on every
84
+ non-security error (CI guard, no python3, unsupported python-minor,
85
+ manifest 404, network failure, tuple missing) so the SDK remains
86
+ installable as a JS library; only sha256 mismatch hard-fails.
87
+ - **`"bin": { "sentisec": "./bin/sentisec.js" }`** in package.json
88
+ so `npm install -g @sentisec/sdk` puts `sentisec` on PATH.
89
+ - Env overrides: `SENTISEC_SKIP_POSTINSTALL`,
90
+ `SENTISEC_NPM_FETCH_IN_CI`, `SENTISEC_CLI_VERSION_OVERRIDE`.
91
+
92
+ ### Supports
93
+
94
+ - Python 3.11, 3.12, 3.13, 3.14 on darwin-arm64 / darwin-x64 /
95
+ linux-x64 / linux-arm64.
96
+
97
+ ---
98
+
9
99
  ## [0.1.0] — 2026-04-22
10
100
 
11
101
  First public release of `@sentisec/sdk`. Ships the full Phase-1.5 TS SDK:
package/README.md CHANGED
@@ -22,6 +22,40 @@ Requires Node 20+.
22
22
 
23
23
  ---
24
24
 
25
+ ## Choose your control plane first
26
+
27
+ > **Warning — an unset endpoint means production.**
28
+ > `new Monitor({ ... })` with no `endpoint` sends every wrapped request
29
+ > to the hosted plane at `https://api.sentisec.ch`. If you are running
30
+ > Sentisec locally or self-hosted and you skip this, your prompts leave
31
+ > your machine. Set it explicitly; the SDK cannot infer your intent.
32
+
33
+ Resolution order, highest first:
34
+
35
+ 1. `wrap(client, { baseUrl })` — a literal, fully-formed URL for one
36
+ wrap call. Nothing is appended to it.
37
+ 2. `new Monitor({ endpoint })` — a control-plane **host**; the SDK
38
+ appends `/ws/<workspace>/v1`.
39
+ 3. `SENTISEC_ENDPOINT` — same host semantics, from the environment.
40
+ 4. the hosted default, `https://api.sentisec.ch`.
41
+
42
+ ```bash
43
+ # Local or self-hosted: set this once and both SDKs obey it.
44
+ export SENTISEC_ENDPOINT=http://localhost:8080
45
+ ```
46
+
47
+ Identical field, identical precedence, identical failure mode as the
48
+ Python SDK's `Monitor(endpoint=...)`.
49
+
50
+ **`wrap()` replaces your client's `baseURL`.** That is what the wrapper
51
+ is for — traffic has to go through Sentisec to be gated. But if your
52
+ client already pointed at Azure, a local vLLM, or another gateway, that
53
+ destination is discarded, and the SDK prints a one-line warning naming
54
+ the remedy. Route the upstream through Sentisec rather than setting it
55
+ on the client.
56
+
57
+ ---
58
+
25
59
  ## Quick start — OpenAI (non-streaming)
26
60
 
27
61
  ```ts
@@ -35,6 +69,9 @@ const monitor = new Monitor({
35
69
  policy: "research_agent",
36
70
  responsePolicy: "gated",
37
71
  customerId: "ws_acme",
72
+ // Explicit on purpose — omit it and this snippet targets the hosted
73
+ // plane. Point it at your own control plane when self-hosting.
74
+ endpoint: process.env.SENTISEC_ENDPOINT ?? "https://api.sentisec.ch",
38
75
  });
39
76
 
40
77
  // Wraps the OpenAI client in place — type is preserved.
@@ -71,6 +108,7 @@ const monitor = new Monitor({
71
108
  task: "answer customer support tickets",
72
109
  policy: "customer_support",
73
110
  customerId: "ws_support",
111
+ endpoint: process.env.SENTISEC_ENDPOINT ?? "https://api.sentisec.ch",
74
112
  });
75
113
 
76
114
  const anthropic = monitor.wrap(new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }));
@@ -228,7 +266,7 @@ pinned at `sdk_error_surface_version: v1.0-phase1`.
228
266
  ```bash
229
267
  pnpm install # from repo root
230
268
  pnpm --filter @sentisec/sdk build # tsup → dist/
231
- pnpm --filter @sentisec/sdk test # vitest (23 tests)
269
+ pnpm --filter @sentisec/sdk test # vitest (36 tests)
232
270
  pnpm --filter @sentisec/sdk typecheck
233
271
  ```
234
272
 
@@ -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/dist/index.cjs CHANGED
@@ -17,9 +17,44 @@ var SentisecHijackError = class extends Error {
17
17
  };
18
18
 
19
19
  // src/openai.ts
20
+ var ENV_ENDPOINT = "SENTISEC_ENDPOINT";
21
+ var DEFAULT_ENDPOINT = "https://api.sentisec.ch";
22
+ var WORKSPACE_PROXY_PATH = "/ws/{workspace}/v1";
23
+ function endpointFromEnv() {
24
+ const env = globalThis.process?.env;
25
+ const raw = env?.[ENV_ENDPOINT];
26
+ return raw !== void 0 && raw.trim() !== "" ? raw.trim() : void 0;
27
+ }
28
+ function composeWorkspaceUrl(endpoint, workspace) {
29
+ return endpoint.replace(/\/+$/, "") + WORKSPACE_PROXY_PATH.replace("{workspace}", workspace);
30
+ }
31
+ var VENDOR_DEFAULT_BASE_URLS = /* @__PURE__ */ new Set([
32
+ "https://api.openai.com/v1",
33
+ "https://api.openai.com",
34
+ "https://api.anthropic.com/v1",
35
+ "https://api.anthropic.com"
36
+ ]);
37
+ function canonicalUrl(url) {
38
+ return url.trim().replace(/\/+$/, "");
39
+ }
40
+ function warnIfDiscardingExplicitBaseUrl(previous, next) {
41
+ if (typeof previous !== "string") return;
42
+ const before = canonicalUrl(previous);
43
+ if (before === "") return;
44
+ if (before === canonicalUrl(next)) return;
45
+ if (VENDOR_DEFAULT_BASE_URLS.has(before)) return;
46
+ console.warn(
47
+ `[sentisec] wrap() replaced the client's baseURL ${before} with ${next}. If that was deliberate, pass it through Sentisec instead \u2014 new Monitor({ endpoint }) for a Sentisec control plane on another host, or wrap(client, { baseUrl }) to target one wrap at a literal URL.`
48
+ );
49
+ }
20
50
  var DEFAULT_INGRESS_TEMPLATE = "https://api.sentisec.ch/ws/{workspace}/v1";
21
- function resolveProxyBaseUrl(workspace, opts) {
51
+ function resolveProxyBaseUrl(workspace, opts, endpoint) {
22
52
  if (opts?.baseUrl !== void 0) return opts.baseUrl;
53
+ if (endpoint !== void 0 && endpoint.trim() !== "") {
54
+ return composeWorkspaceUrl(endpoint.trim(), workspace);
55
+ }
56
+ const fromEnv = endpointFromEnv();
57
+ if (fromEnv !== void 0) return composeWorkspaceUrl(fromEnv, workspace);
23
58
  return DEFAULT_INGRESS_TEMPLATE.replace("{workspace}", workspace);
24
59
  }
25
60
 
@@ -45,7 +80,8 @@ function wrapOpenAI(client, ctx, opts) {
45
80
  "wrap-openai: client failed isOpenAILike() but the OpenAI adapter was selected \u2014 vendor-registry mismatch."
46
81
  );
47
82
  }
48
- const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts);
83
+ const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
84
+ warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
49
85
  client.baseURL = proxyBaseUrl;
50
86
  client.defaultHeaders = {
51
87
  ...client.defaultHeaders,
@@ -190,7 +226,8 @@ function wrapAnthropic(client, ctx, opts) {
190
226
  "wrap-anthropic: client failed isAnthropicLike() but the Anthropic adapter was selected \u2014 vendor-registry mismatch."
191
227
  );
192
228
  }
193
- const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts);
229
+ const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
230
+ warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
194
231
  client.baseURL = proxyBaseUrl;
195
232
  client.defaultHeaders = {
196
233
  ...client.defaultHeaders,
@@ -253,7 +290,8 @@ function installWrap(MonitorCtor) {
253
290
  apiKey: this.apiKey,
254
291
  model: this.model,
255
292
  task: this.task,
256
- policy: this.policy
293
+ policy: this.policy,
294
+ endpoint: this.endpoint
257
295
  };
258
296
  for (const entry of registry) {
259
297
  if (entry.detect(client)) {
@@ -706,6 +744,7 @@ var Monitor = class {
706
744
  policy;
707
745
  responsePolicy;
708
746
  customerId;
747
+ endpoint;
709
748
  constructor(config) {
710
749
  this.apiKey = config.apiKey;
711
750
  this.model = config.model;
@@ -713,6 +752,7 @@ var Monitor = class {
713
752
  this.policy = config.policy ?? "research_agent";
714
753
  this.responsePolicy = config.responsePolicy ?? "gated";
715
754
  this.customerId = config.customerId ?? "cust_local";
755
+ this.endpoint = config.endpoint;
716
756
  this.validatePolicy();
717
757
  }
718
758
  validatePolicy() {
@@ -743,7 +783,9 @@ Object.setPrototypeOf(SentisecAnthropicBlockError.prototype, SentisecError.proto
743
783
  installWrap(Monitor);
744
784
 
745
785
  exports.BUILTIN_POLICIES = BUILTIN_POLICIES;
786
+ exports.DEFAULT_ENDPOINT = DEFAULT_ENDPOINT;
746
787
  exports.DEFAULT_INGRESS_TEMPLATE = DEFAULT_INGRESS_TEMPLATE;
788
+ exports.ENV_ENDPOINT = ENV_ENDPOINT;
747
789
  exports.Monitor = Monitor;
748
790
  exports.SentisecAnthropicBlockError = SentisecAnthropicBlockError;
749
791
  exports.SentisecError = SentisecError;
@@ -752,6 +794,8 @@ exports.Session = Session;
752
794
  exports.TaskTamperError = TaskTamperError;
753
795
  exports.UnknownPolicyError = UnknownPolicyError;
754
796
  exports.VerifierBackendNotConfigured = VerifierBackendNotConfigured;
797
+ exports.WORKSPACE_PROXY_PATH = WORKSPACE_PROXY_PATH;
755
798
  exports.default = src_default;
799
+ exports.resolveProxyBaseUrl = resolveProxyBaseUrl;
756
800
  exports.wrapAnthropicStream = wrapAnthropicStream;
757
801
  exports.wrapOpenAIStream = wrapOpenAIStream;
package/dist/index.d.cts CHANGED
@@ -61,6 +61,22 @@ interface OpenAILike {
61
61
  interface WrapOptions {
62
62
  baseUrl?: string;
63
63
  }
64
+ /**
65
+ * Environment variable naming the Sentisec control-plane host. Parity
66
+ * with the Python SDK's `SENTISEC_ENDPOINT` (`credentials.py`), so a
67
+ * self-hosted operator sets one variable and both SDKs obey it.
68
+ */
69
+ declare const ENV_ENDPOINT = "SENTISEC_ENDPOINT";
70
+ /**
71
+ * Hosted control-plane host, used when nothing overrides it. Parity
72
+ * with the Python SDK's `DEFAULT_ENDPOINT`.
73
+ */
74
+ declare const DEFAULT_ENDPOINT = "https://api.sentisec.ch";
75
+ /**
76
+ * Workspace-scoped proxy path appended to an endpoint host. The hosted
77
+ * default below is this path joined onto `DEFAULT_ENDPOINT`.
78
+ */
79
+ declare const WORKSPACE_PROXY_PATH = "/ws/{workspace}/v1";
64
80
  /**
65
81
  * The Sentisec hosted-ingress base URL template. The `{workspace}`
66
82
  * placeholder is substituted with `Monitor.customerId` at wrap
@@ -73,6 +89,30 @@ interface WrapOptions {
73
89
  * `test_wrap_rewrites_base_url` grep-guards the literal.
74
90
  */
75
91
  declare const DEFAULT_INGRESS_TEMPLATE = "https://api.sentisec.ch/ws/{workspace}/v1";
92
+ /**
93
+ * Resolve the proxy base URL for a given workspace.
94
+ *
95
+ * Precedence, highest first — mirroring the Python SDK's
96
+ * arg -> env -> default chain (`resolve_credentials`):
97
+ *
98
+ * 1. `opts.baseUrl` — a literal, fully-formed URL for this one
99
+ * wrap call. No path is appended.
100
+ * 2. `endpoint` — `new Monitor({ endpoint })`, a HOST
101
+ * (e.g. `http://localhost:8080`); the
102
+ * workspace path is appended to it.
103
+ * 3. `SENTISEC_ENDPOINT` — same host semantics, from the environment.
104
+ * 4. the hosted default — `https://api.sentisec.ch/ws/<ws>/v1`.
105
+ *
106
+ * Step 4 is the trap S1-FU-05 caught on the Python side: a reader
107
+ * running a local control plane who never set a destination had their
108
+ * prompts silently routed to production. The SDK cannot detect that
109
+ * intent, so the fix is to make steps 2 and 3 exist and to say so
110
+ * loudly in the docs — not to guess.
111
+ *
112
+ * Pure function so it can be unit-tested without constructing a
113
+ * `Monitor`.
114
+ */
115
+ declare function resolveProxyBaseUrl(workspace: string, opts?: WrapOptions, endpoint?: string): string;
76
116
 
77
117
  /**
78
118
  * @sentisec/sdk · monitor.ts — Monitor.wrap dispatcher (T-151).
@@ -582,6 +622,18 @@ interface MonitorConfig {
582
622
  policy?: string;
583
623
  responsePolicy?: ResponsePolicy;
584
624
  customerId?: string;
625
+ /**
626
+ * Sentisec control-plane HOST (e.g. `http://localhost:8080`), not a
627
+ * full URL — `wrap()` appends the workspace-scoped path.
628
+ *
629
+ * Set this whenever you are not talking to the hosted plane. Leaving
630
+ * it unset falls back to `SENTISEC_ENDPOINT` and then to
631
+ * `https://api.sentisec.ch`, which means a local or self-hosted
632
+ * deployment that forgets it ships its prompts to production. Same
633
+ * field, same precedence, same failure mode as the Python SDK's
634
+ * `Monitor(endpoint=...)`.
635
+ */
636
+ endpoint?: string;
585
637
  }
586
638
  /**
587
639
  * A monitored session handle. T-150 pins the shape; the wave-2 cards
@@ -638,6 +690,7 @@ declare class Monitor {
638
690
  readonly policy: string;
639
691
  readonly responsePolicy: ResponsePolicy;
640
692
  readonly customerId: string;
693
+ readonly endpoint: string | undefined;
641
694
  constructor(config: MonitorConfig);
642
695
  private validatePolicy;
643
696
  /**
@@ -651,4 +704,4 @@ declare class Monitor {
651
704
  session(): Session;
652
705
  }
653
706
 
654
- export { type AnthropicContentBlock, type AnthropicInputMessage, type AnthropicLike, type AnthropicMessageCreateParams, type AnthropicMessageResponse, type AnthropicStreamEvent, type AnthropicStreamingLike, type AnthropicTextBlock, type AnthropicToolUseBlock, BUILTIN_POLICIES, type BuiltinPolicy, DEFAULT_INGRESS_TEMPLATE, Monitor, type MonitorConfig, type OpenAILike, type OpenAIStreamChunk, type OpenAIStreamingLike, type ResponsePolicy, SentisecAnthropicBlockError, SentisecError, type SentisecHaltEnvelope, SentisecHijackError, Session, type SessionStatus, type StreamCloseReason, type StreamOptions, TaskTamperError, UnknownPolicyError, type Verdict, type VerdictValue, VerifierBackendNotConfigured, type WrapOptions, Monitor as default, wrapAnthropicStream, wrapOpenAIStream };
707
+ export { type AnthropicContentBlock, type AnthropicInputMessage, type AnthropicLike, type AnthropicMessageCreateParams, type AnthropicMessageResponse, type AnthropicStreamEvent, type AnthropicStreamingLike, type AnthropicTextBlock, type AnthropicToolUseBlock, BUILTIN_POLICIES, type BuiltinPolicy, DEFAULT_ENDPOINT, DEFAULT_INGRESS_TEMPLATE, ENV_ENDPOINT, Monitor, type MonitorConfig, type OpenAILike, type OpenAIStreamChunk, type OpenAIStreamingLike, type ResponsePolicy, SentisecAnthropicBlockError, SentisecError, type SentisecHaltEnvelope, SentisecHijackError, Session, type SessionStatus, type StreamCloseReason, type StreamOptions, TaskTamperError, UnknownPolicyError, type Verdict, type VerdictValue, VerifierBackendNotConfigured, WORKSPACE_PROXY_PATH, type WrapOptions, Monitor as default, resolveProxyBaseUrl, wrapAnthropicStream, wrapOpenAIStream };
package/dist/index.d.ts CHANGED
@@ -61,6 +61,22 @@ interface OpenAILike {
61
61
  interface WrapOptions {
62
62
  baseUrl?: string;
63
63
  }
64
+ /**
65
+ * Environment variable naming the Sentisec control-plane host. Parity
66
+ * with the Python SDK's `SENTISEC_ENDPOINT` (`credentials.py`), so a
67
+ * self-hosted operator sets one variable and both SDKs obey it.
68
+ */
69
+ declare const ENV_ENDPOINT = "SENTISEC_ENDPOINT";
70
+ /**
71
+ * Hosted control-plane host, used when nothing overrides it. Parity
72
+ * with the Python SDK's `DEFAULT_ENDPOINT`.
73
+ */
74
+ declare const DEFAULT_ENDPOINT = "https://api.sentisec.ch";
75
+ /**
76
+ * Workspace-scoped proxy path appended to an endpoint host. The hosted
77
+ * default below is this path joined onto `DEFAULT_ENDPOINT`.
78
+ */
79
+ declare const WORKSPACE_PROXY_PATH = "/ws/{workspace}/v1";
64
80
  /**
65
81
  * The Sentisec hosted-ingress base URL template. The `{workspace}`
66
82
  * placeholder is substituted with `Monitor.customerId` at wrap
@@ -73,6 +89,30 @@ interface WrapOptions {
73
89
  * `test_wrap_rewrites_base_url` grep-guards the literal.
74
90
  */
75
91
  declare const DEFAULT_INGRESS_TEMPLATE = "https://api.sentisec.ch/ws/{workspace}/v1";
92
+ /**
93
+ * Resolve the proxy base URL for a given workspace.
94
+ *
95
+ * Precedence, highest first — mirroring the Python SDK's
96
+ * arg -> env -> default chain (`resolve_credentials`):
97
+ *
98
+ * 1. `opts.baseUrl` — a literal, fully-formed URL for this one
99
+ * wrap call. No path is appended.
100
+ * 2. `endpoint` — `new Monitor({ endpoint })`, a HOST
101
+ * (e.g. `http://localhost:8080`); the
102
+ * workspace path is appended to it.
103
+ * 3. `SENTISEC_ENDPOINT` — same host semantics, from the environment.
104
+ * 4. the hosted default — `https://api.sentisec.ch/ws/<ws>/v1`.
105
+ *
106
+ * Step 4 is the trap S1-FU-05 caught on the Python side: a reader
107
+ * running a local control plane who never set a destination had their
108
+ * prompts silently routed to production. The SDK cannot detect that
109
+ * intent, so the fix is to make steps 2 and 3 exist and to say so
110
+ * loudly in the docs — not to guess.
111
+ *
112
+ * Pure function so it can be unit-tested without constructing a
113
+ * `Monitor`.
114
+ */
115
+ declare function resolveProxyBaseUrl(workspace: string, opts?: WrapOptions, endpoint?: string): string;
76
116
 
77
117
  /**
78
118
  * @sentisec/sdk · monitor.ts — Monitor.wrap dispatcher (T-151).
@@ -582,6 +622,18 @@ interface MonitorConfig {
582
622
  policy?: string;
583
623
  responsePolicy?: ResponsePolicy;
584
624
  customerId?: string;
625
+ /**
626
+ * Sentisec control-plane HOST (e.g. `http://localhost:8080`), not a
627
+ * full URL — `wrap()` appends the workspace-scoped path.
628
+ *
629
+ * Set this whenever you are not talking to the hosted plane. Leaving
630
+ * it unset falls back to `SENTISEC_ENDPOINT` and then to
631
+ * `https://api.sentisec.ch`, which means a local or self-hosted
632
+ * deployment that forgets it ships its prompts to production. Same
633
+ * field, same precedence, same failure mode as the Python SDK's
634
+ * `Monitor(endpoint=...)`.
635
+ */
636
+ endpoint?: string;
585
637
  }
586
638
  /**
587
639
  * A monitored session handle. T-150 pins the shape; the wave-2 cards
@@ -638,6 +690,7 @@ declare class Monitor {
638
690
  readonly policy: string;
639
691
  readonly responsePolicy: ResponsePolicy;
640
692
  readonly customerId: string;
693
+ readonly endpoint: string | undefined;
641
694
  constructor(config: MonitorConfig);
642
695
  private validatePolicy;
643
696
  /**
@@ -651,4 +704,4 @@ declare class Monitor {
651
704
  session(): Session;
652
705
  }
653
706
 
654
- export { type AnthropicContentBlock, type AnthropicInputMessage, type AnthropicLike, type AnthropicMessageCreateParams, type AnthropicMessageResponse, type AnthropicStreamEvent, type AnthropicStreamingLike, type AnthropicTextBlock, type AnthropicToolUseBlock, BUILTIN_POLICIES, type BuiltinPolicy, DEFAULT_INGRESS_TEMPLATE, Monitor, type MonitorConfig, type OpenAILike, type OpenAIStreamChunk, type OpenAIStreamingLike, type ResponsePolicy, SentisecAnthropicBlockError, SentisecError, type SentisecHaltEnvelope, SentisecHijackError, Session, type SessionStatus, type StreamCloseReason, type StreamOptions, TaskTamperError, UnknownPolicyError, type Verdict, type VerdictValue, VerifierBackendNotConfigured, type WrapOptions, Monitor as default, wrapAnthropicStream, wrapOpenAIStream };
707
+ export { type AnthropicContentBlock, type AnthropicInputMessage, type AnthropicLike, type AnthropicMessageCreateParams, type AnthropicMessageResponse, type AnthropicStreamEvent, type AnthropicStreamingLike, type AnthropicTextBlock, type AnthropicToolUseBlock, BUILTIN_POLICIES, type BuiltinPolicy, DEFAULT_ENDPOINT, DEFAULT_INGRESS_TEMPLATE, ENV_ENDPOINT, Monitor, type MonitorConfig, type OpenAILike, type OpenAIStreamChunk, type OpenAIStreamingLike, type ResponsePolicy, SentisecAnthropicBlockError, SentisecError, type SentisecHaltEnvelope, SentisecHijackError, Session, type SessionStatus, type StreamCloseReason, type StreamOptions, TaskTamperError, UnknownPolicyError, type Verdict, type VerdictValue, VerifierBackendNotConfigured, WORKSPACE_PROXY_PATH, type WrapOptions, Monitor as default, resolveProxyBaseUrl, wrapAnthropicStream, wrapOpenAIStream };
package/dist/index.js CHANGED
@@ -13,9 +13,44 @@ var SentisecHijackError = class extends Error {
13
13
  };
14
14
 
15
15
  // src/openai.ts
16
+ var ENV_ENDPOINT = "SENTISEC_ENDPOINT";
17
+ var DEFAULT_ENDPOINT = "https://api.sentisec.ch";
18
+ var WORKSPACE_PROXY_PATH = "/ws/{workspace}/v1";
19
+ function endpointFromEnv() {
20
+ const env = globalThis.process?.env;
21
+ const raw = env?.[ENV_ENDPOINT];
22
+ return raw !== void 0 && raw.trim() !== "" ? raw.trim() : void 0;
23
+ }
24
+ function composeWorkspaceUrl(endpoint, workspace) {
25
+ return endpoint.replace(/\/+$/, "") + WORKSPACE_PROXY_PATH.replace("{workspace}", workspace);
26
+ }
27
+ var VENDOR_DEFAULT_BASE_URLS = /* @__PURE__ */ new Set([
28
+ "https://api.openai.com/v1",
29
+ "https://api.openai.com",
30
+ "https://api.anthropic.com/v1",
31
+ "https://api.anthropic.com"
32
+ ]);
33
+ function canonicalUrl(url) {
34
+ return url.trim().replace(/\/+$/, "");
35
+ }
36
+ function warnIfDiscardingExplicitBaseUrl(previous, next) {
37
+ if (typeof previous !== "string") return;
38
+ const before = canonicalUrl(previous);
39
+ if (before === "") return;
40
+ if (before === canonicalUrl(next)) return;
41
+ if (VENDOR_DEFAULT_BASE_URLS.has(before)) return;
42
+ console.warn(
43
+ `[sentisec] wrap() replaced the client's baseURL ${before} with ${next}. If that was deliberate, pass it through Sentisec instead \u2014 new Monitor({ endpoint }) for a Sentisec control plane on another host, or wrap(client, { baseUrl }) to target one wrap at a literal URL.`
44
+ );
45
+ }
16
46
  var DEFAULT_INGRESS_TEMPLATE = "https://api.sentisec.ch/ws/{workspace}/v1";
17
- function resolveProxyBaseUrl(workspace, opts) {
47
+ function resolveProxyBaseUrl(workspace, opts, endpoint) {
18
48
  if (opts?.baseUrl !== void 0) return opts.baseUrl;
49
+ if (endpoint !== void 0 && endpoint.trim() !== "") {
50
+ return composeWorkspaceUrl(endpoint.trim(), workspace);
51
+ }
52
+ const fromEnv = endpointFromEnv();
53
+ if (fromEnv !== void 0) return composeWorkspaceUrl(fromEnv, workspace);
19
54
  return DEFAULT_INGRESS_TEMPLATE.replace("{workspace}", workspace);
20
55
  }
21
56
 
@@ -41,7 +76,8 @@ function wrapOpenAI(client, ctx, opts) {
41
76
  "wrap-openai: client failed isOpenAILike() but the OpenAI adapter was selected \u2014 vendor-registry mismatch."
42
77
  );
43
78
  }
44
- const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts);
79
+ const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
80
+ warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
45
81
  client.baseURL = proxyBaseUrl;
46
82
  client.defaultHeaders = {
47
83
  ...client.defaultHeaders,
@@ -186,7 +222,8 @@ function wrapAnthropic(client, ctx, opts) {
186
222
  "wrap-anthropic: client failed isAnthropicLike() but the Anthropic adapter was selected \u2014 vendor-registry mismatch."
187
223
  );
188
224
  }
189
- const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts);
225
+ const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
226
+ warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
190
227
  client.baseURL = proxyBaseUrl;
191
228
  client.defaultHeaders = {
192
229
  ...client.defaultHeaders,
@@ -249,7 +286,8 @@ function installWrap(MonitorCtor) {
249
286
  apiKey: this.apiKey,
250
287
  model: this.model,
251
288
  task: this.task,
252
- policy: this.policy
289
+ policy: this.policy,
290
+ endpoint: this.endpoint
253
291
  };
254
292
  for (const entry of registry) {
255
293
  if (entry.detect(client)) {
@@ -702,6 +740,7 @@ var Monitor = class {
702
740
  policy;
703
741
  responsePolicy;
704
742
  customerId;
743
+ endpoint;
705
744
  constructor(config) {
706
745
  this.apiKey = config.apiKey;
707
746
  this.model = config.model;
@@ -709,6 +748,7 @@ var Monitor = class {
709
748
  this.policy = config.policy ?? "research_agent";
710
749
  this.responsePolicy = config.responsePolicy ?? "gated";
711
750
  this.customerId = config.customerId ?? "cust_local";
751
+ this.endpoint = config.endpoint;
712
752
  this.validatePolicy();
713
753
  }
714
754
  validatePolicy() {
@@ -738,4 +778,4 @@ Object.setPrototypeOf(SentisecHijackError.prototype, SentisecError.prototype);
738
778
  Object.setPrototypeOf(SentisecAnthropicBlockError.prototype, SentisecError.prototype);
739
779
  installWrap(Monitor);
740
780
 
741
- export { BUILTIN_POLICIES, DEFAULT_INGRESS_TEMPLATE, Monitor, SentisecAnthropicBlockError, SentisecError, SentisecHijackError, Session, TaskTamperError, UnknownPolicyError, VerifierBackendNotConfigured, src_default as default, wrapAnthropicStream, wrapOpenAIStream };
781
+ export { BUILTIN_POLICIES, DEFAULT_ENDPOINT, DEFAULT_INGRESS_TEMPLATE, ENV_ENDPOINT, Monitor, SentisecAnthropicBlockError, SentisecError, SentisecHijackError, Session, TaskTamperError, UnknownPolicyError, VerifierBackendNotConfigured, WORKSPACE_PROXY_PATH, src_default as default, resolveProxyBaseUrl, wrapAnthropicStream, wrapOpenAIStream };
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.5",
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);