arena-bridge 0.11.0 → 0.12.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,24 @@ 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.12.0
8
+
9
+ ### Added
10
+ - Trust window events: open, extend, change, close and expire, each logged once; changes made by another writer (such as the app) are logged as external. The `trust` command takes `--source`.
11
+ - Bridge start and stop, and tunnel up and down, are logged with their origin.
12
+ - `GET /audit` pages with `before`, `after`, `tool`, `kind` and `level` filters; `GET /audit/entry?id=` returns the full record.
13
+ - `POST /log/event` accepts interface step events. `GET /v1/events` sends new audit records as they arrive.
14
+
15
+ ### Changed
16
+ - The audit log rotates into 5 MB segments; retention keeps 7 days and at most 20 MB of audit log (the newest archive is never removed) and 7 days and at most 200 MB of artifacts.
17
+ - `arena-bridge cleanup` removes artifacts older than 7 days by default (was 14).
18
+
19
+ ### Fixed
20
+ - The macOS release job uploads the app checksums with the release checksums file instead of failing.
21
+
22
+ ### CI
23
+ - npm publishing uses trusted publishing (OIDC) with Node 24; no npm token is used.
24
+
7
25
  ## 0.11.0
8
26
 
9
27
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arena-bridge",
3
- "version": "0.11.0",
3
+ "version": "0.12.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 && 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",
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 && node --test test/log-paging.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 && node --test test/log-paging.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/approvals.mjs CHANGED
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
4
  import { APPROVALS_DIR, ensureDirs } from './config.mjs';
5
5
  import { sendTelegram, approvalKeyboard } from './telegram.mjs';
6
- import { saveTrust } from './trust.mjs';
6
+ import { openTrust } from './trust.mjs';
7
7
 
8
8
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
9
9
 
