blocknet 0.0.0-stage → 0.7.1

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.
@@ -0,0 +1,18 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="referrer" content="no-referrer">
7
+ <title>Blocknet console</title>
8
+ <link rel="icon" href="data:,">
9
+ <link rel="stylesheet" href="/console/console.css">
10
+ </head>
11
+ <body>
12
+ <div id="app" class="app">
13
+ <p class="boot">Loading…</p>
14
+ </div>
15
+ <div id="toasts" class="toasts" role="status" aria-live="polite"></div>
16
+ <script type="module" src="/console/console.js"></script>
17
+ </body>
18
+ </html>
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Loads Blocknet Enterprise, the separate package that adds single sign-on, audit export and metrics
3
+ * for Team and Enterprise customers. Blocknet works fully without it; with it, those features also
4
+ * need a licence that includes them.
5
+ *
6
+ * Where it's looked for, first found: $BLOCKNET_ENTERPRISE, `enterprise` in the config file,
7
+ * then ~/.blocknet/enterprise/. Each is a folder with an index.js, or the file itself.
8
+ * If one is named but can't be loaded, Blocknet stops with the reason rather than start without it.
9
+ */
10
+ import { existsSync, statSync } from 'node:fs';
11
+ import { join, resolve } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+
14
+ export const ENTERPRISE_API_VERSION = 1;
15
+
16
+ /** The package's location, or null. `named` is true when someone asked for it explicitly. */
17
+ export function findEnterprise(config, home) {
18
+ const named = process.env.BLOCKNET_ENTERPRISE || config.enterprise;
19
+ if (named) return { path: resolve(named), named: true };
20
+ const dflt = join(home, 'enterprise');
21
+ return existsSync(join(dflt, 'index.js')) ? { path: dflt, named: false } : null;
22
+ }
23
+
24
+ /** @returns {Promise<object|null>} the package's module, or null when none is installed */
25
+ export async function loadEnterprise(config, home) {
26
+ const found = findEnterprise(config, home);
27
+ if (!found) return null;
28
+ let file = found.path;
29
+ if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.js');
30
+ if (!existsSync(file)) throw new Error(`Blocknet Enterprise not found at ${found.path}`);
31
+ const mod = await import(pathToFileURL(file).href);
32
+ if (typeof mod.createEnterprise !== 'function') throw new Error(`${file} is not the Blocknet Enterprise package`);
33
+ if (mod.apiVersion !== ENTERPRISE_API_VERSION) {
34
+ throw new Error(`Blocknet Enterprise ${mod.version ?? ''} doesn't match this Blocknet (package API ${mod.apiVersion}, needs ${ENTERPRISE_API_VERSION}); update both to the same release`);
35
+ }
36
+ return mod;
37
+ }
package/src/gateway.js ADDED
@@ -0,0 +1,480 @@
1
+ import { createServer } from 'node:http';
2
+ import { connect, isIP } from 'node:net';
3
+ import { lookup as dnsLookup } from 'node:dns/promises';
4
+ import { Readable } from 'node:stream';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { evaluateNetwork, evaluatePayment, round } from './policy.js';
7
+ import { chooseOption, parsePaymentRequired } from './x402.js';
8
+ import { Ledger, utcDay } from './ledger.js';
9
+ import { createTrust } from './trust.js';
10
+ import { ApprovalStore } from './approvals.js';
11
+ import { agentsEnabled, effectiveConfig, keyFromHeaders, resolveAgent } from './agents.js';
12
+ import { createNotifier } from './notify.js';
13
+ import { publicKeyOf, signApproval } from './signing.js';
14
+ import { matchAddress, PRIVATE_NETWORKS } from './hosts.js';
15
+ import { HOME, VERSION } from './config.js';
16
+ import { Settings } from './settings.js';
17
+ import { UserStore } from './users.js';
18
+ import { LoginLimiter, SessionStore } from './sessions.js';
19
+ import { createAdmin } from './admin.js';
20
+ import { entitlements, findLicenseKey } from './license.js';
21
+
22
+ const PAYMENT_HEADERS = ['payment-signature', 'x-payment'];
23
+ const BLOCKNET_HEADERS = ['x-blocknet-approval', 'x-blocknet-key'];
24
+ const HOP_HEADERS = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'content-encoding', 'proxy-authorization', 'proxy-connection']);
25
+
26
+ /**
27
+ * Blocknet Agent Gateway.
28
+ *
29
+ * Agents send outbound calls through POST /v1/fetch instead of calling services directly.
30
+ * Blocknet applies network policy, and when a service answers 402 Payment Required,
31
+ * decides whether the agent may pay (budget, price, trust) before the agent's wallet signs.
32
+ *
33
+ * @param {object} config from loadConfig()
34
+ * @param {object} [deps]
35
+ * @param {Ledger} [deps.ledger]
36
+ * @param {object} [deps.trust]
37
+ * @param {ApprovalStore} [deps.approvals]
38
+ * @param {typeof fetch} [deps.fetchImpl]
39
+ * @param {string} [deps.adminToken] needed to approve or deny; unset means anyone can (tests only)
40
+ * @param {string} [deps.signingKey] Ed25519 private key (PEM) for signed approvals
41
+ * @param {(host: string) => Promise<{address: string}[]>} [deps.lookup] DNS lookup, replaceable in tests
42
+ * @param {object} [deps.enterprise] the Blocknet Enterprise module, from loadEnterprise() (enterprise.js)
43
+ */
44
+ export function createGateway(
45
+ config,
46
+ { ledger, trust, approvals, fetchImpl = fetch, adminToken = process.env.BLOCKNET_ADMIN_TOKEN, signingKey, lookup, notifier, settings, users, sessions, enterprise: enterpriseModule, oidcFetch, licensePublicKey } = {},
47
+ ) {
48
+ ledger ??= new Ledger(config.auditLog);
49
+ trust ??= createTrust(config, ledger);
50
+ approvals ??= new ApprovalStore(config.approvalsFile ?? null);
51
+ lookup ??= (host) => dnsLookup(host, { all: true });
52
+ settings ??= new Settings(config);
53
+ const admin = config.admin ?? {};
54
+ const gatewayUrl = `http://${config.host === '0.0.0.0' ? '127.0.0.1' : config.host}:${config.port}`;
55
+ const adminUrl = admin.publicUrl ?? (admin.port ? `http://${admin.host ?? config.host}:${admin.port}` : gatewayUrl);
56
+ notifier ??= createNotifier(() => config.notify, { ledger, fetchImpl, dashboardUrl: config.notify?.dashboardUrl ?? adminUrl });
57
+ const publicKey = signingKey ? publicKeyOf(signingKey) : null;
58
+ users ??= new UserStore(config.usersFile ?? null);
59
+ sessions ??= new SessionStore(config.sessionsFile ?? null, { idleHours: admin.sessionIdleHours ?? 12, maxDays: admin.sessionMaxDays ?? 7 });
60
+ // Blocknet Enterprise (single sign-on, audit export, metrics), when installed: see enterprise.js.
61
+ const enterprise = enterpriseModule ? enterpriseModule.createEnterprise({ config, adminUrl, fetchImpl: oidcFetch ?? fetchImpl }) : null;
62
+
63
+ const budget = (agent) => {
64
+ const day = utcDay();
65
+ const team = config.payments.dailyBudgetUsd;
66
+ const spent = ledger.spentOn(day);
67
+ const reserved = approvals.reservedUsd();
68
+ const out = { day, spentUsd: round(spent), reservedUsd: round(reserved), dailyBudgetUsd: team, remainingUsd: round(team - spent - reserved) };
69
+ if (agent?.name) {
70
+ const limit = agent.config.payments.dailyBudgetUsd;
71
+ const aSpent = ledger.spentOn(day, agent.name);
72
+ const aReserved = approvals.reservedUsd(agent.name);
73
+ out.agent = {
74
+ name: agent.name,
75
+ spentUsd: round(aSpent),
76
+ reservedUsd: round(aReserved),
77
+ dailyBudgetUsd: limit,
78
+ remainingUsd: round(Math.min(limit - aSpent - aReserved, out.remainingUsd)),
79
+ };
80
+ }
81
+ return out;
82
+ };
83
+
84
+ /** Name rules first, then (when address rules exist) what the name resolves to. */
85
+ async function checkHost(host, network) {
86
+ const net = evaluateNetwork(host, network);
87
+ if (net.decision !== 'allow') return net;
88
+ const ranges = [...(network.blockAddresses ?? []), ...(network.blockPrivateNetworks ? PRIVATE_NETWORKS : [])];
89
+ if (!ranges.length) return net;
90
+ const bare = host.replace(/^\[|\]$/g, '');
91
+ let addresses;
92
+ try {
93
+ addresses = isIP(bare) ? [bare] : (await lookup(bare)).map((r) => r.address);
94
+ } catch {
95
+ return net; // can't resolve: the request itself will fail
96
+ }
97
+ for (const address of addresses) {
98
+ const range = matchAddress(address, ranges);
99
+ if (range) return { decision: 'deny', reasons: [`${host} resolves to ${address}, in blocked range ${range}`] };
100
+ }
101
+ return net;
102
+ }
103
+
104
+ function identify(req) {
105
+ return resolveAgent(config, keyFromHeaders(req.headers));
106
+ }
107
+
108
+ async function handleFetch(req, res) {
109
+ const agent = identify(req);
110
+ if (!agent) return send(res, 401, { error: 'agent key required: send your key in the x-blocknet-key header' });
111
+ const cfg = agent.config;
112
+ const input = await readJson(req);
113
+ let target;
114
+ try {
115
+ target = new URL(input.url);
116
+ if (!['http:', 'https:'].includes(target.protocol)) throw new Error();
117
+ } catch {
118
+ return send(res, 400, { error: 'url must be an absolute http(s) URL' });
119
+ }
120
+ const host = target.hostname;
121
+ const method = (input.method ?? 'GET').toUpperCase();
122
+ const headers = lower(input.headers ?? {});
123
+ const who = agent.name ? { agent: agent.name } : {};
124
+
125
+ const net = await checkHost(host, cfg.network);
126
+ if (net.decision !== 'allow') {
127
+ ledger.record({ type: 'blocked', ...who, host, url: target.href, method, ...net });
128
+ return send(res, 403, { blocked: true, ...net });
129
+ }
130
+
131
+ const paying = PAYMENT_HEADERS.some((h) => headers[h]);
132
+ let approval = null;
133
+ if (paying) {
134
+ approval = approvals.get(input.approval ?? headers['x-blocknet-approval']);
135
+ const problem = !approval
136
+ ? 'paid retry needs an approval id from Blocknet'
137
+ : approval.host !== host
138
+ ? 'approval was issued for a different host'
139
+ : (approval.agent ?? null) !== agent.name
140
+ ? 'approval was issued to a different agent'
141
+ : approval.status !== 'approved'
142
+ ? `approval is ${approval.status}`
143
+ : approval.usedAt
144
+ ? 'approval was already used'
145
+ : approval.expiresAt < Date.now()
146
+ ? 'approval expired'
147
+ : null;
148
+ if (problem) {
149
+ ledger.record({ type: 'payment_refused', ...who, host, url: target.href, reason: problem });
150
+ return send(res, 403, { blocked: true, decision: 'deny', reasons: [problem] });
151
+ }
152
+ approval.usedAt = Date.now();
153
+ approvals.put(approval);
154
+ }
155
+
156
+ for (const h of BLOCKNET_HEADERS) delete headers[h];
157
+ let upstream;
158
+ try {
159
+ upstream = await fetchImpl(target, {
160
+ method,
161
+ headers,
162
+ body: ['GET', 'HEAD'].includes(method) ? undefined : bodyOf(input.body),
163
+ redirect: 'manual',
164
+ });
165
+ } catch (err) {
166
+ if (approval) recordPayment(approval, false, 0, String(err.message ?? err));
167
+ return send(res, 502, { error: 'upstream unreachable', detail: String(err.message ?? err) });
168
+ }
169
+
170
+ if (approval) {
171
+ recordPayment(approval, upstream.ok, upstream.status, upstream.headers.get('payment-response'));
172
+ } else {
173
+ ledger.record({ type: 'request', ...who, host, method, status: upstream.status });
174
+ }
175
+
176
+ if (upstream.status === 402 && !approval) {
177
+ const text = await upstream.text();
178
+ const required = parsePaymentRequired(upstream.headers, text);
179
+ if (required) return send(res, 402, await decide(target, required, agent), passHeaders(upstream.headers));
180
+ res.writeHead(402, passHeaders(upstream.headers));
181
+ return res.end(text);
182
+ }
183
+
184
+ // Everything else streams straight through, bytes untouched (images, PDFs, large downloads).
185
+ res.writeHead(upstream.status, { ...passHeaders(upstream.headers), ...(approval && { 'x-blocknet-approval': approval.id }) });
186
+ if (!upstream.body) return res.end();
187
+ Readable.fromWeb(upstream.body)
188
+ .on('error', () => res.destroy())
189
+ .pipe(res);
190
+ }
191
+
192
+ async function decide(target, required, agent) {
193
+ const host = target.hostname;
194
+ const cfg = agent.config;
195
+ const { option, acceptable } = chooseOption(required.options, cfg.payments);
196
+ const score = await trust.score(host);
197
+ const b = budget(agent);
198
+ const own = b.agent ?? b;
199
+ const verdict = evaluatePayment({
200
+ option,
201
+ acceptable,
202
+ trust: score,
203
+ spentTodayUsd: own.spentUsd + own.reservedUsd,
204
+ teamRemainingUsd: agent.name ? b.remainingUsd : undefined,
205
+ config: cfg,
206
+ });
207
+ const status = { allow: 'approved', review: 'pending', deny: 'denied' }[verdict.decision];
208
+ const approval = {
209
+ id: randomUUID(),
210
+ ...(agent.name && { agent: agent.name }),
211
+ host,
212
+ url: target.href,
213
+ option,
214
+ trust: score,
215
+ decision: verdict.decision,
216
+ reasons: verdict.reasons,
217
+ status,
218
+ createdAt: Date.now(),
219
+ expiresAt: Date.now() + cfg.payments.approvalTtlSeconds * 1000,
220
+ };
221
+ if (status === 'approved') sign(approval);
222
+ approvals.put(approval);
223
+ ledger.record({ type: 'payment_decision', id: approval.id, ...(agent.name && { agent: agent.name }), host, amountUsd: option.amountUsd, network: option.network, asset: option.asset, decision: verdict.decision, reasons: verdict.reasons, trust: score });
224
+ if (status === 'pending') notifier.pending(approval);
225
+ return {
226
+ status: 402,
227
+ blocknet: {
228
+ decision: verdict.decision,
229
+ approval: approval.id,
230
+ approvalStatus: status,
231
+ reasons: verdict.reasons,
232
+ option,
233
+ trust: score,
234
+ budgetRemainingUsd: verdict.remainingUsd,
235
+ ...(approval.signature && { signature: approval.signature, expiresAt: approval.expiresAt }),
236
+ next:
237
+ status === 'approved'
238
+ ? 'Sign the payment and retry through /v1/fetch with this approval id.'
239
+ : status === 'pending'
240
+ ? 'A human must approve this payment. Poll GET /v1/approvals/{id}.'
241
+ : 'Do not pay this service.',
242
+ },
243
+ paymentRequired: required.raw,
244
+ };
245
+ }
246
+
247
+ function sign(approval) {
248
+ if (signingKey) approval.signature = signApproval(approval, signingKey);
249
+ }
250
+
251
+ function recordPayment(approval, settled, status, receipt) {
252
+ ledger.record({
253
+ type: 'payment',
254
+ id: approval.id,
255
+ ...(approval.agent && { agent: approval.agent }),
256
+ host: approval.host,
257
+ amountUsd: settled ? approval.option.amountUsd : 0,
258
+ quotedUsd: approval.option.amountUsd,
259
+ network: approval.option.network,
260
+ payTo: approval.option.payTo,
261
+ settled,
262
+ status,
263
+ receipt: receipt ?? null,
264
+ });
265
+ }
266
+
267
+ const isAdmin = (req) => !adminToken || req.headers.authorization === `Bearer ${adminToken}`;
268
+
269
+ /** A person approves or denies a pending payment (API, CLI or console). */
270
+ function decideApproval(id, verb, actor) {
271
+ const a = approvals.get(id);
272
+ if (!a) return { status: 404, body: { error: 'unknown approval' } };
273
+ if (a.status !== 'pending') return { status: 409, body: { error: `approval is ${a.status}` } };
274
+ if (verb === 'approve') {
275
+ const owner = a.agent && config.agents?.[a.agent] ? { name: a.agent, config: effectiveConfig(config, config.agents[a.agent]) } : null;
276
+ const b = budget(owner);
277
+ if (a.option.amountUsd > (b.agent ?? b).remainingUsd) return { status: 409, body: { error: 'not enough daily budget left' } };
278
+ }
279
+ a.status = verb === 'approve' ? 'approved' : 'denied';
280
+ a.decidedBy = actor;
281
+ a.expiresAt = Date.now() + config.payments.approvalTtlSeconds * 1000;
282
+ if (a.status === 'approved') sign(a);
283
+ approvals.put(a);
284
+ ledger.record({ type: 'approval', id: a.id, ...(a.agent && { agent: a.agent }), host: a.host, status: a.status, actor });
285
+ return { status: 200, body: a };
286
+ }
287
+
288
+ // The plan in force. Re-checked when the key or the date changes; never consulted on the request path.
289
+ let licenseCache = { text: undefined, day: '', value: null };
290
+ const licensing = () => {
291
+ const found = findLicenseKey(config, HOME);
292
+ const day = new Date().toISOString().slice(0, 13);
293
+ if (licenseCache.text !== found?.key || licenseCache.day !== day) {
294
+ licenseCache = { text: found?.key, day, value: entitlements(found, { publicKey: licensePublicKey }) };
295
+ }
296
+ return licenseCache.value;
297
+ };
298
+
299
+ const console_ = createAdmin({
300
+ licensing,
301
+ config, settings, users, sessions, limiter: new LoginLimiter(), enterprise, ledger, approvals, budget, decideApproval, publicKey, adminToken,
302
+ home: HOME, gatewayUrl, adminUrl,
303
+ });
304
+ const separateAdmin = Boolean(admin.port);
305
+
306
+ /** Who may read: with agents configured, the admin (everything) or a known agent (its own). */
307
+ function reader(req) {
308
+ if (!agentsEnabled(config) || (adminToken && isAdmin(req))) return { admin: true };
309
+ const agent = identify(req);
310
+ return agent ? { agent } : null;
311
+ }
312
+
313
+ async function route(req, res) {
314
+ settings.refresh();
315
+ if (/^https?:\/\//i.test(req.url)) return handleProxyRequest(req, res);
316
+ const url = new URL(req.url, 'http://blocknet');
317
+ const path = url.pathname;
318
+
319
+ if (req.method === 'GET' && path === '/healthz') return send(res, 200, { ok: true, version: VERSION });
320
+ if (!separateAdmin) {
321
+ if (await console_.handle(req, res, url)) return;
322
+ } else if (path === '/' || /^\/(admin|auth|console)\//.test(path) || path === '/metrics') {
323
+ return send(res, 404, { error: 'the admin console is on its own port', adminUrl });
324
+ }
325
+ if (req.method === 'POST' && path === '/v1/fetch') return handleFetch(req, res);
326
+ if (req.method === 'GET' && path === '/v1/signing-key') {
327
+ if (!publicKey) return send(res, 404, { error: 'approval signing is off' });
328
+ return send(res, 200, { algorithm: 'ed25519', publicKey });
329
+ }
330
+
331
+ const who = reader(req);
332
+ if (req.method === 'GET' && path === '/v1/budget') {
333
+ if (!who) return send(res, 401, { error: 'agent key or admin token required' });
334
+ return send(res, 200, budget(who.agent));
335
+ }
336
+ if (req.method === 'GET' && path === '/v1/audit') {
337
+ // The full log names every host, agent and user: always admin only (the console has its own search).
338
+ if (!isAdmin(req)) return send(res, 401, { error: 'admin token required' });
339
+ return send(res, 200, { entries: ledger.recent(Math.min(1000, Number(url.searchParams.get('limit') ?? 50) || 50)) });
340
+ }
341
+ if (req.method === 'GET' && path === '/v1/approvals') {
342
+ if (!who) return send(res, 401, { error: 'agent key or admin token required' });
343
+ return send(res, 200, { approvals: approvals.list({ status: url.searchParams.get('status'), agent: who.agent?.name }) });
344
+ }
345
+
346
+ const m = path.match(/^\/v1\/approvals\/([\w-]+)(?:\/(approve|deny))?$/);
347
+ if (m) {
348
+ const a = approvals.get(m[1]);
349
+ if (req.method === 'GET' && !m[2]) {
350
+ if (!who) return send(res, 401, { error: 'agent key or admin token required' });
351
+ if (!a || (who.agent && (a.agent ?? null) !== who.agent.name)) return send(res, 404, { error: 'unknown approval' });
352
+ return send(res, 200, a);
353
+ }
354
+ if (req.method === 'POST' && m[2]) {
355
+ if (!isAdmin(req)) return send(res, 401, { error: 'admin token required' });
356
+ const out = decideApproval(m[1], m[2], 'admin-token');
357
+ return send(res, out.status, out.body);
358
+ }
359
+ }
360
+ send(res, 404, { error: 'not found' });
361
+ }
362
+
363
+ // ---- Proxy mode (HTTP_PROXY / HTTPS_PROXY): network rules only, off unless proxy.enabled ----
364
+
365
+ function proxyAgent(req) {
366
+ if (!config.proxy?.enabled) return { refused: [405, 'proxy mode is off; set proxy.enabled to use Blocknet as HTTP_PROXY / HTTPS_PROXY'] };
367
+ const agent = identify(req);
368
+ if (!agent) return { refused: [407, 'agent key required: use http://agent:<key>@host:port as the proxy URL'] };
369
+ return { agent };
370
+ }
371
+
372
+ async function handleProxyRequest(req, res) {
373
+ const { agent, refused } = proxyAgent(req);
374
+ if (refused) return send(res, refused[0], { error: refused[1] }, refused[0] === 407 ? { 'proxy-authenticate': 'Basic realm="blocknet"' } : {});
375
+ const target = new URL(req.url);
376
+ const who = agent.name ? { agent: agent.name } : {};
377
+ const headers = lower(req.headers);
378
+ if (PAYMENT_HEADERS.some((h) => headers[h])) {
379
+ ledger.record({ type: 'payment_refused', ...who, host: target.hostname, url: target.href, reason: 'payments must go through /v1/fetch' });
380
+ return send(res, 403, { blocked: true, decision: 'deny', reasons: ['payments must go through /v1/fetch, not the proxy'] });
381
+ }
382
+ const net = await checkHost(target.hostname, agent.config.network);
383
+ if (net.decision !== 'allow') {
384
+ ledger.record({ type: 'blocked', ...who, host: target.hostname, url: target.href, method: req.method, via: 'proxy', ...net });
385
+ return send(res, 403, { blocked: true, ...net });
386
+ }
387
+ for (const h of [...HOP_HEADERS, ...BLOCKNET_HEADERS]) delete headers[h];
388
+ let upstream;
389
+ try {
390
+ upstream = await fetchImpl(target, {
391
+ method: req.method,
392
+ headers,
393
+ body: ['GET', 'HEAD'].includes(req.method) ? undefined : Readable.toWeb(req),
394
+ duplex: 'half',
395
+ redirect: 'manual',
396
+ });
397
+ } catch (err) {
398
+ return send(res, 502, { error: 'upstream unreachable', detail: String(err.message ?? err) });
399
+ }
400
+ ledger.record({ type: 'request', ...who, host: target.hostname, method: req.method, status: upstream.status, via: 'proxy' });
401
+ res.writeHead(upstream.status, passHeaders(upstream.headers));
402
+ if (!upstream.body) return res.end();
403
+ Readable.fromWeb(upstream.body).on('error', () => res.destroy()).pipe(res);
404
+ }
405
+
406
+ async function handleConnect(req, socket, head) {
407
+ const reply = (status, text) => socket.end(`HTTP/1.1 ${status} ${text}\r\n${status === 407 ? 'Proxy-Authenticate: Basic realm="blocknet"\r\n' : ''}\r\n`);
408
+ const { agent, refused } = proxyAgent(req);
409
+ if (refused) return reply(refused[0], refused[0] === 407 ? 'Proxy Authentication Required' : 'Method Not Allowed');
410
+ const [, host, port = '443'] = req.url.match(/^\[?([^\]]+?)\]?(?::(\d+))?$/) ?? [];
411
+ if (!host) return reply(400, 'Bad Request');
412
+ const who = agent.name ? { agent: agent.name } : {};
413
+ const net = await checkHost(host, agent.config.network);
414
+ if (net.decision !== 'allow') {
415
+ ledger.record({ type: 'blocked', ...who, host, method: 'CONNECT', via: 'proxy', ...net });
416
+ return reply(403, 'Forbidden');
417
+ }
418
+ const upstream = connect(Number(port), host, () => {
419
+ ledger.record({ type: 'tunnel', ...who, host, port: Number(port) });
420
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
421
+ if (head?.length) upstream.write(head);
422
+ upstream.pipe(socket);
423
+ socket.pipe(upstream);
424
+ });
425
+ upstream.on('error', () => reply(502, 'Bad Gateway'));
426
+ socket.on('error', () => upstream.destroy());
427
+ }
428
+
429
+ const server = createServer((req, res) => {
430
+ route(req, res).catch((err) => {
431
+ if (!res.headersSent) send(res, err.status ?? 500, { error: err.expose ? err.message : 'internal error' });
432
+ else res.end();
433
+ });
434
+ });
435
+ server.on('connect', (req, socket, head) => handleConnect(req, socket, head).catch(() => socket.destroy()));
436
+
437
+ // With admin.port set, the console and admin API listen on their own server; agents only need the gateway port.
438
+ const adminServer = separateAdmin
439
+ ? createServer(async (req, res) => {
440
+ try {
441
+ settings.refresh();
442
+ const url = new URL(req.url, 'http://blocknet');
443
+ if (url.pathname === '/healthz') return send(res, 200, { ok: true, version: VERSION });
444
+ if (!(await console_.handle(req, res, url))) send(res, 404, { error: 'not found' });
445
+ } catch {
446
+ if (!res.headersSent) send(res, 500, { error: 'internal error' });
447
+ else res.end();
448
+ }
449
+ })
450
+ : null;
451
+
452
+ return { server, adminServer, ledger, approvals, budget, publicKey, users, sessions, settings, licensing, enterprise };
453
+ }
454
+
455
+ function send(res, status, body, headers = {}) {
456
+ res.writeHead(status, { ...headers, 'content-type': 'application/json' });
457
+ res.end(JSON.stringify(body, null, 2));
458
+ }
459
+
460
+ async function readJson(req) {
461
+ let raw = '';
462
+ for await (const chunk of req) {
463
+ raw += chunk;
464
+ if (raw.length > 1_000_000) throw Object.assign(new Error('body too large'), { status: 413, expose: true });
465
+ }
466
+ try {
467
+ return JSON.parse(raw || '{}');
468
+ } catch {
469
+ throw Object.assign(new Error('body must be JSON'), { status: 400, expose: true });
470
+ }
471
+ }
472
+
473
+ const lower = (h) => Object.fromEntries(Object.entries(h).map(([k, v]) => [k.toLowerCase(), String(v)]));
474
+ const bodyOf = (b) => (b == null ? undefined : typeof b === 'string' ? b : JSON.stringify(b));
475
+
476
+ function passHeaders(headers) {
477
+ const out = {};
478
+ for (const [k, v] of headers) if (!HOP_HEADERS.has(k)) out[k] = v;
479
+ return out;
480
+ }
package/src/hosts.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Host pattern matching for network policy.
3
+ *
4
+ * "api.example.com" matches exactly that host
5
+ * "*.example.com" matches any subdomain (not example.com itself)
6
+ * "*" matches everything
7
+ */
8
+ export function matchHost(host, pattern) {
9
+ host = host.toLowerCase();
10
+ pattern = pattern.toLowerCase();
11
+ if (pattern === '*') return true;
12
+ if (pattern.startsWith('*.')) return host.endsWith(pattern.slice(1));
13
+ return host === pattern;
14
+ }
15
+
16
+ export function matchAny(host, patterns = []) {
17
+ return patterns.find((p) => matchHost(host, p)) ?? null;
18
+ }
19
+
20
+ /**
21
+ * IP range matching, for rules on what an address resolves to (not just its name).
22
+ *
23
+ * ipInCidr('169.254.169.254', '169.254.0.0/16') -> true
24
+ * ipInCidr('::ffff:10.0.0.1', '10.0.0.0/8') -> true (IPv4-mapped IPv6 is treated as IPv4)
25
+ */
26
+ export function ipInCidr(ip, cidr) {
27
+ const [range, bitsText] = cidr.split('/');
28
+ const a = ipToBigInt(ip);
29
+ const b = ipToBigInt(range);
30
+ if (!a || !b || a.v !== b.v) return false;
31
+ const width = a.v === 4 ? 32 : 128;
32
+ const bits = bitsText === undefined ? width : Number(bitsText);
33
+ if (!Number.isInteger(bits) || bits < 0 || bits > width) return false;
34
+ const shift = BigInt(width - bits);
35
+ return a.n >> shift === b.n >> shift;
36
+ }
37
+
38
+ export function matchAddress(ip, cidrs = []) {
39
+ return cidrs.find((c) => ipInCidr(ip, c)) ?? null;
40
+ }
41
+
42
+ /** Private, loopback and link-local ranges: added when network.blockPrivateNetworks is on. */
43
+ export const PRIVATE_NETWORKS = [
44
+ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8', '100.64.0.0/10', '0.0.0.0/8',
45
+ '::1/128', 'fc00::/7', '::/128',
46
+ ];
47
+
48
+ function ipToBigInt(ip) {
49
+ ip = ip.replace(/^\[|\]$/g, '').split('%')[0].toLowerCase();
50
+ const mapped = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
51
+ if (mapped) ip = mapped[1];
52
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(ip)) {
53
+ const parts = ip.split('.').map(Number);
54
+ if (parts.some((p) => p > 255)) return null;
55
+ return { v: 4, n: parts.reduce((n, p) => (n << 8n) + BigInt(p), 0n) };
56
+ }
57
+ if (!ip.includes(':')) return null;
58
+ let [head, tail] = ip.split('::');
59
+ if (ip.split('::').length > 2) return null;
60
+ const h = head ? head.split(':') : [];
61
+ const t = tail !== undefined ? (tail ? tail.split(':') : []) : null;
62
+ // a trailing dotted IPv4 counts as two groups
63
+ const expand = (groups) =>
64
+ groups.flatMap((g) => {
65
+ if (!g.includes('.')) return [g];
66
+ const v4 = ipToBigInt(g);
67
+ return v4 ? [(v4.n >> 16n).toString(16), (v4.n & 0xffffn).toString(16)] : ['x'];
68
+ });
69
+ const hh = expand(h);
70
+ const tt = t ? expand(t) : [];
71
+ const groups = t ? [...hh, ...Array(8 - hh.length - tt.length).fill('0'), ...tt] : hh;
72
+ if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/.test(g))) return null;
73
+ const n = groups.reduce((acc, g) => (acc << 16n) + BigInt(parseInt(g, 16)), 0n);
74
+ // ::ffff:a9fe:a9fe is 169.254.169.254 written in hex (URL parsing produces this form)
75
+ if (n >> 32n === 0xffffn) return { v: 4, n: n & 0xffffffffn };
76
+ return { v: 6, n };
77
+ }
package/src/ledger.js ADDED
@@ -0,0 +1,55 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+
4
+ /**
5
+ * Append-only audit log (JSONL) plus a daily spend tally.
6
+ * Today's spend is rebuilt from the log on startup, so restarts don't reset the budget.
7
+ */
8
+ export class Ledger {
9
+ constructor(path) {
10
+ this.path = path;
11
+ this.entries = [];
12
+ if (path && existsSync(path)) {
13
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
14
+ if (!line.trim()) continue;
15
+ try {
16
+ this.entries.push(JSON.parse(line));
17
+ } catch {
18
+ // skip a torn line
19
+ }
20
+ }
21
+ }
22
+ }
23
+
24
+ record(event) {
25
+ const entry = { ts: new Date().toISOString(), ...event };
26
+ this.entries.push(entry);
27
+ if (this.path) {
28
+ mkdirSync(dirname(this.path), { recursive: true });
29
+ appendFileSync(this.path, JSON.stringify(entry) + '\n');
30
+ }
31
+ return entry;
32
+ }
33
+
34
+ /** Settled spend on a UTC day, for everyone or one agent. */
35
+ spentOn(day = utcDay(), agent) {
36
+ return this.entries
37
+ .filter((e) => e.type === 'payment' && e.settled && e.ts.slice(0, 10) === day && (!agent || e.agent === agent))
38
+ .reduce((sum, e) => sum + (e.amountUsd ?? 0), 0);
39
+ }
40
+
41
+ recent(limit = 50) {
42
+ return this.entries.slice(-limit).reverse();
43
+ }
44
+
45
+ /** Local outcome history for a host: successes / failures of paid calls. */
46
+ history(host) {
47
+ const paid = this.entries.filter((e) => e.type === 'payment' && e.host === host);
48
+ return {
49
+ successes: paid.filter((e) => e.settled).length,
50
+ failures: paid.filter((e) => !e.settled).length,
51
+ };
52
+ }
53
+ }
54
+
55
+ export const utcDay = (d = new Date()) => d.toISOString().slice(0, 10);