@agent-beam/beam 0.2.23 → 0.2.24

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.
@@ -0,0 +1,108 @@
1
+ // Detection rules for `beam monitor`: attacks against a running application, seen in its logs and
2
+ // HTTP access logs. Separate from the agent-hook catalog in core.ts on purpose -- application logs
3
+ // are full of words like "env", "token" and "production" that would drown those rules -- but a few
4
+ // built-in rules that mean the same thing anywhere (reverse shells, piped remote code, cloud
5
+ // metadata access, prompt injection) are reused as-is. Heuristic, like everything else in Beam.
6
+ import { builtinRulesById } from "./core.js";
7
+ // Trailing boundary for shell commands, so `| id=5` in a log line isn't read as running `id`.
8
+ const END = String.raw `(?=$|[\s;'"&|)\x60])`;
9
+ const commandInjection = new RegExp(String.raw `(?:[;|\x60]|\$\(|&&)\s*(?:id|whoami|uname\s+-a|cat\s+/etc/(?:passwd|shadow)|(?:curl|wget)\s+\S+|nc\s+-\w|bash\s+-[ic]|sh\s+-c|ping\s+-c\s*\d+)${END}`, "i");
10
+ const appRules = [
11
+ { id: "web.jndi_injection", title: "JNDI lookup (Log4Shell-style) injection", severity: "critical", category: "exploit",
12
+ match: s => /\$\{\s*jndi\s*:|\$\{\s*\$\{\s*(?:::-|lower:|upper:|env:)/i.test(s) },
13
+ { id: "web.path_traversal", title: "Path traversal attempt", severity: "high", category: "exploit",
14
+ match: s => /(?:\.\.[/\\]){2,}|\/etc\/(?:passwd|shadow)\b|\bwin\.ini\b|\/proc\/self\/(?:environ|cmdline)/i.test(s) },
15
+ { id: "web.sql_injection", title: "SQL injection attempt", severity: "high", category: "exploit",
16
+ match: s => /\bunion\b[\s(]+(?:all\s+)?select\b|'\s*(?:or|and)\s+'?\d+'?\s*=\s*'?\d+|\b(?:or|and)\s+1\s*=\s*1\b|\b(?:sleep|pg_sleep)\s*\(\s*\d+\s*\)|\bbenchmark\s*\(\s*\d+|\bwaitfor\s+delay\s+'|\binformation_schema\b|\bxp_cmdshell\b/i.test(s) },
17
+ { id: "web.command_injection", title: "Command injection attempt", severity: "high", category: "exploit",
18
+ match: s => commandInjection.test(s) },
19
+ { id: "web.template_injection", title: "Server-side template injection probe", severity: "high", category: "exploit",
20
+ match: s => /\{\{\s*\d+\s*\*\s*\d+\s*\}\}|\$\{\s*\d+\s*\*\s*\d+\s*\}|<%=?\s*\d+\s*\*\s*\d+\s*%>|__class__\.__mro__|__globals__\[|\{\{\s*(?:config|self|request)\.[a-z_]/i.test(s) },
21
+ { id: "web.webshell", title: "Web shell access", severity: "high", category: "persistence",
22
+ match: s => /\/(?:c99|r57|wso|b374k|webshell|cmd|shell)\.(?:php|jsp|aspx?)\b|[?&](?:cmd|exec|command)=(?:whoami|id|ls|uname|cat)\b/i.test(s) },
23
+ { id: "web.deserialization", title: "Serialized object payload", severity: "high", category: "exploit",
24
+ match: s => /\brO0AB[A-Za-z0-9+/=]{8,}|\bO:\d+:"[A-Za-z_\\]+":\d+:\{/.test(s) },
25
+ { id: "app.secret_in_log", title: "Credential written to logs", severity: "high", category: "secrets",
26
+ match: (_s, raw) => /-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9_]{30,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[A-Z0-9]{16}|xox[baprs]-[\w-]{10,}|AIza[0-9A-Za-z_-]{35})\b|\bauthorization:\s*bearer\s+[A-Za-z0-9._~+/-]{20,}/i.test(raw) },
27
+ { id: "web.xss", title: "Cross-site scripting attempt", severity: "medium", category: "exploit",
28
+ match: s => /<script[\s>]|javascript:\s*[a-z(]|<(?:img|svg|body|iframe)\b[^>]{0,200}\son(?:error|load)\s*=|\bdocument\.cookie\b/i.test(s) },
29
+ { id: "web.prototype_pollution", title: "Prototype pollution attempt", severity: "medium", category: "exploit",
30
+ match: s => /\b__proto__\b\s*[\]["'=:.]|constructor\s*\[\s*["']?prototype/i.test(s) },
31
+ { id: "web.sensitive_file_probe", title: "Probe for secrets or config files", severity: "medium", category: "recon", sources: ["http"],
32
+ match: s => /\/(?:\.env(?:\.[\w-]+)?|\.git\/(?:config|HEAD)|\.aws\/credentials|\.ssh\/id_\w+|wp-config\.php(?:\.bak)?|\.htpasswd|server-status|actuator\/(?:env|heapdump)|\.DS_Store)(?=[\s?"'#]|$)/i.test(s) },
33
+ { id: "web.scanner", title: "Known attack tool", severity: "medium", category: "recon", sources: ["http"],
34
+ match: s => /\b(?:sqlmap|nikto|nuclei|masscan|zgrab|acunetix|nessus|wpscan|dirbuster|gobuster|feroxbuster|ffuf|hydra|openvas|commix|xsstrike)\b/i.test(s) },
35
+ ];
36
+ const sharedRules = builtinRulesById(["network.reverse-shell", "execution.remote", "execution.obfuscated", "network.metadata", "instructions.override"])
37
+ .map(r => ({ id: r.id, title: r.title, severity: r.severity === "info" ? "medium" : r.severity, category: r.category, match: (s) => r.match(s) }));
38
+ export const monitorRules = [...appRules, ...sharedRules];
39
+ const HTTP_LINE = /"(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|CONNECT|TRACE) \S+ HTTP\/[\d.]+"|^\S+ \S+ \S+ \[[^\]]+\] "|"(?:method|http_method|request_method)"\s*:\s*"[A-Z]+"/;
40
+ export function lineSource(line) {
41
+ return HTTP_LINE.test(line) ? "http" : "log";
42
+ }
43
+ function percentDecode(s) {
44
+ try {
45
+ return decodeURIComponent(s);
46
+ }
47
+ catch {
48
+ return s.replace(/%[0-9a-f]{2}/gi, m => String.fromCharCode(parseInt(m.slice(1), 16)));
49
+ }
50
+ }
51
+ /** URL-decodes up to twice so `%252e%252e%252f` (double-encoded `../`) is matched too. */
52
+ export function decodeForMatch(line) {
53
+ let s = line.length > 16_384 ? line.slice(0, 16_384) : line;
54
+ for (let i = 0; i < 2; i++) {
55
+ const next = percentDecode(s.replace(/\+/g, " "));
56
+ if (next === s)
57
+ break;
58
+ s = next;
59
+ }
60
+ return s;
61
+ }
62
+ export function matchLine(line, source = lineSource(line)) {
63
+ const decoded = decodeForMatch(line);
64
+ const raw = line.length > 16_384 ? line.slice(0, 16_384) : line;
65
+ return monitorRules.filter(r => (!r.sources || r.sources.includes(source)) && r.match(decoded, raw));
66
+ }
67
+ /**
68
+ * Redaction for evidence that leaves the machine. Unlike the agent-hook redaction it keeps query
69
+ * strings -- for an access log the query usually *is* the attack -- but removes credentials,
70
+ * bearer tokens, URL userinfo, email addresses and the policy's custom detector matches.
71
+ */
72
+ export function redactLine(line, custom = []) {
73
+ let out = line.slice(0, 4000)
74
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g, "[REDACTED PRIVATE KEY]")
75
+ .replace(/\b(?:sk-(?:proj-|ant-)?[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|xox[baprs]-[\w-]{10,}|AIza[0-9A-Za-z_-]{35})\b/g, "[REDACTED TOKEN]")
76
+ .replace(/(bearer\s+)[A-Za-z0-9._~+/-]{8,}/gi, "$1[REDACTED]")
77
+ .replace(/(\b(?:[\w-]*(?:api[_-]?key|token|secret|password|passwd|pwd|authorization|session|cookie)[\w-]*)["']?\s*[:=]\s*)["']?[^\s,"';&}\]]+/gi, "$1[REDACTED]")
78
+ .replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[REDACTED]@")
79
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, "[EMAIL]");
80
+ for (const detector of custom) {
81
+ try {
82
+ out = out.replace(new RegExp(detector.pattern, "g"), detector.replacement);
83
+ }
84
+ catch { /* reported by policy validation */ }
85
+ }
86
+ return out.slice(0, 600);
87
+ }
88
+ // JSON access logs (Railway, Vercel, Caddy, ALB/CloudFront exports, app loggers) name the client field.
89
+ const JSON_CLIENT_IP = /"(?:srcIp|src_ip|clientIp|client_ip|remoteAddr|remote_addr|remoteIp|remote_ip|ip|client|x_forwarded_for|xForwardedFor|http_x_forwarded_for)"\s*:\s*"\[?([0-9a-fA-F:.]{3,45})/;
90
+ const LEADING_IP = /^\[?((?:\d{1,3}\.){3}\d{1,3}|[0-9a-fA-F]*:[0-9a-fA-F:]+)\]?\s/;
91
+ // Not preceded by a word character, "/" or "." so version strings like "Chrome/120.0.0.0" aren't read as addresses.
92
+ const BARE_IPV4 = /(?<![\w/.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])/;
93
+ /**
94
+ * The client address in an access-log line: a named field in JSON logs, the first token in
95
+ * nginx/Apache/Caddy common log format, otherwise the first standalone IPv4 address.
96
+ */
97
+ export function clientIp(line) {
98
+ return line.match(JSON_CLIENT_IP)?.[1] ?? line.match(LEADING_IP)?.[1] ?? line.match(BARE_IPV4)?.[0];
99
+ }
100
+ const AUTH_PATH = /\/(?:login|signin|sign-in|auth|oauth|token|session|api\/v\d+\/auth|wp-login\.php|admin)\b/i;
101
+ const AUTH_FAIL_TEXT = /\b(?:login|authentication|auth|sign[- ]?in)\s+(?:failed|failure|denied)|\binvalid\s+(?:password|credentials|username or password|api key|token)|\bfailed\s+password\b|\bincorrect\s+password\b|\bunauthori[sz]ed\b/i;
102
+ /** A failed sign-in: a 401/403 on an auth path in an access log, or an app's own "login failed" line. */
103
+ export function isAuthFailure(line, source) {
104
+ if (source === "http")
105
+ return (/"\s(?:401|403)\s/.test(line) || /"(?:status|httpStatus|status_code|statusCode|response_status)"\s*:\s*"?(?:401|403)\b/.test(line)) && AUTH_PATH.test(line);
106
+ return AUTH_FAIL_TEXT.test(line);
107
+ }
108
+ //# sourceMappingURL=monitor-rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitor-rules.js","sourceRoot":"","sources":["../src/monitor-rules.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,mGAAmG;AACnG,mGAAmG;AACnG,6FAA6F;AAC7F,gGAAgG;AAChG,OAAO,EAAE,gBAAgB,EAAqB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B;IAC5D,IAAI,MAAM,KAAK,MAAM;QAAE,OAAO,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,sFAAsF,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3L,OAAO,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC"}
@@ -0,0 +1,72 @@
1
+ import { type MonitorFinding, type MonitorLevel, type MonitorSeverity, type Vulnerability } from "./monitor-client.js";
2
+ import type { CustomDetector } from "./data-detectors.js";
3
+ /** light: critical only · standard: high and up · strict: medium and up (same thresholds as the server). */
4
+ export declare const meetsLevel: (severity: MonitorSeverity, level: MonitorLevel) => boolean;
5
+ export declare const DEDUPE_WINDOW_MS: Record<MonitorLevel, number>;
6
+ export declare const BRUTE_FORCE_THRESHOLD: Record<MonitorLevel, number>;
7
+ export declare const MAX_NEW_FINDINGS_PER_10_MIN = 200;
8
+ export type SendOutcome = "sent" | "retry" | "drop";
9
+ export interface PipelineOptions {
10
+ /** The active level, or null while capture is off (not enabled, or the allowance is spent). */
11
+ level: () => MonitorLevel | null;
12
+ customDetectors?: () => CustomDetector[];
13
+ now?: () => number;
14
+ }
15
+ export declare class MonitorPipeline {
16
+ private readonly opts;
17
+ private seen;
18
+ private queue;
19
+ private queued;
20
+ private authFailures;
21
+ private floodBucket;
22
+ private floodCount;
23
+ private suppressed;
24
+ constructor(opts: PipelineOptions);
25
+ private now;
26
+ get pending(): MonitorFinding[];
27
+ /** Matches one line and queues any findings at or above the level. Returns the rule ids raised. */
28
+ ingestLine(line: string, file?: string): string[];
29
+ /** Queues a finding produced elsewhere (dependency checks) under its own stable id, once. */
30
+ addFinding(finding: MonitorFinding): boolean;
31
+ private raise;
32
+ private emitSuppressed;
33
+ private enqueue;
34
+ /** Sends queued findings in batches; a "retry" outcome keeps the batch for the next flush. */
35
+ flush(send: (batch: MonitorFinding[]) => Promise<SendOutcome>): Promise<void>;
36
+ }
37
+ /** Follows a log file like `tail -F`: survives rotation (new inode) and truncation (copytruncate). */
38
+ export declare class FileTailer {
39
+ private readonly path;
40
+ private readonly onLine;
41
+ private readonly fromStart;
42
+ private offset;
43
+ private ino;
44
+ private tracking;
45
+ private firstPoll;
46
+ private partial;
47
+ private decoder;
48
+ private signature;
49
+ private timer;
50
+ private busy;
51
+ constructor(path: string, onLine: (line: string) => void, fromStart?: boolean);
52
+ start(intervalMs?: number): void;
53
+ stop(): void;
54
+ private reset;
55
+ poll(): Promise<void>;
56
+ private signatureHolds;
57
+ }
58
+ /** A dependency vulnerability as a monitor finding. CISA KEV (exploited in the wild) is raised to critical. */
59
+ export declare function vulnerabilityFinding(v: Vulnerability): MonitorFinding;
60
+ export interface MonitorOptions {
61
+ files?: string[];
62
+ stdin?: boolean;
63
+ /** Pass stdin lines through to stdout so piping an app into beam doesn't swallow its output. */
64
+ echo?: boolean;
65
+ /** App directory whose lockfiles are checked for known vulnerabilities at start and daily. */
66
+ app?: string;
67
+ fromStart?: boolean;
68
+ /** Keep waiting while App monitoring is off in the dashboard (default) instead of exiting. */
69
+ wait?: boolean;
70
+ }
71
+ export declare function runMonitor(options: MonitorOptions, log?: (message: string) => void): Promise<void>;
72
+ export declare function monitorStatus(write?: (line: string) => void): Promise<number>;
@@ -0,0 +1,459 @@
1
+ // `beam monitor`: 24x7 watch over a running application's logs and traffic. Lines are matched
2
+ // against monitor-rules.ts on this machine; only redacted, deduplicated findings are sent to the
3
+ // workspace, which stores them, meters them and delivers them to the workspace's webhooks.
4
+ //
5
+ // It never blocks or alters the application: it reads log files (or a pipe it echoes straight
6
+ // through) and does nothing else to the app. It is also inert until the workspace turns App
7
+ // monitoring on in the dashboard -- before that, and whenever it is turned off again or the
8
+ // monthly allowance runs out, lines are read and discarded.
9
+ import { createHash } from "node:crypto";
10
+ import { open } from "node:fs/promises";
11
+ import { resolve } from "node:path";
12
+ import { createInterface } from "node:readline";
13
+ import { StringDecoder } from "node:string_decoder";
14
+ import { readIdentity } from "./enroll.js";
15
+ import { readPolicy } from "./policy.js";
16
+ import { readInstalledPackages } from "./lockfiles.js";
17
+ import { checkPackages, fetchMonitorConfig, sendFindings, } from "./monitor-client.js";
18
+ import { clientIp, isAuthFailure, lineSource, matchLine, redactLine } from "./monitor-rules.js";
19
+ import { judgeWithOwnLlm, ownLlmConfig } from "./monitor-llm.js";
20
+ const RANK = { critical: 3, high: 2, medium: 1, low: 0 };
21
+ const MIN_RANK = { light: 3, standard: 2, strict: 1 };
22
+ /** light: critical only · standard: high and up · strict: medium and up (same thresholds as the server). */
23
+ export const meetsLevel = (severity, level) => RANK[severity] >= MIN_RANK[level];
24
+ // One finding absorbs repeats (its `count` goes up) for this long before a new one is raised.
25
+ export const DEDUPE_WINDOW_MS = { light: 60 * 60_000, standard: 15 * 60_000, strict: 5 * 60_000 };
26
+ // Failed sign-ins from one address within five minutes before it counts as brute forcing.
27
+ export const BRUTE_FORCE_THRESHOLD = { light: 50, standard: 20, strict: 10 };
28
+ const BRUTE_FORCE_WINDOW_MS = 5 * 60_000;
29
+ // A scan or a log loop can match thousands of distinct lines; past this many new findings in ten
30
+ // minutes the rest are folded into one summary finding so a flood can't spend the month's allowance.
31
+ export const MAX_NEW_FINDINGS_PER_10_MIN = 200;
32
+ const FLOOD_WINDOW_MS = 10 * 60_000;
33
+ const MAX_QUEUE = 1000;
34
+ const BATCH_SIZE = 100;
35
+ /** Groups lines that differ only in ids, numbers, addresses or timestamps. */
36
+ function normalizeForGrouping(line) {
37
+ return line.toLowerCase()
38
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, "<ip>")
39
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, "<id>")
40
+ .replace(/\b[0-9a-f]{16,}\b/g, "<hex>")
41
+ .replace(/\d+/g, "0")
42
+ .replace(/\s+/g, " ")
43
+ .slice(0, 300);
44
+ }
45
+ export class MonitorPipeline {
46
+ opts;
47
+ seen = new Map();
48
+ queue = [];
49
+ queued = new Set();
50
+ authFailures = new Map();
51
+ floodBucket = -1;
52
+ floodCount = 0;
53
+ suppressed = null;
54
+ constructor(opts) {
55
+ this.opts = opts;
56
+ }
57
+ now() { return this.opts.now?.() ?? Date.now(); }
58
+ get pending() { return [...this.queue]; }
59
+ /** Matches one line and queues any findings at or above the level. Returns the rule ids raised. */
60
+ ingestLine(line, file) {
61
+ const level = this.opts.level();
62
+ if (!level || !line.trim())
63
+ return [];
64
+ const custom = this.opts.customDetectors?.() ?? [];
65
+ const source = lineSource(line);
66
+ const ip = source === "http" ? clientIp(line) : undefined;
67
+ const raised = [];
68
+ for (const rule of matchLine(line, source)) {
69
+ if (!meetsLevel(rule.severity, level))
70
+ continue;
71
+ // Traffic groups by client address (one scan = one finding); app logs group by line shape.
72
+ this.raise(level, ip ?? normalizeForGrouping(line), {
73
+ ruleId: rule.id, title: ip ? `${rule.title} from ${ip}` : rule.title, severity: rule.severity,
74
+ category: rule.category, source, file, evidence: redactLine(line, custom),
75
+ });
76
+ raised.push(rule.id);
77
+ }
78
+ if (isAuthFailure(line, source) && meetsLevel("high", level)) {
79
+ const key = clientIp(line) ?? "unknown address";
80
+ const now = this.now();
81
+ const recent = (this.authFailures.get(key) ?? []).filter(t => now - t < BRUTE_FORCE_WINDOW_MS);
82
+ recent.push(now);
83
+ this.authFailures.set(key, recent);
84
+ if (this.authFailures.size > 10_000)
85
+ this.authFailures.delete(this.authFailures.keys().next().value);
86
+ if (recent.length >= BRUTE_FORCE_THRESHOLD[level]) {
87
+ this.raise(level, key, {
88
+ ruleId: "app.auth_bruteforce", title: `Repeated failed sign-ins from ${key}`, severity: "high", category: "recon",
89
+ source, file, evidence: `${recent.length} failures in 5 minutes. Latest: ${redactLine(line, custom)}`.slice(0, 600),
90
+ });
91
+ raised.push("app.auth_bruteforce");
92
+ }
93
+ }
94
+ return raised;
95
+ }
96
+ /** Queues a finding produced elsewhere (dependency checks) under its own stable id, once. */
97
+ addFinding(finding) {
98
+ const level = this.opts.level();
99
+ if (!level || !meetsLevel(finding.severity, level) || this.queued.has(finding.id))
100
+ return false;
101
+ this.queued.add(finding.id);
102
+ this.enqueue(finding);
103
+ return true;
104
+ }
105
+ raise(level, groupKey, partial) {
106
+ const now = this.now();
107
+ const bucket = Math.floor(now / DEDUPE_WINDOW_MS[level]);
108
+ const fp = createHash("sha256").update(`${partial.ruleId}\0${groupKey}`).digest("hex").slice(0, 24);
109
+ const existing = this.seen.get(fp);
110
+ if (existing && existing.bucket === bucket) {
111
+ existing.finding.count++; // still queued: the batch carries the new count
112
+ return;
113
+ }
114
+ const flood = Math.floor(now / FLOOD_WINDOW_MS);
115
+ if (flood !== this.floodBucket) {
116
+ this.emitSuppressed();
117
+ this.floodBucket = flood;
118
+ this.floodCount = 0;
119
+ }
120
+ if (this.floodCount >= MAX_NEW_FINDINGS_PER_10_MIN) {
121
+ const worst = this.suppressed && RANK[this.suppressed.severity] >= RANK[partial.severity] ? this.suppressed.severity : partial.severity;
122
+ this.suppressed = { count: (this.suppressed?.count ?? 0) + 1, severity: worst };
123
+ return;
124
+ }
125
+ this.floodCount++;
126
+ const finding = { id: `${fp}-${bucket}`, ...partial, count: 1, firstSeen: new Date(now).toISOString() };
127
+ this.seen.set(fp, { bucket, finding, at: now });
128
+ this.enqueue(finding);
129
+ }
130
+ emitSuppressed() {
131
+ if (!this.suppressed)
132
+ return;
133
+ const { count, severity } = this.suppressed;
134
+ this.suppressed = null;
135
+ this.enqueue({
136
+ id: `flood-${this.floodBucket}`, ruleId: "beam.monitor.flood", title: "Too many findings to send individually", severity,
137
+ category: "integrity", source: "log", count,
138
+ evidence: `${count} more findings within 10 minutes were not sent one by one, to protect the monthly allowance. Check this server's logs.`,
139
+ firstSeen: new Date(this.floodBucket * FLOOD_WINDOW_MS).toISOString(),
140
+ });
141
+ }
142
+ enqueue(finding) {
143
+ if (this.queue.length >= MAX_QUEUE) {
144
+ // Full (usually: the workspace is unreachable). Make room by dropping the least severe, oldest.
145
+ let drop = 0;
146
+ for (let i = 1; i < this.queue.length; i++)
147
+ if (RANK[this.queue[i].severity] < RANK[this.queue[drop].severity])
148
+ drop = i;
149
+ this.queue.splice(drop, 1);
150
+ }
151
+ this.queue.push(finding);
152
+ }
153
+ /** Sends queued findings in batches; a "retry" outcome keeps the batch for the next flush. */
154
+ async flush(send) {
155
+ if (this.suppressed && Math.floor(this.now() / FLOOD_WINDOW_MS) !== this.floodBucket)
156
+ this.emitSuppressed();
157
+ while (this.queue.length) {
158
+ const batch = this.queue.splice(0, BATCH_SIZE);
159
+ if ((await send(batch)) === "retry") {
160
+ this.queue.unshift(...batch);
161
+ break;
162
+ }
163
+ }
164
+ const cutoff = this.now() - 2 * DEDUPE_WINDOW_MS.light;
165
+ for (const [fp, entry] of this.seen)
166
+ if (entry.at < cutoff)
167
+ this.seen.delete(fp);
168
+ }
169
+ }
170
+ /** Follows a log file like `tail -F`: survives rotation (new inode) and truncation (copytruncate). */
171
+ export class FileTailer {
172
+ path;
173
+ onLine;
174
+ fromStart;
175
+ offset = 0;
176
+ ino = -1;
177
+ tracking = false;
178
+ firstPoll = true;
179
+ partial = "";
180
+ decoder = new StringDecoder("utf8");
181
+ // The last bytes read. If they're no longer at the same position, the file was truncated and
182
+ // rewritten past our offset between polls (copytruncate under load), which size alone can't show.
183
+ signature = Buffer.alloc(0);
184
+ timer;
185
+ busy = false;
186
+ constructor(path, onLine, fromStart = false) {
187
+ this.path = path;
188
+ this.onLine = onLine;
189
+ this.fromStart = fromStart;
190
+ }
191
+ start(intervalMs = 1000) {
192
+ void this.poll();
193
+ this.timer = setInterval(() => void this.poll(), intervalMs);
194
+ }
195
+ stop() { if (this.timer)
196
+ clearInterval(this.timer); }
197
+ reset(offset, ino) {
198
+ this.offset = offset;
199
+ this.ino = ino;
200
+ this.partial = "";
201
+ this.decoder = new StringDecoder("utf8");
202
+ this.signature = Buffer.alloc(0);
203
+ }
204
+ async poll() {
205
+ if (this.busy)
206
+ return;
207
+ this.busy = true;
208
+ let handle;
209
+ try {
210
+ try {
211
+ handle = await open(this.path, "r");
212
+ }
213
+ catch {
214
+ this.firstPoll = false;
215
+ return;
216
+ } // not there (yet): keep waiting
217
+ const info = await handle.stat();
218
+ if (!this.tracking) {
219
+ // Existing file at start: begin at the end, like tail. A file that appears later is read whole.
220
+ this.reset(this.firstPoll && !this.fromStart ? info.size : 0, info.ino);
221
+ this.tracking = true;
222
+ const keep = Math.min(SIGNATURE_BYTES, this.offset);
223
+ if (keep)
224
+ this.signature = await readAt(handle, this.offset - keep, keep);
225
+ }
226
+ else if (info.ino !== this.ino || info.size < this.offset || !(await this.signatureHolds(handle))) {
227
+ this.reset(0, info.ino);
228
+ }
229
+ this.firstPoll = false;
230
+ while (info.size > this.offset) {
231
+ const chunk = await readAt(handle, this.offset, Math.min(info.size - this.offset, 4 * 1024 * 1024));
232
+ if (!chunk.length)
233
+ break;
234
+ this.offset += chunk.length;
235
+ this.signature = Buffer.concat([this.signature, chunk.subarray(-SIGNATURE_BYTES)]).subarray(-SIGNATURE_BYTES);
236
+ const lines = (this.partial + this.decoder.write(chunk)).split(/\r?\n/);
237
+ this.partial = lines.pop() ?? "";
238
+ if (this.partial.length > 65_536) {
239
+ lines.push(this.partial.slice(0, 65_536));
240
+ this.partial = "";
241
+ }
242
+ for (const line of lines)
243
+ this.onLine(line);
244
+ }
245
+ }
246
+ finally {
247
+ await handle?.close();
248
+ this.busy = false;
249
+ }
250
+ }
251
+ async signatureHolds(handle) {
252
+ if (!this.signature.length)
253
+ return true;
254
+ return (await readAt(handle, this.offset - this.signature.length, this.signature.length)).equals(this.signature);
255
+ }
256
+ }
257
+ const SIGNATURE_BYTES = 64;
258
+ async function readAt(handle, position, length) {
259
+ const buffer = Buffer.alloc(length);
260
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
261
+ return buffer.subarray(0, bytesRead);
262
+ }
263
+ const SEVERITIES = ["critical", "high", "medium", "low"];
264
+ /** A dependency vulnerability as a monitor finding. CISA KEV (exploited in the wild) is raised to critical. */
265
+ export function vulnerabilityFinding(v) {
266
+ const severity = v.kev ? "critical" : SEVERITIES.includes(v.severity) ? v.severity : "medium";
267
+ const id = createHash("sha256").update(`${v.id}\0${v.ecosystem}\0${v.name}\0${v.version}`).digest("hex").slice(0, 24);
268
+ return {
269
+ id: `cve-${id}`, ruleId: v.id, title: `${v.id} in ${v.name} ${v.version}${v.kev ? " (actively exploited)" : ""}`, severity,
270
+ category: "cve", source: "cve", file: v.files[0], count: 1, firstSeen: new Date().toISOString(),
271
+ evidence: `${v.name} ${v.version} (${v.ecosystem}) is in the affected range ${v.vulnerable}; ${v.patched ? `fixed in ${v.patched}` : "no fixed version yet"}. ${v.title} ${v.url}`.slice(0, 600),
272
+ };
273
+ }
274
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
275
+ export async function runMonitor(options, log = m => console.error(`[beam monitor] ${m}`)) {
276
+ const files = (options.files ?? []).map(f => resolve(f));
277
+ const appDir = options.app ? resolve(options.app) : undefined;
278
+ if (!files.length && !options.stdin && !appDir)
279
+ throw new Error("Tell beam monitor what to watch: --file <path> (repeatable) for log files, --stdin to read piped output, and/or --app <dir> for dependency checks.");
280
+ const identity = await readIdentity();
281
+ if (!identity)
282
+ throw new Error("Connect this server to your Beam workspace first: run 'beam connect'. App monitoring is then turned on for the workspace in the dashboard.");
283
+ const custom = (await readPolicy())?.rules.customDetectors ?? [];
284
+ const ownLlm = ownLlmConfig();
285
+ let config = null;
286
+ let lastRefresh = 0;
287
+ let pausedUntil = 0;
288
+ let offNotice = false;
289
+ let fatal = null;
290
+ const refresh = async () => {
291
+ lastRefresh = Date.now();
292
+ const result = await fetchMonitorConfig(identity);
293
+ if (result.ok) {
294
+ if (!config) {
295
+ log(`App monitoring is on (${result.config.level} level). Findings go to your workspace${result.config.webhooks ? ` and ${result.config.webhooks} webhook${result.config.webhooks === 1 ? "" : "s"}` : ""}.`);
296
+ log(ownLlm
297
+ ? `LLM checks: your own model, ${ownLlm.model} at ${new URL(ownLlm.baseUrl).host}.`
298
+ : `LLM checks: ${result.config.llm ? "Beam's model (set in the dashboard)" : "off"}.`);
299
+ }
300
+ else if (config.level !== result.config.level)
301
+ log(`Level changed to ${result.config.level}.`);
302
+ config = result.config;
303
+ offNotice = false;
304
+ return;
305
+ }
306
+ if (result.status === "disabled") {
307
+ if (!offNotice)
308
+ log(`${result.message}${options.wait === false ? "" : " Nothing is captured until then; checking again every minute."}`);
309
+ offNotice = true;
310
+ config = null;
311
+ return;
312
+ }
313
+ if (result.status === "revoked" || result.status === "unsupported")
314
+ throw new Error(result.message);
315
+ log(`${result.message} Retrying.`); // unreachable: keep the last known settings
316
+ };
317
+ await refresh();
318
+ while (!config) {
319
+ if (options.wait === false)
320
+ throw new Error("App monitoring is not on for this workspace.");
321
+ await sleep(60_000);
322
+ await refresh();
323
+ }
324
+ const pipeline = new MonitorPipeline({
325
+ level: () => (config && Date.now() >= pausedUntil ? config.level : null),
326
+ customDetectors: () => custom,
327
+ });
328
+ const send = async (batch) => {
329
+ if (ownLlm && config)
330
+ await judgeWithOwnLlm(batch, config.level, ownLlm);
331
+ const result = await sendFindings(identity, batch);
332
+ if (result.ok)
333
+ return "sent";
334
+ if (result.status === "disabled") {
335
+ log(`${result.message} Capture paused.`);
336
+ config = null;
337
+ offNotice = true;
338
+ return "drop";
339
+ }
340
+ if (result.status === "quota") {
341
+ pausedUntil = result.resetAt ? Date.parse(result.resetAt) : Date.now() + 60 * 60_000;
342
+ log(`${result.message} Capture paused until then.`);
343
+ return "drop";
344
+ }
345
+ if (result.status === "revoked" || result.status === "unsupported") {
346
+ fatal = new Error(result.message);
347
+ return "drop";
348
+ }
349
+ return "retry";
350
+ };
351
+ const checkDependencies = async () => {
352
+ if (!appDir || !config)
353
+ return;
354
+ const scan = await readInstalledPackages(appDir);
355
+ if (!scan.packages.length) {
356
+ log(`No pinned dependencies found under ${appDir}; skipping the dependency check.`);
357
+ return;
358
+ }
359
+ const result = await checkPackages(identity, scan.packages);
360
+ if (!result.ok) {
361
+ log(`Dependency check skipped: ${result.message}`);
362
+ return;
363
+ }
364
+ const { vulnerabilities, checked } = result.result;
365
+ log(`Dependency check: ${vulnerabilities.length} known vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"} in ${checked} packages under ${appDir}.`);
366
+ for (const v of vulnerabilities)
367
+ pipeline.addFinding(vulnerabilityFinding(v));
368
+ };
369
+ const tailers = files.map(path => new FileTailer(path, line => pipeline.ingestLine(line, path), options.fromStart));
370
+ for (const tailer of tailers)
371
+ tailer.start();
372
+ if (files.length)
373
+ log(`Watching ${files.join(", ")}.`);
374
+ let flushing = false;
375
+ const flush = async () => {
376
+ if (flushing)
377
+ return;
378
+ flushing = true;
379
+ try {
380
+ await pipeline.flush(send);
381
+ }
382
+ finally {
383
+ flushing = false;
384
+ }
385
+ };
386
+ const timers = [
387
+ setInterval(() => void flush(), 5_000),
388
+ setInterval(() => {
389
+ if (Date.now() - lastRefresh >= (config ? 5 * 60_000 : 60_000))
390
+ void refresh().catch(e => { fatal = e; });
391
+ }, 15_000),
392
+ setInterval(() => void checkDependencies(), 24 * 60 * 60_000),
393
+ ];
394
+ void checkDependencies();
395
+ let stdinDone = !options.stdin;
396
+ if (options.stdin) {
397
+ if (options.echo !== false)
398
+ process.stdout.on("error", () => { });
399
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
400
+ lines.on("line", line => {
401
+ if (options.echo !== false)
402
+ process.stdout.write(`${line}\n`);
403
+ pipeline.ingestLine(line, "stdin");
404
+ });
405
+ lines.on("close", () => { stdinDone = true; });
406
+ }
407
+ let stopping = false;
408
+ const stop = () => { stopping = true; };
409
+ process.once("SIGINT", stop);
410
+ process.once("SIGTERM", stop);
411
+ // Runs until stopped or revoked; when reading only a pipe, also until the piped app exits.
412
+ const endsWithStdin = Boolean(options.stdin) && !files.length;
413
+ while (!stopping && !fatal && !(endsWithStdin && stdinDone))
414
+ await sleep(250);
415
+ for (const timer of timers)
416
+ clearInterval(timer);
417
+ for (const tailer of tailers)
418
+ tailer.stop();
419
+ process.removeListener("SIGINT", stop);
420
+ process.removeListener("SIGTERM", stop);
421
+ // Last flush, bounded so a dead network can't hold up shutdown.
422
+ let giveUp;
423
+ await Promise.race([flush(), new Promise(r => { giveUp = setTimeout(r, 5_000); })]);
424
+ clearTimeout(giveUp);
425
+ if (fatal)
426
+ throw fatal;
427
+ }
428
+ const fmt = (n) => (n >= 2_147_483_647 ? "unlimited" : n.toLocaleString("en-US"));
429
+ export async function monitorStatus(write = console.log) {
430
+ const identity = await readIdentity();
431
+ if (!identity) {
432
+ write("Not connected to a Beam workspace. Run 'beam connect' first.");
433
+ return 1;
434
+ }
435
+ const result = await fetchMonitorConfig(identity);
436
+ if (!result.ok) {
437
+ write(result.status === "disabled" ? `App monitoring: off\n${result.message}` : result.message);
438
+ return result.status === "disabled" ? 0 : 1;
439
+ }
440
+ const { level, llm, webhooks, usage, limits, resetAt, settingsUrl } = result.config;
441
+ let own = null;
442
+ let ownError = "";
443
+ try {
444
+ own = ownLlmConfig();
445
+ }
446
+ catch (error) {
447
+ ownError = error.message;
448
+ }
449
+ write([
450
+ "App monitoring: on",
451
+ `Level: ${level}`,
452
+ `LLM checks: ${own ? `your own model, ${own.model} at ${new URL(own.baseUrl).host}` : ownError ? `misconfigured: ${ownError}` : llm ? "Beam's model" : "off"}`,
453
+ `Webhooks: ${webhooks}`,
454
+ `This month: ${fmt(usage.findings)} / ${fmt(limits.findings)} findings · ${fmt(usage.cveChecks)} / ${fmt(limits.cveChecks)} dependency checks · ${fmt(usage.llmChecks)} / ${fmt(limits.llmChecks)} LLM checks (resets ${resetAt.slice(0, 10)})`,
455
+ `Settings: ${settingsUrl}`,
456
+ ].join("\n"));
457
+ return 0;
458
+ }
459
+ //# sourceMappingURL=monitor.js.map