@xtrom-ai/sdk 0.0.0-stage → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// What the local CLI tells a person (docs/design/PUBLIC-INSTALL.md): the install summary, `xtrom status` and
|
|
2
|
+
// `xtrom log` in words. Parity with xtrom_sdk/local/view.py. Pure functions over the local audit log and status
|
|
3
|
+
// rows. The audit log holds metadata only (time, agent, tool, verdict, reason, untrusted-source hosts).
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { AGENTS, ALIASES } from "./agents.ts";
|
|
6
|
+
import { REASON_TEXT } from "./reasonText.ts";
|
|
7
|
+
|
|
8
|
+
type Row = Record<string, unknown>;
|
|
9
|
+
// Tool names come from the agent or an MCP server: never let one carry terminal escape sequences to the screen.
|
|
10
|
+
// eslint-disable-next-line no-control-regex
|
|
11
|
+
const safe = (s: unknown): string => String(s).replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
|
|
12
|
+
|
|
13
|
+
export function reasonText(code: unknown): string {
|
|
14
|
+
const c = String(code ?? "").trim();
|
|
15
|
+
if (!c) return "";
|
|
16
|
+
if (Object.hasOwn(REASON_TEXT, c)) return REASON_TEXT[c];
|
|
17
|
+
const h = c.replace(/[._]/g, " ");
|
|
18
|
+
return h.charAt(0).toUpperCase() + h.slice(1);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** "30m", "2h", "7d" → seconds; undefined/"" → no limit. Anything else throws. */
|
|
22
|
+
export function parseSince(spec: string | undefined): number | null {
|
|
23
|
+
if (!spec) return null;
|
|
24
|
+
const m = /^(\d{1,5})([mhd])$/.exec(spec.trim().toLowerCase());
|
|
25
|
+
if (!m) throw new Error(`--since takes a number and m, h or d (e.g. 30m, 2h, 7d), not '${spec}'`);
|
|
26
|
+
return Number(m[1]) * ({ m: 60, h: 3600, d: 86400 } as Record<string, number>)[m[2]];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const epoch = (ts: unknown): number | null => {
|
|
30
|
+
const s = String(ts ?? "");
|
|
31
|
+
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(s)) return null;
|
|
32
|
+
const t = Date.parse(s.slice(0, 19) + "Z");
|
|
33
|
+
return Number.isNaN(t) ? null : t / 1000;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Newest-first decisions from the local audit log; without includeAllowed only what was stopped or held. */
|
|
37
|
+
export function readAudit(path: string, o: { sinceS?: number | null; includeAllowed?: boolean; limit?: number; now?: number } = {}): Row[] {
|
|
38
|
+
const now = o.now ?? Date.now() / 1000, limit = o.limit ?? 50;
|
|
39
|
+
let lines: string[];
|
|
40
|
+
try { lines = readFileSync(path, "utf8").split("\n"); } catch { return []; }
|
|
41
|
+
const rows: Row[] = [];
|
|
42
|
+
for (let i = lines.length - 1; i >= 0 && rows.length < limit; i--) {
|
|
43
|
+
let d: unknown;
|
|
44
|
+
try { d = JSON.parse(lines[i]); } catch { continue; }
|
|
45
|
+
if (!d || typeof d !== "object" || Array.isArray(d) || !("verdict" in d)) continue;
|
|
46
|
+
const r = d as Row;
|
|
47
|
+
const t = epoch(r.ts);
|
|
48
|
+
if (o.sinceS != null && (t === null || now - t > o.sinceS)) continue;
|
|
49
|
+
if (!o.includeAllowed && r.verdict === "ALLOW") continue;
|
|
50
|
+
rows.push(r);
|
|
51
|
+
}
|
|
52
|
+
return rows;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function verdictWord(d: Row): string {
|
|
56
|
+
const monitor = d.mode === "monitor";
|
|
57
|
+
if (d.verdict === "BLOCK") return monitor ? "Would block" : "Blocked";
|
|
58
|
+
if (d.verdict === "STEP_UP") return monitor ? "Would ask" : "Asked you";
|
|
59
|
+
return "Allowed";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function agentLabel(client: unknown): string {
|
|
63
|
+
const c = String(client ?? "");
|
|
64
|
+
const id = Object.hasOwn(ALIASES, c) ? ALIASES[c] : c; // hooks record e.g. "claude-code"
|
|
65
|
+
return Object.hasOwn(AGENTS, id) ? AGENTS[id].label : (c ? safe(c).slice(0, 40) : "Unknown agent");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const pad = (s: string, n: number) => s + " ".repeat(Math.max(0, n - s.length));
|
|
69
|
+
|
|
70
|
+
function clock(ts: unknown, now: number): string {
|
|
71
|
+
const t = epoch(ts);
|
|
72
|
+
if (t === null) return "—";
|
|
73
|
+
const d = new Date(t * 1000), today = new Date(now * 1000);
|
|
74
|
+
const two = (n: number) => String(n).padStart(2, "0");
|
|
75
|
+
if (d.toDateString() === today.toDateString()) return `${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
|
|
76
|
+
return `${d.toLocaleString("en-US", { month: "short" })} ${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function logLines(rows: Row[], o: { now?: number; includeAllowed?: boolean } = {}): string[] {
|
|
80
|
+
const now = o.now ?? Date.now() / 1000;
|
|
81
|
+
if (!rows.length) return [o.includeAllowed ? "Nothing yet." : "Nothing stopped yet. `xtrom log --all` shows everything Xtrom decided."];
|
|
82
|
+
const width = Math.max(...rows.map((d) => agentLabel(d.client).length));
|
|
83
|
+
const toolW = Math.min(24, Math.max(...rows.map((d) => safe(d.tool_name ?? "—").length)));
|
|
84
|
+
return rows.map((d) => `${pad(clock(d.ts, now), 12)} ${pad(agentLabel(d.client), width)} `
|
|
85
|
+
+ `${pad(safe(d.tool_name ?? "—").slice(0, toolW), toolW)} ${pad(verdictWord(d), 11)} ${safe(reasonText(d.reason_code))}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function statusLines(rows: Row[], mode = "enforce"): string[] {
|
|
89
|
+
if (!rows.length) return ["No coding agents found on this machine. `xtrom install --agent all` sets up every one Xtrom supports."];
|
|
90
|
+
const width = Math.max(...rows.map((r) => String(r.label ?? r.agent ?? "").length));
|
|
91
|
+
return rows.map((r) => {
|
|
92
|
+
const name = pad(String(r.label ?? r.agent ?? ""), width);
|
|
93
|
+
if (!r.installed) return `${name} not protected · \`xtrom install --agent ${r.agent}\``;
|
|
94
|
+
if (!r.runtime_ok) return `${name} broken: the hook script is missing · run \`xtrom install\` again`;
|
|
95
|
+
const how = mode === "monitor" ? "monitoring (records, never blocks)" : "enforcing";
|
|
96
|
+
const where = r.reporting ? "reporting to your Xtrom console" : "local only, nothing sent";
|
|
97
|
+
return `${name} protected · ${how} · ${where}`;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function installSummary(labels: string[], o: { reporting: boolean; monitor: boolean; cmd?: string }): string[] {
|
|
102
|
+
const cmd = o.cmd ?? "xtrom";
|
|
103
|
+
const lines = [`Xtrom is protecting: ${labels.join(", ")}.`,
|
|
104
|
+
o.reporting ? "Decisions are made on this machine; metadata goes to your Xtrom console."
|
|
105
|
+
: "Decisions are made on this machine. Nothing is sent anywhere; no account needed."];
|
|
106
|
+
if (o.monitor) lines.push("Monitor mode: risky calls are recorded, not blocked. Re-run without --monitor to enforce.");
|
|
107
|
+
lines.push("", ` ${cmd} log what Xtrom stopped (--all for everything)`, ` ${cmd} status what's protected`,
|
|
108
|
+
o.reporting ? ` ${cmd} connect --off stop reporting` : ` ${cmd} connect report to your team's Xtrom console`);
|
|
109
|
+
return lines;
|
|
110
|
+
}
|
package/src/memory.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Memory provenance (docs/design/MEMORY-PROVENANCE.md in the Xtrom repo, OWASP ASI06). Mirrors
|
|
2
|
+
// xtrom-engine/xtrom/memory.py and is held to xtrom-engine/memory_golden.json.
|
|
3
|
+
// Taint tracking lives inside one session; agent memory outlives it. What an agent stores is fingerprinted
|
|
4
|
+
// with whether it was clean or tainted, and what it later recalls is labelled by those fingerprints.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_MEMORY_WRITE_ACTIONS = new Set([
|
|
8
|
+
"memory_write", "remember", "save_memory", "store_memory", "add_memory", "memory_add", "update_memory",
|
|
9
|
+
"vector_upsert", "upsert_memory", "create_entities", "add_observations", "create_relations",
|
|
10
|
+
]);
|
|
11
|
+
export const DEFAULT_MEMORY_READ_ACTIONS = new Set([
|
|
12
|
+
"memory_read", "recall", "search_memory", "memory_search", "retrieve_memory", "get_memory", "load_memory",
|
|
13
|
+
"query_memory", "vector_query", "search_nodes", "open_nodes", "read_graph",
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
export type MemoryTrust = "trusted" | "untrusted";
|
|
17
|
+
const MIN_CHUNK = 16; // a piece shorter than this joins its neighbours
|
|
18
|
+
const MAX_STRINGS = 512;
|
|
19
|
+
const LONG_TOKEN = 64; // a no-space string this long is attributed (encoded payloads)
|
|
20
|
+
const SPLIT_RX = /[\r\n]+|(?<=[.!?])\s+/;
|
|
21
|
+
const WS_RX = /\s+/g;
|
|
22
|
+
const DEST_MARKS = ["://", "@", "/", "\\"];
|
|
23
|
+
const cp = (s: string) => [...s].length; // code points, as Python's len()
|
|
24
|
+
|
|
25
|
+
const MAX_DEPTH = 16;
|
|
26
|
+
|
|
27
|
+
/** String leaves of a value (object keys included, sorted), and whether all of it was read. Numbers,
|
|
28
|
+
* booleans and null carry no words. Objects are read by their own fields (class instances too), maps by
|
|
29
|
+
* their entries, byte arrays as UTF-8. Anything else, or anything past the bounds, leaves `complete`
|
|
30
|
+
* false: content Xtrom could not read is never vouched for. */
|
|
31
|
+
class Reader {
|
|
32
|
+
out: string[] = [];
|
|
33
|
+
complete = true;
|
|
34
|
+
|
|
35
|
+
leaf(s: string): void {
|
|
36
|
+
if (this.out.length >= MAX_STRINGS) this.complete = false;
|
|
37
|
+
else this.out.push(s);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
walk(value: unknown, depth = 0): void {
|
|
41
|
+
if (value === null || value === undefined || typeof value === "boolean" || typeof value === "number" ||
|
|
42
|
+
typeof value === "bigint") return;
|
|
43
|
+
if (depth > MAX_DEPTH || this.out.length >= MAX_STRINGS) { this.complete = false; return; }
|
|
44
|
+
if (typeof value === "string") this.leaf(value);
|
|
45
|
+
else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
46
|
+
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value)
|
|
47
|
+
: new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
48
|
+
this.leaf(new TextDecoder().decode(bytes));
|
|
49
|
+
} else if (Array.isArray(value)) for (const v of value) this.walk(v, depth + 1);
|
|
50
|
+
else if (value instanceof Set) for (const v of [...value].sort((x, y) => (String(x) < String(y) ? -1 : 1))) this.walk(v, depth + 1);
|
|
51
|
+
else if (value instanceof Map) this.walk(Object.fromEntries([...value].map(([k, v]) => [String(k), v])), depth);
|
|
52
|
+
else if (typeof value === "object") {
|
|
53
|
+
const o = value as Record<string, unknown>;
|
|
54
|
+
for (const k of Object.keys(o).sort()) { this.leaf(k); this.walk(o[k], depth + 1); }
|
|
55
|
+
} else this.complete = false; // a function or symbol: nothing readable
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function read(value: unknown): Reader {
|
|
60
|
+
const r = new Reader();
|
|
61
|
+
r.walk(value);
|
|
62
|
+
return r;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isText(leaf: string): boolean {
|
|
66
|
+
const t = leaf.trim();
|
|
67
|
+
if (!t) return false;
|
|
68
|
+
return /\s/.test(t) || DEST_MARKS.some((m) => t.includes(m)) || cp(t) >= LONG_TOKEN;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Normalised pieces of what was stored or recalled; a short piece joins its neighbours (never dropped). */
|
|
72
|
+
export function memoryChunks(value: unknown): string[] {
|
|
73
|
+
return chunks(read(value).out);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function chunks(leaves: string[]): string[] {
|
|
77
|
+
const out: string[] = [];
|
|
78
|
+
for (const leaf of leaves) {
|
|
79
|
+
if (!isText(leaf)) continue;
|
|
80
|
+
const pieces = leaf.split(SPLIT_RX).map((s) => s.replace(WS_RX, " ").trim().toLowerCase()).filter(Boolean);
|
|
81
|
+
const mine: string[] = [];
|
|
82
|
+
let buf = "";
|
|
83
|
+
for (const p of pieces) {
|
|
84
|
+
buf = buf ? buf + " " + p : p;
|
|
85
|
+
if (cp(buf) >= MIN_CHUNK) { mine.push(buf); buf = ""; }
|
|
86
|
+
}
|
|
87
|
+
if (buf) { if (mine.length) mine[mine.length - 1] += " " + buf; else mine.push(buf); }
|
|
88
|
+
out.push(...mine);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function memoryFingerprints(value: unknown): string[] {
|
|
94
|
+
return fingerprints(memoryChunks(value));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function fingerprints(cs: string[]): string[] {
|
|
98
|
+
const seen = new Set<string>();
|
|
99
|
+
for (const c of cs) seen.add(createHash("sha256").update(c, "utf8").digest("hex"));
|
|
100
|
+
return [...seen];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** untrusted if any part was written tainted; trusted if every part was written clean and all of it could
|
|
104
|
+
* be read; else `unknown`. Nothing to read at all → trusted. */
|
|
105
|
+
export function memoryReadTrust(value: unknown, clean: Set<string>, tainted: Set<string>,
|
|
106
|
+
unknown: MemoryTrust = "untrusted"): MemoryTrust {
|
|
107
|
+
const r = read(value);
|
|
108
|
+
const fps = fingerprints(chunks(r.out));
|
|
109
|
+
if (fps.some((f) => tainted.has(f))) return "untrusted";
|
|
110
|
+
if (!r.complete) return unknown;
|
|
111
|
+
if (fps.every((f) => clean.has(f))) return "trusted";
|
|
112
|
+
return unknown;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Fingerprints of what an agent wrote to memory, clean or tainted. Bounded (oldest evicted → unknown);
|
|
116
|
+
* tainted wins over a later clean write of the same content. */
|
|
117
|
+
export class MemoryProvenance {
|
|
118
|
+
maxFingerprints = 50_000;
|
|
119
|
+
protected fp = new Map<string, "clean" | "tainted">();
|
|
120
|
+
|
|
121
|
+
constructor(entries: Record<string, string> = {}) {
|
|
122
|
+
for (const [k, v] of Object.entries(entries)) if ((v === "clean" || v === "tainted") && k.length === 64) this.fp.set(k, v);
|
|
123
|
+
this.evict();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
recordWrite(value: unknown, tainted: boolean): void {
|
|
127
|
+
for (const f of memoryFingerprints(value)) {
|
|
128
|
+
const prev = this.fp.get(f);
|
|
129
|
+
this.fp.delete(f);
|
|
130
|
+
this.fp.set(f, tainted || prev === "tainted" ? "tainted" : "clean");
|
|
131
|
+
}
|
|
132
|
+
this.evict();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
trustOf(value: unknown, unknown: MemoryTrust = "untrusted"): MemoryTrust {
|
|
136
|
+
const clean = new Set<string>(), tainted = new Set<string>();
|
|
137
|
+
for (const [f, s] of this.fp) (s === "clean" ? clean : tainted).add(f);
|
|
138
|
+
return memoryReadTrust(value, clean, tainted, unknown);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
entries(): Record<string, string> { return Object.fromEntries(this.fp); }
|
|
142
|
+
|
|
143
|
+
private evict(): void {
|
|
144
|
+
while (this.fp.size > this.maxFingerprints) this.fp.delete(this.fp.keys().next().value as string);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A private file per agent (~/.xtrom/memory/<agent>.json, 0600): fingerprints only, no content. */
|
|
149
|
+
export class FileMemoryProvenance extends MemoryProvenance {
|
|
150
|
+
readonly path: string;
|
|
151
|
+
private fs: typeof import("node:fs");
|
|
152
|
+
|
|
153
|
+
constructor(path: string, fs: typeof import("node:fs")) {
|
|
154
|
+
let entries: Record<string, string> = {};
|
|
155
|
+
try { entries = JSON.parse(fs.readFileSync(path, "utf8")); } catch { /* new */ }
|
|
156
|
+
super(entries && typeof entries === "object" ? entries : {});
|
|
157
|
+
this.path = path;
|
|
158
|
+
this.fs = fs;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
override recordWrite(value: unknown, tainted: boolean): void {
|
|
162
|
+
super.recordWrite(value, tainted);
|
|
163
|
+
try {
|
|
164
|
+
const dir = this.path.slice(0, this.path.lastIndexOf("/"));
|
|
165
|
+
this.fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
166
|
+
const tmp = this.path + ".tmp";
|
|
167
|
+
this.fs.rmSync(tmp, { force: true }); // created fresh below, owner-only from the first byte
|
|
168
|
+
this.fs.writeFileSync(tmp, JSON.stringify(this.entries()), { mode: 0o600, flag: "wx" });
|
|
169
|
+
this.fs.renameSync(tmp, this.path);
|
|
170
|
+
} catch { /* kept for this process; a later read fails safe to the policy default */ }
|
|
171
|
+
}
|
|
172
|
+
}
|
package/src/reporter.ts
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// DecisionReporter — ships privacy-scrubbed decision METADATA to the control-plane ingest API.
|
|
2
|
+
// Port of xtrom_sdk/reporter.py. Invariants: never blocks or breaks enforcement (bounded queue; a full
|
|
3
|
+
// queue drops, counted in `dropped`); metadata only, never raw argument values; zero deps.
|
|
4
|
+
// Transient failures (network, timeout, 408/425/429/5xx) keep the batch and retry with backoff,
|
|
5
|
+
// honouring Retry-After — the gateway's policy. 401/403 or a redirect pause 5 minutes and keep the
|
|
6
|
+
// batch; any other 4xx drops it. Events carry ids and are written idempotently, so retries never
|
|
7
|
+
// double-count.
|
|
8
|
+
import type { ResultInspection } from "./inspect.ts";
|
|
9
|
+
import { parseWorkspaceMode, type WorkspaceMode } from "./workspace.ts";
|
|
10
|
+
import { directiveVerifierFromEnv } from "./directive.ts";
|
|
11
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
12
|
+
import { hostname } from "node:os";
|
|
13
|
+
import { decisionSignals, type Decision } from "./enforce.ts";
|
|
14
|
+
import { API_VERSION, SDK_VERSION } from "./version.ts";
|
|
15
|
+
|
|
16
|
+
export const INGEST_PATH = "/v1/ingest";
|
|
17
|
+
export const HEARTBEAT_MAX_IDENTITIES = 200;
|
|
18
|
+
const LATENCY_WINDOW = 4096;
|
|
19
|
+
export const BACKOFF_MIN_MS = 2_000;
|
|
20
|
+
export const BACKOFF_MAX_MS = 300_000;
|
|
21
|
+
export const AUTH_PAUSE_MS = 300_000;
|
|
22
|
+
export const RETRY_AFTER_CAP_MS = 3_600_000;
|
|
23
|
+
|
|
24
|
+
export type SendResult = "ok" | "retry" | "pause" | "reject";
|
|
25
|
+
|
|
26
|
+
export function classifyStatus(code: number): SendResult {
|
|
27
|
+
if (code >= 200 && code < 300) return "ok";
|
|
28
|
+
if (code === 401 || code === 403 || (code >= 300 && code < 400)) return "pause";
|
|
29
|
+
if (code === 408 || code === 425 || code === 429 || code >= 500) return "retry";
|
|
30
|
+
return "reject";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Retry-After in seconds → ms, clamped to [1s, 1h]; HTTP-date or junk → null (use backoff). */
|
|
34
|
+
export function retryAfterMs(value: string | null | undefined): number | null {
|
|
35
|
+
if (value == null || !/^\s*\d+(\.\d+)?\s*$/.test(value)) return null;
|
|
36
|
+
return Math.min(RETRY_AFTER_CAP_MS, Math.max(1_000, Number(value) * 1000));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type WireEvent = Record<string, unknown>;
|
|
40
|
+
|
|
41
|
+
export interface ReporterOpts {
|
|
42
|
+
batch?: number;
|
|
43
|
+
intervalMs?: number;
|
|
44
|
+
maxQueue?: number;
|
|
45
|
+
/** Seconds between liveness beats (0 disables). Default 60; first beat on the first flush. */
|
|
46
|
+
heartbeatInterval?: number;
|
|
47
|
+
timeoutMs?: number;
|
|
48
|
+
fetchImpl?: typeof fetch;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isoNow(): string {
|
|
52
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function pct(sorted: number[], p: number): number {
|
|
56
|
+
const k = Math.floor((p / 100) * (sorted.length - 1) + 0.5);
|
|
57
|
+
return sorted[Math.max(0, Math.min(k, sorted.length - 1))];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function instanceId(): string {
|
|
61
|
+
let host = "";
|
|
62
|
+
try { host = hostname(); } catch { /* sandboxed */ }
|
|
63
|
+
const h = host.replace(/[^A-Za-z0-9._:-]/g, "-").slice(0, 40) || "sdk";
|
|
64
|
+
return `${h}-${process.pid}-${randomBytes(3).toString("hex")}`.slice(0, 64);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
68
|
+
|
|
69
|
+
/** The bearer token rides on every request: refuse plaintext HTTP except to this machine. */
|
|
70
|
+
export function requireSecureUrl(url: string): string {
|
|
71
|
+
let u: URL;
|
|
72
|
+
try { u = new URL(String(url ?? "")); } catch { u = new URL("invalid:"); }
|
|
73
|
+
const host = u.hostname.toLowerCase();
|
|
74
|
+
if (u.protocol === "https:" && host) return url;
|
|
75
|
+
if (u.protocol === "http:" && (LOOPBACK.has(host) || host.endsWith(".localhost"))) return url;
|
|
76
|
+
throw new Error("control-plane URL must be https:// (plain http is allowed only for localhost)");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** POST one batch to the ingest API → [result, retryAfterMs]. The single delivery path shared by
|
|
80
|
+
* DecisionReporter and the background shipper, so classification/retry semantics stay identical.
|
|
81
|
+
* `url` is the full ingest URL (base + INGEST_PATH). Never throws — a down control plane classifies
|
|
82
|
+
* as "retry" so the caller keeps the batch. */
|
|
83
|
+
export async function postEvents(url: string, token: string, events: WireEvent[],
|
|
84
|
+
timeoutMs = 5000, fetchImpl: typeof fetch = fetch,
|
|
85
|
+
onWorkspaceMode?: (wm: WorkspaceMode) => void): Promise<[SendResult, number | null]> {
|
|
86
|
+
try {
|
|
87
|
+
const res = await fetchImpl(url, {
|
|
88
|
+
method: "POST",
|
|
89
|
+
headers: {
|
|
90
|
+
"content-type": "application/json",
|
|
91
|
+
authorization: "Bearer " + token,
|
|
92
|
+
"x-xtrom-api-version": API_VERSION,
|
|
93
|
+
},
|
|
94
|
+
body: JSON.stringify({ events }),
|
|
95
|
+
redirect: "manual", // the token never follows a redirect: a 3xx classifies as a pause
|
|
96
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
97
|
+
});
|
|
98
|
+
const result = classifyStatus(res.status);
|
|
99
|
+
if (result === "ok" && onWorkspaceMode) {
|
|
100
|
+
// The workspace mode rides on every accepted answer (a few hundred bytes; capped all the same).
|
|
101
|
+
try {
|
|
102
|
+
const text = (await res.text()).slice(0, 16 * 1024);
|
|
103
|
+
const wm = parseWorkspaceMode(JSON.parse(text), directiveVerifierFromEnv());
|
|
104
|
+
if (wm) onWorkspaceMode(wm);
|
|
105
|
+
} catch { /* an unreadable body leaves the mode as it was */ }
|
|
106
|
+
} else {
|
|
107
|
+
await res.body?.cancel().catch(() => {});
|
|
108
|
+
}
|
|
109
|
+
return [result, result === "retry" ? retryAfterMs(res.headers?.get?.("retry-after")) : null];
|
|
110
|
+
} catch {
|
|
111
|
+
// An unreachable control plane must never affect the agent: keep the batch and retry.
|
|
112
|
+
return ["retry", null];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export class DecisionReporter {
|
|
117
|
+
dropped = 0;
|
|
118
|
+
readonly instanceId = instanceId();
|
|
119
|
+
/** Random per process. Decisions carry it with a `seq` from 1; heartbeats carry `last_seq` and
|
|
120
|
+
* `dropped_total`, so the control plane can tell decisions that never arrived from ones shed. */
|
|
121
|
+
readonly stream = randomBytes(8).toString("hex");
|
|
122
|
+
private seq = 0;
|
|
123
|
+
/** The workspace mode the last accepted batch carried, and when it arrived (epoch ms). */
|
|
124
|
+
private workspace: [WorkspaceMode, number] | null = null;
|
|
125
|
+
private url: string;
|
|
126
|
+
private token: string;
|
|
127
|
+
private q: WireEvent[] = [];
|
|
128
|
+
private batch: number;
|
|
129
|
+
private maxQueue: number;
|
|
130
|
+
private timeoutMs: number;
|
|
131
|
+
private fetchImpl: typeof fetch;
|
|
132
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
133
|
+
private inflight: Promise<void> = Promise.resolve();
|
|
134
|
+
private closed = false;
|
|
135
|
+
private hbEvery: number;
|
|
136
|
+
private hbNext = 0;
|
|
137
|
+
private hbDroppedMark = 0;
|
|
138
|
+
private hbCounts = { allow: 0, step_up: 0, block: 0 };
|
|
139
|
+
private hbIds = new Set<string>();
|
|
140
|
+
private hbIdsTruncated = false;
|
|
141
|
+
private hbLat: number[] = [];
|
|
142
|
+
private hbMode: string | null = null;
|
|
143
|
+
private hbPolicy: string | null = null;
|
|
144
|
+
private attempt = 0;
|
|
145
|
+
private resumeAt = 0;
|
|
146
|
+
|
|
147
|
+
constructor(controlPlaneUrl: string, token: string, opts: ReporterOpts = {}) {
|
|
148
|
+
requireSecureUrl(controlPlaneUrl);
|
|
149
|
+
this.url = controlPlaneUrl.replace(/\/+$/, "") + INGEST_PATH;
|
|
150
|
+
this.token = token;
|
|
151
|
+
this.batch = opts.batch ?? 50;
|
|
152
|
+
this.maxQueue = opts.maxQueue ?? 10_000;
|
|
153
|
+
this.timeoutMs = opts.timeoutMs ?? 5000;
|
|
154
|
+
this.fetchImpl = opts.fetchImpl ?? fetch;
|
|
155
|
+
this.hbEvery = Number(opts.heartbeatInterval ?? 60) || 0;
|
|
156
|
+
const interval = opts.intervalMs ?? 2000;
|
|
157
|
+
if (interval > 0) {
|
|
158
|
+
this.timer = setInterval(() => { void this.tick(); }, interval);
|
|
159
|
+
this.timer.unref?.(); // never keep the agent's process alive
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Enqueue a decision event. Non-blocking: if the queue is full the event is dropped. Events held
|
|
164
|
+
* for retry share the same bound. */
|
|
165
|
+
report(event: WireEvent): void {
|
|
166
|
+
this.seq += 1;
|
|
167
|
+
event = { ...event, stream: this.stream, seq: this.seq };
|
|
168
|
+
if (this.hbEvery > 0) this.observe(event);
|
|
169
|
+
if (this.q.length >= this.maxQueue) { this.dropped += 1; return; }
|
|
170
|
+
this.q.push(event);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private observe(ev: WireEvent): void {
|
|
174
|
+
const v = String(ev.verdict ?? "").toLowerCase() as keyof typeof this.hbCounts;
|
|
175
|
+
if (v in this.hbCounts) this.hbCounts[v] += 1;
|
|
176
|
+
const id = ev.identity;
|
|
177
|
+
if (typeof id === "string" && id && !this.hbIds.has(id)) {
|
|
178
|
+
if (this.hbIds.size < HEARTBEAT_MAX_IDENTITIES) this.hbIds.add(id);
|
|
179
|
+
else this.hbIdsTruncated = true;
|
|
180
|
+
}
|
|
181
|
+
const lat = ev.latency_us;
|
|
182
|
+
if (Number.isInteger(lat) && (lat as number) > 0 && this.hbLat.length < LATENCY_WINDOW) this.hbLat.push(lat as number);
|
|
183
|
+
if (ev.mode === "enforce" || ev.mode === "monitor") this.hbMode = ev.mode;
|
|
184
|
+
if (ev.policy_version) this.hbPolicy = String(ev.policy_version);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Snapshot + reset the window as a signals-v2 heartbeat (sent even with zero traffic). */
|
|
188
|
+
heartbeatEvent(): WireEvent {
|
|
189
|
+
const lat = [...this.hbLat].sort((a, b) => a - b);
|
|
190
|
+
const ev: WireEvent = {
|
|
191
|
+
kind: "heartbeat", mediator: "sdk-ts", mediator_version: SDK_VERSION,
|
|
192
|
+
instance_id: this.instanceId, interval_s: Math.trunc(Math.min(3600, Math.max(10, this.hbEvery))),
|
|
193
|
+
ts: isoNow(), counts: { ...this.hbCounts }, dropped: Math.max(0, this.dropped - this.hbDroppedMark),
|
|
194
|
+
stream: this.stream, last_seq: this.seq, dropped_total: this.dropped,
|
|
195
|
+
};
|
|
196
|
+
const ids = [...this.hbIds].sort();
|
|
197
|
+
if (ids.length) ev.identities = ids;
|
|
198
|
+
if (this.hbIdsTruncated) ev.identities_truncated = true;
|
|
199
|
+
if (lat.length) ev.latency_us = { p50: pct(lat, 50), p95: pct(lat, 95), p99: pct(lat, 99) };
|
|
200
|
+
if (this.hbMode) ev.mode = this.hbMode;
|
|
201
|
+
if (this.hbPolicy) ev.policy_version = this.hbPolicy;
|
|
202
|
+
this.hbDroppedMark = this.dropped;
|
|
203
|
+
this.hbCounts = { allow: 0, step_up: 0, block: 0 };
|
|
204
|
+
this.hbIds = new Set();
|
|
205
|
+
this.hbIdsTruncated = false;
|
|
206
|
+
this.hbLat = [];
|
|
207
|
+
return ev;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private beatDue(): boolean {
|
|
211
|
+
if (this.hbEvery <= 0 || Date.now() < this.hbNext) return false;
|
|
212
|
+
this.hbNext = Date.now() + this.hbEvery * 1000;
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private tick(): Promise<void> {
|
|
217
|
+
// Serialize posts so batches never overlap; errors are swallowed inside post().
|
|
218
|
+
this.inflight = this.inflight.then(async () => {
|
|
219
|
+
if (Date.now() < this.resumeAt) return;
|
|
220
|
+
const batch = this.q.splice(0, this.batch);
|
|
221
|
+
if (this.beatDue()) batch.push(this.heartbeatEvent());
|
|
222
|
+
if (batch.length) await this.post(batch);
|
|
223
|
+
});
|
|
224
|
+
return this.inflight;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async post(batch: WireEvent[]): Promise<void> {
|
|
228
|
+
const [result, wait] = await this.send(batch);
|
|
229
|
+
if (result === "ok") { this.attempt = 0; return; }
|
|
230
|
+
if (result === "reject") { this.dropped += batch.length; return; }
|
|
231
|
+
let delay: number;
|
|
232
|
+
if (result === "pause") delay = AUTH_PAUSE_MS;
|
|
233
|
+
else {
|
|
234
|
+
this.attempt += 1;
|
|
235
|
+
delay = wait ?? Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * 2 ** (this.attempt - 1)) * (0.5 + Math.random() / 2);
|
|
236
|
+
}
|
|
237
|
+
this.resumeAt = Date.now() + delay;
|
|
238
|
+
// Back to the front, in order, within the queue bound (newest events overflow first).
|
|
239
|
+
const room = Math.max(0, this.maxQueue - this.q.length);
|
|
240
|
+
const keep = batch.slice(0, room);
|
|
241
|
+
this.dropped += batch.length - keep.length;
|
|
242
|
+
this.q.unshift(...keep);
|
|
243
|
+
if (this.q.length > this.maxQueue) this.dropped += this.q.splice(this.maxQueue).length;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** [mode, receivedAt] from the control plane, or [null, null] before the first answer. */
|
|
247
|
+
workspaceMode(): [WorkspaceMode | null, number | null] {
|
|
248
|
+
return this.workspace ? [this.workspace[0], this.workspace[1]] : [null, null];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private send(batch: WireEvent[]): Promise<[SendResult, number | null]> {
|
|
252
|
+
return postEvents(this.url, this.token, batch, this.timeoutMs, this.fetchImpl,
|
|
253
|
+
(wm) => {
|
|
254
|
+
// An unverifiable answer carries no `held`: it never releases an agent held before.
|
|
255
|
+
const prev = this.workspace?.[0]?.held;
|
|
256
|
+
this.workspace = [wm.held === undefined && prev ? { ...wm, held: prev } : wm, Date.now()];
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Best-effort drain of everything queued (bounded by the per-request timeout). Makes one attempt
|
|
261
|
+
* even inside a backoff window, and stops at the first failure. */
|
|
262
|
+
async flush(): Promise<void> {
|
|
263
|
+
this.resumeAt = 0;
|
|
264
|
+
while (this.q.length && Date.now() >= this.resumeAt) await this.tick();
|
|
265
|
+
await this.inflight;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Stop the timer and flush (idempotent). */
|
|
269
|
+
async close(): Promise<void> {
|
|
270
|
+
if (this.closed) return;
|
|
271
|
+
this.closed = true;
|
|
272
|
+
if (this.timer) clearInterval(this.timer);
|
|
273
|
+
await this.flush();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const OWNER_RX = /^[A-Za-z0-9._@+-]{1,128}$/;
|
|
278
|
+
const DEVICE_RX = /^[A-Za-z0-9._-]{1,64}$/;
|
|
279
|
+
const CLIENT_RX = /^[a-z0-9][a-z0-9._-]{0,31}$/;
|
|
280
|
+
|
|
281
|
+
export interface Attribution { owner?: string; device?: string; client?: string }
|
|
282
|
+
|
|
283
|
+
/** Human-owner attribution: explicit values, else XTROM_OWNER / XTROM_DEVICE / XTROM_CLIENT.
|
|
284
|
+
* Values that don't fit the control-plane-enforced shapes are dropped. Never guessed from the OS. */
|
|
285
|
+
export function attribution(owner?: string | null, device?: string | null, client?: string | null): Attribution {
|
|
286
|
+
const env = process.env;
|
|
287
|
+
const vals: Array<[keyof Attribution, unknown, RegExp]> = [
|
|
288
|
+
["owner", owner || env.XTROM_OWNER, OWNER_RX],
|
|
289
|
+
["device", device || env.XTROM_DEVICE, DEVICE_RX],
|
|
290
|
+
["client", client || env.XTROM_CLIENT, CLIENT_RX],
|
|
291
|
+
];
|
|
292
|
+
const out: Attribution = {};
|
|
293
|
+
for (const [k, v, rx] of vals) if (typeof v === "string" && rx.test(v)) out[k] = v;
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export interface EventOpts extends Attribution {
|
|
298
|
+
sessionId?: string;
|
|
299
|
+
mode?: string;
|
|
300
|
+
approved?: boolean | null;
|
|
301
|
+
/** guard(..., { source: true }) — the call's OUTPUT is labeled untrusted and taints the session. */
|
|
302
|
+
taintSource?: boolean;
|
|
303
|
+
/** What the call RETURNED (inspectResult) — flags + byte count, never content. */
|
|
304
|
+
result?: ResultInspection | null;
|
|
305
|
+
/** Flags of everything the session had ingested BEFORE this call. */
|
|
306
|
+
contextFlags?: Iterable<string>;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Map a decision → the metadata-only ingest event (signals v2). Never includes argument values. */
|
|
310
|
+
export function decisionEvent(identity: string, d: Decision, opts: EventOpts = {}): WireEvent {
|
|
311
|
+
// The free-text `reason` is intentionally NOT sent — it can interpolate raw argument-derived
|
|
312
|
+
// values (host, amount, exception text, taint origins) that would cross to the control plane.
|
|
313
|
+
// Only the closed-enum `reason_code` leaves; the console renders human text from it.
|
|
314
|
+
const ev: WireEvent = {
|
|
315
|
+
id: randomUUID().replaceAll("-", ""),
|
|
316
|
+
identity,
|
|
317
|
+
action: d.action,
|
|
318
|
+
verdict: String(d.verdict).toUpperCase(),
|
|
319
|
+
layer: d.layer,
|
|
320
|
+
ts: isoNow(),
|
|
321
|
+
mediator: "sdk-ts",
|
|
322
|
+
mediator_version: SDK_VERSION,
|
|
323
|
+
};
|
|
324
|
+
if (d.reasonCode) ev.reason_code = d.reasonCode;
|
|
325
|
+
if (d.policyVersion) ev.policy_version = d.policyVersion;
|
|
326
|
+
if ("sinkClass" in d) Object.assign(ev, decisionSignals(d));
|
|
327
|
+
if (opts.taintSource) ev.taint_source = true;
|
|
328
|
+
if (opts.result) { ev.result_flags = [...opts.result.flags]; ev.result_bytes = opts.result.bytes; }
|
|
329
|
+
const ctx = [...new Set(opts.contextFlags ?? [])].sort();
|
|
330
|
+
if (ctx.length) ev.context_flags = ctx;
|
|
331
|
+
if (opts.sessionId) ev.session_id = opts.sessionId;
|
|
332
|
+
if (opts.mode === "enforce" || opts.mode === "monitor") ev.mode = opts.mode;
|
|
333
|
+
if (ev.verdict === "STEP_UP" && opts.approved !== undefined && opts.approved !== null) ev.approved = !!opts.approved;
|
|
334
|
+
for (const k of ["owner", "device", "client"] as const) if (opts[k]) ev[k] = opts[k];
|
|
335
|
+
return ev;
|
|
336
|
+
}
|