@@ -64,13 +64,11 @@ export function decide(id, decision, by = 'cli') {
64
64
  export function settle(id, decision, by = 'cli', { trustSec = 0 } = {}) {
65
65
  const res = decide(id, decision, by);
66
66
  if (res.ok && trustSec > 0) {
67
- saveTrust({
68
- enabled: true,
67
+ openTrust({
69
68
  until: Date.now() + trustSec * 1000,
70
69
  tools: [], // blanket: all tools, any agent
71
70
  paths: [],
72
- createdAt: Date.now(),
73
- });
71
+ }, { via: 'approval' });
74
72
  }
75
73
  return res;
76
74
  }
package/src/audit.mjs CHANGED
@@ -8,13 +8,25 @@ function configDir() {
8
8
  return process.env.ARENA_BRIDGE_HOME || CONFIG_DIR;
9
9
  }
10
10
 
11
+ const ACTIVE = 'audit.log';
12
+ const ARCHIVE = /^audit-\d{13}\.log$/;
13
+
11
14
  export function auditPath() {
12
- return path.join(configDir(), 'audit.log');
15
+ return path.join(configDir(), ACTIVE);
13
16
  }
14
17
 
15
18
  export const LEVELS = ['info', 'notice', 'warning', 'alert'];
16
19
  const ARGS_INLINE_BYTES = 64 * 1024;
17
20
  const FIELD_CLIP = 4000;
21
+ const ROTATE_BYTES = 5 * 1024 * 1024;
22
+ const RETAIN_DAYS = 7;
23
+ const RETAIN_BYTES = 20 * 1024 * 1024;
24
+ const ART_RETAIN_DAYS = 7;
25
+ const ART_RETAIN_BYTES = 200 * 1024 * 1024;
26
+ const READ_CHUNK = 256 * 1024;
27
+ const SCAN_BUDGET = 8 * 1024 * 1024;
28
+ const LEAN_DROP = ['args', 'result', 'output', 'stdout', 'stderr', 'content', 'body', 'data'];
29
+ const LEAN_CLIP = 300;
18
30
 
19
31
  const SECRETS = [
20
32
  /(?<!\d)\d{6,12}:[A-Za-z0-9_-]{25,}/g, // telegram bot tokens
@@ -54,7 +66,7 @@ export function levelFor({ kind = 'call', status = '', level } = {}) {
54
66
  if (kind === 'auth' || (kind === 'approval' && status === 'forbidden')) return 'alert';
55
67
  if (kind === 'note') return status === 'ok' ? 'info' : 'warning';
56
68
  if (status === 'ok') return 'info';
57
- if (['trust', 'service', 'tunnel', 'log', 'approval'].includes(kind)) return 'notice';
69
+ if (['trust', 'service', 'tunnel', 'log', 'approval', 'step'].includes(kind)) return 'notice';
58
70
  return 'warning';
59
71
  }
60
72
 
@@ -92,10 +104,7 @@ function argsFor(id, args) {
92
104
 
93
105
  export function audit(entry = {}) {
94
106
  try {
95
- const dir = configDir();
96
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
97
- // auto-rotate if over 10 MB (cheap stat, keeps log bounded)
98
- try { const st = fs.statSync(auditPath()); if (st.size > 10*1024*1024) rotateAuditIfNeeded(); } catch {}
107
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
99
108
  const { id, args, ...fields } = entry;
100
109
  const recId = String(id || newEntryId(fields.tool));
101
110
  const params = argsFor(recId, args);
@@ -111,65 +120,287 @@ export function audit(entry = {}) {
111
120
  args_truncated: params.truncated,
112
121
  ...(params.artifact ? { args_artifact: params.artifact } : {}),
113
122
  };
114
- fs.appendFileSync(auditPath(), JSON.stringify(rec) + '\n', { mode: 0o600 });
123
+ const file = auditPath();
124
+ fs.appendFileSync(file, JSON.stringify(rec) + '\n', { mode: 0o600 });
125
+ if (fs.statSync(file).size > ROTATE_BYTES) rotateAudit();
115
126
  } catch {
116
127
  /* auditing must never break the request */
117
128
  }
118
129
  }
119
130
 
120
- export function tailAudit(n = 50) {
121
- const file = auditPath();
122
- if (!fs.existsSync(file)) return [];
123
- // R6 fix: read from end, not whole file, to handle large audit.log
131
+ /* ------------------------------------------------------------------ *
132
+ * segments: the active file plus closed archives, oldest first
133
+ * ------------------------------------------------------------------ */
134
+
135
+ /** Last rotation only: maps the active file's previous name to its archive name, so open cursors survive it. */
136
+ const renamed = new Map();
137
+ const resolveName = (n) => renamed.get(n) || n;
138
+ const fileOf = (n) => path.join(configDir(), n);
139
+ const sizeOf = (n) => {
140
+ try {
141
+ return fs.statSync(fileOf(n)).size;
142
+ } catch {
143
+ return 0;
144
+ }
145
+ };
146
+
147
+ export function segments() {
148
+ let names = [];
149
+ try {
150
+ names = fs.readdirSync(configDir()).filter((f) => ARCHIVE.test(f)).sort();
151
+ } catch {
152
+ /* no log yet */
153
+ }
154
+ return [...names, ACTIVE];
155
+ }
156
+
157
+ const encode = (c) => (c ? Buffer.from(`${c.name}:${c.off}`).toString('base64url') : null);
158
+
159
+ function decode(token) {
160
+ const m = /^(.+):(\d+)$/.exec(Buffer.from(String(token), 'base64url').toString('utf8'));
161
+ if (!m || !(ARCHIVE.test(m[1]) || m[1] === ACTIVE)) return null;
162
+ return { name: resolveName(m[1]), off: Number(m[2]) };
163
+ }
164
+
165
+ /** Cursor at the very beginning of the oldest segment. */
166
+ export function startCursor() {
167
+ return encode({ name: segments()[0], off: 0 });
168
+ }
169
+
170
+ /** Cursor at the current end of the active file: new records are after it. */
171
+ export function headCursor() {
172
+ return encode({ name: ACTIVE, off: sizeOf(ACTIVE) });
173
+ }
174
+
175
+ /** Complete lines of one file, from the end backwards: { text, start, end } with byte offsets. */
176
+ function* backLines(file, end) {
177
+ let fd;
124
178
  try {
125
- const stat = fs.statSync(file);
126
- // if file small (<1MB), use simple path
127
- if (stat.size < 1024*1024) {
128
- const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
129
- return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
179
+ fd = fs.openSync(file, 'r');
180
+ } catch {
181
+ return;
182
+ }
183
+ try {
184
+ let pos = end;
185
+ let carry = Buffer.alloc(0);
186
+ for (;;) {
187
+ const from = Math.max(0, pos - READ_CHUNK);
188
+ const chunk = Buffer.alloc(pos - from);
189
+ if (chunk.length) fs.readSync(fd, chunk, 0, chunk.length, from);
190
+ pos = from;
191
+ const buf = Buffer.concat([chunk, carry]);
192
+ let hi = buf.length;
193
+ let i = hi > 0 ? buf.lastIndexOf(0x0a, hi - 1) : -1;
194
+ while (i !== -1) {
195
+ const s = i + 1;
196
+ if (hi > s) yield { text: buf.toString('utf8', s, hi), start: from + s, end: from + hi + 1 };
197
+ hi = i;
198
+ i = hi > 0 ? buf.lastIndexOf(0x0a, hi - 1) : -1;
199
+ }
200
+ carry = buf.subarray(0, hi);
201
+ if (from === 0) {
202
+ if (carry.length) yield { text: carry.toString('utf8'), start: 0, end: carry.length };
203
+ return;
204
+ }
130
205
  }
131
- // For large files, read last 512KB and get needed lines (reverse-read approximation)
132
- const fd = fs.openSync(file, 'r');
133
- const chunkSize = 512*1024;
134
- const start = Math.max(0, stat.size - chunkSize);
135
- const buf = Buffer.alloc(stat.size - start);
136
- fs.readSync(fd, buf, 0, buf.length, start);
206
+ } finally {
137
207
  fs.closeSync(fd);
138
- const lines = buf.toString('utf8').trim().split('\n').filter(Boolean);
139
- // If we didn't get enough due to truncation, fallback to reading more
140
- if (lines.length < n && start > 0) {
141
- const moreStart = Math.max(0, stat.size - chunkSize*4);
142
- const buf2 = Buffer.alloc(stat.size - moreStart);
143
- const fd2 = fs.openSync(file, 'r');
144
- fs.readSync(fd2, buf2, 0, buf2.length, moreStart);
145
- fs.closeSync(fd2);
146
- const lines2 = buf2.toString('utf8').trim().split('\n').filter(Boolean);
147
- return lines2.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
148
- }
149
- return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
208
+ }
209
+ }
210
+
211
+ /** Complete lines of one file, from an offset forwards, up to `budget` bytes. */
212
+ function forwardLines(name, off, budget) {
213
+ const out = [];
214
+ let fd;
215
+ try {
216
+ fd = fs.openSync(fileOf(name), 'r');
150
217
  } catch {
151
- // fallback to old method
152
- try {
153
- const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
154
- return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
155
- } catch { return []; }
218
+ return { lines: out, eof: true };
219
+ }
220
+ try {
221
+ const size = fs.fstatSync(fd).size;
222
+ let pos = off;
223
+ let used = 0;
224
+ while (pos < size && used < budget) {
225
+ let n = Math.min(READ_CHUNK, size - pos);
226
+ let buf;
227
+ let last;
228
+ for (;;) {
229
+ buf = Buffer.alloc(n);
230
+ fs.readSync(fd, buf, 0, n, pos);
231
+ last = buf.lastIndexOf(0x0a);
232
+ if (last !== -1 || pos + n >= size) break;
233
+ n = Math.min(n * 2, size - pos);
234
+ }
235
+ if (last === -1) break;
236
+ let s = 0;
237
+ while (s <= last && used < budget) {
238
+ const e = buf.indexOf(0x0a, s);
239
+ out.push({ text: buf.toString('utf8', s, e), end: pos + e + 1 });
240
+ used += e + 1 - s;
241
+ s = e + 1;
242
+ }
243
+ pos += s;
244
+ if (s <= last) break;
245
+ }
246
+ return { lines: out, eof: pos >= size };
247
+ } finally {
248
+ fs.closeSync(fd);
156
249
  }
157
250
  }
158
251
 
159
- export function rotateAuditIfNeeded(maxBytes = 10*1024*1024) {
160
- const file = auditPath();
161
- if (!fs.existsSync(file)) return;
252
+ function parse(text) {
162
253
  try {
163
- const stat = fs.statSync(file);
164
- if (stat.size > maxBytes) {
165
- const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
166
- // keep last 50% of lines
167
- const keep = lines.slice(Math.floor(lines.length/2));
168
- const tmp = file + '.tmp';
169
- fs.writeFileSync(tmp, keep.join('\n') + '\n', { mode: 0o600 });
170
- fs.renameSync(tmp, file);
254
+ return JSON.parse(text);
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+
260
+ /**
261
+ * One page of the log. Default: the newest `limit` records, oldest first, with `next` (older page).
262
+ * `before` pages further back. `after` reads forward from a cursor (new records).
263
+ */
264
+ export function auditPage({ limit = 100, before, after, tool, kind, level } = {}) {
265
+ const minLevel = level ? LEVELS.indexOf(level) : -1;
266
+ if (level && minLevel < 0) return { error: 'invalid level', entries: [], next: null, has_more: false };
267
+ const want = (rec) =>
268
+ (!tool || rec.tool === tool) && (!kind || rec.kind === kind) && (minLevel < 0 || LEVELS.indexOf(rec.level) >= minLevel);
269
+ const names = segments();
270
+ const out = [];
271
+ let scanned = 0;
272
+
273
+ if (after) {
274
+ const c = decode(after);
275
+ if (!c) return { error: 'invalid cursor', entries: [], next: null, has_more: false };
276
+ let ci = names.indexOf(c.name);
277
+ if (ci < 0) return { entries: [], next: headCursor(), has_more: false, reset: true };
278
+ let off = c.off;
279
+ let cur = c;
280
+ for (;;) {
281
+ const f = forwardLines(names[ci], off, SCAN_BUDGET - scanned);
282
+ for (const ln of f.lines) {
283
+ scanned += ln.end - off;
284
+ off = ln.end;
285
+ cur = { name: names[ci], off };
286
+ const rec = parse(ln.text);
287
+ if (rec && want(rec)) {
288
+ out.push(rec);
289
+ if (out.length >= limit) break;
290
+ }
291
+ }
292
+ if (out.length >= limit || scanned >= SCAN_BUDGET) break;
293
+ if (f.eof && ci < names.length - 1) {
294
+ ci++;
295
+ off = 0;
296
+ cur = { name: names[ci], off: 0 };
297
+ continue;
298
+ }
299
+ break;
300
+ }
301
+ const more = !(names.indexOf(cur.name) === names.length - 1 && cur.off >= sizeOf(ACTIVE));
302
+ return { entries: out, next: encode(cur), has_more: more, reset: false };
303
+ }
304
+
305
+ let ci = names.length - 1;
306
+ let off = sizeOf(names[ci]);
307
+ if (before) {
308
+ const c = decode(before);
309
+ if (!c) return { error: 'invalid cursor', entries: [], next: null, has_more: false };
310
+ ci = names.indexOf(c.name);
311
+ if (ci < 0) return { entries: [], next: null, has_more: false, reset: true };
312
+ off = c.off;
313
+ }
314
+ let cur = null;
315
+ outer: while (ci >= 0) {
316
+ for (const ln of backLines(fileOf(names[ci]), off)) {
317
+ cur = { name: names[ci], off: ln.start };
318
+ scanned += ln.end - ln.start;
319
+ const rec = parse(ln.text);
320
+ if (rec && want(rec)) {
321
+ out.push(rec);
322
+ if (out.length >= limit) break outer;
323
+ }
324
+ if (scanned >= SCAN_BUDGET) break outer;
171
325
  }
172
- } catch {}
326
+ ci--;
327
+ if (ci >= 0) off = sizeOf(names[ci]);
328
+ }
329
+ const done = ci < 0;
330
+ const more = !done && !(cur && cur.name === names[0] && cur.off === 0);
331
+ return { entries: out.reverse(), next: more ? encode(cur) : null, has_more: more, reset: false };
332
+ }
333
+
334
+ export function tailAudit(n = 50) {
335
+ return auditPage({ limit: n }).entries;
336
+ }
337
+
338
+ /** The record with this id, searched newest first, or null. */
339
+ export function findEntry(id) {
340
+ const names = segments();
341
+ for (let ci = names.length - 1; ci >= 0; ci--) {
342
+ for (const ln of backLines(fileOf(names[ci]), sizeOf(names[ci]))) {
343
+ if (!ln.text.includes(id)) continue;
344
+ const rec = parse(ln.text);
345
+ if (rec && rec.id === id) return rec;
346
+ }
347
+ }
348
+ return null;
349
+ }
350
+
351
+ /** The API view of a record: no parameters or bulky output, long strings clipped, plus a short args preview. */
352
+ export function lean(rec) {
353
+ const out = {};
354
+ for (const [k, v] of Object.entries(rec)) {
355
+ if (LEAN_DROP.includes(k)) continue;
356
+ out[k] = typeof v === 'string' && v.length > LEAN_CLIP ? `${v.slice(0, LEAN_CLIP)}…` : v;
357
+ }
358
+ if (rec.args !== undefined) out.args_preview = JSON.stringify(rec.args).slice(0, 200);
359
+ return out;
360
+ }
361
+
362
+ /** Close the active file into an archive. The newest archive is never removed by retention. */
363
+ export function rotateAudit(now = Date.now()) {
364
+ const file = auditPath();
365
+ if (!fs.existsSync(file)) return null;
366
+ let ms = now;
367
+ let name;
368
+ do {
369
+ name = `audit-${String(ms).padStart(13, '0')}.log`;
370
+ ms++;
371
+ } while (fs.existsSync(fileOf(name)));
372
+ fs.renameSync(file, fileOf(name));
373
+ renamed.set(ACTIVE, name);
374
+ pruneAudit();
375
+ return name;
376
+ }
377
+
378
+ /** Delete archives older than `days`, then the oldest ones while the total is above `maxBytes`. */
379
+ export function pruneAudit({ days = RETAIN_DAYS, maxBytes = RETAIN_BYTES, now = Date.now() } = {}) {
380
+ const archives = segments()
381
+ .slice(0, -1)
382
+ .map((name) => {
383
+ try {
384
+ const st = fs.statSync(fileOf(name));
385
+ return { name, size: st.size, mtime: st.mtimeMs };
386
+ } catch {
387
+ return null;
388
+ }
389
+ })
390
+ .filter(Boolean);
391
+ let total = archives.reduce((s, f) => s + f.size, sizeOf(ACTIVE));
392
+ const cutoff = now - Number(days) * 86400000;
393
+ let removed = 0;
394
+ let freed = 0;
395
+ for (let i = 0; i < archives.length - 1; i++) {
396
+ const f = archives[i];
397
+ if (f.mtime >= cutoff && total <= maxBytes) break;
398
+ fs.rmSync(fileOf(f.name), { force: true });
399
+ total -= f.size;
400
+ freed += f.size;
401
+ removed++;
402
+ }
403
+ return { removed, freed_bytes: freed };
173
404
  }
174
405
 
175
406
  /* ------------------------------------------------------------------ *
@@ -228,24 +459,47 @@ export function listArtifacts() {
228
459
  return out;
229
460
  }
230
461
 
231
- export function pruneArtifacts(days = 14) {
462
+ function dirBytes(sub) {
463
+ let n = 0;
464
+ try {
465
+ for (const f of fs.readdirSync(sub)) {
466
+ try {
467
+ n += fs.statSync(path.join(sub, f)).size;
468
+ } catch {
469
+ /* ignore */
470
+ }
471
+ }
472
+ } catch {
473
+ /* ignore */
474
+ }
475
+ return n;
476
+ }
477
+
478
+ /** Remove artifact folders older than `days`, then the oldest while the total is above `maxBytes`. */
479
+ export function pruneArtifacts(days = ART_RETAIN_DAYS, maxBytes = ART_RETAIN_BYTES) {
232
480
  const dir = auditDir();
233
481
  if (!fs.existsSync(dir)) return { removed: 0, freed_bytes: 0 };
234
482
  const cutoff = Date.now() - Number(days) * 86400000;
235
- let removed = 0;
236
- let freed = 0;
483
+ const folders = [];
237
484
  for (const entry of fs.readdirSync(dir)) {
238
485
  const sub = path.join(dir, entry);
239
486
  try {
240
487
  const st = fs.statSync(sub);
241
- if (st.mtimeMs < cutoff) {
242
- freed += st.size;
243
- fs.rmSync(sub, { recursive: true, force: true });
244
- removed++;
245
- }
488
+ if (st.isDirectory()) folders.push({ sub, mtime: st.mtimeMs, size: dirBytes(sub) });
246
489
  } catch {
247
490
  /* ignore */
248
491
  }
249
492
  }
493
+ folders.sort((a, b) => a.mtime - b.mtime);
494
+ let total = folders.reduce((s, f) => s + f.size, 0);
495
+ let removed = 0;
496
+ let freed = 0;
497
+ for (const f of folders) {
498
+ if (f.mtime >= cutoff && total <= maxBytes) break;
499
+ fs.rmSync(f.sub, { recursive: true, force: true });
500
+ total -= f.size;
501
+ freed += f.size;
502
+ removed++;
503
+ }
250
504
  return { removed, freed_bytes: freed };
251
505
  }
package/src/cli.mjs CHANGED
@@ -14,7 +14,8 @@ import { pruneInbox } from './telegram.mjs';
14
14
  import { pruneApprovals } from './approvals.mjs';
15
15
  import { startTunnel, isPortOpen } from './tunnel.mjs';
16
16
  import { spawn, execSync, spawnSync } from 'node:child_process';
17
- import { parseDuration, trustState, saveTrust, clearTrust } from './trust.mjs';
17
+ import { parseDuration, trustState, openTrust, closeTrust, reconcileTrust } from './trust.mjs';
18
+ import { bridgeEvent, tunnelEvent } from './lifecycle.mjs';
18
19
  import { findPeekaboo } from './mac.mjs';
19
20
  import { coldStartMs, mem, uptimeSec } from './telemetry.mjs';
20
21
  import { tailLog, logPathForCli } from './log.mjs';
@@ -96,7 +97,7 @@ Commands:
96
97
  --paths p1,p2 only these paths (bash is not covered)
97
98
  --off | --status | --extend --for 1h
98
99
  audit [-n N] [--tool NAME] [--since DUR] [--from DATE] [--to DATE] [--json] Show the audit log
99
- cleanup [--days N] Remove old artifacts + approvals (default 14 days)
100
+ cleanup [--days N] Remove old artifacts + approvals (default 7 days)
100
101
  events [--json] Stream live events (approvals/audit) via SSE /v1/events
101
102
  logs [-n N] [--json] Show bridge.log (structured logs)
102
103
  config Manage configuration (get/set/edit)
@@ -189,11 +190,11 @@ async function cmdStart(args) {
189
190
  process.exit(1);
190
191
  }
191
192
  try {
192
- const { trustState, saveTrust } = await import('./trust.mjs');
193
+ const { trustState, openTrust } = await import('./trust.mjs');
193
194
  const st = trustState();
194
195
  if (!st.active) {
195
196
  const now = Date.now();
196
- saveTrust({ enabled: true, until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now });
197
+ openTrust({ until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now }, { via: 'launch', source: { channel: 'local' } });
197
198
  console.log('✓ trust window auto-opened for 3 h (all tools, any agent) — no approvals needed');
198
199
  }
199
200
  } catch {}
@@ -212,6 +213,7 @@ async function cmdStart(args) {
212
213
  process.exit(1);
213
214
  });
214
215
  server.listen(cfg.port, cfg.host, () => {
216
+ bridgeEvent('start', { port: cfg.port });
215
217
  const local = `http://${cfg.host}:${cfg.port}`;
216
218
  console.log(`arena-bridge listening on ${local} (device "${cfg.device}")`);
217
219
  console.log(`\nExpose it to the cloud agent, e.g.:\n cloudflared tunnel --url ${local}\n ngrok http ${cfg.port}\n tailscale funnel --bg ${cfg.port}\n`);
@@ -221,6 +223,7 @@ async function cmdStart(args) {
221
223
  console.log('-----8<-----');
222
224
  });
223
225
  const bye = () => {
226
+ bridgeEvent('stop', { reason: 'signal' });
224
227
  server.close(() => process.exit(0));
225
228
  setTimeout(() => process.exit(0), 2000).unref();
226
229
  };
@@ -241,11 +244,11 @@ async function cmdTunnel(args) {
241
244
 
242
245
  // Auto-open blanket trust window on start (3h, all tools, any agent) per user request
243
246
  try {
244
- const { trustState, saveTrust } = await import('./trust.mjs');
247
+ const { trustState, openTrust } = await import('./trust.mjs');
245
248
  const st = trustState();
246
249
  if (!st.active) {
247
250
  const now = Date.now();
248
- saveTrust({ enabled: true, until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now });
251
+ openTrust({ until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now }, { via: 'launch', source: { channel: 'local' } });
249
252
  console.log('✓ trust window auto-opened for 3 h (all tools, any agent) — no approvals needed');
250
253
  }
251
254
  } catch {}
@@ -256,6 +259,7 @@ async function cmdTunnel(args) {
256
259
  } else {
257
260
  server = createDirectServer(cfg, engine);
258
261
  await new Promise((r) => server.listen(port, cfg.host, r));
262
+ bridgeEvent('start', { port });
259
263
  console.log(`arena-bridge API on http://${cfg.host}:${port}`);
260
264
  }
261
265
 
@@ -266,6 +270,7 @@ async function cmdTunnel(args) {
266
270
  bin,
267
271
  authtoken: args.flags.authtoken,
268
272
  domain: args.flags.domain,
273
+ onExit: (code) => tunnelEvent('down', { code }),
269
274
  });
270
275
 
271
276
  let publicUrl;
@@ -288,6 +293,7 @@ async function cmdTunnel(args) {
288
293
 
289
294
  cfg.publicUrl = publicUrl;
290
295
  cfg.port = port;
296
+ tunnelEvent('up', { url: new URL(publicUrl).host });
291
297
  saveConfig(cfg);
292
298
 
293
299
  onUrl((url) => {
@@ -295,6 +301,7 @@ async function cmdTunnel(args) {
295
301
  publicUrl = url;
296
302
  cfg.publicUrl = url;
297
303
  saveConfig(cfg);
304
+ tunnelEvent('up', { url: new URL(url).host, reason: 'reconnected' });
298
305
  console.log(`\n⚠ tunnel reconnected — new public URL: ${url}`);
299
306
  console.log('Update the base URL in the agent chat (arena-bridge prompt prints a fresh copy).');
300
307
  });
@@ -307,6 +314,7 @@ async function cmdTunnel(args) {
307
314
  console.log('Ctrl+C stops both the tunnel and the API.');
308
315
 
309
316
  const bye = () => {
317
+ bridgeEvent('stop', { reason: 'signal' });
310
318
  try {
311
319
  child.kill();
312
320
  } catch {
@@ -411,11 +419,14 @@ function cmdApprove(args) {
411
419
 
412
420
  function cmdTrust(args) {
413
421
  const state = trustState();
422
+ reconcileTrust();
423
+ const via = /^[a-z]{1,20}$/.test(String(args.flags.source || '')) ? args.flags.source : 'cli';
424
+ const source = { channel: 'cli' };
414
425
  if (args.flags.extend || args.flags.extend) {
415
426
  const cur = trustState();
416
427
  if (!cur.active) { console.error('no active trust window to extend — use arena-bridge trust --for 2h'); process.exit(1); }
417
428
  const ms = parseDuration(args.flags.for || args.flags.extend || '1h');
418
- const saved = saveTrust({ ...cur, until: cur.until + ms, enabled: true, createdAt: cur.createdAt || Date.now() });
429
+ const saved = openTrust({ ...cur, until: cur.until + ms, createdAt: cur.createdAt || Date.now() }, { via, source });
419
430
  console.log(`✓ trust window extended: until ${new Date(saved.until).toLocaleString()} (+${Math.round(ms/60000)} min)`);
420
431
  return;
421
432
  }
@@ -430,7 +441,7 @@ function cmdTrust(args) {
430
441
  return;
431
442
  }
432
443
  if (args.flags.off) {
433
- clearTrust();
444
+ closeTrust({ via, source });
434
445
  console.log('✓ trust window cleared — every side-effecting action needs approval again');
435
446
  return;
436
447
  }
@@ -465,13 +476,7 @@ function cmdTrust(args) {
465
476
  .filter(Boolean);
466
477
  const tools = list(args.flags.tools);
467
478
  const paths = list(args.flags.paths).map((p) => path.resolve(p.replace(/^~/, os.homedir())));
468
- const saved = saveTrust({
469
- enabled: true,
470
- until: Date.now() + ms,
471
- tools,
472
- paths,
473
- createdAt: Date.now(),
474
- });
479
+ const saved = openTrust({ until: Date.now() + ms, tools, paths, createdAt: Date.now() }, { via, source });
475
480
  console.log(`✓ trust window: until ${new Date(saved.until).toLocaleString()} (${Math.round(ms / 60000)} min)`);
476
481
  console.log(` tools: ${tools.length ? tools.join(', ') : 'all side-effecting tools'}`);
477
482
  console.log(` paths: ${paths.length ? paths.join(', ') : 'no path restriction'}`);
@@ -485,7 +490,7 @@ function cmdAudit(args) {
485
490
  return;
486
491
  }
487
492
  if (what === 'prune') {
488
- const res = pruneArtifacts(Number(args.flags.days || 14));
493
+ const res = pruneArtifacts(Number(args.flags.days || 7));
489
494
  console.log(`removed ${res.removed} artifact folder(s), ${res.freed_bytes} bytes`);
490
495
  return;
491
496
  }
package/src/direct.mjs CHANGED
@@ -8,7 +8,8 @@ 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, audit } from './audit.mjs';
11
+ import { tailAudit, readArtifact, auditDir, audit, auditPage, findEntry, lean, headCursor, LEVELS, pruneAudit, pruneArtifacts } from './audit.mjs';
12
+ import { reconcileTrust } from './trust.mjs';
12
13
  import { describeSource, sourceOf, admitUnauthorized } from './source.mjs';
13
14
  import { errorResponse } from './errors.mjs';
14
15
  import { startPoller, parseCommand, sendTelegram, answerCallback, editMessageText } from './telegram.mjs';
@@ -136,14 +137,49 @@ export function createDirectServer(cfg, engine) {
136
137
  }
137
138
 
138
139
  if (req.method === 'GET' && p === '/audit') {
139
- const raw = url.searchParams.get('limit');
140
- let limit = 30;
141
- if (raw !== null && raw !== '') {
142
- const parsed = Number(raw);
143
- if (!Number.isFinite(parsed) || parsed <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
144
- limit = Math.min(200, Math.floor(parsed));
145
- }
146
- return sendJson(res, 200, { ok: true, entries: tailAudit(limit), artifacts_dir: auditDir() });
140
+ const q = url.searchParams;
141
+ const raw = q.get('limit');
142
+ const limit = raw === null || raw === '' ? 100 : Number(raw);
143
+ if (!Number.isFinite(limit) || limit <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
144
+ const page = auditPage({
145
+ limit: Math.min(500, Math.floor(limit)),
146
+ before: q.get('before') || undefined,
147
+ after: q.get('after') || undefined,
148
+ tool: q.get('tool') || undefined,
149
+ kind: q.get('kind') || undefined,
150
+ level: q.get('level') || undefined,
151
+ });
152
+ if (page.error) return sendJson(res, 400, { ok: false, error: page.error });
153
+ return sendJson(res, 200, {
154
+ ok: true,
155
+ entries: page.entries.map(lean),
156
+ next: page.next,
157
+ has_more: page.has_more,
158
+ reset: page.reset,
159
+ head: headCursor(),
160
+ artifacts_dir: auditDir(),
161
+ });
162
+ }
163
+
164
+ if (req.method === 'GET' && p === '/audit/entry') {
165
+ const id = url.searchParams.get('id');
166
+ if (!id) return sendJson(res, 400, { ok: false, error: 'id query parameter is required' });
167
+ const entry = findEntry(id);
168
+ if (!entry) return sendJson(res, 404, { ok: false, error: 'entry_not_found' });
169
+ return sendJson(res, 200, { ok: true, entry });
170
+ }
171
+
172
+ if (req.method === 'POST' && p === '/log/event') {
173
+ // Interface steps only: trust and service events are written by their own modules.
174
+ const body = await readJson(req, 16 * 1024);
175
+ const tool = typeof body.tool === 'string' ? body.tool : 'gui';
176
+ const level = body.level ?? 'notice';
177
+ const ok = body.kind === 'step' && typeof body.status === 'string' && body.status.length <= 20
178
+ && typeof body.message === 'string' && body.message.length <= 500
179
+ && LEVELS.includes(level) && /^[\w.-]{1,40}$/.test(tool);
180
+ if (!ok) return sendJson(res, 400, { ok: false, error: 'invalid event' });
181
+ audit({ kind: 'step', tool, status: body.status, level, message: body.message, via: 'gui', actor: 'user', source: describeSource(req, 'http') });
182
+ return sendJson(res, 200, { ok: true });
147
183
  }
148
184
 
149
185
  if (req.method === 'GET' && p === '/audit/artifact') {
@@ -292,11 +328,15 @@ export function createDirectServer(cfg, engine) {
292
328
  const pending = listApprovals().filter(a=>a.status==='pending');
293
329
  send('approvals', { pending: pending.length, approvals: pending.slice(0,10) });
294
330
  } catch {}
295
- try { const { tailAudit } = await import('./audit.mjs'); send('audit', { entries: tailAudit(5) }); } catch {}
331
+ let cursor = headCursor();
332
+ try { send('audit', { entries: tailAudit(5).map(lean) }); } catch {}
296
333
  send('hello', { version: VERSION, time: new Date().toISOString() });
297
334
  const interval = setInterval(async ()=>{
298
335
  if (closed) { clearInterval(interval); return; }
299
336
  try {
337
+ const delta = auditPage({ after: cursor, limit: 200 });
338
+ cursor = delta.next || cursor;
339
+ if (delta.entries.length) send('audit', { entries: delta.entries.map(lean) });
300
340
  const pending = listApprovals().filter(a=>a.status==='pending');
301
341
  // simple: send heartbeat + counts every tick; client can diff
302
342
  send('heartbeat', { ts: Date.now(), pending_approvals: pending.length });
@@ -326,7 +366,12 @@ export function createDirectServer(cfg, engine) {
326
366
  });
327
367
 
328
368
  const poller = startPoller(cfg, { onMessage: handleTelegramMessage, onCallback: handleTelegramCallback });
329
- server.on('close', () => poller?.stop());
369
+ try { reconcileTrust(); pruneAudit(); pruneArtifacts(); } catch {}
370
+ const maint = setInterval(() => { try { reconcileTrust(); } catch {} }, 5000);
371
+ const sweep = setInterval(() => { try { pruneAudit(); pruneArtifacts(); } catch {} }, 3600000);
372
+ maint.unref();
373
+ sweep.unref();
374
+ server.on('close', () => { poller?.stop(); clearInterval(maint); clearInterval(sweep); });
330
375
 
331
376
  return server;
332
377
  }
@@ -0,0 +1,13 @@
1
+ import { audit } from './audit.mjs';
2
+ import { VERSION } from './version.mjs';
3
+
4
+ /** Launchd jobs set XPC_SERVICE_NAME; anything else was started by hand. */
5
+ const origin = () => (process.env.XPC_SERVICE_NAME ? 'launchd' : 'cli');
6
+
7
+ export function bridgeEvent(status, { port, reason } = {}) {
8
+ audit({ kind: 'service', tool: 'bridge', status, via: origin(), source: { channel: 'local' }, pid: process.pid, version: VERSION, port, reason });
9
+ }
10
+
11
+ export function tunnelEvent(status, extra = {}) {
12
+ audit({ kind: 'tunnel', tool: 'tunnel', status, via: origin(), ...extra });
13
+ }
package/src/trust.mjs CHANGED
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { CONFIG_DIR, ensureDirs } from './config.mjs';
4
4
  import { isInside, resolveTarget } from './policy.mjs';
5
+ import { audit } from './audit.mjs';
5
6
 
6
7
  export const TRUST_PATH = path.join(CONFIG_DIR, 'trust.json');
7
8
 
@@ -36,17 +37,90 @@ export function clearTrust() {
36
37
  if (fs.existsSync(TRUST_PATH)) fs.rmSync(TRUST_PATH);
37
38
  }
38
39
 
39
- /** Normalised view of the trust window: { active, until, tools, paths, expired }. */
40
- export function pruneExpiredTrust() {
40
+ /*
41
+ * Every writer (CLI, approvals, app launch, expiry) goes through openTrust/closeTrust, which log one event.
42
+ * trust.marker holds the signature of the last state that was logged; reconcileTrust compares it with the file,
43
+ * so a change made by another writer (for example the app) is logged once, as external.
44
+ */
45
+ const MARKER = path.join(path.dirname(TRUST_PATH), 'trust.marker');
46
+ const signature = (t) =>
47
+ t && t.enabled !== false && t.until ? `${t.until}|${(t.tools || []).join(',')}|${(t.paths || []).join(',')}` : 'none';
48
+ const readMarker = () => {
41
49
  try {
42
- const cur = trustState();
43
- if (cur && cur.until && Date.now() > cur.until && cur.active) {
44
- clearTrust();
45
- return true;
46
- }
47
- } catch {}
50
+ return fs.readFileSync(MARKER, 'utf8');
51
+ } catch {
52
+ return null;
53
+ }
54
+ };
55
+ const writeMarker = (sig) => fs.writeFileSync(MARKER, sig, { mode: 0o600 });
56
+
57
+ function record(status, t, via, source = null, reason = null) {
58
+ audit({
59
+ kind: 'trust',
60
+ tool: 'trust',
61
+ status,
62
+ via,
63
+ source,
64
+ reason,
65
+ actor: via === 'expiry' || via === 'launch' ? 'bridge' : 'user',
66
+ until: t?.until ?? null,
67
+ tools: t?.tools || [],
68
+ paths: t?.paths || [],
69
+ });
70
+ }
71
+
72
+ /** Open or change the window. Records one event: open, extend (later end time) or change. */
73
+ export function openTrust(state, { via = 'cli', source = null } = {}) {
74
+ const prev = trustState();
75
+ const saved = saveTrust({
76
+ enabled: true,
77
+ until: state.until,
78
+ tools: state.tools || [],
79
+ paths: state.paths || [],
80
+ createdAt: state.createdAt || Date.now(),
81
+ });
82
+ writeMarker(signature(saved));
83
+ const status = !prev.active ? 'open' : saved.until > (prev.until || 0) ? 'extend' : 'change';
84
+ record(status, saved, via, source);
85
+ return saved;
86
+ }
87
+
88
+ /** Close the window by hand or from the app; records one close event. */
89
+ export function closeTrust({ via = 'cli', source = null, reason = 'manual' } = {}) {
90
+ const cur = loadTrust();
91
+ if (!cur) return false;
92
+ clearTrust();
93
+ writeMarker('none');
94
+ record('close', cur, via, source, reason);
95
+ return true;
96
+ }
97
+
98
+ /**
99
+ * Expire a window whose end time has passed (one expire event), and log changes made outside this module.
100
+ * Returns true when a window expired.
101
+ */
102
+ export function reconcileTrust(now = Date.now()) {
103
+ const t = loadTrust();
104
+ const cur = signature(t);
105
+ let mark = readMarker();
106
+ if (mark === null) {
107
+ writeMarker(cur);
108
+ mark = cur;
109
+ }
110
+ if (t && t.enabled !== false && t.until && t.until <= now) {
111
+ clearTrust();
112
+ writeMarker('none');
113
+ record('expire', t, 'expiry', null, 'expired');
114
+ return true;
115
+ }
116
+ if (cur !== mark) {
117
+ writeMarker(cur);
118
+ record(cur === 'none' ? 'close' : mark === 'none' ? 'open' : 'change', t, 'external', null, 'external');
119
+ }
48
120
  return false;
49
121
  }
122
+
123
+ /** Normalised view of the trust window: { active, until, tools, paths, expired }. */
50
124
  export function trustState() {
51
125
  const t = loadTrust();
52
126
  if (!t) return { active: false, until: null, tools: [], paths: [] };
package/src/tunnel.mjs CHANGED
@@ -45,7 +45,7 @@ export function killStaleNgrok(domain) {
45
45
 
46
46
  export function startTunnel(
47
47
  cfg,
48
- { port, protocol = 'http2', bin = 'cloudflared', authtoken, domain, restarts = 20, delay = 2000 } = {},
48
+ { port, protocol = 'http2', bin = 'cloudflared', authtoken, domain, restarts = 20, delay = 2000, onExit } = {},
49
49
  ) {
50
50
  const target = `http://127.0.0.1:${port}`;
51
51
  const isNgrok = /ngrok/i.test(bin);
@@ -97,6 +97,7 @@ export function startTunnel(
97
97
  }
98
98
  });
99
99
  child.on('exit', (code) => {
100
+ onExit?.(code);
100
101
  if (!settled) {
101
102
  if (isNgrok && attempt++ < restarts) {
102
103
  killStaleNgrok(domain);
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.11.0";
6
+ export const VERSION = "0.12.0";
7
7
 
8
8
  export function getVersion() {
9
9
  try {