arena-bridge 0.18.15 → 0.19.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 CHANGED
@@ -4,6 +4,21 @@ 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.19.0
8
+
9
+ ### Added
10
+ - Tool calls are validated against the published schemas before handlers run, including required fields, types, and unknown arguments.
11
+ - `config validate` checks mode, URLs, limits, tokens, tunnel settings, Telegram settings, and core runtime values.
12
+ - Hub mode now exposes the same health, config, approval polling, and audit read endpoints as direct mode.
13
+ - Added the retryable `DEVICE_BUSY` error for bounded hub queues.
14
+
15
+ ## 0.18.16
16
+
17
+ ### Fixed
18
+ - The macOS app no longer refreshes the full interface for every SSE heartbeat; background refreshes are coalesced, spaced out, and publish state only when it changes.
19
+ - Hub devices retry result delivery after transient network failures, and expired queued jobs are removed instead of executing later.
20
+ - Hub job queues are bounded and completed process sessions are pruned after retention.
21
+
7
22
  ## 0.18.15
8
23
 
9
24
  ### Fixed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arena-bridge",
3
- "version": "0.18.15",
3
+ "version": "0.19.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": {
package/src/catalog.mjs CHANGED
@@ -9,6 +9,13 @@ import { clip, runShell } from './engine_helpers.mjs';
9
9
  import { errorResponse } from './errors.mjs';
10
10
 
11
11
  let lastNoteAt = 0;
12
+ const SESSION_RETENTION_MS = 10 * 60 * 1000;
13
+
14
+ function pruneSessions(sessions, now = Date.now()) {
15
+ for (const [id, session] of sessions) {
16
+ if (session.exited && session.endedAt && now - session.endedAt > SESSION_RETENTION_MS) sessions.delete(id);
17
+ }
18
+ }
12
19
 
13
20
  const S = (o) => ({ type: 'object', properties: o, required: [], additionalProperties: false });
14
21
 
@@ -448,6 +455,7 @@ export function toolCatalog() {
448
455
  handler: async (args, ctx) => {
449
456
  const command = String(args.command ?? '');
450
457
  if (!command.trim()) return { ok: false, error: 'command is required' };
458
+ pruneSessions(ctx.sessions);
451
459
  const base = args.cwd ? resolveTarget(args.cwd, ctx.base) : ctx.base;
452
460
  const chk = checkPath(base, ctx.cfg, ctx.base);
453
461
  if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
@@ -489,6 +497,7 @@ export function toolCatalog() {
489
497
  child.on('close', (code) => {
490
498
  session.exited = true;
491
499
  session.exitCode = code;
500
+ session.endedAt = Date.now();
492
501
  });
493
502
  // R6: limit bash sessions to 20, cleanup oldest
494
503
  if (ctx.sessions.size >= 20) {
package/src/cli.mjs CHANGED
@@ -36,6 +36,63 @@ import {
36
36
 
37
37
  const REPEATABLE_FLAGS = new Set(['root']);
38
38
 
39
+ export function validateConfig(cfg = {}) {
40
+ const errors = [];
41
+ const add = (message) => errors.push(message);
42
+ const nonEmptyString = (name, value) => {
43
+ if (typeof value !== 'string' || !value.trim()) add(`${name} must be a non-empty string`);
44
+ };
45
+ const integerRange = (name, value, min, max) => {
46
+ if (!Number.isInteger(value) || value < min || value > max) add(`${name} must be an integer from ${min} to ${max}`);
47
+ };
48
+ const urlValue = (name, value, required = false) => {
49
+ if (value == null || value === '') {
50
+ if (required) add(`${name} is required`);
51
+ return;
52
+ }
53
+ try {
54
+ const parsed = new URL(String(value));
55
+ if (!['http:', 'https:'].includes(parsed.protocol)) add(`${name} must use http or https`);
56
+ } catch {
57
+ add(`${name} must be a valid URL`);
58
+ }
59
+ };
60
+
61
+ if (!['direct', 'hub'].includes(cfg.mode)) add(`mode must be direct or hub`);
62
+ nonEmptyString('host', cfg.host);
63
+ integerRange('port', Number(cfg.port), 1, 65535);
64
+ nonEmptyString('device', cfg.device);
65
+ for (const key of ['token', 'deviceToken', 'localToken']) nonEmptyString(key, cfg[key]);
66
+ if (!Array.isArray(cfg.roots) || cfg.roots.some((value) => typeof value !== 'string')) add('roots must be an array of strings');
67
+ if (!Array.isArray(cfg.protected) || cfg.protected.some((value) => typeof value !== 'string')) add('protected must be an array of strings');
68
+ for (const key of ['requireApproval', 'allowShell', 'audit', 'exposeDeviceInHealth']) {
69
+ if (typeof cfg[key] !== 'boolean') add(`${key} must be boolean`);
70
+ }
71
+ integerRange('approvalWaitSec', Number(cfg.approvalWaitSec), 0, 3600);
72
+ integerRange('approvalTtlSec', Number(cfg.approvalTtlSec), 1, 86400);
73
+ integerRange('maxOutputBytes', Number(cfg.maxOutputBytes), 1, 256 * 1024 * 1024);
74
+ integerRange('maxUploadBytes', Number(cfg.maxUploadBytes), 1, 256 * 1024 * 1024);
75
+ integerRange('commandTimeoutSec', Number(cfg.commandTimeoutSec), 1, 1800);
76
+ urlValue('hub', cfg.hub, cfg.mode === 'hub');
77
+ urlValue('publicUrl', cfg.publicUrl);
78
+
79
+ if (!cfg.tunnel || typeof cfg.tunnel !== 'object' || Array.isArray(cfg.tunnel)) add('tunnel must be an object');
80
+ else {
81
+ nonEmptyString('tunnel.bin', cfg.tunnel.bin);
82
+ if (cfg.tunnel.domain != null && (typeof cfg.tunnel.domain !== 'string' || /\s/.test(cfg.tunnel.domain))) add('tunnel.domain must be a hostname without spaces');
83
+ if (cfg.tunnel.authtoken != null && typeof cfg.tunnel.authtoken !== 'string') add('tunnel.authtoken must be a string or null');
84
+ }
85
+ if (cfg.peekabooPath != null && typeof cfg.peekabooPath !== 'string') add('peekabooPath must be a string or null');
86
+ if (!cfg.telegram || typeof cfg.telegram !== 'object' || Array.isArray(cfg.telegram)) add('telegram must be an object');
87
+ else {
88
+ if (typeof cfg.telegram.enabled !== 'boolean') add('telegram.enabled must be boolean');
89
+ if (!Array.isArray(cfg.telegram.chatIds) || cfg.telegram.chatIds.some((id) => typeof id !== 'string' || !id.trim())) add('telegram.chatIds must be an array of non-empty strings');
90
+ if (typeof cfg.telegram.poll !== 'boolean') add('telegram.poll must be boolean');
91
+ if (cfg.telegram.enabled && (!cfg.telegram.botToken || !cfg.telegram.chatIds.length)) add('enabled Telegram requires botToken and at least one chat id');
92
+ }
93
+ return errors;
94
+ }
95
+
39
96
  export function parseArgs(argv) {
40
97
  const out = { _: [], flags: {} };
41
98
  const set = (key, value) => {
@@ -854,7 +911,19 @@ function cmdRotate(args) {
854
911
 
855
912
  function cmdConfig(args) {
856
913
  const sub = args._[1] || 'list';
857
- const cfg = loadConfig();
914
+ let cfg;
915
+ try {
916
+ cfg = loadConfig();
917
+ } catch (e) {
918
+ if (sub === 'validate') {
919
+ const errors = [e.message];
920
+ if (args.flags.json) console.log(JSON.stringify({ ok: false, errors }, null, 2));
921
+ else { console.log('✗ config issues:'); for (const error of errors) console.log(` - ${error}`); }
922
+ process.exitCode = 1;
923
+ return;
924
+ }
925
+ throw e;
926
+ }
858
927
  if (sub === 'list' || sub === 'show') {
859
928
  const out = { ...cfg };
860
929
  delete out.configPath;
@@ -931,10 +1000,7 @@ function cmdConfig(args) {
931
1000
  }
932
1001
  if (sub === 'validate') {
933
1002
  const isJson = !!(args.flags.json);
934
- const errs = [];
935
- if (!cfg.token) errs.push('token missing — run arena-bridge init');
936
- if (!cfg.deviceToken) errs.push('deviceToken missing');
937
- if (!Number.isFinite(Number(cfg.port)) || Number(cfg.port) < 1 || Number(cfg.port) > 65535) errs.push(`port invalid: ${cfg.port}`);
1003
+ const errs = validateConfig(cfg);
938
1004
  if (isJson) console.log(JSON.stringify({ ok: errs.length===0, errors: errs }, null, 2));
939
1005
  else { if (!errs.length) console.log('✓ config valid'); else { console.log('✗ config issues:'); for (const e of errs) console.log(` - ${e}`); process.exitCode=1; } }
940
1006
  return;
package/src/device.mjs CHANGED
@@ -4,6 +4,35 @@
4
4
  */
5
5
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
6
6
 
7
+ /** Retry a result while the hub may still be waiting for it. A 404 means the job expired. */
8
+ export async function postResult(base, headers, payload, {
9
+ fetchImpl = fetch,
10
+ sleepImpl = sleep,
11
+ log = () => {},
12
+ maxAttempts = 8,
13
+ } = {}) {
14
+ let delay = 1000;
15
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
16
+ try {
17
+ const res = await fetchImpl(`${base}/device/result`, {
18
+ method: 'POST',
19
+ headers,
20
+ body: JSON.stringify(payload),
21
+ });
22
+ if (res.ok) return true;
23
+ if (res.status === 404) return false;
24
+ log(`[device] result failed: HTTP ${res.status} (attempt ${attempt}/${maxAttempts})`);
25
+ } catch (e) {
26
+ log(`[device] result connection error (attempt ${attempt}/${maxAttempts}): ${e.message}`);
27
+ }
28
+ if (attempt < maxAttempts) {
29
+ await sleepImpl(delay);
30
+ delay = Math.min(delay * 2, 30_000);
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+
7
36
  export async function runDevice(cfg, engine, { log = console.log } = {}) {
8
37
  const base = String(cfg.hub || '').replace(/\/+$/, '');
9
38
  if (!base) throw new Error('cfg.hub is required in hub mode');
@@ -48,11 +77,7 @@ export async function runDevice(cfg, engine, { log = console.log } = {}) {
48
77
  result = { ok: false, error: e.message };
49
78
  }
50
79
 
51
- await fetch(`${base}/device/result`, {
52
- method: 'POST',
53
- headers,
54
- body: JSON.stringify({ id: job.id, result }),
55
- });
80
+ await postResult(base, headers, { id: job.id, result }, { log });
56
81
  } catch (e) {
57
82
  log(`[device] connection error: ${e.message}`);
58
83
  await sleep(backoff);
package/src/engine.mjs CHANGED
@@ -10,6 +10,7 @@ import { BrowserManager, cleanupOrphanChromes } from './browser.mjs';
10
10
  import { macTools } from './mac.mjs';
11
11
  import { trustState, trustAllows } from './trust.mjs';
12
12
  import { errorResponse } from './errors.mjs';
13
+ import { validateArgs } from './schema.mjs';
13
14
  import { telegramTools } from './telegram.mjs';
14
15
 
15
16
  /* ------------------------------------------------------------------ *
@@ -72,6 +73,11 @@ export class Engine {
72
73
  record({ kind: 'call', status: 'rejected', error: 'UNKNOWN_TOOL', via: 'direct' });
73
74
  return errorResponse('UNKNOWN_TOOL', { message: `unknown tool: ${name}`, tool: name, hint });
74
75
  }
76
+ const valid = validateArgs(tool.schema, tool.required, args);
77
+ if (!valid.ok) {
78
+ record({ kind: 'call', status: 'rejected', error: 'INVALID_ARGS', via: 'validation' });
79
+ return errorResponse('INVALID_ARGS', { message: valid.message, field: valid.field });
80
+ }
75
81
  const started = Date.now();
76
82
  let approval = null;
77
83
  const entryId = `${new Date().toISOString().replace(/[:.]/g, '-')}-${String(name).replace(/[^\w.-]/g, '_')}-${Math.random()
package/src/errors.mjs CHANGED
@@ -17,6 +17,7 @@ export const ERROR_CODES = {
17
17
  UNKNOWN_TOOL: { message: 'unknown tool', hint: 'GET /tools for catalog', retryable: false },
18
18
  INVALID_ARGS: { message: 'arguments are missing or malformed', hint: 'check the tool schema in GET /tools', retryable: false },
19
19
  RATE_LIMITED: { message: 'too many calls in a short time', hint: 'wait a second and retry', retryable: true },
20
+ DEVICE_BUSY: { message: 'the target device queue is full', hint: 'wait and retry the call', retryable: true },
20
21
  };
21
22
 
22
23
  export function errorResponse(code, extra = {}) {
package/src/hub.mjs CHANGED
@@ -1,18 +1,23 @@
1
1
  import http from 'node:http';
2
2
  import { VERSION } from './version.mjs';
3
3
  import crypto from 'node:crypto';
4
- import { sendJson, sendText, readJson, readBody, isAuthorized, bearer, safeEqual, actorFor } from './http.mjs';
4
+ import { sendJson, sendText, sendRaw, readJson, readBody, isAuthorized, bearer, safeEqual, actorFor } from './http.mjs';
5
5
  import { handleMcp } from './mcp.mjs';
6
6
  import { buildPrompt } from './prompt.mjs';
7
7
  import { toolCatalog } from './engine.mjs';
8
8
  import { listApprovals, decide } from './approvals.mjs';
9
9
  import { checkPath } from './policy.mjs';
10
- import { loadConfig } from './config.mjs';
10
+ import { loadConfig, CONFIG_DIR } from './config.mjs';
11
11
  import fsp from 'node:fs/promises';
12
- import { audit } from './audit.mjs';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { audit, auditPage, auditDir, findEntry, headCursor, lean, readArtifact, tailAudit } from './audit.mjs';
13
15
  import { sourceOf, describeSource, admitUnauthorized } from './source.mjs';
16
+ import { errorResponse } from './errors.mjs';
17
+ import { trustState } from './trust.mjs';
14
18
 
15
19
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
20
+ const MAX_QUEUED_PER_DEVICE = 100;
16
21
 
17
22
  function deviceTokens(cfg) {
18
23
  const list = [];
@@ -34,10 +39,23 @@ export function createHubServer(cfg) {
34
39
  const queues = new Map(); // name -> [{id, tool, args}]
35
40
  const jobs = new Map(); // id -> { resolve, timer }
36
41
 
37
- const dispatch = (device, tool, args, timeoutSec = 120, source = null) =>
38
- new Promise((resolve) => {
42
+ const removeQueued = (device, id) => {
43
+ const q = queues.get(device);
44
+ if (!q) return;
45
+ const remaining = q.filter((job) => job.id !== id);
46
+ if (remaining.length) queues.set(device, remaining);
47
+ else queues.delete(device);
48
+ };
49
+
50
+ const dispatch = (device, tool, args, timeoutSec = 120, source = null) => {
51
+ const q = queues.get(device) || [];
52
+ if (q.length >= MAX_QUEUED_PER_DEVICE) {
53
+ return Promise.resolve(errorResponse('DEVICE_BUSY', { reason: `device "${device}" has too many queued jobs` }));
54
+ }
55
+ return new Promise((resolve) => {
39
56
  const id = crypto.randomUUID();
40
57
  const timer = setTimeout(() => {
58
+ removeQueued(device, id);
41
59
  jobs.delete(id);
42
60
  resolve({
43
61
  ok: false,
@@ -46,10 +64,10 @@ export function createHubServer(cfg) {
46
64
  });
47
65
  }, (timeoutSec + 15) * 1000);
48
66
  jobs.set(id, { resolve, timer });
49
- const q = queues.get(device) || [];
50
67
  q.push({ id, tool, args, source });
51
68
  queues.set(device, q);
52
69
  });
70
+ };
53
71
 
54
72
  const callTool = async (tool, args, source = null) => {
55
73
  const device = args?.device || cfg.device;
@@ -90,10 +108,27 @@ export function createHubServer(cfg) {
90
108
 
91
109
  try {
92
110
  if (p === '/health') {
111
+ const current = loadConfig();
112
+ let pending = 0, auditCount = 0, logSize = 0;
113
+ try { pending = listApprovals().filter((item) => item.status === 'pending').length; } catch {}
114
+ try { auditCount = tailAudit(500).length; } catch {}
115
+ try {
116
+ const log = path.join(CONFIG_DIR, 'logs', 'bridge.log');
117
+ if (fs.existsSync(log)) logSize = fs.statSync(log).size;
118
+ } catch {}
93
119
  return sendJson(res, 200, {
94
120
  ok: true,
95
121
  mode: 'hub',
96
122
  version: VERSION,
123
+ device: current.device,
124
+ uptime_sec: Math.round(process.uptime()),
125
+ pending_approvals: pending,
126
+ trust_active: !!trustState().active,
127
+ audit_count: auditCount,
128
+ log_size: logSize,
129
+ has_public_url: !!current.publicUrl,
130
+ public_url: current.publicUrl ?? null,
131
+ tunnel_alive: null,
97
132
  devices: [...devices.keys()],
98
133
  });
99
134
  }
@@ -168,6 +203,80 @@ export function createHubServer(cfg) {
168
203
  return sendJson(res, 200, { ok: true, approvals: listApprovals() });
169
204
  }
170
205
 
206
+ if (req.method === 'GET' && /^\/approvals\/[\w-]+$/.test(p)) {
207
+ const id = p.split('/').pop();
208
+ const approval = listApprovals().find((item) => item.id === id);
209
+ if (!approval) return sendJson(res, 404, { ok: false, error: 'approval_not_found' });
210
+ return sendJson(res, 200, { ok: true, approval });
211
+ }
212
+
213
+ if (req.method === 'GET' && p === '/config') {
214
+ const current = loadConfig();
215
+ return sendJson(res, 200, {
216
+ ok: true,
217
+ device: current.device,
218
+ roots: current.roots,
219
+ protected_count: current.protected.length,
220
+ requireApproval: current.requireApproval,
221
+ allowShell: current.allowShell,
222
+ approvalWaitSec: current.approvalWaitSec,
223
+ maxOutputBytes: current.maxOutputBytes,
224
+ telegram: {
225
+ enabled: !!current.telegram?.enabled,
226
+ chat_ids: current.telegram?.chatIds || [],
227
+ },
228
+ });
229
+ }
230
+
231
+ if (req.method === 'GET' && p === '/audit') {
232
+ const q = url.searchParams;
233
+ const raw = q.get('limit');
234
+ const limit = raw === null || raw === '' ? 100 : Number(raw);
235
+ if (!Number.isFinite(limit) || limit <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
236
+ const page = auditPage({
237
+ limit: Math.min(500, Math.floor(limit)),
238
+ before: q.get('before') || undefined,
239
+ after: q.get('after') || undefined,
240
+ tool: q.get('tool') || undefined,
241
+ kind: q.get('kind') || undefined,
242
+ level: q.get('level') || undefined,
243
+ });
244
+ if (page.error) return sendJson(res, 400, { ok: false, error: page.error });
245
+ return sendJson(res, 200, {
246
+ ok: true,
247
+ entries: page.entries.map(lean),
248
+ next: page.next,
249
+ has_more: page.has_more,
250
+ reset: page.reset,
251
+ head: headCursor(),
252
+ artifacts_dir: auditDir(),
253
+ });
254
+ }
255
+
256
+ if (req.method === 'GET' && p === '/audit/entry') {
257
+ const id = url.searchParams.get('id');
258
+ if (!id) return sendJson(res, 400, { ok: false, error: 'id query parameter is required' });
259
+ const entry = findEntry(id);
260
+ if (!entry) return sendJson(res, 404, { ok: false, error: 'entry_not_found' });
261
+ return sendJson(res, 200, { ok: true, entry });
262
+ }
263
+
264
+ if (req.method === 'GET' && p === '/audit/artifact') {
265
+ const entry = url.searchParams.get('entry');
266
+ const file = url.searchParams.get('file');
267
+ if (!entry || !file) return sendJson(res, 400, { ok: false, error: 'entry and file query parameters are required' });
268
+ const art = readArtifact(entry, file);
269
+ if (!art) return sendJson(res, 404, { ok: false, error: 'artifact_not_found' });
270
+ const type = /\.png$/i.test(art.file)
271
+ ? 'image/png'
272
+ : /\.jpe?g$/i.test(art.file)
273
+ ? 'image/jpeg'
274
+ : /\.json$/i.test(art.file)
275
+ ? 'application/json; charset=utf-8'
276
+ : 'text/plain; charset=utf-8';
277
+ return sendRaw(res, 200, art.data, type);
278
+ }
279
+
171
280
  const approveMatch = /^\/approvals\/([\w-]+)$/.exec(p);
172
281
  if (req.method === 'POST' && approveMatch) {
173
282
  // settling a request is a local-only privilege: the agent token must not self-approve
@@ -259,4 +368,4 @@ export function createHubServer(cfg) {
259
368
  return server;
260
369
  }
261
370
 
262
- export { sleep };
371
+ export { sleep };
package/src/schema.mjs ADDED
@@ -0,0 +1,38 @@
1
+ function actualType(value) {
2
+ if (value === null) return 'null';
3
+ if (Array.isArray(value)) return 'array';
4
+ return typeof value;
5
+ }
6
+
7
+ function matchesType(value, type) {
8
+ if (type === 'number') return typeof value === 'number' && Number.isFinite(value);
9
+ if (type === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value);
10
+ if (type === 'array') return Array.isArray(value);
11
+ return actualType(value) === type;
12
+ }
13
+
14
+ /** Validate the shallow JSON schemas exposed by the tool catalog. */
15
+ export function validateArgs(schema, required = [], args) {
16
+ if (!matchesType(args, 'object')) {
17
+ return { ok: false, field: null, message: `arguments must be an object, got ${actualType(args)}` };
18
+ }
19
+
20
+ const properties = schema?.properties || {};
21
+ for (const key of Object.keys(args)) {
22
+ if (schema?.additionalProperties === false && !Object.hasOwn(properties, key)) {
23
+ return { ok: false, field: key, message: `unknown argument: ${key}` };
24
+ }
25
+ }
26
+ for (const key of required || []) {
27
+ if (!Object.hasOwn(args, key) || args[key] === undefined) {
28
+ return { ok: false, field: key, message: `argument is required: ${key}` };
29
+ }
30
+ }
31
+ for (const [key, spec] of Object.entries(properties)) {
32
+ if (!Object.hasOwn(args, key) || args[key] === undefined || !spec?.type) continue;
33
+ if (!matchesType(args[key], spec.type)) {
34
+ return { ok: false, field: key, message: `argument ${key} must be ${spec.type}, got ${actualType(args[key])}` };
35
+ }
36
+ }
37
+ return { ok: true };
38
+ }
package/src/version.mjs CHANGED
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
- export const VERSION = "0.18.15";
6
+ export const VERSION = "0.19.0";
7
7
 
8
8
  export function getVersion() {
9
9
  try {