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,292 @@
1
+ /**
2
+ * Live settings: validate, save and apply policy and agent changes without a restart.
3
+ *
4
+ * Changes are written to the config file Blocknet loaded (or ~/.blocknet/config.json), atomically and
5
+ * readable only by you, then applied to the running config. Edits made to the file by hand or by the CLI
6
+ * are picked up on the next request (the file's modification time is checked).
7
+ */
8
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { HOME, loadConfig } from './config.js';
11
+ import { ipInCidr } from './hosts.js';
12
+ import { problem } from './users.js';
13
+
14
+ export const POLICY_SECTIONS = ['network', 'payments', 'trust', 'notify', 'proxy', 'advisor'];
15
+ const LIVE = [...POLICY_SECTIONS, 'agents'];
16
+ const DECISIONS = ['allow', 'review', 'deny'];
17
+
18
+ const mtimeOf = (f) => (f && existsSync(f) ? statSync(f).mtimeMs : 0);
19
+
20
+ export class Settings {
21
+ constructor(config) {
22
+ this.config = config;
23
+ this.file = config.configFile ?? join(HOME, 'config.json');
24
+ this.historyFile = config.policyHistoryFile === undefined ? join(HOME, 'policy-history.jsonl') : config.policyHistoryFile;
25
+ this.mtime = mtimeOf(this.file);
26
+ this.memoryHistory = [];
27
+ }
28
+
29
+ // ---- versions: every change keeps the policy it replaced, so it can be undone ----
30
+
31
+ /** Earlier versions, newest first: { version, ts, actor, reason, policy, agentLimits }. */
32
+ history() {
33
+ if (!this.historyFile) return [...this.memoryHistory].reverse();
34
+ if (!existsSync(this.historyFile)) return [];
35
+ const out = [];
36
+ for (const line of readFileSync(this.historyFile, 'utf8').split('\n')) {
37
+ if (!line.trim()) continue;
38
+ try {
39
+ out.push(JSON.parse(line));
40
+ } catch {}
41
+ }
42
+ return out.reverse();
43
+ }
44
+
45
+ #snapshot(meta = {}) {
46
+ const last = this.history()[0];
47
+ const entry = {
48
+ version: (last?.version ?? 0) + 1,
49
+ ts: new Date().toISOString(),
50
+ actor: meta.actor ?? null,
51
+ reason: meta.reason ?? null,
52
+ policy: this.policy(),
53
+ agentLimits: Object.fromEntries(Object.entries(this.agents()).map(([n, a]) => [n, { payments: a.payments ?? null, network: a.network ?? null }])),
54
+ };
55
+ if (!this.historyFile) this.memoryHistory.push(entry);
56
+ else {
57
+ mkdirSync(dirname(this.historyFile), { recursive: true, mode: 0o700 });
58
+ appendFileSync(this.historyFile, JSON.stringify(entry) + '\n', { mode: 0o600 });
59
+ }
60
+ return entry;
61
+ }
62
+
63
+ /**
64
+ * Puts back the policy as it was before version `version` was replaced, and each agent's limits.
65
+ * Agent keys, and whether an agent exists or is disabled, are never rolled back: a rotated key stays
66
+ * rotated and a removed agent stays removed (fail closed).
67
+ */
68
+ rollback(version, meta = {}) {
69
+ const v = this.history().find((h) => h.version === Number(version));
70
+ if (!v) throw problem(404, `no policy version ${version}`);
71
+ const policy = Object.fromEntries(POLICY_SECTIONS.map((s) => [s, VALIDATE[s]({ ...this.policy()[s], ...v.policy[s] })]));
72
+ this.write(
73
+ (raw) => {
74
+ Object.assign(raw, policy);
75
+ for (const [name, limits] of Object.entries(v.agentLimits ?? {})) {
76
+ const a = raw.agents?.[name];
77
+ if (!a) continue;
78
+ if (limits.payments) a.payments = limits.payments;
79
+ else delete a.payments;
80
+ if (limits.network) a.network = limits.network;
81
+ else delete a.network;
82
+ }
83
+ },
84
+ { actor: meta.actor, reason: meta.reason ?? `roll back to version ${v.version}` },
85
+ );
86
+ return v;
87
+ }
88
+
89
+ /** Checks a policy change without saving it: the full candidate sections, validated. */
90
+ preview(input) {
91
+ const current = this.policy();
92
+ const out = {};
93
+ for (const [section, value] of Object.entries(input ?? {})) {
94
+ if (!POLICY_SECTIONS.includes(section)) throw problem(400, `unknown section ${section}`, section);
95
+ if (!value || typeof value !== 'object') throw problem(400, `${section} must be an object`, section);
96
+ out[section] = VALIDATE[section]({ ...current[section], ...value });
97
+ }
98
+ return out;
99
+ }
100
+
101
+ /** Re-reads the file if it changed on disk. Cheap: one stat. */
102
+ refresh() {
103
+ const m = mtimeOf(this.file);
104
+ if (m === this.mtime) return;
105
+ this.mtime = m;
106
+ try {
107
+ const fresh = loadConfig(this.file);
108
+ for (const k of LIVE) this.config[k] = fresh[k];
109
+ } catch {
110
+ // a half-written or broken file: keep the last good settings
111
+ }
112
+ }
113
+
114
+ raw() {
115
+ return existsSync(this.file) ? JSON.parse(readFileSync(this.file, 'utf8')) : {};
116
+ }
117
+
118
+ /** Applies `mutate(raw)` to the file's JSON, saves it, and reloads the live config. */
119
+ write(mutate, meta) {
120
+ this.#snapshot(meta);
121
+ const raw = this.raw();
122
+ mutate(raw);
123
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
124
+ const tmp = `${this.file}.tmp`;
125
+ writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', { mode: 0o600 });
126
+ renameSync(tmp, this.file);
127
+ this.config.configFile = this.file;
128
+ this.mtime = -1; // force reload
129
+ this.refresh();
130
+ }
131
+
132
+ policy() {
133
+ const c = this.config;
134
+ return {
135
+ network: pick(c.network, ['default', 'allow', 'deny', 'blockAddresses', 'blockPrivateNetworks']),
136
+ payments: pick(c.payments, ['maxPerRequestUsd', 'dailyBudgetUsd', 'reviewAboveUsd', 'allowedNetworks', 'allowedAssets', 'approvalTtlSeconds']),
137
+ trust: pick(c.trust, ['minScore', 'unknown', 'belowMin', 'scores']),
138
+ notify: { webhookUrl: c.notify?.webhookUrl ?? null },
139
+ proxy: { enabled: Boolean(c.proxy?.enabled) },
140
+ advisor: {
141
+ autoTighten: Boolean(c.advisor?.autoTighten),
142
+ maxPerDay: c.advisor?.maxPerDay ?? 3,
143
+ watchHours: c.advisor?.watchHours ?? 24,
144
+ maxNewBlocks: c.advisor?.maxNewBlocks ?? 10,
145
+ },
146
+ };
147
+ }
148
+
149
+ /** Validates the sections given (fields merge over the current values) and saves them. */
150
+ updatePolicy(input, meta) {
151
+ const next = this.preview(input);
152
+ this.write((raw) => Object.assign(raw, next), meta);
153
+ return this.policy();
154
+ }
155
+
156
+ agents() {
157
+ return this.config.agents ?? {};
158
+ }
159
+
160
+ /** Saves one agent's settings (validated); `fields` merge over what's there. */
161
+ putAgent(name, fields, { create = false, meta } = {}) {
162
+ if (!/^[\w.-]{1,40}$/.test(name ?? '')) throw problem(400, 'agent name: 1 to 40 letters, digits, - _ or .', 'name');
163
+ const existing = this.agents()[name];
164
+ if (create && existing) throw problem(409, `agent ${name} already exists`, 'name');
165
+ if (!create && !existing) throw problem(404, `unknown agent ${name}`);
166
+ const agent = validateAgent({ ...(existing ?? {}), ...fields });
167
+ this.write((raw) => {
168
+ raw.agents ??= {};
169
+ raw.agents[name] = agent;
170
+ }, meta);
171
+ return agent;
172
+ }
173
+
174
+ removeAgent(name, meta) {
175
+ if (!this.agents()[name]) throw problem(404, `unknown agent ${name}`);
176
+ this.write((raw) => {
177
+ delete raw.agents?.[name];
178
+ }, meta);
179
+ }
180
+ }
181
+
182
+ const pick = (o = {}, keys) => Object.fromEntries(keys.map((k) => [k, o[k] ?? null]));
183
+
184
+ // ---- validation: every field checked, errors name the field ----
185
+
186
+ const num = (v, field, { min = 0, max = Infinity, int = false } = {}) => {
187
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max || (int && !Number.isInteger(v))) {
188
+ throw problem(400, `${field} must be ${int ? 'a whole number' : 'a number'} ${max === Infinity ? `≥ ${min}` : `from ${min} to ${max}`}`, field);
189
+ }
190
+ return v;
191
+ };
192
+ const oneOf = (v, field, options) => {
193
+ if (!options.includes(v)) throw problem(400, `${field} must be one of ${options.join(', ')}`, field);
194
+ return v;
195
+ };
196
+ const bool = (v, field) => {
197
+ if (typeof v !== 'boolean') throw problem(400, `${field} must be true or false`, field);
198
+ return v;
199
+ };
200
+ const list = (v, field, check = () => true, what = 'entry') => {
201
+ if (!Array.isArray(v)) throw problem(400, `${field} must be a list`, field);
202
+ const out = [...new Set(v.map((x) => String(x).trim()).filter(Boolean))];
203
+ if (out.length > 1000) throw problem(400, `${field} has too many entries`, field);
204
+ const bad = out.find((x) => !check(x));
205
+ if (bad !== undefined) throw problem(400, `${field}: "${bad}" is not a valid ${what}`, field);
206
+ return out;
207
+ };
208
+ const HOST = /^(\*|(\*\.)?[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)*|\[?[0-9a-f:.]+\]?)$/i;
209
+ const isHost = (h) => h.length <= 253 && HOST.test(h);
210
+ const isCidr = (c) => {
211
+ const [base, bits] = c.split('/');
212
+ return bits !== undefined && /^\d+$/.test(bits) && ipInCidr(base, c);
213
+ };
214
+ const isToken = (s) => /^[\w:.-]{1,64}$/.test(s);
215
+
216
+ const VALIDATE = {
217
+ network: (n) => ({
218
+ default: oneOf(n.default, 'network.default', ['allow', 'deny']),
219
+ allow: list(n.allow ?? [], 'network.allow', isHost, 'host pattern'),
220
+ deny: list(n.deny ?? [], 'network.deny', isHost, 'host pattern'),
221
+ blockAddresses: list(n.blockAddresses ?? [], 'network.blockAddresses', isCidr, 'address range (like 10.0.0.0/8)'),
222
+ blockPrivateNetworks: bool(n.blockPrivateNetworks ?? false, 'network.blockPrivateNetworks'),
223
+ }),
224
+ payments: (p) => ({
225
+ maxPerRequestUsd: num(p.maxPerRequestUsd, 'payments.maxPerRequestUsd'),
226
+ dailyBudgetUsd: num(p.dailyBudgetUsd, 'payments.dailyBudgetUsd'),
227
+ reviewAboveUsd: num(p.reviewAboveUsd, 'payments.reviewAboveUsd'),
228
+ allowedNetworks: list(p.allowedNetworks ?? [], 'payments.allowedNetworks', isToken, 'network name'),
229
+ allowedAssets: list(p.allowedAssets ?? [], 'payments.allowedAssets', isToken, 'currency'),
230
+ approvalTtlSeconds: num(p.approvalTtlSeconds, 'payments.approvalTtlSeconds', { min: 10, max: 86400, int: true }),
231
+ }),
232
+ trust: (t) => {
233
+ if (!t.scores || typeof t.scores !== 'object' || Array.isArray(t.scores)) throw problem(400, 'trust.scores must be an object of host: score', 'trust.scores');
234
+ const scores = {};
235
+ for (const [host, s] of Object.entries(t.scores)) {
236
+ if (!isHost(host)) throw problem(400, `trust.scores: "${host}" is not a valid host pattern`, 'trust.scores');
237
+ scores[host] = num(s, `trust.scores["${host}"]`, { min: 0, max: 1 });
238
+ }
239
+ return {
240
+ minScore: num(t.minScore, 'trust.minScore', { min: 0, max: 1 }),
241
+ unknown: oneOf(t.unknown, 'trust.unknown', DECISIONS),
242
+ belowMin: oneOf(t.belowMin, 'trust.belowMin', DECISIONS),
243
+ scores,
244
+ };
245
+ },
246
+ notify: (n) => {
247
+ const url = n.webhookUrl === '' ? null : n.webhookUrl;
248
+ if (url != null) {
249
+ let u;
250
+ try {
251
+ u = new URL(url);
252
+ } catch {}
253
+ if (!u || !['http:', 'https:'].includes(u.protocol)) throw problem(400, 'notify.webhookUrl must be an http(s) URL', 'notify.webhookUrl');
254
+ }
255
+ return { webhookUrl: url ?? null };
256
+ },
257
+ proxy: (p) => ({ enabled: bool(p.enabled ?? false, 'proxy.enabled') }),
258
+ advisor: (a) => ({
259
+ autoTighten: bool(a.autoTighten ?? false, 'advisor.autoTighten'),
260
+ maxPerDay: num(a.maxPerDay ?? 3, 'advisor.maxPerDay', { min: 1, max: 20, int: true }),
261
+ watchHours: num(a.watchHours ?? 24, 'advisor.watchHours', { min: 1, max: 168, int: true }),
262
+ maxNewBlocks: num(a.maxNewBlocks ?? 10, 'advisor.maxNewBlocks', { min: 0, max: 10000, int: true }),
263
+ }),
264
+ };
265
+
266
+ function validateAgent(a) {
267
+ const out = {};
268
+ if (a.keySha256 != null) {
269
+ if (!/^[0-9a-f]{64}$/.test(a.keySha256)) throw problem(400, 'keySha256 must be 64 hex characters', 'keySha256');
270
+ out.keySha256 = a.keySha256;
271
+ } else if (a.key) out.key = String(a.key);
272
+ else throw problem(400, 'agent needs a key', 'key');
273
+ if (a.payments) {
274
+ const p = {};
275
+ for (const k of ['maxPerRequestUsd', 'dailyBudgetUsd', 'reviewAboveUsd']) {
276
+ if (a.payments[k] != null && a.payments[k] !== '') p[k] = num(a.payments[k], `payments.${k}`);
277
+ }
278
+ for (const k of ['allowedNetworks', 'allowedAssets']) if (a.payments[k]) p[k] = list(a.payments[k], `payments.${k}`, isToken);
279
+ if (Object.keys(p).length) out.payments = p;
280
+ }
281
+ if (a.network) {
282
+ const n = {};
283
+ if (a.network.deny?.length) n.deny = list(a.network.deny, 'network.deny', isHost, 'host pattern');
284
+ if (a.network.allow) n.allow = list(a.network.allow, 'network.allow', isHost, 'host pattern');
285
+ if (a.network.default === 'deny') n.default = 'deny';
286
+ if (Object.keys(n).length) out.network = n;
287
+ }
288
+ if (a.disabled) out.disabled = bool(a.disabled, 'disabled');
289
+ out.createdAt = a.createdAt ?? new Date().toISOString();
290
+ if (a.keyPreview) out.keyPreview = a.keyPreview;
291
+ return out;
292
+ }
package/src/signing.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Signed approvals: Blocknet signs its *decision*, never a payment.
3
+ *
4
+ * When a payment is approved, Blocknet signs the exact terms it approved (who gets paid, how much,
5
+ * on which network, until when) with its own Ed25519 key. A wallet that holds the agent's key can
6
+ * check that signature with Blocknet's public key before it signs the payment, so an agent can't
7
+ * forge or stretch an approval. Blocknet still never holds a wallet key or moves money.
8
+ */
9
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto';
10
+
11
+ /** The fields that are signed, in a fixed order. */
12
+ export function approvalTerms(a) {
13
+ return {
14
+ v: 1,
15
+ id: a.id,
16
+ agent: a.agent ?? null,
17
+ host: a.host,
18
+ network: a.option.network,
19
+ asset: a.option.asset,
20
+ payTo: a.option.payTo ?? null,
21
+ amountAtomic: a.option.amountAtomic ?? null,
22
+ expiresAt: a.expiresAt,
23
+ };
24
+ }
25
+
26
+ const bytes = (terms) => Buffer.from(JSON.stringify(terms));
27
+
28
+ export function generateSigningKey() {
29
+ return generateKeyPairSync('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' });
30
+ }
31
+
32
+ export function publicKeyOf(privateKeyPem) {
33
+ return createPublicKey(createPrivateKey(privateKeyPem)).export({ type: 'spki', format: 'pem' });
34
+ }
35
+
36
+ /** Returns the base64 signature over the approval's terms. */
37
+ export function signApproval(approval, privateKeyPem) {
38
+ return sign(null, bytes(approvalTerms(approval)), createPrivateKey(privateKeyPem)).toString('base64');
39
+ }
40
+
41
+ /**
42
+ * For wallets: true only if `approval.signature` is Blocknet's signature over these exact terms
43
+ * and the approval hasn't expired.
44
+ *
45
+ * import { verifyApproval } from 'blocknet/signing';
46
+ * if (!verifyApproval(approval, BLOCKNET_PUBLIC_KEY)) throw new Error('not approved by Blocknet');
47
+ */
48
+ export function verifyApproval(approval, publicKeyPem, now = Date.now()) {
49
+ if (!approval?.signature || !approval.option || approval.expiresAt < now) return false;
50
+ try {
51
+ return verify(null, bytes(approvalTerms(approval)), createPublicKey(publicKeyPem), Buffer.from(approval.signature, 'base64'));
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Policy simulation: replays the audit log against a candidate policy and reports what would have
3
+ * been decided differently. Pure: no I/O, no clock. Used before any policy change is saved, by people
4
+ * in the console and by Blocknet Enterprise's policy advisor, so a change is tested on real traffic
5
+ * before it touches real traffic.
6
+ *
7
+ * Both the current and the candidate policy are re-evaluated on the same history, so the report shows
8
+ * only the effect of the change. What can't be replayed is listed in `limits`.
9
+ */
10
+ import { evaluateNetwork, evaluatePayment, round } from './policy.js';
11
+ import { effectiveConfig } from './agents.js';
12
+ import { matchAny } from './hosts.js';
13
+
14
+ const RANK = { allow: 0, review: 1, deny: 2 };
15
+ const ADDRESS_BLOCK = /resolves to .* in blocked range|in blocked range/;
16
+ const MAX_CHANGES = 200;
17
+
18
+ /**
19
+ * @param {object[]} entries audit log entries, oldest first
20
+ * @param {{current: object, candidate: object, since?: string}} opts
21
+ * current, candidate: config-like objects with network, payments, trust and agents
22
+ * since: ISO time; earlier entries only build up history (spend, outcomes)
23
+ */
24
+ export function simulate(entries, { current, candidate, since = '' }) {
25
+ const approvals = new Map(); // payment id -> what a person decided
26
+ for (const e of entries) if (e.type === 'approval' && e.actor) approvals.set(e.id, e.status);
27
+
28
+ const spend = new Map(); // `${day}|${agent ?? ''}` -> settled USD
29
+ const outcomes = new Map(); // host -> {s, f}
30
+ const report = {
31
+ since: since || entries[0]?.ts || null,
32
+ until: entries.at(-1)?.ts ?? null,
33
+ considered: { requests: 0, payments: 0 },
34
+ network: { blockedBefore: 0, blockedAfter: 0 },
35
+ payments: { before: { allow: 0, review: 0, deny: 0 }, after: { allow: 0, review: 0, deny: 0 } },
36
+ loosens: 0,
37
+ tightens: 0,
38
+ humanDeniedNowAllowed: 0,
39
+ humanApprovedNowDenied: 0,
40
+ changes: [],
41
+ limits: [
42
+ 'Spend is replayed as it happened: if a payment would have been refused, later spend that day is still counted.',
43
+ 'Address checks (what a name resolved to) are kept as they were; DNS is not looked up again.',
44
+ 'Payments still waiting for approval are not counted against the budget.',
45
+ ],
46
+ };
47
+
48
+ const cfgFor = (cfg, agent) => (agent && cfg.agents?.[agent] ? effectiveConfig(cfg, cfg.agents[agent]) : cfg);
49
+ const change = (e, kind, before, after, why) => {
50
+ if (RANK[after] < RANK[before]) report.loosens++;
51
+ else report.tightens++;
52
+ if (report.changes.length < MAX_CHANGES) report.changes.push({ ts: e.ts, kind, host: e.host, ...(e.agent && { agent: e.agent }), ...(e.amountUsd != null && { amountUsd: e.amountUsd }), before, after, reasons: why });
53
+ };
54
+
55
+ for (const e of entries) {
56
+ const inWindow = e.ts >= report.since;
57
+ if (inWindow && (e.type === 'request' || e.type === 'blocked' || e.type === 'tunnel') && e.host) {
58
+ report.considered.requests++;
59
+ const addressBlocked = e.type === 'blocked' && (e.reasons ?? []).some((r) => ADDRESS_BLOCK.test(r));
60
+ const before = addressBlocked ? 'deny' : evaluateNetwork(e.host, cfgFor(current, e.agent).network).decision;
61
+ const afterNet = evaluateNetwork(e.host, cfgFor(candidate, e.agent).network);
62
+ const after = addressBlocked ? 'deny' : afterNet.decision;
63
+ if (before !== 'allow') report.network.blockedBefore++;
64
+ if (after !== 'allow') report.network.blockedAfter++;
65
+ if ((before === 'allow') !== (after === 'allow')) change(e, 'network', before === 'allow' ? 'allow' : 'deny', after === 'allow' ? 'allow' : 'deny', afterNet.reasons);
66
+ }
67
+
68
+ if (inWindow && e.type === 'payment_decision' && e.host && e.amountUsd != null) {
69
+ report.considered.payments++;
70
+ const before = decidePayment(e, cfgFor(current, e.agent), current, spend, outcomes);
71
+ const after = decidePayment(e, cfgFor(candidate, e.agent), candidate, spend, outcomes);
72
+ report.payments.before[before.decision]++;
73
+ report.payments.after[after.decision]++;
74
+ if (before.decision !== after.decision) {
75
+ change(e, 'payment', before.decision, after.decision, after.reasons);
76
+ const human = approvals.get(e.id);
77
+ if (human === 'denied' && after.decision === 'allow') report.humanDeniedNowAllowed++;
78
+ if (human === 'approved' && after.decision === 'deny') report.humanApprovedNowDenied++;
79
+ }
80
+ }
81
+
82
+ // history builds up from every entry, in or out of the window
83
+ if (e.type === 'payment' && e.host) {
84
+ const o = outcomes.get(e.host) ?? { s: 0, f: 0 };
85
+ if (e.settled) o.s++;
86
+ else o.f++;
87
+ outcomes.set(e.host, o);
88
+ if (e.settled && e.amountUsd) {
89
+ const day = e.ts.slice(0, 10);
90
+ for (const k of [`${day}|`, ...(e.agent ? [`${day}|${e.agent}`] : [])]) spend.set(k, (spend.get(k) ?? 0) + e.amountUsd);
91
+ }
92
+ }
93
+ }
94
+ return report;
95
+ }
96
+
97
+ function decidePayment(e, cfg, whole, spend, outcomes) {
98
+ const net = evaluateNetwork(e.host, cfg.network);
99
+ if (net.decision !== 'allow') return { decision: 'deny', reasons: net.reasons };
100
+ const day = e.ts.slice(0, 10);
101
+ const own = spend.get(`${day}|${e.agent ?? ''}`) ?? 0;
102
+ const team = spend.get(`${day}|`) ?? 0;
103
+ const pay = cfg.payments ?? {};
104
+ const acceptable =
105
+ e.network || e.asset
106
+ ? (!e.network || !pay.allowedNetworks?.length || pay.allowedNetworks.includes(e.network)) && (!e.asset || !pay.allowedAssets?.length || pay.allowedAssets.includes(e.asset))
107
+ : !(e.reasons ?? []).some((r) => /network\/asset .* not allowed/.test(r));
108
+ return evaluatePayment({
109
+ option: { amountUsd: e.amountUsd, network: e.network, asset: e.asset },
110
+ acceptable,
111
+ trust: trustAt(e.host, cfg.trust, outcomes),
112
+ spentTodayUsd: e.agent ? own : team,
113
+ teamRemainingUsd: e.agent ? round((whole.payments?.dailyBudgetUsd ?? Infinity) - team) : undefined,
114
+ config: cfg,
115
+ });
116
+ }
117
+
118
+ /** The same blend as trust.js, from the outcomes seen so far in the replay. */
119
+ export function trustAt(host, trust = {}, outcomes) {
120
+ const scores = trust.scores ?? {};
121
+ const key = matchAny(host, Object.keys(scores));
122
+ const configured = key ? scores[key] : null;
123
+ const { s = 0, f = 0 } = outcomes.get(host) ?? {};
124
+ const n = s + f;
125
+ if (configured == null && n < 3) return { score: null, source: 'no record' };
126
+ if (n === 0) return { score: configured, source: 'configured' };
127
+ const w = n / (n + 5);
128
+ return { score: Math.round(((configured ?? 0.5) * (1 - w) + (s / n) * w) * 100) / 100, source: 'replay' };
129
+ }
130
+
131
+ /** A candidate config: the current one with policy sections and agent limits replaced. */
132
+ export function withChanges(config, { policy = {}, agents = {} } = {}) {
133
+ const next = { ...config };
134
+ for (const [section, value] of Object.entries(policy)) next[section] = { ...config[section], ...value };
135
+ if (Object.keys(agents).length) {
136
+ next.agents = { ...config.agents };
137
+ for (const [name, fields] of Object.entries(agents)) if (next.agents[name]) next.agents[name] = { ...next.agents[name], ...fields };
138
+ }
139
+ return next;
140
+ }
package/src/trust.js ADDED
@@ -0,0 +1,37 @@
1
+ import { matchAny } from './hosts.js';
2
+
3
+ /**
4
+ * Trust answers "how much should an agent trust this paid service?"
5
+ * with a score in [0, 1], or null when nothing is known.
6
+ *
7
+ * The score starts from what the operator configured (trust.scores) and is
8
+ * blended with this gateway's own record of what each service returned after
9
+ * being paid. Blocknet's data stays with the deployment that recorded it.
10
+ */
11
+ export class Trust {
12
+ constructor(config, ledger) {
13
+ this.scores = config.trust?.scores ?? {};
14
+ this.ledger = ledger;
15
+ }
16
+
17
+ async score(host) {
18
+ const key = matchAny(host, Object.keys(this.scores));
19
+ const configured = key ? this.scores[key] : null;
20
+ const { successes, failures } = this.ledger.history(host);
21
+ const n = successes + failures;
22
+ if (configured == null && n < 3) return { score: null, source: 'no record' };
23
+ if (n === 0) return { score: configured, source: 'configured' };
24
+ // Blend the configured prior with the observed success rate; evidence weighs more as it grows.
25
+ const observed = successes / n;
26
+ const prior = configured ?? 0.5;
27
+ const w = n / (n + 5);
28
+ return {
29
+ score: round2(prior * (1 - w) + observed * w),
30
+ source: `${configured == null ? 'record' : 'configured+record'} of ${n} paid call${n === 1 ? '' : 's'}`,
31
+ };
32
+ }
33
+ }
34
+
35
+ export const createTrust = (config, ledger) => new Trust(config, ledger);
36
+
37
+ const round2 = (n) => Math.round(n * 100) / 100;