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/admin.js ADDED
@@ -0,0 +1,612 @@
1
+ /**
2
+ * The admin console and its API: sign-in, users and roles, approvals, activity search, agents,
3
+ * policy and system info. Single sign-on, audit export and metrics come from the Blocknet Enterprise
4
+ * package when it's installed and licensed (see enterprise.js); this file checks the user and the
5
+ * licence, then hands those requests to it.
6
+ *
7
+ * Every request is authenticated by a session cookie (with a CSRF token for changes) or the admin
8
+ * token, checked against the role's permissions, and every change is written to the audit log.
9
+ */
10
+ import { readFileSync, existsSync } from 'node:fs';
11
+ import { timingSafeEqual, createHash } from 'node:crypto';
12
+ import { VERSION } from './config.js';
13
+ import { utcDay } from './ledger.js';
14
+ import { effectiveConfig, keyHash, keyPreview, newAgentKey, agentsEnabled } from './agents.js';
15
+ import { can, PERMISSIONS, ROLES, publicUser, verifyPassword, hashPassword, passwordProblem, problem, temporaryPassword } from './users.js';
16
+ import { cookie, parseCookies } from './sessions.js';
17
+ import { PLANS, upgradeNeeded } from './license.js';
18
+ import { simulate, withChanges } from './simulate.js';
19
+
20
+ const SESSION_COOKIE = 'bk_session';
21
+ const CONSOLE_DIR = new URL('./console/', import.meta.url);
22
+ const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
23
+ const PAGE_HEADERS = {
24
+ 'content-security-policy': CSP,
25
+ 'x-frame-options': 'DENY',
26
+ 'x-content-type-options': 'nosniff',
27
+ 'referrer-policy': 'no-referrer',
28
+ 'permissions-policy': 'camera=(), microphone=(), geolocation=()',
29
+ 'cross-origin-opener-policy': 'same-origin',
30
+ };
31
+ // Spent on a missing user too, so response time doesn't reveal which emails exist.
32
+ const DUMMY_HASH = await hashPassword('blocknet-timing-equaliser');
33
+
34
+ const eqToken = (a, b) => {
35
+ const ha = createHash('sha256').update(String(a)).digest();
36
+ const hb = createHash('sha256').update(String(b)).digest();
37
+ return timingSafeEqual(ha, hb);
38
+ };
39
+
40
+ /**
41
+ * @param {object} ctx
42
+ * @returns {{handle: (req, res, url) => Promise<boolean>}} handle() returns false for paths it doesn't own
43
+ */
44
+ export function createAdmin(ctx) {
45
+ const { config, settings, users, sessions, limiter, enterprise, ledger, approvals, budget, decideApproval, publicKey, adminToken, startedAt = Date.now() } = ctx;
46
+ const licensing = ctx.licensing ?? (() => ({ plan: 'free', ...PLANS.free, status: 'none', message: null, license: null }));
47
+ const activeUsers = () => users.list().filter((u) => !u.disabled).length;
48
+ /** Throws 402 when the plan doesn't include a feature. */
49
+ const requireFeature = (feature) => {
50
+ const ent = licensing();
51
+ if (!ent[feature]) throw upgradeNeeded(feature, ent);
52
+ };
53
+ const requireSeat = () => {
54
+ const ent = licensing();
55
+ if (ent.seats != null && activeUsers() >= ent.seats) {
56
+ throw Object.assign(upgradeNeeded('seats', ent), { message: `Your ${ent.name} plan includes ${ent.seats} console users, and all are in use. Disable someone, or get a licence for more: contact@acificlabs.com` });
57
+ }
58
+ };
59
+ /** Throws when the plan includes a feature but the Enterprise package isn't installed. */
60
+ const requirePackage = (feature) => {
61
+ if (!enterprise) throw problem(501, missingPackage(feature), undefined);
62
+ };
63
+ const ssoOn = () => Boolean(enterprise?.sso) && Boolean(licensing().sso);
64
+ const planView = () => {
65
+ const ent = licensing();
66
+ return {
67
+ plan: ent.plan,
68
+ name: ent.name,
69
+ status: ent.status,
70
+ message: ent.message,
71
+ seats: ent.seats,
72
+ seatsUsed: activeUsers(),
73
+ features: { auditExport: ent.auditExport, metrics: ent.metrics, advisor: ent.advisor, sso: ent.sso },
74
+ enterprisePackage: enterprise ? { version: enterprise.version ?? null } : null,
75
+ license: ent.license ? { id: ent.license.id, customer: ent.license.customer, expiresAt: ent.license.expiresAt, from: ent.license.from } : null,
76
+ };
77
+ };
78
+ const assets = loadAssets();
79
+ const secure = String(config.admin?.publicUrl ?? '').startsWith('https:');
80
+ const sessionMaxAge = (config.admin?.sessionMaxDays ?? 7) * 86400;
81
+
82
+ const audit = (actor, action, target, detail) =>
83
+ ledger.record({ type: 'admin', actor, action, ...(target != null && { target }), ...(detail && { detail }) });
84
+ const authEvent = (actor, action, detail) => ledger.record({ type: 'auth', actor, action, ...(detail && { detail }) });
85
+
86
+ /** Who's calling: { user, session?, viaToken? } or null. */
87
+ function principal(req) {
88
+ const auth = req.headers.authorization ?? '';
89
+ if (adminToken && auth.startsWith('Bearer ') && eqToken(auth.slice(7), adminToken)) {
90
+ return { user: { id: 'admin-token', email: 'admin-token', name: 'Admin token', role: 'admin' }, viaToken: true };
91
+ }
92
+ const token = parseCookies(req.headers.cookie)[SESSION_COOKIE];
93
+ const found = sessions.get(token, users);
94
+ return found ? { user: found.user, session: found.session, token } : null;
95
+ }
96
+
97
+ const actorOf = (p) => (p.viaToken ? 'admin-token' : p.user.email);
98
+ const clientAddress = (req) => (config.admin?.trustProxy ? String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim() : '') || req.socket.remoteAddress || 'unknown';
99
+
100
+ function startSession(res, user, req, extra, alsoSet = []) {
101
+ const { token, session } = sessions.create(user, { address: clientAddress(req), userAgent: String(req.headers['user-agent'] ?? '').slice(0, 200), ...extra });
102
+ users.update(user.id, { lastLoginAt: new Date().toISOString() });
103
+ res.setHeader('set-cookie', [cookie(SESSION_COOKIE, token, { secure, maxAgeSeconds: sessionMaxAge }), ...alsoSet]);
104
+ return session;
105
+ }
106
+
107
+ const me = (p) => ({
108
+ user: publicUser(p.user) ?? p.user,
109
+ csrf: p.session?.csrf ?? null,
110
+ permissions: PERMISSIONS[p.user.role] ?? [],
111
+ sso: { enabled: ssoOn(), label: enterprise?.sso?.label ?? null },
112
+ plan: planView(),
113
+ });
114
+
115
+ // ---------- route table ----------
116
+
117
+ async function handle(req, res, url) {
118
+ const path = url.pathname;
119
+ const method = req.method;
120
+
121
+ if (method === 'GET' && (path === '/' || path === '/index.html')) return page(res, assets.html), true;
122
+ if (method === 'GET' && path === '/console/console.js') return asset(res, assets.js, 'text/javascript; charset=utf-8'), true;
123
+ if (method === 'GET' && path === '/console/console.css') return asset(res, assets.css, 'text/css; charset=utf-8'), true;
124
+ if (method === 'GET' && (path === '/auth/oidc/login' || path === '/auth/oidc/callback')) return sso(req, res, url, path), true;
125
+ if (method === 'GET' && path === '/metrics') return metrics(req, res), true;
126
+ if (!path.startsWith('/admin/api/')) return false;
127
+
128
+ res.setHeader('cache-control', 'no-store');
129
+ res.setHeader('x-content-type-options', 'nosniff');
130
+ try {
131
+ await api(req, res, method, path.slice('/admin/api'.length), url);
132
+ } catch (err) {
133
+ if (res.headersSent) return res.end(), true;
134
+ if (err.expose) json(res, err.status ?? 400, { error: err.message, ...(err.field && { field: err.field }), ...(err.extra ?? {}) });
135
+ else json(res, 500, { error: 'internal error' });
136
+ }
137
+ return true;
138
+ }
139
+
140
+ async function api(req, res, method, route, url) {
141
+ // ---- no session needed ----
142
+ if (route === '/login' && method === 'POST') return login(req, res);
143
+ if (route === '/setup' && method === 'POST') return setup(req, res);
144
+
145
+ const p = principal(req);
146
+ if (route === '/me' && method === 'GET') {
147
+ if (!p) return json(res, 401, { error: 'sign in required', setupRequired: users.count() === 0, sso: { enabled: ssoOn(), label: enterprise?.sso?.label ?? null } });
148
+ return json(res, 200, me(p));
149
+ }
150
+ if (!p) throw problem(401, 'sign in required');
151
+
152
+ // CSRF: cookie sessions must echo the token on anything that changes state
153
+ if (method !== 'GET' && !p.viaToken) {
154
+ const sent = String(req.headers['x-csrf-token'] ?? '');
155
+ if (!sent || !eqToken(sent, p.session.csrf)) throw problem(403, 'missing or wrong CSRF token');
156
+ }
157
+
158
+ if (route === '/logout' && method === 'POST') {
159
+ if (p.token) sessions.destroy(p.token);
160
+ res.setHeader('set-cookie', cookie(SESSION_COOKIE, '', { secure, maxAgeSeconds: 0 }));
161
+ authEvent(actorOf(p), 'logout');
162
+ return empty(res);
163
+ }
164
+ if (route === '/account/password' && method === 'POST') return changePassword(req, res, p);
165
+ if (p.user.mustChangePassword) throw problem(403, 'password change required');
166
+ if (route === '/account/logout-all' && method === 'POST') {
167
+ if (p.viaToken) throw problem(400, 'the admin token has no sessions');
168
+ sessions.destroyUser(p.user.id);
169
+ res.setHeader('set-cookie', cookie(SESSION_COOKIE, '', { secure, maxAgeSeconds: 0 }));
170
+ authEvent(actorOf(p), 'logout_all');
171
+ return empty(res);
172
+ }
173
+
174
+ const need = (perm) => {
175
+ if (!can(p.user.role, perm)) throw problem(403, "your role can't do this");
176
+ };
177
+ let m;
178
+
179
+ if (route === '/overview' && method === 'GET') return need('overview'), json(res, 200, overview());
180
+ if (route === '/system' && method === 'GET') return need('system.view'), json(res, 200, system());
181
+ if (route === '/plan' && method === 'GET') return json(res, 200, planView());
182
+
183
+ // approvals
184
+ if (route === '/approvals' && method === 'GET') {
185
+ need('approvals.view');
186
+ const q = url.searchParams;
187
+ const limit = clampInt(q.get('limit'), 100, 1, 1000);
188
+ return json(res, 200, { approvals: approvals.list({ status: q.get('status') || undefined, agent: q.get('agent') || undefined }).slice(0, limit) });
189
+ }
190
+ if ((m = route.match(/^\/approvals\/([\w-]+)\/(approve|deny)$/)) && method === 'POST') {
191
+ need('approvals.decide');
192
+ const out = decideApproval(m[1], m[2], actorOf(p));
193
+ return json(res, out.status, out.body);
194
+ }
195
+
196
+ // activity
197
+ if (route === '/audit' && method === 'GET') {
198
+ need('audit.view');
199
+ const limit = clampInt(url.searchParams.get('limit'), 100, 1, 1000);
200
+ const all = queryAudit(url.searchParams);
201
+ const page = all.slice(0, limit);
202
+ return json(res, 200, { entries: page, next: all.length > limit ? page.at(-1).ts : null });
203
+ }
204
+ if (route === '/audit/export' && method === 'GET') {
205
+ need('audit.view');
206
+ requireFeature('auditExport');
207
+ requirePackage('Audit log export');
208
+ return enterprise.auditExport(kit, req, res, url, actorOf(p));
209
+ }
210
+
211
+ // agents
212
+ if (route === '/agents' && method === 'GET') return need('agents.view'), json(res, 200, { agents: listAgents() });
213
+ if (route === '/agents' && method === 'POST') {
214
+ need('agents.manage');
215
+ const body = await readJson(req);
216
+ const key = newAgentKey();
217
+ settings.putAgent(body.name, { keySha256: keyHash(key), keyPreview: keyPreview(key), payments: body.payments, network: body.network }, { create: true, meta: { actor: actorOf(p), reason: `add agent ${body.name}` } });
218
+ audit(actorOf(p), 'agent.create', body.name, { payments: body.payments ?? null });
219
+ return json(res, 201, { agent: agentView(body.name), key });
220
+ }
221
+ if ((m = route.match(/^\/agents\/([\w.-]+)$/))) {
222
+ const name = m[1];
223
+ if (method === 'PATCH') {
224
+ need('agents.manage');
225
+ const body = await readJson(req);
226
+ const current = settings.agents()[name];
227
+ if (!current) throw problem(404, `unknown agent ${name}`);
228
+ const fields = {};
229
+ if ('payments' in body) fields.payments = body.payments ?? undefined;
230
+ if ('network' in body) fields.network = body.network ?? undefined;
231
+ if ('disabled' in body) fields.disabled = Boolean(body.disabled);
232
+ settings.putAgent(name, fields, { meta: { actor: actorOf(p), reason: `change agent ${name}` } });
233
+ audit(actorOf(p), 'agent.update', name, fields);
234
+ return json(res, 200, { agent: agentView(name) });
235
+ }
236
+ if (method === 'DELETE') {
237
+ need('agents.manage');
238
+ settings.removeAgent(name, { actor: actorOf(p), reason: `remove agent ${name}` });
239
+ audit(actorOf(p), 'agent.delete', name);
240
+ return empty(res);
241
+ }
242
+ }
243
+ if ((m = route.match(/^\/agents\/([\w.-]+)\/rotate$/)) && method === 'POST') {
244
+ need('agents.manage');
245
+ const key = newAgentKey();
246
+ const current = settings.agents()[m[1]];
247
+ if (!current) throw problem(404, `unknown agent ${m[1]}`);
248
+ const { key: _old, ...rest } = current;
249
+ settings.putAgent(m[1], { ...rest, keySha256: keyHash(key), keyPreview: keyPreview(key) }, { meta: { actor: actorOf(p), reason: `rotate key for ${m[1]}` } });
250
+ audit(actorOf(p), 'agent.rotate_key', m[1]);
251
+ return json(res, 200, { agent: agentView(m[1]), key });
252
+ }
253
+
254
+ // policy
255
+ if (route === '/policy' && method === 'GET') return need('policy.view'), json(res, 200, settings.policy());
256
+ if (route === '/policy' && method === 'PUT') {
257
+ need('policy.manage');
258
+ const body = await readJson(req);
259
+ const before = settings.policy();
260
+ const after = settings.updatePolicy(body, { actor: actorOf(p), reason: 'policy change' });
261
+ audit(actorOf(p), 'policy.update', Object.keys(body).join(','), diff(before, after));
262
+ return json(res, 200, after);
263
+ }
264
+ // test a change on recorded traffic before saving it
265
+ if (route === '/policy/simulate' && method === 'POST') {
266
+ need('policy.view');
267
+ const body = await readJson(req);
268
+ return json(res, 200, simulateChange(body));
269
+ }
270
+ if (route === '/policy/history' && method === 'GET') {
271
+ need('policy.view');
272
+ return json(res, 200, { versions: settings.history().slice(0, clampInt(url.searchParams.get('limit'), 50, 1, 500)) });
273
+ }
274
+ if ((m = route.match(/^\/policy\/history\/(\d+)\/rollback$/)) && method === 'POST') {
275
+ need('policy.manage');
276
+ const before = settings.policy();
277
+ const v = settings.rollback(m[1], { actor: actorOf(p) });
278
+ audit(actorOf(p), 'policy.rollback', `version ${v.version}`, diff(before, settings.policy()));
279
+ return json(res, 200, { restored: v.version, policy: settings.policy() });
280
+ }
281
+
282
+ // the policy advisor (Blocknet Enterprise): proposals from Blocknet's own record, tested before they're shown
283
+ if (route === '/advisor' || route.startsWith('/advisor/')) {
284
+ need('policy.view');
285
+ requireFeature('advisor');
286
+ requirePackage('The policy advisor');
287
+ if (typeof enterprise.advisor !== 'function') throw problem(501, 'The policy advisor needs a newer Blocknet Enterprise package. Help: contact@acificlabs.com');
288
+ return enterprise.advisor(kit, { req, res, method, route, url, actor: actorOf(p), allowed: (perm) => can(p.user.role, perm), readJson });
289
+ }
290
+
291
+ // users
292
+ if (route === '/users' && method === 'GET') return need('users.manage'), json(res, 200, { users: users.list().map(publicUser) });
293
+ if (route === '/users' && method === 'POST') {
294
+ need('users.manage');
295
+ const body = await readJson(req);
296
+ requireSeat();
297
+ const { user, temporaryPassword: temp } = await users.create({ email: body.email, name: body.name, role: body.role });
298
+ audit(actorOf(p), 'user.create', user.email, { role: user.role });
299
+ return json(res, 201, { user: publicUser(user), temporaryPassword: temp });
300
+ }
301
+ if ((m = route.match(/^\/users\/(u_\w+)$/))) {
302
+ need('users.manage');
303
+ const target = users.get(m[1]);
304
+ if (!target) throw problem(404, 'unknown user');
305
+ const self = target.id === p.user.id;
306
+ if (method === 'PATCH') {
307
+ const body = await readJson(req);
308
+ const fields = {};
309
+ if ('name' in body) fields.name = String(body.name ?? '').trim().slice(0, 120) || target.name;
310
+ if ('role' in body && body.role !== target.role) {
311
+ if (!ROLES.includes(body.role)) throw problem(400, `role must be one of ${ROLES.join(', ')}`, 'role');
312
+ if (self) throw problem(409, "you can't change your own role");
313
+ if (target.role === 'admin' && lastAdmin(target)) throw problem(409, "can't remove the last active admin");
314
+ fields.role = body.role;
315
+ }
316
+ if ('disabled' in body && Boolean(body.disabled) !== Boolean(target.disabled)) {
317
+ if (self) throw problem(409, "you can't disable yourself");
318
+ if (!body.disabled) requireSeat();
319
+ if (body.disabled && target.role === 'admin' && lastAdmin(target)) throw problem(409, "can't disable the last active admin");
320
+ fields.disabled = Boolean(body.disabled);
321
+ }
322
+ users.update(target.id, fields);
323
+ if (fields.role || fields.disabled) {
324
+ users.revokeSessions(target.id);
325
+ sessions.destroyUser(target.id);
326
+ }
327
+ audit(actorOf(p), 'user.update', target.email, fields);
328
+ return json(res, 200, { user: publicUser(users.get(target.id)) });
329
+ }
330
+ if (method === 'DELETE') {
331
+ if (self) throw problem(409, "you can't delete yourself");
332
+ if (target.role === 'admin' && lastAdmin(target)) throw problem(409, "can't remove the last active admin");
333
+ users.remove(target.id);
334
+ sessions.destroyUser(target.id);
335
+ audit(actorOf(p), 'user.delete', target.email);
336
+ return empty(res);
337
+ }
338
+ }
339
+ if ((m = route.match(/^\/users\/(u_\w+)\/reset-password$/)) && method === 'POST') {
340
+ need('users.manage');
341
+ const target = users.get(m[1]);
342
+ if (!target) throw problem(404, 'unknown user');
343
+ if (target.sso) throw problem(409, 'this user signs in with SSO and has no password');
344
+ const temp = temporaryPassword();
345
+ await users.setPassword(target.id, temp, { mustChange: true });
346
+ sessions.destroyUser(target.id);
347
+ audit(actorOf(p), 'user.reset_password', target.email);
348
+ return json(res, 200, { temporaryPassword: temp });
349
+ }
350
+
351
+ throw problem(404, 'not found');
352
+ }
353
+
354
+ // ---------- sign-in ----------
355
+
356
+ async function login(req, res) {
357
+ const body = await readJson(req);
358
+ const email = String(body.email ?? '').trim().toLowerCase();
359
+ const address = clientAddress(req);
360
+ const wait = limiter.retryAfter(email, address);
361
+ if (wait) {
362
+ authEvent(email || 'unknown', 'login_throttled', { address });
363
+ throw Object.assign(problem(429, 'too many attempts; try again later'), { extra: { retryAfterSeconds: wait } });
364
+ }
365
+ const user = users.byEmail(email);
366
+ const ok = await verifyPassword(String(body.password ?? ''), user?.passwordHash ?? DUMMY_HASH);
367
+ if (!user || !ok || user.disabled || user.sso) {
368
+ limiter.fail(email, address);
369
+ authEvent(email || 'unknown', 'login_failed', { address });
370
+ throw problem(401, 'wrong email or password');
371
+ }
372
+ limiter.succeed(email);
373
+ const session = startSession(res, user, req);
374
+ authEvent(user.email, 'login', { address });
375
+ return json(res, 200, me({ user: users.get(user.id), session }));
376
+ }
377
+
378
+ async function setup(req, res) {
379
+ const body = await readJson(req);
380
+ if (users.count() > 0) throw problem(409, 'setup is already done; sign in instead');
381
+ if (!adminToken || !body.adminToken || !eqToken(body.adminToken, adminToken)) {
382
+ limiter.fail('setup', clientAddress(req));
383
+ throw problem(401, 'wrong admin token (it is in ~/.blocknet/admin-token)', 'adminToken');
384
+ }
385
+ const { user } = await users.create({ email: body.email, name: body.name, role: 'admin', password: body.password });
386
+ const session = startSession(res, user, req);
387
+ audit(user.email, 'setup', user.email);
388
+ return json(res, 200, me({ user, session }));
389
+ }
390
+
391
+ async function changePassword(req, res, p) {
392
+ if (p.viaToken) throw problem(400, 'the admin token has no password');
393
+ if (p.user.sso) throw problem(409, 'you sign in with SSO; change your password there');
394
+ const body = await readJson(req);
395
+ if (!(await verifyPassword(String(body.current ?? ''), p.user.passwordHash))) throw problem(400, 'current password is wrong', 'current');
396
+ const bad = passwordProblem(body.next);
397
+ if (bad) throw problem(400, bad, 'next');
398
+ if (body.next === body.current) throw problem(400, 'choose a new password', 'next');
399
+ const user = await users.setPassword(p.user.id, body.next);
400
+ sessions.destroyUser(user.id);
401
+ startSession(res, user, req);
402
+ authEvent(user.email, 'password_changed');
403
+ return empty(res);
404
+ }
405
+
406
+ // ---------- paid features, handed to the Enterprise package ----------
407
+
408
+ /** What the Enterprise package may use. It runs in this process, after the checks above. */
409
+ const kit = {
410
+ config, users, sessions, ledger, approvals, settings, budget, licensing, upgradeNeeded, secure,
411
+ agentBudget: (name) => agentBudget(name),
412
+ queryAudit: (q) => queryAudit(q),
413
+ activeUsers, audit, authEvent, clientAddress, cookie, parseCookies, redirect, json, utcDay, problem, diff,
414
+ home: ctx.home ?? null,
415
+ simulateChange: (change) => simulateChange(change),
416
+ signIn: (res, user, req, extra, alsoSet) => startSession(res, user, req, extra, alsoSet),
417
+ };
418
+
419
+ function sso(req, res, url, path) {
420
+ const ent = licensing();
421
+ const refuse = (message) => redirect(res, '/?error=' + encodeURIComponent(message));
422
+ if (!ent.sso) return refuse(upgradeNeeded('sso', ent).message);
423
+ if (!enterprise) return refuse(missingPackage('Single sign-on'));
424
+ if (!enterprise.sso) return refuse('single sign-on is not set up');
425
+ return path === '/auth/oidc/login' ? enterprise.ssoLogin(kit, req, res) : enterprise.ssoCallback(kit, req, res, url);
426
+ }
427
+
428
+ function metrics(req, res) {
429
+ const p = principal(req);
430
+ if (!p || !can(p.user.role, 'system.view')) {
431
+ res.writeHead(401, { 'content-type': 'text/plain', 'www-authenticate': 'Bearer' });
432
+ return res.end('admin token or a signed-in user required\n');
433
+ }
434
+ const ent = licensing();
435
+ if (!ent.metrics || !enterprise) {
436
+ res.writeHead(ent.metrics ? 501 : 402, { 'content-type': 'text/plain' });
437
+ return res.end((ent.metrics ? missingPackage('Prometheus metrics') : upgradeNeeded('metrics', ent).message) + '\n');
438
+ }
439
+ return enterprise.metrics(kit, req, res);
440
+ }
441
+
442
+ const lastAdmin = (target) => users.activeAdmins().filter((u) => u.id !== target.id).length === 0;
443
+
444
+ // ---------- views ----------
445
+
446
+ function agentBudget(name) {
447
+ const a = settings.agents()[name];
448
+ return budget({ name, config: effectiveConfig(config, a) }).agent;
449
+ }
450
+
451
+ function agentView(name) {
452
+ const a = settings.agents()[name];
453
+ const today = agentBudget(name);
454
+ return {
455
+ name,
456
+ payments: a.payments ?? {},
457
+ network: a.network ?? {},
458
+ disabled: Boolean(a.disabled),
459
+ createdAt: a.createdAt ?? null,
460
+ keyPreview: a.keyPreview ?? (a.key ? keyPreview(a.key) : null),
461
+ keyStorage: a.keySha256 ? 'hashed' : 'plain',
462
+ today: { spentUsd: today.spentUsd, reservedUsd: today.reservedUsd, remainingUsd: today.remainingUsd, dailyBudgetUsd: today.dailyBudgetUsd },
463
+ };
464
+ }
465
+ const listAgents = () => Object.keys(settings.agents()).sort().map(agentView);
466
+
467
+ function overview() {
468
+ const day = utcDay();
469
+ const today = ledger.entries.filter((e) => e.ts.startsWith(day));
470
+ const count = (pred) => today.filter(pred).length;
471
+ return {
472
+ budget: budget(),
473
+ agents: Object.keys(settings.agents()).sort().map((name) => ({ name, ...agentBudget(name), disabled: Boolean(settings.agents()[name].disabled) })),
474
+ counts: {
475
+ requestsToday: count((e) => e.type === 'request'),
476
+ blockedToday: count((e) => e.type === 'blocked'),
477
+ paymentsToday: count((e) => e.type === 'payment' && e.settled),
478
+ deniedToday: count((e) => e.type === 'payment_decision' && e.decision === 'deny'),
479
+ },
480
+ pending: approvals.list({ status: 'pending' }),
481
+ recent: ledger.recent(15),
482
+ };
483
+ }
484
+
485
+ function system() {
486
+ return {
487
+ version: VERSION,
488
+ uptimeSeconds: Math.round((Date.now() - startedAt) / 1000),
489
+ home: ctx.home ?? null,
490
+ configFile: config.configFile ?? settings.file,
491
+ auditLog: config.auditLog,
492
+ approvalsFile: config.approvalsFile,
493
+ gatewayUrl: ctx.gatewayUrl ?? null,
494
+ adminUrl: ctx.adminUrl ?? null,
495
+ agentsEnabled: agentsEnabled(config),
496
+ proxyEnabled: Boolean(config.proxy?.enabled),
497
+ sso: { enabled: ssoOn(), issuer: enterprise?.sso?.issuer ?? null },
498
+ enterprisePackage: enterprise ? { version: enterprise.version ?? null } : null,
499
+ signingPublicKey: publicKey ?? null,
500
+ plan: planView(),
501
+ };
502
+ }
503
+
504
+ /**
505
+ * Replays recorded traffic against the current policy with `change` applied.
506
+ * change: { policy?: {section: fields}, agents?: {name: {payments, network}}, days?, since? }
507
+ */
508
+ function simulateChange(change = {}) {
509
+ const policy = settings.preview(change.policy ?? {});
510
+ const agents = {};
511
+ for (const [name, a] of Object.entries(change.agents ?? {})) {
512
+ if (!settings.agents()[name]) throw problem(400, `unknown agent ${name}`, 'agents');
513
+ agents[name] = { ...(a?.payments && { payments: a.payments }), ...(a?.network && { network: a.network }) };
514
+ }
515
+ const days = clampInt(change.days, 30, 1, 365);
516
+ const since = change.since ? new Date(change.since).toISOString() : new Date(Date.now() - days * 86_400_000).toISOString();
517
+ const report = simulate(ledger.entries, { current: config, candidate: withChanges(config, { policy, agents }), since });
518
+ return { days, ...report };
519
+ }
520
+
521
+ function queryAudit(q) {
522
+ const type = q.get('type'), agent = q.get('agent'), host = q.get('host')?.toLowerCase(), text = q.get('q')?.toLowerCase();
523
+ const from = q.get('from') ? new Date(q.get('from')).toISOString() : null;
524
+ const to = q.get('to') ? endOf(q.get('to')) : null;
525
+ const before = q.get('before');
526
+ const out = [];
527
+ for (let i = ledger.entries.length - 1; i >= 0; i--) {
528
+ const e = ledger.entries[i];
529
+ if (before && e.ts >= before) continue;
530
+ if (from && e.ts < from) break; // entries are in time order
531
+ if (to && e.ts > to) continue;
532
+ if (type && e.type !== type) continue;
533
+ if (agent && e.agent !== agent) continue;
534
+ if (host && !String(e.host ?? '').toLowerCase().includes(host)) continue;
535
+ if (text && !JSON.stringify(e).toLowerCase().includes(text)) continue;
536
+ out.push(e);
537
+ }
538
+ return out;
539
+ }
540
+
541
+ // Background work for the Enterprise package (the advisor's automatic tightening), never on the request path.
542
+ enterprise?.start?.(kit);
543
+
544
+ return { handle };
545
+ }
546
+
547
+ // ---------- helpers ----------
548
+
549
+ function loadAssets() {
550
+ const read = (f) => {
551
+ const url = new URL(f, CONSOLE_DIR);
552
+ return existsSync(url) ? readFileSync(url) : null;
553
+ };
554
+ return {
555
+ html: read('index.html') ?? Buffer.from('<!doctype html><title>blocknet.</title><p>The console files are missing from src/console/.</p>'),
556
+ js: read('console.js') ?? Buffer.from(''),
557
+ css: read('console.css') ?? Buffer.from(''),
558
+ };
559
+ }
560
+
561
+ function page(res, body) {
562
+ res.writeHead(200, { ...PAGE_HEADERS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
563
+ res.end(body);
564
+ }
565
+ function asset(res, body, type) {
566
+ res.writeHead(200, { 'content-type': type, 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' });
567
+ res.end(body);
568
+ }
569
+ function json(res, status, body) {
570
+ res.writeHead(status, { 'content-type': 'application/json' });
571
+ res.end(JSON.stringify(body, null, 2));
572
+ }
573
+ function empty(res) {
574
+ res.writeHead(204);
575
+ res.end();
576
+ }
577
+ function redirect(res, location) {
578
+ res.writeHead(302, { location, 'cache-control': 'no-store' });
579
+ res.end();
580
+ }
581
+
582
+ async function readJson(req) {
583
+ let raw = '';
584
+ for await (const chunk of req) {
585
+ raw += chunk;
586
+ if (raw.length > 256_000) throw problem(413, 'body too large');
587
+ }
588
+ try {
589
+ const v = JSON.parse(raw || '{}');
590
+ if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error();
591
+ return v;
592
+ } catch {
593
+ throw problem(400, 'body must be a JSON object');
594
+ }
595
+ }
596
+
597
+ const clampInt = (v, dflt, min, max) => Math.min(max, Math.max(min, Number.parseInt(v ?? dflt, 10) || dflt));
598
+ const endOf = (d) => (/^\d{4}-\d{2}-\d{2}$/.test(d) ? `${d}T23:59:59.999Z` : new Date(d).toISOString());
599
+
600
+ function diff(before, after) {
601
+ const out = {};
602
+ for (const s of Object.keys(after)) {
603
+ for (const k of Object.keys(after[s] ?? {})) {
604
+ if (JSON.stringify(before[s]?.[k]) !== JSON.stringify(after[s][k])) out[`${s}.${k}`] = { from: before[s]?.[k] ?? null, to: after[s][k] };
605
+ }
606
+ }
607
+ return out;
608
+ }
609
+
610
+ function missingPackage(feature) {
611
+ return `${feature} is in your plan, but the Blocknet Enterprise package isn't installed. Put the package that came with your licence in ~/.blocknet/enterprise (or set BLOCKNET_ENTERPRISE) and restart. Help: contact@acificlabs.com`;
612
+ }