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.
package/src/agents.js ADDED
@@ -0,0 +1,75 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+
3
+ /**
4
+ * Per-agent keys and budgets.
5
+ *
6
+ * With no `agents` in the config, every caller is the same anonymous agent: today's zero-config setup.
7
+ * Once any agent is configured, every call must carry a known agent key (fail closed), and each agent
8
+ * gets its own limits on top of the global ones. An agent's settings can only make things stricter:
9
+ * its deny rules add to the global deny list, and each money limit is the lower of the two.
10
+ */
11
+
12
+ export const newAgentKey = () => `bk_${randomBytes(24).toString('base64url')}`;
13
+
14
+ const digest = (s) => createHash('sha256').update(String(s)).digest();
15
+ /** What Blocknet stores for a key made by the console or CLI: its SHA-256, never the key. */
16
+ export const keyHash = (key) => digest(key).toString('hex');
17
+ export const keyPreview = (key) => `${String(key).slice(0, 7)}…`;
18
+
19
+ export const agentsEnabled = (config) => Object.keys(config.agents ?? {}).length > 0;
20
+
21
+ /**
22
+ * @returns {{name: string|null, config: object} | null} null when agents are configured and the key is unknown
23
+ */
24
+ export function resolveAgent(config, presentedKey) {
25
+ if (!agentsEnabled(config)) return { name: null, config };
26
+ if (!presentedKey) return null;
27
+ const want = digest(presentedKey);
28
+ for (const [name, agent] of Object.entries(config.agents)) {
29
+ if (!agent || agent.disabled) continue;
30
+ const stored = agent.keySha256 ? Buffer.from(agent.keySha256, 'hex') : agent.key ? digest(agent.key) : null;
31
+ if (stored?.length === 32 && timingSafeEqual(stored, want)) return { name, config: effectiveConfig(config, agent) };
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /** The global config narrowed by one agent's settings. Pure. */
37
+ export function effectiveConfig(config, agent = {}) {
38
+ const g = config.payments ?? {};
39
+ const a = agent.payments ?? {};
40
+ const lower = (k) => (a[k] == null ? g[k] : g[k] == null ? a[k] : Math.min(a[k], g[k]));
41
+ const within = (k) => (a[k] ? (g[k] ? a[k].filter((x) => g[k].includes(x)) : a[k]) : g[k]);
42
+ const net = config.network ?? {};
43
+ const an = agent.network ?? {};
44
+ return {
45
+ ...config,
46
+ network: {
47
+ ...net,
48
+ default: an.default === 'deny' ? 'deny' : net.default,
49
+ allow: an.allow ?? net.allow,
50
+ deny: [...(net.deny ?? []), ...(an.deny ?? [])],
51
+ },
52
+ payments: {
53
+ ...g,
54
+ maxPerRequestUsd: lower('maxPerRequestUsd'),
55
+ dailyBudgetUsd: lower('dailyBudgetUsd'),
56
+ reviewAboveUsd: lower('reviewAboveUsd'),
57
+ allowedNetworks: within('allowedNetworks'),
58
+ allowedAssets: within('allowedAssets'),
59
+ },
60
+ };
61
+ }
62
+
63
+ /** Pulls an agent key from a request: x-blocknet-key, a bearer token, or proxy basic auth (any user, key as password). */
64
+ export function keyFromHeaders(headers) {
65
+ if (headers['x-blocknet-key']) return headers['x-blocknet-key'];
66
+ const auth = headers['proxy-authorization'] ?? headers.authorization;
67
+ if (!auth) return null;
68
+ const [scheme, value = ''] = auth.split(' ');
69
+ if (/^bearer$/i.test(scheme)) return value;
70
+ if (/^basic$/i.test(scheme)) {
71
+ const decoded = Buffer.from(value, 'base64').toString();
72
+ return decoded.slice(decoded.indexOf(':') + 1) || null;
73
+ }
74
+ return null;
75
+ }
@@ -0,0 +1,73 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+
4
+ const KEEP_FINISHED_MS = 24 * 60 * 60 * 1000;
5
+
6
+ /**
7
+ * Payment approvals, kept on disk so a restart doesn't drop them.
8
+ *
9
+ * Every change is written to a JSON file (atomically: temp file, then rename).
10
+ * On load, finished approvals older than a day are dropped. A file that can't be read
11
+ * starts empty and is set aside, rather than trusted: fail closed.
12
+ */
13
+ export class ApprovalStore {
14
+ /** @param {string|null} path null keeps approvals in memory only (tests, demos) */
15
+ constructor(path) {
16
+ this.path = path;
17
+ /** @type {Map<string, object>} */
18
+ this.map = new Map();
19
+ if (path && existsSync(path)) {
20
+ try {
21
+ const cutoff = Date.now() - KEEP_FINISHED_MS;
22
+ for (const a of JSON.parse(readFileSync(path, 'utf8'))) {
23
+ const finished = a.status === 'denied' || a.usedAt || a.expiresAt < Date.now();
24
+ if (!finished || (a.usedAt ?? a.expiresAt) > cutoff) this.map.set(a.id, a);
25
+ }
26
+ } catch {
27
+ renameSync(path, `${path}.unreadable-${Date.now()}`);
28
+ this.map.clear();
29
+ }
30
+ }
31
+ }
32
+
33
+ get(id) {
34
+ return id ? this.map.get(id) : undefined;
35
+ }
36
+
37
+ /** Adds or updates an approval and saves. */
38
+ put(approval) {
39
+ this.map.set(approval.id, approval);
40
+ this.save();
41
+ return approval;
42
+ }
43
+
44
+ values() {
45
+ return this.map.values();
46
+ }
47
+
48
+ /** Newest first, optionally only one status or one agent. */
49
+ list({ status, agent } = {}) {
50
+ return [...this.map.values()]
51
+ .filter((a) => (!status || a.status === status) && (!agent || a.agent === agent))
52
+ .reverse();
53
+ }
54
+
55
+ /** Budget held by approved payments that haven't been used or expired yet. */
56
+ reservedUsd(agent) {
57
+ const now = Date.now();
58
+ let sum = 0;
59
+ for (const a of this.map.values()) {
60
+ if (agent && a.agent !== agent) continue;
61
+ if (a.status === 'approved' && !a.usedAt && a.expiresAt > now) sum += a.option.amountUsd;
62
+ }
63
+ return sum;
64
+ }
65
+
66
+ save() {
67
+ if (!this.path) return;
68
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
69
+ const tmp = `${this.path}.tmp`;
70
+ writeFileSync(tmp, JSON.stringify([...this.map.values()], null, 1), { mode: 0o600 });
71
+ renameSync(tmp, this.path);
72
+ }
73
+ }
package/src/client.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * A drop-in fetch() for agents that routes every call through Blocknet.
3
+ *
4
+ * import { createBlocknetFetch } from 'blocknet';
5
+ * const fetch = createBlocknetFetch({ signPayment }); // signPayment is optional
6
+ * const res = await fetch('https://api.example.com/data');
7
+ *
8
+ * - Allowed calls return the service's own Response.
9
+ * - Blocked calls and refused payments throw a BlocknetError with Blocknet's reasons.
10
+ * - Payments that need a person wait (polling) until approved or denied.
11
+ * - Approved payments are signed by YOUR signPayment(option, paymentRequired),
12
+ * which returns the PAYMENT-SIGNATURE value. Blocknet never sees the key.
13
+ * Without signPayment, a paid service throws a BlocknetError with code "payment_required".
14
+ * - With per-agent keys configured, pass agentKey (or set BLOCKNET_AGENT_KEY).
15
+ * - With approval signing on, signPayment can check the approval first: verifyApproval() from 'blocknet/signing'.
16
+ */
17
+ export { verifyApproval } from './signing.js';
18
+
19
+ export class BlocknetError extends Error {
20
+ /**
21
+ * @param {string} message
22
+ * @param {{code: 'blocked'|'denied'|'payment_required'|'timeout'|'unauthorized', reasons?: string[], decision?: object}} info
23
+ */
24
+ constructor(message, info) {
25
+ super(message);
26
+ this.name = 'BlocknetError';
27
+ Object.assign(this, info);
28
+ }
29
+ }
30
+
31
+ export function createBlocknetFetch({
32
+ gateway = process.env.BLOCKNET_URL ?? 'http://127.0.0.1:8402',
33
+ signPayment,
34
+ approvalTimeoutMs = 5 * 60_000,
35
+ pollMs = 3000,
36
+ agentKey = process.env.BLOCKNET_AGENT_KEY,
37
+ fetchImpl = fetch,
38
+ } = {}) {
39
+ gateway = gateway.replace(/\/$/, '');
40
+ const auth = agentKey ? { 'x-blocknet-key': agentKey } : {};
41
+
42
+ const send = (url, init, extra = {}) =>
43
+ fetchImpl(`${gateway}/v1/fetch`, {
44
+ method: 'POST',
45
+ headers: { 'content-type': 'application/json', ...auth },
46
+ body: JSON.stringify({
47
+ url: String(url),
48
+ method: init.method ?? 'GET',
49
+ headers: { ...headersToObject(init.headers), ...extra.headers },
50
+ body: init.body,
51
+ approval: extra.approval,
52
+ }),
53
+ });
54
+
55
+ return async function blocknetFetch(url, init = {}) {
56
+ const res = await send(url, init);
57
+
58
+ if (res.status === 401) {
59
+ const body = await res.clone().json().catch(() => ({}));
60
+ throw new BlocknetError(`Blocknet refused the call: ${body.error ?? 'agent key required'}`, { code: 'unauthorized', reasons: [body.error] });
61
+ }
62
+ if (res.status === 403) {
63
+ const body = await res.clone().json().catch(() => null);
64
+ if (body?.blocked) {
65
+ throw new BlocknetError(`Blocked by Blocknet: ${body.reasons.join('; ')}`, { code: 'blocked', reasons: body.reasons });
66
+ }
67
+ return res;
68
+ }
69
+ if (res.status !== 402) return res;
70
+
71
+ const body = await res.clone().json().catch(() => null);
72
+ const decision = body?.blocknet;
73
+ if (!decision) return res; // a 402 Blocknet couldn't read: hand it back as the service's own answer
74
+
75
+ let status = decision.approvalStatus;
76
+ const deadline = Date.now() + approvalTimeoutMs;
77
+ while (status === 'pending') {
78
+ if (Date.now() > deadline) {
79
+ throw new BlocknetError('Timed out waiting for a person to approve the payment', { code: 'timeout', decision });
80
+ }
81
+ await new Promise((r) => setTimeout(r, pollMs));
82
+ const check = await fetchImpl(`${gateway}/v1/approvals/${decision.approval}`, { headers: auth });
83
+ status = (await check.json()).status;
84
+ }
85
+
86
+ if (status !== 'approved') {
87
+ throw new BlocknetError(`Payment refused by Blocknet: ${decision.reasons.join('; ')}`, {
88
+ code: 'denied',
89
+ reasons: decision.reasons,
90
+ decision,
91
+ });
92
+ }
93
+ if (!signPayment) {
94
+ throw new BlocknetError(
95
+ `Payment of $${decision.option.amountUsd} ${decision.option.asset} approved, but no signPayment was given`,
96
+ { code: 'payment_required', reasons: decision.reasons, decision },
97
+ );
98
+ }
99
+
100
+ let approved = decision;
101
+ if (!decision.signature && decision.approvalStatus === 'pending') {
102
+ // approved by a person after the fact: fetch the signed record
103
+ approved = await (await fetchImpl(`${gateway}/v1/approvals/${decision.approval}`, { headers: auth })).json();
104
+ }
105
+ const signature = await signPayment(decision.option, body.paymentRequired, { approval: approved });
106
+ return send(url, init, { approval: decision.approval, headers: { 'PAYMENT-SIGNATURE': signature } });
107
+ };
108
+ }
109
+
110
+ function headersToObject(h) {
111
+ if (!h) return {};
112
+ if (typeof h.entries === 'function') return Object.fromEntries(h.entries());
113
+ if (Array.isArray(h)) return Object.fromEntries(h);
114
+ return { ...h };
115
+ }
package/src/config.js ADDED
@@ -0,0 +1,89 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
6
+
7
+ /** Where Blocknet keeps its config, audit log and admin token unless told otherwise. */
8
+ export const HOME = process.env.BLOCKNET_HOME ?? join(homedir(), '.blocknet');
9
+
10
+ export const DEFAULT_CONFIG = {
11
+ host: process.env.BLOCKNET_HOST ?? '127.0.0.1',
12
+ port: Number(process.env.BLOCKNET_PORT ?? 8402),
13
+ network: {
14
+ default: 'allow',
15
+ allow: [],
16
+ // Cloud metadata endpoints hand out credentials; no agent needs them.
17
+ deny: ['169.254.169.254', 'metadata.google.internal', 'metadata.azure.com'],
18
+ // Checked against what a host name resolves to, so a name pointing at these is caught too.
19
+ blockAddresses: ['169.254.0.0/16', 'fe80::/10', 'fd00:ec2::254/128'],
20
+ // Also block private, loopback and carrier-grade NAT ranges (10/8, 192.168/16, 127/8, …).
21
+ blockPrivateNetworks: false,
22
+ },
23
+ payments: {
24
+ maxPerRequestUsd: 0.1,
25
+ dailyBudgetUsd: 5,
26
+ reviewAboveUsd: 0.01,
27
+ allowedNetworks: ['base', 'base-sepolia', 'eip155:8453', 'eip155:84532'],
28
+ allowedAssets: ['USDC'],
29
+ approvalTtlSeconds: 300,
30
+ },
31
+ trust: {
32
+ minScore: 0.6,
33
+ unknown: 'review',
34
+ belowMin: 'deny',
35
+ scores: {},
36
+ },
37
+ // Per-agent keys and budgets. Empty: one anonymous agent, no keys needed.
38
+ agents: {},
39
+ // POST pending approvals to a webhook (Slack, Discord, or your own).
40
+ notify: { webhookUrl: null },
41
+ // Accept HTTP_PROXY / HTTPS_PROXY traffic. Network rules only: payments must use /v1/fetch.
42
+ proxy: { enabled: false },
43
+ // The policy advisor (Team, Enterprise). autoTighten: apply proposals that only make the policy stricter,
44
+ // at most maxPerDay a day; each is watched for watchHours and undone if it blocks more than maxNewBlocks decisions.
45
+ advisor: { autoTighten: false, maxPerDay: 3, watchHours: 24, maxNewBlocks: 10 },
46
+ // The admin console. port: serve it on its own port (recommended when agents can reach the gateway).
47
+ admin: {
48
+ port: null,
49
+ host: null,
50
+ publicUrl: null, // e.g. https://blocknet.example.com, for SSO redirects and Secure cookies
51
+ sessionIdleHours: 12,
52
+ sessionMaxDays: 7,
53
+ trustProxy: false, // read the client address from X-Forwarded-For (only behind your own proxy)
54
+ oidc: null, // single sign-on, with Blocknet Enterprise: { issuer, clientId, clientSecret, roleClaim, roleMap, defaultRole, allowedDomains, label }
55
+ },
56
+ // Where the Blocknet Enterprise package is, if not in ~/.blocknet/enterprise (Team and Enterprise customers).
57
+ enterprise: null,
58
+ auditLog: join(HOME, 'audit.jsonl'),
59
+ approvalsFile: join(HOME, 'approvals.json'),
60
+ usersFile: join(HOME, 'users.json'),
61
+ sessionsFile: join(HOME, 'sessions.json'),
62
+ // Every earlier version of the policy, so any change can be undone.
63
+ policyHistoryFile: join(HOME, 'policy-history.jsonl'),
64
+ };
65
+
66
+ /**
67
+ * Config file, first found: the given path, $BLOCKNET_CONFIG, ./blocknet.config.json, ~/.blocknet/config.json.
68
+ * None is needed: the defaults are safe.
69
+ * A relative auditLog or approvalsFile in a file is read from that file's folder, not from wherever the agent started,
70
+ * so one config always means one log and one budget. `configFile` says which file was used (null: defaults).
71
+ */
72
+ export function loadConfig(path, overrides = {}) {
73
+ const candidates = path ? [path] : [process.env.BLOCKNET_CONFIG, 'blocknet.config.json', join(HOME, 'config.json')].filter(Boolean);
74
+ const full = resolve(candidates.find((c) => existsSync(resolve(c))) ?? candidates[0]);
75
+ const found = existsSync(full);
76
+ const fromFile = found ? JSON.parse(readFileSync(full, 'utf8')) : {};
77
+ for (const key of ['auditLog', 'approvalsFile', 'usersFile', 'sessionsFile', 'enterprise', 'policyHistoryFile']) {
78
+ if (typeof fromFile[key] === 'string' && !isAbsolute(fromFile[key])) fromFile[key] = resolve(dirname(full), fromFile[key]);
79
+ }
80
+ return { ...merge(merge(DEFAULT_CONFIG, fromFile), overrides), configFile: found ? full : null };
81
+ }
82
+
83
+ function merge(base, extra) {
84
+ const out = { ...base };
85
+ for (const [k, v] of Object.entries(extra ?? {})) {
86
+ out[k] = v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object' ? merge(base[k], v) : v;
87
+ }
88
+ return out;
89
+ }