agentinbox-cli 0.1.0-nightly.3 → 0.1.0-nightly.4

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 CHANGED
@@ -216,9 +216,9 @@ 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` and
220
- `AGENTINBOX_LOG_LEVEL` are taken from your shell and remembered in `<data>/service.env`, so later installs keep them
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
 
@@ -231,7 +231,10 @@ Tailscale Funnel) and:
231
231
 
232
232
  - bind it to localhost: `--host 127.0.0.1`
233
233
  - 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
234
+ the right end of `X-Forwarded-For`; with more than one proxy in front, set `TRUST_PROXY_HOPS` to their number.
235
+ Forwarding headers are believed only from a proxy on the same host (loopback); if the proxy runs on another machine,
236
+ 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)
237
+ `X-Forwarded-For`; a tunnel or proxy that passes the header through unchanged lets clients choose their own address
235
238
  - set **Settings → Public URL** to the https address, so MCP snippets, the skill and the OAuth redirect use it
236
239
 
237
240
  `GET /health` (or `/api/health`) needs no auth and suits uptime monitors: `200` when healthy, `503` when degraded, for
@@ -258,6 +261,7 @@ agentinbox reset-password [--data …]
258
261
  | | `AGENTINBOX_MASTER_KEY` | | Base64 32-byte key for encrypting secrets, instead of `<data>/master.key` |
259
262
  | | `TRUST_PROXY` | | `1` behind a reverse proxy: client IPs from `X-Forwarded-For`, https from `X-Forwarded-Proto` |
260
263
  | | `TRUST_PROXY_HOPS` | `1` | Number of proxies in front of agentinbox (which `X-Forwarded-For` entry, from the right, is the client) |
264
+ | | `TRUST_PROXY_FROM` | loopback | Other proxy addresses whose forwarding headers are believed: comma-separated IPs or CIDRs (IPv4 or IPv6) |
261
265
  | | `AGENTINBOX_LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` |
262
266
 
263
267
  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 loopback or private address (where the proxy runs); it is read from the
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 && isPrivateAddress(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 && isPrivateAddress(peer) && c.req.header("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase() === "https";
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 { resetAdminPassword as _, adminAuth as a, csrfGuard as c, hasSession as d, isClaimed as f, requireAdmin as g, rejection as h, Semaphore as i, currentSetupToken as l, lockedOut as m, MAX_PASSWORD_LENGTH as n, checkSecret as o, isPrivateAddress as p, SESSION_COOKIE as r, clientIp as s, CSRF_HEADER as t, endSession as u, sessionToken as v, startSession as y };
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-B3ukRgpB.js.map
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,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,7 +41,7 @@ const configInput = (o) => ({
41
41
  });
42
42
  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
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
- const { runForeground } = await import("./server-BvX0c9MQ.js");
44
+ const { runForeground } = await import("./server-F3DTB7YC.js");
45
45
  await runForeground({
46
46
  ...configInput(o),
47
47
  dev: !!o.dev,
@@ -52,16 +52,16 @@ withServerOptions(program.command("start", { isDefault: true }).description("run
52
52
  const service = program.command("service").description("run agentinbox as a background service (systemd / launchd)");
53
53
  withServerOptions(service.command("install").description("install and start the service; re-run to update")).action(async (o) => {
54
54
  const { loadConfig } = await import("./config-CIvgMqLx.js");
55
- const { installService } = await import("./service-lFSuvmgq.js");
55
+ const { installService } = await import("./service-lHEFbRJQ.js");
56
56
  await installService(loadConfig(configInput(o), version));
57
57
  });
58
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
59
  const { loadConfig } = await import("./config-CIvgMqLx.js");
60
- const { uninstallService } = await import("./service-lFSuvmgq.js");
60
+ const { uninstallService } = await import("./service-lHEFbRJQ.js");
61
61
  uninstallService(loadConfig(configInput(o), version));
62
62
  });
63
63
  service.command("status").description("show service status").action(async () => {
64
- const { serviceStatus } = await import("./service-lFSuvmgq.js");
64
+ const { serviceStatus } = await import("./service-lHEFbRJQ.js");
65
65
  serviceStatus();
66
66
  });
67
67
  const skill = program.command("skill").description("the agentinbox agent skill (SKILL.md)");
@@ -86,7 +86,7 @@ withServerOptions(program.command("reset-password").description("remove the admi
86
86
  const { createBus } = await import("./bus-OKIGut72.js");
87
87
  const { SettingsStore } = await import("./settings-DoPS659W.js");
88
88
  const { AuditLog } = await import("./audit-Bf3TvAAN.js");
89
- const { currentSetupToken, isClaimed, resetAdminPassword } = await import("./auth-B9dqCyaj.js");
89
+ const { currentSetupToken, isClaimed, resetAdminPassword } = await import("./auth-X5SGuNNB.js");
90
90
  const { runningInstance } = await import("./instance-BEEO0AHU.js");
91
91
  const { consoleUrls } = await import("./urls-CNYhbeUQ.js");
92
92
  const running = runningInstance(dataDir);
@@ -3,7 +3,7 @@ import { i as now, n as bool, r as json, t as Db } from "./db-B2pnfQW5.js";
3
3
  import { t as AuditLog } from "./audit-CNYWHcik.js";
4
4
  import { a as errorMessage, i as conflict, n as PolicyDenied, o as notFound, r as badRequest, t as HttpError } from "./errors-FbMS3QBo.js";
5
5
  import { a as verifyPasswordAsync, i as sha256, n as hashPasswordAsync, r as safeEqual, t as Crypto } from "./crypto-DYZ4R7c2.js";
6
- import { a as adminAuth, c as csrfGuard, d as hasSession, f as isClaimed, g as requireAdmin, h as rejection, l as currentSetupToken, m as lockedOut, n as MAX_PASSWORD_LENGTH, o as checkSecret, s as clientIp, u as endSession, v as sessionToken, y as startSession } from "./auth-B3ukRgpB.js";
6
+ import { _ as sessionToken, a as adminAuth, c as csrfGuard, d as hasSession, f as isClaimed, h as requireAdmin, l as currentSetupToken, m as rejection, n as MAX_PASSWORD_LENGTH, o as checkSecret, p as lockedOut, s as clientIp, u as endSession, v as startSession } from "./auth-D4yzhGUg.js";
7
7
  import { a as setupTokenPath, o as newId, r as readSetupToken, s as randomToken, t as deleteSetupToken } from "./setup-token-BO89xnpb.js";
8
8
  import { t as createBus } from "./bus-Cz0flS37.js";
9
9
  import { n as loadConfig } from "./config-v975gxv4.js";
@@ -1060,9 +1060,9 @@ function compareVersions(a, b) {
1060
1060
  }
1061
1061
  const DEFAULT_DATA_DIR = () => resolve(join(homedir(), ".agentinbox"));
1062
1062
  /** Runs, or reinstalls as a service, the latest version with this instance's options. */
1063
- function upgradeCommand(config) {
1063
+ function upgradeCommand(config, env = process.env) {
1064
+ const proxyEnv = config.trustProxy ? ["TRUST_PROXY=1", ...["TRUST_PROXY_HOPS", "TRUST_PROXY_FROM"].filter((k) => env[k]?.trim()).map((k) => `${k}=${shellQuote(env[k].trim())}`)] : [];
1064
1065
  const args = [
1065
- ...config.trustProxy ? ["TRUST_PROXY=1"] : [],
1066
1066
  "npx",
1067
1067
  "-y",
1068
1068
  NPM_PACKAGE
@@ -1071,7 +1071,7 @@ function upgradeCommand(config) {
1071
1071
  if (config.dataDir !== DEFAULT_DATA_DIR()) args.push("--data", config.dataDir);
1072
1072
  if (config.port !== 8425) args.push("--port", String(config.port));
1073
1073
  if (config.host !== DEFAULT_HOST) args.push("--host", config.host);
1074
- return args.map(shellQuote).join(" ");
1074
+ return [...proxyEnv, ...args.map(shellQuote)].join(" ");
1075
1075
  }
1076
1076
  const shellQuote = (a) => /^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`;
1077
1077
  //#endregion
@@ -4679,4 +4679,4 @@ function openBrowser(url) {
4679
4679
  //#endregion
4680
4680
  export { runForeground };
4681
4681
 
4682
- //# sourceMappingURL=server-BvX0c9MQ.js.map
4682
+ //# sourceMappingURL=server-F3DTB7YC.js.map