arena-bridge 0.9.0 → 0.11.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/CHANGELOG.md +29 -0
- package/package.json +3 -3
- package/src/audit.mjs +74 -26
- package/src/browser.mjs +0 -1
- package/src/catalog.mjs +21 -0
- package/src/cli.mjs +6 -1
- package/src/device.mjs +1 -1
- package/src/direct.mjs +39 -11
- package/src/engine.mjs +24 -31
- package/src/errors.mjs +2 -0
- package/src/gate.mjs +2 -2
- package/src/hub.mjs +21 -8
- package/src/prompt.mjs +1 -0
- package/src/source.mjs +81 -0
- package/src/telemetry.mjs +8 -0
- package/src/version.mjs +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,35 @@ All notable changes to this project are documented here.
|
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/) and the project uses
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## 0.11.0
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- Work log records every call with its full parameters (large payloads move to an `args.json` artifact), the caller (tunnel address, country, reverse-DNS host, client), and an alert level.
|
|
11
|
+
- Unauthorized requests are logged at alert level, limited to 5 per address per minute, with a suppressed count.
|
|
12
|
+
- `log_note` tool: adds an info entry to the work log (1–500 characters, one per second). Node only; the Python package does not receive new tools.
|
|
13
|
+
- Errors `INVALID_ARGS` and `RATE_LIMITED`; `INVALID_JSON` and `PAYLOAD_TOO_LARGE` responses for malformed or oversized HTTP bodies.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
- Duplicate `chrome_screenshot` audit entry removed; the call is recorded once.
|
|
17
|
+
- Masking covers bearer tokens, AWS key ids, private key blocks, `env` values and secret-named keys.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
- `/files` GET, PUT and DELETE are all audited and authorized through the same path.
|
|
21
|
+
|
|
22
|
+
## 0.10.0
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
- `src/telemetry.mjs` — cold-start, RSS/heap and uptime exported to `doctor --json` (`telemetry` field) and as new `cold_start`/`memory`/`uptime` checks; `GET /health` still exposes `uptime_sec`/`trust_active`/`audit_count`/`log_size`.
|
|
26
|
+
- `docs/reference/errors.md` — single source error code table generated from `src/errors.mjs` (`PROTECTED`, `APPROVAL_*`, `TIMEOUT`, `UNKNOWN_TOOL` → retryable/hint mapping).
|
|
27
|
+
- `macos/ArenaBridge/Sources/MenuBar.swift` — optional `MenuBarExtra` popover (pending count + trust remaining), ready for Developer ID flow without replacing `WindowGroup`.
|
|
28
|
+
- `.github/workflows/release.yml` now publishes `SHA256SUMS` (+ `SHA256SUMS-apps` for zips) and `install.sh` verifies them (`shasum -a 256 -c`).
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
- `AppIcon.png` recompressed 982 KB → 82 KB (quantized 1024px PNG, `iconutil` still generates 5 scales + @2x).
|
|
32
|
+
|
|
33
|
+
### Fixed
|
|
34
|
+
- `release.yml` `if: success()` already — kept; macOS job now `needs: [release]` and uploads both arch zips with checksums.
|
|
35
|
+
|
|
7
36
|
## 0.9.0
|
|
8
37
|
|
|
9
38
|
### Added
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arena-bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Give a cloud AI agent (Arena.ai Agent Mode, Claude, Cursor, ...) controlled access to your own machine over HTTP/MCP: files, shell, Chrome and the macOS desktop, with an approval gate, trust windows and an audit log.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
"node": ">=18"
|
|
20
20
|
},
|
|
21
21
|
"scripts": {
|
|
22
|
-
"test": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node --test test/test_security.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
|
|
23
|
-
"test:node": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
|
|
22
|
+
"test": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node --test test/test_security.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs",
|
|
23
|
+
"test:node": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs && node --test test/log.test.mjs",
|
|
24
24
|
"test:python": "python3 test/test_approvals.py && python3 test/test_bridge.py && python3 test/test_browser.py && python3 test/test_mac.py && python3 test/test_service.py && python3 test/test_telegram.py",
|
|
25
25
|
"pack:check": "npm pack --dry-run"
|
|
26
26
|
},
|
package/src/audit.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
3
4
|
import { CONFIG_DIR } from './config.mjs';
|
|
4
5
|
|
|
5
6
|
/** The config directory is resolved on every call so tests and relocations stay isolated. */
|
|
@@ -11,58 +12,105 @@ export function auditPath() {
|
|
|
11
12
|
return path.join(configDir(), 'audit.log');
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
export const LEVELS = ['info', 'notice', 'warning', 'alert'];
|
|
16
|
+
const ARGS_INLINE_BYTES = 64 * 1024;
|
|
17
|
+
const FIELD_CLIP = 4000;
|
|
18
|
+
|
|
14
19
|
const SECRETS = [
|
|
15
20
|
/(?<!\d)\d{6,12}:[A-Za-z0-9_-]{25,}/g, // telegram bot tokens
|
|
16
21
|
/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, // github tokens
|
|
17
22
|
/\bnpm_[A-Za-z0-9]{20,}\b/g, // npm tokens
|
|
18
23
|
/\bpypi-[A-Za-z0-9_-]{20,}\b/g, // pypi tokens
|
|
19
24
|
/\bsk-[A-Za-z0-9]{20,}\b/g, // api keys
|
|
25
|
+
/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/gi, // bearer credentials
|
|
26
|
+
/\bAKIA[0-9A-Z]{16}\b/g, // aws access key ids
|
|
27
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
20
28
|
];
|
|
29
|
+
const SENSITIVE_KEY = /token|secret|passw|authorization|api[_-]?key|cookie|credential/i;
|
|
21
30
|
|
|
22
31
|
/** Mask anything that looks like a credential, so the log never becomes a secret store. */
|
|
23
|
-
export function scrub(value) {
|
|
32
|
+
export function scrub(value, key = '') {
|
|
24
33
|
if (typeof value === 'string') {
|
|
34
|
+
if (SENSITIVE_KEY.test(key)) return '***';
|
|
25
35
|
let out = value;
|
|
26
36
|
for (const re of SECRETS) out = out.replace(re, '***');
|
|
27
37
|
return out;
|
|
28
38
|
}
|
|
29
|
-
if (Array.isArray(value)) return value.map(scrub);
|
|
39
|
+
if (Array.isArray(value)) return value.map((v) => scrub(v, key));
|
|
40
|
+
if (value && typeof value === 'object') {
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [k, v] of Object.entries(value)) {
|
|
43
|
+
const masked = (key === 'env' || SENSITIVE_KEY.test(k)) && v !== null && typeof v !== 'object';
|
|
44
|
+
out[k] = masked ? '***' : scrub(v, k);
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The alert level of an entry: explicit level wins, otherwise derived from kind and status. */
|
|
52
|
+
export function levelFor({ kind = 'call', status = '', level } = {}) {
|
|
53
|
+
if (level) return level;
|
|
54
|
+
if (kind === 'auth' || (kind === 'approval' && status === 'forbidden')) return 'alert';
|
|
55
|
+
if (kind === 'note') return status === 'ok' ? 'info' : 'warning';
|
|
56
|
+
if (status === 'ok') return 'info';
|
|
57
|
+
if (['trust', 'service', 'tunnel', 'log', 'approval'].includes(kind)) return 'notice';
|
|
58
|
+
return 'warning';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function newEntryId(tool) {
|
|
62
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
63
|
+
const name = String(tool || 'event').replace(/[^\w.-]/g, '_');
|
|
64
|
+
return `${stamp}-${name}-${crypto.randomBytes(3).toString('hex')}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Long free-text fields other than the parameters are clipped; parameters are kept whole (see argsFor). */
|
|
68
|
+
function clipFields(value) {
|
|
69
|
+
if (typeof value === 'string') return value.length > FIELD_CLIP ? `[${value.length} chars truncated]` : value;
|
|
70
|
+
if (Array.isArray(value)) return value.map(clipFields);
|
|
30
71
|
if (value && typeof value === 'object') {
|
|
31
72
|
const out = {};
|
|
32
|
-
for (const [k, v] of Object.entries(value)) out[k] =
|
|
73
|
+
for (const [k, v] of Object.entries(value)) out[k] = clipFields(v);
|
|
33
74
|
return out;
|
|
34
75
|
}
|
|
35
76
|
return value;
|
|
36
77
|
}
|
|
37
78
|
|
|
38
|
-
|
|
79
|
+
/** Parameters are stored whole; the ones above the inline limit go to an artifact next to the entry. */
|
|
80
|
+
function argsFor(id, args) {
|
|
81
|
+
if (args === undefined) return { args: {}, truncated: false };
|
|
82
|
+
const clean = scrub(args);
|
|
83
|
+
const json = JSON.stringify(clean);
|
|
84
|
+
if (Buffer.byteLength(json) <= ARGS_INLINE_BYTES) return { args: clean, truncated: false };
|
|
85
|
+
const saved = saveArtifact(id, 'args', 'args.json', JSON.stringify(clean, null, 2));
|
|
86
|
+
return {
|
|
87
|
+
args: { preview: json.slice(0, 2000) },
|
|
88
|
+
truncated: true,
|
|
89
|
+
artifact: saved ? 'args.json' : undefined,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function audit(entry = {}) {
|
|
39
94
|
try {
|
|
40
95
|
const dir = configDir();
|
|
41
96
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
42
97
|
// auto-rotate if over 10 MB (cheap stat, keeps log bounded)
|
|
43
98
|
try { const st = fs.statSync(auditPath()); if (st.size > 10*1024*1024) rotateAuditIfNeeded(); } catch {}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
return out;
|
|
62
|
-
}
|
|
63
|
-
return v;
|
|
64
|
-
}
|
|
65
|
-
const rec = { ts: new Date().toISOString(), ...trunc(scrub(entry)) };
|
|
99
|
+
const { id, args, ...fields } = entry;
|
|
100
|
+
const recId = String(id || newEntryId(fields.tool));
|
|
101
|
+
const params = argsFor(recId, args);
|
|
102
|
+
const body = clipFields(scrub({ kind: 'call', ...fields }));
|
|
103
|
+
const rec = {
|
|
104
|
+
id: recId,
|
|
105
|
+
ts: new Date().toISOString(),
|
|
106
|
+
...body,
|
|
107
|
+
level: levelFor({ kind: body.kind, status: body.status, level: body.level }),
|
|
108
|
+
actor: body.actor || 'agent',
|
|
109
|
+
source: body.source ?? null,
|
|
110
|
+
args: params.args,
|
|
111
|
+
args_truncated: params.truncated,
|
|
112
|
+
...(params.artifact ? { args_artifact: params.artifact } : {}),
|
|
113
|
+
};
|
|
66
114
|
fs.appendFileSync(auditPath(), JSON.stringify(rec) + '\n', { mode: 0o600 });
|
|
67
115
|
} catch {
|
|
68
116
|
/* auditing must never break the request */
|
package/src/browser.mjs
CHANGED
|
@@ -1063,7 +1063,6 @@ export class BrowserManager {
|
|
|
1063
1063
|
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
1064
1064
|
fs.mkdirSync(path.dirname(chk.abs), { recursive: true });
|
|
1065
1065
|
fs.writeFileSync(chk.abs, Buffer.from(b64, 'base64'));
|
|
1066
|
-
audit({ tool: 'chrome_screenshot', args, status: 'ok', path: chk.abs });
|
|
1067
1066
|
return { ok: true, tab_id: tab.targetId, path: chk.abs, bytes: Math.round((b64.length * 3) / 4) };
|
|
1068
1067
|
}
|
|
1069
1068
|
return { ok: true, tab_id: tab.targetId, image_base64: b64, bytes: Math.round((b64.length * 3) / 4) };
|
package/src/catalog.mjs
CHANGED
|
@@ -5,6 +5,9 @@ import path from 'node:path';
|
|
|
5
5
|
import { checkPath, resolveTarget } from './policy.mjs';
|
|
6
6
|
import { audit, saveArtifact, tailAudit, readArtifact, auditDir } from './audit.mjs';
|
|
7
7
|
import { clip, runShell } from './engine_helpers.mjs';
|
|
8
|
+
import { errorResponse } from './errors.mjs';
|
|
9
|
+
|
|
10
|
+
let lastNoteAt = 0;
|
|
8
11
|
|
|
9
12
|
const S = (o) => ({ type: 'object', properties: o, required: [], additionalProperties: false });
|
|
10
13
|
|
|
@@ -352,6 +355,24 @@ export function toolCatalog() {
|
|
|
352
355
|
return { ok: true, count: entries.length, entries, artifacts_dir: auditDir() };
|
|
353
356
|
},
|
|
354
357
|
},
|
|
358
|
+
{
|
|
359
|
+
name: 'log_note',
|
|
360
|
+
description:
|
|
361
|
+
'Write a short comment into the work log that the user reads, for example what you are about to do and why. It changes nothing else and needs no approval. Plain text, up to 500 characters, at most one note per second.',
|
|
362
|
+
approval: false,
|
|
363
|
+
schema: S({ text: { type: 'string', description: 'the comment, plain text, 1 to 500 characters' } }),
|
|
364
|
+
required: ['text'],
|
|
365
|
+
handler: async (args) => {
|
|
366
|
+
const text = typeof args.text === 'string' ? args.text.trim() : '';
|
|
367
|
+
if (!text || [...text].length > 500) {
|
|
368
|
+
return errorResponse('INVALID_ARGS', { message: 'text must be 1 to 500 characters' });
|
|
369
|
+
}
|
|
370
|
+
const now = Date.now();
|
|
371
|
+
if (now - lastNoteAt < 1000) return errorResponse('RATE_LIMITED');
|
|
372
|
+
lastNoteAt = now;
|
|
373
|
+
return { ok: true, noted: true, text };
|
|
374
|
+
},
|
|
375
|
+
},
|
|
355
376
|
{
|
|
356
377
|
name: 'audit_artifact',
|
|
357
378
|
description:
|
package/src/cli.mjs
CHANGED
|
@@ -16,7 +16,9 @@ import { startTunnel, isPortOpen } from './tunnel.mjs';
|
|
|
16
16
|
import { spawn, execSync, spawnSync } from 'node:child_process';
|
|
17
17
|
import { parseDuration, trustState, saveTrust, clearTrust } from './trust.mjs';
|
|
18
18
|
import { findPeekaboo } from './mac.mjs';
|
|
19
|
+
import { coldStartMs, mem, uptimeSec } from './telemetry.mjs';
|
|
19
20
|
import { tailLog, logPathForCli } from './log.mjs';
|
|
21
|
+
import { VERSION } from './version.mjs';
|
|
20
22
|
import { cmdBrowser as _cmdBrowserImpl } from './cli/browser.mjs';
|
|
21
23
|
import { findChrome, listProfiles, resolveProfile, sanitizeProfile } from './browser.mjs';
|
|
22
24
|
import { COMPLETION_BASH, COMPLETION_ZSH, COMPLETION_FISH } from './completion.mjs';
|
|
@@ -1046,6 +1048,9 @@ function cmdDoctor(args) {
|
|
|
1046
1048
|
} catch {}
|
|
1047
1049
|
const peek = findPeekaboo(cfg);
|
|
1048
1050
|
checks.push({ name: 'peekaboo (desktop control)', code: 'peekaboo', passed: !!peek, detail: peek || 'not installed - screen and mouse control are off', hint: 'brew install peekaboo or set peekabooPath' });
|
|
1051
|
+
try { const c = coldStartMs(); checks.push({ name: 'cold start', code: 'cold_start', passed: c < 2000, detail: `${c} ms`, hint: c > 2000 ? 'check bridge.log for slow imports' : '' }); } catch {}
|
|
1052
|
+
try { const m = mem(); if (m) checks.push({ name: 'memory rss', code: 'memory', passed: m.rss < 300*1024, detail: `${Math.round(m.rss/1024)} MB rss / ${Math.round(m.heapUsed/1024)} MB heap`, hint: m.rss > 300*1024 ? 'restart bridge if growing' : '' }); } catch {}
|
|
1053
|
+
try { const u = uptimeSec(); checks.push({ name: 'uptime', code: 'uptime', passed: true, detail: `${u}s`, hint: '' }); } catch {}
|
|
1049
1054
|
const chrome = [
|
|
1050
1055
|
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
1051
1056
|
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
@@ -1053,7 +1058,7 @@ function cmdDoctor(args) {
|
|
|
1053
1058
|
checks.push({ name: 'chrome', code: 'chrome', passed: !!chrome, detail: chrome || 'not found in /Applications', hint: 'install Chrome to use browser tools' });
|
|
1054
1059
|
const ok = checks.every(c => c.passed);
|
|
1055
1060
|
if (isJson) {
|
|
1056
|
-
console.log(JSON.stringify({ ok, version: VERSION, publicUrl: cfg.publicUrl || null, node: process.version, checks }, null, 2));
|
|
1061
|
+
try { const t = { cold_start_ms: coldStartMs(), memory: mem(), uptime_sec: uptimeSec() }; console.log(JSON.stringify({ ok, version: VERSION, publicUrl: cfg.publicUrl || null, node: process.version, telemetry: t, checks }, null, 2)); } catch { console.log(JSON.stringify({ ok, version: VERSION, publicUrl: cfg.publicUrl || null, node: process.version, checks }, null, 2)); }
|
|
1057
1062
|
} else {
|
|
1058
1063
|
for (const c of checks) {
|
|
1059
1064
|
console.log(`${c.passed ? '✓' : '✗'} ${c.name.padEnd(18)} ${c.detail}`);
|
package/src/device.mjs
CHANGED
|
@@ -43,7 +43,7 @@ export async function runDevice(cfg, engine, { log = console.log } = {}) {
|
|
|
43
43
|
|
|
44
44
|
let result;
|
|
45
45
|
try {
|
|
46
|
-
result = await engine.call(job.tool, job.args || {});
|
|
46
|
+
result = await engine.call(job.tool, job.args || {}, { source: job.source || { channel: 'hub', ip: null, country: null, host: null, client: null } });
|
|
47
47
|
} catch (e) {
|
|
48
48
|
result = { ok: false, error: e.message };
|
|
49
49
|
}
|
package/src/direct.mjs
CHANGED
|
@@ -8,7 +8,9 @@ import { buildPrompt } from './prompt.mjs';
|
|
|
8
8
|
import { listApprovals, decide, settle } from './approvals.mjs';
|
|
9
9
|
import { checkPath } from './policy.mjs';
|
|
10
10
|
import { loadConfig } from './config.mjs';
|
|
11
|
-
import { tailAudit, readArtifact, auditDir } from './audit.mjs';
|
|
11
|
+
import { tailAudit, readArtifact, auditDir, audit } from './audit.mjs';
|
|
12
|
+
import { describeSource, sourceOf, admitUnauthorized } from './source.mjs';
|
|
13
|
+
import { errorResponse } from './errors.mjs';
|
|
12
14
|
import { startPoller, parseCommand, sendTelegram, answerCallback, editMessageText } from './telegram.mjs';
|
|
13
15
|
|
|
14
16
|
export function createDirectServer(cfg, engine) {
|
|
@@ -95,6 +97,14 @@ export function createDirectServer(cfg, engine) {
|
|
|
95
97
|
const cfgNow = loadConfig();
|
|
96
98
|
mcpCtx.cfg = cfgNow;
|
|
97
99
|
if (!isAuthorized(req, cfgNow)) {
|
|
100
|
+
const source = describeSource(req, 'http');
|
|
101
|
+
const seen = admitUnauthorized(source.ip);
|
|
102
|
+
if (seen.previousSuppressed) {
|
|
103
|
+
audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'direct', actor: 'system', source, args: { path: p, suppressed: seen.previousSuppressed } });
|
|
104
|
+
}
|
|
105
|
+
if (seen.write) {
|
|
106
|
+
audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'direct', actor: 'system', source, args: { path: p, method: req.method, count_in_minute: seen.count } });
|
|
107
|
+
}
|
|
98
108
|
res.setHeader('www-authenticate', 'Bearer');
|
|
99
109
|
return sendJson(res, 401, { ok: false, error: 'unauthorized' });
|
|
100
110
|
}
|
|
@@ -171,6 +181,7 @@ export function createDirectServer(cfg, engine) {
|
|
|
171
181
|
const expected = loadConfig().localToken;
|
|
172
182
|
const presented = bearer(req);
|
|
173
183
|
if (!expected || !presented || !safeEqual(presented, expected)) {
|
|
184
|
+
audit({ kind: 'approval', tool: null, status: 'forbidden', error: 'FORBIDDEN', via: 'api', actor: 'agent', source: await sourceOf(req, 'http'), args: { approval_id: approveMatch[1] } });
|
|
174
185
|
return sendJson(res, 403, {
|
|
175
186
|
ok: false,
|
|
176
187
|
error: 'forbidden',
|
|
@@ -185,20 +196,25 @@ export function createDirectServer(cfg, engine) {
|
|
|
185
196
|
|
|
186
197
|
if (req.method === 'POST' && p === '/exec') {
|
|
187
198
|
const body = await readJson(req, cfgNow.maxUploadBytes);
|
|
199
|
+
const source = await sourceOf(req, 'http');
|
|
188
200
|
const result = await engine.call('bash', {
|
|
189
201
|
command: body.command,
|
|
190
202
|
cwd: body.cwd,
|
|
191
203
|
timeout_sec: body.timeout_sec,
|
|
192
204
|
env: body.env,
|
|
193
|
-
});
|
|
205
|
+
}, { source });
|
|
194
206
|
const status = result.ok ? 200 : (result.error === 'APPROVAL_PENDING' ? 202 : 400);
|
|
195
207
|
return sendJson(res, status, result);
|
|
196
208
|
}
|
|
197
209
|
|
|
198
210
|
if (req.method === 'POST' && p === '/call') {
|
|
199
211
|
const body = await readJson(req, cfgNow.maxUploadBytes);
|
|
200
|
-
|
|
201
|
-
|
|
212
|
+
const source = await sourceOf(req, 'http');
|
|
213
|
+
if (!body.tool) {
|
|
214
|
+
audit({ kind: 'call', tool: null, status: 'rejected', error: 'INVALID_ARGS', via: 'direct', source, args: {} });
|
|
215
|
+
return sendJson(res, 400, { ok: false, error: 'tool is required' });
|
|
216
|
+
}
|
|
217
|
+
const result = await engine.call(String(body.tool), body.args || {}, { source });
|
|
202
218
|
// R5: return 202 for pending approvals, so client can poll GET /approvals/:id
|
|
203
219
|
const status = result.ok ? 200 : (result.error === 'APPROVAL_PENDING' ? 202 : 400);
|
|
204
220
|
return sendJson(res, status, result);
|
|
@@ -206,14 +222,18 @@ export function createDirectServer(cfg, engine) {
|
|
|
206
222
|
|
|
207
223
|
if (p === '/files') {
|
|
208
224
|
const target = url.searchParams.get('path');
|
|
225
|
+
const source = await sourceOf(req, 'http');
|
|
226
|
+
const toolName = req.method === 'GET' ? 'file_get' : req.method === 'DELETE' ? 'delete_path' : 'file_put';
|
|
209
227
|
if (!target) return sendJson(res, 400, { ok: false, error: 'path query parameter is required' });
|
|
210
228
|
const chk = checkPath(target, cfgNow, engine.base, { write: req.method !== 'GET' });
|
|
211
|
-
if (!chk.ok)
|
|
229
|
+
if (!chk.ok) {
|
|
230
|
+
audit({ tool: toolName, args: { path: target }, status: 'error', error: chk.error, via: 'files_api', source });
|
|
231
|
+
return sendJson(res, 403, { ok: false, error: chk.error, reason: chk.reason });
|
|
232
|
+
}
|
|
212
233
|
// PUT/DELETE must go through the approval gate and audit, like the tools
|
|
213
234
|
if (req.method !== 'GET') {
|
|
214
|
-
const toolName = req.method === 'DELETE' ? 'delete_path' : 'file_put';
|
|
215
235
|
const { authorize } = await import('./gate.mjs');
|
|
216
|
-
const resAuth = await authorize(toolName, { path: target }, cfgNow);
|
|
236
|
+
const resAuth = await authorize(toolName, { path: target }, cfgNow, source);
|
|
217
237
|
if (!resAuth.ok) {
|
|
218
238
|
const status = resAuth.status || 'denied';
|
|
219
239
|
const pending = resAuth.pending;
|
|
@@ -228,21 +248,23 @@ export function createDirectServer(cfg, engine) {
|
|
|
228
248
|
try {
|
|
229
249
|
if (req.method === 'GET') {
|
|
230
250
|
const buf = await fsp.readFile(chk.abs);
|
|
251
|
+
audit({ tool: 'file_get', args: { path: target }, status: 'ok', via: 'files_api', source, bytes: buf.length });
|
|
231
252
|
return sendRaw(res, 200, buf);
|
|
232
253
|
}
|
|
233
254
|
if (req.method === 'PUT' || req.method === 'POST') {
|
|
234
255
|
const buf = await readBody(req, cfgNow.maxUploadBytes);
|
|
235
256
|
await fsp.mkdir(path.dirname(chk.abs), { recursive: true });
|
|
236
257
|
await fsp.writeFile(chk.abs, buf);
|
|
237
|
-
|
|
258
|
+
audit({ tool: 'file_put', args: { path: target }, status: 'ok', via: 'files_api', source, bytes: buf.length });
|
|
238
259
|
return sendJson(res, 200, { ok: true, path: chk.abs, bytes: buf.length });
|
|
239
260
|
}
|
|
240
261
|
if (req.method === 'DELETE') {
|
|
241
262
|
await fsp.rm(chk.abs, { recursive: true, force: true });
|
|
242
|
-
|
|
263
|
+
audit({ tool: 'delete_path', args: { path: target }, status: 'ok', via: 'files_api', source });
|
|
243
264
|
return sendJson(res, 200, { ok: true, path: chk.abs, deleted: true });
|
|
244
265
|
}
|
|
245
266
|
} catch (e) {
|
|
267
|
+
audit({ tool: toolName, args: { path: target }, status: 'error', error: e.message, via: 'files_api', source });
|
|
246
268
|
return sendJson(res, 400, { ok: false, error: e.message });
|
|
247
269
|
}
|
|
248
270
|
return sendJson(res, 405, { ok: false, error: 'method not allowed' });
|
|
@@ -288,12 +310,18 @@ export function createDirectServer(cfg, engine) {
|
|
|
288
310
|
if (req.method !== 'POST') {
|
|
289
311
|
return sendJson(res, 405, { ok: false, error: 'method not allowed', hint: 'use POST /mcp' });
|
|
290
312
|
}
|
|
291
|
-
|
|
313
|
+
const source = await sourceOf(req, 'mcp');
|
|
314
|
+
return handleMcp(req, res, { ...mcpCtx, callTool: (name, args) => engine.call(name, args, { source }) });
|
|
292
315
|
}
|
|
293
316
|
|
|
294
317
|
return sendJson(res, 404, { ok: false, error: `no route for ${req.method} ${p}` });
|
|
295
318
|
} catch (e) {
|
|
296
|
-
|
|
319
|
+
const code = /invalid JSON/.test(e.message) ? 'INVALID_JSON' : /too large/.test(e.message) ? 'PAYLOAD_TOO_LARGE' : null;
|
|
320
|
+
if (!code) return sendJson(res, 500, { ok: false, error: e.message });
|
|
321
|
+
if (p === '/call' || p === '/exec') {
|
|
322
|
+
audit({ kind: 'call', tool: null, status: 'rejected', error: code, via: 'direct', source: describeSource(req, 'http'), args: {} });
|
|
323
|
+
}
|
|
324
|
+
return sendJson(res, code === 'PAYLOAD_TOO_LARGE' ? 413 : 400, errorResponse(code));
|
|
297
325
|
}
|
|
298
326
|
});
|
|
299
327
|
|
package/src/engine.mjs
CHANGED
|
@@ -43,7 +43,7 @@ export class Engine {
|
|
|
43
43
|
return [...toolCatalog(), ...this.browser.tools(), ...macTools(this.cfg), ...telegramTools(this.cfg)];
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
async call(name, args = {}, { requireApproval, cfg } = {}) {
|
|
46
|
+
async call(name, args = {}, { requireApproval, cfg, source } = {}) {
|
|
47
47
|
let cfgNow;
|
|
48
48
|
if (cfg) {
|
|
49
49
|
cfgNow = cfg;
|
|
@@ -56,6 +56,10 @@ export class Engine {
|
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
this.cfg = cfgNow;
|
|
59
|
+
const src = source || { channel: 'local', ip: null, country: null, host: null, client: null };
|
|
60
|
+
const record = (fields) => {
|
|
61
|
+
if (this.cfg.audit !== false) audit({ tool: name, args, source: src, kind: name === 'log_note' ? 'note' : 'call', ...fields });
|
|
62
|
+
};
|
|
59
63
|
const tool = this.catalog().find((t) => t.name === name);
|
|
60
64
|
if (!tool) {
|
|
61
65
|
const all = this.catalog().map(t=>t.name);
|
|
@@ -63,6 +67,7 @@ export class Engine {
|
|
|
63
67
|
const lev=(a,b)=>{ a=String(a); b=String(b); const m=a.length,n=b.length; const dp=Array(m+1).fill(null).map(()=>Array(n+1).fill(0)); for(let i=0;i<=m;i++) dp[i][0]=i; for(let j=0;j<=n;j++) dp[0][j]=j; for(let i=1;i<=m;i++) for(let j=1;j<=n;j++) dp[i][j]=Math.min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+(a[i-1]===b[j-1]?0:1)); return dp[m][n]; };
|
|
64
68
|
for (const n of all) { const d=lev(name,n); if(d<bestD){bestD=d; best=n;} }
|
|
65
69
|
const hint = best && bestD <= 3 ? `did you mean '${best}'?` : `available: ${all.slice(0,10).join(', ')}`;
|
|
70
|
+
record({ kind: 'call', status: 'rejected', error: 'UNKNOWN_TOOL', via: 'direct' });
|
|
66
71
|
return errorResponse('UNKNOWN_TOOL', { message: `unknown tool: ${name}`, tool: name, hint });
|
|
67
72
|
}
|
|
68
73
|
const started = Date.now();
|
|
@@ -73,6 +78,7 @@ export class Engine {
|
|
|
73
78
|
const ctx = Object.create(this);
|
|
74
79
|
ctx.entryId = entryId;
|
|
75
80
|
ctx.artifacts = [];
|
|
81
|
+
ctx.source = src;
|
|
76
82
|
ctx.artifact = (kind, file, data, meta) => {
|
|
77
83
|
const saved = saveArtifact(entryId, kind, file, data, meta);
|
|
78
84
|
if (saved) ctx.artifacts.push(saved);
|
|
@@ -84,25 +90,24 @@ export class Engine {
|
|
|
84
90
|
if (requireApproval === true) needApproval = true;
|
|
85
91
|
else if (requireApproval === false) needApproval = false;
|
|
86
92
|
|
|
93
|
+
const artifactsOf = () => (ctx.artifacts.length ? ctx.artifacts : undefined);
|
|
94
|
+
|
|
87
95
|
if (needApproval) {
|
|
88
96
|
const trust = trustState();
|
|
89
97
|
if (trustAllows(trust, tool.name, args, this.cfg)) {
|
|
90
98
|
const res = await tool.handler(args, ctx);
|
|
91
|
-
|
|
92
|
-
audit({ id: entryId, tool: tool.name, args, status: res.ok ? 'ok' : 'error', duration_ms: Date.now() - started, via: 'trust_window', exit_code: res.exit_code, error: res.ok ? undefined : res.error, artifacts: ctx.artifacts.length ? ctx.artifacts : undefined });
|
|
93
|
-
}
|
|
99
|
+
record({ id: entryId, status: res.ok ? 'ok' : 'error', duration_ms: Date.now() - started, via: 'trust_window', exit_code: res.exit_code, error: res.ok ? undefined : res.error, artifacts: artifactsOf() });
|
|
94
100
|
return res;
|
|
95
101
|
}
|
|
96
102
|
approval = await requestApproval(tool.name, args, this.cfg);
|
|
97
103
|
if (!approval.approved) {
|
|
98
104
|
const status = approval.rec?.status || 'denied';
|
|
99
|
-
if (this.cfg.audit !== false) {
|
|
100
|
-
audit({ id: entryId, tool: tool.name, args, status: 'approval_denied', approval_status: status });
|
|
101
|
-
}
|
|
102
105
|
const pending = status === 'pending' || status === 'timeout' || status === 'expired';
|
|
106
|
+
const code = pending ? 'APPROVAL_PENDING' : 'APPROVAL_DENIED';
|
|
107
|
+
record({ id: entryId, status: 'approval_denied', approval_status: status, error: code, via: 'approval', duration_ms: Date.now() - started });
|
|
103
108
|
return {
|
|
104
109
|
ok: false,
|
|
105
|
-
error:
|
|
110
|
+
error: code,
|
|
106
111
|
status,
|
|
107
112
|
pending,
|
|
108
113
|
reason: pending
|
|
@@ -116,33 +121,21 @@ export class Engine {
|
|
|
116
121
|
}
|
|
117
122
|
}
|
|
118
123
|
|
|
124
|
+
const via = approval ? 'approval' : 'direct';
|
|
119
125
|
try {
|
|
120
126
|
const res = await tool.handler(args, ctx);
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
artifacts: ctx.artifacts.length ? ctx.artifacts : undefined,
|
|
131
|
-
});
|
|
132
|
-
}
|
|
127
|
+
record({
|
|
128
|
+
id: entryId,
|
|
129
|
+
status: res.ok ? 'ok' : 'error',
|
|
130
|
+
duration_ms: Date.now() - started,
|
|
131
|
+
exit_code: res.exit_code,
|
|
132
|
+
error: res.ok ? undefined : res.error,
|
|
133
|
+
via,
|
|
134
|
+
artifacts: artifactsOf(),
|
|
135
|
+
});
|
|
133
136
|
return res;
|
|
134
137
|
} catch (e) {
|
|
135
|
-
|
|
136
|
-
audit({
|
|
137
|
-
id: entryId,
|
|
138
|
-
tool: tool.name,
|
|
139
|
-
args,
|
|
140
|
-
status: 'exception',
|
|
141
|
-
duration_ms: Date.now() - started,
|
|
142
|
-
error: e.message,
|
|
143
|
-
artifacts: ctx.artifacts.length ? ctx.artifacts : undefined,
|
|
144
|
-
});
|
|
145
|
-
}
|
|
138
|
+
record({ id: entryId, status: 'exception', duration_ms: Date.now() - started, error: e.message, via, artifacts: artifactsOf() });
|
|
146
139
|
return { ok: false, error: e.message };
|
|
147
140
|
}
|
|
148
141
|
}
|
package/src/errors.mjs
CHANGED
|
@@ -15,6 +15,8 @@ export const ERROR_CODES = {
|
|
|
15
15
|
PAYLOAD_TOO_LARGE: { message: 'payload exceeds maxUploadBytes', hint: 'reduce file size or increase limit', retryable: false },
|
|
16
16
|
INVALID_JSON: { message: 'invalid JSON body', hint: 'check JSON syntax', retryable: false },
|
|
17
17
|
UNKNOWN_TOOL: { message: 'unknown tool', hint: 'GET /tools for catalog', retryable: false },
|
|
18
|
+
INVALID_ARGS: { message: 'arguments are missing or malformed', hint: 'check the tool schema in GET /tools', retryable: false },
|
|
19
|
+
RATE_LIMITED: { message: 'too many calls in a short time', hint: 'wait a second and retry', retryable: true },
|
|
18
20
|
};
|
|
19
21
|
|
|
20
22
|
export function errorResponse(code, extra = {}) {
|
package/src/gate.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { trustState, trustAllows } from './trust.mjs';
|
|
|
2
2
|
import { requestApproval } from './approvals.mjs';
|
|
3
3
|
import { audit } from './audit.mjs';
|
|
4
4
|
|
|
5
|
-
export async function authorize(tool, args, cfg) {
|
|
5
|
+
export async function authorize(tool, args, cfg, source = null) {
|
|
6
6
|
const trust = trustState();
|
|
7
7
|
let needApproval = true;
|
|
8
8
|
if (trustAllows(trust, tool, args, cfg)) needApproval = false;
|
|
@@ -11,8 +11,8 @@ export async function authorize(tool, args, cfg) {
|
|
|
11
11
|
const approval = await requestApproval(tool, args, cfg);
|
|
12
12
|
if (!approval.approved) {
|
|
13
13
|
const status = approval.rec?.status || "denied";
|
|
14
|
-
try { audit({ tool, args, status: "approval_denied", approval_status: status }); } catch {}
|
|
15
14
|
const pending = status === "pending" || status === "timeout" || status === "expired";
|
|
15
|
+
try { audit({ tool, args, status: "approval_denied", approval_status: status, via: "approval", source, error: pending ? "APPROVAL_PENDING" : "APPROVAL_DENIED" }); } catch {}
|
|
16
16
|
return { ok: false, status, approval_id: approval.rec?.id || null, pending };
|
|
17
17
|
}
|
|
18
18
|
return { ok: true };
|
package/src/hub.mjs
CHANGED
|
@@ -9,6 +9,8 @@ import { listApprovals, decide } from './approvals.mjs';
|
|
|
9
9
|
import { checkPath } from './policy.mjs';
|
|
10
10
|
import { loadConfig } from './config.mjs';
|
|
11
11
|
import fsp from 'node:fs/promises';
|
|
12
|
+
import { audit } from './audit.mjs';
|
|
13
|
+
import { sourceOf, describeSource, admitUnauthorized } from './source.mjs';
|
|
12
14
|
|
|
13
15
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
14
16
|
|
|
@@ -32,7 +34,7 @@ export function createHubServer(cfg) {
|
|
|
32
34
|
const queues = new Map(); // name -> [{id, tool, args}]
|
|
33
35
|
const jobs = new Map(); // id -> { resolve, timer }
|
|
34
36
|
|
|
35
|
-
const dispatch = (device, tool, args, timeoutSec = 120) =>
|
|
37
|
+
const dispatch = (device, tool, args, timeoutSec = 120, source = null) =>
|
|
36
38
|
new Promise((resolve) => {
|
|
37
39
|
const id = crypto.randomUUID();
|
|
38
40
|
const timer = setTimeout(() => {
|
|
@@ -45,11 +47,11 @@ export function createHubServer(cfg) {
|
|
|
45
47
|
}, (timeoutSec + 15) * 1000);
|
|
46
48
|
jobs.set(id, { resolve, timer });
|
|
47
49
|
const q = queues.get(device) || [];
|
|
48
|
-
q.push({ id, tool, args });
|
|
50
|
+
q.push({ id, tool, args, source });
|
|
49
51
|
queues.set(device, q);
|
|
50
52
|
});
|
|
51
53
|
|
|
52
|
-
const callTool = async (tool, args) => {
|
|
54
|
+
const callTool = async (tool, args, source = null) => {
|
|
53
55
|
const device = args?.device || cfg.device;
|
|
54
56
|
if (!device) return { ok: false, error: 'no target device specified' };
|
|
55
57
|
const known = devices.get(device);
|
|
@@ -58,7 +60,7 @@ export function createHubServer(cfg) {
|
|
|
58
60
|
}
|
|
59
61
|
const clean = { ...args };
|
|
60
62
|
delete clean.device;
|
|
61
|
-
return dispatch(device, tool, clean, Number(args?.timeout_sec || 120));
|
|
63
|
+
return dispatch(device, tool, clean, Number(args?.timeout_sec || 120), source);
|
|
62
64
|
};
|
|
63
65
|
|
|
64
66
|
const mcpCtx = {
|
|
@@ -112,7 +114,7 @@ export function createHubServer(cfg) {
|
|
|
112
114
|
res.writeHead(204).end();
|
|
113
115
|
return;
|
|
114
116
|
}
|
|
115
|
-
return sendJson(res, 200, { id: job.id, tool: job.tool, args: job.args });
|
|
117
|
+
return sendJson(res, 200, { id: job.id, tool: job.tool, args: job.args, source: job.source });
|
|
116
118
|
}
|
|
117
119
|
if (req.method === 'POST' && p === '/device/result') {
|
|
118
120
|
const body = await readJson(req, cfg.maxUploadBytes);
|
|
@@ -128,6 +130,14 @@ export function createHubServer(cfg) {
|
|
|
128
130
|
|
|
129
131
|
/* ---------- agent side (agent token) ---------- */
|
|
130
132
|
if (!isAuthorized(req, loadConfig())) {
|
|
133
|
+
const source = describeSource(req, 'http');
|
|
134
|
+
const seen = admitUnauthorized(source.ip);
|
|
135
|
+
if (seen.previousSuppressed) {
|
|
136
|
+
audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'hub', actor: 'system', source, args: { path: p, suppressed: seen.previousSuppressed } });
|
|
137
|
+
}
|
|
138
|
+
if (seen.write) {
|
|
139
|
+
audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'hub', actor: 'system', source, args: { path: p, method: req.method, count_in_minute: seen.count } });
|
|
140
|
+
}
|
|
131
141
|
res.setHeader('www-authenticate', 'Bearer');
|
|
132
142
|
return sendJson(res, 401, { ok: false, error: 'unauthorized' });
|
|
133
143
|
}
|
|
@@ -177,20 +187,22 @@ export function createHubServer(cfg) {
|
|
|
177
187
|
|
|
178
188
|
if (req.method === 'POST' && p === '/exec') {
|
|
179
189
|
const body = await readJson(req, cfg.maxUploadBytes);
|
|
190
|
+
const source = await sourceOf(req, 'http');
|
|
180
191
|
const result = await callTool('bash', {
|
|
181
192
|
device: body.device,
|
|
182
193
|
command: body.command,
|
|
183
194
|
cwd: body.cwd,
|
|
184
195
|
timeout_sec: body.timeout_sec,
|
|
185
196
|
env: body.env,
|
|
186
|
-
});
|
|
197
|
+
}, source);
|
|
187
198
|
return sendJson(res, result.ok ? 200 : 400, result);
|
|
188
199
|
}
|
|
189
200
|
|
|
190
201
|
if (req.method === 'POST' && p === '/call') {
|
|
191
202
|
const body = await readJson(req, cfg.maxUploadBytes);
|
|
192
203
|
if (!body.tool) return sendJson(res, 400, { ok: false, error: 'tool is required' });
|
|
193
|
-
const
|
|
204
|
+
const source = await sourceOf(req, 'http');
|
|
205
|
+
const result = await callTool(String(body.tool), body.args || {}, source);
|
|
194
206
|
return sendJson(res, result.ok ? 200 : 400, result);
|
|
195
207
|
}
|
|
196
208
|
|
|
@@ -222,7 +234,8 @@ export function createHubServer(cfg) {
|
|
|
222
234
|
}
|
|
223
235
|
|
|
224
236
|
if (req.method === 'POST' && p === '/mcp') {
|
|
225
|
-
|
|
237
|
+
const source = await sourceOf(req, 'mcp');
|
|
238
|
+
return handleMcp(req, res, { ...mcpCtx, callTool: (name, args) => callTool(name, args, source) });
|
|
226
239
|
}
|
|
227
240
|
|
|
228
241
|
return sendJson(res, 404, { ok: false, error: `no route for ${req.method} ${p}` });
|
package/src/prompt.mjs
CHANGED
|
@@ -109,6 +109,7 @@ Every call is logged with its arguments, result and duration. Screenshots taken
|
|
|
109
109
|
the accessibility trees that were read are stored next to the log.
|
|
110
110
|
- \`audit_log\` — the recent calls (filter by tool or time).
|
|
111
111
|
- \`audit_artifact\` — fetch a saved artifact: a screenshot (base64 PNG) or an accessibility tree (JSON).
|
|
112
|
+
- \`log_note\` — write a short comment into the work log before a step (what you are about to do and why). It changes nothing else.
|
|
112
113
|
Use them when you need to look back at what was on the screen or what the interface contained.
|
|
113
114
|
|
|
114
115
|
## Talking to the user (Telegram)
|
package/src/source.mjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import dns from 'node:dns/promises';
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
|
|
4
|
+
const HOST_BUDGET_MS = 250;
|
|
5
|
+
const HOST_TTL_MS = 60 * 60 * 1000;
|
|
6
|
+
const HOST_MISS_TTL_MS = 5 * 60 * 1000;
|
|
7
|
+
const UNAUTH_WINDOW_MS = 60 * 1000;
|
|
8
|
+
const UNAUTH_LINES = 5;
|
|
9
|
+
const CACHE_LIMIT = 1000;
|
|
10
|
+
|
|
11
|
+
const hosts = new Map(); // ip -> { host, expires }
|
|
12
|
+
const unauth = new Map(); // ip -> { start, count, logged }
|
|
13
|
+
|
|
14
|
+
const isLocal = (ip) =>
|
|
15
|
+
!ip || /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1$|fe80|fc|fd)/i.test(ip);
|
|
16
|
+
|
|
17
|
+
/** The caller's address: set by the tunnel edge, or the socket for local requests. */
|
|
18
|
+
export function clientIp(req) {
|
|
19
|
+
const header = req.headers['cf-connecting-ip'];
|
|
20
|
+
const candidates = [typeof header === 'string' ? header.trim() : '', req.socket?.remoteAddress || ''];
|
|
21
|
+
for (const raw of candidates) {
|
|
22
|
+
const ip = raw.replace(/^::ffff:/, '');
|
|
23
|
+
if (net.isIP(ip)) return ip;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Describe the caller without any network lookup. */
|
|
29
|
+
export function describeSource(req, channel) {
|
|
30
|
+
const ip = clientIp(req);
|
|
31
|
+
const country = typeof req.headers['cf-ipcountry'] === 'string' ? req.headers['cf-ipcountry'].slice(0, 2) : null;
|
|
32
|
+
const agent = String(req.headers['user-agent'] || '').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 120);
|
|
33
|
+
return { channel, ip, country, host: null, client: agent || null };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Reverse-DNS name of an address, within a short budget and cached. Null when unknown. */
|
|
37
|
+
export async function lookupHost(ip, now = Date.now()) {
|
|
38
|
+
if (isLocal(ip)) return null;
|
|
39
|
+
const hit = hosts.get(ip);
|
|
40
|
+
if (hit && hit.expires > now) return hit.host;
|
|
41
|
+
let host = null;
|
|
42
|
+
try {
|
|
43
|
+
const names = await Promise.race([
|
|
44
|
+
dns.reverse(ip),
|
|
45
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), HOST_BUDGET_MS).unref()),
|
|
46
|
+
]);
|
|
47
|
+
host = names?.[0] || null;
|
|
48
|
+
} catch {
|
|
49
|
+
host = null;
|
|
50
|
+
}
|
|
51
|
+
if (hosts.size >= CACHE_LIMIT) hosts.clear();
|
|
52
|
+
hosts.set(ip, { host, expires: now + (host ? HOST_TTL_MS : HOST_MISS_TTL_MS) });
|
|
53
|
+
return host;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A full source description, including the reverse-DNS name. */
|
|
57
|
+
export async function sourceOf(req, channel) {
|
|
58
|
+
const source = describeSource(req, channel);
|
|
59
|
+
source.host = await lookupHost(source.ip);
|
|
60
|
+
return source;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Failed-authentication bookkeeping per address: the first lines of each minute are logged,
|
|
65
|
+
* the rest is counted and reported once when the minute ends.
|
|
66
|
+
*/
|
|
67
|
+
export function admitUnauthorized(ip, now = Date.now()) {
|
|
68
|
+
const key = ip || 'unknown';
|
|
69
|
+
let w = unauth.get(key);
|
|
70
|
+
let previousSuppressed = 0;
|
|
71
|
+
if (!w || now - w.start >= UNAUTH_WINDOW_MS) {
|
|
72
|
+
if (w && w.count > w.logged) previousSuppressed = w.count - w.logged;
|
|
73
|
+
if (unauth.size >= CACHE_LIMIT) unauth.clear();
|
|
74
|
+
w = { start: now, count: 0, logged: 0 };
|
|
75
|
+
unauth.set(key, w);
|
|
76
|
+
}
|
|
77
|
+
w.count += 1;
|
|
78
|
+
const write = w.logged < UNAUTH_LINES;
|
|
79
|
+
if (write) w.logged += 1;
|
|
80
|
+
return { write, count: w.count, previousSuppressed };
|
|
81
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// telemetry: cold-start + memory + timing for doctor/status/health
|
|
2
|
+
let t0 = Date.now();
|
|
3
|
+
try { t0 = Number(process.env.ARENA_BRIDGE_T0) || Date.now(); } catch {}
|
|
4
|
+
export function coldStartMs() { try { return Date.now() - t0; } catch { return 0; } }
|
|
5
|
+
export function mem() {
|
|
6
|
+
try { const m=process.memoryUsage(); return { rss: Math.round(m.rss/1024), heapUsed: Math.round(m.heapUsed/1024), heapTotal: Math.round(m.heapTotal/1024) }; } catch { return null; }
|
|
7
|
+
}
|
|
8
|
+
export function uptimeSec() { try { return Math.round(process.uptime()); } catch { return 0; } }
|