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/LICENSE +202 -0
- package/NOTICE +13 -0
- package/README.md +233 -2
- package/bin/blocknet.js +388 -0
- package/package.json +54 -4
- package/src/admin.js +612 -0
- package/src/agents.js +75 -0
- package/src/approvals.js +73 -0
- package/src/client.js +115 -0
- package/src/config.js +89 -0
- package/src/console/console.css +493 -0
- package/src/console/console.js +1571 -0
- package/src/console/index.html +18 -0
- package/src/enterprise.js +37 -0
- package/src/gateway.js +480 -0
- package/src/hosts.js +77 -0
- package/src/ledger.js +55 -0
- package/src/license.js +111 -0
- package/src/mcp.js +163 -0
- package/src/notify.js +34 -0
- package/src/policy.js +69 -0
- package/src/sessions.js +147 -0
- package/src/settings.js +292 -0
- package/src/signing.js +55 -0
- package/src/simulate.js +140 -0
- package/src/trust.js +37 -0
- package/src/users.js +182 -0
- package/src/x402.js +81 -0
|
@@ -0,0 +1,1571 @@
|
|
|
1
|
+
// Blocknet admin console. Vanilla ES module, no dependencies.
|
|
2
|
+
// Runs under a strict CSP: no inline scripts, styles or handlers. Every string from the API is escaped.
|
|
3
|
+
|
|
4
|
+
// ---------- Escaping and templates ----------
|
|
5
|
+
|
|
6
|
+
class Raw {
|
|
7
|
+
constructor(s) {
|
|
8
|
+
this.s = s;
|
|
9
|
+
}
|
|
10
|
+
toString() {
|
|
11
|
+
return this.s;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const raw = (s) => new Raw(String(s));
|
|
15
|
+
const esc = (s) =>
|
|
16
|
+
String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
17
|
+
const val = (v) => (v instanceof Raw ? v.s : Array.isArray(v) ? v.map(val).join('') : v == null || v === false ? '' : esc(v));
|
|
18
|
+
/** Tagged template: interpolations are escaped unless wrapped in raw() or produced by h``. */
|
|
19
|
+
const h = (strings, ...vals) => raw(strings.reduce((out, s, i) => out + s + (i < vals.length ? val(vals[i]) : ''), ''));
|
|
20
|
+
|
|
21
|
+
const $ = (sel, root = document) => root.querySelector(sel);
|
|
22
|
+
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
|
|
23
|
+
|
|
24
|
+
// ---------- State ----------
|
|
25
|
+
|
|
26
|
+
const state = {
|
|
27
|
+
me: null,
|
|
28
|
+
csrf: null,
|
|
29
|
+
perms: new Set(),
|
|
30
|
+
sso: { enabled: false, label: 'SSO' },
|
|
31
|
+
route: null,
|
|
32
|
+
renderToken: 0,
|
|
33
|
+
poll: null,
|
|
34
|
+
flashError: null,
|
|
35
|
+
approvalStatus: 'pending',
|
|
36
|
+
activity: { filters: {}, entries: [], next: null },
|
|
37
|
+
pendingCount: 0,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const can = (p) => state.perms.has(p);
|
|
41
|
+
|
|
42
|
+
class ApiError extends Error {
|
|
43
|
+
constructor(message, status, data) {
|
|
44
|
+
super(message);
|
|
45
|
+
this.status = status;
|
|
46
|
+
this.data = data;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ---------- API ----------
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {string} path
|
|
54
|
+
* @param {{method?: string, body?: any, quiet?: boolean, noRedirect?: boolean}} [opts]
|
|
55
|
+
*/
|
|
56
|
+
async function api(path, opts = {}) {
|
|
57
|
+
const method = opts.method ?? 'GET';
|
|
58
|
+
const headers = { accept: 'application/json' };
|
|
59
|
+
if (opts.body !== undefined) headers['content-type'] = 'application/json';
|
|
60
|
+
if (method !== 'GET' && state.csrf) headers['x-csrf-token'] = state.csrf;
|
|
61
|
+
let res;
|
|
62
|
+
try {
|
|
63
|
+
res = await fetch(path, {
|
|
64
|
+
method,
|
|
65
|
+
credentials: 'same-origin',
|
|
66
|
+
headers,
|
|
67
|
+
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
68
|
+
});
|
|
69
|
+
} catch {
|
|
70
|
+
const err = new ApiError('Blocknet is not reachable. Check that the gateway is running.', 0, null);
|
|
71
|
+
if (!opts.quiet) toast(err.message, 'error');
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
if (res.status === 204) return null;
|
|
75
|
+
let data = null;
|
|
76
|
+
try {
|
|
77
|
+
data = await res.json();
|
|
78
|
+
} catch {}
|
|
79
|
+
if (res.status === 401 && !opts.noRedirect) {
|
|
80
|
+
signedOut(data);
|
|
81
|
+
throw new ApiError(data?.error ?? 'Sign in required', 401, data);
|
|
82
|
+
}
|
|
83
|
+
if (res.status === 403 && data?.error === 'password change required') {
|
|
84
|
+
renderForcedChange();
|
|
85
|
+
throw new ApiError(data.error, 403, data);
|
|
86
|
+
}
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
const err = new ApiError(data?.error ?? `Request failed (${res.status})`, res.status, data);
|
|
89
|
+
if (!opts.quiet) toast(err.message, 'error');
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
92
|
+
return data;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Runs an event handler; API errors are already shown, anything else is reported. */
|
|
96
|
+
async function run(fn, ...args) {
|
|
97
|
+
try {
|
|
98
|
+
await fn(...args);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
if (!(err instanceof ApiError)) {
|
|
101
|
+
console.error(err);
|
|
102
|
+
toast('Something went wrong. Try again.', 'error');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------- Formatting ----------
|
|
108
|
+
|
|
109
|
+
function usd(n) {
|
|
110
|
+
if (n == null || Number.isNaN(Number(n))) return '—';
|
|
111
|
+
const v = Number(n);
|
|
112
|
+
const a = Math.abs(v);
|
|
113
|
+
// Cents when that's exact; otherwise up to 4 decimals, so $4.949 never shows as $4.95.
|
|
114
|
+
const exactCents = Math.abs(a * 100 - Math.round(a * 100)) < 1e-6;
|
|
115
|
+
let text = a.toFixed(exactCents ? 2 : 4);
|
|
116
|
+
if (!exactCents) text = text.replace(/0+$/, '').replace(/\.(\d)$/, '.$10');
|
|
117
|
+
return `${v < 0 ? '−' : ''}$${text}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toDate(ts) {
|
|
121
|
+
if (ts == null) return null;
|
|
122
|
+
const d = typeof ts === 'number' ? new Date(ts) : new Date(String(ts));
|
|
123
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function ago(ts) {
|
|
127
|
+
const d = toDate(ts);
|
|
128
|
+
if (!d) return '—';
|
|
129
|
+
const s = Math.round((Date.now() - d.getTime()) / 1000);
|
|
130
|
+
if (s < -60) return d.toLocaleString();
|
|
131
|
+
if (s < 45) return 'just now';
|
|
132
|
+
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
|
133
|
+
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
|
|
134
|
+
return d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const timeEl = (ts) => {
|
|
138
|
+
const d = toDate(ts);
|
|
139
|
+
return d ? h`<time datetime="${d.toISOString()}" title="${d.toLocaleString()}">${ago(ts)}</time>` : raw('—');
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const clock = (ts) => {
|
|
143
|
+
const d = toDate(ts);
|
|
144
|
+
return d ? d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '';
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
function duration(sec) {
|
|
148
|
+
if (sec == null) return '—';
|
|
149
|
+
const d = Math.floor(sec / 86400);
|
|
150
|
+
const hr = Math.floor((sec % 86400) / 3600);
|
|
151
|
+
const m = Math.floor((sec % 3600) / 60);
|
|
152
|
+
if (d) return `${d} d ${hr} h`;
|
|
153
|
+
if (hr) return `${hr} h ${m} min`;
|
|
154
|
+
return `${m} min`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const PILL = {
|
|
158
|
+
ok: ['allow', 'approved', 'settled', 'paid', 'active', 'login', 'sso_login', 'admin'],
|
|
159
|
+
warn: ['review', 'pending', 'approver'],
|
|
160
|
+
bad: ['deny', 'denied', 'blocked', 'failed', 'disabled', 'payment_refused', 'login_failed', 'sso_denied', 'notify_failed'],
|
|
161
|
+
};
|
|
162
|
+
function pill(text, kind) {
|
|
163
|
+
const k = kind ?? (PILL.ok.includes(text) ? 'ok' : PILL.warn.includes(text) ? 'warn' : PILL.bad.includes(text) ? 'bad' : '');
|
|
164
|
+
return h`<span class="pill${k ? ` pill-${k}` : ''}">${text}</span>`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const rolePill = (role) => pill(role, role === 'admin' ? 'accent' : role === 'approver' ? 'warn' : '');
|
|
168
|
+
|
|
169
|
+
const lines = (text) =>
|
|
170
|
+
String(text ?? '')
|
|
171
|
+
.split('\n')
|
|
172
|
+
.map((s) => s.trim())
|
|
173
|
+
.filter(Boolean);
|
|
174
|
+
|
|
175
|
+
const numOrNull = (v) => (String(v ?? '').trim() === '' ? null : Number(v));
|
|
176
|
+
|
|
177
|
+
const initials = (name) =>
|
|
178
|
+
String(name || '?')
|
|
179
|
+
.split(/[\s@.]+/)
|
|
180
|
+
.filter(Boolean)
|
|
181
|
+
.slice(0, 2)
|
|
182
|
+
.map((p) => p[0].toUpperCase())
|
|
183
|
+
.join('');
|
|
184
|
+
|
|
185
|
+
// ---------- Toasts ----------
|
|
186
|
+
|
|
187
|
+
function toast(message, kind = '') {
|
|
188
|
+
const box = $('#toasts');
|
|
189
|
+
const el = document.createElement('div');
|
|
190
|
+
el.className = `toast${kind ? ` toast-${kind}` : ''}`;
|
|
191
|
+
el.textContent = message;
|
|
192
|
+
box.append(el);
|
|
193
|
+
setTimeout(() => el.remove(), kind === 'error' ? 7000 : 4000);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---------- Dialogs ----------
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Opens a modal. `content` is markup from h``. If the content has a <form>, onSubmit(form, dialog) runs on submit;
|
|
200
|
+
* return false from it to keep the dialog open. Resolves with the dialog's returnValue when it closes.
|
|
201
|
+
*/
|
|
202
|
+
function openDialog(content, { onSubmit, label } = {}) {
|
|
203
|
+
const dialog = document.createElement('dialog');
|
|
204
|
+
if (label) dialog.setAttribute('aria-label', label);
|
|
205
|
+
dialog.innerHTML = String(content);
|
|
206
|
+
document.body.append(dialog);
|
|
207
|
+
const opener = document.activeElement;
|
|
208
|
+
return new Promise((resolve) => {
|
|
209
|
+
dialog.addEventListener('click', (e) => {
|
|
210
|
+
const close = e.target.closest('[data-close]');
|
|
211
|
+
if (close) {
|
|
212
|
+
e.preventDefault();
|
|
213
|
+
dialog.close(close.dataset.close || '');
|
|
214
|
+
}
|
|
215
|
+
const copy = e.target.closest('[data-action="copy"]');
|
|
216
|
+
if (copy) run(actions.copy, copy);
|
|
217
|
+
});
|
|
218
|
+
const form = $('form', dialog);
|
|
219
|
+
if (form) {
|
|
220
|
+
form.addEventListener('submit', async (e) => {
|
|
221
|
+
e.preventDefault();
|
|
222
|
+
const submit = $('button[type="submit"]', form);
|
|
223
|
+
if (submit) submit.disabled = true;
|
|
224
|
+
try {
|
|
225
|
+
const keep = onSubmit ? await onSubmit(form, dialog) : undefined;
|
|
226
|
+
if (keep !== false && dialog.open) dialog.close('ok');
|
|
227
|
+
} catch (err) {
|
|
228
|
+
const box = $('.form-error', form);
|
|
229
|
+
if (box) box.textContent = err instanceof ApiError ? err.message : 'Something went wrong. Try again.';
|
|
230
|
+
if (!(err instanceof ApiError)) console.error(err);
|
|
231
|
+
} finally {
|
|
232
|
+
if (submit) submit.disabled = false;
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
dialog.addEventListener('close', () => {
|
|
237
|
+
resolve(dialog.returnValue);
|
|
238
|
+
dialog.remove();
|
|
239
|
+
if (opener && document.contains(opener)) opener.focus();
|
|
240
|
+
});
|
|
241
|
+
dialog.showModal();
|
|
242
|
+
const first = $('[autofocus], input:not([type="hidden"]):not([disabled]), select, textarea, button[type="submit"]', dialog);
|
|
243
|
+
if (first) first.focus();
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function confirmDialog({ title, body, confirm = 'Confirm', danger = false }) {
|
|
248
|
+
const result = await openDialog(
|
|
249
|
+
h`<form>
|
|
250
|
+
<div class="dialog-head"><h2>${title}</h2></div>
|
|
251
|
+
<div class="dialog-body"><p>${body}</p></div>
|
|
252
|
+
<div class="dialog-foot">
|
|
253
|
+
<button type="button" class="btn" data-close="cancel">Cancel</button>
|
|
254
|
+
<button type="submit" class="btn ${danger ? 'btn-danger-solid' : 'btn-primary'}">${confirm}</button>
|
|
255
|
+
</div>
|
|
256
|
+
</form>`,
|
|
257
|
+
{ label: title },
|
|
258
|
+
);
|
|
259
|
+
return result === 'ok';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Shows a secret (agent key, temporary password) once. */
|
|
263
|
+
function secretDialog({ title, intro, value }) {
|
|
264
|
+
const id = `secret-${Math.random().toString(36).slice(2)}`;
|
|
265
|
+
return openDialog(
|
|
266
|
+
h`<div class="dialog-inner">
|
|
267
|
+
<div class="dialog-head"><h2>${title}</h2><p>${intro}</p></div>
|
|
268
|
+
<div class="dialog-body">
|
|
269
|
+
<div class="secret"><code id="${id}">${value}</code>
|
|
270
|
+
<button type="button" class="btn btn-sm" data-action="copy" data-copy="${id}">Copy</button></div>
|
|
271
|
+
<p class="callout">Copy it now. You won't see it again.</p>
|
|
272
|
+
</div>
|
|
273
|
+
<div class="dialog-foot"><button type="button" class="btn btn-primary" data-close="done" autofocus>I've copied it</button></div>
|
|
274
|
+
</div>`,
|
|
275
|
+
{ label: title },
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ---------- Auth screens ----------
|
|
280
|
+
|
|
281
|
+
function stopPoll() {
|
|
282
|
+
if (state.poll) clearInterval(state.poll);
|
|
283
|
+
state.poll = null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function signedOut(data) {
|
|
287
|
+
state.me = null;
|
|
288
|
+
state.csrf = null;
|
|
289
|
+
state.perms = new Set();
|
|
290
|
+
stopPoll();
|
|
291
|
+
if (data?.sso) state.sso = data.sso;
|
|
292
|
+
if (data?.setupRequired) renderSetup();
|
|
293
|
+
else renderSignIn();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function authShell(inner) {
|
|
297
|
+
$('#app').innerHTML = String(h`<main class="auth"><div class="auth-card">
|
|
298
|
+
<a class="wordmark" href="/">blocknet<span>.</span></a>
|
|
299
|
+
${inner}
|
|
300
|
+
</div></main>`);
|
|
301
|
+
document.title = 'Sign in · Blocknet';
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function renderSignIn() {
|
|
305
|
+
const flash = state.flashError;
|
|
306
|
+
state.flashError = null;
|
|
307
|
+
authShell(h`
|
|
308
|
+
<div><h1>Sign in</h1><p class="muted">to the Blocknet console</p></div>
|
|
309
|
+
<p class="form-error" id="signin-error">${flash ?? ''}</p>
|
|
310
|
+
${state.sso?.enabled ? h`<a class="btn btn-primary btn-block" href="/auth/oidc/login">Sign in with ${state.sso.label || 'SSO'}</a><div class="divider">or with a password</div>` : ''}
|
|
311
|
+
<form data-form="signin" novalidate>
|
|
312
|
+
<div class="field"><label for="si-email">Email</label><input id="si-email" name="email" type="email" autocomplete="username" required></div>
|
|
313
|
+
<div class="field"><label for="si-password">Password</label><input id="si-password" name="password" type="password" autocomplete="current-password" required></div>
|
|
314
|
+
<button type="submit" class="btn ${state.sso?.enabled ? '' : 'btn-primary'} btn-block">Sign in</button>
|
|
315
|
+
</form>`);
|
|
316
|
+
$(state.sso?.enabled ? '.auth-card .btn-primary' : '#si-email')?.focus();
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function renderSetup() {
|
|
320
|
+
authShell(h`
|
|
321
|
+
<div><h1>Set up Blocknet</h1><p class="muted">Create the first admin account. You'll need the admin token from <code>~/.blocknet/admin-token</code>, or run <code>blocknet status</code> to see where it is.</p></div>
|
|
322
|
+
<form data-form="setup" novalidate>
|
|
323
|
+
<p class="form-error"></p>
|
|
324
|
+
<div class="field"><label for="su-token">Admin token</label><input id="su-token" name="adminToken" type="password" autocomplete="off" required></div>
|
|
325
|
+
<div class="field"><label for="su-name">Your name</label><input id="su-name" name="name" type="text" autocomplete="name" required></div>
|
|
326
|
+
<div class="field"><label for="su-email">Email</label><input id="su-email" name="email" type="email" autocomplete="username" required></div>
|
|
327
|
+
<div class="field"><label for="su-password">Password</label><input id="su-password" name="password" type="password" autocomplete="new-password" minlength="12" required><span class="hint">At least 12 characters.</span></div>
|
|
328
|
+
<div class="field"><label for="su-confirm">Confirm password</label><input id="su-confirm" name="confirm" type="password" autocomplete="new-password" required></div>
|
|
329
|
+
<button type="submit" class="btn btn-primary btn-block">Create admin and sign in</button>
|
|
330
|
+
</form>`);
|
|
331
|
+
document.title = 'Set up · Blocknet';
|
|
332
|
+
$('#su-token').focus();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function renderForcedChange() {
|
|
336
|
+
stopPoll();
|
|
337
|
+
authShell(h`
|
|
338
|
+
<div><h1>Choose a new password</h1><p class="muted">You signed in with a temporary password. Set your own to continue.</p></div>
|
|
339
|
+
<form data-form="forced-change" novalidate>
|
|
340
|
+
<p class="form-error"></p>
|
|
341
|
+
<div class="field"><label for="fc-current">Temporary password</label><input id="fc-current" name="current" type="password" autocomplete="current-password" required></div>
|
|
342
|
+
<div class="field"><label for="fc-next">New password</label><input id="fc-next" name="next" type="password" autocomplete="new-password" minlength="12" required><span class="hint">At least 12 characters.</span></div>
|
|
343
|
+
<div class="field"><label for="fc-confirm">Confirm new password</label><input id="fc-confirm" name="confirm" type="password" autocomplete="new-password" required></div>
|
|
344
|
+
<button type="submit" class="btn btn-primary btn-block">Save and continue</button>
|
|
345
|
+
<button type="button" class="btn-link" data-action="logout">Sign out</button>
|
|
346
|
+
</form>`);
|
|
347
|
+
document.title = 'New password · Blocknet';
|
|
348
|
+
$('#fc-current').focus();
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const formData = (form) => Object.fromEntries(new FormData(form).entries());
|
|
352
|
+
const formError = (form, message) => {
|
|
353
|
+
const box = $('.form-error', form);
|
|
354
|
+
if (box) box.textContent = message;
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// ---------- Shell ----------
|
|
358
|
+
|
|
359
|
+
const ROUTES = [
|
|
360
|
+
{ id: 'overview', label: 'Overview', perm: 'overview', render: renderOverview },
|
|
361
|
+
{ id: 'approvals', label: 'Approvals', perm: 'approvals.view', render: renderApprovals },
|
|
362
|
+
{ id: 'activity', label: 'Activity', perm: 'audit.view', render: renderActivity },
|
|
363
|
+
{ id: 'agents', label: 'Agents', perm: 'agents.view', render: renderAgents },
|
|
364
|
+
{ id: 'policy', label: 'Policy', perm: 'policy.view', render: renderPolicy },
|
|
365
|
+
{ id: 'users', label: 'Users', perm: 'users.manage', render: renderUsers },
|
|
366
|
+
{ id: 'settings', label: 'Settings', perm: null, render: renderSettings },
|
|
367
|
+
];
|
|
368
|
+
const allowedRoutes = () => ROUTES.filter((r) => !r.perm || can(r.perm));
|
|
369
|
+
|
|
370
|
+
function renderShell() {
|
|
371
|
+
const u = state.me.user;
|
|
372
|
+
$('#app').innerHTML = String(h`
|
|
373
|
+
<header class="topbar"><div class="topbar-inner">
|
|
374
|
+
<a class="wordmark" href="#/overview">blocknet<span>.</span></a>
|
|
375
|
+
<nav class="nav" aria-label="Console">
|
|
376
|
+
${allowedRoutes().map(
|
|
377
|
+
(r) => h`<a href="#/${r.id}" data-route="${r.id}">${r.label}${r.id === 'approvals' ? h`<span class="count" data-pending-count hidden></span>` : ''}</a>`,
|
|
378
|
+
)}
|
|
379
|
+
</nav>
|
|
380
|
+
<details class="usermenu">
|
|
381
|
+
<summary aria-label="Account menu"><span class="avatar" aria-hidden="true">${initials(u.name || u.email)}</span><span class="who">${u.name || u.email}</span></summary>
|
|
382
|
+
<div class="usermenu-panel">
|
|
383
|
+
<div class="meta"><div class="cell-strong">${u.name || u.email}</div><div class="cell-sub">${u.email}</div><div>${rolePill(u.role)}${u.sso ? h` ${pill('SSO')}` : ''}</div></div>
|
|
384
|
+
<a href="#/settings">Account and system</a>
|
|
385
|
+
<button type="button" data-action="logout">Sign out</button>
|
|
386
|
+
</div>
|
|
387
|
+
</details>
|
|
388
|
+
</div></header>
|
|
389
|
+
${state.me.plan?.message && can('users.manage') ? h`<div class="plan-banner" role="status">${state.me.plan.message}</div>` : ''}
|
|
390
|
+
<main class="main" id="view" tabindex="-1"></main>`);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** "Free", "Team", … with what's included, for the plan card and upgrade notes. */
|
|
394
|
+
const planOf = () => state.me?.plan ?? { plan: 'free', name: 'Free', features: {}, seats: 3, seatsUsed: 0 };
|
|
395
|
+
const UPGRADE_MAIL = 'mailto:contact@acificlabs.com?subject=Blocknet%20licence';
|
|
396
|
+
|
|
397
|
+
function setPendingCount(n) {
|
|
398
|
+
state.pendingCount = n;
|
|
399
|
+
const el = $('[data-pending-count]');
|
|
400
|
+
if (!el) return;
|
|
401
|
+
el.hidden = !n;
|
|
402
|
+
el.textContent = n > 99 ? '99+' : String(n);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function currentRoute() {
|
|
406
|
+
const id = location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] || 'overview';
|
|
407
|
+
const allowed = allowedRoutes();
|
|
408
|
+
return allowed.find((r) => r.id === id) ?? allowed[0];
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function navigate() {
|
|
412
|
+
if (!state.me) return;
|
|
413
|
+
const route = currentRoute();
|
|
414
|
+
if (`#/${route.id}` !== location.hash) history.replaceState(null, '', `#/${route.id}`);
|
|
415
|
+
state.route = route.id;
|
|
416
|
+
$$('.nav a').forEach((a) => (a.dataset.route === route.id ? a.setAttribute('aria-current', 'page') : a.removeAttribute('aria-current')));
|
|
417
|
+
$('.usermenu')?.removeAttribute('open');
|
|
418
|
+
document.title = `${route.label} · Blocknet`;
|
|
419
|
+
const view = $('#view');
|
|
420
|
+
view.innerHTML = '<p class="boot">Loading…</p>';
|
|
421
|
+
await run(route.render, view, { first: true });
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Writes into the view only if the user hasn't navigated away meanwhile. */
|
|
425
|
+
function paint(view, token, markup) {
|
|
426
|
+
if (token !== state.renderToken || !document.contains(view)) return false;
|
|
427
|
+
view.innerHTML = String(markup);
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function startPoll() {
|
|
432
|
+
stopPoll();
|
|
433
|
+
state.poll = setInterval(() => {
|
|
434
|
+
if (document.hidden || !state.me || $('dialog[open]')) return;
|
|
435
|
+
if (state.route === 'overview') run(renderOverview, $('#view'), { first: false });
|
|
436
|
+
else if (can('approvals.view')) run(refreshPendingCount);
|
|
437
|
+
}, 5000);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async function refreshPendingCount() {
|
|
441
|
+
const { approvals } = await api('/admin/api/approvals?status=pending&limit=100', { quiet: true });
|
|
442
|
+
setPendingCount(approvals.length);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// ---------- Shared bits ----------
|
|
446
|
+
|
|
447
|
+
function describe(e) {
|
|
448
|
+
switch (e.type) {
|
|
449
|
+
case 'request':
|
|
450
|
+
return h`${e.method ?? ''} <span class="num">${e.status ?? ''}</span>${e.via ? h` <span class="faint">via ${e.via}</span>` : ''}`;
|
|
451
|
+
case 'blocked':
|
|
452
|
+
return h`${(e.reasons ?? []).join('; ')}${e.via ? h` <span class="faint">via ${e.via}</span>` : ''}`;
|
|
453
|
+
case 'payment_decision':
|
|
454
|
+
return h`${pill(e.decision)} <span class="num">${usd(e.amountUsd)}</span>`;
|
|
455
|
+
case 'payment':
|
|
456
|
+
return h`${pill(e.settled ? 'paid' : 'failed')} <span class="num">${usd(e.quotedUsd ?? e.amountUsd)}</span>${e.status ? h` <span class="faint">HTTP ${e.status}</span>` : ''}`;
|
|
457
|
+
case 'payment_refused':
|
|
458
|
+
return h`${e.reason ?? ''}`;
|
|
459
|
+
case 'approval':
|
|
460
|
+
return h`${pill(e.status)}${e.actor ? h` <span class="faint">by ${e.actor}</span>` : ''}`;
|
|
461
|
+
case 'tunnel':
|
|
462
|
+
return h`port <span class="num">${e.port ?? ''}</span>`;
|
|
463
|
+
case 'notify_failed':
|
|
464
|
+
return h`${e.error ?? ''}`;
|
|
465
|
+
case 'admin':
|
|
466
|
+
return h`<span class="cell-strong">${e.actor ?? ''}</span> ${String(e.action ?? '').replace(/_/g, ' ')} ${e.target ? h`<code>${e.target}</code>` : ''}`;
|
|
467
|
+
case 'auth':
|
|
468
|
+
return h`<span class="cell-strong">${e.actor ?? ''}</span> ${pill(String(e.action ?? ''))}${e.reason ? h` <span class="faint">${e.reason}</span>` : ''}`;
|
|
469
|
+
default:
|
|
470
|
+
return h`${e.status ?? e.reason ?? e.error ?? e.action ?? ''}`;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const TYPE_LABEL = {
|
|
475
|
+
request: 'Request',
|
|
476
|
+
blocked: 'Blocked',
|
|
477
|
+
payment_decision: 'Payment decision',
|
|
478
|
+
payment: 'Payment',
|
|
479
|
+
payment_refused: 'Payment refused',
|
|
480
|
+
approval: 'Approval',
|
|
481
|
+
tunnel: 'Tunnel',
|
|
482
|
+
notify_failed: 'Notify failed',
|
|
483
|
+
admin: 'Admin',
|
|
484
|
+
auth: 'Sign-in',
|
|
485
|
+
};
|
|
486
|
+
const typePill = (t) => pill(TYPE_LABEL[t] ?? t, t === 'blocked' || t === 'payment_refused' || t === 'notify_failed' ? 'bad' : t === 'admin' || t === 'auth' ? 'accent' : '');
|
|
487
|
+
|
|
488
|
+
function approvalRow(a, { actionsCol = true } = {}) {
|
|
489
|
+
const decide = actionsCol && can('approvals.decide') && a.status === 'pending';
|
|
490
|
+
const opt = a.option ?? {};
|
|
491
|
+
return h`<tr>
|
|
492
|
+
<td><div class="cell-strong">${a.host}</div>${a.url ? h`<div class="cell-sub">${a.url}</div>` : ''}</td>
|
|
493
|
+
<td>${a.agent ?? h`<span class="faint">—</span>`}</td>
|
|
494
|
+
<td class="nowrap"><span class="num cell-strong">${usd(opt.amountUsd)}</span> ${opt.asset ?? ''}<div class="cell-sub">${opt.network ?? ''}</div></td>
|
|
495
|
+
<td class="num">${a.trust?.score != null ? Number(a.trust.score).toFixed(2) : h`<span class="faint">unknown</span>`}</td>
|
|
496
|
+
<td><ul class="reasons">${(a.reasons ?? []).map((r) => h`<li>${r}</li>`)}</ul></td>
|
|
497
|
+
<td>${pill(a.status)}${a.usedAt ? h` ${pill('used')}` : ''}</td>
|
|
498
|
+
<td class="nowrap">${timeEl(a.createdAt)}</td>
|
|
499
|
+
${actionsCol ? h`<td class="actions">${decide ? h`<button type="button" class="btn btn-sm btn-ok" data-action="decide" data-verb="approve" data-id="${a.id}">Approve</button><button type="button" class="btn btn-sm btn-danger" data-action="decide" data-verb="deny" data-id="${a.id}">Deny</button>` : ''}</td>` : ''}
|
|
500
|
+
</tr>`;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const approvalsTable = (list, empty) =>
|
|
504
|
+
list.length
|
|
505
|
+
? h`<div class="table-wrap"><table>
|
|
506
|
+
<thead><tr><th>Service</th><th>Agent</th><th>Price</th><th>Trust</th><th>Why</th><th>Status</th><th>When</th><th><span class="sr-only">Actions</span></th></tr></thead>
|
|
507
|
+
<tbody>${list.map((a) => approvalRow(a))}</tbody></table></div>`
|
|
508
|
+
: h`<p class="empty">${empty}</p>`;
|
|
509
|
+
|
|
510
|
+
// ---------- Overview ----------
|
|
511
|
+
|
|
512
|
+
async function renderOverview(view, { first }) {
|
|
513
|
+
const token = first ? ++state.renderToken : state.renderToken;
|
|
514
|
+
const o = await api('/admin/api/overview', { quiet: !first });
|
|
515
|
+
const b = o.budget ?? {};
|
|
516
|
+
const used = (b.spentUsd ?? 0) + (b.reservedUsd ?? 0);
|
|
517
|
+
const ratio = b.dailyBudgetUsd ? used / b.dailyBudgetUsd : 0;
|
|
518
|
+
const c = o.counts ?? {};
|
|
519
|
+
setPendingCount((o.pending ?? []).length);
|
|
520
|
+
paint(
|
|
521
|
+
view,
|
|
522
|
+
token,
|
|
523
|
+
h`
|
|
524
|
+
<div class="page-head"><div><h1>Overview</h1><p>Today, ${b.day ?? ''} (UTC). Updates every few seconds.</p></div></div>
|
|
525
|
+
|
|
526
|
+
<section class="stats" aria-label="Budget">
|
|
527
|
+
<div class="card stat"><div class="label">Left today</div><div class="value">${usd(b.remainingUsd)}</div><div class="sub">of ${usd(b.dailyBudgetUsd)}</div></div>
|
|
528
|
+
<div class="card stat"><div class="label">Spent</div><div class="value">${usd(b.spentUsd)}</div><div class="sub">settled payments</div></div>
|
|
529
|
+
<div class="card stat"><div class="label">Held</div><div class="value">${usd(b.reservedUsd)}</div><div class="sub">approved, not used yet</div></div>
|
|
530
|
+
<div class="card stat"><div class="label">Daily limit</div><div class="value">${usd(b.dailyBudgetUsd)}</div><div class="sub">for the whole team</div></div>
|
|
531
|
+
</section>
|
|
532
|
+
|
|
533
|
+
<section class="card">
|
|
534
|
+
<div class="budget-bar">
|
|
535
|
+
<div class="row"><span class="label">Budget used</span><span class="num muted">${usd(used)} of ${usd(b.dailyBudgetUsd)}</span></div>
|
|
536
|
+
<progress class="${ratio >= 1 ? 'full' : ratio >= 0.8 ? 'high' : ''}" max="${b.dailyBudgetUsd || 1}" value="${Math.min(used, b.dailyBudgetUsd || 1)}" aria-label="Budget used"></progress>
|
|
537
|
+
</div>
|
|
538
|
+
<div class="counts">
|
|
539
|
+
<div><div class="value">${c.requestsToday ?? 0}</div><div class="label">Requests</div></div>
|
|
540
|
+
<div><div class="value">${c.blockedToday ?? 0}</div><div class="label">Blocked</div></div>
|
|
541
|
+
<div><div class="value">${c.paymentsToday ?? 0}</div><div class="label">Payments</div></div>
|
|
542
|
+
<div><div class="value">${c.deniedToday ?? 0}</div><div class="label">Payments refused</div></div>
|
|
543
|
+
</div>
|
|
544
|
+
</section>
|
|
545
|
+
|
|
546
|
+
<section class="card">
|
|
547
|
+
<div class="card-head"><div><h2>Waiting for a person</h2><p>Payments Blocknet held for review.</p></div>
|
|
548
|
+
${o.pending?.length ? h`<a class="btn btn-sm" href="#/approvals">All approvals</a>` : ''}</div>
|
|
549
|
+
${approvalsTable(o.pending ?? [], 'Nothing waiting for you.')}
|
|
550
|
+
</section>
|
|
551
|
+
|
|
552
|
+
<div class="grid-2">
|
|
553
|
+
<section class="card">
|
|
554
|
+
<div class="card-head"><div><h2>Agents</h2><p>Spend today against each agent's budget.</p></div>
|
|
555
|
+
${can('agents.view') ? h`<a class="btn btn-sm" href="#/agents">Manage</a>` : ''}</div>
|
|
556
|
+
${
|
|
557
|
+
o.agents?.length
|
|
558
|
+
? h`<div class="table-wrap"><table>
|
|
559
|
+
<thead><tr><th>Agent</th><th>Spent</th><th>Held</th><th>Left</th><th>Budget</th><th>Status</th></tr></thead>
|
|
560
|
+
<tbody>${o.agents.map(
|
|
561
|
+
(a) => h`<tr><td class="cell-strong">${a.name}</td><td class="num">${usd(a.spentUsd)}</td><td class="num">${usd(a.reservedUsd)}</td>
|
|
562
|
+
<td class="num">${usd(a.remainingUsd)}</td><td class="num">${usd(a.dailyBudgetUsd)}</td><td>${pill(a.disabled ? 'disabled' : 'active')}</td></tr>`,
|
|
563
|
+
)}</tbody></table></div>`
|
|
564
|
+
: h`<p class="empty">No agents yet. Every caller counts as one agent, with no key needed.</p>`
|
|
565
|
+
}
|
|
566
|
+
</section>
|
|
567
|
+
|
|
568
|
+
<section class="card">
|
|
569
|
+
<div class="card-head"><div><h2>Recent activity</h2></div>${can('audit.view') ? h`<a class="btn btn-sm" href="#/activity">All activity</a>` : ''}</div>
|
|
570
|
+
${
|
|
571
|
+
o.recent?.length
|
|
572
|
+
? h`<ul class="feed">${o.recent.map(
|
|
573
|
+
(e) => h`<li><span class="t">${clock(e.ts)}</span><div class="what">${typePill(e.type)} ${e.host ? h`<span class="host">${e.host}</span>` : ''} ${describe(e)}${e.agent ? h` <span class="faint">· ${e.agent}</span>` : ''}</div></li>`,
|
|
574
|
+
)}</ul>`
|
|
575
|
+
: h`<p class="empty">No traffic yet.</p>`
|
|
576
|
+
}
|
|
577
|
+
</section>
|
|
578
|
+
</div>`,
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// ---------- Approvals ----------
|
|
583
|
+
|
|
584
|
+
async function renderApprovals(view) {
|
|
585
|
+
const token = ++state.renderToken;
|
|
586
|
+
const status = state.approvalStatus;
|
|
587
|
+
const q = new URLSearchParams({ limit: '100' });
|
|
588
|
+
if (status !== 'all') q.set('status', status);
|
|
589
|
+
const { approvals } = await api(`/admin/api/approvals?${q}`);
|
|
590
|
+
if (status === 'pending') setPendingCount(approvals.length);
|
|
591
|
+
const tabs = ['pending', 'approved', 'denied', 'all'];
|
|
592
|
+
paint(
|
|
593
|
+
view,
|
|
594
|
+
token,
|
|
595
|
+
h`
|
|
596
|
+
<div class="page-head"><div><h1>Approvals</h1><p>Every payment decision. Approved payments are single use and expire after a few minutes.</p></div></div>
|
|
597
|
+
<section class="card">
|
|
598
|
+
<div class="tabs" role="tablist" aria-label="Status">
|
|
599
|
+
${tabs.map((t) => h`<button type="button" role="tab" aria-selected="${t === status}" data-action="approval-tab" data-status="${t}">${t[0].toUpperCase() + t.slice(1)}</button>`)}
|
|
600
|
+
</div>
|
|
601
|
+
${approvalsTable(approvals, status === 'pending' ? 'Nothing waiting for you.' : 'No approvals here yet.')}
|
|
602
|
+
</section>`,
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// ---------- Activity ----------
|
|
607
|
+
|
|
608
|
+
const ACTIVITY_TYPES = ['request', 'blocked', 'payment_decision', 'payment', 'payment_refused', 'approval', 'tunnel', 'notify_failed', 'admin', 'auth'];
|
|
609
|
+
|
|
610
|
+
function auditQuery(filters, extra = {}) {
|
|
611
|
+
const q = new URLSearchParams();
|
|
612
|
+
for (const k of ['type', 'agent', 'host', 'q']) if (filters[k]) q.set(k, filters[k]);
|
|
613
|
+
// Date inputs are local calendar days; send the whole local day as ISO times.
|
|
614
|
+
if (filters.from) q.set('from', new Date(`${filters.from}T00:00:00`).toISOString());
|
|
615
|
+
if (filters.to) q.set('to', new Date(`${filters.to}T23:59:59.999`).toISOString());
|
|
616
|
+
for (const [k, v] of Object.entries(extra)) if (v != null) q.set(k, v);
|
|
617
|
+
return q;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
async function renderActivity(view) {
|
|
621
|
+
const token = ++state.renderToken;
|
|
622
|
+
const f = state.activity.filters;
|
|
623
|
+
const data = await api(`/admin/api/audit?${auditQuery(f, { limit: 100 })}`);
|
|
624
|
+
state.activity.entries = data.entries;
|
|
625
|
+
state.activity.next = data.next;
|
|
626
|
+
const exportQ = auditQuery(f);
|
|
627
|
+
paint(
|
|
628
|
+
view,
|
|
629
|
+
token,
|
|
630
|
+
h`
|
|
631
|
+
<div class="page-head"><div><h1>Activity</h1><p>The audit log: every request, decision, payment and admin action, with its reason.</p></div>
|
|
632
|
+
<div class="page-actions">
|
|
633
|
+
${
|
|
634
|
+
planOf().features?.auditExport
|
|
635
|
+
? h`<a class="btn" href="/admin/api/audit/export?${raw(esc(new URLSearchParams({ format: 'csv', ...Object.fromEntries(exportQ) }).toString()))}" download>Export CSV</a>
|
|
636
|
+
<a class="btn" href="/admin/api/audit/export?${raw(esc(new URLSearchParams({ format: 'jsonl', ...Object.fromEntries(exportQ) }).toString()))}" download>Export JSONL</a>`
|
|
637
|
+
: h`<button type="button" class="btn" data-action="upgrade" data-feature="Audit log export" data-plan="Team">Export <span class="pill pill-plan">Team</span></button>`
|
|
638
|
+
}
|
|
639
|
+
</div></div>
|
|
640
|
+
<section class="card">
|
|
641
|
+
<form class="filters" data-form="activity-filters">
|
|
642
|
+
<div class="field"><label for="af-type">Type</label><select id="af-type" name="type"><option value="">All types</option>
|
|
643
|
+
${ACTIVITY_TYPES.map((t) => h`<option value="${t}" ${f.type === t ? raw('selected') : ''}>${TYPE_LABEL[t]}</option>`)}</select></div>
|
|
644
|
+
<div class="field"><label for="af-agent">Agent</label><input id="af-agent" name="agent" type="text" value="${f.agent ?? ''}" placeholder="Any"></div>
|
|
645
|
+
<div class="field"><label for="af-host">Service</label><input id="af-host" name="host" type="text" value="${f.host ?? ''}" placeholder="Host contains"></div>
|
|
646
|
+
<div class="field"><label for="af-q">Text</label><input id="af-q" name="q" type="search" value="${f.q ?? ''}" placeholder="Any field"></div>
|
|
647
|
+
<div class="field"><label for="af-from">From</label><input id="af-from" name="from" type="date" value="${f.from ?? ''}"></div>
|
|
648
|
+
<div class="field"><label for="af-to">To</label><input id="af-to" name="to" type="date" value="${f.to ?? ''}"></div>
|
|
649
|
+
<div class="filter-actions"><button type="submit" class="btn btn-primary">Filter</button><button type="button" class="btn" data-action="activity-clear">Clear</button></div>
|
|
650
|
+
</form>
|
|
651
|
+
<div id="activity-rows">${activityRows(state.activity.entries)}</div>
|
|
652
|
+
<div class="load-more" id="activity-more" ${data.next ? '' : raw('hidden')}><button type="button" class="btn" data-action="activity-more">Load more</button></div>
|
|
653
|
+
</section>`,
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const activityRows = (entries) =>
|
|
658
|
+
entries.length
|
|
659
|
+
? h`<div class="table-wrap"><table>
|
|
660
|
+
<thead><tr><th>Time</th><th>Event</th><th>Agent</th><th>Service</th><th>Detail</th></tr></thead>
|
|
661
|
+
<tbody>${entries.map(
|
|
662
|
+
(e) => h`<tr>
|
|
663
|
+
<td class="nowrap num">${toDate(e.ts)?.toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'medium' }) ?? ''}</td>
|
|
664
|
+
<td>${typePill(e.type)}</td>
|
|
665
|
+
<td>${e.agent ?? h`<span class="faint">—</span>`}</td>
|
|
666
|
+
<td>${e.host ?? h`<span class="faint">—</span>`}</td>
|
|
667
|
+
<td>${describe(e)}</td>
|
|
668
|
+
</tr>`,
|
|
669
|
+
)}</tbody></table></div>`
|
|
670
|
+
: h`<p class="empty">Nothing matches these filters.</p>`;
|
|
671
|
+
|
|
672
|
+
// ---------- Agents ----------
|
|
673
|
+
|
|
674
|
+
async function renderAgents(view) {
|
|
675
|
+
const token = ++state.renderToken;
|
|
676
|
+
const { agents } = await api('/admin/api/agents');
|
|
677
|
+
state.agents = agents;
|
|
678
|
+
const manage = can('agents.manage');
|
|
679
|
+
paint(
|
|
680
|
+
view,
|
|
681
|
+
token,
|
|
682
|
+
h`
|
|
683
|
+
<div class="page-head"><div><h1>Agents</h1><p>Each agent has its own key and limits. Its limits can only be stricter than the team's policy. Changes apply at once.</p></div>
|
|
684
|
+
${manage ? h`<div class="page-actions"><button type="button" class="btn btn-primary" data-action="agent-create">Add agent</button></div>` : ''}</div>
|
|
685
|
+
<section class="card">
|
|
686
|
+
${
|
|
687
|
+
agents.length
|
|
688
|
+
? h`<div class="table-wrap"><table>
|
|
689
|
+
<thead><tr><th>Agent</th><th>Budget per day</th><th>Per request</th><th>Today</th><th>Key</th><th>Status</th>${manage ? h`<th><span class="sr-only">Actions</span></th>` : ''}</tr></thead>
|
|
690
|
+
<tbody>${agents.map(
|
|
691
|
+
(a) => h`<tr>
|
|
692
|
+
<td><div class="cell-strong">${a.name}</div>${a.createdAt ? h`<div class="cell-sub">added ${ago(a.createdAt)}</div>` : ''}${a.network?.deny?.length ? h`<div class="cell-sub">${a.network.deny.length} extra deny rule${a.network.deny.length === 1 ? '' : 's'}</div>` : ''}</td>
|
|
693
|
+
<td class="num">${a.payments?.dailyBudgetUsd != null ? usd(a.payments.dailyBudgetUsd) : h`<span class="faint">team budget</span>`}</td>
|
|
694
|
+
<td class="num">${a.payments?.maxPerRequestUsd != null ? usd(a.payments.maxPerRequestUsd) : h`<span class="faint">policy cap</span>`}</td>
|
|
695
|
+
<td class="num nowrap">${usd(a.today?.spentUsd)} spent<div class="cell-sub">${usd(a.today?.remainingUsd)} left</div></td>
|
|
696
|
+
<td><code>${a.keyPreview ?? '—'}</code></td>
|
|
697
|
+
<td>${pill(a.disabled ? 'disabled' : 'active')}</td>
|
|
698
|
+
${
|
|
699
|
+
manage
|
|
700
|
+
? h`<td class="actions">
|
|
701
|
+
<button type="button" class="btn btn-sm" data-action="agent-edit" data-name="${a.name}">Edit</button>
|
|
702
|
+
<button type="button" class="btn btn-sm" data-action="agent-rotate" data-name="${a.name}">Rotate key</button>
|
|
703
|
+
<button type="button" class="btn btn-sm" data-action="agent-toggle" data-name="${a.name}">${a.disabled ? 'Enable' : 'Disable'}</button>
|
|
704
|
+
<button type="button" class="btn btn-sm btn-danger" data-action="agent-delete" data-name="${a.name}">Delete</button>
|
|
705
|
+
</td>`
|
|
706
|
+
: ''
|
|
707
|
+
}
|
|
708
|
+
</tr>`,
|
|
709
|
+
)}</tbody></table></div>`
|
|
710
|
+
: h`<div class="empty"><p>No agents yet. Without agents, every caller is one agent and needs no key.</p>${manage ? h`<p class="small">Add one to give it a key and its own budget. Once any agent exists, every call needs a key.</p>` : ''}</div>`
|
|
711
|
+
}
|
|
712
|
+
</section>`,
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function agentForm(a, { create }) {
|
|
717
|
+
return h`<form novalidate>
|
|
718
|
+
<div class="dialog-head"><h2>${create ? 'Add agent' : `Edit ${a.name}`}</h2>
|
|
719
|
+
<p>${create ? "You'll get its key once, after you save." : 'Leave a limit empty to use the team policy.'}</p></div>
|
|
720
|
+
<div class="dialog-body">
|
|
721
|
+
<p class="form-error"></p>
|
|
722
|
+
${create ? h`<div class="field"><label for="ag-name">Name</label><input id="ag-name" name="name" type="text" required pattern="[A-Za-z0-9_.\\-]{1,40}" maxlength="40" autocomplete="off"><span class="hint">Letters, digits, dot, dash or underscore.</span></div>` : ''}
|
|
723
|
+
<div class="form-grid">
|
|
724
|
+
<div class="field"><label for="ag-budget">Daily budget (USD)</label><input id="ag-budget" name="dailyBudgetUsd" type="number" min="0" step="any" inputmode="decimal" value="${a?.payments?.dailyBudgetUsd ?? ''}" placeholder="Team budget"></div>
|
|
725
|
+
<div class="field"><label for="ag-max">Max per request (USD)</label><input id="ag-max" name="maxPerRequestUsd" type="number" min="0" step="any" inputmode="decimal" value="${a?.payments?.maxPerRequestUsd ?? ''}" placeholder="Policy cap"></div>
|
|
726
|
+
<div class="field"><label for="ag-review">Ask a person above (USD)</label><input id="ag-review" name="reviewAboveUsd" type="number" min="0" step="any" inputmode="decimal" value="${a?.payments?.reviewAboveUsd ?? ''}" placeholder="Policy threshold"></div>
|
|
727
|
+
</div>
|
|
728
|
+
<div class="field"><label for="ag-deny">Extra blocked hosts</label><textarea id="ag-deny" name="deny" placeholder="*.social-media.com">${(a?.network?.deny ?? []).join('\n')}</textarea><span class="hint">One host pattern per line. Added to the team's deny list.</span></div>
|
|
729
|
+
</div>
|
|
730
|
+
<div class="dialog-foot"><button type="button" class="btn" data-close="cancel">Cancel</button><button type="submit" class="btn btn-primary">${create ? 'Add agent' : 'Save'}</button></div>
|
|
731
|
+
</form>`;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function agentBody(form, existing) {
|
|
735
|
+
const d = formData(form);
|
|
736
|
+
const payments = {};
|
|
737
|
+
for (const k of ['dailyBudgetUsd', 'maxPerRequestUsd', 'reviewAboveUsd']) {
|
|
738
|
+
const n = numOrNull(d[k]);
|
|
739
|
+
if (n != null) {
|
|
740
|
+
if (!Number.isFinite(n) || n < 0) throw new ApiError('Limits must be dollar amounts of 0 or more.', 400);
|
|
741
|
+
payments[k] = n;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
// Keep payment settings the console doesn't edit (allowed networks, assets).
|
|
745
|
+
for (const k of ['allowedNetworks', 'allowedAssets']) if (existing?.payments?.[k]) payments[k] = existing.payments[k];
|
|
746
|
+
const network = { ...(existing?.network ?? {}), deny: lines(d.deny) };
|
|
747
|
+
if (!network.deny.length) delete network.deny;
|
|
748
|
+
return { name: d.name?.trim(), payments, network };
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const findAgent = (name) => (state.agents ?? []).find((a) => a.name === name);
|
|
752
|
+
|
|
753
|
+
// ---------- Policy ----------
|
|
754
|
+
|
|
755
|
+
async function renderPolicy(view) {
|
|
756
|
+
const token = ++state.renderToken;
|
|
757
|
+
const p = await api('/admin/api/policy');
|
|
758
|
+
state.policy = p;
|
|
759
|
+
const manage = can('policy.manage');
|
|
760
|
+
const dis = manage ? '' : raw('disabled');
|
|
761
|
+
const n = p.network ?? {};
|
|
762
|
+
const pay = p.payments ?? {};
|
|
763
|
+
const t = p.trust ?? {};
|
|
764
|
+
const err = (field) => h`<p class="field-error" data-error-for="${field}"></p>`;
|
|
765
|
+
const section = (id, title, intro, body) => h`
|
|
766
|
+
<section class="card"><form data-form="policy" data-section="${id}" novalidate>
|
|
767
|
+
<div class="card-head"><div><h2>${title}</h2><p>${intro}</p></div></div>
|
|
768
|
+
<div class="card-body"><fieldset ${dis}>${body}</fieldset><p class="form-error" data-error-for="${id}"></p></div>
|
|
769
|
+
${manage ? h`<div class="card-foot"><span class="saved-note" role="status"></span>${['network', 'payments', 'trust'].includes(id) ? h`<button type="button" class="btn" data-action="policy-test" data-section="${id}">Test on last 30 days</button>` : ''}<button type="submit" class="btn btn-primary">Save ${title.toLowerCase()}</button></div>` : ''}
|
|
770
|
+
</form></section>`;
|
|
771
|
+
const opt = (value, current, label = value) => h`<option value="${value}" ${current === value ? raw('selected') : ''}>${label}</option>`;
|
|
772
|
+
const decision = (name, current) => h`<select id="${name}" name="${name}">${opt('allow', current, 'Allow')}${opt('review', current, 'Ask a person')}${opt('deny', current, 'Refuse')}</select>`;
|
|
773
|
+
|
|
774
|
+
paint(
|
|
775
|
+
view,
|
|
776
|
+
token,
|
|
777
|
+
h`
|
|
778
|
+
<div class="page-head"><div><h1>Policy</h1><p>The team's rules. Agents can only be stricter. Each section saves on its own and applies at once. Test a change on recorded traffic before you save it; every earlier version can be restored.</p></div></div>
|
|
779
|
+
${manage ? '' : h`<p class="readonly-note">You can view the policy. Ask an admin to change it.</p>`}
|
|
780
|
+
${await advisorCard(manage)}
|
|
781
|
+
|
|
782
|
+
${section('network', 'Network', 'What agents may reach. Deny rules win over allow rules.', h`
|
|
783
|
+
<div class="form-grid">
|
|
784
|
+
<div class="field"><label for="network.default">When no rule matches</label>
|
|
785
|
+
<select id="network.default" name="network.default">${opt('allow', n.default, 'Allow')}${opt('deny', n.default, 'Refuse (allowlist only)')}</select>${err('network.default')}</div>
|
|
786
|
+
<div class="field"><span class="label">Private networks</span>
|
|
787
|
+
<label class="check"><input type="checkbox" name="network.blockPrivateNetworks" ${n.blockPrivateNetworks ? raw('checked') : ''}> Block private, loopback and shared ranges</label>${err('network.blockPrivateNetworks')}</div>
|
|
788
|
+
<div class="field"><label for="network.allow">Allowed hosts</label><textarea id="network.allow" name="network.allow" placeholder="api.anthropic.com">${(n.allow ?? []).join('\n')}</textarea><span class="hint">One pattern per line, like <code>*.example.com</code>.</span>${err('network.allow')}</div>
|
|
789
|
+
<div class="field"><label for="network.deny">Blocked hosts</label><textarea id="network.deny" name="network.deny">${(n.deny ?? []).join('\n')}</textarea><span class="hint">Keep the cloud metadata hosts in this list.</span>${err('network.deny')}</div>
|
|
790
|
+
<div class="field span-2"><label for="network.blockAddresses">Blocked address ranges</label><textarea id="network.blockAddresses" name="network.blockAddresses">${(n.blockAddresses ?? []).join('\n')}</textarea><span class="hint">CIDR ranges, one per line. Checked against what each host name resolves to.</span>${err('network.blockAddresses')}</div>
|
|
791
|
+
</div>`)}
|
|
792
|
+
|
|
793
|
+
${section('payments', 'Payments', 'What agents may pay, per request and per day.', h`
|
|
794
|
+
<div class="form-grid">
|
|
795
|
+
<div class="field"><label for="payments.maxPerRequestUsd">Max per request (USD)</label><input id="payments.maxPerRequestUsd" name="payments.maxPerRequestUsd" type="number" min="0" step="any" value="${pay.maxPerRequestUsd ?? ''}">${err('payments.maxPerRequestUsd')}</div>
|
|
796
|
+
<div class="field"><label for="payments.dailyBudgetUsd">Team daily budget (USD)</label><input id="payments.dailyBudgetUsd" name="payments.dailyBudgetUsd" type="number" min="0" step="any" value="${pay.dailyBudgetUsd ?? ''}">${err('payments.dailyBudgetUsd')}</div>
|
|
797
|
+
<div class="field"><label for="payments.reviewAboveUsd">Ask a person above (USD)</label><input id="payments.reviewAboveUsd" name="payments.reviewAboveUsd" type="number" min="0" step="any" value="${pay.reviewAboveUsd ?? ''}">${err('payments.reviewAboveUsd')}</div>
|
|
798
|
+
<div class="field"><label for="payments.approvalTtlSeconds">Approval valid for (seconds)</label><input id="payments.approvalTtlSeconds" name="payments.approvalTtlSeconds" type="number" min="1" step="1" value="${pay.approvalTtlSeconds ?? ''}">${err('payments.approvalTtlSeconds')}</div>
|
|
799
|
+
<div class="field"><label for="payments.allowedNetworks">Payment networks</label><textarea id="payments.allowedNetworks" name="payments.allowedNetworks">${(pay.allowedNetworks ?? []).join('\n')}</textarea><span class="hint">One per line. Empty means any.</span>${err('payments.allowedNetworks')}</div>
|
|
800
|
+
<div class="field"><label for="payments.allowedAssets">Currencies</label><textarea id="payments.allowedAssets" name="payments.allowedAssets">${(pay.allowedAssets ?? []).join('\n')}</textarea><span class="hint">One per line. Empty means any.</span>${err('payments.allowedAssets')}</div>
|
|
801
|
+
</div>`)}
|
|
802
|
+
|
|
803
|
+
${section('trust', 'Trust', 'Which services agents may pay, from your scores and Blocknet\'s own record.', h`
|
|
804
|
+
<div class="form-grid">
|
|
805
|
+
<div class="field"><label for="trust.minScore">Minimum score (0 to 1)</label><input id="trust.minScore" name="trust.minScore" type="number" min="0" max="1" step="0.01" value="${t.minScore ?? ''}">${err('trust.minScore')}</div>
|
|
806
|
+
<div class="field"><label for="trust.unknown">Service with no score</label>${decision('trust.unknown', t.unknown)}${err('trust.unknown')}</div>
|
|
807
|
+
<div class="field"><label for="trust.belowMin">Score below the minimum</label>${decision('trust.belowMin', t.belowMin)}${err('trust.belowMin')}</div>
|
|
808
|
+
<div class="field span-2"><label for="trust.scores">Your scores</label><textarea id="trust.scores" name="trust.scores" placeholder="api.good-data.com = 0.9">${Object.entries(t.scores ?? {}).map(([k, v]) => `${k} = ${v}`).join('\n')}</textarea><span class="hint">One per line: <code>host pattern = score</code>.</span>${err('trust.scores')}</div>
|
|
809
|
+
</div>`)}
|
|
810
|
+
|
|
811
|
+
${section('notify', 'Notifications', 'Where Blocknet posts payments that wait for a person.', h`
|
|
812
|
+
<div class="field"><label for="notify.webhookUrl">Webhook URL</label><input id="notify.webhookUrl" name="notify.webhookUrl" type="url" value="${p.notify?.webhookUrl ?? ''}" placeholder="https://hooks.slack.com/services/…"><span class="hint">Works with Slack and Discord incoming webhooks, or your own endpoint. Empty turns it off.</span>${err('notify.webhookUrl')}</div>`)}
|
|
813
|
+
|
|
814
|
+
${section('proxy', 'Proxy mode', 'For tools that only know HTTP_PROXY and HTTPS_PROXY. Network rules only: payments still go through Blocknet\'s fetch.', h`
|
|
815
|
+
<label class="check"><input type="checkbox" name="proxy.enabled" ${p.proxy?.enabled ? raw('checked') : ''}> Accept proxy traffic</label>${err('proxy.enabled')}
|
|
816
|
+
<p class="hint">Turn on blocking of private networks too, so agents can't tunnel to internal services.</p>`)}
|
|
817
|
+
|
|
818
|
+
${section('advisor', 'Automatic tightening', "Team and Enterprise. Lets the advisor apply suggestions that only make the policy stricter, then watches each one and undoes it if it blocks too much. Anything less strict always waits for a person.", h`
|
|
819
|
+
<div class="form-grid">
|
|
820
|
+
<div class="field span-2"><label class="check"><input type="checkbox" name="advisor.autoTighten" ${p.advisor?.autoTighten ? raw('checked') : ''}> Apply stricter suggestions automatically</label>${err('advisor.autoTighten')}</div>
|
|
821
|
+
<div class="field"><label for="advisor.maxPerDay">At most per day</label><input id="advisor.maxPerDay" name="advisor.maxPerDay" type="number" min="1" max="20" step="1" value="${p.advisor?.maxPerDay ?? 3}">${err('advisor.maxPerDay')}</div>
|
|
822
|
+
<div class="field"><label for="advisor.watchHours">Watch each change for (hours)</label><input id="advisor.watchHours" name="advisor.watchHours" type="number" min="1" max="168" step="1" value="${p.advisor?.watchHours ?? 24}">${err('advisor.watchHours')}</div>
|
|
823
|
+
<div class="field"><label for="advisor.maxNewBlocks">Undo it after this many new blocks</label><input id="advisor.maxNewBlocks" name="advisor.maxNewBlocks" type="number" min="0" step="1" value="${p.advisor?.maxNewBlocks ?? 10}"><span class="hint">Requests blocked or payments refused because of the change, while it's watched.</span>${err('advisor.maxNewBlocks')}</div>
|
|
824
|
+
</div>`)}
|
|
825
|
+
`,
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ---------- improving the policy: replay tests, the advisor, versions ----------
|
|
830
|
+
|
|
831
|
+
/** One line for a replay: what would have been decided differently. Accepts a simulation or an advisor effect. */
|
|
832
|
+
function effectText(r) {
|
|
833
|
+
if (!r) return '';
|
|
834
|
+
const e = r.network
|
|
835
|
+
? { requestsNowBlocked: Math.max(0, r.network.blockedAfter - r.network.blockedBefore), requestsNowAllowed: Math.max(0, r.network.blockedBefore - r.network.blockedAfter), payments: r.payments, considered: r.considered }
|
|
836
|
+
: r;
|
|
837
|
+
const parts = [];
|
|
838
|
+
if (e.requestsNowBlocked) parts.push(`${e.requestsNowBlocked} request${e.requestsNowBlocked === 1 ? '' : 's'} would have been blocked`);
|
|
839
|
+
if (e.requestsNowAllowed) parts.push(`${e.requestsNowAllowed} blocked request${e.requestsNowAllowed === 1 ? '' : 's'} would have gone through`);
|
|
840
|
+
const b = e.payments?.before ?? {}, a = e.payments?.after ?? {};
|
|
841
|
+
const word = { allow: 'paid without asking', review: 'asked a person', deny: 'refused' };
|
|
842
|
+
for (const k of ['allow', 'review', 'deny']) if ((b[k] ?? 0) !== (a[k] ?? 0)) parts.push(`payments ${word[k]}: ${b[k] ?? 0} → ${a[k] ?? 0}`);
|
|
843
|
+
const on = `${e.considered?.requests ?? 0} requests and ${e.considered?.payments ?? 0} payment decisions`;
|
|
844
|
+
return parts.length ? `Replayed on ${on}: ${parts.join('; ')}.` : `Replayed on ${on}: no difference.`;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
function replayDialog(title, r) {
|
|
848
|
+
const flags = [];
|
|
849
|
+
if (r.loosens) flags.push(`${r.loosens} decision${r.loosens === 1 ? '' : 's'} would have been less strict.`);
|
|
850
|
+
if (r.humanDeniedNowAllowed) flags.push(`${r.humanDeniedNowAllowed} payment${r.humanDeniedNowAllowed === 1 ? '' : 's'} a person refused would have gone through.`);
|
|
851
|
+
if (r.humanApprovedNowDenied) flags.push(`${r.humanApprovedNowDenied} payment${r.humanApprovedNowDenied === 1 ? '' : 's'} a person approved would have been refused.`);
|
|
852
|
+
return openDialog(
|
|
853
|
+
h`<form>
|
|
854
|
+
<div class="dialog-head"><h2>${title}</h2></div>
|
|
855
|
+
<div class="dialog-body">
|
|
856
|
+
<p>${effectText(r)}</p>
|
|
857
|
+
${flags.length ? h`<p class="callout">${flags.join(' ')}</p>` : ''}
|
|
858
|
+
${r.changes?.length ? h`<div class="table-wrap"><table><thead><tr><th>When</th><th>Service</th><th>Was</th><th>Would be</th></tr></thead><tbody>${r.changes.slice(0, 12).map((c) => h`<tr><td>${ago(c.ts)}</td><td><code>${c.host}</code>${c.agent ? h` <span class="cell-sub">${c.agent}</span>` : ''}</td><td>${c.before}</td><td>${c.after}</td></tr>`)}</tbody></table></div>` : ''}
|
|
859
|
+
<p class="hint">${(r.limits ?? []).join(' ')}</p>
|
|
860
|
+
</div>
|
|
861
|
+
<div class="dialog-foot"><button type="submit" class="btn btn-primary">Close</button></div>
|
|
862
|
+
</form>`,
|
|
863
|
+
{ label: title },
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
async function advisorCard(manage) {
|
|
868
|
+
const plan = planOf();
|
|
869
|
+
const head = h`<div class="card-head"><div><h2>Advisor</h2><p>Changes Blocknet suggests from your team's own decisions and paid-call results. Each one is replayed on the last 30 days of traffic before it's shown, and nothing changes until someone applies it.</p></div>${plan.features?.advisor ? '' : h`<button type="button" class="btn btn-sm" data-action="upgrade" data-feature="The policy advisor" data-plan="Team">Advisor <span class="pill pill-plan">Team</span></button>`}</div>`;
|
|
870
|
+
let body;
|
|
871
|
+
if (!plan.features?.advisor) {
|
|
872
|
+
body = h`<div class="card-body"><p class="muted">On the Team and Enterprise plans, Blocknet proposes rules from what it sees: block services people keep refusing or that take money and fail, trust services that always deliver, lower budgets far above real spending. You see the evidence and the replayed effect, and you decide.</p></div>`;
|
|
873
|
+
} else {
|
|
874
|
+
let data;
|
|
875
|
+
try {
|
|
876
|
+
data = await api('/admin/api/advisor', { quiet: true });
|
|
877
|
+
} catch (err) {
|
|
878
|
+
if (!(err instanceof ApiError)) throw err;
|
|
879
|
+
return h`<section class="card">${head}<div class="card-body"><p class="callout">${err.message}</p></div></section>`;
|
|
880
|
+
}
|
|
881
|
+
const item = (p, staged) => h`<li class="advice">
|
|
882
|
+
<div class="advice-head"><strong>${p.title}</strong> ${p.tightens ? pill('stricter', 'ok') : pill('less strict', 'warn')}${staged ? h` ${pill('shadow test')}` : ''}</div>
|
|
883
|
+
<p>${p.why}</p>
|
|
884
|
+
<p class="muted small">${staged ? (p.live ? `Since ${clock(p.stagedAt)}: ${effectText(p.live)}` : 'No longer passes its safety check.') : effectText(p.effect)}</p>
|
|
885
|
+
${p.risk ? h`<p class="callout">${p.risk}</p>` : ''}
|
|
886
|
+
${manage ? h`<div class="advice-actions">
|
|
887
|
+
<button type="button" class="btn btn-sm btn-primary" data-action="advisor-apply" data-id="${p.id}" data-loosens="${p.tightens ? '' : '1'}" data-title="${p.title}">Apply</button>
|
|
888
|
+
${staged ? '' : h`<button type="button" class="btn btn-sm" data-action="advisor-stage" data-id="${p.id}">Shadow test</button>`}
|
|
889
|
+
<button type="button" class="btn btn-sm" data-action="advisor-dismiss" data-id="${p.id}">Dismiss</button></div>` : ''}
|
|
890
|
+
</li>`;
|
|
891
|
+
const list = [...data.staged.map((p) => item(p, true)), ...data.proposals.map((p) => item(p, false))];
|
|
892
|
+
body = list.length ? h`<ul class="advice-list">${list}</ul>` : h`<div class="card-body"><p class="muted">Nothing to suggest right now. Suggestions appear as people approve and refuse payments and as paid calls succeed or fail.</p></div>`;
|
|
893
|
+
const auto = data.auto ?? {};
|
|
894
|
+
const statusPill = (s) => pill({ watching: 'watching', kept: 'kept', undone: 'undone automatically', superseded: 'changed since' }[s] ?? s, s === 'undone' ? 'warn' : s === 'kept' ? 'ok' : '');
|
|
895
|
+
body = h`${body}<div class="card-body">
|
|
896
|
+
<h3 class="small-head">Automatic tightening: ${auto.autoTighten ? `on, up to ${auto.maxPerDay} a day, each watched for ${auto.watchHours} hours` : 'off'}</h3>
|
|
897
|
+
${auto.recent?.length
|
|
898
|
+
? h`<ul class="versions">${auto.recent.map((r) => h`<li><span>${r.title} · ${ago(r.appliedAt)} ${statusPill(r.status)}${r.newBlocks ? ` · ${r.newBlocks} new block${r.newBlocks === 1 ? '' : 's'}` : ''}</span></li>`)}</ul>`
|
|
899
|
+
: h`<p class="muted small">${auto.autoTighten ? 'Nothing applied yet. It checks every 10 minutes.' : 'Turn it on under Automatic tightening below.'}</p>`}
|
|
900
|
+
${manage && auto.autoTighten ? h`<div class="advice-actions"><button type="button" class="btn btn-sm" data-action="advisor-run">Run now</button></div>` : ''}
|
|
901
|
+
</div>`;
|
|
902
|
+
}
|
|
903
|
+
let versions = [];
|
|
904
|
+
try {
|
|
905
|
+
versions = (await api('/admin/api/policy/history?limit=8', { quiet: true })).versions;
|
|
906
|
+
} catch {}
|
|
907
|
+
const history = versions.length
|
|
908
|
+
? h`<div class="card-body"><h3 class="small-head">Earlier versions</h3><ul class="versions">${versions.map(
|
|
909
|
+
(v) => h`<li><span>v${v.version} · ${ago(v.ts)} · replaced by ${v.reason ?? 'a change'}${v.actor ? ` (${v.actor})` : ''}</span>${manage ? h`<button type="button" class="btn btn-sm" data-action="policy-restore" data-version="${v.version}">Restore</button>` : ''}</li>`,
|
|
910
|
+
)}</ul></div>`
|
|
911
|
+
: '';
|
|
912
|
+
return h`<section class="card">${head}${body}${history}</section>`;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
class FieldError extends Error {
|
|
916
|
+
constructor(field, message) {
|
|
917
|
+
super(message);
|
|
918
|
+
this.field = field;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function policySection(form, section) {
|
|
923
|
+
const d = new FormData(form);
|
|
924
|
+
const get = (k) => d.get(`${section}.${k}`);
|
|
925
|
+
const checked = (k) => d.get(`${section}.${k}`) === 'on';
|
|
926
|
+
const num = (k) => {
|
|
927
|
+
const n = numOrNull(get(k));
|
|
928
|
+
if (n != null && !Number.isFinite(n)) throw new FieldError(`${section}.${k}`, 'Enter a number.');
|
|
929
|
+
return n;
|
|
930
|
+
};
|
|
931
|
+
switch (section) {
|
|
932
|
+
case 'network':
|
|
933
|
+
return {
|
|
934
|
+
default: get('default'),
|
|
935
|
+
allow: lines(get('allow')),
|
|
936
|
+
deny: lines(get('deny')),
|
|
937
|
+
blockAddresses: lines(get('blockAddresses')),
|
|
938
|
+
blockPrivateNetworks: checked('blockPrivateNetworks'),
|
|
939
|
+
};
|
|
940
|
+
case 'payments':
|
|
941
|
+
return {
|
|
942
|
+
...(state.policy?.payments ?? {}),
|
|
943
|
+
maxPerRequestUsd: num('maxPerRequestUsd'),
|
|
944
|
+
dailyBudgetUsd: num('dailyBudgetUsd'),
|
|
945
|
+
reviewAboveUsd: num('reviewAboveUsd'),
|
|
946
|
+
approvalTtlSeconds: num('approvalTtlSeconds'),
|
|
947
|
+
allowedNetworks: lines(get('allowedNetworks')),
|
|
948
|
+
allowedAssets: lines(get('allowedAssets')),
|
|
949
|
+
};
|
|
950
|
+
case 'trust': {
|
|
951
|
+
const scores = {};
|
|
952
|
+
for (const line of lines(get('scores'))) {
|
|
953
|
+
const m = line.match(/^(.+?)\s*[=:]\s*([0-9.]+)$/);
|
|
954
|
+
if (!m) throw new FieldError('trust.scores', `Can't read "${line}". Use: host = 0.9`);
|
|
955
|
+
scores[m[1].trim()] = Number(m[2]);
|
|
956
|
+
}
|
|
957
|
+
return { ...(state.policy?.trust ?? {}), minScore: num('minScore'), unknown: get('unknown'), belowMin: get('belowMin'), scores };
|
|
958
|
+
}
|
|
959
|
+
case 'notify':
|
|
960
|
+
return { ...(state.policy?.notify ?? {}), webhookUrl: String(get('webhookUrl') ?? '').trim() || null };
|
|
961
|
+
case 'proxy':
|
|
962
|
+
return { ...(state.policy?.proxy ?? {}), enabled: checked('enabled') };
|
|
963
|
+
case 'advisor':
|
|
964
|
+
return { autoTighten: checked('autoTighten'), maxPerDay: num('maxPerDay'), watchHours: num('watchHours'), maxNewBlocks: num('maxNewBlocks') };
|
|
965
|
+
default:
|
|
966
|
+
throw new Error(`unknown section ${section}`);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function showFieldError(form, section, field, message) {
|
|
971
|
+
const slots = $$('[data-error-for]', form);
|
|
972
|
+
const slot = slots.find((s) => s.dataset.errorFor === field) ?? slots.find((s) => s.dataset.errorFor === section);
|
|
973
|
+
if (slot) slot.textContent = message;
|
|
974
|
+
const input = $$('[name]', form).find((i) => i.name === field);
|
|
975
|
+
if (input) {
|
|
976
|
+
input.setAttribute('aria-invalid', 'true');
|
|
977
|
+
input.focus();
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// ---------- Users ----------
|
|
982
|
+
|
|
983
|
+
async function renderUsers(view) {
|
|
984
|
+
const token = ++state.renderToken;
|
|
985
|
+
const { users } = await api('/admin/api/users');
|
|
986
|
+
state.users = users;
|
|
987
|
+
const myId = state.me.user.id;
|
|
988
|
+
paint(
|
|
989
|
+
view,
|
|
990
|
+
token,
|
|
991
|
+
h`
|
|
992
|
+
<div class="page-head"><div><h1>Users</h1><p>Who can use this console. Viewers can look, approvers can also decide on payments, admins can change everything.</p>
|
|
993
|
+
<p class="hint">${planOf().seats == null ? `${users.filter((x) => !x.disabled).length} active users on ${planOf().name}, no limit.` : `${users.filter((x) => !x.disabled).length} of ${planOf().seats} console users on the ${planOf().name} plan.`}${planOf().seats != null && users.filter((x) => !x.disabled).length >= planOf().seats ? h` <a href="${UPGRADE_MAIL}">Get more seats</a>` : ''}</p></div>
|
|
994
|
+
<div class="page-actions"><button type="button" class="btn btn-primary" data-action="user-create">Add user</button></div></div>
|
|
995
|
+
<section class="card">
|
|
996
|
+
${
|
|
997
|
+
users.length
|
|
998
|
+
? h`<div class="table-wrap"><table>
|
|
999
|
+
<thead><tr><th>Name</th><th>Role</th><th>Status</th><th>Last sign-in</th><th><span class="sr-only">Actions</span></th></tr></thead>
|
|
1000
|
+
<tbody>${users.map((u) => {
|
|
1001
|
+
const self = u.id === myId;
|
|
1002
|
+
return h`<tr>
|
|
1003
|
+
<td><div class="cell-strong">${u.name || u.email}${self ? h` <span class="faint">(you)</span>` : ''}</div><div class="cell-sub">${u.email}</div></td>
|
|
1004
|
+
<td>
|
|
1005
|
+
<label class="sr-only" for="role-${u.id}">Role for ${u.email}</label>
|
|
1006
|
+
<select id="role-${u.id}" data-change="user-role" data-id="${u.id}" ${self || u.sso ? raw('disabled') : ''} ${u.sso ? raw('title="Set by your identity provider at each sign-in"') : ''}>
|
|
1007
|
+
${['viewer', 'approver', 'admin'].map((r) => h`<option value="${r}" ${u.role === r ? raw('selected') : ''}>${r[0].toUpperCase() + r.slice(1)}</option>`)}
|
|
1008
|
+
</select>
|
|
1009
|
+
${u.sso ? h`<div class="cell-sub">${pill('SSO')} role from your identity provider</div>` : ''}
|
|
1010
|
+
</td>
|
|
1011
|
+
<td>${pill(u.disabled ? 'disabled' : 'active')}</td>
|
|
1012
|
+
<td class="nowrap">${u.lastLoginAt ? timeEl(u.lastLoginAt) : h`<span class="faint">never</span>`}</td>
|
|
1013
|
+
<td class="actions">${
|
|
1014
|
+
self
|
|
1015
|
+
? ''
|
|
1016
|
+
: h`${u.sso ? '' : h`<button type="button" class="btn btn-sm" data-action="user-reset" data-id="${u.id}">Reset password</button>`}
|
|
1017
|
+
<button type="button" class="btn btn-sm" data-action="user-toggle" data-id="${u.id}">${u.disabled ? 'Enable' : 'Disable'}</button>
|
|
1018
|
+
<button type="button" class="btn btn-sm btn-danger" data-action="user-delete" data-id="${u.id}">Delete</button>`
|
|
1019
|
+
}</td>
|
|
1020
|
+
</tr>`;
|
|
1021
|
+
})}</tbody></table></div>`
|
|
1022
|
+
: h`<p class="empty">No users yet.</p>`
|
|
1023
|
+
}
|
|
1024
|
+
</section>
|
|
1025
|
+
${state.sso.enabled ? h`<p class="hint">People who sign in with ${state.sso.label || 'SSO'} are added here automatically, with the role their groups map to.</p>` : ''}`,
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const findUser = (id) => (state.users ?? []).find((u) => u.id === id);
|
|
1030
|
+
|
|
1031
|
+
// ---------- Settings ----------
|
|
1032
|
+
|
|
1033
|
+
async function renderSettings(view) {
|
|
1034
|
+
const token = ++state.renderToken;
|
|
1035
|
+
const u = state.me.user;
|
|
1036
|
+
const sys = can('system.view') ? await api('/admin/api/system', { quiet: true }).catch(() => null) : null;
|
|
1037
|
+
paint(
|
|
1038
|
+
view,
|
|
1039
|
+
token,
|
|
1040
|
+
h`
|
|
1041
|
+
<div class="page-head"><div><h1>Settings</h1><p>Your account, and how this Blocknet is set up.</p></div></div>
|
|
1042
|
+
${planCard(sys?.plan ?? planOf())}
|
|
1043
|
+
<div class="grid-2">
|
|
1044
|
+
<section class="card">
|
|
1045
|
+
<div class="card-head"><div><h2>Your account</h2><p>${u.email} · ${rolePill(u.role)}</p></div></div>
|
|
1046
|
+
${
|
|
1047
|
+
u.sso
|
|
1048
|
+
? h`<div class="card-body"><p class="muted">You sign in with ${state.sso.label || 'SSO'}. Change your password with your identity provider.</p></div>`
|
|
1049
|
+
: h`<form data-form="change-password" novalidate>
|
|
1050
|
+
<div class="card-body"><div class="form-grid">
|
|
1051
|
+
<p class="form-error span-2"></p>
|
|
1052
|
+
<div class="field span-2"><label for="cp-current">Current password</label><input id="cp-current" name="current" type="password" autocomplete="current-password" required></div>
|
|
1053
|
+
<div class="field"><label for="cp-next">New password</label><input id="cp-next" name="next" type="password" autocomplete="new-password" minlength="12" required><span class="hint">At least 12 characters.</span></div>
|
|
1054
|
+
<div class="field"><label for="cp-confirm">Confirm new password</label><input id="cp-confirm" name="confirm" type="password" autocomplete="new-password" required></div>
|
|
1055
|
+
</div></div>
|
|
1056
|
+
<div class="card-foot"><button type="submit" class="btn btn-primary">Change password</button></div>
|
|
1057
|
+
</form>`
|
|
1058
|
+
}
|
|
1059
|
+
<div class="card-foot"><span class="muted small">Signed in somewhere you shouldn't be?</span><button type="button" class="btn btn-danger" data-action="logout-all">Sign out everywhere</button></div>
|
|
1060
|
+
</section>
|
|
1061
|
+
|
|
1062
|
+
${
|
|
1063
|
+
sys
|
|
1064
|
+
? h`<section class="card">
|
|
1065
|
+
<div class="card-head"><div><h2>System</h2><p>Read-only.</p></div></div>
|
|
1066
|
+
<dl class="kv">
|
|
1067
|
+
<dt>Version</dt><dd class="num">${sys.version}</dd>
|
|
1068
|
+
<dt>Running for</dt><dd>${duration(sys.uptimeSeconds)}</dd>
|
|
1069
|
+
<dt>Gateway</dt><dd><code>${sys.gatewayUrl ?? '—'}</code></dd>
|
|
1070
|
+
<dt>Console</dt><dd><code>${sys.adminUrl ?? sys.gatewayUrl ?? '—'}</code></dd>
|
|
1071
|
+
<dt>Agents</dt><dd>${sys.agentsEnabled ? 'Keys required' : 'One agent, no key needed'}</dd>
|
|
1072
|
+
<dt>Proxy mode</dt><dd>${sys.proxyEnabled ? 'On' : 'Off'}</dd>
|
|
1073
|
+
<dt>Single sign-on</dt><dd>${sys.sso?.enabled ? h`<code>${sys.sso.issuer}</code>` : 'Off'}</dd>
|
|
1074
|
+
<dt>Data folder</dt><dd><code>${sys.home ?? '—'}</code></dd>
|
|
1075
|
+
<dt>Config file</dt><dd><code>${sys.configFile ?? 'none, safe defaults'}</code></dd>
|
|
1076
|
+
<dt>Audit log</dt><dd><code>${sys.auditLog ?? 'in memory'}</code></dd>
|
|
1077
|
+
</dl>
|
|
1078
|
+
</section>`
|
|
1079
|
+
: ''
|
|
1080
|
+
}
|
|
1081
|
+
</div>
|
|
1082
|
+
${
|
|
1083
|
+
sys?.signingPublicKey
|
|
1084
|
+
? h`<section class="card">
|
|
1085
|
+
<div class="card-head"><div><h2>Approval signing key</h2><p>Wallet code checks approvals with this public key. Copy it into your wallet's config.</p></div>
|
|
1086
|
+
<button type="button" class="btn btn-sm" data-action="copy" data-copy="signing-key">Copy</button></div>
|
|
1087
|
+
<div class="card-body"><pre class="key" id="signing-key">${sys.signingPublicKey}</pre></div>
|
|
1088
|
+
</section>`
|
|
1089
|
+
: ''
|
|
1090
|
+
}`,
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function planCard(p) {
|
|
1095
|
+
const yes = (b) => (b ? h`${pill('included')}` : h`<span class="faint">not included</span>`);
|
|
1096
|
+
return h`<section class="card">
|
|
1097
|
+
<div class="card-head"><div><h2>Plan: ${p.name}</h2><p>${
|
|
1098
|
+
p.license ? `Licensed to ${p.license.customer}, until ${String(p.license.expiresAt).slice(0, 10)}.` : 'Free to run. Network rules, payment decisions, budgets, agents and approvals are the same on every plan.'
|
|
1099
|
+
}</p></div>${p.plan !== 'enterprise' ? h`<a class="btn btn-sm" href="${UPGRADE_MAIL}">Talk to us about ${p.plan === 'team' ? 'Enterprise' : 'Team or Enterprise'}</a>` : ''}</div>
|
|
1100
|
+
${p.message ? h`<div class="card-body"><p class="callout">${p.message}</p></div>` : ''}
|
|
1101
|
+
<dl class="kv">
|
|
1102
|
+
<dt>Console users</dt><dd>${p.seats == null ? `${p.seatsUsed} (no limit)` : `${p.seatsUsed} of ${p.seats}`}</dd>
|
|
1103
|
+
<dt>Audit log export</dt><dd>${yes(p.features?.auditExport)}</dd>
|
|
1104
|
+
<dt>Prometheus metrics</dt><dd>${yes(p.features?.metrics)}</dd>
|
|
1105
|
+
<dt>Policy advisor</dt><dd>${yes(p.features?.advisor)}</dd>
|
|
1106
|
+
<dt>Single sign-on</dt><dd>${yes(p.features?.sso)}</dd>
|
|
1107
|
+
<dt>Enterprise package</dt><dd>${
|
|
1108
|
+
p.enterprisePackage ? `installed (${p.enterprisePackage.version ?? 'unknown version'})` : p.plan === 'free' ? h`<span class="faint">not needed on Free</span>` : 'not installed: it comes with your licence; put it in ~/.blocknet/enterprise'
|
|
1109
|
+
}</dd>
|
|
1110
|
+
</dl>
|
|
1111
|
+
</section>`;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// ---------- Actions (click delegation) ----------
|
|
1115
|
+
|
|
1116
|
+
const actions = {
|
|
1117
|
+
async logout() {
|
|
1118
|
+
await api('/admin/api/logout', { method: 'POST', quiet: true, noRedirect: true }).catch(() => {});
|
|
1119
|
+
signedOut({ sso: state.sso });
|
|
1120
|
+
await boot();
|
|
1121
|
+
},
|
|
1122
|
+
|
|
1123
|
+
async 'policy-test'(btn) {
|
|
1124
|
+
const form = btn.closest('form');
|
|
1125
|
+
const section = btn.dataset.section;
|
|
1126
|
+
$$('[data-error-for]', form).forEach((s) => (s.textContent = ''));
|
|
1127
|
+
let body;
|
|
1128
|
+
try {
|
|
1129
|
+
body = policySection(form, section);
|
|
1130
|
+
} catch (err) {
|
|
1131
|
+
if (err instanceof FieldError) return showFieldError(form, section, err.field, err.message);
|
|
1132
|
+
throw err;
|
|
1133
|
+
}
|
|
1134
|
+
try {
|
|
1135
|
+
const r = await api('/admin/api/policy/simulate', { method: 'POST', body: { policy: { [section]: body }, days: 30 }, quiet: true });
|
|
1136
|
+
await replayDialog('This change on the last 30 days', r);
|
|
1137
|
+
} catch (err) {
|
|
1138
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1139
|
+
showFieldError(form, section, err.data?.field ?? section, err.message);
|
|
1140
|
+
}
|
|
1141
|
+
},
|
|
1142
|
+
|
|
1143
|
+
async 'advisor-apply'(btn) {
|
|
1144
|
+
const loosens = Boolean(btn.dataset.loosens);
|
|
1145
|
+
const ok = await confirmDialog({
|
|
1146
|
+
title: `${btn.dataset.title}?`,
|
|
1147
|
+
body: loosens
|
|
1148
|
+
? 'This makes the policy less strict. It applies at once; you can restore the previous version from Policy.'
|
|
1149
|
+
: 'This applies at once. You can restore the previous version from Policy.',
|
|
1150
|
+
confirm: 'Apply',
|
|
1151
|
+
danger: loosens,
|
|
1152
|
+
});
|
|
1153
|
+
if (!ok) return;
|
|
1154
|
+
const r = await api(`/admin/api/advisor/${btn.dataset.id}/apply`, { method: 'POST', body: { confirm: loosens } });
|
|
1155
|
+
toast(`Applied: ${r.title}. To undo, restore v${r.rollbackVersion}.`, 'ok');
|
|
1156
|
+
await rerender();
|
|
1157
|
+
},
|
|
1158
|
+
|
|
1159
|
+
async 'advisor-stage'(btn) {
|
|
1160
|
+
await api(`/admin/api/advisor/${btn.dataset.id}/stage`, { method: 'POST' });
|
|
1161
|
+
toast('Shadow test started: nothing changes; you\'ll see what it would have done on new traffic.', 'ok');
|
|
1162
|
+
await rerender();
|
|
1163
|
+
},
|
|
1164
|
+
|
|
1165
|
+
async 'advisor-run'() {
|
|
1166
|
+
const r = await api('/admin/api/advisor/run', { method: 'POST' });
|
|
1167
|
+
const undone = (r.watched ?? []).filter((w) => w.status === 'undone');
|
|
1168
|
+
toast(r.applied ? `Applied automatically: ${r.applied.title}.` : undone.length ? `Undone: ${undone.map((w) => w.title).join(', ')}.` : `Nothing applied: ${r.skipped ?? 'nothing to do'}.`, r.applied ? 'ok' : '');
|
|
1169
|
+
await rerender();
|
|
1170
|
+
},
|
|
1171
|
+
|
|
1172
|
+
async 'advisor-dismiss'(btn) {
|
|
1173
|
+
await api(`/admin/api/advisor/${btn.dataset.id}/dismiss`, { method: 'POST' });
|
|
1174
|
+
await rerender();
|
|
1175
|
+
},
|
|
1176
|
+
|
|
1177
|
+
async 'policy-restore'(btn) {
|
|
1178
|
+
const v = btn.dataset.version;
|
|
1179
|
+
if (!(await confirmDialog({ title: `Restore version ${v}?`, body: 'Puts back the policy and agent limits as they were. Agent keys stay as they are now.', confirm: 'Restore' }))) return;
|
|
1180
|
+
await api(`/admin/api/policy/history/${v}/rollback`, { method: 'POST' });
|
|
1181
|
+
toast(`Restored version ${v}.`, 'ok');
|
|
1182
|
+
await rerender();
|
|
1183
|
+
},
|
|
1184
|
+
|
|
1185
|
+
upgrade(el) {
|
|
1186
|
+
toast(`${el.dataset.feature} needs the ${el.dataset.plan} plan. Write to contact@acificlabs.com for a licence or a trial.`);
|
|
1187
|
+
},
|
|
1188
|
+
|
|
1189
|
+
async 'logout-all'() {
|
|
1190
|
+
if (!(await confirmDialog({ title: 'Sign out everywhere?', body: 'This ends all your sessions, including this one.', confirm: 'Sign out everywhere', danger: true }))) return;
|
|
1191
|
+
await api('/admin/api/account/logout-all', { method: 'POST', noRedirect: true });
|
|
1192
|
+
signedOut({ sso: state.sso });
|
|
1193
|
+
await boot();
|
|
1194
|
+
},
|
|
1195
|
+
|
|
1196
|
+
async copy(btn) {
|
|
1197
|
+
const el = document.getElementById(btn.dataset.copy);
|
|
1198
|
+
if (!el) return;
|
|
1199
|
+
const text = el.textContent;
|
|
1200
|
+
try {
|
|
1201
|
+
await navigator.clipboard.writeText(text);
|
|
1202
|
+
} catch {
|
|
1203
|
+
const range = document.createRange();
|
|
1204
|
+
range.selectNodeContents(el);
|
|
1205
|
+
const sel = getSelection();
|
|
1206
|
+
sel.removeAllRanges();
|
|
1207
|
+
sel.addRange(range);
|
|
1208
|
+
document.execCommand?.('copy');
|
|
1209
|
+
}
|
|
1210
|
+
const before = btn.textContent;
|
|
1211
|
+
btn.textContent = 'Copied';
|
|
1212
|
+
setTimeout(() => (btn.textContent = before), 1500);
|
|
1213
|
+
},
|
|
1214
|
+
|
|
1215
|
+
async decide(btn) {
|
|
1216
|
+
const verb = btn.dataset.verb;
|
|
1217
|
+
btn.disabled = true;
|
|
1218
|
+
try {
|
|
1219
|
+
const a = await api(`/admin/api/approvals/${encodeURIComponent(btn.dataset.id)}/${verb}`, { method: 'POST' });
|
|
1220
|
+
toast(`${verb === 'approve' ? 'Approved' : 'Denied'}: ${usd(a.option?.amountUsd)} ${a.option?.asset ?? ''} to ${a.host}`, verb === 'approve' ? 'ok' : '');
|
|
1221
|
+
} finally {
|
|
1222
|
+
btn.disabled = false;
|
|
1223
|
+
}
|
|
1224
|
+
await rerender();
|
|
1225
|
+
},
|
|
1226
|
+
|
|
1227
|
+
async 'approval-tab'(btn) {
|
|
1228
|
+
state.approvalStatus = btn.dataset.status;
|
|
1229
|
+
await rerender();
|
|
1230
|
+
},
|
|
1231
|
+
|
|
1232
|
+
async 'activity-clear'() {
|
|
1233
|
+
state.activity.filters = {};
|
|
1234
|
+
await rerender();
|
|
1235
|
+
},
|
|
1236
|
+
|
|
1237
|
+
async 'activity-more'(btn) {
|
|
1238
|
+
btn.disabled = true;
|
|
1239
|
+
try {
|
|
1240
|
+
const data = await api(`/admin/api/audit?${auditQuery(state.activity.filters, { limit: 100, before: state.activity.next })}`);
|
|
1241
|
+
state.activity.entries = state.activity.entries.concat(data.entries);
|
|
1242
|
+
state.activity.next = data.next;
|
|
1243
|
+
$('#activity-rows').innerHTML = String(activityRows(state.activity.entries));
|
|
1244
|
+
$('#activity-more').hidden = !data.next;
|
|
1245
|
+
} finally {
|
|
1246
|
+
btn.disabled = false;
|
|
1247
|
+
}
|
|
1248
|
+
},
|
|
1249
|
+
|
|
1250
|
+
async 'agent-create'() {
|
|
1251
|
+
let created = null;
|
|
1252
|
+
await openDialog(agentForm(null, { create: true }), {
|
|
1253
|
+
label: 'Add agent',
|
|
1254
|
+
onSubmit: async (form) => {
|
|
1255
|
+
const body = agentBody(form);
|
|
1256
|
+
if (!/^[\w.-]{1,40}$/.test(body.name ?? '')) throw new ApiError('Give the agent a name: letters, digits, dot, dash or underscore.', 400);
|
|
1257
|
+
if (!Object.keys(body.payments).length) delete body.payments;
|
|
1258
|
+
if (!Object.keys(body.network).length) delete body.network;
|
|
1259
|
+
created = await api('/admin/api/agents', { method: 'POST', body, quiet: true });
|
|
1260
|
+
},
|
|
1261
|
+
});
|
|
1262
|
+
if (!created) return;
|
|
1263
|
+
await secretDialog({ title: `Key for ${created.agent?.name ?? 'the agent'}`, intro: 'Give it to the agent as BLOCKNET_AGENT_KEY. Blocknet keeps only a fingerprint of it.', value: created.key });
|
|
1264
|
+
await rerender();
|
|
1265
|
+
},
|
|
1266
|
+
|
|
1267
|
+
async 'agent-edit'(btn) {
|
|
1268
|
+
const a = findAgent(btn.dataset.name);
|
|
1269
|
+
if (!a) return;
|
|
1270
|
+
let saved = false;
|
|
1271
|
+
await openDialog(agentForm(a, { create: false }), {
|
|
1272
|
+
label: `Edit ${a.name}`,
|
|
1273
|
+
onSubmit: async (form) => {
|
|
1274
|
+
const { payments, network } = agentBody(form, a);
|
|
1275
|
+
await api(`/admin/api/agents/${encodeURIComponent(a.name)}`, { method: 'PATCH', body: { payments, network }, quiet: true });
|
|
1276
|
+
saved = true;
|
|
1277
|
+
},
|
|
1278
|
+
});
|
|
1279
|
+
if (saved) {
|
|
1280
|
+
toast(`Saved ${a.name}.`, 'ok');
|
|
1281
|
+
await rerender();
|
|
1282
|
+
}
|
|
1283
|
+
},
|
|
1284
|
+
|
|
1285
|
+
async 'agent-rotate'(btn) {
|
|
1286
|
+
const name = btn.dataset.name;
|
|
1287
|
+
if (!(await confirmDialog({ title: `Rotate the key for ${name}?`, body: 'The current key stops working at once. You will need to give the agent the new one.', confirm: 'Rotate key', danger: true }))) return;
|
|
1288
|
+
const r = await api(`/admin/api/agents/${encodeURIComponent(name)}/rotate`, { method: 'POST' });
|
|
1289
|
+
await secretDialog({ title: `New key for ${name}`, intro: 'The old key no longer works.', value: r.key });
|
|
1290
|
+
await rerender();
|
|
1291
|
+
},
|
|
1292
|
+
|
|
1293
|
+
async 'agent-toggle'(btn) {
|
|
1294
|
+
const a = findAgent(btn.dataset.name);
|
|
1295
|
+
if (!a) return;
|
|
1296
|
+
if (!a.disabled && !(await confirmDialog({ title: `Disable ${a.name}?`, body: 'Its calls will be refused until you enable it again.', confirm: 'Disable', danger: true }))) return;
|
|
1297
|
+
await api(`/admin/api/agents/${encodeURIComponent(a.name)}`, { method: 'PATCH', body: { disabled: !a.disabled } });
|
|
1298
|
+
toast(`${a.name} ${a.disabled ? 'enabled' : 'disabled'}.`, 'ok');
|
|
1299
|
+
await rerender();
|
|
1300
|
+
},
|
|
1301
|
+
|
|
1302
|
+
async 'agent-delete'(btn) {
|
|
1303
|
+
const name = btn.dataset.name;
|
|
1304
|
+
if (!(await confirmDialog({ title: `Delete ${name}?`, body: 'Its key stops working at once. Its history stays in the audit log.', confirm: 'Delete agent', danger: true }))) return;
|
|
1305
|
+
await api(`/admin/api/agents/${encodeURIComponent(name)}`, { method: 'DELETE' });
|
|
1306
|
+
toast(`Deleted ${name}.`, 'ok');
|
|
1307
|
+
await rerender();
|
|
1308
|
+
},
|
|
1309
|
+
|
|
1310
|
+
async 'user-create'() {
|
|
1311
|
+
let created = null;
|
|
1312
|
+
await openDialog(
|
|
1313
|
+
h`<form novalidate>
|
|
1314
|
+
<div class="dialog-head"><h2>Add user</h2><p>They get a temporary password and choose their own at first sign-in.</p></div>
|
|
1315
|
+
<div class="dialog-body">
|
|
1316
|
+
<p class="form-error"></p>
|
|
1317
|
+
<div class="field"><label for="nu-name">Name</label><input id="nu-name" name="name" type="text" autocomplete="off" required></div>
|
|
1318
|
+
<div class="field"><label for="nu-email">Email</label><input id="nu-email" name="email" type="email" autocomplete="off" required></div>
|
|
1319
|
+
<div class="field"><label for="nu-role">Role</label><select id="nu-role" name="role">
|
|
1320
|
+
<option value="viewer">Viewer: can look</option><option value="approver">Approver: can also decide on payments</option><option value="admin">Admin: can change everything</option></select></div>
|
|
1321
|
+
</div>
|
|
1322
|
+
<div class="dialog-foot"><button type="button" class="btn" data-close="cancel">Cancel</button><button type="submit" class="btn btn-primary">Add user</button></div>
|
|
1323
|
+
</form>`,
|
|
1324
|
+
{
|
|
1325
|
+
label: 'Add user',
|
|
1326
|
+
onSubmit: async (form) => {
|
|
1327
|
+
const d = formData(form);
|
|
1328
|
+
if (!/^[^@\s]+@[^@\s]+$/.test(d.email ?? '')) throw new ApiError('Enter a valid email address.', 400);
|
|
1329
|
+
created = await api('/admin/api/users', { method: 'POST', body: { email: d.email.trim(), name: d.name.trim(), role: d.role }, quiet: true });
|
|
1330
|
+
},
|
|
1331
|
+
},
|
|
1332
|
+
);
|
|
1333
|
+
if (!created) return;
|
|
1334
|
+
await secretDialog({ title: `Temporary password for ${created.user?.email ?? 'the user'}`, intro: 'Send it to them privately. They must change it when they first sign in.', value: created.temporaryPassword });
|
|
1335
|
+
await rerender();
|
|
1336
|
+
},
|
|
1337
|
+
|
|
1338
|
+
async 'user-reset'(btn) {
|
|
1339
|
+
const u = findUser(btn.dataset.id);
|
|
1340
|
+
if (!u) return;
|
|
1341
|
+
if (!(await confirmDialog({ title: `Reset the password for ${u.email}?`, body: 'Their current password stops working and they are signed out everywhere.', confirm: 'Reset password', danger: true }))) return;
|
|
1342
|
+
const r = await api(`/admin/api/users/${encodeURIComponent(u.id)}/reset-password`, { method: 'POST' });
|
|
1343
|
+
await secretDialog({ title: `Temporary password for ${u.email}`, intro: 'Send it to them privately. They must change it when they sign in.', value: r.temporaryPassword });
|
|
1344
|
+
await rerender();
|
|
1345
|
+
},
|
|
1346
|
+
|
|
1347
|
+
async 'user-toggle'(btn) {
|
|
1348
|
+
const u = findUser(btn.dataset.id);
|
|
1349
|
+
if (!u) return;
|
|
1350
|
+
if (!u.disabled && !(await confirmDialog({ title: `Disable ${u.email}?`, body: 'They are signed out and can\'t sign in until you enable them again.', confirm: 'Disable', danger: true }))) return;
|
|
1351
|
+
await api(`/admin/api/users/${encodeURIComponent(u.id)}`, { method: 'PATCH', body: { disabled: !u.disabled } });
|
|
1352
|
+
toast(`${u.email} ${u.disabled ? 'enabled' : 'disabled'}.`, 'ok');
|
|
1353
|
+
await rerender();
|
|
1354
|
+
},
|
|
1355
|
+
|
|
1356
|
+
async 'user-delete'(btn) {
|
|
1357
|
+
const u = findUser(btn.dataset.id);
|
|
1358
|
+
if (!u) return;
|
|
1359
|
+
if (!(await confirmDialog({ title: `Delete ${u.email}?`, body: 'They lose access at once. Their past actions stay in the audit log.', confirm: 'Delete user', danger: true }))) return;
|
|
1360
|
+
await api(`/admin/api/users/${encodeURIComponent(u.id)}`, { method: 'DELETE' });
|
|
1361
|
+
toast(`Deleted ${u.email}.`, 'ok');
|
|
1362
|
+
await rerender();
|
|
1363
|
+
},
|
|
1364
|
+
};
|
|
1365
|
+
|
|
1366
|
+
const changes = {
|
|
1367
|
+
async 'user-role'(select) {
|
|
1368
|
+
const u = findUser(select.dataset.id);
|
|
1369
|
+
if (!u) return;
|
|
1370
|
+
try {
|
|
1371
|
+
await api(`/admin/api/users/${encodeURIComponent(u.id)}`, { method: 'PATCH', body: { role: select.value } });
|
|
1372
|
+
toast(`${u.email} is now ${select.value === 'admin' ? 'an' : 'a'} ${select.value}.`, 'ok');
|
|
1373
|
+
u.role = select.value;
|
|
1374
|
+
} catch (err) {
|
|
1375
|
+
select.value = u.role;
|
|
1376
|
+
throw err;
|
|
1377
|
+
}
|
|
1378
|
+
},
|
|
1379
|
+
};
|
|
1380
|
+
|
|
1381
|
+
// ---------- Forms (submit delegation) ----------
|
|
1382
|
+
|
|
1383
|
+
const forms = {
|
|
1384
|
+
async signin(form) {
|
|
1385
|
+
const d = formData(form);
|
|
1386
|
+
const box = $('#signin-error');
|
|
1387
|
+
box.textContent = '';
|
|
1388
|
+
if (!d.email || !d.password) {
|
|
1389
|
+
box.textContent = 'Enter your email and password.';
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
try {
|
|
1393
|
+
const r = await api('/admin/api/login', { method: 'POST', body: { email: d.email.trim(), password: d.password }, quiet: true, noRedirect: true });
|
|
1394
|
+
state.csrf = r.csrf;
|
|
1395
|
+
await boot();
|
|
1396
|
+
} catch (err) {
|
|
1397
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1398
|
+
if (err.status === 429) {
|
|
1399
|
+
const min = Math.max(1, Math.ceil((err.data?.retryAfterSeconds ?? 900) / 60));
|
|
1400
|
+
box.textContent = `Too many attempts. Try again in ${min} minute${min === 1 ? '' : 's'}.`;
|
|
1401
|
+
} else {
|
|
1402
|
+
box.textContent = err.status === 401 ? 'Wrong email or password.' : err.message;
|
|
1403
|
+
}
|
|
1404
|
+
$('[name="password"]', form).value = '';
|
|
1405
|
+
$('[name="password"]', form).focus();
|
|
1406
|
+
}
|
|
1407
|
+
},
|
|
1408
|
+
|
|
1409
|
+
async setup(form) {
|
|
1410
|
+
const d = formData(form);
|
|
1411
|
+
formError(form, '');
|
|
1412
|
+
if (!d.adminToken || !d.name || !d.email) return formError(form, 'Fill in every field.');
|
|
1413
|
+
if ((d.password ?? '').length < 12) return formError(form, 'Use a password of at least 12 characters.');
|
|
1414
|
+
if (d.password !== d.confirm) return formError(form, "The passwords don't match.");
|
|
1415
|
+
try {
|
|
1416
|
+
const r = await api('/admin/api/setup', { method: 'POST', body: { adminToken: d.adminToken.trim(), name: d.name.trim(), email: d.email.trim(), password: d.password }, quiet: true, noRedirect: true });
|
|
1417
|
+
state.csrf = r.csrf;
|
|
1418
|
+
await boot();
|
|
1419
|
+
} catch (err) {
|
|
1420
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1421
|
+
formError(form, err.status === 401 ? "That admin token isn't right." : err.status === 409 ? 'Blocknet is already set up. Sign in instead.' : err.message);
|
|
1422
|
+
if (err.status === 409) setTimeout(() => boot(), 1500);
|
|
1423
|
+
}
|
|
1424
|
+
},
|
|
1425
|
+
|
|
1426
|
+
async 'forced-change'(form) {
|
|
1427
|
+
const d = formData(form);
|
|
1428
|
+
formError(form, '');
|
|
1429
|
+
if ((d.next ?? '').length < 12) return formError(form, 'Use a password of at least 12 characters.');
|
|
1430
|
+
if (d.next !== d.confirm) return formError(form, "The new passwords don't match.");
|
|
1431
|
+
try {
|
|
1432
|
+
await api('/admin/api/account/password', { method: 'POST', body: { current: d.current, next: d.next }, quiet: true, noRedirect: true });
|
|
1433
|
+
toast('Password saved.', 'ok');
|
|
1434
|
+
await boot();
|
|
1435
|
+
} catch (err) {
|
|
1436
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1437
|
+
formError(form, err.message);
|
|
1438
|
+
}
|
|
1439
|
+
},
|
|
1440
|
+
|
|
1441
|
+
async 'change-password'(form) {
|
|
1442
|
+
const d = formData(form);
|
|
1443
|
+
formError(form, '');
|
|
1444
|
+
if ((d.next ?? '').length < 12) return formError(form, 'Use a password of at least 12 characters.');
|
|
1445
|
+
if (d.next !== d.confirm) return formError(form, "The new passwords don't match.");
|
|
1446
|
+
try {
|
|
1447
|
+
await api('/admin/api/account/password', { method: 'POST', body: { current: d.current, next: d.next }, quiet: true });
|
|
1448
|
+
} catch (err) {
|
|
1449
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1450
|
+
return formError(form, err.message);
|
|
1451
|
+
}
|
|
1452
|
+
form.reset();
|
|
1453
|
+
toast('Password changed. Your other sessions were signed out.', 'ok');
|
|
1454
|
+
},
|
|
1455
|
+
|
|
1456
|
+
async 'activity-filters'(form) {
|
|
1457
|
+
const d = formData(form);
|
|
1458
|
+
state.activity.filters = Object.fromEntries(Object.entries(d).map(([k, v]) => [k, String(v).trim()]).filter(([, v]) => v));
|
|
1459
|
+
await rerender();
|
|
1460
|
+
},
|
|
1461
|
+
|
|
1462
|
+
async policy(form) {
|
|
1463
|
+
const section = form.dataset.section;
|
|
1464
|
+
$$('[data-error-for]', form).forEach((s) => (s.textContent = ''));
|
|
1465
|
+
$$('[aria-invalid]', form).forEach((i) => i.removeAttribute('aria-invalid'));
|
|
1466
|
+
const note = $('.saved-note', form);
|
|
1467
|
+
if (note) note.textContent = '';
|
|
1468
|
+
let body;
|
|
1469
|
+
try {
|
|
1470
|
+
body = policySection(form, section);
|
|
1471
|
+
} catch (err) {
|
|
1472
|
+
if (err instanceof FieldError) return showFieldError(form, section, err.field, err.message);
|
|
1473
|
+
throw err;
|
|
1474
|
+
}
|
|
1475
|
+
const submit = $('button[type="submit"]', form);
|
|
1476
|
+
if (submit) submit.disabled = true;
|
|
1477
|
+
try {
|
|
1478
|
+
const p = await api('/admin/api/policy', { method: 'PUT', body: { [section]: body }, quiet: true });
|
|
1479
|
+
state.policy = p;
|
|
1480
|
+
if (note) note.textContent = 'Saved. Applies now.';
|
|
1481
|
+
} catch (err) {
|
|
1482
|
+
if (!(err instanceof ApiError)) throw err;
|
|
1483
|
+
showFieldError(form, section, err.data?.field ?? section, err.message);
|
|
1484
|
+
} finally {
|
|
1485
|
+
if (submit) submit.disabled = false;
|
|
1486
|
+
}
|
|
1487
|
+
},
|
|
1488
|
+
};
|
|
1489
|
+
|
|
1490
|
+
async function rerender() {
|
|
1491
|
+
const view = $('#view');
|
|
1492
|
+
if (!view) return;
|
|
1493
|
+
const route = ROUTES.find((r) => r.id === state.route);
|
|
1494
|
+
if (route) await run(route.render, view, { first: true });
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
// ---------- Boot ----------
|
|
1498
|
+
|
|
1499
|
+
async function boot() {
|
|
1500
|
+
let me;
|
|
1501
|
+
try {
|
|
1502
|
+
me = await api('/admin/api/me', { quiet: true });
|
|
1503
|
+
} catch (err) {
|
|
1504
|
+
if (err instanceof ApiError && err.status === 0) {
|
|
1505
|
+
$('#app').innerHTML = String(h`<main class="auth"><div class="auth-card"><a class="wordmark" href="/">blocknet<span>.</span></a><p>${err.message}</p><button type="button" class="btn btn-primary" data-action="retry">Try again</button></div></main>`);
|
|
1506
|
+
}
|
|
1507
|
+
return; // 401 and 403 already rendered the right screen
|
|
1508
|
+
}
|
|
1509
|
+
state.me = me;
|
|
1510
|
+
state.csrf = me.csrf;
|
|
1511
|
+
state.perms = new Set(me.permissions ?? []);
|
|
1512
|
+
if (me.sso) state.sso = me.sso;
|
|
1513
|
+
if (me.user?.mustChangePassword) return renderForcedChange();
|
|
1514
|
+
renderShell();
|
|
1515
|
+
await navigate();
|
|
1516
|
+
startPoll();
|
|
1517
|
+
if (can('approvals.view') && state.route !== 'overview' && state.route !== 'approvals') run(refreshPendingCount);
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
actions.retry = () => boot();
|
|
1521
|
+
|
|
1522
|
+
document.addEventListener('click', (e) => {
|
|
1523
|
+
if (e.target.closest('dialog')) return; // dialogs handle their own clicks
|
|
1524
|
+
const el = e.target.closest('[data-action]');
|
|
1525
|
+
if (el && actions[el.dataset.action]) {
|
|
1526
|
+
e.preventDefault();
|
|
1527
|
+
run(actions[el.dataset.action], el, e);
|
|
1528
|
+
}
|
|
1529
|
+
const menu = $('.usermenu[open]');
|
|
1530
|
+
if (menu && !e.target.closest('.usermenu')) menu.removeAttribute('open');
|
|
1531
|
+
});
|
|
1532
|
+
|
|
1533
|
+
document.addEventListener('submit', (e) => {
|
|
1534
|
+
const form = e.target.closest('form[data-form]');
|
|
1535
|
+
if (!form || form.closest('dialog')) return;
|
|
1536
|
+
e.preventDefault();
|
|
1537
|
+
const handler = forms[form.dataset.form];
|
|
1538
|
+
if (!handler) return;
|
|
1539
|
+
const submit = $('button[type="submit"]', form);
|
|
1540
|
+
const wasDisabled = submit?.disabled;
|
|
1541
|
+
if (submit && form.dataset.form !== 'policy') submit.disabled = true;
|
|
1542
|
+
run(handler, form, e).finally(() => {
|
|
1543
|
+
if (submit && document.contains(submit) && form.dataset.form !== 'policy') submit.disabled = wasDisabled ?? false;
|
|
1544
|
+
});
|
|
1545
|
+
});
|
|
1546
|
+
|
|
1547
|
+
document.addEventListener('change', (e) => {
|
|
1548
|
+
const el = e.target.closest('[data-change]');
|
|
1549
|
+
if (el && changes[el.dataset.change]) run(changes[el.dataset.change], el, e);
|
|
1550
|
+
});
|
|
1551
|
+
|
|
1552
|
+
document.addEventListener('keydown', (e) => {
|
|
1553
|
+
if (e.key === 'Escape') $('.usermenu[open]')?.removeAttribute('open');
|
|
1554
|
+
});
|
|
1555
|
+
|
|
1556
|
+
window.addEventListener('hashchange', () => run(navigate));
|
|
1557
|
+
|
|
1558
|
+
document.addEventListener('visibilitychange', () => {
|
|
1559
|
+
if (!document.hidden && state.me && state.route === 'overview' && !$('dialog[open]')) run(renderOverview, $('#view'), { first: false });
|
|
1560
|
+
});
|
|
1561
|
+
|
|
1562
|
+
// An SSO failure comes back as /?error=…; show it on the sign-in screen, then clean the URL.
|
|
1563
|
+
{
|
|
1564
|
+
const params = new URLSearchParams(location.search);
|
|
1565
|
+
if (params.has('error')) {
|
|
1566
|
+
state.flashError = params.get('error');
|
|
1567
|
+
history.replaceState(null, '', location.pathname + location.hash);
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
boot();
|