agentinbox-cli 0.1.0-nightly.3 → 0.1.0-nightly.5
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/README.md +29 -4
- package/dist/{auth-B3ukRgpB.js → auth-D4yzhGUg.js} +119 -16
- package/dist/auth-D4yzhGUg.js.map +1 -0
- package/dist/auth-X5SGuNNB.js +2 -0
- package/dist/cli.js +102 -25
- package/dist/cli.js.map +1 -1
- package/dist/{instance-BnbMB2EK.js → instance-CpTBwgrK.js} +7 -3
- package/dist/{instance-BnbMB2EK.js.map → instance-CpTBwgrK.js.map} +1 -1
- package/dist/instance-Dh5kDs31.js +2 -0
- package/dist/{server-BvX0c9MQ.js → server-B0zZclGt.js} +76 -37
- package/dist/server-B0zZclGt.js.map +1 -0
- package/dist/service-CFnr0e9w.js +473 -0
- package/dist/service-CFnr0e9w.js.map +1 -0
- package/dist/{settings-DkA2sgzt.js → settings-BIuG-X7b.js} +12 -3
- package/dist/settings-BIuG-X7b.js.map +1 -0
- package/dist/settings-BK7h99j7.js +2 -0
- package/dist/skill-BJFn2bHK.js +2 -0
- package/dist/urls-Dp8pBGMU.js +2 -0
- package/dist/{urls-DmnonkJo.js → urls-U_LfYV61.js} +7 -2
- package/dist/urls-U_LfYV61.js.map +1 -0
- package/package.json +1 -1
- package/dist/auth-B3ukRgpB.js.map +0 -1
- package/dist/auth-B9dqCyaj.js +0 -2
- package/dist/instance-BEEO0AHU.js +0 -2
- package/dist/server-BvX0c9MQ.js.map +0 -1
- package/dist/service-lFSuvmgq.js +0 -332
- package/dist/service-lFSuvmgq.js.map +0 -1
- package/dist/settings-DkA2sgzt.js.map +0 -1
- package/dist/settings-DoPS659W.js +0 -2
- package/dist/skill-BWWtinsE.js +0 -2
- package/dist/urls-CNYhbeUQ.js +0 -2
- package/dist/urls-DmnonkJo.js.map +0 -1
package/README.md
CHANGED
|
@@ -216,14 +216,35 @@ Installs a background service that starts at boot: systemd on Linux (a user serv
|
|
|
216
216
|
service when run as root) and launchd on macOS. The service runs its own copy of agentinbox from the data directory,
|
|
217
217
|
so it never depends on the npx cache; a failed install leaves the running service as it was. Re-run `service install`
|
|
218
218
|
to update; `service status` and `service uninstall` do what you'd expect, and uninstalling keeps your data. Pass the same
|
|
219
|
-
`--port`, `--host` and `--data` options each time. `AGENTINBOX_MASTER_KEY`, `TRUST_PROXY`, `TRUST_PROXY_HOPS
|
|
220
|
-
`AGENTINBOX_LOG_LEVEL` are taken from your shell and remembered in `<data>/service.env`, so later
|
|
221
|
-
(set one to an empty value to remove it).
|
|
219
|
+
`--port`, `--host` and `--data` options each time. `AGENTINBOX_MASTER_KEY`, `TRUST_PROXY`, `TRUST_PROXY_HOPS`,
|
|
220
|
+
`TRUST_PROXY_FROM` and `AGENTINBOX_LOG_LEVEL` are taken from your shell and remembered in `<data>/service.env`, so later
|
|
221
|
+
installs keep them (set one to an empty value to remove it).
|
|
222
222
|
|
|
223
223
|
Only one agentinbox runs per data directory; a second one refuses to start.
|
|
224
224
|
|
|
225
225
|
When a newer version is published, the console shows **Update available** with the exact command to run.
|
|
226
226
|
|
|
227
|
+
The unit runs the Node.js binary you installed it with. If you remove or replace that Node, run `service install` again.
|
|
228
|
+
If the service doesn't come up, `service install` rolls back and prints where to look (`systemctl --user status
|
|
229
|
+
agentinbox`, `journalctl --user -u agentinbox`). Over `su` or `sudo -u` there is often no systemd user session: log
|
|
230
|
+
in as that user directly, or enable lingering and set `XDG_RUNTIME_DIR=/run/user/$(id -u)` first.
|
|
231
|
+
|
|
232
|
+
A service that hasn't been claimed yet doesn't print its setup token to the journal. Get the link with
|
|
233
|
+
`npx agentinbox-cli reset-password --data <dir>`, or read the token from `<data>/setup-token`.
|
|
234
|
+
|
|
235
|
+
### With your own supervisor
|
|
236
|
+
|
|
237
|
+
On other systems, or to manage it yourself (Docker, runit, supervisord, pm2), install the command and run it in the
|
|
238
|
+
foreground:
|
|
239
|
+
|
|
240
|
+
```sh
|
|
241
|
+
npm i -g agentinbox-cli
|
|
242
|
+
agentinbox start --no-open --data /var/lib/agentinbox
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Use the installed `agentinbox` binary rather than `npx`: npx doesn't pass stop signals on, so agentinbox wouldn't shut
|
|
246
|
+
down cleanly.
|
|
247
|
+
|
|
227
248
|
### Behind a reverse proxy
|
|
228
249
|
|
|
229
250
|
agentinbox serves plain HTTP. To expose it beyond your network, put it behind a TLS-terminating proxy (Caddy, nginx,
|
|
@@ -231,7 +252,10 @@ Tailscale Funnel) and:
|
|
|
231
252
|
|
|
232
253
|
- bind it to localhost: `--host 127.0.0.1`
|
|
233
254
|
- set `TRUST_PROXY=1`, so lockouts apply per client and cookies are marked `Secure`. The client address is taken from
|
|
234
|
-
the right end of `X-Forwarded-For`; with more than one proxy in front, set `TRUST_PROXY_HOPS` to their number
|
|
255
|
+
the right end of `X-Forwarded-For`; with more than one proxy in front, set `TRUST_PROXY_HOPS` to their number.
|
|
256
|
+
Forwarding headers are believed only from a proxy on the same host (loopback); if the proxy runs on another machine,
|
|
257
|
+
list its address in `TRUST_PROXY_FROM` (for example `TRUST_PROXY_FROM=10.0.0.5` or a CIDR like `10.0.0.0/24`; `/0` is refused). The proxy must append to (or overwrite)
|
|
258
|
+
`X-Forwarded-For`; a tunnel or proxy that passes the header through unchanged lets clients choose their own address
|
|
235
259
|
- set **Settings → Public URL** to the https address, so MCP snippets, the skill and the OAuth redirect use it
|
|
236
260
|
|
|
237
261
|
`GET /health` (or `/api/health`) needs no auth and suits uptime monitors: `200` when healthy, `503` when degraded, for
|
|
@@ -258,6 +282,7 @@ agentinbox reset-password [--data …]
|
|
|
258
282
|
| | `AGENTINBOX_MASTER_KEY` | | Base64 32-byte key for encrypting secrets, instead of `<data>/master.key` |
|
|
259
283
|
| | `TRUST_PROXY` | | `1` behind a reverse proxy: client IPs from `X-Forwarded-For`, https from `X-Forwarded-Proto` |
|
|
260
284
|
| | `TRUST_PROXY_HOPS` | `1` | Number of proxies in front of agentinbox (which `X-Forwarded-For` entry, from the right, is the client) |
|
|
285
|
+
| | `TRUST_PROXY_FROM` | loopback | Other proxy addresses whose forwarding headers are believed: comma-separated IPs or CIDRs (IPv4 or IPv6) |
|
|
261
286
|
| | `AGENTINBOX_LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` |
|
|
262
287
|
|
|
263
288
|
Forgot the admin password? Run `npx agentinbox-cli reset-password` on the server, as the user agentinbox runs as (`sudo` for a
|
|
@@ -129,6 +129,104 @@ function clientKey(ip) {
|
|
|
129
129
|
]).slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":")}::/64`;
|
|
130
130
|
}
|
|
131
131
|
//#endregion
|
|
132
|
+
//#region server/auth/proxy.ts
|
|
133
|
+
function parseV4(ip) {
|
|
134
|
+
return ip.split(".").reduce((acc, part) => acc << 8n | BigInt(Number(part)), 0n);
|
|
135
|
+
}
|
|
136
|
+
function parseAddress(raw) {
|
|
137
|
+
const ip = raw.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "").toLowerCase();
|
|
138
|
+
if (isIPv4(ip)) return {
|
|
139
|
+
v6: false,
|
|
140
|
+
n: parseV4(ip)
|
|
141
|
+
};
|
|
142
|
+
if (!isIPv6(ip)) return null;
|
|
143
|
+
const mapped = /^(?:0{0,4}:){0,5}:?ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
|
|
144
|
+
if (mapped && isIPv4(mapped[1])) return {
|
|
145
|
+
v6: false,
|
|
146
|
+
n: parseV4(mapped[1])
|
|
147
|
+
};
|
|
148
|
+
let text = ip;
|
|
149
|
+
const v4Tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
|
|
150
|
+
if (v4Tail) {
|
|
151
|
+
const n = parseV4(v4Tail[1]);
|
|
152
|
+
text = text.slice(0, -v4Tail[1].length) + `${(n >> 16n).toString(16)}:${(n & 65535n).toString(16)}`;
|
|
153
|
+
}
|
|
154
|
+
const [head = "", tail] = text.split("::");
|
|
155
|
+
const left = head ? head.split(":") : [];
|
|
156
|
+
const right = tail ? tail.split(":") : [];
|
|
157
|
+
const groups = tail === void 0 ? left : [
|
|
158
|
+
...left,
|
|
159
|
+
...Array(8 - left.length - right.length).fill("0"),
|
|
160
|
+
...right
|
|
161
|
+
];
|
|
162
|
+
if (groups.length !== 8) return null;
|
|
163
|
+
return {
|
|
164
|
+
v6: true,
|
|
165
|
+
n: groups.reduce((acc, g) => acc << 16n | BigInt(Number.parseInt(g || "0", 16)), 0n)
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Parses "10.0.0.5", "10.0.0.0/8", "fd00::/8", "::ffff:10.0.0.0/104"; null when invalid. A /0
|
|
170
|
+
* (trust everyone) is refused: it would let any client pick its own address.
|
|
171
|
+
*/
|
|
172
|
+
function parseRange(entry) {
|
|
173
|
+
const parts = entry.trim().split("/");
|
|
174
|
+
if (parts.length > 2) return null;
|
|
175
|
+
const [ip = "", prefix] = parts;
|
|
176
|
+
const addr = parseAddress(ip);
|
|
177
|
+
if (!addr) return null;
|
|
178
|
+
let bits = addr.v6 ? 128 : 32;
|
|
179
|
+
if (prefix !== void 0) {
|
|
180
|
+
if (!/^\d{1,3}$/.test(prefix)) return null;
|
|
181
|
+
bits = Number(prefix);
|
|
182
|
+
if (!addr.v6 && ip.includes(":")) bits -= 96;
|
|
183
|
+
if (bits <= 0 || bits > (addr.v6 ? 128 : 32)) return null;
|
|
184
|
+
}
|
|
185
|
+
const width = BigInt(addr.v6 ? 128 : 32);
|
|
186
|
+
const mask = bits === 0 ? 0n : (1n << BigInt(bits)) - 1n << width - BigInt(bits);
|
|
187
|
+
return {
|
|
188
|
+
v6: addr.v6,
|
|
189
|
+
base: addr.n & mask,
|
|
190
|
+
bits
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function inRange(addr, r) {
|
|
194
|
+
if (addr.v6 !== r.v6) return false;
|
|
195
|
+
const width = BigInt(r.v6 ? 128 : 32);
|
|
196
|
+
const mask = r.bits === 0 ? 0n : (1n << BigInt(r.bits)) - 1n << width - BigInt(r.bits);
|
|
197
|
+
return (addr.n & mask) === r.base;
|
|
198
|
+
}
|
|
199
|
+
const LOOPBACK = [parseRange("127.0.0.0/8"), parseRange("::1/128")];
|
|
200
|
+
let cache;
|
|
201
|
+
/** TRUST_PROXY_FROM as ranges. Invalid entries are reported once and ignored. */
|
|
202
|
+
function trustedRanges(raw) {
|
|
203
|
+
if (cache?.raw === raw) return cache.ranges;
|
|
204
|
+
const ranges = [];
|
|
205
|
+
const invalid = [];
|
|
206
|
+
for (const entry of raw.split(/[,\s]+/).filter(Boolean)) {
|
|
207
|
+
const r = parseRange(entry);
|
|
208
|
+
if (r) ranges.push(r);
|
|
209
|
+
else invalid.push(entry);
|
|
210
|
+
}
|
|
211
|
+
if (invalid.length) process.stderr.write(`agentinbox: ignoring invalid TRUST_PROXY_FROM entries: ${invalid.join(", ")}\n`);
|
|
212
|
+
cache = {
|
|
213
|
+
raw,
|
|
214
|
+
ranges
|
|
215
|
+
};
|
|
216
|
+
return ranges;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Whether forwarding headers from this socket peer may be believed: loopback always (a proxy on
|
|
220
|
+
* the same host), anything else only when listed in TRUST_PROXY_FROM (IPs or CIDRs, comma-separated).
|
|
221
|
+
* The daemon usually binds 0.0.0.0, so trusting whole private ranges would let any LAN or tailnet
|
|
222
|
+
* peer forge its address.
|
|
223
|
+
*/
|
|
224
|
+
function isTrustedProxy(peer, trustFrom = process.env.TRUST_PROXY_FROM ?? "") {
|
|
225
|
+
const addr = parseAddress(peer);
|
|
226
|
+
if (!addr) return false;
|
|
227
|
+
return [...LOOPBACK, ...trustedRanges(trustFrom)].some((r) => inRange(addr, r));
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
132
230
|
//#region server/auth/sessions.ts
|
|
133
231
|
const SESSION_TTL_MS = 2592e6;
|
|
134
232
|
/** Sliding refresh never extends a session past this age: sign in again after 90 days. */
|
|
@@ -257,16 +355,6 @@ function resetAdminPassword(ctx) {
|
|
|
257
355
|
});
|
|
258
356
|
return regenerateSetupToken(ctx.config.dataDir);
|
|
259
357
|
}
|
|
260
|
-
/** Loopback, RFC 1918, CGNAT (100.64/10) and IPv6 ULA (fc00::/7): where a reverse proxy can be. */
|
|
261
|
-
function isPrivateAddress(ip) {
|
|
262
|
-
const addr = ip.replace(/%.*$/, "").toLowerCase().replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, "");
|
|
263
|
-
if (isIPv4(addr)) {
|
|
264
|
-
const [a = 0, b = 0] = addr.split(".").map(Number);
|
|
265
|
-
return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127;
|
|
266
|
-
}
|
|
267
|
-
if (isIPv6(addr)) return addr === "::1" || /^f[cd][0-9a-f]{0,2}:/.test(addr);
|
|
268
|
-
return false;
|
|
269
|
-
}
|
|
270
358
|
function socketAddress(c) {
|
|
271
359
|
try {
|
|
272
360
|
return getConnInfo(c).remote.address ?? null;
|
|
@@ -276,15 +364,30 @@ function socketAddress(c) {
|
|
|
276
364
|
}
|
|
277
365
|
/**
|
|
278
366
|
* The client address. X-Forwarded-For is honored only with TRUST_PROXY and only when the
|
|
279
|
-
* connection comes from a
|
|
367
|
+
* connection comes from a trusted proxy (loopback, or TRUST_PROXY_FROM); it is read from the
|
|
280
368
|
* right, since proxies append the address they saw and entries further left are client-controlled.
|
|
281
369
|
* TRUST_PROXY_HOPS (default 1) is the number of proxies in front of agentinbox.
|
|
282
370
|
*/
|
|
371
|
+
/** Some proxies (Azure, IIS) append ":port" to X-Forwarded-For entries. */
|
|
372
|
+
function stripPort(entry) {
|
|
373
|
+
const v6 = /^\[([^\]]+)\](?::\d+)?$/.exec(entry);
|
|
374
|
+
if (v6) return v6[1];
|
|
375
|
+
const v4 = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/.exec(entry);
|
|
376
|
+
return v4 ? v4[1] : entry;
|
|
377
|
+
}
|
|
378
|
+
let warnedUntrustedProxy = false;
|
|
379
|
+
/** Upgrades from the old private-range rule silently lost proxy trust; say so once. */
|
|
380
|
+
function warnUntrustedProxy(peer) {
|
|
381
|
+
if (warnedUntrustedProxy) return;
|
|
382
|
+
warnedUntrustedProxy = true;
|
|
383
|
+
process.stderr.write(`agentinbox: ignoring X-Forwarded-For from ${peer}: TRUST_PROXY only trusts loopback proxies unless TRUST_PROXY_FROM lists them (e.g. TRUST_PROXY_FROM=${peer}).\n`);
|
|
384
|
+
}
|
|
283
385
|
function clientIp(c, trustProxy) {
|
|
284
386
|
const peer = socketAddress(c);
|
|
285
|
-
if (trustProxy && peer &&
|
|
387
|
+
if (trustProxy && peer && !isTrustedProxy(peer) && c.req.header("x-forwarded-for")) warnUntrustedProxy(peer);
|
|
388
|
+
if (trustProxy && peer && isTrustedProxy(peer)) {
|
|
286
389
|
const hops = Math.max(1, Number.parseInt(process.env.TRUST_PROXY_HOPS ?? "1", 10) || 1);
|
|
287
|
-
const chain = (c.req.header("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
390
|
+
const chain = (c.req.header("x-forwarded-for") ?? "").split(",").map((s) => stripPort(s.trim())).filter(Boolean);
|
|
288
391
|
const forwarded = chain[chain.length - hops];
|
|
289
392
|
if (forwarded && isIP(forwarded)) return forwarded;
|
|
290
393
|
}
|
|
@@ -293,7 +396,7 @@ function clientIp(c, trustProxy) {
|
|
|
293
396
|
function isSecure(c, trustProxy) {
|
|
294
397
|
if (new URL(c.req.url).protocol === "https:") return true;
|
|
295
398
|
const peer = socketAddress(c);
|
|
296
|
-
return trustProxy && !!peer &&
|
|
399
|
+
return trustProxy && !!peer && isTrustedProxy(peer) && c.req.header("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase() === "https";
|
|
297
400
|
}
|
|
298
401
|
function sessionToken(c) {
|
|
299
402
|
return getCookie(c, "aib_session") || void 0;
|
|
@@ -442,6 +545,6 @@ function rejection(c, check) {
|
|
|
442
545
|
return check.lockedMinutes ? lockedOut(c, check.lockedMinutes) : null;
|
|
443
546
|
}
|
|
444
547
|
//#endregion
|
|
445
|
-
export {
|
|
548
|
+
export { sessionToken as _, adminAuth as a, csrfGuard as c, hasSession as d, isClaimed as f, resetAdminPassword as g, requireAdmin as h, Semaphore as i, currentSetupToken as l, rejection as m, MAX_PASSWORD_LENGTH as n, checkSecret as o, lockedOut as p, SESSION_COOKIE as r, clientIp as s, CSRF_HEADER as t, endSession as u, startSession as v };
|
|
446
549
|
|
|
447
|
-
//# sourceMappingURL=auth-
|
|
550
|
+
//# sourceMappingURL=auth-D4yzhGUg.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-D4yzhGUg.js","names":[],"sources":["../server/auth/lockout.ts","../server/auth/proxy.ts","../server/auth/sessions.ts","../server/auth/index.ts"],"sourcesContent":["import { isIPv6 } from \"node:net\";\nimport { sha256 } from \"../crypto.ts\";\n\n/** Distinct wrong secrets per client within the window before a ban. */\nexport const MAX_FAILURES = 5;\n/** Raw failed attempts per client within the window (repeats of the same wrong secret included). */\nexport const MAX_ATTEMPTS = 30;\n/** Distinct wrong secrets across all clients within the window before every attempt is slowed down. */\nexport const GLOBAL_MAX_FAILURES = 100;\n/** Delay per attempt while the global budget is exceeded. */\nexport const GLOBAL_SLOWDOWN_MS = 2000;\nexport const WINDOW_MS = 15 * 60_000;\nexport const BAN_MS = 15 * 60_000;\n/** Tracked clients; the least recently seen is dropped beyond this. */\nexport const MAX_ENTRIES = 10_000;\n\ninterface Entry {\n tried: Set<string>;\n attempts: number;\n since: number;\n bannedUntil: number;\n}\n\n/**\n * Failed sign-in limiter. Per client (IPv4 address or IPv6 /64): 5 distinct wrong secrets or 30\n * attempts within 15 minutes ban it for 15 minutes. A secret already known to be wrong is\n * rejected without hashing (`knownBad`) and counts only as an attempt, so a client retrying a stale\n * password can't spend every attempt, and can't make the server hash it again either. Past a global\n * budget of distinct failures, every attempt is slowed down (never refused, so many clients can't\n * lock the owner out).\n */\nexport class LoginLimiter {\n private readonly entries = new Map<string, Entry>();\n private global = { failures: 0, since: 0 };\n\n constructor(private readonly clock: () => number = Date.now) {}\n\n /** Minutes until this client may try again, or 0. */\n bannedMinutes(ip: string): number {\n const t = this.clock();\n const entry = this.entries.get(clientKey(ip));\n const until = entry && entry.bannedUntil > t ? entry.bannedUntil : 0;\n return until > t ? Math.ceil((until - t) / 60_000) : 0;\n }\n\n /** The global failure budget is exhausted: slow every attempt down. */\n overGlobalBudget(): boolean {\n return this.global.failures >= GLOBAL_MAX_FAILURES && this.clock() - this.global.since < WINDOW_MS;\n }\n\n /** The client already failed with exactly this secret in the current window. */\n knownBad(ip: string, secret: string): boolean {\n const entry = this.current(clientKey(ip), this.clock());\n return !!entry?.tried.has(sha256(secret));\n }\n\n /** Records a failure; returns true when it started a ban for this client. `global: false` keeps it out of the global budget. */\n fail(ip: string, secret: string, opts: { global?: boolean } = {}): boolean {\n return this.record(ip, secret, opts).banned;\n }\n\n /**\n * Counts an attempt with this secret now, before it is verified, so concurrent requests can't\n * all pass the ban check first. `countedGlobally` says whether it used global budget (refund it\n * with `refundGlobal` when the secret turns out to be right).\n */\n record(ip: string, secret: string, opts: { global?: boolean } = {}): { banned: boolean; countedGlobally: boolean } {\n const t = this.clock();\n const key = clientKey(ip);\n const entry = this.current(key, t) ?? { tried: new Set<string>(), attempts: 0, since: t, bannedUntil: 0 };\n const hash = sha256(secret);\n let countedGlobally = false;\n if (!entry.tried.has(hash)) {\n entry.tried.add(hash);\n if (opts.global !== false) {\n if (t - this.global.since >= WINDOW_MS) this.global = { failures: 0, since: t };\n this.global.failures++;\n countedGlobally = true;\n }\n }\n entry.attempts++;\n const banned = entry.tried.size >= MAX_FAILURES || entry.attempts >= MAX_ATTEMPTS;\n if (banned) entry.bannedUntil = t + BAN_MS;\n this.touch(key, entry);\n return { banned, countedGlobally };\n }\n\n refundGlobal(): void {\n if (this.global.failures > 0) this.global.failures--;\n }\n\n clear(ip: string): void {\n this.entries.delete(clientKey(ip));\n }\n\n /** After the password changes, previously wrong secrets may be right. */\n reset(): void {\n this.entries.clear();\n this.global = { failures: 0, since: 0 };\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n /** The client's entry if its window (or ban) is still running. */\n private current(key: string, t: number): Entry | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (entry.bannedUntil > t || (!entry.bannedUntil && t - entry.since < WINDOW_MS)) return entry;\n this.entries.delete(key);\n return undefined;\n }\n\n /** Map order doubles as LRU order: re-insert on use, evict from the front. */\n private touch(key: string, entry: Entry): void {\n this.entries.delete(key);\n this.entries.set(key, entry);\n while (this.entries.size > MAX_ENTRIES) this.entries.delete(this.entries.keys().next().value!);\n }\n}\n\n/** IPv4 addresses as is (also when IPv4-mapped); IPv6 by /64, since one client usually owns the whole prefix. */\nexport function clientKey(ip: string): string {\n const addr = ip.replace(/%.*$/, \"\").toLowerCase();\n const mapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(addr);\n if (mapped) return mapped[1]!;\n if (!isIPv6(addr)) return addr;\n const [head = \"\", tail] = addr.split(\"::\");\n const left = head ? head.split(\":\") : [];\n const right = tail ? tail.split(\":\") : [];\n const groups = tail === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill(\"0\"), ...right];\n return `${groups\n .slice(0, 4)\n .map((g) => g.replace(/^0+(?=.)/, \"\"))\n .join(\":\")}::/64`;\n}\n","import { isIPv4, isIPv6 } from \"node:net\";\n\n/** An address as a family and a big integer, with IPv4-mapped IPv6 (::ffff:a.b.c.d) treated as IPv4. */\ninterface Addr {\n v6: boolean;\n n: bigint;\n}\n\nfunction parseV4(ip: string): bigint {\n return ip.split(\".\").reduce((acc, part) => (acc << 8n) | BigInt(Number(part)), 0n);\n}\n\nexport function parseAddress(raw: string): Addr | null {\n const ip = raw.trim().replace(/^\\[|\\]$/g, \"\").replace(/%.*$/, \"\").toLowerCase();\n if (isIPv4(ip)) return { v6: false, n: parseV4(ip) };\n if (!isIPv6(ip)) return null;\n const mapped = /^(?:0{0,4}:){0,5}:?ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(ip);\n if (mapped && isIPv4(mapped[1]!)) return { v6: false, n: parseV4(mapped[1]!) };\n // Expand an embedded IPv4 tail into two hextets, then \"::\".\n let text = ip;\n const v4Tail = /(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(text);\n if (v4Tail) {\n const n = parseV4(v4Tail[1]!);\n text = text.slice(0, -v4Tail[1]!.length) + `${(n >> 16n).toString(16)}:${(n & 0xffffn).toString(16)}`;\n }\n const [head = \"\", tail] = text.split(\"::\");\n const left = head ? head.split(\":\") : [];\n const right = tail ? tail.split(\":\") : [];\n const groups = tail === undefined ? left : [...left, ...Array<string>(8 - left.length - right.length).fill(\"0\"), ...right];\n if (groups.length !== 8) return null;\n return { v6: true, n: groups.reduce((acc, g) => (acc << 16n) | BigInt(Number.parseInt(g || \"0\", 16)), 0n) };\n}\n\ninterface Range {\n v6: boolean;\n base: bigint;\n bits: number;\n}\n\n/**\n * Parses \"10.0.0.5\", \"10.0.0.0/8\", \"fd00::/8\", \"::ffff:10.0.0.0/104\"; null when invalid. A /0\n * (trust everyone) is refused: it would let any client pick its own address.\n */\nexport function parseRange(entry: string): Range | null {\n const parts = entry.trim().split(\"/\");\n if (parts.length > 2) return null;\n const [ip = \"\", prefix] = parts;\n const addr = parseAddress(ip);\n if (!addr) return null;\n let bits = addr.v6 ? 128 : 32;\n if (prefix !== undefined) {\n if (!/^\\d{1,3}$/.test(prefix)) return null;\n bits = Number(prefix);\n // A mapped IPv4 range written in IPv6 form: drop the 96-bit ::ffff: prefix.\n if (!addr.v6 && ip.includes(\":\")) bits -= 96;\n if (bits <= 0 || bits > (addr.v6 ? 128 : 32)) return null;\n }\n const width = BigInt(addr.v6 ? 128 : 32);\n const mask = bits === 0 ? 0n : ((1n << BigInt(bits)) - 1n) << (width - BigInt(bits));\n return { v6: addr.v6, base: addr.n & mask, bits };\n}\n\nfunction inRange(addr: Addr, r: Range): boolean {\n if (addr.v6 !== r.v6) return false;\n const width = BigInt(r.v6 ? 128 : 32);\n const mask = r.bits === 0 ? 0n : ((1n << BigInt(r.bits)) - 1n) << (width - BigInt(r.bits));\n return (addr.n & mask) === r.base;\n}\n\nconst LOOPBACK = [parseRange(\"127.0.0.0/8\")!, parseRange(\"::1/128\")!];\n\nlet cache: { raw: string; ranges: Range[] } | undefined;\n\n/** TRUST_PROXY_FROM as ranges. Invalid entries are reported once and ignored. */\nfunction trustedRanges(raw: string): Range[] {\n if (cache?.raw === raw) return cache.ranges;\n const ranges: Range[] = [];\n const invalid: string[] = [];\n for (const entry of raw.split(/[,\\s]+/).filter(Boolean)) {\n const r = parseRange(entry);\n if (r) ranges.push(r);\n else invalid.push(entry);\n }\n if (invalid.length) process.stderr.write(`agentinbox: ignoring invalid TRUST_PROXY_FROM entries: ${invalid.join(\", \")}\\n`);\n cache = { raw, ranges };\n return ranges;\n}\n\n/**\n * Whether forwarding headers from this socket peer may be believed: loopback always (a proxy on\n * the same host), anything else only when listed in TRUST_PROXY_FROM (IPs or CIDRs, comma-separated).\n * The daemon usually binds 0.0.0.0, so trusting whole private ranges would let any LAN or tailnet\n * peer forge its address.\n */\nexport function isTrustedProxy(peer: string, trustFrom = process.env.TRUST_PROXY_FROM ?? \"\"): boolean {\n const addr = parseAddress(peer);\n if (!addr) return false;\n return [...LOOPBACK, ...trustedRanges(trustFrom)].some((r) => inRange(addr, r));\n}\n","import { randomBytes } from \"node:crypto\";\nimport { sha256 } from \"../crypto.ts\";\nimport type { Db } from \"../db/index.ts\";\n\nexport const SESSION_TTL_MS = 30 * 24 * 3600_000;\n/** Sliding refresh never extends a session past this age: sign in again after 90 days. */\nexport const SESSION_MAX_AGE_MS = 90 * 24 * 3600_000;\n/** Sliding expiry is pushed forward at most once per this interval, to avoid a write per request. */\nconst REFRESH_AFTER_MS = 24 * 3600_000;\n\nexport interface SessionCheck {\n valid: boolean;\n /** The expiry was extended: re-send the cookie so the browser keeps it as long. */\n refreshed: boolean;\n}\n\n/** Admin console sessions. Only sha256(token) is stored. */\nexport class SessionStore {\n constructor(\n private readonly db: Db,\n private readonly clock: () => number = Date.now,\n ) {}\n\n create(meta: { ip?: string | null; userAgent?: string | null } = {}): string {\n const token = randomBytes(32).toString(\"base64url\");\n const t = this.clock();\n this.db.run(\n \"INSERT INTO admin_sessions (token_hash, created_at, expires_at, ip, user_agent) VALUES (?, ?, ?, ?, ?)\",\n sha256(token),\n new Date(t).toISOString(),\n new Date(t + SESSION_TTL_MS).toISOString(),\n meta.ip ?? null,\n meta.userAgent?.slice(0, 300) ?? null,\n );\n return token;\n }\n\n check(token: string | undefined | null): SessionCheck {\n if (!token) return { valid: false, refreshed: false };\n const hash = sha256(token);\n const row = this.db.get<{ created_at: string; expires_at: string }>(\n \"SELECT created_at, expires_at FROM admin_sessions WHERE token_hash = ?\",\n hash,\n );\n if (!row) return { valid: false, refreshed: false };\n const t = this.clock();\n const expires = Date.parse(row.expires_at);\n const hardLimit = Date.parse(row.created_at) + SESSION_MAX_AGE_MS;\n if (!(expires > t) || !(hardLimit > t)) {\n this.db.run(\"DELETE FROM admin_sessions WHERE token_hash = ?\", hash);\n return { valid: false, refreshed: false };\n }\n const next = Math.min(t + SESSION_TTL_MS, hardLimit);\n if (next - expires < REFRESH_AFTER_MS) return { valid: true, refreshed: false };\n this.db.run(\"UPDATE admin_sessions SET expires_at = ? WHERE token_hash = ?\", new Date(next).toISOString(), hash);\n return { valid: true, refreshed: true };\n }\n\n delete(token: string): void {\n this.db.run(\"DELETE FROM admin_sessions WHERE token_hash = ?\", sha256(token));\n }\n\n /** Revokes every session, optionally keeping one (the caller's own). */\n deleteAll(exceptToken?: string | null): number {\n if (exceptToken) return this.db.run(\"DELETE FROM admin_sessions WHERE token_hash != ?\", sha256(exceptToken)).changes;\n return this.db.run(\"DELETE FROM admin_sessions\").changes;\n }\n\n pruneExpired(): number {\n return this.db.run(\"DELETE FROM admin_sessions WHERE expires_at <= ?\", new Date(this.clock()).toISOString()).changes;\n }\n}\n","import { isIP } from \"node:net\";\nimport { getConnInfo } from \"@hono/node-server/conninfo\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { deleteCookie, getCookie, setCookie } from \"hono/cookie\";\nimport type { AppEnv } from \"../api/util.ts\";\nimport type { CoreContext } from \"../context.ts\";\nimport { HttpError } from \"../util/errors.ts\";\nimport { clientKey, GLOBAL_SLOWDOWN_MS, LoginLimiter } from \"./lockout.ts\";\nimport { isTrustedProxy } from \"./proxy.ts\";\nimport { SESSION_TTL_MS, SessionStore } from \"./sessions.ts\";\nimport { ensureSetupToken, regenerateSetupToken } from \"./setup-token.ts\";\n\nexport const SESSION_COOKIE = \"aib_session\";\nexport const CSRF_HEADER = \"x-agentinbox-csrf\";\nexport const MIN_PASSWORD_LENGTH = 10;\nexport const MAX_PASSWORD_LENGTH = 1024;\n\n/** Secret checks (scrypt) allowed at once: libuv's default thread pool size. */\nexport const MAX_CONCURRENT_VERIFICATIONS = 4;\n/** Requests from one client that may wait behind its in-flight check; more get 429. */\nexport const MAX_QUEUED_PER_CLIENT = 4;\n\n/** Hands out at most `max` slots; waiters are served in order. */\nexport class Semaphore {\n private active = 0;\n private readonly waiters: (() => void)[] = [];\n\n constructor(private readonly max: number) {}\n\n get inUse(): number {\n return this.active;\n }\n\n async acquire(): Promise<() => void> {\n if (this.active < this.max) this.active++;\n else await new Promise<void>((resolve) => this.waiters.push(resolve));\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const next = this.waiters.shift();\n if (next) next();\n else this.active--;\n };\n }\n}\n\n/** Per-context admin auth state: the session store, the failed-login limiter and verification queues. */\nexport interface AdminAuth {\n sessions: SessionStore;\n limiter: LoginLimiter;\n /** One secret check per client at a time: the tail of each client's queue. */\n lanes: Map<string, { tail: Promise<void>; queued: number }>;\n verifySlots: Semaphore;\n}\n\n/** What admin auth needs from the context (the CLI builds this without loading the master key). */\nexport type AuthCore = Pick<CoreContext, \"db\" | \"settings\" | \"audit\" | \"config\">;\n\nconst instances = new WeakMap<AuthCore, AdminAuth>();\n\nexport function adminAuth(ctx: AuthCore): AdminAuth {\n let auth = instances.get(ctx);\n if (!auth) {\n auth = { sessions: new SessionStore(ctx.db), limiter: new LoginLimiter(), lanes: new Map(), verifySlots: new Semaphore(MAX_CONCURRENT_VERIFICATIONS) };\n instances.set(ctx, auth);\n }\n return auth;\n}\n\n/** Claimed = an admin password exists. Before that only the setup-token claim works. */\nexport const isClaimed = (ctx: AuthCore): boolean => !!ctx.settings.getState(\"admin.passwordHash\");\n\n/** The current setup token while unclaimed (created on demand), otherwise null. */\nexport function currentSetupToken(ctx: AuthCore): string | null {\n return isClaimed(ctx) ? null : ensureSetupToken(ctx.config.dataDir);\n}\n\n/** `agentinbox reset-password`: back to the unclaimed state with a fresh setup link. */\nexport function resetAdminPassword(ctx: AuthCore): string {\n const auth = adminAuth(ctx);\n ctx.db.tx(() => {\n ctx.settings.deleteState(\"admin.passwordHash\");\n auth.sessions.deleteAll();\n });\n auth.limiter.reset();\n ctx.audit.record({ actorType: \"system\", action: \"admin.password_reset\", outcome: \"ok\" });\n return regenerateSetupToken(ctx.config.dataDir);\n}\n\nfunction socketAddress(c: Context): string | null {\n try {\n return getConnInfo(c).remote.address ?? null;\n } catch {\n // No Node socket (e.g. app.request() without bindings).\n return null;\n }\n}\n\n/**\n * The client address. X-Forwarded-For is honored only with TRUST_PROXY and only when the\n * connection comes from a trusted proxy (loopback, or TRUST_PROXY_FROM); it is read from the\n * right, since proxies append the address they saw and entries further left are client-controlled.\n * TRUST_PROXY_HOPS (default 1) is the number of proxies in front of agentinbox.\n */\n/** Some proxies (Azure, IIS) append \":port\" to X-Forwarded-For entries. */\nfunction stripPort(entry: string): string {\n const v6 = /^\\[([^\\]]+)\\](?::\\d+)?$/.exec(entry);\n if (v6) return v6[1]!;\n const v4 = /^(\\d{1,3}(?:\\.\\d{1,3}){3}):\\d+$/.exec(entry);\n return v4 ? v4[1]! : entry;\n}\n\nlet warnedUntrustedProxy = false;\n\n/** Upgrades from the old private-range rule silently lost proxy trust; say so once. */\nfunction warnUntrustedProxy(peer: string): void {\n if (warnedUntrustedProxy) return;\n warnedUntrustedProxy = true;\n process.stderr.write(\n `agentinbox: ignoring X-Forwarded-For from ${peer}: TRUST_PROXY only trusts loopback proxies unless TRUST_PROXY_FROM lists them (e.g. TRUST_PROXY_FROM=${peer}).\\n`,\n );\n}\n\nexport function clientIp(c: Context, trustProxy: boolean): string {\n const peer = socketAddress(c);\n if (trustProxy && peer && !isTrustedProxy(peer) && c.req.header(\"x-forwarded-for\")) warnUntrustedProxy(peer);\n if (trustProxy && peer && isTrustedProxy(peer)) {\n const hops = Math.max(1, Number.parseInt(process.env.TRUST_PROXY_HOPS ?? \"1\", 10) || 1);\n const chain = (c.req.header(\"x-forwarded-for\") ?? \"\")\n .split(\",\")\n .map((s) => stripPort(s.trim()))\n .filter(Boolean);\n const forwarded = chain[chain.length - hops];\n if (forwarded && isIP(forwarded)) return forwarded;\n }\n return peer ?? \"unknown\";\n}\n\nfunction isSecure(c: Context, trustProxy: boolean): boolean {\n if (new URL(c.req.url).protocol === \"https:\") return true;\n const peer = socketAddress(c);\n return trustProxy && !!peer && isTrustedProxy(peer) && c.req.header(\"x-forwarded-proto\")?.split(\",\")[0]?.trim().toLowerCase() === \"https\";\n}\n\nexport function sessionToken(c: Context): string | undefined {\n return getCookie(c, SESSION_COOKIE) || undefined;\n}\n\nfunction writeSessionCookie(c: Context, token: string, trustProxy: boolean): void {\n setCookie(c, SESSION_COOKIE, token, {\n httpOnly: true,\n sameSite: \"Lax\",\n path: \"/\",\n secure: isSecure(c, trustProxy),\n maxAge: Math.floor(SESSION_TTL_MS / 1000),\n });\n}\n\n/** Creates a session for the requester and sets the cookie. */\nexport function startSession(c: Context, ctx: AuthCore): void {\n const token = adminAuth(ctx).sessions.create({ ip: clientIp(c, ctx.config.trustProxy), userAgent: c.req.header(\"user-agent\") });\n writeSessionCookie(c, token, ctx.config.trustProxy);\n}\n\nexport function endSession(c: Context, ctx: AuthCore): void {\n const token = sessionToken(c);\n if (token) adminAuth(ctx).sessions.delete(token);\n deleteCookie(c, SESSION_COOKIE, { path: \"/\" });\n}\n\n/** Whether the request carries a valid session; refreshes the cookie when the expiry slid forward. */\nexport function hasSession(c: Context, ctx: AuthCore): boolean {\n const token = sessionToken(c);\n const check = adminAuth(ctx).sessions.check(token);\n if (check.refreshed && token) writeSessionCookie(c, token, ctx.config.trustProxy);\n return check.valid;\n}\n\n/** Requires an admin session on every route it guards. */\nexport function requireAdmin(ctx: AuthCore): MiddlewareHandler<AppEnv> {\n return async (c, next) => {\n if (!hasSession(c, ctx)) {\n if (!isClaimed(ctx)) {\n throw new HttpError(401, \"setup_required\", \"This instance has not been claimed yet\", \"Open the setup link printed by agentinbox on startup.\");\n }\n throw new HttpError(401, \"unauthorized\", \"Sign in to continue\");\n }\n c.set(\"admin\", true);\n await next();\n };\n}\n\nconst MUTATING = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * CSRF guard: a custom header can't be sent cross-site without a CORS preflight (which this server\n * never approves), and SameSite=Lax already keeps the cookie off cross-site POSTs.\n */\nexport function csrfGuard(): MiddlewareHandler<AppEnv> {\n return async (c, next) => {\n if (MUTATING.has(c.req.method) && c.req.header(CSRF_HEADER) !== \"1\") {\n throw new HttpError(403, \"csrf\", `Missing ${CSRF_HEADER} header`, `Send \"${CSRF_HEADER}: 1\" with every mutating /api request.`);\n }\n await next();\n };\n}\n\n/** 429 response for a locked-out address. */\nexport function lockedOut(c: Context, minutes: number): Response {\n c.header(\"Retry-After\", String(minutes * 60));\n const message = `Too many failed attempts. Try again in ${minutes} minute${minutes === 1 ? \"\" : \"s\"}.`;\n return c.json({ error: { code: \"locked_out\", message } }, 429);\n}\n\nexport type CheckResult =\n | { ok: true }\n | { ok: false; lockedMinutes: number; nowBanned: boolean; /** Too many concurrent attempts from this client. */ busy?: boolean };\n\nexport interface CheckOptions {\n /**\n * Count toward (and be slowed down by) the instance-wide failure budget. Off for the setup claim:\n * it's only open while unclaimed and needs the token.\n */\n global?: boolean;\n /** Test hook: how long to wait while over the global budget. */\n slowdownMs?: number;\n}\n\n/**\n * Verifies a secret under the failed-login limiter.\n * - Each client gets one check at a time (a few more may queue, the rest get `busy`), and at most\n * MAX_CONCURRENT_VERIFICATIONS run at once overall.\n * - The attempt is recorded before `verify` (scrypt) runs and refunded if it succeeds, so\n * concurrent requests can't all slip past the ban.\n * - Locked-out clients and secrets this client already failed with never reach `verify`.\n * - While the instance-wide budget is exhausted, each attempt waits a little first; it is never refused.\n */\nexport async function checkSecret(\n ctx: AuthCore,\n ip: string,\n secret: string,\n verify: () => boolean | Promise<boolean>,\n opts: CheckOptions = {},\n): Promise<CheckResult> {\n const auth = adminAuth(ctx);\n const key = clientKey(ip);\n const lane = auth.lanes.get(key) ?? { tail: Promise.resolve(), queued: 0 };\n if (lane.queued > MAX_QUEUED_PER_CLIENT) return { ok: false, lockedMinutes: 0, nowBanned: false, busy: true };\n lane.queued++;\n auth.lanes.set(key, lane);\n const previous = lane.tail;\n let done!: () => void;\n lane.tail = new Promise<void>((resolve) => (done = resolve));\n try {\n await previous;\n return await checkOnce(auth, ip, secret, verify, opts);\n } finally {\n done();\n if (--lane.queued === 0) auth.lanes.delete(key);\n }\n}\n\nasync function checkOnce(auth: AdminAuth, ip: string, secret: string, verify: () => boolean | Promise<boolean>, opts: CheckOptions): Promise<CheckResult> {\n const { limiter } = auth;\n const global = opts.global !== false;\n if (global && limiter.overGlobalBudget() && !limiter.bannedMinutes(ip)) {\n await new Promise((r) => setTimeout(r, opts.slowdownMs ?? GLOBAL_SLOWDOWN_MS));\n }\n // From here to the reservation everything is synchronous.\n const locked = limiter.bannedMinutes(ip);\n if (locked) return { ok: false, lockedMinutes: locked, nowBanned: false };\n if (limiter.knownBad(ip, secret)) return { ok: false, lockedMinutes: 0, nowBanned: limiter.fail(ip, secret, { global }) };\n const reservation = limiter.record(ip, secret, { global });\n const release = await auth.verifySlots.acquire();\n let ok = false;\n try {\n ok = await verify();\n } finally {\n release();\n }\n if (!ok) return { ok: false, lockedMinutes: 0, nowBanned: reservation.banned };\n limiter.clear(ip);\n if (reservation.countedGlobally) limiter.refundGlobal();\n return { ok: true };\n}\n\n/** The 429 for a rejected check (locked out or too many at once), or null to continue. */\nexport function rejection(c: Context, check: CheckResult): Response | null {\n if (check.ok) return null;\n if (check.busy) {\n c.header(\"Retry-After\", \"2\");\n return c.json({ error: { code: \"too_many_requests\", message: \"Another sign-in attempt from your address is still being checked. Try again in a moment.\" } }, 429);\n }\n return check.lockedMinutes ? lockedOut(c, check.lockedMinutes) : null;\n}\n"],"mappings":";;;;;;;;AAYA,MAAa,SAAS;;AAEtB,MAAa,cAAc;;;;;;;;;AAiB3B,IAAa,eAAb,MAA0B;CAIK;CAH7B,0BAA2B,IAAI,IAAmB;CAClD,SAAiB;EAAE,UAAU;EAAG,OAAO;CAAE;CAEzC,YAAY,QAAuC,KAAK,KAAK;EAAhC,KAAA,QAAA;CAAiC;;CAG9D,cAAc,IAAoB;EAChC,MAAM,IAAI,KAAK,MAAM;EACrB,MAAM,QAAQ,KAAK,QAAQ,IAAI,UAAU,EAAE,CAAC;EAC5C,MAAM,QAAQ,SAAS,MAAM,cAAc,IAAI,MAAM,cAAc;EACnE,OAAO,QAAQ,IAAI,KAAK,MAAM,QAAQ,KAAK,GAAM,IAAI;CACvD;;CAGA,mBAA4B;EAC1B,OAAO,KAAK,OAAO,YAAA,OAAmC,KAAK,MAAM,IAAI,KAAK,OAAO,QAAA;CACnF;;CAGA,SAAS,IAAY,QAAyB;EAE5C,OAAO,CAAC,CADM,KAAK,QAAQ,UAAU,EAAE,GAAG,KAAK,MAAM,CACxC,CAAC,EAAE,MAAM,IAAI,OAAO,MAAM,CAAC;CAC1C;;CAGA,KAAK,IAAY,QAAgB,OAA6B,CAAC,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AQ;CACV;CACA,IAAI,CAAC,IAAI,OAAO;EAAE,IAAI;EAAO,eAAe;EAAG,WAAW,YAAY;CAAO;CAC7E,QAAQ,MAAM,EAAE;CAChB,IAAI,YAAY,iBAAiB,QAAQ,aAAa;CACtD,OAAO,EAAE,IAAI,KAAK;AACpB;;AAGA,SAAgB,UAAU,GAAY,OAAqC;CACzE,IAAI,MAAM,IAAI,OAAO;CACrB,IAAI,MAAM,MAAM;EACd,EAAE,OAAO,eAAe,GAAG;EAC3B,OAAO,EAAE,KAAK,EAAE,OAAO;GAAE,MAAM;GAAqB,SAAS;EAA2F,EAAE,GAAG,GAAG;CAClK;CACA,OAAO,MAAM,gBAAgB,UAAU,GAAG,MAAM,aAAa,IAAI;AACnE"}
|
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
|
-
import { join, resolve } from "node:path";
|
|
5
|
-
|
|
6
|
-
import
|
|
4
|
+
import { join, resolve, sep } from "node:path";
|
|
5
|
+
//#region server/node-check.ts
|
|
6
|
+
/** The oldest Node.js agentinbox runs on (node:sqlite unflagged, import.meta.dirname). Keep in sync with package.json engines. */
|
|
7
|
+
const MIN_NODE = "22.13.0";
|
|
8
|
+
/** An explanation when `version` (e.g. process.versions.node) is too old, else null. */
|
|
9
|
+
function nodeVersionError(version) {
|
|
10
|
+
const parse = (v) => v.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
11
|
+
const have = parse(version);
|
|
12
|
+
const need = parse(MIN_NODE);
|
|
13
|
+
for (let i = 0; i < 3; i++) {
|
|
14
|
+
if ((have[i] ?? 0) > need[i]) return null;
|
|
15
|
+
if ((have[i] ?? 0) < need[i]) return `agentinbox needs Node.js 22.13 or newer (you have ${version.replace(/^v?/, "v")}). Install a current Node.js from https://nodejs.org and try again.`;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
const problem = nodeVersionError(process.versions.node);
|
|
20
|
+
if (problem) {
|
|
21
|
+
console.error(problem);
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
7
25
|
//#region server/cli.ts
|
|
26
|
+
const { Command, InvalidArgumentError } = await import("commander");
|
|
27
|
+
const { default: pc } = await import("picocolors");
|
|
28
|
+
process.title = "agentinbox";
|
|
8
29
|
const emitWarning = process.emitWarning.bind(process);
|
|
9
30
|
process.emitWarning = ((warning, ...rest) => {
|
|
10
31
|
const message = typeof warning === "string" ? warning : warning.message;
|
|
@@ -40,8 +61,9 @@ const configInput = (o) => ({
|
|
|
40
61
|
dataDir: o.data
|
|
41
62
|
});
|
|
42
63
|
const program = new Command("agentinbox").description("Self-hosted Gmail broker for AI agents: MCP tools, webhooks, guardrails and a web console.").version(version, "-v, --version", "print the version").helpOption("-h, --help", "show help").addHelpText("after", "\nWithout installing: npx agentinbox-cli [command]. To install the command: npm i -g agentinbox-cli").showSuggestionAfterError();
|
|
43
|
-
withServerOptions(program.command("start", { isDefault: true }).description("run agentinbox in the foreground (default)")).option("--no-open", "don't open a browser on first run").option("--dev", "development: API only, the console runs on Vite (:5173)").action(async (o) => {
|
|
44
|
-
|
|
64
|
+
withServerOptions(program.command("start", { isDefault: true }).description("run agentinbox in the foreground (default)")).option("--no-open", "don't open a browser on first run").option("--dev", "development: API only, the console runs on Vite (:5173)").allowExcessArguments().action(async (o, cmd) => {
|
|
65
|
+
if (cmd.args.length) throw new Error(unknownCommand(cmd.args[0]));
|
|
66
|
+
const { runForeground } = await import("./server-B0zZclGt.js");
|
|
45
67
|
await runForeground({
|
|
46
68
|
...configInput(o),
|
|
47
69
|
dev: !!o.dev,
|
|
@@ -52,43 +74,43 @@ withServerOptions(program.command("start", { isDefault: true }).description("run
|
|
|
52
74
|
const service = program.command("service").description("run agentinbox as a background service (systemd / launchd)");
|
|
53
75
|
withServerOptions(service.command("install").description("install and start the service; re-run to update")).action(async (o) => {
|
|
54
76
|
const { loadConfig } = await import("./config-CIvgMqLx.js");
|
|
55
|
-
const { installService } = await import("./service-
|
|
77
|
+
const { installService } = await import("./service-CFnr0e9w.js");
|
|
56
78
|
await installService(loadConfig(configInput(o), version));
|
|
57
79
|
});
|
|
58
|
-
service.command("uninstall").description("stop and remove the service (keeps your data)").option("-d, --data <dir>", "data directory (default ~/.agentinbox, env AGENTINBOX_DATA)").action(async (o) => {
|
|
59
|
-
const {
|
|
60
|
-
|
|
61
|
-
uninstallService(loadConfig(configInput(o), version));
|
|
80
|
+
service.command("uninstall").description("stop and remove the service (keeps your data)").option("-d, --data <dir>", "data directory, if the installed service doesn't say (default ~/.agentinbox, env AGENTINBOX_DATA)").action(async (o) => {
|
|
81
|
+
const { uninstallService } = await import("./service-CFnr0e9w.js");
|
|
82
|
+
uninstallService({ dataDir: resolve(o.data ?? process.env.AGENTINBOX_DATA ?? join(homedir(), ".agentinbox")) });
|
|
62
83
|
});
|
|
63
84
|
service.command("status").description("show service status").action(async () => {
|
|
64
|
-
const { serviceStatus } = await import("./service-
|
|
85
|
+
const { serviceStatus } = await import("./service-CFnr0e9w.js");
|
|
65
86
|
serviceStatus();
|
|
66
87
|
});
|
|
67
88
|
const skill = program.command("skill").description("the agentinbox agent skill (SKILL.md)");
|
|
68
89
|
skill.command("print").description("print SKILL.md to stdout").option("--url <url>", "agentinbox server URL to fill in (env AGENTINBOX_URL)").action(async (o) => {
|
|
69
|
-
const { renderSkill } = await import("./skill-
|
|
70
|
-
process.stdout.write(renderSkill(serverUrl(o.url)));
|
|
90
|
+
const { renderSkill } = await import("./skill-BJFn2bHK.js");
|
|
91
|
+
process.stdout.write(renderSkill(await serverUrl(o.url)));
|
|
71
92
|
});
|
|
72
|
-
skill.command("install").description("install SKILL.md for an agent (no running server needed)").option("-t, --target <target>", "claude, codex, agents, or a skills directory", "claude").option("--url <url>", "agentinbox server URL agents connect to (env AGENTINBOX_URL)").action(async (o) => {
|
|
73
|
-
const { renderSkill, skillPath, writeSkill } = await import("./skill-
|
|
74
|
-
|
|
93
|
+
skill.command("install").description("install SKILL.md for an agent (no running server needed)").option("-t, --target <target>", "claude, codex, agents, or a skills directory path", "claude").option("--url <url>", "agentinbox server URL agents connect to (env AGENTINBOX_URL)").action(async (o) => {
|
|
94
|
+
const { renderSkill, SKILL_TARGETS, skillPath, writeSkill } = await import("./skill-BJFn2bHK.js");
|
|
95
|
+
checkSkillTarget(o.target, Object.keys(SKILL_TARGETS));
|
|
96
|
+
const url = await serverUrl(o.url);
|
|
75
97
|
const path = skillPath(o.target);
|
|
76
98
|
writeSkill(path, renderSkill(url));
|
|
77
99
|
console.log(`Installed the agentinbox skill to ${pc.cyan(path)} (server ${url}).`);
|
|
78
100
|
if (!o.url && !process.env.AGENTINBOX_URL) console.log(pc.dim("Agents on other machines need the server's address: re-run with --url https://your-server."));
|
|
79
101
|
});
|
|
80
|
-
|
|
102
|
+
program.command("reset-password").description("remove the admin password and print a new setup link").option("-d, --data <dir>", "data directory (default ~/.agentinbox, env AGENTINBOX_DATA)").option("-p, --port <port>", "port of the running instance, used for the printed link", parsePort).option("--host <host>", "host of the running instance, used for the printed link").action(async (o) => {
|
|
81
103
|
const dataDir = resolve(o.data ?? process.env.AGENTINBOX_DATA ?? join(homedir(), ".agentinbox"));
|
|
82
104
|
const dbPath = join(dataDir, "agentinbox.db");
|
|
83
105
|
if (!existsSync(dbPath)) throw new Error(`No agentinbox data in ${dataDir}. If agentinbox runs as a system service, run this with sudo; otherwise pass the data directory it uses with --data.`);
|
|
84
106
|
const { loadConfig } = await import("./config-CIvgMqLx.js");
|
|
85
107
|
const { Db } = await import("./db-CXhlUuVP.js");
|
|
86
108
|
const { createBus } = await import("./bus-OKIGut72.js");
|
|
87
|
-
const { SettingsStore } = await import("./settings-
|
|
109
|
+
const { SettingsStore } = await import("./settings-BK7h99j7.js");
|
|
88
110
|
const { AuditLog } = await import("./audit-Bf3TvAAN.js");
|
|
89
|
-
const { currentSetupToken, isClaimed, resetAdminPassword } = await import("./auth-
|
|
90
|
-
const { runningInstance } = await import("./instance-
|
|
91
|
-
const { consoleUrls } = await import("./urls-
|
|
111
|
+
const { currentSetupToken, isClaimed, resetAdminPassword } = await import("./auth-X5SGuNNB.js");
|
|
112
|
+
const { runningInstance } = await import("./instance-Dh5kDs31.js");
|
|
113
|
+
const { consoleUrls } = await import("./urls-Dp8pBGMU.js");
|
|
92
114
|
const running = runningInstance(dataDir);
|
|
93
115
|
const config = loadConfig({
|
|
94
116
|
dataDir,
|
|
@@ -116,9 +138,22 @@ withServerOptions(program.command("reset-password").description("remove the admi
|
|
|
116
138
|
db.close();
|
|
117
139
|
}
|
|
118
140
|
});
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
|
|
141
|
+
/**
|
|
142
|
+
* The URL written into SKILL.md: --url, AGENTINBOX_URL, else the agentinbox running on this
|
|
143
|
+
* machine (its lock file), else http://localhost:8425.
|
|
144
|
+
*/
|
|
145
|
+
async function serverUrl(flag) {
|
|
146
|
+
let raw = flag ?? process.env.AGENTINBOX_URL;
|
|
147
|
+
if (!raw) {
|
|
148
|
+
const { runningInstance } = await import("./instance-Dh5kDs31.js");
|
|
149
|
+
const running = runningInstance(resolve(process.env.AGENTINBOX_DATA || join(homedir(), ".agentinbox")));
|
|
150
|
+
const host = running && ![
|
|
151
|
+
"0.0.0.0",
|
|
152
|
+
"::",
|
|
153
|
+
""
|
|
154
|
+
].includes(running.host) ? running.host : "localhost";
|
|
155
|
+
raw = `http://${host.includes(":") ? `[${host}]` : host}:${running?.port || process.env.PORT || 8425}`;
|
|
156
|
+
}
|
|
122
157
|
let url;
|
|
123
158
|
try {
|
|
124
159
|
url = new URL(raw);
|
|
@@ -128,6 +163,48 @@ function serverUrl(flag) {
|
|
|
128
163
|
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("--url must start with http:// or https://");
|
|
129
164
|
return (url.origin + url.pathname).replace(/\/+$/, "");
|
|
130
165
|
}
|
|
166
|
+
/** A known agent name, or something that is clearly a path; typos like "claud" are refused. */
|
|
167
|
+
function checkSkillTarget(target, known) {
|
|
168
|
+
if (known.includes(target) || target.includes("/") || target.includes(sep) || target.startsWith(".") || isDir(target)) return;
|
|
169
|
+
const near = closest(target, known);
|
|
170
|
+
throw new Error(`Unknown skill target "${target}".${near ? ` Did you mean ${near}?` : ""} Use ${known.join(", ")}, or a directory path such as ./skills.`);
|
|
171
|
+
}
|
|
172
|
+
function isDir(path) {
|
|
173
|
+
try {
|
|
174
|
+
return statSync(path).isDirectory();
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function unknownCommand(name) {
|
|
180
|
+
const near = closest(name, [...program.commands.map((c) => c.name()), "help"]);
|
|
181
|
+
return `unknown command '${name}'${near ? `\n(Did you mean ${near}?)` : ""}\nRun agentinbox --help for the list of commands.`;
|
|
182
|
+
}
|
|
183
|
+
/** The candidate within edit distance 2 (or a prefix match), if any. */
|
|
184
|
+
function closest(word, candidates) {
|
|
185
|
+
const distance = (a, b) => {
|
|
186
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
187
|
+
for (let i = 1; i <= a.length; i++) {
|
|
188
|
+
let prev = row[0];
|
|
189
|
+
row[0] = i;
|
|
190
|
+
for (let j = 1; j <= b.length; j++) {
|
|
191
|
+
const cur = row[j];
|
|
192
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
193
|
+
prev = cur;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return row[b.length];
|
|
197
|
+
};
|
|
198
|
+
let best = null;
|
|
199
|
+
for (const c of candidates) {
|
|
200
|
+
const d = c.startsWith(word) && word.length >= 3 ? 0 : distance(word.toLowerCase(), c);
|
|
201
|
+
if (d <= 2 && (!best || d < best.d)) best = {
|
|
202
|
+
name: c,
|
|
203
|
+
d
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
return best?.name ?? null;
|
|
207
|
+
}
|
|
131
208
|
try {
|
|
132
209
|
await program.parseAsync(process.argv);
|
|
133
210
|
} catch (err) {
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../server/cli.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport pc from \"picocolors\";\n\n// node:sqlite is stable enough for us but still warns on Node 22. This runs before any server\n// module loads: everything that touches node:sqlite is imported dynamically below.\nconst emitWarning = process.emitWarning.bind(process);\nprocess.emitWarning = ((warning: string | Error, ...rest: unknown[]) => {\n const message = typeof warning === \"string\" ? warning : warning.message;\n const type = typeof rest[0] === \"string\" ? rest[0] : (rest[0] as { type?: string } | undefined)?.type;\n if ((type === \"ExperimentalWarning\" || (warning as Error).name === \"ExperimentalWarning\") && /SQLite/i.test(message)) return;\n return (emitWarning as (...args: unknown[]) => void)(warning, ...rest);\n}) as typeof process.emitWarning;\n\n/** package.json sits one level above both dist/cli.js and server/cli.ts. */\nfunction packageVersion(): string {\n try {\n return (JSON.parse(readFileSync(join(import.meta.dirname, \"..\", \"package.json\"), \"utf8\")) as { version: string }).version;\n } catch {\n return \"0.0.0\";\n }\n}\n\nconst version = packageVersion();\n\ninterface ServerFlags {\n port?: number;\n host?: string;\n data?: string;\n}\n\nconst validPort = (value: string) => /^\\d+$/.test(value) && Number(value) <= 65535;\n\nfunction parsePort(value: string): number {\n if (!validPort(value)) throw new InvalidArgumentError(\"Port must be a number from 0 to 65535.\");\n return Number(value);\n}\n\n/** --port, else a validated PORT env (a typo there would otherwise become NaN deep inside). */\nfunction portOption(flag: number | undefined): number | undefined {\n if (flag !== undefined) return flag;\n const env = process.env.PORT?.trim();\n if (!env) return undefined;\n if (!validPort(env)) throw new Error(`PORT=\"${process.env.PORT}\" is not a valid port. Use a number from 0 to 65535.`);\n return Number(env);\n}\n\nconst withServerOptions = (cmd: Command) =>\n cmd\n .option(\"-p, --port <port>\", \"port to listen on (default 8425, env PORT)\", parsePort)\n .option(\"--host <host>\", \"bind address (default 0.0.0.0, env HOST)\")\n .option(\"-d, --data <dir>\", \"data directory (default ~/.agentinbox, env AGENTINBOX_DATA)\");\n\nconst configInput = (o: ServerFlags) => ({ port: portOption(o.port), host: o.host, dataDir: o.data });\n\nconst program = new Command(\"agentinbox\")\n .description(\"Self-hosted Gmail broker for AI agents: MCP tools, webhooks, guardrails and a web console.\")\n .version(version, \"-v, --version\", \"print the version\")\n .helpOption(\"-h, --help\", \"show help\")\n .addHelpText(\"after\", \"\\nWithout installing: npx agentinbox-cli [command]. To install the command: npm i -g agentinbox-cli\")\n .showSuggestionAfterError();\n\nwithServerOptions(program.command(\"start\", { isDefault: true }).description(\"run agentinbox in the foreground (default)\"))\n .option(\"--no-open\", \"don't open a browser on first run\")\n .option(\"--dev\", \"development: API only, the console runs on Vite (:5173)\")\n .action(async (o: ServerFlags & { open: boolean; dev?: boolean }) => {\n const { runForeground } = await import(\"./server.ts\");\n await runForeground({ ...configInput(o), dev: !!o.dev, open: o.open, version });\n });\n\nconst service = program.command(\"service\").description(\"run agentinbox as a background service (systemd / launchd)\");\n\nwithServerOptions(service.command(\"install\").description(\"install and start the service; re-run to update\")).action(async (o: ServerFlags) => {\n const { loadConfig } = await import(\"./config.ts\");\n const { installService } = await import(\"./service.ts\");\n await installService(loadConfig(configInput(o), version));\n});\n\nservice\n .command(\"uninstall\")\n .description(\"stop and remove the service (keeps your data)\")\n .option(\"-d, --data <dir>\", \"data directory (default ~/.agentinbox, env AGENTINBOX_DATA)\")\n .action(async (o: ServerFlags) => {\n const { loadConfig } = await import(\"./config.ts\");\n const { uninstallService } = await import(\"./service.ts\");\n uninstallService(loadConfig(configInput(o), version));\n });\n\nservice\n .command(\"status\")\n .description(\"show service status\")\n .action(async () => {\n const { serviceStatus } = await import(\"./service.ts\");\n serviceStatus();\n });\n\nconst skill = program.command(\"skill\").description(\"the agentinbox agent skill (SKILL.md)\");\n\nskill\n .command(\"print\")\n .description(\"print SKILL.md to stdout\")\n .option(\"--url <url>\", \"agentinbox server URL to fill in (env AGENTINBOX_URL)\")\n .action(async (o: { url?: string }) => {\n const { renderSkill } = await import(\"./skill/index.ts\");\n process.stdout.write(renderSkill(serverUrl(o.url)));\n });\n\nskill\n .command(\"install\")\n .description(\"install SKILL.md for an agent (no running server needed)\")\n .option(\"-t, --target <target>\", \"claude, codex, agents, or a skills directory\", \"claude\")\n .option(\"--url <url>\", \"agentinbox server URL agents connect to (env AGENTINBOX_URL)\")\n .action(async (o: { target: string; url?: string }) => {\n const { renderSkill, skillPath, writeSkill } = await import(\"./skill/index.ts\");\n const url = serverUrl(o.url);\n const path = skillPath(o.target);\n writeSkill(path, renderSkill(url));\n console.log(`Installed the agentinbox skill to ${pc.cyan(path)} (server ${url}).`);\n if (!o.url && !process.env.AGENTINBOX_URL) {\n console.log(pc.dim(\"Agents on other machines need the server's address: re-run with --url https://your-server.\"));\n }\n });\n\nwithServerOptions(program.command(\"reset-password\").description(\"remove the admin password and print a new setup link\")).action(\n async (o: ServerFlags) => {\n // Never create a data directory or master key here: a wrong --data (or a service running as\n // another user) must not silently produce a fresh instance.\n const dataDir = resolve(o.data ?? process.env.AGENTINBOX_DATA ?? join(homedir(), \".agentinbox\"));\n const dbPath = join(dataDir, \"agentinbox.db\");\n if (!existsSync(dbPath)) {\n throw new Error(\n `No agentinbox data in ${dataDir}. If agentinbox runs as a system service, run this with sudo; ` +\n \"otherwise pass the data directory it uses with --data.\",\n );\n }\n const { loadConfig } = await import(\"./config.ts\");\n const { Db } = await import(\"./db/index.ts\");\n const { createBus } = await import(\"./bus.ts\");\n const { SettingsStore } = await import(\"./settings.ts\");\n const { AuditLog } = await import(\"./audit.ts\");\n const { currentSetupToken, isClaimed, resetAdminPassword } = await import(\"./auth/index.ts\");\n const { runningInstance } = await import(\"./instance.ts\");\n const { consoleUrls } = await import(\"./urls.ts\");\n\n const running = runningInstance(dataDir);\n const config = loadConfig(\n { dataDir, port: portOption(o.port) ?? running?.port, host: o.host ?? (process.env.HOST || running?.host) },\n version,\n );\n const db = new Db(dbPath);\n try {\n const bus = createBus();\n const core = { config, db, settings: new SettingsStore(db, bus, config), audit: new AuditLog(db, bus) };\n const claimed = isClaimed(core);\n const token = claimed ? resetAdminPassword(core) : currentSetupToken(core)!;\n console.log(\n claimed\n ? \"\\n The admin password was removed and all console sessions were signed out.\\n Open this link to set a new password:\\n\"\n : \"\\n This instance hasn't been claimed yet, so there is no password to reset.\\n Open this link to claim it:\\n\",\n );\n const urls = consoleUrls(config.host, config.port);\n const publicUrl = core.settings.publicUrl();\n if (!urls.includes(publicUrl)) urls.push(publicUrl);\n for (const url of urls) console.log(` ${pc.cyan(`${url}/setup?token=${token}`)}`);\n console.log(pc.dim(`\\n ${running ? \"The running agentinbox picks this up immediately; no restart needed.\" : \"Start agentinbox to use it.\"}\\n`));\n } finally {\n db.close();\n }\n },\n);\n\n/** The URL written into SKILL.md: --url, AGENTINBOX_URL, or this machine's default. */\nfunction serverUrl(flag: string | undefined): string {\n const raw = flag ?? process.env.AGENTINBOX_URL ?? `http://localhost:${process.env.PORT || 8425}`;\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new Error(`Invalid --url \"${raw}\". Use a full URL such as https://mail.example.com.`);\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"--url must start with http:// or https://\");\n return (url.origin + url.pathname).replace(/\\/+$/, \"\");\n}\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n console.error(pc.red(err instanceof Error ? err.message : String(err)));\n if (process.env.AGENTINBOX_DEBUG && err instanceof Error) console.error(err.stack);\n process.exit(1);\n}\n"],"mappings":";;;;;;;AAQA,MAAM,cAAc,QAA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AAM,2CAA2C;CACtH,QAAQ,IAAI,SAAS,IAAI,SAAA,CAAU,QAAQ,QAAQ,EAAE;AACvD;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,KAAK;CACZ,QAAQ,MAAM,GAAG,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,CAAC;CACtE,IAAI,QAAQ,IAAI,oBAAoB,eAAe,OAAO,QAAQ,MAAM,IAAI,KAAK;CACjF,QAAQ,KAAK,CAAC;AAChB"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../server/node-check.ts","../server/cli.ts"],"sourcesContent":["/** The oldest Node.js agentinbox runs on (node:sqlite unflagged, import.meta.dirname). Keep in sync with package.json engines. */\nexport const MIN_NODE = \"22.13.0\";\n\n/** An explanation when `version` (e.g. process.versions.node) is too old, else null. */\nexport function nodeVersionError(version: string): string | null {\n const parse = (v: string) => v.replace(/^v/, \"\").split(\".\").map((n) => Number.parseInt(n, 10) || 0);\n const have = parse(version);\n const need = parse(MIN_NODE);\n for (let i = 0; i < 3; i++) {\n if ((have[i] ?? 0) > need[i]!) return null;\n if ((have[i] ?? 0) < need[i]!) return `agentinbox needs Node.js 22.13 or newer (you have ${version.replace(/^v?/, \"v\")}). Install a current Node.js from https://nodejs.org and try again.`;\n }\n return null;\n}\n\n// Runs on import, before anything that needs a newer Node is loaded.\nconst problem = nodeVersionError(process.versions.node);\nif (problem) {\n console.error(problem);\n process.exit(1);\n}\n","// Must stay the first import: exits with a clear message on a too-old Node.\nimport \"./node-check.ts\";\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve, sep } from \"node:path\";\nimport type { Command as CommandType } from \"commander\";\n\n// Loaded after the Node check (static imports are hoisted above it in the bundle).\nconst { Command, InvalidArgumentError } = await import(\"commander\");\nconst { default: pc } = await import(\"picocolors\");\n\nprocess.title = \"agentinbox\";\n\n// node:sqlite is stable enough for us but still warns on Node 22. This runs before any server\n// module loads: everything that touches node:sqlite is imported dynamically below.\nconst emitWarning = process.emitWarning.bind(process);\nprocess.emitWarning = ((warning: string | Error, ...rest: unknown[]) => {\n const message = typeof warning === \"string\" ? warning : warning.message;\n const type = typeof rest[0] === \"string\" ? rest[0] : (rest[0] as { type?: string } | undefined)?.type;\n if ((type === \"ExperimentalWarning\" || (warning as Error).name === \"ExperimentalWarning\") && /SQLite/i.test(message)) return;\n return (emitWarning as (...args: unknown[]) => void)(warning, ...rest);\n}) as typeof process.emitWarning;\n\n/** package.json sits one level above both dist/cli.js and server/cli.ts. */\nfunction packageVersion(): string {\n try {\n return (JSON.parse(readFileSync(join(import.meta.dirname, \"..\", \"package.json\"), \"utf8\")) as { version: string }).version;\n } catch {\n return \"0.0.0\";\n }\n}\n\nconst version = packageVersion();\n\ninterface ServerFlags {\n port?: number;\n host?: string;\n data?: string;\n}\n\nconst validPort = (value: string) => /^\\d+$/.test(value) && Number(value) <= 65535;\n\nfunction parsePort(value: string): number {\n if (!validPort(value)) throw new InvalidArgumentError(\"Port must be a number from 0 to 65535.\");\n return Number(value);\n}\n\n/** --port, else a validated PORT env (a typo there would otherwise become NaN deep inside). */\nfunction portOption(flag: number | undefined): number | undefined {\n if (flag !== undefined) return flag;\n const env = process.env.PORT?.trim();\n if (!env) return undefined;\n if (!validPort(env)) throw new Error(`PORT=\"${process.env.PORT}\" is not a valid port. Use a number from 0 to 65535.`);\n return Number(env);\n}\n\nconst withServerOptions = (cmd: CommandType) =>\n cmd\n .option(\"-p, --port <port>\", \"port to listen on (default 8425, env PORT)\", parsePort)\n .option(\"--host <host>\", \"bind address (default 0.0.0.0, env HOST)\")\n .option(\"-d, --data <dir>\", \"data directory (default ~/.agentinbox, env AGENTINBOX_DATA)\");\n\nconst configInput = (o: ServerFlags) => ({ port: portOption(o.port), host: o.host, dataDir: o.data });\n\nconst program = new Command(\"agentinbox\")\n .description(\"Self-hosted Gmail broker for AI agents: MCP tools, webhooks, guardrails and a web console.\")\n .version(version, \"-v, --version\", \"print the version\")\n .helpOption(\"-h, --help\", \"show help\")\n .addHelpText(\"after\", \"\\nWithout installing: npx agentinbox-cli [command]. To install the command: npm i -g agentinbox-cli\")\n .showSuggestionAfterError();\n\nwithServerOptions(program.command(\"start\", { isDefault: true }).description(\"run agentinbox in the foreground (default)\"))\n .option(\"--no-open\", \"don't open a browser on first run\")\n .option(\"--dev\", \"development: API only, the console runs on Vite (:5173)\")\n // `agentinbox typo` lands here as an extra argument: report it as the unknown command it is.\n .allowExcessArguments()\n .action(async (o: ServerFlags & { open: boolean; dev?: boolean }, cmd: CommandType) => {\n if (cmd.args.length) throw new Error(unknownCommand(cmd.args[0]!));\n const { runForeground } = await import(\"./server.ts\");\n await runForeground({ ...configInput(o), dev: !!o.dev, open: o.open, version });\n });\n\nconst service = program.command(\"service\").description(\"run agentinbox as a background service (systemd / launchd)\");\n\nwithServerOptions(service.command(\"install\").description(\"install and start the service; re-run to update\")).action(async (o: ServerFlags) => {\n const { loadConfig } = await import(\"./config.ts\");\n const { installService } = await import(\"./service.ts\");\n await installService(loadConfig(configInput(o), version));\n});\n\nservice\n .command(\"uninstall\")\n .description(\"stop and remove the service (keeps your data)\")\n .option(\"-d, --data <dir>\", \"data directory, if the installed service doesn't say (default ~/.agentinbox, env AGENTINBOX_DATA)\")\n .action(async (o: ServerFlags) => {\n const { uninstallService } = await import(\"./service.ts\");\n // No loadConfig: uninstalling must not create a data directory.\n uninstallService({ dataDir: resolve(o.data ?? process.env.AGENTINBOX_DATA ?? join(homedir(), \".agentinbox\")) });\n });\n\nservice\n .command(\"status\")\n .description(\"show service status\")\n .action(async () => {\n const { serviceStatus } = await import(\"./service.ts\");\n serviceStatus();\n });\n\nconst skill = program.command(\"skill\").description(\"the agentinbox agent skill (SKILL.md)\");\n\nskill\n .command(\"print\")\n .description(\"print SKILL.md to stdout\")\n .option(\"--url <url>\", \"agentinbox server URL to fill in (env AGENTINBOX_URL)\")\n .action(async (o: { url?: string }) => {\n const { renderSkill } = await import(\"./skill/index.ts\");\n process.stdout.write(renderSkill(await serverUrl(o.url)));\n });\n\nskill\n .command(\"install\")\n .description(\"install SKILL.md for an agent (no running server needed)\")\n .option(\"-t, --target <target>\", \"claude, codex, agents, or a skills directory path\", \"claude\")\n .option(\"--url <url>\", \"agentinbox server URL agents connect to (env AGENTINBOX_URL)\")\n .action(async (o: { target: string; url?: string }) => {\n const { renderSkill, SKILL_TARGETS, skillPath, writeSkill } = await import(\"./skill/index.ts\");\n checkSkillTarget(o.target, Object.keys(SKILL_TARGETS));\n const url = await serverUrl(o.url);\n const path = skillPath(o.target);\n writeSkill(path, renderSkill(url));\n console.log(`Installed the agentinbox skill to ${pc.cyan(path)} (server ${url}).`);\n if (!o.url && !process.env.AGENTINBOX_URL) {\n console.log(pc.dim(\"Agents on other machines need the server's address: re-run with --url https://your-server.\"));\n }\n });\n\nprogram\n .command(\"reset-password\")\n .description(\"remove the admin password and print a new setup link\")\n .option(\"-d, --data <dir>\", \"data directory (default ~/.agentinbox, env AGENTINBOX_DATA)\")\n .option(\"-p, --port <port>\", \"port of the running instance, used for the printed link\", parsePort)\n .option(\"--host <host>\", \"host of the running instance, used for the printed link\")\n .action(\n async (o: ServerFlags) => {\n // Never create a data directory or master key here: a wrong --data (or a service running as\n // another user) must not silently produce a fresh instance.\n const dataDir = resolve(o.data ?? process.env.AGENTINBOX_DATA ?? join(homedir(), \".agentinbox\"));\n const dbPath = join(dataDir, \"agentinbox.db\");\n if (!existsSync(dbPath)) {\n throw new Error(\n `No agentinbox data in ${dataDir}. If agentinbox runs as a system service, run this with sudo; ` +\n \"otherwise pass the data directory it uses with --data.\",\n );\n }\n const { loadConfig } = await import(\"./config.ts\");\n const { Db } = await import(\"./db/index.ts\");\n const { createBus } = await import(\"./bus.ts\");\n const { SettingsStore } = await import(\"./settings.ts\");\n const { AuditLog } = await import(\"./audit.ts\");\n const { currentSetupToken, isClaimed, resetAdminPassword } = await import(\"./auth/index.ts\");\n const { runningInstance } = await import(\"./instance.ts\");\n const { consoleUrls } = await import(\"./urls.ts\");\n\n const running = runningInstance(dataDir);\n const config = loadConfig(\n { dataDir, port: portOption(o.port) ?? running?.port, host: o.host ?? (process.env.HOST || running?.host) },\n version,\n );\n const db = new Db(dbPath);\n try {\n const bus = createBus();\n const core = { config, db, settings: new SettingsStore(db, bus, config), audit: new AuditLog(db, bus) };\n const claimed = isClaimed(core);\n const token = claimed ? resetAdminPassword(core) : currentSetupToken(core)!;\n console.log(\n claimed\n ? \"\\n The admin password was removed and all console sessions were signed out.\\n Open this link to set a new password:\\n\"\n : \"\\n This instance hasn't been claimed yet, so there is no password to reset.\\n Open this link to claim it:\\n\",\n );\n const urls = consoleUrls(config.host, config.port);\n const publicUrl = core.settings.publicUrl();\n if (!urls.includes(publicUrl)) urls.push(publicUrl);\n for (const url of urls) console.log(` ${pc.cyan(`${url}/setup?token=${token}`)}`);\n console.log(pc.dim(`\\n ${running ? \"The running agentinbox picks this up immediately; no restart needed.\" : \"Start agentinbox to use it.\"}\\n`));\n } finally {\n db.close();\n }\n },\n);\n\n/**\n * The URL written into SKILL.md: --url, AGENTINBOX_URL, else the agentinbox running on this\n * machine (its lock file), else http://localhost:8425.\n */\nasync function serverUrl(flag: string | undefined): Promise<string> {\n let raw = flag ?? process.env.AGENTINBOX_URL;\n if (!raw) {\n const { runningInstance } = await import(\"./instance.ts\");\n const running = runningInstance(resolve(process.env.AGENTINBOX_DATA || join(homedir(), \".agentinbox\")));\n const host = running && ![\"0.0.0.0\", \"::\", \"\"].includes(running.host) ? running.host : \"localhost\";\n raw = `http://${host.includes(\":\") ? `[${host}]` : host}:${running?.port || process.env.PORT || 8425}`;\n }\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new Error(`Invalid --url \"${raw}\". Use a full URL such as https://mail.example.com.`);\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"--url must start with http:// or https://\");\n return (url.origin + url.pathname).replace(/\\/+$/, \"\");\n}\n\n/** A known agent name, or something that is clearly a path; typos like \"claud\" are refused. */\nfunction checkSkillTarget(target: string, known: string[]): void {\n if (known.includes(target) || target.includes(\"/\") || target.includes(sep) || target.startsWith(\".\") || isDir(target)) return;\n const near = closest(target, known);\n throw new Error(\n `Unknown skill target \"${target}\".${near ? ` Did you mean ${near}?` : \"\"} Use ${known.join(\", \")}, or a directory path such as ./skills.`,\n );\n}\n\nfunction isDir(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction unknownCommand(name: string): string {\n const near = closest(name, [...program.commands.map((c) => c.name()), \"help\"]);\n return `unknown command '${name}'${near ? `\\n(Did you mean ${near}?)` : \"\"}\\nRun agentinbox --help for the list of commands.`;\n}\n\n/** The candidate within edit distance 2 (or a prefix match), if any. */\nfunction closest(word: string, candidates: string[]): string | null {\n const distance = (a: string, b: string) => {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let prev = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cur = row[j]!;\n row[j] = Math.min(row[j]! + 1, row[j - 1]! + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));\n prev = cur;\n }\n }\n return row[b.length]!;\n };\n let best: { name: string; d: number } | null = null;\n for (const c of candidates) {\n const d = c.startsWith(word) && word.length >= 3 ? 0 : distance(word.toLowerCase(), c);\n if (d <= 2 && (!best || d < best.d)) best = { name: c, d };\n }\n return best?.name ?? null;\n}\n\ntry {\n await program.parseAsync(process.argv);\n} catch (err) {\n console.error(pc.red(err instanceof Error ? err.message : String(err)));\n if (process.env.AGENTINBOX_DEBUG && err instanceof Error) console.error(err.stack);\n process.exit(1);\n}\n"],"mappings":";;;;;;AACA,MAAa,WAAW;;AAGxB,SAAgB,iBAAiB,SAAgC;CAC/D,MAAM,SAAS,MAAc,EAAE,QAAQ,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,MA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Y;EAC1B,MAAM,IAAI,EAAE,WAAW,IAAI,KAAK,KAAK,UAAU,IAAI,IAAI,SAAS,KAAK,YAAY,GAAG,CAAC;EACrF,IAAI,KAAK,MAAM,CAAC,QAAQ,IAAI,KAAK,IAAI,OAAO;GAAE,MAAM;GAAG;EAAE;CAC3D;CACA,OAAO,MAAM,QAAQ;AACvB;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,KAAK;CACZ,QAAQ,MAAM,GAAG,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,CAAC;CACtE,IAAI,QAAQ,IAAI,oBAAoB,eAAe,OAAO,QAAQ,MAAM,IAAI,KAAK;CACjF,QAAQ,KAAK,CAAC;AAChB"}
|
|
@@ -111,7 +111,8 @@ function acquireInstanceLock(config) {
|
|
|
111
111
|
port: config.port,
|
|
112
112
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
113
113
|
bootId: bootId(),
|
|
114
|
-
processStart: processStartTime(process.pid)
|
|
114
|
+
processStart: processStartTime(process.pid),
|
|
115
|
+
service: process.env.AGENTINBOX_SERVICE === "1"
|
|
115
116
|
};
|
|
116
117
|
for (let attempt = 0;; attempt++) try {
|
|
117
118
|
writeFileSync(file, JSON.stringify(info), {
|
|
@@ -122,7 +123,10 @@ function acquireInstanceLock(config) {
|
|
|
122
123
|
} catch (err) {
|
|
123
124
|
if (err.code !== "EEXIST" || attempt > 0) throw err;
|
|
124
125
|
const other = runningInstance(dataDir);
|
|
125
|
-
if (other)
|
|
126
|
+
if (other) {
|
|
127
|
+
const where = `(pid ${other.pid}${other.port ? `, port ${other.port}` : ""})`;
|
|
128
|
+
throw new Error(other.service ? `agentinbox is already running as a background service with the data directory ${dataDir} ${where}. Use that one, stop it (\`${cliCommand("service uninstall")}\` keeps your data), or use another --data directory.` : `agentinbox is already running with the data directory ${dataDir} ${where}. Stop it first, or use another --data directory. If no such process exists, delete ${file}.`);
|
|
129
|
+
}
|
|
126
130
|
rmSync(file, { force: true });
|
|
127
131
|
}
|
|
128
132
|
heldByUs.add(dataDir);
|
|
@@ -180,4 +184,4 @@ function assertMasterKeyUsable(config, envKey = process.env.AGENTINBOX_MASTER_KE
|
|
|
180
184
|
//#endregion
|
|
181
185
|
export { lockPath as a, EVENT_TYPES as c, cliCommand as i, NPM_PACKAGE as l, assertMasterKeyUsable as n, processStartTime as o, bootId as r, runningInstance as s, acquireInstanceLock as t };
|
|
182
186
|
|
|
183
|
-
//# sourceMappingURL=instance-
|
|
187
|
+
//# sourceMappingURL=instance-CpTBwgrK.js.map
|