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,388 @@
1
+ #!/usr/bin/env node
2
+ import { randomBytes } from 'node:crypto';
3
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { HOME, VERSION, loadConfig } from '../src/config.js';
6
+ import { createGateway } from '../src/gateway.js';
7
+ import { runMcpServer } from '../src/mcp.js';
8
+ import { keyHash, keyPreview, newAgentKey } from '../src/agents.js';
9
+ import { ROLES, UserStore, publicUser } from '../src/users.js';
10
+ import { generateSigningKey } from '../src/signing.js';
11
+ import { PLANS, entitlements, findLicenseKey, verifyLicense } from '../src/license.js';
12
+ import { findEnterprise, loadEnterprise } from '../src/enterprise.js';
13
+ import { Settings } from '../src/settings.js';
14
+
15
+ const SELF = new URL('../bin/blocknet.js', import.meta.url).pathname;
16
+ const HELP = `blocknet ${VERSION}: security and spending control for AI agents
17
+
18
+ Run
19
+ blocknet start Run the gateway and admin console (http://127.0.0.1:8402)
20
+ blocknet mcp Run as an MCP server for Claude and other AI clients
21
+ (starts the gateway too, unless one is already running)
22
+
23
+ Watch and decide (talk to the running gateway, using the admin token)
24
+ blocknet status Budget, payments waiting for you, recent activity
25
+ blocknet pending Payments waiting for a person
26
+ blocknet approve <id> Approve a waiting payment (the first characters of the id are enough)
27
+ blocknet deny <id> Deny a waiting payment
28
+ blocknet log [n] The last n audit entries (default 20)
29
+
30
+ Agents
31
+ blocknet agent add <name> [--budget 1] [--max 0.05]
32
+ Give an agent its own key and budget (written to your config file)
33
+ blocknet agent list Agents and their limits
34
+ blocknet agent remove <name> Remove an agent and its key
35
+
36
+ Console users (sign in at the admin console)
37
+ blocknet user add <email> [--role admin|approver|viewer] [--name "Ana"]
38
+ Add a user; prints a temporary password they change at first sign-in
39
+ blocknet user list Users and their roles
40
+ blocknet user reset-password <email>
41
+ blocknet user remove <email>
42
+
43
+ Plan
44
+ blocknet license Your plan, what it includes, and when it renews
45
+ blocknet license install <key> Install a licence key from Acific Labs
46
+ blocknet license remove Go back to the Free plan
47
+
48
+ Options: --config <file> --port <port>. Data lives in ${HOME}
49
+
50
+ Add to Claude Code:
51
+ claude mcp add -s user blocknet -- node ${SELF} mcp
52
+ `;
53
+
54
+ const [cmd = 'start', ...args] = process.argv.slice(2);
55
+ const flag = (name) => {
56
+ const i = args.indexOf(`--${name}`);
57
+ return i >= 0 ? args[i + 1] : undefined;
58
+ };
59
+ const positional = args.filter((a, i) => !a.startsWith('--') && !args[i - 1]?.startsWith('--'));
60
+
61
+ const COMMANDS = ['start', 'mcp', 'status', 'pending', 'approve', 'deny', 'log', 'agent', 'user', 'license'];
62
+ if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
63
+ process.stdout.write(HELP);
64
+ process.exit(0);
65
+ }
66
+ if (cmd === '--version' || cmd === '-v') {
67
+ process.stdout.write(VERSION + '\n');
68
+ process.exit(0);
69
+ }
70
+ if (!COMMANDS.includes(cmd)) {
71
+ process.stderr.write(HELP);
72
+ process.exit(1);
73
+ }
74
+
75
+ const config = loadConfig(flag('config'));
76
+ if (flag('port')) config.port = Number(flag('port'));
77
+ const gatewayUrl = process.env.BLOCKNET_URL ?? `http://${config.host === '0.0.0.0' ? '127.0.0.1' : config.host}:${config.port}`;
78
+ // In MCP mode stdout is the protocol, so everything human goes to stderr.
79
+ const log = (line = '') => (cmd === 'mcp' ? process.stderr : process.stdout).write(line + '\n');
80
+ const fail = (line) => {
81
+ process.stderr.write(line + '\n');
82
+ process.exit(1);
83
+ };
84
+
85
+ /** The running gateway's health answer, or null if none is listening. */
86
+ async function runningGateway() {
87
+ try {
88
+ const res = await fetch(`${gatewayUrl}/healthz`, { signal: AbortSignal.timeout(500) });
89
+ return res.ok ? await res.json().catch(() => ({})) : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ /** Reusing a gateway is fine, but say so, and warn when it's from another version: it may have older rules. */
96
+ async function reuseGateway() {
97
+ const running = (await runningGateway()) ?? {};
98
+ log(`blocknet. using the gateway already running at ${gatewayUrl}`);
99
+ if (running.version !== VERSION) {
100
+ log(` warning: that gateway is version ${running.version ?? 'unknown'}, this is ${VERSION}. Its settings and log come from where it was started. Restart it to pick up this version.`);
101
+ }
102
+ }
103
+
104
+ /** A secret Blocknet makes once and keeps in its home, readable only by you. */
105
+ function secretFile(name, make) {
106
+ const file = join(HOME, name);
107
+ if (!existsSync(file)) {
108
+ mkdirSync(HOME, { recursive: true, mode: 0o700 });
109
+ writeFileSync(file, make(), { mode: 0o600 });
110
+ }
111
+ return { value: readFileSync(file, 'utf8').trim(), file };
112
+ }
113
+
114
+ /**
115
+ * Safe with no setup: approving payments always needs a token, so an agent can't approve its own.
116
+ * BLOCKNET_ADMIN_TOKEN wins; otherwise one is made once and kept in ~/.blocknet/admin-token.
117
+ */
118
+ function adminToken() {
119
+ if (process.env.BLOCKNET_ADMIN_TOKEN) return { token: process.env.BLOCKNET_ADMIN_TOKEN, from: 'BLOCKNET_ADMIN_TOKEN' };
120
+ const { value, file } = secretFile('admin-token', () => randomBytes(16).toString('hex') + '\n');
121
+ return { token: value, from: file };
122
+ }
123
+
124
+ async function startGateway() {
125
+ const { token, from } = adminToken();
126
+ const signingKey = process.env.BLOCKNET_SIGNING_KEY ?? secretFile('signing-key.pem', generateSigningKey).value;
127
+ const enterprise = await loadEnterprise(config, HOME);
128
+ const { server, adminServer, users } = createGateway(config, { adminToken: token, signingKey, enterprise });
129
+ const agents = Object.keys(config.agents ?? {});
130
+ const admin = config.admin ?? {};
131
+ const consoleUrl = admin.publicUrl ?? `http://${admin.host ?? config.host}:${admin.port ?? config.port}`;
132
+ if (adminServer) {
133
+ adminServer.on('error', (err) => fail(`admin console: ${err.message}`));
134
+ adminServer.listen(admin.port, admin.host ?? config.host);
135
+ }
136
+ return new Promise((resolve, reject) => {
137
+ server.once('error', reject);
138
+ server.listen(config.port, config.host, () => {
139
+ log(`blocknet. gateway on http://${config.host}:${config.port}`);
140
+ log(` admin console: ${consoleUrl}${users.count() ? '' : ' (first run: open it to create the first admin, using the admin token)'}${admin.oidc?.issuer ? ' SSO: on' : ''}`);
141
+ log(` config: ${config.configFile ?? 'none, using safe defaults'} audit log: ${config.auditLog}`);
142
+ log(` daily budget: $${config.payments.dailyBudgetUsd} per request: up to $${config.payments.maxPerRequestUsd}`);
143
+ log(` agents: ${agents.length ? agents.join(', ') + ' (keys required)' : 'one, no key needed'}${config.proxy?.enabled ? ' proxy mode: on' : ''}${config.notify?.webhookUrl ? ' notifications: on' : ''}`);
144
+ const ent = entitlements(findLicenseKey(config, HOME));
145
+ log(` plan: ${ent.name}${ent.license ? ` (${ent.license.customer}, until ${ent.license.expiresAt.slice(0, 10)})` : ' (blocknet license to see what it includes)'}${enterprise ? ` Blocknet Enterprise ${enterprise.version}` : ''}`);
146
+ if (ent.plan !== 'free' && !enterprise) log(' Your licence includes paid features: install the Blocknet Enterprise package that came with it in ~/.blocknet/enterprise to turn them on.');
147
+ if (ent.message) log(` note: ${ent.message}`);
148
+ log(` admin token (to approve payments): ${from}`);
149
+ resolve(adminServer ? { close: () => (server.close(), adminServer.close()), closeAllConnections: () => (server.closeAllConnections?.(), adminServer.closeAllConnections?.()) } : server);
150
+ });
151
+ });
152
+ }
153
+
154
+ /** Calls the running gateway as the admin. */
155
+ async function admin(path, init = {}) {
156
+ let res;
157
+ try {
158
+ res = await fetch(gatewayUrl + path, { ...init, headers: { authorization: `Bearer ${adminToken().token}`, ...init.headers } });
159
+ } catch {
160
+ fail(`No gateway running at ${gatewayUrl}. Start one with: blocknet start`);
161
+ }
162
+ const body = await res.json().catch(() => ({}));
163
+ if (!res.ok) fail(`Blocknet: ${body.error ?? res.status}`);
164
+ return body;
165
+ }
166
+
167
+ const usd = (n) => `$${Number(n ?? 0).toFixed(n && Math.abs(n) < 0.01 ? 4 : 2)}`;
168
+ const time = (ts) => new Date(ts).toLocaleTimeString();
169
+ const short = (id) => id.slice(0, 8);
170
+
171
+ function printPending(list) {
172
+ if (!list.length) return log('Nothing waiting for you.');
173
+ for (const a of list) {
174
+ log(`${short(a.id)} ${usd(a.option.amountUsd)} ${a.option.asset} to ${a.host}${a.agent ? ` (agent ${a.agent})` : ''}`);
175
+ log(` ${a.reasons.join('; ')}`);
176
+ }
177
+ log();
178
+ log('Approve with: blocknet approve <id> Deny with: blocknet deny <id>');
179
+ }
180
+
181
+ function describe(e) {
182
+ const who = e.agent ? ` [${e.agent}]` : '';
183
+ const what =
184
+ e.type === 'payment_decision' ? `${e.decision} ${usd(e.amountUsd)}`
185
+ : e.type === 'payment' ? `${e.settled ? 'paid' : 'failed'} ${usd(e.quotedUsd)}`
186
+ : e.type === 'blocked' ? e.reasons?.join('; ')
187
+ : e.type === 'approval' ? e.status
188
+ : e.status ?? e.reason ?? e.error ?? '';
189
+ return `${time(e.ts)} ${e.type.padEnd(16)} ${String(e.host ?? '').padEnd(28)} ${what}${who}`;
190
+ }
191
+
192
+ /**
193
+ * The raw config file, for `agent` commands, which edit it. Saved through Settings, so the write is
194
+ * atomic and the version it replaces is kept (it can be restored from the console).
195
+ */
196
+ function configFile() {
197
+ const file = config.configFile ?? join(HOME, 'config.json');
198
+ const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
199
+ return {
200
+ file,
201
+ raw,
202
+ save(reason) {
203
+ new Settings({ ...config, configFile: file }).write((current) => {
204
+ for (const k of Object.keys(current)) delete current[k];
205
+ Object.assign(current, raw);
206
+ }, { actor: 'cli', reason });
207
+ },
208
+ };
209
+ }
210
+
211
+ /** Stop cleanly on Ctrl-C and on `docker stop` (Node as PID 1 ignores SIGTERM otherwise). */
212
+ function stopOnSignal(server) {
213
+ for (const signal of ['SIGINT', 'SIGTERM']) {
214
+ process.once(signal, () => {
215
+ server.close();
216
+ server.closeAllConnections?.();
217
+ process.exit(0);
218
+ });
219
+ }
220
+ }
221
+
222
+ switch (cmd) {
223
+ case 'start':
224
+ stopOnSignal(await startGateway());
225
+ break;
226
+
227
+ case 'mcp':
228
+ if (await runningGateway()) await reuseGateway();
229
+ else {
230
+ // Another client may have started one at the same moment; if so, share it.
231
+ await startGateway().catch((err) => {
232
+ if (err.code !== 'EADDRINUSE') throw err;
233
+ return reuseGateway();
234
+ });
235
+ }
236
+ await runMcpServer({ gateway: gatewayUrl });
237
+ process.exit(0);
238
+ break;
239
+
240
+ case 'status': {
241
+ const [b, p, a] = await Promise.all([admin('/v1/budget'), admin('/v1/approvals?status=pending'), admin('/v1/audit?limit=8')]);
242
+ log(`blocknet. ${gatewayUrl}`);
243
+ log(`Today (${b.day} UTC): spent ${usd(b.spentUsd)}, held ${usd(b.reservedUsd)}, left ${usd(b.remainingUsd)} of ${usd(b.dailyBudgetUsd)}`);
244
+ log();
245
+ log(`Waiting for you: ${p.approvals.length}`);
246
+ if (p.approvals.length) printPending(p.approvals);
247
+ log();
248
+ log('Recent:');
249
+ for (const e of a.entries) log(' ' + describe(e));
250
+ if (!a.entries.length) log(' no traffic yet');
251
+ break;
252
+ }
253
+
254
+ case 'pending':
255
+ printPending((await admin('/v1/approvals?status=pending')).approvals);
256
+ break;
257
+
258
+ case 'approve':
259
+ case 'deny': {
260
+ const want = positional[0];
261
+ if (!want) fail(`Usage: blocknet ${cmd} <id>`);
262
+ const { approvals } = await admin('/v1/approvals?status=pending');
263
+ const matches = approvals.filter((a) => a.id.startsWith(want));
264
+ if (matches.length !== 1) fail(matches.length ? `"${want}" matches ${matches.length} payments; use more of the id.` : `No waiting payment starts with "${want}". See: blocknet pending`);
265
+ const a = await admin(`/v1/approvals/${matches[0].id}/${cmd}`, { method: 'POST' });
266
+ log(`${a.status === 'approved' ? 'Approved' : 'Denied'}: ${usd(a.option.amountUsd)} ${a.option.asset} to ${a.host}${a.status === 'approved' ? `, valid until ${time(a.expiresAt)}` : ''}`);
267
+ break;
268
+ }
269
+
270
+ case 'log': {
271
+ const { entries } = await admin(`/v1/audit?limit=${Number(positional[0]) || 20}`);
272
+ for (const e of entries.reverse()) log(describe(e));
273
+ if (!entries.length) log('No traffic yet.');
274
+ break;
275
+ }
276
+
277
+ case 'agent': {
278
+ const [action, name] = positional;
279
+ const cf = configFile();
280
+ cf.raw.agents ??= {};
281
+ if (action === 'list') {
282
+ const names = Object.keys(config.agents ?? {});
283
+ if (!names.length) log('No agents configured: every caller is one agent, no key needed. Add one with: blocknet agent add <name>');
284
+ for (const n of names) {
285
+ const p = config.agents[n].payments ?? {};
286
+ log(`${n.padEnd(20)} budget ${p.dailyBudgetUsd != null ? usd(p.dailyBudgetUsd) : 'global'}/day per request ${p.maxPerRequestUsd != null ? usd(p.maxPerRequestUsd) : 'global'}`);
287
+ }
288
+ } else if (action === 'add') {
289
+ if (!name || !/^[\w.-]{1,40}$/.test(name)) fail('Usage: blocknet agent add <name> [--budget 1] [--max 0.05] (letters, digits, - _ .)');
290
+ if (cf.raw.agents[name]) fail(`Agent "${name}" already exists. Remove it first to make a new key.`);
291
+ const key = newAgentKey();
292
+ const payments = {};
293
+ if (flag('budget')) payments.dailyBudgetUsd = Number(flag('budget'));
294
+ if (flag('max')) payments.maxPerRequestUsd = Number(flag('max'));
295
+ if (Object.values(payments).some((v) => !Number.isFinite(v) || v < 0)) fail('--budget and --max must be dollar amounts, like 1 or 0.05');
296
+ cf.raw.agents[name] = { keySha256: keyHash(key), keyPreview: keyPreview(key), ...(Object.keys(payments).length && { payments }), createdAt: new Date().toISOString() };
297
+ cf.save(`add agent ${name}`);
298
+ log(`Added agent "${name}" to ${cf.file}.`);
299
+ log(`Its key, shown only now (Blocknet keeps just a hash of it):\n\n ${key}\n`);
300
+ log('Give it to the agent as BLOCKNET_AGENT_KEY, for example:');
301
+ log(` claude mcp add -s user blocknet -e BLOCKNET_AGENT_KEY=${key} -- node ${SELF} mcp`);
302
+ log();
303
+ log('Once any agent exists, every call needs a key. A running gateway picks this up straight away.');
304
+ } else if (action === 'remove') {
305
+ if (!cf.raw.agents[name]) fail(`No agent "${name}" in ${cf.file}.`);
306
+ delete cf.raw.agents[name];
307
+ cf.save(`remove agent ${name}`);
308
+ log(`Removed agent "${name}". A running gateway picks this up straight away.`);
309
+ } else {
310
+ fail('Usage: blocknet agent add|list|remove <name>');
311
+ }
312
+ break;
313
+ }
314
+
315
+ case 'license': {
316
+ const [action, key] = positional;
317
+ const file = join(HOME, 'license');
318
+ if (action === 'install') {
319
+ if (!key) fail('Usage: blocknet license install <key>');
320
+ try {
321
+ const claims = verifyLicense(key);
322
+ mkdirSync(HOME, { recursive: true, mode: 0o700 });
323
+ writeFileSync(file, key.trim() + '\n', { mode: 0o600 });
324
+ log(`Installed: ${PLANS[claims.plan].name} plan for ${claims.customer}, until ${claims.expiresAt.slice(0, 10)}${claims.trial ? ' (trial)' : ''}.`);
325
+ log('A running gateway picks it up straight away.');
326
+ } catch (err) {
327
+ fail(`Not installed: ${err.message}.`);
328
+ }
329
+ break;
330
+ }
331
+ if (action === 'remove') {
332
+ if (existsSync(file)) rmSync(file);
333
+ log('Removed. Blocknet runs on the Free plan; traffic rules are unchanged.');
334
+ break;
335
+ }
336
+ const ent = entitlements(findLicenseKey(config, HOME));
337
+ const yes = (b) => (b ? 'yes' : 'no');
338
+ log(`Plan: ${ent.name}${ent.license ? ` for ${ent.license.customer}` : ''}`);
339
+ if (ent.license) log(`Licence: ${ent.license.id}, until ${ent.license.expiresAt.slice(0, 10)} (from ${ent.license.from})`);
340
+ if (ent.message) log(ent.message);
341
+ log(`Console users: ${ent.seats ?? 'unlimited'} Audit export: ${yes(ent.auditExport)} Metrics: ${yes(ent.metrics)} Single sign-on: ${yes(ent.sso)}`);
342
+ const pkg = findEnterprise(config, HOME);
343
+ log(`Blocknet Enterprise package: ${pkg ? pkg.path : 'not installed'}${!pkg && ent.plan !== 'free' ? ' (needed for audit export, metrics and single sign-on; it comes with your licence)' : ''}`);
344
+ log('Network rules, payment decisions, budgets, agents and approvals are the same on every plan.');
345
+ if (ent.plan === 'free') log('Team and Enterprise licences: contact@acificlabs.com');
346
+ break;
347
+ }
348
+
349
+ case 'user': {
350
+ const [action, email] = positional;
351
+ const store = new UserStore(config.usersFile);
352
+ const find = () => store.byEmail(email) ?? fail(`No user ${email}. See: blocknet user list`);
353
+ if (action === 'list') {
354
+ const list = store.list().map(publicUser);
355
+ if (!list.length) log('No users yet. Add one with: blocknet user add you@example.com --role admin');
356
+ for (const u of list) log(`${u.email.padEnd(32)} ${u.role.padEnd(9)} ${u.sso ? 'SSO ' : ' '}${u.disabled ? 'disabled' : ''}${u.mustChangePassword ? 'must change password' : ''}`);
357
+ } else if (action === 'add') {
358
+ const role = flag('role') ?? 'viewer';
359
+ if (!ROLES.includes(role)) fail(`--role must be one of ${ROLES.join(', ')}`);
360
+ const ent = entitlements(findLicenseKey(config, HOME));
361
+ const active = store.list().filter((u) => !u.disabled).length;
362
+ if (ent.seats != null && active >= ent.seats) fail(`Your ${ent.name} plan includes ${ent.seats} console users, and all are in use. Get a licence for more: contact@acificlabs.com`);
363
+ try {
364
+ const { user, temporaryPassword } = await store.create({ email, name: flag('name'), role });
365
+ log(`Added ${user.email} as ${user.role}.`);
366
+ log(`Temporary password, shown only now: ${temporaryPassword}`);
367
+ log('They choose their own at first sign-in.');
368
+ } catch (err) {
369
+ fail(err.message);
370
+ }
371
+ } else if (action === 'reset-password') {
372
+ const u = find();
373
+ if (u.sso) fail('That user signs in with SSO.');
374
+ const { temporaryPassword } = await import('../src/users.js');
375
+ const temp = temporaryPassword();
376
+ await store.setPassword(u.id, temp, { mustChange: true });
377
+ log(`New temporary password for ${u.email}, shown only now: ${temp}`);
378
+ } else if (action === 'remove') {
379
+ const u = find();
380
+ if (u.role === 'admin' && store.activeAdmins().filter((a) => a.id !== u.id).length === 0 && store.count() > 1) fail("Can't remove the last active admin.");
381
+ store.remove(u.id);
382
+ log(`Removed ${u.email}.`);
383
+ } else {
384
+ fail('Usage: blocknet user add|list|reset-password|remove <email>');
385
+ }
386
+ break;
387
+ }
388
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "blocknet",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.1",
4
+ "description": "Security and spending control for AI agents: network rules, x402 spending limits, approvals and rules that improve safely. MCP server, fetch client or HTTP gateway.",
5
+ "keywords": [
6
+ "ai-agents",
7
+ "agent-security",
8
+ "firewall",
9
+ "mcp",
10
+ "x402",
11
+ "payments",
12
+ "spending-limits",
13
+ "egress",
14
+ "audit-log"
15
+ ],
16
+ "type": "module",
17
+ "license": "Apache-2.0",
18
+ "author": "Acific Labs LLC",
19
+ "homepage": "https://blocknet.acific.com",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/acific/blocknet.git"
23
+ },
24
+ "engines": {
25
+ "node": ">=22"
26
+ },
27
+ "bin": {
28
+ "blocknet": "bin/blocknet.js"
29
+ },
30
+ "exports": {
31
+ ".": "./src/client.js",
32
+ "./gateway": "./src/gateway.js",
33
+ "./mcp": "./src/mcp.js",
34
+ "./signing": "./src/signing.js"
35
+ },
36
+ "files": [
37
+ "bin",
38
+ "src",
39
+ "README.md",
40
+ "LICENSE",
41
+ "NOTICE"
42
+ ],
43
+ "scripts": {
44
+ "start": "node bin/blocknet.js start",
45
+ "dev": "node --watch bin/blocknet.js start",
46
+ "test": "node --import ./test/setup.mjs --test test/*.test.js",
47
+ "demo": "node examples/demo.mjs",
48
+ "check": "npm test && npm run demo && node scripts/check-links.mjs",
49
+ "site:dev": "npx wrangler dev",
50
+ "site:deploy": "npx wrangler deploy"
51
+ },
52
+ "bugs": {
53
+ "url": "https://github.com/acific/blocknet/issues"
54
+ },
55
+ "mcpName": "io.github.acific/blocknet"
56
+ }