@xtrom-ai/sdk 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +185 -2
- package/dist/allowances.js +74 -0
- package/dist/cli.js +268 -0
- package/dist/credentials.js +37 -0
- package/dist/directive.js +57 -0
- package/dist/enforce.js +972 -0
- package/dist/index.js +31 -0
- package/dist/inspect.js +135 -0
- package/dist/local/agents.js +378 -0
- package/dist/local/appliers.js +61 -0
- package/dist/local/browser.js +135 -0
- package/dist/local/discover.js +154 -0
- package/dist/local/hook.js +778 -0
- package/dist/local/install.js +238 -0
- package/dist/local/inventory.js +219 -0
- package/dist/local/reasonText.js +29 -0
- package/dist/local/shipper.js +251 -0
- package/dist/local/spool.js +178 -0
- package/dist/local/updateKeys.js +3 -0
- package/dist/local/updater.js +224 -0
- package/dist/local/view.js +110 -0
- package/dist/memory.js +172 -0
- package/dist/reporter.js +336 -0
- package/dist/session.js +439 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +72 -0
- package/package.json +23 -4
- package/src/allowances.ts +74 -0
- package/src/cli.ts +268 -0
- package/src/credentials.ts +37 -0
- package/src/directive.ts +57 -0
- package/src/enforce.ts +972 -0
- package/src/index.ts +31 -0
- package/src/inspect.ts +135 -0
- package/src/local/agents.ts +378 -0
- package/src/local/appliers.ts +61 -0
- package/src/local/browser.ts +135 -0
- package/src/local/discover.ts +154 -0
- package/src/local/hook.ts +778 -0
- package/src/local/install.ts +238 -0
- package/src/local/inventory.ts +219 -0
- package/src/local/reasonText.ts +29 -0
- package/src/local/shipper.ts +251 -0
- package/src/local/spool.ts +178 -0
- package/src/local/updateKeys.ts +3 -0
- package/src/local/updater.ts +224 -0
- package/src/local/view.ts +110 -0
- package/src/memory.ts +172 -0
- package/src/reporter.ts +336 -0
- package/src/session.ts +439 -0
- package/src/version.ts +2 -0
- package/src/workspace.ts +72 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// xtrom — local coding-agent protection. `npx -y <console>/pkgs/npm/xtrom-sdk-<ver>.tgz install`
|
|
3
|
+
// wires the hook into every supported coding agent found on the machine (see local/agents.ts).
|
|
4
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
import { createInterface } from "node:readline";
|
|
10
|
+
import { discover } from "./local/discover.js";
|
|
11
|
+
import { main as hookMain } from "./local/hook.js";
|
|
12
|
+
import { AGENTS, AGENT_IDS, detected, resolveAgents } from "./local/agents.js";
|
|
13
|
+
import { install, setReporting, settingsPath, status, uninstall, } from "./local/install.js";
|
|
14
|
+
import { installSummary, logLines, parseSince, readAudit, statusLines } from "./local/view.js";
|
|
15
|
+
import { paths, readConfig } from "./local/hook.js";
|
|
16
|
+
import { SDK_VERSION } from "./version.js";
|
|
17
|
+
|
|
18
|
+
const HELP = `xtrom ${SDK_VERSION} — deterministic runtime firewall for AI coding agents
|
|
19
|
+
|
|
20
|
+
Usage:
|
|
21
|
+
xtrom install [--agent A] [--project] [--monitor] [--url URL (--token TOKEN | --token-stdin)]
|
|
22
|
+
Add Xtrom hooks to your coding agents (user scope by
|
|
23
|
+
default); --url/--token store reporting creds 0600.
|
|
24
|
+
--token-stdin reads the token from XTROM_INSTALL_TOKEN,
|
|
25
|
+
piped stdin, or a hidden prompt — never from argv.
|
|
26
|
+
xtrom uninstall [--agent A] [--project] Remove only Xtrom's hook entries
|
|
27
|
+
xtrom status [--agent A] [--project] [--json]
|
|
28
|
+
What's protected on this machine (--json: the stable
|
|
29
|
+
machine format)
|
|
30
|
+
xtrom log [--all] [--since 2h] [--limit N] [--json]
|
|
31
|
+
What Xtrom stopped (--all: allowed calls too), newest first
|
|
32
|
+
xtrom connect --url URL (--token-stdin | --token T) | xtrom connect --off
|
|
33
|
+
Report decision metadata to your team's console, or stop
|
|
34
|
+
xtrom discover [--json] List MCP servers in Claude/Cursor/Codex/VS Code configs
|
|
35
|
+
xtrom hook Hook entrypoint (invoked by the coding agent)
|
|
36
|
+
xtrom version
|
|
37
|
+
|
|
38
|
+
Agents (--agent): auto (agents found on this machine; install default), all (uninstall/status
|
|
39
|
+
default), or a comma list of: ${AGENT_IDS.join(", ")}
|
|
40
|
+
|
|
41
|
+
Env: XTROM_MODE=monitor|enforce, XTROM_CONTROL_PLANE_URL + XTROM_TOKEN (optional reporting),
|
|
42
|
+
XTROM_LOCAL_HOME (state dir, default ~/.xtrom/local)`;
|
|
43
|
+
|
|
44
|
+
function readAllStdin() {
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
let data = "";
|
|
47
|
+
process.stdin.setEncoding("utf8");
|
|
48
|
+
process.stdin.on("data", (c) => (data += c));
|
|
49
|
+
process.stdin.on("end", () => resolve(data));
|
|
50
|
+
process.stdin.resume();
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Read a secret from the TTY without echoing it — nothing is written for the typed characters, so
|
|
55
|
+
// neither the value nor its length is shown.
|
|
56
|
+
function promptHidden(prompt ) {
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
59
|
+
(rl )._writeToOutput = (s) => {
|
|
60
|
+
if (s.startsWith(prompt)) process.stdout.write(s);
|
|
61
|
+
};
|
|
62
|
+
rl.question(prompt, (ans) => { rl.close(); process.stdout.write("\n"); resolve(ans); });
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Mirror of the Python CLI: `--token` wins (explicit, argv-visible); otherwise `--token-stdin`
|
|
67
|
+
// takes the token off the command line — XTROM_INSTALL_TOKEN, then piped stdin, then a hidden
|
|
68
|
+
// prompt — so it never lands in argv or shell history. Undefined ⇒ anonymous local install.
|
|
69
|
+
const TOKEN_RX = /^xtrom_dp_[A-Za-z0-9_-]{32,128}$/;
|
|
70
|
+
const TOKEN_HELP = "that doesn't look like an Xtrom enrollment token (they start with xtrom_dp_). "
|
|
71
|
+
+ "Copy it from Connect in the console and try again";
|
|
72
|
+
|
|
73
|
+
/** Refuse anything not shaped like an enrollment token, without echoing it. */
|
|
74
|
+
export function checkedToken(tok ) {
|
|
75
|
+
if (!TOKEN_RX.test(tok)) throw new Error(TOKEN_HELP);
|
|
76
|
+
return tok;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function resolveInstallToken(token , tokenStdin ) {
|
|
80
|
+
if (token) return checkedToken(token.trim());
|
|
81
|
+
if (!tokenStdin) return undefined;
|
|
82
|
+
const env = (process.env.XTROM_INSTALL_TOKEN ?? "").trim();
|
|
83
|
+
if (env) return checkedToken(env);
|
|
84
|
+
if (!process.stdin.isTTY) {
|
|
85
|
+
const tok = (await readAllStdin()).trim();
|
|
86
|
+
if (tok) return checkedToken(tok);
|
|
87
|
+
throw new Error("--token-stdin: stdin was empty and XTROM_INSTALL_TOKEN is unset");
|
|
88
|
+
}
|
|
89
|
+
const tok = (await promptHidden("Paste your Xtrom install token (hidden): ")).trim();
|
|
90
|
+
if (tok) return checkedToken(tok);
|
|
91
|
+
throw new Error("--token-stdin: no token entered");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** How to run this CLI again. Under npx there is no `xtrom` on PATH, so name the same package npx ran
|
|
95
|
+
* (npm passes it as npm_config_package); a name or URL only, never anything that looks like a token. */
|
|
96
|
+
export function selfCommand(env = process.env, here = fileURLToPath(import.meta.url)) {
|
|
97
|
+
if (env.npm_command !== "exec") return "xtrom";
|
|
98
|
+
let spec = (env.npm_config_package ?? "").split(/\s+/)[0];
|
|
99
|
+
if (!spec) spec = npxSpec(here); // `npx -y <url> …`: npx records the spec in its cache dir
|
|
100
|
+
if (!spec || /xtrom_dp_|token=/i.test(spec) || /[\s;&|`$<>"'\\]/.test(spec)) return "xtrom";
|
|
101
|
+
return `npx -y ${spec}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The package spec npx ran, from its cache dir (~/.npm/_npx/<id>/package.json lists it as a dependency). */
|
|
105
|
+
function npxSpec(here ) {
|
|
106
|
+
const m = /^(.*[\\/]_npx[\\/][^\\/]+)[\\/]node_modules[\\/]/.exec(here);
|
|
107
|
+
if (!m) return "";
|
|
108
|
+
try {
|
|
109
|
+
const deps = JSON.parse(readFileSync(join(m[1], "package.json"), "utf8")).dependencies ?? {};
|
|
110
|
+
for (const name of ["xtrom", "@xtrom-ai/sdk"]) {
|
|
111
|
+
const v = deps[name];
|
|
112
|
+
if (typeof v !== "string") continue;
|
|
113
|
+
if (/^https?:\/\//.test(v)) return v; // `npx -y <url>`: the tarball URL
|
|
114
|
+
if (/^[\w.^~*<>=| -]+$/.test(v)) return name; // from the registry: its name
|
|
115
|
+
}
|
|
116
|
+
return "";
|
|
117
|
+
} catch { return ""; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function run(argv ) {
|
|
121
|
+
const [cmd, ...rest] = argv;
|
|
122
|
+
if (cmd === "hook") return hookMain(rest); // never parse hook args strictly: it must not fail loud
|
|
123
|
+
if (cmd === "__ship") { const { main } = await import("./local/shipper.js"); return main(rest); } // detached background spool drainer (spawned by the hook)
|
|
124
|
+
let values ;
|
|
125
|
+
try {
|
|
126
|
+
({ values } = parseArgs({
|
|
127
|
+
args: rest, strict: true, allowPositionals: false,
|
|
128
|
+
options: {
|
|
129
|
+
project: { type: "boolean" }, monitor: { type: "boolean" }, json: { type: "boolean" },
|
|
130
|
+
url: { type: "string" }, token: { type: "string" }, "token-stdin": { type: "boolean" }, agent: { type: "string" },
|
|
131
|
+
all: { type: "boolean" }, since: { type: "string" }, limit: { type: "string" }, off: { type: "boolean" },
|
|
132
|
+
},
|
|
133
|
+
}));
|
|
134
|
+
} catch (e) {
|
|
135
|
+
process.stderr.write(`${(e ).message}\n\n${HELP}\n`);
|
|
136
|
+
return 2;
|
|
137
|
+
}
|
|
138
|
+
const scope = values.project ? "project" : "user";
|
|
139
|
+
const home = homedir();
|
|
140
|
+
let ids = [];
|
|
141
|
+
if (cmd === "install" || cmd === "uninstall" || cmd === "status") {
|
|
142
|
+
try {
|
|
143
|
+
ids = resolveAgents((values.agent ) ?? (cmd === "install" ? "auto" : "all"), home, process.env);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
process.stderr.write(`xtrom: ${(e ).message}\n`);
|
|
146
|
+
return 2;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
switch (cmd) {
|
|
150
|
+
case "install": {
|
|
151
|
+
let token ;
|
|
152
|
+
try {
|
|
153
|
+
token = await resolveInstallToken(values.token , !!values["token-stdin"]); // resolve once, not per agent
|
|
154
|
+
} catch (e) {
|
|
155
|
+
process.stderr.write(`xtrom: ${(e ).message}\n`);
|
|
156
|
+
return 2;
|
|
157
|
+
}
|
|
158
|
+
let runtime = "";
|
|
159
|
+
const labels = [];
|
|
160
|
+
for (const agent of ids) {
|
|
161
|
+
const label = AGENTS[agent].label;
|
|
162
|
+
let r;
|
|
163
|
+
try {
|
|
164
|
+
r = install(scope, {
|
|
165
|
+
agent, monitor: !!values.monitor,
|
|
166
|
+
controlPlaneUrl: values.url , token,
|
|
167
|
+
});
|
|
168
|
+
} catch (e) { // includes malformed JSON: the file is left untouched
|
|
169
|
+
process.stderr.write(`xtrom: ${label}: ${(e ).message}\n`);
|
|
170
|
+
return 2;
|
|
171
|
+
}
|
|
172
|
+
runtime = r.runtime;
|
|
173
|
+
labels.push(label);
|
|
174
|
+
console.log(`Hooks added for ${label}: ${r.settingsPath}`);
|
|
175
|
+
if (r.backup) console.log(` Backup: ${r.backup}`);
|
|
176
|
+
if (agent === "codex") console.log(" Codex asks you to trust new hooks: open Codex and approve Xtrom in /hooks.");
|
|
177
|
+
if (r.pythonHookPresent) console.log(" Note: the Python xtrom hook is also installed here; run `xtrom uninstall` from one of them to avoid double prompts.");
|
|
178
|
+
}
|
|
179
|
+
console.log(`Runtime: ${runtime}`);
|
|
180
|
+
const cfg = readConfig(paths());
|
|
181
|
+
console.log("\n" + installSummary(labels, { reporting: !!(cfg.control_plane_url && cfg.token), monitor: cfg.mode === "monitor", cmd: selfCommand() }).join("\n"));
|
|
182
|
+
return 0;
|
|
183
|
+
}
|
|
184
|
+
case "uninstall":
|
|
185
|
+
for (const agent of ids) {
|
|
186
|
+
if (existsSync(settingsPath(scope, home, process.cwd(), agent))) {
|
|
187
|
+
console.log(`Xtrom hooks removed for ${AGENTS[agent].label}: ${uninstall(scope, { agent })}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return 0;
|
|
191
|
+
case "status": {
|
|
192
|
+
const found = new Set(detected(home, process.env));
|
|
193
|
+
let rows = ids.map((agent) => status(scope, { agent }));
|
|
194
|
+
if (!values.agent || values.agent === "all") rows = rows.filter((r) => r.installed || found.has(r.agent));
|
|
195
|
+
if (values.json) console.log(JSON.stringify(rows, null, 2));
|
|
196
|
+
else console.log(statusLines(rows, String(readConfig(paths()).mode ?? "enforce")).join("\n"));
|
|
197
|
+
return 0;
|
|
198
|
+
}
|
|
199
|
+
case "log": {
|
|
200
|
+
let sinceS ;
|
|
201
|
+
try { sinceS = parseSince(values.since ); } catch (e) {
|
|
202
|
+
process.stderr.write(`xtrom: ${(e ).message}\n`);
|
|
203
|
+
return 2;
|
|
204
|
+
}
|
|
205
|
+
const limit = Math.max(1, Math.min(Number(values.limit ?? 50) || 50, 1000));
|
|
206
|
+
const rows = readAudit(paths().audit, { sinceS, includeAllowed: !!values.all, limit });
|
|
207
|
+
if (values.json) console.log(JSON.stringify(rows, null, 2));
|
|
208
|
+
else console.log(logLines(rows, { includeAllowed: !!values.all }).join("\n"));
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
case "connect": {
|
|
212
|
+
try {
|
|
213
|
+
if (values.off) {
|
|
214
|
+
setReporting(undefined, undefined);
|
|
215
|
+
console.log("Reporting is off. Xtrom keeps deciding on this machine; nothing is sent.");
|
|
216
|
+
return 0;
|
|
217
|
+
}
|
|
218
|
+
if (!values.url) {
|
|
219
|
+
process.stderr.write("xtrom: connect needs --url (your console's API URL) and a token (--token-stdin)\n");
|
|
220
|
+
return 2;
|
|
221
|
+
}
|
|
222
|
+
const token = await resolveInstallToken(values.token , !!values["token-stdin"] || !values.token);
|
|
223
|
+
setReporting(values.url , token);
|
|
224
|
+
} catch (e) {
|
|
225
|
+
process.stderr.write(`xtrom: ${(e ).message}\n`);
|
|
226
|
+
return 2;
|
|
227
|
+
}
|
|
228
|
+
console.log(`Reporting to ${values.url}: decision metadata only (tool, verdict, reason), never arguments or output.`);
|
|
229
|
+
console.log("Same hooks, same local decisions. `xtrom connect --off` stops reporting.");
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
232
|
+
case "discover": {
|
|
233
|
+
const rows = discover();
|
|
234
|
+
if (values.json) console.log(JSON.stringify(rows, null, 2));
|
|
235
|
+
else if (!rows.length) console.log("No MCP servers found.");
|
|
236
|
+
else for (const r of rows) {
|
|
237
|
+
const hints = r.risk_hints.length ? ` [${r.risk_hints.join("; ")}]` : "";
|
|
238
|
+
console.log(`${r.name}\t${r.transport}\t${r.command_or_url}\t${r.source_file}${hints}`);
|
|
239
|
+
}
|
|
240
|
+
return 0;
|
|
241
|
+
}
|
|
242
|
+
case "version":
|
|
243
|
+
case "--version":
|
|
244
|
+
console.log(SDK_VERSION);
|
|
245
|
+
return 0;
|
|
246
|
+
case undefined:
|
|
247
|
+
case "help":
|
|
248
|
+
case "--help":
|
|
249
|
+
case "-h":
|
|
250
|
+
console.log(HELP);
|
|
251
|
+
return 0;
|
|
252
|
+
default:
|
|
253
|
+
process.stderr.write(`unknown command: ${cmd}\n\n${HELP}\n`);
|
|
254
|
+
return 2;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function isMain() {
|
|
259
|
+
// npm links bin entries via symlinks (node_modules/.bin/xtrom), so compare real paths.
|
|
260
|
+
try { return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); }
|
|
261
|
+
catch { return false; }
|
|
262
|
+
}
|
|
263
|
+
if (isMain()) {
|
|
264
|
+
run(process.argv.slice(2)).then(
|
|
265
|
+
(code) => { process.exitCode = code; },
|
|
266
|
+
(e) => { process.stderr.write(`xtrom: ${(e ).message}\n`); process.exitCode = 1; },
|
|
267
|
+
);
|
|
268
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Just-in-time AWS credentials from the Xtrom gateway (docs/design/JIT-BROKER.md in the Xtrom repo).
|
|
2
|
+
// Mirrors xtrom_sdk/credentials.py. The agent asks its gateway for a role its operator configured; the gateway
|
|
3
|
+
// checks it is a signed-in agent allowed that role and returns short-lived credentials for this grant only.
|
|
4
|
+
import { requireSecureUrl } from "./reporter.js";
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
export class CredentialsError extends Error {}
|
|
11
|
+
|
|
12
|
+
export async function credentials(role , opts
|
|
13
|
+
|
|
14
|
+
= {}) {
|
|
15
|
+
const base = (opts.gatewayUrl ?? process.env.XTROM_GATEWAY_URL ?? "").replace(/\/+$/, "");
|
|
16
|
+
const url = requireSecureUrl(base) + "/v1/credentials";
|
|
17
|
+
const token = opts.token ?? process.env.XTROM_GATEWAY_TOKEN ?? "";
|
|
18
|
+
if (!token) throw new CredentialsError("no caller token: set XTROM_GATEWAY_TOKEN (credentials go only to a signed-in agent)");
|
|
19
|
+
let res ;
|
|
20
|
+
try {
|
|
21
|
+
res = await (opts.fetchImpl ?? fetch)(url, {
|
|
22
|
+
method: "POST", redirect: "manual", signal: AbortSignal.timeout(opts.timeoutMs ?? 10_000),
|
|
23
|
+
headers: { "content-type": "application/json", authorization: "Bearer " + token },
|
|
24
|
+
body: JSON.stringify(opts.ttl ? { role, ttl: Math.trunc(opts.ttl) } : { role }),
|
|
25
|
+
});
|
|
26
|
+
} catch (e) {
|
|
27
|
+
throw new CredentialsError(`the gateway could not be reached: ${(e ).message}`);
|
|
28
|
+
}
|
|
29
|
+
const body = await res.json().catch(() => ({})) ;
|
|
30
|
+
if (res.status !== 200) {
|
|
31
|
+
throw new CredentialsError(`the gateway refused (${res.status}): ${String(body.message ?? body.error ?? res.statusText)}`);
|
|
32
|
+
}
|
|
33
|
+
const c = (body.credentials ?? {}) ;
|
|
34
|
+
if (!c.AccessKeyId) throw new CredentialsError("the gateway returned no credentials");
|
|
35
|
+
return { AccessKeyId: c.AccessKeyId, SecretAccessKey: c.SecretAccessKey, SessionToken: c.SessionToken,
|
|
36
|
+
Expiration: c.Expiration, grant: String(body.grant ?? "") };
|
|
37
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// The signed enforcement directive, as the SDK checks it. Mirrors xtrom_sdk/directive.py (control plane:
|
|
2
|
+
// app/directive.py; the gateway does the same in settings_cache.go).
|
|
3
|
+
//
|
|
4
|
+
// The ingest response carries `directive`: {payload (base64), kid, alg, sig}, ES256 over the canonical JSON of
|
|
5
|
+
// {schema, tenant, enforcement_enabled, enforcement_kill_expires_at, workspace_mode, signed_at}. With
|
|
6
|
+
// XTROM_POLICY_VERIFY_KEY (the PEM from GET /v1/signing-keys, or a path to it) and XTROM_TENANT set, the
|
|
7
|
+
// workspace mode comes ONLY from a directive that verifies, is for this tenant and is no older than the last
|
|
8
|
+
// one accepted; anything else means enforce. Without the key the mode is taken from the response over TLS.
|
|
9
|
+
import { createPublicKey, verify as cryptoVerify } from "node:crypto";
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
|
|
12
|
+
export const DIRECTIVE_SCHEMA = "xtrom.directive/1";
|
|
13
|
+
|
|
14
|
+
export class DirectiveVerifier {
|
|
15
|
+
minSignedAt = 0;
|
|
16
|
+
pem ;
|
|
17
|
+
tenant ;
|
|
18
|
+
kid ;
|
|
19
|
+
constructor(pem , tenant , kid = "") {
|
|
20
|
+
this.pem = pem; this.tenant = tenant; this.kid = kid;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The verified payload, or null. Never throws, never parses unauthenticated bytes. */
|
|
24
|
+
verify(envelope ) {
|
|
25
|
+
try {
|
|
26
|
+
if (!envelope || typeof envelope !== "object") return null;
|
|
27
|
+
const e = envelope ;
|
|
28
|
+
if (e.alg !== "ES256" || typeof e.payload !== "string" || typeof e.sig !== "string") return null;
|
|
29
|
+
if (this.kid && e.kid !== this.kid) return null;
|
|
30
|
+
const payload = Buffer.from(e.payload, "base64");
|
|
31
|
+
if (!cryptoVerify("sha256", payload, createPublicKey(this.pem), Buffer.from(e.sig, "base64"))) return null;
|
|
32
|
+
const d = JSON.parse(payload.toString("utf8"));
|
|
33
|
+
if (!d || typeof d !== "object" || d.schema !== DIRECTIVE_SCHEMA || d.tenant !== this.tenant) return null;
|
|
34
|
+
if (!Number.isInteger(d.signed_at) || d.signed_at < this.minSignedAt) return null; // a replay
|
|
35
|
+
this.minSignedAt = d.signed_at;
|
|
36
|
+
return d;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let cached = null;
|
|
44
|
+
|
|
45
|
+
/** The process's verifier, or null when XTROM_POLICY_VERIFY_KEY is unset. A key without XTROM_TENANT can't
|
|
46
|
+
* bind the directive to this workspace, so it verifies nothing (monitor is never honoured). */
|
|
47
|
+
export function directiveVerifierFromEnv(env = process.env) {
|
|
48
|
+
let pem = (env.XTROM_POLICY_VERIFY_KEY ?? "").trim();
|
|
49
|
+
if (!pem) return null;
|
|
50
|
+
if (!pem.startsWith("-----BEGIN")) {
|
|
51
|
+
try { pem = readFileSync(pem, "utf8"); } catch { pem = ""; }
|
|
52
|
+
}
|
|
53
|
+
const tenant = (env.XTROM_TENANT ?? "").trim() || "\0no-tenant", kid = (env.XTROM_POLICY_VERIFY_KID ?? "").trim();
|
|
54
|
+
const key = [pem, tenant, kid].join("\n");
|
|
55
|
+
if (!cached || cached.key !== key) cached = { key, v: new DirectiveVerifier(pem, tenant, kid) };
|
|
56
|
+
return cached.v;
|
|
57
|
+
}
|