@agent-custody/receipts 0.16.5 → 0.16.7

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.
Files changed (65) hide show
  1. package/README.md +29 -13
  2. package/dist/capture.d.ts +2 -0
  3. package/dist/capture.js +13 -2
  4. package/dist/check.d.ts +1 -1
  5. package/dist/check.js +34 -10
  6. package/dist/cli.js +54 -9
  7. package/dist/config.d.ts +27 -2
  8. package/dist/config.js +66 -2
  9. package/dist/console-page.js +144 -50
  10. package/dist/deny-report.d.ts +7 -0
  11. package/dist/deny-report.js +8 -3
  12. package/dist/design.d.ts +11 -0
  13. package/dist/design.js +91 -0
  14. package/dist/door-app.d.ts +28 -0
  15. package/dist/door-app.js +244 -0
  16. package/dist/door-partner.d.ts +66 -0
  17. package/dist/door-partner.js +94 -0
  18. package/dist/door.d.ts +139 -10
  19. package/dist/door.js +297 -137
  20. package/dist/gateway-http.d.ts +1 -1
  21. package/dist/index.d.ts +8 -2
  22. package/dist/index.js +5 -1
  23. package/dist/log-admin.js +100 -59
  24. package/dist/log-store.d.ts +8 -2
  25. package/dist/log-store.js +22 -12
  26. package/dist/perathos.d.ts +50 -0
  27. package/dist/perathos.js +188 -0
  28. package/dist/portal.d.ts +66 -5
  29. package/dist/portal.js +895 -242
  30. package/dist/receipt.d.ts +4 -1
  31. package/dist/session-audit.d.ts +46 -0
  32. package/dist/session-audit.js +150 -0
  33. package/dist/site-links.d.ts +23 -0
  34. package/dist/site-links.js +29 -0
  35. package/dist/verify.js +44 -4
  36. package/dist/web-bot-auth.d.ts +105 -0
  37. package/dist/web-bot-auth.js +508 -0
  38. package/docs/acs.md +2 -0
  39. package/docs/approvals.md +1 -1
  40. package/docs/completeness.md +1 -1
  41. package/docs/configuration.md +2 -0
  42. package/docs/console.md +11 -2
  43. package/docs/door-languages.md +168 -0
  44. package/docs/door-middleware.md +216 -0
  45. package/docs/door-quickstart.md +1 -1
  46. package/docs/door-signals.md +43 -6
  47. package/docs/door.md +129 -32
  48. package/docs/egress.md +3 -1
  49. package/docs/github-action.md +2 -2
  50. package/docs/mandates.md +1 -1
  51. package/docs/perathos.md +100 -0
  52. package/docs/sdk.md +32 -1
  53. package/docs/threat-model.md +2 -1
  54. package/docs/tutorials.md +6 -0
  55. package/docs/usage.md +3 -1
  56. package/docs/verification.md +3 -1
  57. package/package.json +7 -1
  58. package/vectors/audit.json +27 -27
  59. package/vectors/canonical.json +5 -5
  60. package/vectors/interop/perathos/LICENSE +21 -0
  61. package/vectors/interop/perathos/README.md +17 -0
  62. package/vectors/interop/perathos/pocketos-replay/session.head.json +11 -0
  63. package/vectors/interop/perathos/pocketos-replay/session.jsonl +8 -0
  64. package/vectors/interop/perathos/pocketos-replay/verification.json +65 -0
  65. package/vectors/receipts.json +1701 -1210
package/dist/portal.js CHANGED
@@ -8,12 +8,14 @@
8
8
  // content-security policy, and every API write requires a JSON body, which with a SameSite=Strict cookie is what
9
9
  // keeps a cross-site page from acting as the user. Billing is Stripe Checkout for the team plan; the webhook moves
10
10
  // the tenant's plan, and nothing about a card ever passes through here.
11
- import { createHmac, randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
11
+ import { createHash, createHmac, randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
12
12
  import { createServer } from "node:http";
13
13
  import { postgresCheckpoints } from "./checkpoints.js";
14
+ import { DESIGN_CSS, LOGO_MARK as MARK } from "./design.js";
14
15
  import { welcomeSheet } from "./log-admin.js";
15
16
  import { clientAddress } from "./log-sink.js";
16
- import { RateLimiter } from "./log-store.js";
17
+ import { SITE_NAV, siteUrl } from "./site-links.js";
18
+ import { PLAN_QUOTAS, RateLimiter } from "./log-store.js";
17
19
  import { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.js";
18
20
  /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
19
21
  export class UnverifiedAccountError extends Error {
@@ -66,6 +68,205 @@ export function totpStep(key, code, now = Date.now()) {
66
68
  }
67
69
  return null;
68
70
  }
71
+ // ---- QR code (ISO/IEC 18004): byte mode, error correction level M, versions 1 to 40; for the two-step setup ----
72
+ // Level M per version: error correction codewords per block, and the number of blocks.
73
+ const QR_ECC = [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28];
74
+ const QR_BLOCKS = [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49];
75
+ const gfMul = (x, y) => {
76
+ let z = 0;
77
+ for (let i = 7; i >= 0; i--)
78
+ z = ((z << 1) ^ ((z >>> 7) * 0x11d)) ^ (((y >>> i) & 1) * x);
79
+ return z;
80
+ };
81
+ const qrRawModules = (v) => {
82
+ let n = (16 * v + 128) * v + 64;
83
+ if (v >= 2) {
84
+ const a = Math.floor(v / 7) + 2;
85
+ n -= (25 * a - 10) * a - 55;
86
+ if (v >= 7)
87
+ n -= 36;
88
+ }
89
+ return n;
90
+ };
91
+ /** The modules of the QR code for `text`, true for dark, without the quiet zone. */
92
+ export function qrMatrix(text) {
93
+ const data = [...Buffer.from(text, "utf8")];
94
+ let v = 1;
95
+ const capacity = (v) => (Math.floor(qrRawModules(v) / 8) - QR_ECC[v] * QR_BLOCKS[v]) * 8;
96
+ while (4 + (v < 10 ? 8 : 16) + data.length * 8 > capacity(v))
97
+ if (++v > 40)
98
+ throw new Error("too long for a QR code");
99
+ const bits = [];
100
+ const put = (val, len) => { for (let i = len - 1; i >= 0; i--)
101
+ bits.push((val >>> i) & 1); };
102
+ put(4, 4);
103
+ put(data.length, v < 10 ? 8 : 16);
104
+ for (const b of data)
105
+ put(b, 8);
106
+ const cap = capacity(v);
107
+ put(0, Math.min(4, cap - bits.length));
108
+ put(0, (8 - (bits.length % 8)) % 8);
109
+ for (let pad = 0xec; bits.length < cap; pad ^= 0xec ^ 0x11)
110
+ put(pad, 8);
111
+ const words = Array.from({ length: bits.length / 8 }, (_, i) => parseInt(bits.slice(i * 8, i * 8 + 8).join(""), 2));
112
+ // Reed-Solomon over GF(256), and the blocks interleaved
113
+ const eccLen = QR_ECC[v];
114
+ const nBlocks = QR_BLOCKS[v];
115
+ const div = new Array(eccLen).fill(0);
116
+ div[eccLen - 1] = 1;
117
+ for (let i = 0, root = 1; i < eccLen; i++, root = gfMul(root, 2))
118
+ for (let j = 0; j < eccLen; j++)
119
+ div[j] = gfMul(div[j], root) ^ (div[j + 1] ?? 0);
120
+ const raw = Math.floor(qrRawModules(v) / 8);
121
+ const nShort = nBlocks - (raw % nBlocks);
122
+ const shortLen = Math.floor(raw / nBlocks);
123
+ const blocks = [];
124
+ for (let i = 0, k = 0; i < nBlocks; i++) {
125
+ const dat = words.slice(k, k + shortLen - eccLen + (i < nShort ? 0 : 1));
126
+ k += dat.length;
127
+ const rem = new Array(eccLen).fill(0);
128
+ for (const b of dat) {
129
+ const f = b ^ rem.shift();
130
+ rem.push(0);
131
+ div.forEach((c, j) => { rem[j] ^= gfMul(c, f); });
132
+ }
133
+ if (i < nShort)
134
+ dat.push(0);
135
+ blocks.push([...dat, ...rem]);
136
+ }
137
+ const all = [];
138
+ for (let i = 0; i < blocks[0].length; i++)
139
+ blocks.forEach((b, j) => { if (i !== shortLen - eccLen || j >= nShort)
140
+ all.push(b[i]); });
141
+ // function patterns
142
+ const size = v * 4 + 17;
143
+ const m = Array.from({ length: size }, () => new Array(size).fill(false));
144
+ const fixed = Array.from({ length: size }, () => new Array(size).fill(false));
145
+ const set = (x, y, dark) => { m[y][x] = dark; fixed[y][x] = true; };
146
+ for (let i = 0; i < size; i++) {
147
+ set(6, i, i % 2 === 0);
148
+ set(i, 6, i % 2 === 0);
149
+ }
150
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
151
+ for (let dy = -4; dy <= 4; dy++)
152
+ for (let dx = -4; dx <= 4; dx++) {
153
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
154
+ if (cx + dx >= 0 && cx + dx < size && cy + dy >= 0 && cy + dy < size)
155
+ set(cx + dx, cy + dy, d !== 2 && d !== 4);
156
+ }
157
+ }
158
+ const align = [];
159
+ if (v > 1) {
160
+ const n = Math.floor(v / 7) + 2;
161
+ const step = Math.floor((v * 8 + n * 3 + 5) / (n * 4 - 4)) * 2;
162
+ align.push(6);
163
+ for (let pos = size - 7; align.length < n; pos -= step)
164
+ align.splice(1, 0, pos);
165
+ }
166
+ for (const [i, ax] of align.entries())
167
+ for (const [j, ay] of align.entries()) {
168
+ if ((i === 0 && j === 0) || (i === 0 && j === align.length - 1) || (i === align.length - 1 && j === 0))
169
+ continue;
170
+ for (let dy = -2; dy <= 2; dy++)
171
+ for (let dx = -2; dx <= 2; dx++)
172
+ set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
173
+ }
174
+ const format = (mask) => {
175
+ const d = mask; // level M is 00
176
+ let r = d;
177
+ for (let i = 0; i < 10; i++)
178
+ r = (r << 1) ^ ((r >>> 9) * 0x537);
179
+ const f = ((d << 10) | r) ^ 0x5412;
180
+ const bit = (i) => ((f >>> i) & 1) === 1;
181
+ for (let i = 0; i <= 5; i++)
182
+ set(8, i, bit(i));
183
+ set(8, 7, bit(6));
184
+ set(8, 8, bit(7));
185
+ set(7, 8, bit(8));
186
+ for (let i = 9; i < 15; i++)
187
+ set(14 - i, 8, bit(i));
188
+ for (let i = 0; i < 8; i++)
189
+ set(size - 1 - i, 8, bit(i));
190
+ for (let i = 8; i < 15; i++)
191
+ set(8, size - 15 + i, bit(i));
192
+ set(8, size - 8, true);
193
+ };
194
+ format(0);
195
+ if (v >= 7) {
196
+ let r = v;
197
+ for (let i = 0; i < 12; i++)
198
+ r = (r << 1) ^ ((r >>> 11) * 0x1f25);
199
+ const f = (v << 12) | r;
200
+ for (let i = 0; i < 18; i++) {
201
+ const a = size - 11 + (i % 3), b = Math.floor(i / 3), dark = ((f >>> i) & 1) === 1;
202
+ set(a, b, dark);
203
+ set(b, a, dark);
204
+ }
205
+ }
206
+ // the codewords, in the zigzag from the bottom right
207
+ let i = 0;
208
+ for (let right = size - 1; right >= 1; right -= 2) {
209
+ if (right === 6)
210
+ right = 5;
211
+ for (let vert = 0; vert < size; vert++)
212
+ for (let j = 0; j < 2; j++) {
213
+ const x = right - j;
214
+ const y = ((right + 1) & 2) === 0 ? size - 1 - vert : vert;
215
+ if (!fixed[y][x] && i < all.length * 8) {
216
+ m[y][x] = ((all[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;
217
+ i++;
218
+ }
219
+ }
220
+ }
221
+ // the mask with the lowest penalty
222
+ const MASKS = [(x, y) => (x + y) % 2 === 0, (_x, y) => y % 2 === 0, (x) => x % 3 === 0, (x, y) => (x + y) % 3 === 0, (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0, (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0, (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0];
223
+ const apply = (k) => { for (let y = 0; y < size; y++)
224
+ for (let x = 0; x < size; x++)
225
+ if (!fixed[y][x] && MASKS[k](x, y))
226
+ m[y][x] = !m[y][x]; };
227
+ const penalty = () => {
228
+ let p = 0, dark = 0;
229
+ const lines = [...m.map((r) => r.map(Number).join("")), ...m.map((_, x) => m.map((r) => Number(r[x])).join(""))];
230
+ for (const l of lines) {
231
+ for (const run of l.match(/0{5,}|1{5,}/g) ?? [])
232
+ p += run.length - 2;
233
+ p += 40 * ((l.match(/(?=10111010000|00001011101)/g) ?? []).length);
234
+ }
235
+ for (let y = 0; y < size; y++)
236
+ for (let x = 0; x < size; x++) {
237
+ if (m[y][x])
238
+ dark++;
239
+ if (x < size - 1 && y < size - 1 && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1])
240
+ p += 3;
241
+ }
242
+ return p + 10 * (Math.ceil(Math.abs(dark * 20 - size * size * 10) / (size * size)) - 1);
243
+ };
244
+ let best = 0, least = Infinity;
245
+ for (let k = 0; k < 8; k++) {
246
+ apply(k);
247
+ format(k);
248
+ const p = penalty();
249
+ if (p < least) {
250
+ least = p;
251
+ best = k;
252
+ }
253
+ apply(k);
254
+ }
255
+ apply(best);
256
+ format(best);
257
+ return m;
258
+ }
259
+ /** The QR code as an SVG, dark on white with a four-module quiet zone, whatever the page's theme. */
260
+ export function qrSvg(text) {
261
+ const m = qrMatrix(text);
262
+ const n = m.length + 8;
263
+ let d = "";
264
+ m.forEach((row, y) => row.forEach((dark, x) => { if (dark)
265
+ d += `M${x + 4} ${y + 4}h1v1h-1z`; }));
266
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" shape-rendering="crispEdges" role="img" aria-label="QR code"><rect width="${n}" height="${n}" fill="#fff"/><path d="${d}" fill="#000"/></svg>`;
267
+ }
268
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
269
+ const recoveryHash = (code) => sha256(code.toLowerCase().replace(/[^a-z0-9]/g, ""));
69
270
  export class PortalStore {
70
271
  client;
71
272
  p;
@@ -91,6 +292,8 @@ export class PortalStore {
91
292
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS ${c} TEXT`);
92
293
  // when the founder's note went out, so it goes once
93
294
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS followed_up_at TIMESTAMPTZ`);
295
+ // when the person asked for no more automatic mail about getting started
296
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS follow_up_opt_out_at TIMESTAMPTZ`);
94
297
  // when the address was confirmed; a provider sign-in links to a password account only once this is set
95
298
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ`);
96
299
  // a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
@@ -103,6 +306,10 @@ export class PortalStore {
103
306
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}removed (tenant_id TEXT NOT NULL, user_id TEXT NOT NULL, PRIMARY KEY (tenant_id, user_id))`);
104
307
  // the address too, so the removal holds after the account is made again under a new id
105
308
  await this.client.query(`ALTER TABLE ${p}removed ADD COLUMN IF NOT EXISTS email TEXT`);
309
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS mfa_recovery TEXT[]`);
310
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS sessions_after BIGINT`);
311
+ // the SHA-256 of each password reset token; the token itself is only in the mail
312
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}resets (token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES ${p}users(id), expires_at TIMESTAMPTZ NOT NULL)`);
106
313
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}sso (tenant_id TEXT PRIMARY KEY, protocol TEXT NOT NULL, config TEXT NOT NULL, domains TEXT[] NOT NULL, default_role TEXT NOT NULL, enforced BOOLEAN NOT NULL DEFAULT false, updated_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
107
314
  })();
108
315
  }
@@ -134,7 +341,7 @@ export class PortalStore {
134
341
  return rows[0] ? PortalStore.asUser(rows[0]) : null;
135
342
  }
136
343
  static asUser(r) {
137
- return { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString(), emailVerifiedAt: r.email_verified_at ? new Date(r.email_verified_at).toISOString() : null };
344
+ return { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString(), emailVerifiedAt: r.email_verified_at ? new Date(r.email_verified_at).toISOString() : null, ...(r.sessions_after != null ? { sessionsAfter: Number(r.sessions_after) } : {}) };
138
345
  }
139
346
  async markEmailVerified(userId, at = new Date()) {
140
347
  await this.init();
@@ -162,9 +369,13 @@ export class PortalStore {
162
369
  async pendingFollowUps(o) {
163
370
  await this.init();
164
371
  const rows = (await this.client.query(`SELECT u.id, u.email, u.name, u.company, m.tenant_id, u.created_at FROM ${this.p}users u JOIN ${this.p}members m ON m.user_id = u.id
165
- WHERE u.followed_up_at IS NULL AND u.name IS NOT NULL AND u.created_at <= $1 AND u.created_at >= $2 ORDER BY u.created_at`, [new Date(o.now.getTime() - o.minAgeMs).toISOString(), new Date(o.now.getTime() - o.maxAgeMs).toISOString()])).rows;
372
+ WHERE u.followed_up_at IS NULL AND u.follow_up_opt_out_at IS NULL AND u.name IS NOT NULL AND u.created_at <= $1 AND u.created_at >= $2 ORDER BY u.created_at`, [new Date(o.now.getTime() - o.minAgeMs).toISOString(), new Date(o.now.getTime() - o.maxAgeMs).toISOString()])).rows;
166
373
  return rows.map((r) => ({ id: String(r.id), email: String(r.email), name: String(r.name), company: r.company == null ? null : String(r.company), tenantId: String(r.tenant_id), createdAt: new Date(r.created_at).toISOString() }));
167
374
  }
375
+ async optOutOfFollowUps(userId) {
376
+ await this.init();
377
+ return (await this.client.query(`UPDATE ${this.p}users SET follow_up_opt_out_at = COALESCE(follow_up_opt_out_at, now()) WHERE id = $1 RETURNING id`, [userId])).rows.length > 0;
378
+ }
168
379
  async markFollowedUp(userId, at = new Date()) {
169
380
  await this.init();
170
381
  await this.client.query(`UPDATE ${this.p}users SET followed_up_at = $2 WHERE id = $1`, [userId, at.toISOString()]);
@@ -206,9 +417,32 @@ export class PortalStore {
206
417
  return null;
207
418
  return { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() };
208
419
  }
420
+ /** A reset token for the account, good for `ttlMs` and once. Only its hash is stored. */
421
+ async createPasswordReset(userId, ttlMs = 3_600_000) {
422
+ await this.init();
423
+ const token = randomBytes(32).toString("base64url");
424
+ await this.client.query(`INSERT INTO ${this.p}resets (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, [sha256(token), userId, new Date(Date.now() + ttlMs).toISOString()]);
425
+ return token;
426
+ }
427
+ /** The account of a reset token that has not expired, and the token is gone; null otherwise. */
428
+ async takePasswordReset(token) {
429
+ await this.init();
430
+ const rows = (await this.client.query(`DELETE FROM ${this.p}resets WHERE token_hash = $1 RETURNING user_id, expires_at`, [sha256(token)])).rows;
431
+ return rows[0] && new Date(rows[0].expires_at).getTime() > Date.now() ? rows[0].user_id : null;
432
+ }
433
+ /** Sets the password, ends every session and MFA cookie signed before `at`, and drops the account's reset tokens. */
434
+ async setPassword(userId, password, at = Date.now()) {
435
+ await this.init();
436
+ await this.client.query(`UPDATE ${this.p}users SET password_hash = $2, sessions_after = $3 WHERE id = $1`, [userId, PortalStore.hashPassword(password), at]);
437
+ await this.client.query(`DELETE FROM ${this.p}resets WHERE user_id = $1`, [userId]);
438
+ }
439
+ async unlinkIdentities(userId) {
440
+ await this.init();
441
+ await this.client.query(`DELETE FROM ${this.p}identities WHERE user_id = $1`, [userId]);
442
+ }
209
443
  async user(id) {
210
444
  await this.init();
211
- const rows = (await this.client.query(`SELECT id, email, created_at, email_verified_at FROM ${this.p}users WHERE id = $1`, [id])).rows;
445
+ const rows = (await this.client.query(`SELECT id, email, created_at, email_verified_at, sessions_after FROM ${this.p}users WHERE id = $1`, [id])).rows;
212
446
  return rows[0] ? PortalStore.asUser(rows[0]) : null;
213
447
  }
214
448
  async addMember(userId, tenantId, role = "owner") {
@@ -263,8 +497,21 @@ export class PortalStore {
263
497
  }
264
498
  async mfa(userId) {
265
499
  await this.init();
266
- const rows = (await this.client.query(`SELECT mfa_secret, mfa_enabled_at FROM ${this.p}users WHERE id = $1`, [userId])).rows;
267
- return { secret: rows[0]?.mfa_secret ? String(rows[0].mfa_secret) : null, enabled: !!rows[0]?.mfa_enabled_at };
500
+ const rows = (await this.client.query(`SELECT mfa_secret, mfa_enabled_at, mfa_recovery FROM ${this.p}users WHERE id = $1`, [userId])).rows;
501
+ return { secret: rows[0]?.mfa_secret ? String(rows[0].mfa_secret) : null, enabled: !!rows[0]?.mfa_enabled_at, recoveryCodes: (rows[0]?.mfa_recovery ?? []).length };
502
+ }
503
+ /** Replaces the account's recovery codes with ten new ones, returned once; only their hashes are stored. */
504
+ async newRecoveryCodes(userId) {
505
+ await this.init();
506
+ const codes = Array.from({ length: 10 }, () => base32(randomBytes(8)).slice(0, 12).toLowerCase().replace(/(.{4})(?=.)/g, "$1-"));
507
+ await this.client.query(`UPDATE ${this.p}users SET mfa_recovery = $2::text[] WHERE id = $1`, [userId, codes.map(recoveryHash)]);
508
+ return codes;
509
+ }
510
+ /** False when the code is not one of the account's unused recovery codes. */
511
+ async takeRecoveryCode(userId, code) {
512
+ await this.init();
513
+ const h = recoveryHash(code);
514
+ return (await this.client.query(`UPDATE ${this.p}users SET mfa_recovery = array_remove(mfa_recovery, $2) WHERE id = $1 AND $2 = ANY(mfa_recovery) RETURNING id`, [userId, h])).rows.length > 0;
268
515
  }
269
516
  async setMfaSecret(userId, secretHex) {
270
517
  await this.init();
@@ -281,7 +528,7 @@ export class PortalStore {
281
528
  }
282
529
  async resetMfa(email) {
283
530
  await this.init();
284
- return (await this.client.query(`UPDATE ${this.p}users SET mfa_secret = NULL, mfa_enabled_at = NULL, mfa_last_step = NULL WHERE email = $1 RETURNING id`, [email])).rows.length > 0;
531
+ return (await this.client.query(`UPDATE ${this.p}users SET mfa_secret = NULL, mfa_enabled_at = NULL, mfa_last_step = NULL, mfa_recovery = NULL WHERE email = $1 RETURNING id`, [email])).rows.length > 0;
285
532
  }
286
533
  /** Replaces the tenant's setting. A domain belongs to one tenant, so a domain that another tenant holds is refused. */
287
534
  async setSso(s) {
@@ -348,7 +595,7 @@ export class PortalStore {
348
595
  role = invited;
349
596
  }
350
597
  if (unverified) {
351
- for (const t of ["members", "identities"])
598
+ for (const t of ["members", "identities", "resets"])
352
599
  await this.client.query(`DELETE FROM ${this.p}${t} WHERE user_id = $1`, [user.id]);
353
600
  await this.client.query(`DELETE FROM ${this.p}users WHERE id = $1`, [user.id]);
354
601
  user = null;
@@ -408,7 +655,7 @@ export class PortalStore {
408
655
  const b64u = (b) => b.toString("base64url");
409
656
  /** `via` records how the user signed in, for example `sso:acme`. */
410
657
  export function signSession(secret, userId, ttlMs = 14 * 86_400_000, via) {
411
- const body = b64u(Buffer.from(JSON.stringify({ u: userId, e: Date.now() + ttlMs, ...(via ? { a: via } : {}) })));
658
+ const body = b64u(Buffer.from(JSON.stringify({ u: userId, e: Date.now() + ttlMs, i: Date.now(), ...(via ? { a: via } : {}) })));
412
659
  return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
413
660
  }
414
661
  function readClaims(secret, cookie) {
@@ -421,8 +668,9 @@ function readClaims(secret, cookie) {
421
668
  if (expected.length !== mac.length || !timingSafeEqual(Buffer.from(expected), Buffer.from(mac)))
422
669
  return null;
423
670
  try {
424
- const { u, e, a } = JSON.parse(Buffer.from(body, "base64url").toString());
425
- return typeof u === "string" && typeof e === "number" && e > Date.now() ? { u, ...(typeof a === "string" ? { a } : {}) } : null;
671
+ const { u, e, a, i } = JSON.parse(Buffer.from(body, "base64url").toString());
672
+ // a cookie from before the issue time was added counts as issued at 0, so a reset ends it too
673
+ return typeof u === "string" && typeof e === "number" && e > Date.now() ? { u, i: typeof i === "number" ? i : 0, ...(typeof a === "string" ? { a } : {}) } : null;
426
674
  }
427
675
  catch {
428
676
  return null;
@@ -462,11 +710,48 @@ const TENANT_ID = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
462
710
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
463
711
  const ENFORCED = "Your organisation signs in through its identity provider. Use Sign in with single sign-on";
464
712
  const RESERVED = new Set(["default", "admin", "api", "www", "log", "checkpoints", "app", "portal", "stripe", "health", "t"]);
713
+ const LOGO_URL = "https://agent-custody.dev/apple-touch-icon.png";
714
+ const escapeHtml = (v) => v.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
715
+ /** Builds the HTML part and the plain-text part of one message from the same fields. Every value in the HTML is escaped, and only an http or https URL becomes a link. */
716
+ export function renderMail(c) {
717
+ const link = (url) => (/^https?:\/\//i.test(url) ? escapeHtml(url) : null);
718
+ const button = c.button && link(c.button.url) ? c.button : undefined;
719
+ const footer = (c.footer ?? []).filter((f) => typeof f === "string" || link(f.url));
720
+ const text = [
721
+ c.heading, "",
722
+ ...c.paragraphs.flatMap((p) => [p, ""]),
723
+ ...(c.code ? [c.code, ""] : []),
724
+ ...(button ? [`${button.label}:`, button.url, ""] : []),
725
+ ...footer.map((f) => (typeof f === "string" ? f : `${f.label}: ${f.url}`)),
726
+ "agent-custody",
727
+ ].join("\n");
728
+ const font = `-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`;
729
+ const p = (v, style, cls = "ink") => `<p class="${cls}" style="margin:0 0 16px;font:15px/1.55 ${font};${style}">${escapeHtml(v)}</p>`;
730
+ const html = `<!doctype html>
731
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark"><title>${escapeHtml(c.heading)}</title>
732
+ <style>@media (prefers-color-scheme: dark) { .bg { background: #0c0a09 !important; } .card { background: #1c1917 !important; border-color: #292524 !important; } .ink { color: #fafaf9 !important; } .mute { color: #a8a29e !important; } .code { background: #0c0a09 !important; border-color: #292524 !important; color: #fafaf9 !important; } .btn { background: #f59e0b !important; } .btn a { color: #1c1917 !important; } .lnk { color: #f59e0b !important; } }</style></head>
733
+ <body class="bg" style="margin:0;padding:0;background:#fafaf9">
734
+ ${c.preheader ? `<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;mso-hide:all">${escapeHtml(c.preheader)}</div>` : ""}
735
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="bg" style="background:#fafaf9"><tr><td align="center" style="padding:24px 12px">
736
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="card" style="max-width:560px;background:#ffffff;border:1px solid #e7e5e4;border-radius:8px">
737
+ <tr><td style="padding:24px 28px 4px"><table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right:10px"><img src="${LOGO_URL}" width="32" height="32" alt="logo" style="display:block;border:0;border-radius:6px"></td><td class="ink" style="font:700 17px/1 ${font};letter-spacing:.02em;color:#1c1917">agent-custody</td></tr></table></td></tr>
738
+ <tr><td style="padding:20px 28px 8px"><h1 class="ink" style="margin:0 0 16px;font:700 22px/1.3 ${font};color:#1c1917">${escapeHtml(c.heading)}</h1>
739
+ ${c.paragraphs.map((v) => p(v, "color:#1c1917")).join("\n")}
740
+ ${c.code ? `<pre class="code ink" style="margin:0 0 16px;padding:12px;background:#fafaf9;border:1px solid #e7e5e4;border-radius:6px;font:12px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#1c1917;white-space:pre-wrap;word-break:break-word">${escapeHtml(c.code)}</pre>` : ""}
741
+ ${button ? `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 16px"><tr><td class="btn" bgcolor="#b45309" style="background:#b45309;border-radius:6px"><a href="${link(button.url)}" style="display:inline-block;padding:12px 24px;font:600 15px/1 ${font};color:#ffffff;text-decoration:none">${escapeHtml(button.label)}</a></td></tr></table>
742
+ ${p("The button does not work? Copy this link into your browser:", "font-size:13px;margin-bottom:4px;color:#57534e", "mute")}<p class="mute" style="margin:0 0 16px;font:13px/1.5 ${font};word-break:break-all"><a href="${link(button.url)}" class="lnk" style="color:#b45309">${escapeHtml(button.url)}</a></p>` : ""}
743
+ </td></tr>
744
+ <tr><td style="padding:8px 28px 24px;border-top:1px solid #e7e5e4">
745
+ ${footer.map((f) => (typeof f === "string" ? `<p class="mute" style="margin:12px 0 0;font:13px/1.5 ${font};color:#57534e">${escapeHtml(f)}</p>` : `<p class="mute" style="margin:12px 0 0;font:13px/1.5 ${font};color:#57534e"><a href="${link(f.url)}" class="lnk" style="color:#b45309">${escapeHtml(f.label)}</a></p>`)).join("\n")}
746
+ </td></tr></table></td></tr></table></body></html>`;
747
+ return { html, text };
748
+ }
465
749
  /** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
466
750
  export async function deliverMail(mail, m, log = console.error) {
467
751
  const f = mail.fetch ?? fetch;
468
752
  try {
469
- const r = await f(mail.url ?? "https://api.resend.com/emails", { method: "POST", headers: { authorization: `Bearer ${mail.apiKey}`, "content-type": "application/json" }, body: JSON.stringify({ from: mail.from, to: [m.to], subject: m.subject, text: m.text }), signal: AbortSignal.timeout(10_000) });
753
+ const body = { from: mail.from, to: [m.to], subject: m.subject, text: m.text, ...(m.html ? { html: m.html } : {}), ...(mail.replyTo ? { reply_to: mail.replyTo } : {}), ...(m.headers ? { headers: m.headers } : {}) };
754
+ const r = await f(mail.url ?? "https://api.resend.com/emails", { method: "POST", headers: { authorization: `Bearer ${mail.apiKey}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000) });
470
755
  if (r.ok)
471
756
  return true;
472
757
  log(`agent-custody portal: mail to ${m.to} refused: ${r.status} ${(await r.text()).slice(0, 200)}`);
@@ -476,37 +761,47 @@ export async function deliverMail(mail, m, log = console.error) {
476
761
  }
477
762
  return false;
478
763
  }
764
+ const UNSUBSCRIBE_TTL_MS = 365 * 86_400_000;
479
765
  /**
480
766
  * The founder's note, sent about an hour after a registration by `sendFollowUps`, once. Written to get the first
481
767
  * receipt appended: it asks which stack they are on, offers to do the integration, and says to start in observe mode.
768
+ * The signer is a setting; the default is the team.
482
769
  */
483
770
  export function founderNote(o) {
484
771
  const first = o.name.trim().split(/\s+/)[0] || o.name;
485
- const signer = o.from.replace(/^.*<|>.*$/g, "");
486
- return {
487
- subject: "Welcome to agent-custody, and one question",
488
- text: [
489
- `Hi ${first},`, "",
490
- `Thanks for registering ${o.tenant} on agent-custody. I am Partha, the founder; you will get me, not a queue.`, "",
491
- "One question so I can help rather than guess: which stack are your agents on, and what do they touch? Claude Code, the OpenAI Agents SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes, plain Python, or an MCP host. If you tell me, I will send the exact config for it, and if it is quicker, I will do the integration with you on a call: twenty minutes gets a first receipt into your log and verified in the browser.", "",
492
- 'Two things worth knowing from the start. Run it in observe mode first, "mode": "observe" in the config: nothing is blocked, and each receipt records what the policy would have denied, so you tune the policy against real traffic before turning it on. And the log only ever receives a hash per receipt; the receipts stay on your machines.', "",
493
- `You are on the free plan, ten thousand appends a month, no card. If you hit that, tell me and I move you up while we talk. The setup sheet is under Setup in the dashboard whenever you need it: ${o.portalUrl}`, "",
494
- `What are you building${o.company ? ` at ${o.company}` : ""}? I would like to know what you want the receipts to prove, and to whom.`, "",
495
- "Partha", `agent-custody.dev · ${signer}`,
496
- ].join("\n"),
497
- };
772
+ const subject = "Welcome to agent-custody, and one question";
773
+ // A named signer writes as one person; the default team signature writes as "we".
774
+ const [I, We, me, intro] = o.signer ? ["I", "I", "me", `I am ${o.signer}${o.signerRole ? `, the ${o.signerRole.toLowerCase()}` : ""}; you will get me, not a queue.`] : ["we", "We", "us", "You are writing to a person, not to a queue."];
775
+ const mail = renderMail({
776
+ heading: "One question about your agents",
777
+ preheader: `Which stack are your agents on? ${We} send the exact config.`,
778
+ paragraphs: [
779
+ `Hi ${first},`,
780
+ `Thanks for registering ${o.tenant} on agent-custody. ${intro}`,
781
+ `One question so that ${I} can help rather than guess: which stack are your agents on, and what do they touch? Claude Code, the OpenAI Agents SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes, plain Python, or an MCP host. If you tell ${me}, ${I} send the exact config for it. If it is quicker, ${I} do the integration with you on a call: twenty minutes gets a first receipt into your log and verified in the browser.`,
782
+ 'Two things to know from the start. Run it in observe mode first, "mode": "observe" in the config: nothing is blocked, and each receipt records what the policy would have denied, so you tune the policy against real traffic before you turn it on. And the log only receives a hash per receipt; the receipts stay on your machines.',
783
+ `You are on the free plan: ten thousand appends a month, no card. If you hit that limit, tell ${me} and ${I} move you up while we talk.`,
784
+ `What are you building${o.company ? ` at ${o.company}` : ""}? ${We} would like to know what you want the receipts to prove, and to whom. Reply to this email.`,
785
+ `${o.signer ?? "The agent-custody team"}${o.signerRole ? `, ${o.signerRole}` : ""}`,
786
+ ],
787
+ button: { label: "Open the setup sheet", url: o.portalUrl },
788
+ footer: ["You get this one note because you registered a tenant on agent-custody. We send no other automatic messages about getting started.", { label: "Do not send me these messages", url: o.unsubscribeUrl }],
789
+ });
790
+ return { subject, ...mail, headers: { "List-Unsubscribe": `<${o.unsubscribeUrl}>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" } };
498
791
  }
499
792
  /**
500
793
  * Sends the founder's note to every account registered between an hour and a week ago that has not had it, and
501
- * marks each one. Accounts on the operator's own mail domains are marked without a message. Idempotent: run it hourly.
794
+ * marks each one. Accounts on the operator's own mail domains and accounts that opted out are skipped without a message.
795
+ * `secret` is the portal's secret: it signs the opt-out link. Idempotent: run it hourly.
502
796
  */
503
- export async function sendFollowUps(store, mail, o = { portalUrl: "https://app.agent-custody.dev/" }) {
797
+ export async function sendFollowUps(store, mail, o) {
504
798
  const log = o.log ?? console.error;
505
799
  const now = o.now ?? new Date();
506
800
  const own = new Set([mail.from, mail.notify ?? ""].map((a) => a.replace(/^.*<|>.*$/g, "").split("@")[1]?.toLowerCase()).filter(Boolean));
507
801
  const sent = [];
508
802
  const skipped = [];
509
803
  const failed = [];
804
+ const portalUrl = o.portalUrl.replace(/\/?$/, "/");
510
805
  for (const u of await store.pendingFollowUps({ now, minAgeMs: o.minAgeMs ?? 3_600_000, maxAgeMs: o.maxAgeMs ?? 7 * 86_400_000 })) {
511
806
  if (own.has(u.email.split("@")[1]?.toLowerCase() ?? "")) {
512
807
  if (!o.dryRun)
@@ -514,7 +809,8 @@ export async function sendFollowUps(store, mail, o = { portalUrl: "https://app.a
514
809
  skipped.push(u.email);
515
810
  continue;
516
811
  }
517
- const note = founderNote({ name: u.name, tenant: u.tenantId, company: u.company, portalUrl: o.portalUrl, from: mail.from });
812
+ const unsubscribeUrl = `${portalUrl}unsubscribe?token=${signSession(o.secret, `unsub:${u.id}`, UNSUBSCRIBE_TTL_MS)}`;
813
+ const note = founderNote({ name: u.name, tenant: u.tenantId, company: u.company, portalUrl, unsubscribeUrl, ...(o.signer ? { signer: o.signer } : {}), ...(o.signerRole ? { signerRole: o.signerRole } : {}) });
518
814
  if (o.dryRun) {
519
815
  sent.push(u.email);
520
816
  continue;
@@ -538,27 +834,49 @@ export function portalHandler(o) {
538
834
  const registrations = new RateLimiter({ perSecond: 1 / 600, burst: 5 });
539
835
  // per account, whatever the address
540
836
  const mfaFailures = new RateLimiter({ perSecond: 1 / 120, burst: 5 });
837
+ const resetsByClient = new RateLimiter({ perSecond: 1 / 600, burst: 5 });
838
+ const resetsByEmail = new RateLimiter({ perSecond: 1 / 900, burst: 3 });
541
839
  const base = o.publicUrl.endsWith("/") ? o.publicUrl : `${o.publicUrl}/`;
542
840
  const cookieName = "custody_session";
543
841
  const sheet = (tenant, logId) => welcomeSheet({ tenant, logId, publicUrl: base, ...(o.checkpointsUrl ? { checkpointsUrl: o.checkpointsUrl } : {}), ...(o.keyid ? { keyid: o.keyid } : {}) });
544
842
  const portalBase = (o.portalUrl ?? "http://localhost/").replace(/\/?$/, "/");
545
843
  // Mail is best effort and off the request path: a provider outage is logged, never a failed registration.
546
- const send = async (m) => { if (o.mail)
547
- await deliverMail(o.mail, m, log); };
844
+ const send = async (m) => (o.mail ? deliverMail(o.mail, m, log) : false);
548
845
  /** The verification link: a signed, single-purpose token good for a day. Until it is used, a provider sign-in for this address will not link to the account. */
549
- const verificationMail = (u) => ({
550
- to: u.email,
551
- subject: "Verify your email address for agent-custody",
552
- text: ["Hello,", "", "Please confirm this address for your agent-custody account by opening the link below. It is good for 24 hours.", "", `${portalBase}verify-email?token=${signSession(o.secret, `verify:${u.id}`, 86_400_000)}`, "", "If you did not create an account, ignore this mail; nothing was created in your name that works without it.", "", "agent-custody"].join("\n"),
553
- });
554
- const welcomeMail = (to, name, tenant, logId) => send({ to, subject: `Your agent-custody log "${tenant}" is ready`, text: [
555
- `Hello ${name},`, "",
556
- `Your tenant "${tenant}" is live on the hosted log. Your API key was shown once when you registered and is not in this email; if it is gone, mint another under API keys at ${portalBase}.`, "",
557
- "Everything below is under Setup in the dashboard whenever you need it.", "",
558
- sheet(tenant, logId), "",
559
- `Dashboard: ${portalBase}`, "Getting started: https://agent-custody.dev/guide/getting-started", "Questions: reply to this email.",
560
- ].join("\n") });
561
- const notifyMail = (p) => o.mail?.notify ? send({ to: o.mail.notify, subject: `New registration: ${p.company} (${p.tenant})`, text: [`${p.name}${p.role ? `, ${p.role}` : ""} at ${p.company} registered tenant "${p.tenant}".`, "", `email ${p.email}`, `phone ${p.phone ?? "-"}`, `telegram ${p.telegram ? `@${p.telegram}` : "-"}`, "", "The Registrations section of the admin page has the same, with their usage."].join("\n") }) : Promise.resolve();
846
+ const verificationMail = (u) => {
847
+ const subject = "Verify your email address for agent-custody";
848
+ return { to: u.email, subject, ...renderMail({
849
+ heading: "Confirm your email address",
850
+ preheader: "Confirm this address for your agent-custody account. The link is good for 24 hours.",
851
+ paragraphs: ["Hello,", "Confirm this address for your agent-custody account. The link is good for 24 hours."],
852
+ button: { label: "Confirm email address", url: `${portalBase}verify-email?token=${signSession(o.secret, `verify:${u.id}`, 86_400_000)}` },
853
+ footer: ["If you did not create an account, ignore this email. Nothing that works without this step was created in your name."],
854
+ }) };
855
+ };
856
+ const resetMail = (to, token) => ({ to, subject: "Reset your agent-custody password", ...renderMail({
857
+ heading: "Reset your password",
858
+ preheader: "The link works one time, for one hour.",
859
+ paragraphs: ["Hello,", "Someone asked to reset the password of your agent-custody account. Use the button below to set a new password. The link works one time, for one hour."],
860
+ button: { label: "Set a new password", url: `${portalBase}reset-password?token=${token}` },
861
+ footer: ["If you did not ask for this, ignore this email. Your password stays the same."],
862
+ }) });
863
+ const welcomeMail = (to, name, tenant, logId) => send({ to, subject: `Your agent-custody log "${tenant}" is ready`, ...renderMail({
864
+ heading: `Your log "${tenant}" is ready`,
865
+ preheader: "Your tenant is live on the hosted log. The setup sheet is below.",
866
+ paragraphs: [
867
+ `Hello ${name},`,
868
+ `Your tenant "${tenant}" is live on the hosted log. Your API key was shown once when you registered and is not in this email. If it is gone, create another under API keys in the dashboard.`,
869
+ "The setup sheet is below. It is also under Setup in the dashboard.",
870
+ ],
871
+ code: sheet(tenant, logId),
872
+ button: { label: "Open the dashboard", url: portalBase },
873
+ footer: ["Getting started: https://agent-custody.dev/guide/getting-started", "Questions? Reply to this email."],
874
+ }) });
875
+ const notifyMail = (p) => o.mail?.notify ? send({ to: o.mail.notify, subject: `New registration: ${p.company} (${p.tenant})`, ...renderMail({
876
+ heading: `New registration: ${p.company}`,
877
+ paragraphs: [`${p.name}${p.role ? `, ${p.role}` : ""} at ${p.company} registered tenant "${p.tenant}".`, "The Registrations section of the admin page has the same, with their usage."],
878
+ code: [`email ${p.email}`, `phone ${p.phone ?? "-"}`, `telegram ${p.telegram ? `@${p.telegram}` : "-"}`].join("\n"),
879
+ }) }) : Promise.resolve(false);
562
880
  const exportCommand = (tenant) => `npx @agent-custody/receipts log-export --log-url ${base} --tenant ${tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`;
563
881
  // The welcome sheet as data: what the page renders as numbered steps, at registration and again under Setup.
564
882
  const setupFor = (tenant, logId) => {
@@ -576,6 +894,7 @@ export function portalHandler(o) {
576
894
  export: exportCommand(tenant),
577
895
  };
578
896
  };
897
+ const keyList = async (tenantId) => (await o.tenancy.listTokens(tenantId)).map((k) => ({ label: k.label, hash: k.tokenHash.slice(0, 12), createdAt: k.createdAt, revokedAt: k.revokedAt, lastUsedAt: k.lastUsedAt }));
579
898
  return async (req, res) => {
580
899
  const url = new URL(req.url ?? "/", "http://localhost");
581
900
  const addr = clientAddress(req, o.trustProxy);
@@ -592,8 +911,11 @@ export function portalHandler(o) {
592
911
  // the state between the first step and the code; never a session
593
912
  const mfaCookie = (id) => `custody_mfa=${id ? signSession(o.secret, `mfa:${id}`, 300_000) : ""}; Path=/api/login; HttpOnly; SameSite=Strict${o.trustProxy ? "; Secure" : ""}; Max-Age=${id ? 300 : 0}`;
594
913
  const cookies = Object.fromEntries((req.headers.cookie ?? "").split(";").map((c) => c.trim().split("=")).filter(([k]) => k));
595
- const userId = readSession(o.secret, cookies[cookieName]);
596
- const via = readSessionVia(o.secret, cookies[cookieName]);
914
+ const claims = readClaims(o.secret, cookies[cookieName]);
915
+ const userId = claims?.u ?? null;
916
+ const via = claims?.a ?? null;
917
+ // a password reset or change ends every session and MFA cookie signed before it
918
+ const fresh = (u, c) => (u && c && c.i >= (u.sessionsAfter ?? 0) ? u : null);
597
919
  // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
598
920
  // would not carry it. The page's own navigation to / does.
599
921
  const signedInPage = (who, next, setCookies, lead) => {
@@ -636,7 +958,7 @@ export function portalHandler(o) {
636
958
  if (req.method === "GET" && url.pathname === "/") {
637
959
  res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'" });
638
960
  const providers = JSON.stringify(["github", "google"].filter((p) => !!o.oauth?.[p]));
639
- return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])).replace("__PROVIDERS__", providers));
961
+ return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])).replace("__PROVIDERS__", providers).replace("__MAIL__", String(!!o.mail)).replace("__PLANS__", PLANS_JSON));
640
962
  }
641
963
  // ---- Stripe's webhook: the only caller that is not a browser with a session ----
642
964
  if (req.method === "POST" && url.pathname === "/stripe/webhook") {
@@ -710,13 +1032,17 @@ export function portalHandler(o) {
710
1032
  return { status: 200, body: { tenant: t.id, logId: t.logId, plan: t.plan, token: minted.token, tokenHash: minted.tokenHash.slice(0, 12), welcome: sheet(t.id, t.logId), setup: setupFor(t.id, t.logId), exportCommand: exportCommand(t.id) } };
711
1033
  };
712
1034
  // `on` is the state the account must be in: true to sign in or turn MFA off, false to turn it on.
1035
+ // With MFA on, a recovery code works once in place of a code.
713
1036
  const checkCode = async (id, code, on) => {
714
1037
  if (!mfaFailures.take(id))
715
1038
  return { status: 429, body: { error: "too many codes tried for this account; wait a few minutes" } };
716
1039
  const m = await store.mfa(id);
717
1040
  if (!m.secret || m.enabled !== on)
718
1041
  return { status: 409, body: { error: on ? "MFA is not on for this account" : "start the MFA setup first" } };
719
- const step = totpStep(Buffer.from(m.secret, "hex"), String(code ?? ""));
1042
+ const given = String(code ?? "").trim();
1043
+ if (on && !/^[0-9]{6}$/.test(given))
1044
+ return (await store.takeRecoveryCode(id, given)) ? null : { status: 401, body: { error: "that code is not valid, or was used already" } };
1045
+ const step = totpStep(Buffer.from(m.secret, "hex"), given);
720
1046
  if (step === null || !(await store.takeMfaStep(id, step)))
721
1047
  return { status: 401, body: { error: "that code is not valid, or was used already" } };
722
1048
  if (!on)
@@ -759,6 +1085,20 @@ export function portalHandler(o) {
759
1085
  void send(verificationMail(user));
760
1086
  return json(r.status, r.body, cookie);
761
1087
  }
1088
+ // A GET changes nothing: a mail scanner opens the link before the person does. The opt-out is the POST, from the form below or from a mail provider's one-click request. The body of that request is not read.
1089
+ if ((req.method === "GET" || req.method === "POST") && url.pathname === "/unsubscribe") {
1090
+ const token = url.searchParams.get("token") ?? "";
1091
+ const who = readSession(o.secret, token);
1092
+ const userId = who?.startsWith("unsub:") ? who.slice("unsub:".length) : null;
1093
+ if (!userId || !(await store.user(userId)))
1094
+ return page(400, "Link not valid", "This link is not valid or has expired. Reply to the email and we stop the messages by hand.");
1095
+ if (req.method === "GET") {
1096
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'" });
1097
+ return void res.end(resultPage("Stop these emails?", `<p>Press the button to stop the automatic messages about getting started that agent-custody sends to this account.</p><form method="post" action="/unsubscribe?token=${encodeURIComponent(token)}" style="margin-top:1.25rem"><button type="submit" style="font:inherit;font-weight:600;padding:.6rem 1.2rem;border:0;border-radius:8px;background:var(--accent);color:var(--panel);cursor:pointer">Stop these emails</button></form>`));
1098
+ }
1099
+ await store.optOutOfFollowUps(userId);
1100
+ return page(200, "You are unsubscribed", "You get no more automatic messages about getting started from agent-custody. Messages about your account, such as a sign-in or invite email, still arrive.");
1101
+ }
762
1102
  if (req.method === "GET" && url.pathname === "/verify-email") {
763
1103
  const who = readSession(o.secret, url.searchParams.get("token") ?? undefined);
764
1104
  if (!who?.startsWith("verify:"))
@@ -878,7 +1218,7 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
878
1218
  if (!provider[2]) {
879
1219
  // ?link=1 from a signed-in session links the provider to that account instead of signing in; the state says so
880
1220
  const linking = url.searchParams.get("link") === "1";
881
- if (linking && !userId)
1221
+ if (linking && !fresh(userId ? await store.user(userId) : null, claims))
882
1222
  return json(401, { error: "sign in first, then link a provider from the account page" });
883
1223
  const state = signSession(o.secret, `oauth:${name}:${linking ? `link:${userId}:` : ""}${randomBytes(16).toString("hex")}`, 600_000);
884
1224
  const authorize = name === "github"
@@ -930,7 +1270,7 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
930
1270
  let user;
931
1271
  if (linkTo) {
932
1272
  // linking: the signed state records the session that started it (the Strict cookie does not come back from the provider), so the provider's email need not match; when it does, it also confirms the address
933
- const owner = await store.user(linkTo);
1273
+ const owner = fresh(await store.user(linkTo), readClaims(o.secret, state));
934
1274
  if (!owner)
935
1275
  return json(401, { error: "the account that started the link no longer exists" }, { "set-cookie": stateCookie(null) });
936
1276
  await store.linkIdentity(name, subject, email, owner.id);
@@ -971,8 +1311,8 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
971
1311
  if (!loginFailures.take(`login:${addr}`))
972
1312
  return json(429, { error: "too many attempts; wait a minute" });
973
1313
  const b = await jsonBody();
974
- const who = readSession(o.secret, cookies.custody_mfa);
975
- const half = who?.startsWith("mfa:") ? await store.user(who.slice(4)) : null;
1314
+ const half_ = readClaims(o.secret, cookies.custody_mfa);
1315
+ const half = half_?.u.startsWith("mfa:") ? fresh(await store.user(half_.u.slice(4)), half_) : null;
976
1316
  if (!half)
977
1317
  return json(401, { error: "the password step expired; sign in again" });
978
1318
  const refused = await checkCode(half.id, b.code, true);
@@ -980,12 +1320,71 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
980
1320
  return json(refused.status, refused.body);
981
1321
  return json(200, { email: half.email }, { "set-cookie": [setCookie(signSession(o.secret, half.id)), mfaCookie(null)] });
982
1322
  }
1323
+ // ---- password reset by mail: the same answer for every address, and the token proves the mailbox ----
1324
+ if (req.method === "POST" && url.pathname === "/api/password/forgot") {
1325
+ const email = String((await jsonBody()).email ?? "").trim().toLowerCase();
1326
+ if (!o.mail)
1327
+ return json(503, { error: "mail is not configured on this portal" });
1328
+ if (!EMAIL.test(email))
1329
+ return json(400, { error: "a valid email address is needed" });
1330
+ if (!resetsByClient.take(`reset:${addr}`))
1331
+ return json(429, { error: "too many reset requests from this address; try again later" });
1332
+ // the lookup runs after the answer, so the time to answer does not tell whether the address has an account
1333
+ if (resetsByEmail.take(email))
1334
+ void (async () => {
1335
+ const u = await store.userByEmail(email);
1336
+ // a member of a tenant that enforces single sign-on gets no password
1337
+ if (!u || (await enforcedFor(u.id)))
1338
+ return;
1339
+ await send(resetMail(u.email, await store.createPasswordReset(u.id)));
1340
+ log(`agent-custody portal: ${u.email} asked for a password reset`);
1341
+ })().catch((e) => log(`agent-custody portal: a password reset failed: ${e instanceof Error ? e.message : String(e)}`));
1342
+ return json(200, { ok: true });
1343
+ }
1344
+ if (req.method === "GET" && url.pathname === "/reset-password") {
1345
+ const token = url.searchParams.get("token") ?? "";
1346
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'none'; base-uri 'none'" });
1347
+ return void res.end(`${resultPage("Set a new password", `<style>form { display: grid; gap: .75rem; margin-top: 1rem; } [hidden] { display: none; } label { display: grid; gap: .35rem; font-weight: 600; font-size: .9rem; } label span { font-weight: 400; color: var(--ink2); font-size: .82rem; } input { font: inherit; padding: .6rem .8rem; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); } button { font: inherit; font-weight: 600; padding: .6rem .9rem; border-radius: 8px; border: 1px solid var(--accent); background: var(--accent); color: #fff; cursor: pointer; }</style>
1348
+ <form id="f"><label>New password<input id="pw" type="password" autocomplete="new-password" minlength="10" required><span>At least ten characters.</span></label><button type="submit">Set the password</button></form><p id="m" aria-live="polite"></p>`)}<script>
1349
+ document.getElementById("f").onsubmit = async (e) => {
1350
+ e.preventDefault();
1351
+ const m = document.getElementById("m");
1352
+ const r = await fetch("/api/password/reset", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ token: ${JSON.stringify(token).replace(/</g, "\\u003c")}, password: document.getElementById("pw").value }) });
1353
+ const b = await r.json().catch(() => ({}));
1354
+ if (r.ok) { document.getElementById("f").hidden = true; m.innerHTML = "Your password is set. Other sessions of this account are signed out. <a href='/'>Sign in</a>."; }
1355
+ else m.textContent = b.error || "The password was not set.";
1356
+ };
1357
+ </script>`);
1358
+ }
1359
+ if (req.method === "POST" && url.pathname === "/api/password/reset") {
1360
+ const b = await jsonBody();
1361
+ const password = String(b.password ?? "");
1362
+ // checked before the token is used, so a short password does not spend the link
1363
+ if (password.length < 10)
1364
+ return json(400, { error: "the password needs at least ten characters" });
1365
+ const id = await store.takePasswordReset(String(b.token ?? ""));
1366
+ const u = id ? await store.user(id) : null;
1367
+ if (!u)
1368
+ return json(400, { error: "this reset link is not valid, was used already, or is older than one hour; ask for a new one" });
1369
+ if (await enforcedFor(u.id))
1370
+ return json(403, { error: ENFORCED });
1371
+ await store.setPassword(u.id, password);
1372
+ // The link proves the mailbox, and the new password replaces any password set before that proof. A provider
1373
+ // linked before the address was proved was linked by whoever held that password, so it goes.
1374
+ if (!u.emailVerifiedAt) {
1375
+ await store.unlinkIdentities(u.id);
1376
+ await store.markEmailVerified(u.id);
1377
+ }
1378
+ log(`agent-custody portal: ${u.email} reset their password`);
1379
+ // no session here: the user signs in with the new password, and two-step sign-in still applies
1380
+ return json(200, { ok: true });
1381
+ }
983
1382
  if (req.method === "POST" && url.pathname === "/api/logout")
984
1383
  return json(200, { ok: true }, { "set-cookie": setCookie(null) });
985
1384
  // ---- everything below needs a session ----
986
1385
  if (!url.pathname.startsWith("/api/"))
987
1386
  return json(404, { error: "not found" });
988
- const user = userId ? await store.user(userId) : null;
1387
+ const user = fresh(userId ? await store.user(userId) : null, claims);
989
1388
  if (!user)
990
1389
  return json(401, { error: "sign in first" });
991
1390
  if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
@@ -994,7 +1393,7 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
994
1393
  const ssoConf = tenantId ? await store.ssoOf(tenantId) : null;
995
1394
  if (ssoConf?.enforced && via !== `sso:${tenantId}`)
996
1395
  return json(401, { error: ENFORCED });
997
- const account = async () => ({ emailVerified: !!user.emailVerifiedAt, identities: await store.identities(user.id), providers: ["github", "google"].filter((p) => !!o.oauth?.[p]), mail: !!o.mail, mfa: (await store.mfa(user.id)).enabled });
1396
+ const account = async () => { const m = await store.mfa(user.id); return { emailVerified: !!user.emailVerifiedAt, identities: await store.identities(user.id), providers: ["github", "google"].filter((p) => !!o.oauth?.[p]), mail: !!o.mail, mfa: m.enabled, recoveryCodes: m.recoveryCodes }; };
998
1397
  if (req.method === "POST" && url.pathname === "/api/verify-email") {
999
1398
  const who = readSession(o.secret, String((await jsonBody()).token ?? ""));
1000
1399
  if (!who?.startsWith("verify:"))
@@ -1021,7 +1420,8 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
1021
1420
  if (!(await store.setMfaSecret(user.id, secret.toString("hex"))))
1022
1421
  return json(409, { error: "MFA is on already; turn it off first" });
1023
1422
  const b32 = base32(secret);
1024
- return json(200, { secret: b32, uri: `otpauth://totp/agent-custody:${encodeURIComponent(user.email)}?secret=${b32}&issuer=agent-custody` });
1423
+ const uri = `otpauth://totp/agent-custody:${encodeURIComponent(user.email)}?secret=${b32}&issuer=agent-custody`;
1424
+ return json(200, { secret: b32, uri, qr: qrSvg(uri) });
1025
1425
  }
1026
1426
  if (req.method === "POST" && (url.pathname === "/api/mfa/enable" || url.pathname === "/api/mfa/disable")) {
1027
1427
  const on = url.pathname.endsWith("/disable");
@@ -1031,7 +1431,31 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
1031
1431
  if (on)
1032
1432
  await store.resetMfa(user.email);
1033
1433
  log(`agent-custody portal: ${user.email} turned MFA ${on ? "off" : "on"}`);
1034
- return json(200, { mfa: !on });
1434
+ return json(200, { mfa: !on, ...(on ? {} : { recoveryCodes: await store.newRecoveryCodes(user.id) }) });
1435
+ }
1436
+ // a code is needed, so a stolen session cannot take the codes
1437
+ if (req.method === "POST" && url.pathname === "/api/mfa/recovery") {
1438
+ const refused = await checkCode(user.id, (await jsonBody()).code, true);
1439
+ if (refused)
1440
+ return json(refused.status, refused.body);
1441
+ log(`agent-custody portal: ${user.email} made new recovery codes`);
1442
+ return json(200, { recoveryCodes: await store.newRecoveryCodes(user.id) });
1443
+ }
1444
+ if (req.method === "POST" && url.pathname === "/api/password/change") {
1445
+ const b = await jsonBody();
1446
+ const password = String(b.password ?? "");
1447
+ if (ssoConf?.enforced)
1448
+ return json(409, { error: "this tenant signs in through its identity provider; its members have no password here" });
1449
+ if (password.length < 10)
1450
+ return json(400, { error: "the new password needs at least ten characters" });
1451
+ if (!loginFailures.take(`password:${user.id}`))
1452
+ return json(429, { error: "too many attempts; wait a minute" });
1453
+ if (!(await store.authenticate(user.email, String(b.current ?? ""))))
1454
+ return json(401, { error: "the current password is not correct" });
1455
+ await store.setPassword(user.id, password);
1456
+ log(`agent-custody portal: ${user.email} changed their password`);
1457
+ // this browser stays signed in; every other session ends
1458
+ return json(200, { ok: true }, { "set-cookie": setCookie(signSession(o.secret, user.id, undefined, via ?? undefined)) });
1035
1459
  }
1036
1460
  // The address must be verified: otherwise anyone who registers the invited address with a password gets in.
1037
1461
  if (req.method === "POST" && url.pathname === "/api/invites/accept") {
@@ -1083,11 +1507,22 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
1083
1507
  const u = await o.tenancy.usage(month);
1084
1508
  months.push({ month, appends: u.tenants.find((t) => t.id === tenantId)?.appends ?? 0 });
1085
1509
  }
1086
- const keys = (await o.tenancy.listTokens(tenantId)).map((k) => ({ label: k.label, hash: k.tokenHash.slice(0, 12), createdAt: k.createdAt, revokedAt: k.revokedAt }));
1510
+ const keys = await keyList(tenantId);
1087
1511
  const audit = await o.tenancy.audit({ tenant: tenantId, limit: 50 });
1088
1512
  const billing = await store.billing(tenantId);
1089
1513
  return json(200, { tenant: tenantId, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, treeSize: size, rootHash: size ? await backend.root(size) : null, latestCheckpoint: latest ? { treeSize: latest.treeSize, signedAt: latest.signedAt } : null, months, keys, audit, billing: billing ? { status: billing.status } : null, urls: { log: `${base}t/${tenantId}/`, keys: `${base}.well-known/agent-custody-log.json`, checkpoints: o.checkpointsUrl ? `${o.checkpointsUrl.replace(/\/?$/, "/")}${tenantId}/latest.json` : null }, exportCommand: exportCommand(tenantId), welcome: sheet(tenantId, tenant.logId), setup: setupFor(tenantId, tenant.logId), stripe: !!o.stripe });
1090
1514
  }
1515
+ if (req.method === "GET" && url.pathname === "/api/audit") {
1516
+ const limit = url.searchParams.get("limit") ?? "25";
1517
+ const before = url.searchParams.get("before");
1518
+ if (!/^\d{1,3}$/.test(limit) || +limit < 1 || +limit > 100)
1519
+ return json(400, { error: "limit is a whole number from 1 to 100" });
1520
+ if (before !== null && !/^[1-9]\d{0,15}$/.test(before))
1521
+ return json(400, { error: "before is the id of an entry, a positive whole number" });
1522
+ const entries = await o.tenancy.audit({ tenant: tenantId, limit: +limit + 1, ...(before ? { before: +before } : {}) });
1523
+ const more = entries.length > +limit;
1524
+ return json(200, { entries: entries.slice(0, +limit), next: more ? entries[+limit - 1].id : null });
1525
+ }
1091
1526
  if (req.method === "GET" && url.pathname === "/api/members")
1092
1527
  return json(200, { members: await store.members(tenantId), invites: await store.invitesOf(tenantId) });
1093
1528
  const ownerOnly = (...roles) => myRole !== "owner" && roles.includes("owner");
@@ -1106,8 +1541,14 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
1106
1541
  return json(403, OWNER_ONLY);
1107
1542
  await store.invite(tenantId, email, role, user.email);
1108
1543
  log(`agent-custody portal: ${user.email} invited ${email} to tenant ${tenantId} as ${role}`);
1109
- void send({ to: email, subject: `You are invited to ${tenantId} on agent-custody`, text: [`${user.email} invited you to the agent-custody tenant "${tenantId}" as ${role}.`, "", `Create an account or sign in with this address at ${portalBase}, verify the address, and accept the invite. The invite is good for seven days.`, "", "agent-custody"].join("\n") });
1110
- return json(200, { invited: email, role });
1544
+ const emailSent = await send({ to: email, subject: `You are invited to ${tenantId} on agent-custody`, ...renderMail({
1545
+ heading: `Join "${tenantId}" on agent-custody`,
1546
+ preheader: `${user.email} invited you as ${role}. The invite is good for seven days.`,
1547
+ paragraphs: [`${user.email} invited you to the agent-custody tenant "${tenantId}" as ${role}.`, `Sign in, or create an account, with this address: ${email}. Verify the address. The first screen then shows the invite with an Accept button. The invite is good for seven days.`],
1548
+ button: { label: "Accept the invite", url: portalBase },
1549
+ footer: ["If you do not know the person who invited you, ignore this email."],
1550
+ }) });
1551
+ return json(200, { invited: email, role, emailSent });
1111
1552
  }
1112
1553
  if (req.method === "POST" && url.pathname === "/api/invites/remove") {
1113
1554
  const email = String((await jsonBody()).email ?? "").trim().toLowerCase();
@@ -1142,7 +1583,7 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
1142
1583
  return json(200, { removed: true });
1143
1584
  }
1144
1585
  if (req.method === "GET" && url.pathname === "/api/keys") {
1145
- return json(200, { keys: (await o.tenancy.listTokens(tenantId)).map((k) => ({ label: k.label, hash: k.tokenHash.slice(0, 12), createdAt: k.createdAt, revokedAt: k.revokedAt })) });
1586
+ return json(200, { keys: await keyList(tenantId) });
1146
1587
  }
1147
1588
  if (req.method === "POST" && url.pathname === "/api/keys") {
1148
1589
  const b = await jsonBody();
@@ -1241,149 +1682,189 @@ export function servePortal(o, opts) {
1241
1682
  });
1242
1683
  }
1243
1684
  // ---- the page: one file, no framework, no outside requests ----
1685
+ /** The plan cards of the Billing page. The appends come from PLAN_QUOTAS; a test keeps the names, prices, and appends equal to site/pricing.md. */
1686
+ export const PLAN_CARDS = [
1687
+ { plan: "free", name: "Free", price: "$0", points: ["One tenant on the shared log", "Export and audit trail", "Community support on GitHub"] },
1688
+ { plan: "team", name: "Team", price: "$50 a month", points: ["One tenant on the shared log", "Export and audit trail", "Email support, answer within two working days"] },
1689
+ { plan: "enterprise", name: "Enterprise", price: "by conversation", points: ["A dedicated log, your signing key, your region", "A named contact and a stated response time", "A signed agreement and a DPA"] },
1690
+ ];
1691
+ const PLANS_JSON = JSON.stringify(PLAN_CARDS.map((c) => ({ ...c, appends: PLAN_QUOTAS[c.plan] })));
1244
1692
  const FAVICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#b45309"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path d="M25 20h14M25 27h14" stroke="#b45309" stroke-width="2.6" stroke-linecap="round"/><path d="M25 37.5l5 4.5 9.5-10" fill="none" stroke="#b45309" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
1245
- const MARK = '<svg class="mark" viewBox="0 0 64 64" aria-hidden="true"><rect class="tile" width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path class="ink" d="M25 20h14M25 27h14" stroke-width="2.6" stroke-linecap="round"/><path class="ink" d="M25 37.5l5 4.5 9.5-10" fill="none" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
1246
1693
  // The small pages outside the app (errors, results, the address check) share the brand without the app's script.
1247
1694
  const RESULT_STYLE = `<style>
1248
- :root { color-scheme: light dark; --ink: #1b2430; --ink2: #5b6b7a; --line: #d7dfe5; --bg: #f5f7f9; --panel: #ffffff; --accent: #b45309; --accent-bg: #fbf1dc; }
1249
- @media (prefers-color-scheme: dark) { :root { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #f59e0b; --accent-bg: #2d2412; } }
1250
- * { box-sizing: border-box; }
1251
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 1.5rem .75rem; color: var(--ink); font: 15px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; background-color: var(--bg); background-image: radial-gradient(56rem 26rem at 50% -8rem, var(--accent-bg), transparent 72%), radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink2) 20%, transparent) 1px, transparent 0); background-size: 100% 100%, 22px 22px; background-repeat: no-repeat, repeat; }
1252
- main { position: relative; width: 100%; max-width: 27rem; padding: 2rem 2.25rem; background: var(--panel); border: 1px solid var(--line); border-top: 4px solid var(--accent); border-radius: 14px; box-shadow: 0 1px 2px rgb(0 0 0 / .05), 0 18px 40px -18px rgb(0 0 0 / .25); }
1253
- .brand { display: inline-flex; align-items: center; gap: .55rem; margin: 0 0 1.25rem; color: var(--ink); font-weight: 700; letter-spacing: .04em; text-decoration: none; }
1695
+ ${DESIGN_CSS}
1696
+ body { min-height: 100vh; display: grid; place-items: center; padding: 1.5rem .75rem; font-size: var(--text-md); line-height: 1.6; background-color: var(--bg); background-image: radial-gradient(56rem 26rem at 50% -8rem, var(--accent-bg), transparent 72%), radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink2) 20%, transparent) 1px, transparent 0); background-size: 100% 100%, 22px 22px; background-repeat: no-repeat, repeat; }
1697
+ main { position: relative; width: 100%; max-width: 27rem; padding: 2rem 2.25rem; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md); box-shadow: var(--shadow); }
1698
+ .brand { display: inline-flex; align-items: center; gap: .55rem; margin: 0 0 1.25rem; color: var(--ink); font-weight: 700; text-decoration: none; }
1254
1699
  .mark { width: 28px; height: 28px; display: block; } .mark .tile { fill: var(--accent); } .mark .ink { stroke: var(--accent); }
1255
- h1 { margin: 0 0 .5rem; font-size: 1.4rem; line-height: 1.25; letter-spacing: -.02em; }
1700
+ h1 { margin: 0 0 .5rem; }
1256
1701
  p { margin: 0; color: var(--ink2); overflow-wrap: anywhere; }
1257
- a { color: var(--accent); font-weight: 600; text-underline-offset: 3px; } a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 2px; }
1702
+ a { font-weight: 600; }
1258
1703
  @media (max-width: 30rem) { main { padding: 1.5rem 1.25rem; } }
1259
1704
  </style>`;
1260
1705
  const resultPage = (title, body, head = "") => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${head}<title>${title}</title>${RESULT_STYLE}<main><a class="brand" href="/">${MARK}agent-custody</a><h1>${title}</h1>${body}</main>`;
1706
+ // the website's one nav list, on the dashboard's own host
1707
+ const DASHBOARD_NAV = SITE_NAV.map((l) => `<a href="${siteUrl(l.link)}" target="_blank" rel="noopener">${l.text}</a>`).join("");
1261
1708
  const PORTAL_PAGE = `<!doctype html>
1709
+ <html lang="en">
1262
1710
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
1263
1711
  <title>agent-custody</title>
1264
1712
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
1265
1713
  <script>(() => { try { const t = localStorage.getItem("agent-custody-theme"); if (t === "dark" || t === "light") document.documentElement.dataset.theme = t; } catch {} })();</script>
1266
1714
  <style>
1267
- :root { color-scheme: light dark; --ink: #1b2430; --ink2: #5b6b7a; --line: #d7dfe5; --bg: #f5f7f9; --panel: #ffffff; --accent: #b45309; --accent-bg: #fbf1dc; --warn: #8a5a00; --bad: #b3261e; --ok: #1f7a4d; --accent-ink: #ffffff; --accent-hover: #92400e; --field: #a9b4bd; --lift: 0 1px 2px rgb(0 0 0 / .04); --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; }
1268
- @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #f59e0b; --accent-bg: #2d2412; --warn: #e2b862; --bad: #ff8a80; --ok: #6fd39a; --accent-ink: #1c1917; --accent-hover: #fbbf24; --field: #3d4c57; --lift: none; } }
1269
- :root[data-theme="dark"] { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #f59e0b; --accent-bg: #2d2412; --warn: #e2b862; --bad: #ff8a80; --ok: #6fd39a; --accent-ink: #1c1917; --accent-hover: #fbbf24; --field: #3d4c57; --lift: none; }
1270
- * { box-sizing: border-box; }
1271
- body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
1272
- .top { display: flex; align-items: center; gap: 1rem; padding: .7rem 1.25rem; border-bottom: 1px solid var(--line); background: var(--panel); }
1273
- .brand { font-weight: 700; letter-spacing: .04em; display: inline-flex; align-items: center; gap: .5rem; color: var(--ink); text-decoration: none; } .brand svg { width: 20px; height: 20px; display: block; } .brand rect { fill: var(--accent); }
1274
- .top .links { margin-left: auto; display: flex; gap: .9rem; font-size: .9rem; } .top .links a { color: var(--accent); text-decoration: none; }
1275
- .top .who { color: var(--ink2); font-size: .9rem; margin-left: .5rem; }
1276
- button.theme { background: transparent; color: var(--ink2); border: 1px solid var(--line); padding: .25rem .6rem; font-size: .8rem; border-radius: 4px; } button.theme:hover { color: var(--ink); }
1277
- .pill { display: inline-block; padding: .05rem .5rem; border-radius: 999px; font: 600 .72rem/1.6 var(--mono); letter-spacing: .06em; text-transform: uppercase; background: var(--accent-bg); color: var(--accent); }
1278
- .notice { padding: .6rem 1.25rem; font-size: .9rem; color: var(--ink); background: var(--accent-bg); border-bottom: 1px solid var(--line); } .notice a, .notice button { margin-left: .6rem; } .notice button { font: inherit; background: none; border: 1px solid var(--line); border-radius: 4px; padding: .1rem .5rem; color: var(--ink); cursor: pointer; }
1715
+ ${DESIGN_CSS}
1716
+ :root { --field: var(--line-strong); --lift: 0 1px 2px rgb(28 25 23 / .04); }
1717
+ .top { display: flex; align-items: center; gap: var(--space-3); min-height: 3.5rem; padding: 0 1.25rem; border-bottom: 1px solid var(--line); background: var(--panel); }
1718
+ .top [hidden] { display: none !important; }
1719
+ .brand { flex: none; font-weight: 600; font-size: var(--text-md); display: inline-flex; align-items: center; gap: var(--space-2); color: var(--ink); text-decoration: none; white-space: nowrap; } .brand svg { width: 28px; height: 28px; display: block; } .brand rect { fill: var(--accent); }
1720
+ .top .tenant { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink); font: 600 var(--text-md)/1.5rem var(--font); }
1721
+ .top .tenant::before { content: ""; display: inline-block; width: 1px; height: 1.5rem; margin: 0 var(--space-3) 0 0; vertical-align: middle; position: relative; top: .15rem; background: var(--ink3); opacity: .6; transform: rotate(20deg); }
1722
+ .top .badge { flex: none; padding: 0 var(--space-2); border: 1px solid var(--line-strong); border-radius: var(--radius-full); color: var(--ink2); font: 500 var(--text-xs)/1.25rem var(--font); }
1723
+ .top .links { margin-left: auto; display: flex; align-items: center; gap: var(--space-4); font-size: var(--text-sm); } .top .links a { color: var(--ink2); font-weight: 500; text-decoration: none; transition: color .15s; } .top .links a:hover { color: var(--ink); }
1724
+ .top .sep { width: 1px; height: 1.25rem; background: var(--line-strong); }
1725
+ #themeToggle[aria-pressed="true"] .moon, #themeToggle[aria-pressed="false"] .sun { display: none; }
1726
+ .pill { display: inline-block; padding: .05rem .55rem; border-radius: var(--radius-full); font: 600 var(--text-xs)/1.6 var(--font); background: var(--accent-bg); color: var(--accent); }
1727
+ .notice { padding: .6rem 1.25rem; font-size: .9rem; color: var(--ink); background: var(--accent-bg); border-bottom: 1px solid var(--line); } .notice a, .notice button { margin-left: .6rem; } .notice button { font: inherit; background: none; border: 1px solid var(--line); border-radius: var(--radius-sm); min-height: 0; padding: .1rem .5rem; color: var(--ink); font-weight: 600; cursor: pointer; }
1279
1728
  .notice button:hover { background: var(--panel); border-color: var(--line); }
1280
- a { color: var(--accent); text-underline-offset: 3px; }
1281
- a:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1282
1729
  .layout { display: grid; grid-template-columns: 15rem 1fr; min-height: calc(100vh - 3.3rem); }
1283
1730
  nav { border-right: 1px solid var(--line); background: var(--panel); padding: 1rem 0; }
1284
- nav .group { font: 600 .68rem/1.4 var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--accent); padding: 1rem 1.25rem .35rem; }
1731
+ nav .group { font: 600 var(--text-xs)/1.4 var(--font); color: var(--ink3); padding: 1rem 1.25rem .35rem; }
1285
1732
  nav a { display: flex; justify-content: space-between; gap: .5rem; padding: .45rem 1.25rem; color: var(--ink); text-decoration: none; border-left: 3px solid transparent; }
1286
1733
  nav a:hover { background: var(--bg); } nav a.on { border-left-color: var(--accent); background: var(--accent-bg); font-weight: 600; }
1287
- nav a span.n { color: var(--ink2); font-family: var(--mono); font-size: .8rem; }
1734
+ nav a span.n { color: var(--ink2); font-size: var(--text-xs); font-variant-numeric: tabular-nums; }
1735
+ .navbtn { display: none; }
1736
+ .top .userbtn { flex: none; width: 2.25rem; min-height: 2.25rem; padding: 0; border-color: transparent; border-radius: var(--radius-full); }
1737
+ .top .userbtn:not(:disabled):hover, .top .userbtn[aria-expanded="true"] { background: var(--soft); border-color: transparent; }
1738
+ .userbtn svg, #userMenu svg { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
1739
+ .avatar { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; flex: none; border-radius: var(--radius-full); background: var(--accent-bg); color: var(--accent); font: 600 var(--text-sm)/1 var(--font); text-transform: uppercase; }
1740
+ #userMenu { position: fixed; inset: auto; margin: 0; width: 20rem; max-width: calc(100vw - 1rem); padding: var(--space-2); border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--panel); color: var(--ink); box-shadow: var(--shadow); }
1741
+ #userMenu:popover-open { display: grid; }
1742
+ #userMenu .head { display: grid; gap: 2px; padding: var(--space-2) var(--space-3); }
1743
+ #userMenu .who { color: var(--ink); font-size: var(--text-sm); font-weight: 600; overflow-wrap: anywhere; }
1744
+ #userMenu .meta { color: var(--ink2); font-size: var(--text-xs); } #userMenu .plan { display: none; }
1745
+ #userMenu hr { margin: var(--space-1) 0; border: 0; border-top: 1px solid var(--line); }
1746
+ #userMenu .row { display: flex; align-items: center; justify-content: flex-start; gap: var(--space-3); width: 100%; min-height: 2.25rem; padding: 0 var(--space-3); border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--ink); font: 500 var(--text-sm)/1.2 var(--font); text-decoration: none; text-align: left; }
1747
+ #userMenu .row:hover { background: var(--soft); color: var(--ink); border: 0; }
1748
+ #userMenu .row:focus-visible { outline-offset: -2px; }
1749
+ #userMenu .row.out:hover { color: var(--bad); }
1750
+ #userMenu .state { margin-left: auto; color: var(--ink2); font-size: var(--text-xs); } #userMenu .state::after { content: "Off"; } #themeToggle[aria-pressed="true"] .state::after { content: "On"; }
1751
+ nav .help { display: none; }
1752
+ @media (max-width: 48rem) { .navbtn { display: inline-flex; } nav { position: fixed; z-index: 10; inset: 0 auto 0 0; width: min(18rem, 85vw); overflow-y: auto; visibility: hidden; transform: translateX(-100%); } nav.open { visibility: visible; transform: none; box-shadow: 0 0 0 100vmax rgb(12 10 9 / .5); } }
1753
+ @media (max-width: 48rem) and (prefers-reduced-motion: no-preference) { nav { transition: transform .2s, visibility 0s .2s; } nav.open { transition: transform .2s, visibility 0s; } }
1754
+ @media (max-width: 48rem) { .top:has(#menuBtn:not([hidden])) :is(.links, .sep) { display: none; } .top:has(#menuBtn:not([hidden])) .userbtn { margin-left: auto; } nav { display: flex; flex-direction: column; } nav .help { display: flex; } nav .group.help { display: block; margin-top: auto; } }
1288
1755
  main { padding: 2rem 2rem 3rem; max-width: 72rem; min-width: 0; }
1289
- h1 { font-size: 1.5rem; letter-spacing: -.02em; margin: 0 0 1rem; } h2 { font: 600 .72rem/1.4 var(--mono); letter-spacing: .1em; text-transform: uppercase; color: var(--ink2); margin: 1.5rem 0 .6rem; }
1756
+ h1 { margin: 0 0 1rem; } h2 { font-size: var(--text-md); margin: 1.5rem 0 .6rem; }
1290
1757
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr)); gap: .9rem; }
1291
- .card { background: var(--panel); border: 1px solid var(--line); border-top: 3px solid var(--accent); border-radius: 10px; box-shadow: var(--lift); padding: 1rem 1.1rem; }
1292
- .card.warn { border-top-color: var(--warn); } .card.bad { border-top-color: var(--bad); } .card.ok { border-top-color: var(--ok); }
1293
- .card .k { font: 600 .68rem/1.4 var(--mono); letter-spacing: .1em; text-transform: uppercase; color: var(--ink2); }
1294
- .card .v { font-size: 1.9rem; font-weight: 700; margin: .2rem 0 0; font-variant-numeric: tabular-nums; }
1758
+ .card { box-shadow: var(--lift); padding: 1rem 1.1rem; }
1759
+ .card:is(.ok, .warn, .bad) .k::before { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-right: .45rem; border-radius: var(--radius-full); background: var(--ok); vertical-align: .05em; }
1760
+ .card.warn .k::before { background: var(--warn); } .card.bad .k::before { background: var(--bad); }
1761
+ .card .k { font-weight: 500; color: var(--ink2); }
1762
+ .card .v { font-size: var(--text-2xl); font-weight: 700; margin: .2rem 0 0; font-variant-numeric: tabular-nums; }
1295
1763
  .card .s { color: var(--ink2); font-size: .88rem; }
1296
- .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 1rem 1.25rem; margin-top: .9rem; box-shadow: var(--lift); overflow-x: auto; } .panel > h2:first-child { margin-top: 0; }
1764
+ .panel { padding: 1rem 1.25rem; margin-top: .9rem; box-shadow: var(--lift); overflow-x: auto; } .panel > h2:first-child { margin-top: 0; }
1297
1765
  table { border-collapse: collapse; width: 100%; font-size: .92rem; }
1298
1766
  th, td { text-align: left; padding: .55rem .75rem .55rem 0; border-bottom: 1px solid var(--line); vertical-align: middle; } tbody tr:last-child > * { border-bottom: 0; }
1299
- td button:not(.link) { padding: .25rem .7rem; font-size: .85rem; } td select { padding: .3rem .5rem; }
1300
- #audit td:nth-child(-n+3) { white-space: nowrap; } #audit td:last-child { min-width: 16rem; overflow-wrap: anywhere; font-size: .86rem; }
1301
- th { font: 600 .68rem/1.4 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--ink2); }
1302
- code, pre, .mono { font-family: var(--mono); font-size: .86em; }
1303
- pre { background: var(--bg); border: 1px solid var(--line); border-radius: 8px; padding: .8rem .9rem; overflow-x: auto; white-space: pre-wrap; }
1304
- .bars { display: grid; grid-template-columns: repeat(6, 1fr); gap: .6rem; align-items: end; height: 9rem; }
1305
- .bar { display: flex; flex-direction: column; justify-content: flex-end; align-items: center; height: 100%; font-size: .75rem; color: var(--ink2); }
1306
- .bar i { display: block; width: 70%; max-width: 4rem; background: var(--accent); border-radius: 3px 3px 0 0; min-height: 2px; }
1307
- .bar b { font-family: var(--mono); font-weight: 400; margin-top: .3rem; }
1767
+ td button:not(.link) { min-height: 2rem; padding: 0 .7rem; font-size: var(--text-xs); } td select { min-height: 2rem; }
1768
+ .feed { list-style: none; margin: 0; padding: 0; } .feed li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--space-4); padding: var(--space-2) 0; border-bottom: 1px solid var(--line); } .feed li:last-child { border-bottom: 0; }
1769
+ .feed time { flex: none; color: var(--ink2); font-size: var(--text-xs); font-variant-numeric: tabular-nums; }
1770
+ progress { display: block; width: 100%; height: .5rem; margin: var(--space-2) 0; appearance: none; border: 0; border-radius: var(--radius-full); background: var(--soft); color: var(--accent); overflow: hidden; }
1771
+ progress::-webkit-progress-bar { background: var(--soft); } progress::-webkit-progress-value { background: currentColor; } progress::-moz-progress-bar { background: currentColor; }
1772
+ progress.warn { color: var(--warn); } progress.bad { color: var(--bad); }
1773
+ .plans { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: var(--space-4); margin-top: var(--space-4); }
1774
+ .card.plan { display: flex; flex-direction: column; gap: var(--space-2); padding: var(--space-5); } .card.plan.now { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
1775
+ .plan h2 { margin: 0; display: flex; justify-content: space-between; align-items: center; gap: var(--space-2); } .plan .price { font-size: var(--text-xl); font-weight: 700; } .plan .price::first-letter { text-transform: uppercase; }
1776
+ .plan ul { margin: 0; padding-left: var(--space-5); color: var(--ink2); } .plan .act { margin-top: auto; padding-top: var(--space-3); } .plan .act p { margin: 0; }
1777
+ #policyView { width: min(48rem, calc(100vw - 2rem)); max-width: none; } #policyView pre { max-height: 60vh; overflow: auto; } #publishDialog { width: min(40rem, calc(100vw - 2rem)); max-width: none; } dialog h2 { margin-top: 0; }
1778
+ th { font-size: var(--text-xs); font-weight: 600; color: var(--ink2); } th::first-letter { text-transform: uppercase; }
1779
+ code, pre, .mono { font-size: .86em; }
1780
+ pre { background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: .8rem .9rem; overflow-x: auto; white-space: pre-wrap; }
1781
+ .bars { display: grid; grid-template-columns: repeat(6, 1fr); height: 11rem; }
1782
+ .bar { display: flex; flex-direction: column; align-items: center; height: 100%; font-size: .75rem; color: var(--ink2); }
1783
+ .bar .col { position: relative; flex: 1; width: 100%; display: flex; justify-content: center; align-items: flex-end; border-bottom: 1px solid var(--line); }
1784
+ .bar i { display: block; width: 70%; max-width: 4rem; background: var(--accent); border-radius: var(--radius-sm) var(--radius-sm) 0 0; min-height: 2px; }
1785
+ .bar s { position: absolute; left: 0; right: 0; border-top: 2px dashed var(--bad); }
1786
+ .bar b { font-weight: 400; font-variant-numeric: tabular-nums; margin-top: .3rem; }
1308
1787
  label { display: grid; gap: .25rem; font-size: .85rem; color: var(--ink2); margin: 0 0 .8rem; }
1309
- label .opt { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; margin-left: .3rem; } label .hint { font-size: .8rem; line-height: 1.45; } label .hint code { font-family: var(--mono); font-size: .9em; }
1788
+ label .opt { font-size: var(--text-xs); margin-left: .3rem; } label .hint { font-size: .8rem; line-height: 1.45; } label .hint code { font-family: var(--mono); font-size: .9em; }
1310
1789
  textarea { font: .86rem/1.5 var(--mono); padding: .5rem .6rem; width: 100%; }
1311
- input, select { font: inherit; padding: .5rem .6rem; }
1312
- input, select, textarea { border: 1px solid var(--field); border-radius: 8px; background: var(--bg); color: var(--ink); transition: border-color .15s, box-shadow .15s; }
1790
+ input { font: inherit; padding: .5rem .6rem; }
1791
+ input, textarea { border: 1px solid var(--field); border-radius: var(--radius-sm); background: var(--bg); color: var(--ink); transition: border-color .15s, box-shadow .15s; }
1313
1792
  input::placeholder, textarea::placeholder { color: var(--ink2); opacity: .8; }
1314
1793
  input:focus, select:focus, textarea:focus { outline: 2px solid transparent; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 30%, transparent); }
1315
- button { font: inherit; font-weight: 600; padding: .5rem .9rem; border-radius: 8px; border: 1px solid var(--accent); background: var(--accent); color: var(--accent-ink); cursor: pointer; transition: background-color .15s, border-color .15s; }
1316
- button:not(.quiet, .link, .theme):hover { background: var(--accent-hover); border-color: var(--accent-hover); }
1317
- button.quiet { background: transparent; color: var(--accent); } button.quiet:hover { background: var(--accent-bg); }
1318
- button.link { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; text-underline-offset: 3px; }
1319
- button:disabled { opacity: .55; cursor: default; }
1794
+ button.link { background: none; border: 0; padding: 0; color: var(--accent); font: inherit; text-decoration: underline; text-underline-offset: 3px; cursor: pointer; }
1320
1795
  body:has(> .auth:not([hidden])) { min-height: 100vh; background-color: var(--bg); background-image: radial-gradient(56rem 26rem at 50% -8rem, var(--accent-bg), transparent 72%), radial-gradient(circle at 1px 1px, color-mix(in srgb, var(--ink2) 20%, transparent) 1px, transparent 0); background-size: 100% 100%, 22px 22px; background-repeat: no-repeat, repeat; }
1321
- .auth { --pad: 2.25rem; position: relative; max-width: 27rem; margin: 3.5rem auto 4rem; padding: var(--pad) var(--pad) 1.75rem; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; box-shadow: 0 1px 2px rgb(0 0 0 / .05), 0 18px 40px -18px rgb(0 0 0 / .25); }
1322
- .auth::before { content: ""; position: absolute; top: -1px; left: -1px; right: -1px; height: 4px; border-radius: 14px 14px 0 0; background: var(--accent); }
1796
+ .auth { --pad: 2.25rem; position: relative; max-width: 27rem; margin: 3.5rem auto 4rem; padding: var(--pad) var(--pad) 1.75rem; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md); box-shadow: var(--shadow); }
1323
1797
  #onboard { max-width: 31rem; } .auth.wide { max-width: 44rem; }
1324
1798
  .auth.split { padding: 0; } .auth.split > .pane { padding: var(--pad) var(--pad) 1.75rem; } .pitch { display: none; }
1325
1799
  .pitch .eyebrow { color: #f59e0b; }
1326
- .pitch h2 { margin: 0 0 1rem; font: 700 2rem/1.15 system-ui, -apple-system, "Segoe UI", sans-serif; letter-spacing: -.025em; text-transform: none; color: #fff; }
1327
- .pitch > p { margin: 0 0 2rem; max-width: 30rem; color: #9fb0bd; }
1800
+ .pitch h2 { margin: 0 0 1rem; font: 700 var(--text-2xl)/1.15 var(--font); letter-spacing: -.025em; color: #fafaf9; }
1801
+ .pitch > p { margin: 0 0 2rem; max-width: 30rem; color: #a8a29e; }
1328
1802
  .flow { list-style: none; counter-reset: flow; display: grid; gap: 1.1rem; margin: 0; padding: 0; }
1329
1803
  .flow li { counter-increment: flow; display: grid; grid-template-columns: 2rem 1fr; gap: .1rem .85rem; }
1330
- .flow li::before { content: counter(flow); grid-row: span 2; display: grid; place-items: center; width: 2rem; height: 2rem; border: 1px solid rgb(255 255 255 / .2); border-radius: 50%; color: #9fb0bd; font: 700 .8rem var(--mono); }
1804
+ .flow li::before { content: counter(flow); grid-row: span 2; display: grid; place-items: center; width: 2rem; height: 2rem; border: 1px solid rgb(255 255 255 / .2); border-radius: var(--radius-full); color: #a8a29e; font: 700 var(--text-xs) var(--font); }
1331
1805
  .flow li.now::before { background: #f59e0b; border-color: #f59e0b; color: #1c1917; }
1332
- .flow b { color: #fff; font-weight: 600; } .flow span { color: #9fb0bd; font-size: .9rem; }
1806
+ .flow b { color: #fafaf9; font-weight: 600; } .flow span { color: #a8a29e; font-size: var(--text-sm); }
1333
1807
  @media (min-width: 60rem) {
1334
1808
  .auth.split { display: grid; grid-template-columns: minmax(0, 1fr) 27rem; max-width: 64rem; overflow: hidden; }
1335
1809
  #onboard.split { grid-template-columns: minmax(0, 1fr) 31rem; max-width: 68rem; }
1336
- .pitch { display: flex; flex-direction: column; justify-content: center; padding: 3rem; background: radial-gradient(circle at 1px 1px, rgb(255 255 255 / .07) 1px, transparent 0) 0 0 / 22px 22px, linear-gradient(160deg, #1f2a35, #0e1418); }
1810
+ .pitch { display: flex; flex-direction: column; justify-content: center; padding: 3rem; background: radial-gradient(circle at 1px 1px, rgb(255 255 255 / .07) 1px, transparent 0) 0 0 / 22px 22px, linear-gradient(160deg, #292524, #0c0a09); }
1337
1811
  #onboard .pitch { justify-content: flex-start; padding-top: 4.5rem; }
1338
1812
  .split .fine { border-radius: 0; }
1339
1813
  .auth.wide { display: grid; grid-template-columns: 21rem minmax(0, 1fr); gap: 0 2.5rem; align-items: start; max-width: 72rem; }
1340
1814
  .wide .side { position: sticky; top: 1.5rem; } .wide #firstSetup > .step:first-child { border-top: 0; padding-top: 0; }
1341
1815
  }
1342
- .auth .mark { display: block; width: 40px; height: 40px; margin: 0 0 1rem; } .mark .tile { fill: var(--accent); } .mark .ink { stroke: var(--accent); }
1343
- .auth .eyebrow { margin: 0 0 .3rem; font: 600 .7rem/1.4 var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--accent); }
1344
- .auth h1 { font-size: 1.6rem; line-height: 1.2; letter-spacing: -.02em; margin: 0 0 1.5rem; }
1816
+ .auth .eyebrow { margin: 0 0 .3rem; font: 600 var(--text-sm)/1.4 var(--font); color: var(--accent); }
1817
+ .auth h1 { margin: 0 0 1.5rem; }
1345
1818
  .auth h1 + .muted { margin-top: -.75rem; }
1346
1819
  .auth label { color: var(--ink); font-weight: 600; font-size: .85rem; gap: .4rem; margin: 0 0 1rem; }
1347
1820
  .auth label { position: relative; } .auth label .opt { position: absolute; top: .1rem; right: 0; margin: 0; }
1348
1821
  .auth label .opt, .auth label .hint { font-weight: 400; color: var(--ink2); }
1349
- .auth input, .auth select { width: 100%; min-height: 2.75rem; padding: .6rem .8rem; font-size: 1rem; font-weight: 400; }
1822
+ .auth input { width: 100%; min-height: 2.75rem; padding: .6rem .8rem; font-size: 1rem; font-weight: 400; }
1350
1823
  .auth form > button[type="submit"] { display: block; width: 100%; min-height: 2.75rem; margin-top: .25rem; }
1351
1824
  .providers { display: grid; gap: .6rem; margin: 0 0 1.25rem; }
1352
- .providers a { display: flex; align-items: center; justify-content: center; gap: .6rem; min-height: 2.75rem; padding: .55rem .9rem; border: 1px solid var(--field); border-radius: 8px; background: var(--panel); color: var(--ink); text-decoration: none; font-weight: 600; transition: border-color .15s, background-color .15s; }
1825
+ .providers a { display: flex; align-items: center; justify-content: center; gap: .6rem; min-height: 2.75rem; padding: .55rem .9rem; border: 1px solid var(--field); border-radius: var(--radius-sm); background: var(--panel); color: var(--ink); text-decoration: none; font-weight: 600; transition: border-color .15s, background-color .15s; }
1353
1826
  .providers a:hover { border-color: var(--accent); background: var(--bg); } .providers svg { width: 18px; height: 18px; flex: none; }
1354
- .or { display: flex; align-items: center; gap: .75rem; margin: .4rem 0 0; color: var(--ink2); font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; }
1827
+ .or { display: flex; align-items: center; gap: .75rem; margin: .4rem 0 0; color: var(--ink2); font-size: var(--text-xs); }
1355
1828
  .or::before, .or::after { content: ""; flex: 1; height: 1px; background: var(--line); }
1356
- #authNote { margin: 1rem 0 0; padding: .65rem .85rem; border-radius: 8px; background: var(--accent-bg); color: var(--ink); font-size: .88rem; }
1829
+ #authNote { margin: 1rem 0 0; padding: .65rem .85rem; border-radius: var(--radius-sm); background: var(--accent-bg); color: var(--ink); font-size: .88rem; }
1357
1830
  #ssoForm { margin-top: 1.5rem; padding-top: 1.25rem; border-top: 1px solid var(--line); } #ssoForm button { margin-top: .25rem; }
1358
1831
  .auth .swap { text-align: center; margin: 1.25rem 0 0; }
1359
- .auth .fine { margin: 1.5rem calc(-1 * var(--pad)) -1.75rem; padding: 1rem var(--pad); border-top: 1px solid var(--line); border-radius: 0 0 14px 14px; background: var(--bg); font-size: .82rem; line-height: 1.55; }
1832
+ .tabs { display: grid; grid-template-columns: 1fr 1fr; gap: .25rem; margin: 0 0 1.5rem; padding: .25rem; border-radius: 10px; background: var(--bg); border: 1px solid var(--line); }
1833
+ .tabs button { background: transparent; border: 0; color: var(--ink2); padding: .5rem; border-radius: 7px; } .tabs button[aria-selected="true"] { background: var(--panel); color: var(--ink); box-shadow: 0 1px 2px rgb(0 0 0 / .12); }
1834
+ .tabs button:not([aria-selected="true"]):hover { color: var(--ink); background: transparent; }
1835
+ .auth .forgot { position: absolute; top: 0; right: 0; font-weight: 400; font-size: .82rem; }
1836
+ .qr { width: 12rem; max-width: 100%; margin: .5rem 0; } .qr svg { display: block; width: 100%; height: auto; border-radius: 6px; }
1837
+ .codes { columns: 2; font-family: var(--mono); }
1838
+ #firstSetup pre { overflow-wrap: anywhere; }
1839
+ .auth .fine { margin: 1.5rem calc(-1 * var(--pad)) -1.75rem; padding: 1rem var(--pad); border-top: 1px solid var(--line); border-radius: 0 0 var(--radius-md) var(--radius-md); background: var(--bg); font-size: .82rem; line-height: 1.55; }
1360
1840
  .auth .msg { min-height: 0; margin: .75rem 0 0; font-size: .9rem; } .auth .msg:empty { margin: 0; }
1361
- .auth .msg.err:not(:empty), .auth .msg.ok:not(:empty) { padding: .55rem .8rem; border-radius: 8px; border: 1px solid; }
1841
+ .auth .msg.err:not(:empty), .auth .msg.ok:not(:empty) { padding: .55rem .8rem; border-radius: var(--radius-sm); border: 1px solid; }
1362
1842
  .auth .msg.err:not(:empty) { border-color: color-mix(in srgb, var(--bad) 40%, var(--panel)); background: color-mix(in srgb, var(--bad) 8%, var(--panel)); }
1363
1843
  .auth .msg.ok:not(:empty) { border-color: color-mix(in srgb, var(--ok) 40%, var(--panel)); background: color-mix(in srgb, var(--ok) 8%, var(--panel)); }
1364
- @media (max-width: 30rem) { .top { flex-wrap: wrap; row-gap: .4rem; } .brand, button.theme { white-space: nowrap; } button.theme { margin-left: auto; } .top .links { order: 1; flex-basis: 100%; margin-left: 0; font-size: .85rem; } .top .who, #planTag { display: none !important; } .auth { --pad: 1.25rem; margin: 1rem .75rem 2rem; border-radius: 12px; } .auth::before { border-radius: 12px 12px 0 0; } .auth .fine { border-radius: 0 0 12px 12px; } .auth h1 { font-size: 1.4rem; } }
1844
+ @media (max-width: 30rem) { .top { padding: 0 var(--space-3); } .top:not(:has(#menuBtn:not([hidden]))) { flex-wrap: wrap; padding-block: var(--space-2); row-gap: var(--space-1); } .top:not(:has(#menuBtn:not([hidden]))) .links { order: 1; flex-basis: 100%; margin-left: 0; } .top:not(:has(#menuBtn:not([hidden]))) .userbtn { margin-left: auto; } .top .sep { display: none; } #planTag { display: none !important; } #userMenu .plan { display: block; } .auth { --pad: 1.25rem; margin: 1rem .75rem 2rem; } .auth h1 { font-size: var(--text-xl); } }
1365
1845
  .step { display: grid; grid-template-columns: 2rem 1fr; gap: .2rem .8rem; padding: 1rem 0; border-top: 1px solid var(--line); }
1366
- .step .n { font: 700 .85rem/1.6 var(--mono); color: var(--accent); }
1846
+ .step .n { font: 700 var(--text-sm)/1.6 var(--font); color: var(--accent); }
1367
1847
  .step h3 { margin: 0 0 .3rem; font-size: 1rem; } .step p { margin: 0 0 .5rem; color: var(--ink2); font-size: .92rem; }
1368
1848
  .snip { position: relative; margin: .4rem 0 .6rem; } .snip pre { margin: 0; padding-right: 4.5rem; font-family: var(--mono); font-size: .84rem; }
1369
- .snip button { position: absolute; top: .45rem; right: .45rem; padding: .2rem .6rem; font-size: .8rem; }
1849
+ .snip button { position: absolute; top: .45rem; right: .45rem; min-height: 1.75rem; padding: 0 .6rem; font-size: var(--text-xs); }
1370
1850
  .addr th { text-align: left; font-weight: 600; padding-right: 1rem; white-space: nowrap; } .addr td { word-break: break-all; }
1371
- .once { border: 1px solid var(--warn); background: color-mix(in srgb, var(--warn) 10%, var(--panel)); border-radius: 10px; padding: 1rem 1.1rem; margin: 1rem 0; }
1372
- .tok { font-family: var(--mono); word-break: break-all; padding: .6rem .75rem; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }
1851
+ .once { border: 1px solid var(--warn); background: color-mix(in srgb, var(--warn) 10%, var(--panel)); border-radius: var(--radius-md); padding: 1rem 1.1rem; margin: 1rem 0; }
1852
+ .tok { font-family: var(--mono); word-break: break-all; padding: .6rem .75rem; background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius-sm); }
1373
1853
  .msg { min-height: 1.4rem; margin: .6rem 0; color: var(--ink2); } .panel > .msg:empty { display: none; } .msg.err { color: var(--bad); } .msg.ok { color: var(--ok); }
1374
1854
  .muted { color: var(--ink2); }
1375
1855
  [hidden] { display: none !important; }
1376
- @media (max-width: 48rem) { .layout { grid-template-columns: 1fr; } nav { display: flex; overflow-x: auto; padding: 0 .3rem; border-right: 0; border-bottom: 1px solid var(--line); } nav .group { display: none; } nav a { flex: none; white-space: nowrap; border-left: 0; border-bottom: 3px solid transparent; } main { padding: 1.25rem 1rem 2rem; } nav a.on { border-bottom-color: var(--accent); }
1377
- .cards { grid-template-columns: 1fr 1fr; gap: .6rem; } .card { padding: .75rem .85rem; } .card .k { font-size: .6rem; letter-spacing: .06em; } .card .v { font-size: 1.4rem; } .card .s { font-size: .8rem; line-height: 1.35; }
1378
- table:has(#urls), #urls, table:has(#audit), #audit { display: block; } table:has(#audit) thead { display: none; }
1856
+ @media (max-width: 48rem) { .layout { grid-template-columns: 1fr; } main { padding: 1.25rem 1rem 2rem; }
1857
+ .cards { grid-template-columns: 1fr 1fr; gap: .6rem; } .card { padding: .75rem .85rem; } .card .k { font-size: var(--text-xs); } .card .v { font-size: var(--text-xl); } .card .s { font-size: .8rem; line-height: 1.35; }
1858
+ table:has(#urls), #urls { display: block; } .feed li { flex-direction: column; gap: var(--space-1); }
1379
1859
  #urls tr { display: grid; gap: .15rem; padding: .55rem 0; border-bottom: 1px solid var(--line); } #urls tr:last-child { border-bottom: 0; }
1380
1860
  #urls th, #urls td { padding: 0; border: 0; } #urls td { overflow-wrap: anywhere; font-size: .8rem; }
1381
- #audit tr { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: .15rem .75rem; padding: .65rem 0; border-bottom: 1px solid var(--line); } #audit tr:last-child { border-bottom: 0; }
1382
- #audit td { min-width: 0; padding: 0; border: 0; white-space: normal; }
1383
- #audit td:nth-child(3) { grid-area: 1 / 1; font-weight: 600; } #audit td:nth-child(1) { grid-area: 1 / 2; color: var(--ink2); font-size: .8rem; white-space: nowrap; }
1384
- #audit td:nth-child(2), #audit td:nth-child(4), #audit td[colspan] { grid-column: 1 / -1; font-size: .8rem; } #audit td:nth-child(2) { color: var(--ink2); } }
1861
+ }
1862
+ .toast { position: fixed; right: var(--space-4); bottom: var(--space-4); z-index: 20; max-width: min(26rem, calc(100vw - 2rem)); padding: var(--space-3) var(--space-4); background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-left: 4px solid var(--ok); border-radius: var(--radius-sm); box-shadow: var(--shadow); } .toast.err { border-left-color: var(--bad); } .toast:empty { visibility: hidden; }
1863
+ dialog.confirm { padding: 0; width: min(28rem, calc(100vw - 2rem)); } dialog.confirm form { padding: var(--space-5); } dialog.confirm h2 { margin: 0 0 var(--space-2); overflow-wrap: anywhere; } dialog.confirm p:empty { display: none; }
1864
+ dialog.confirm .acts { display: flex; justify-content: flex-end; gap: var(--space-3); margin-top: var(--space-5); flex-wrap: wrap; } dialog.confirm .choice { display: grid; grid-template-columns: auto 1fr; column-gap: var(--space-3); margin: var(--space-3) 0; font-weight: 400; cursor: pointer; } dialog.confirm .choice input { width: auto; margin: .2rem 0 0; } dialog.confirm .choice span { grid-column: 2; color: var(--ink2); font-size: var(--text-sm); }
1865
+ abbr[title] { text-decoration: underline dotted; text-underline-offset: 2px; cursor: help; }
1385
1866
  </style>
1386
- <div class="top"><a class="brand" href="https://agent-custody.dev/"><svg viewBox="0 0 64 64" aria-hidden="true"><rect width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path d="M25 20h14M25 27h14" stroke="var(--accent)" stroke-width="2.6" stroke-linecap="round"/><path d="M25 37.5l5 4.5 9.5-10" fill="none" stroke="var(--accent)" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>agent-custody</a><span id="tenantTag" class="pill" hidden></span><span id="planTag" class="pill" hidden></span><span class="links"><a href="https://agent-custody.dev/guide/getting-started">Guide</a><a href="https://docs.agent-custody.dev/reference/">Docs</a><a href="https://agent-custody.dev/verify">Verify a receipt</a></span><span class="who" id="who"></span><button class="theme" id="themeToggle" type="button">Dark mode</button></div>
1867
+ <div class="top"><button class="navbtn icon" id="menuBtn" type="button" aria-expanded="false" aria-controls="nav" aria-label="Navigation" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg></button><a class="brand" href="#overview" aria-label="agent-custody, Overview"><svg viewBox="0 0 64 64" aria-hidden="true"><rect width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path d="M25 20h14M25 27h14" stroke="var(--accent)" stroke-width="2.6" stroke-linecap="round"/><path d="M25 37.5l5 4.5 9.5-10" fill="none" stroke="var(--accent)" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg><span data-out>agent-custody</span></a><span id="tenantTag" class="tenant" hidden></span><span id="planTag" class="badge" hidden></span><span class="links">${DASHBOARD_NAV}</span><span class="sep" aria-hidden="true"></span><button class="userbtn quiet" id="userBtn" type="button" popovertarget="userMenu" aria-expanded="false" aria-controls="userMenu" aria-label="Appearance"><span class="avatar" id="avatar" aria-hidden="true" data-acct hidden></span><svg class="theme-ic" viewBox="0 0 24 24" aria-hidden="true" data-out><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/></svg></button><div id="userMenu" popover><div class="head" data-acct><span class="who" id="who"></span><span class="meta" id="whoMeta"></span><span class="meta plan" id="whoPlan"></span></div><hr data-acct><a class="row" href="#account" data-view="account" data-acct><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>Security</a><button class="row" id="themeToggle" type="button" aria-label="Dark mode" aria-pressed="false" title="Dark mode"><svg class="moon" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg><svg class="sun" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>Dark mode<span class="state" aria-hidden="true"></span></button><hr data-acct><button class="row out" id="signout" type="button" data-acct><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4H5v16h4M16 8l4 4-4 4M20 12H9"/></svg>Sign out</button></div></div>
1387
1868
  <div id="notice" class="notice" hidden></div>
1388
1869
  <section id="auth" class="auth split" hidden>
1389
1870
  <aside class="pitch">
@@ -1397,29 +1878,36 @@ const PORTAL_PAGE = `<!doctype html>
1397
1878
  </ol>
1398
1879
  </aside>
1399
1880
  <div class="pane">
1400
- ${MARK}
1401
1881
  <p class="eyebrow">Hosted log</p>
1402
1882
  <h1 id="authTitle">Sign in</h1>
1883
+ <div class="tabs" id="authTabs" role="tablist"><button type="button" role="tab" id="tabSignIn" aria-selected="true">Sign in</button><button type="button" role="tab" id="tabSignUp" aria-selected="false">Sign up</button></div>
1403
1884
  <div id="providers" class="providers" hidden></div>
1404
1885
  <form id="authForm">
1405
1886
  <label>Work email<input id="email" type="email" autocomplete="email" required></label>
1406
- <label>Password<input id="password" type="password" autocomplete="current-password" minlength="10" required></label>
1887
+ <label>Password<button class="link forgot" id="forgotOpen" type="button" hidden>Forgot password?</button><input id="password" type="password" autocomplete="current-password" minlength="10" required><span class="hint" id="pwRule" hidden>At least ten characters.</span></label>
1407
1888
  <button id="authGo" type="submit">Sign in</button>
1408
1889
  <p class="msg" id="authMsg" aria-live="polite"></p>
1409
1890
  </form>
1891
+ <form id="forgotForm" hidden>
1892
+ <p class="muted">Enter the address of your account. We send a link to set a new password. The link works for one hour.</p>
1893
+ <label>Work email<input id="forgotEmail" type="email" autocomplete="email" required></label>
1894
+ <button type="submit">Send the link</button>
1895
+ <p class="msg" id="forgotMsg" aria-live="polite"></p>
1896
+ <p class="muted swap"><button class="link" id="forgotBack" type="button">Back to sign in</button></p>
1897
+ </form>
1410
1898
  <form id="mfaForm" hidden>
1411
- <p class="muted">Your account has two-step sign-in. Enter the six-digit code from your authenticator app.</p>
1412
- <label>Code<input id="mfaCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label>
1899
+ <p class="muted">Your account has two-step sign-in. Enter the six-digit code from your authenticator app, or one of your recovery codes.</p>
1900
+ <label>Code<input id="mfaCode" autocomplete="one-time-code" maxlength="20" required></label>
1413
1901
  <button type="submit">Verify</button>
1414
1902
  <p class="msg" id="mfaMsg" aria-live="polite"></p>
1415
1903
  </form>
1416
1904
  <p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
1417
- <form id="ssoForm" action="/auth/sso" method="get">
1905
+ <p class="muted swap" id="ssoSwap"><button class="link" id="ssoOpen" type="button">Sign in with single sign-on</button></p>
1906
+ <form id="ssoForm" action="/auth/sso" method="get" hidden>
1418
1907
  <label>Work email for single sign-on<input name="email" type="email" autocomplete="email" required></label>
1419
- <button class="quiet" type="submit">Sign in with single sign-on</button>
1908
+ <button class="quiet" type="submit">Continue with single sign-on</button>
1420
1909
  </form>
1421
- <p class="muted swap"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
1422
- <p class="muted fine">The free plan is ten thousand appends a month, no card. Your gateway sends only hashes; nothing you log here can be read by us.</p>
1910
+ <p class="muted fine">The free plan is ten thousand <abbr title="An append is one receipt hash your gateway writes to your log.">appends</abbr> a month, no card. Your gateway sends only hashes; nothing you log here can be read by us.</p>
1423
1911
  </div>
1424
1912
  </section>
1425
1913
  <section id="onboard" class="auth split" hidden>
@@ -1434,7 +1922,6 @@ const PORTAL_PAGE = `<!doctype html>
1434
1922
  </ol>
1435
1923
  </aside>
1436
1924
  <div class="pane">
1437
- ${MARK}
1438
1925
  <h1>Set up your tenant</h1>
1439
1926
  <p class="muted">Signed in as <b id="onboardWho"></b>. A tenant is your own log on this service, with its own keys and its own path.</p>
1440
1927
  <div id="invites" class="panel" hidden><p><b>You are invited to join a tenant.</b> Your email address must be verified first.</p><div id="inviteList"></div></div>
@@ -1443,8 +1930,6 @@ const PORTAL_PAGE = `<!doctype html>
1443
1930
  <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
1444
1931
  <label>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9\\-]{1,38}[a-z0-9]" required><span class="hint">A short name for your organisation, filled in from the company name; change it if you like. It becomes the path of your log, which your gateway config and your auditors will use: <code id="tenantPreview">__LOG_BASE__t/&lt;tenant&gt;/</code></span></label>
1445
1932
  <label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
1446
- <label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
1447
- <label>Telegram username <span class="opt">optional</span><input id="telegram" maxlength="40" placeholder="@yourname"><span class="hint">Your handle in Telegram, under Settings, if you would rather we reach you there than by email.</span></label>
1448
1933
  <button type="submit">Create tenant</button>
1449
1934
  <p class="msg" id="onboardMsg" aria-live="polite"></p>
1450
1935
  </form>
@@ -1453,99 +1938,121 @@ const PORTAL_PAGE = `<!doctype html>
1453
1938
  </section>
1454
1939
  <section id="welcome" class="auth wide" hidden>
1455
1940
  <div class="side">
1456
- ${MARK}
1457
1941
  <h1>Your tenant is ready</h1>
1458
- <p class="muted">Three steps to your first receipt in this log. Everything here is under <b>Setup</b> in the dashboard whenever you need it again.</p>
1459
- <div class="once"><p><b>Your first API key, shown once.</b> Put it in the environment your gateway reads as <code>AGENT_CUSTODY_LOG_TOKEN</code>. We keep only its hash.</p><p class="tok" id="firstToken"></p><button class="quiet" id="copyFirst">Copy key</button></div>
1942
+ <p class="muted">That was step 1 of 4. Steps 2 to 4 take you to your first receipt in this log. Everything here is under <b>Setup</b> in the dashboard whenever you need it again.</p>
1943
+ <div class="once"><p><b>Your first API key, shown once.</b> Put it in the environment your gateway reads as <code>AGENT_CUSTODY_LOG_TOKEN</code>. We keep only its hash.</p><p class="tok" id="firstToken"></p><button class="quiet" id="copyFirst" data-copy>Copy API key</button> <button type="button" id="savedFirst">I saved the key</button></div>
1460
1944
  <p><button id="toDash">Go to the dashboard</button></p>
1461
1945
  </div>
1462
1946
  <div id="firstSetup"></div>
1463
1947
  </section>
1948
+ <section id="loadFail" class="auth" role="alert" hidden>
1949
+ <h1>We could not load your account</h1>
1950
+ <p class="muted" id="loadErr"></p>
1951
+ <p><button type="button" id="retry">Retry</button></p>
1952
+ </section>
1464
1953
  <div class="layout" id="app" hidden>
1465
- <nav>
1954
+ <nav id="nav" aria-label="Main">
1466
1955
  <div class="group">Monitor</div>
1467
1956
  <a href="#overview" data-view="overview">Overview</a>
1468
1957
  <a href="#usage" data-view="usage">Usage</a>
1469
- <div class="group">Configure</div>
1958
+ <a href="#activity" data-view="activity">Activity</a>
1959
+ <div class="group">Log</div>
1470
1960
  <a href="#setup" data-view="setup">Setup</a>
1471
1961
  <a href="#keys" data-view="keys">API keys <span class="n" id="nKeys"></span></a>
1472
1962
  <a href="#policies" data-view="policies">Policies <span class="n" id="nPolicies"></span></a>
1963
+ <a href="#export" data-view="export">Export</a>
1964
+ <div class="group">Organisation</div>
1473
1965
  <a href="#members" data-view="members">Members <span class="n" id="nMembers"></span></a>
1474
1966
  <a href="#billing" data-view="billing">Billing</a>
1475
- <a href="#export" data-view="export">Export</a>
1476
- <div class="group">Account</div>
1477
- <a href="#account" data-view="account">Two-step sign-in</a>
1478
- <a href="#" id="signout">Sign out</a>
1967
+ <div class="group help">Help</div>
1968
+ ${DASHBOARD_NAV.replaceAll("<a ", '<a class="help" ')}
1479
1969
  </nav>
1480
1970
  <main>
1481
1971
  <div data-pane="overview">
1482
1972
  <h1>Overview</h1>
1483
- <div class="cards">
1973
+ <div class="panel" id="firstReceipt" hidden><h2>Send your first receipt</h2><p>Your log is empty. Put your API key where your gateway runs, point the gateway at this log, and run your agent once. The numbers show here after the first append.</p><p><a href="#setup" data-view="setup">Open Setup</a></p></div>
1974
+ <div class="cards" id="ovCards">
1484
1975
  <div class="card" id="cUsed"><div class="k">Appends this month</div><div class="v" id="vUsed">–</div><div class="s" id="sUsed"></div></div>
1485
1976
  <div class="card" id="cSize"><div class="k">Receipts in your log</div><div class="v" id="vSize">–</div><div class="s">leaf hashes, all time</div></div>
1486
- <div class="card" id="cKeys"><div class="k">Live keys</div><div class="v" id="vKeys">–</div><div class="s" id="sKeys"></div></div>
1487
- <div class="card" id="cCp"><div class="k">Latest checkpoint</div><div class="v" id="vCp">–</div><div class="s" id="sCp"></div></div>
1977
+ <div class="card" id="cKeys"><div class="k">Active keys</div><div class="v" id="vKeys">–</div><div class="s" id="sKeys"></div></div>
1978
+ <div class="card" id="cCp"><div class="k"><abbr title="A checkpoint is the log's size and root hash, signed and published apart from the log, so anyone can check later that it was never rewritten.">Latest checkpoint</abbr></div><div class="v" id="vCp">–</div><div class="s" id="sCp"></div></div>
1488
1979
  </div>
1489
- <p class="muted">Tree heads on this log are signed by our key; there is no second, independent witness yet. Every receipt you log here is checkable by anyone with your gateway's public key and ours: <a href="https://agent-custody.dev/receipts/#what-a-receipt-proves-and-what-it-does-not">what a receipt proves and what it does not</a>.</p>
1980
+ <p class="muted">Tree heads on this log are signed by our key; there is no second, independent witness yet. Every receipt you log here is checkable by anyone with your gateway's public key and ours: <a href="https://github.com/svayatta/agent-custody/tree/main/packages/receipts#what-a-receipt-proves-and-what-it-does-not" target="_blank" rel="noopener">what a receipt proves and what it does not</a>.</p>
1490
1981
  <h2>Your log</h2>
1491
1982
  <div class="panel"><table><tbody id="urls"></tbody></table></div>
1492
- <h2>Recent activity</h2>
1493
- <div class="panel"><table><thead><tr><th>when</th><th>who</th><th>action</th><th>detail</th></tr></thead><tbody id="audit"></tbody></table></div>
1983
+ </div>
1984
+ <div data-pane="activity" hidden>
1985
+ <h1>Activity</h1>
1986
+ <p class="muted">Every change to your tenant, newest first. Times are in your time zone. Hold the pointer on a time to see it in UTC.</p>
1987
+ <div class="panel"><ul class="feed" id="activityFeed"></ul></div>
1988
+ <p><button type="button" class="quiet" id="activityMore" hidden>Show older</button></p>
1494
1989
  </div>
1495
1990
  <div data-pane="usage" hidden>
1496
1991
  <h1>Usage</h1>
1497
- <div class="panel"><div class="bars" id="bars"></div></div>
1498
- <p class="muted" id="usageNote"></p>
1992
+ <div class="panel"><h2>This month</h2><p id="usageNow"></p><progress id="usageBar" aria-label="Appends this month against the plan limit"></progress></div>
1993
+ <div class="panel"><h2>Last six months</h2><div class="bars" id="bars"></div><p class="muted" id="usageNote"></p></div>
1499
1994
  </div>
1500
1995
  <div data-pane="keys" hidden>
1501
1996
  <h1>API keys</h1>
1502
- <p class="muted">A key is a bearer token your gateway presents on append. It is shown once when minted; we keep only its hash. Mint a second key before revoking the first to rotate without a gap.</p>
1503
- <div class="panel"><form id="mintForm" style="display:flex;gap:.6rem;align-items:end;flex-wrap:wrap"><label style="margin:0">Label<input id="label" placeholder="support fleet"></label><button type="submit">Mint key</button></form>
1504
- <div id="minted" class="once" hidden><p><b>Shown once.</b></p><p class="tok" id="mintedTok"></p><button class="quiet" id="copyMinted">Copy key</button></div>
1505
- <table style="margin-top:1rem"><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="keys"></tbody></table></div>
1506
- <p class="msg" id="keysMsg"></p>
1997
+ <p class="muted">An API key is what your gateway sends with each append. You see it one time, when you create it; we keep only its hash. To rotate without a gap, create the new API key before you revoke the old one.</p>
1998
+ <div class="panel"><form id="mintForm" style="display:flex;gap:.6rem;align-items:end;flex-wrap:wrap"><label style="margin:0">Label<input id="label" placeholder="support fleet"></label><button type="submit">Create API key</button></form>
1999
+ <div id="minted" class="once" hidden><p><b>Shown once.</b></p><p class="tok" id="mintedTok"></p><button class="quiet" id="copyMinted" data-copy>Copy API key</button> <button type="button" id="savedMinted">I saved the key</button></div>
2000
+ <table style="margin-top:1rem"><thead><tr><th>label</th><th>created</th><th>last used</th><th>state</th><th></th></tr></thead><tbody id="keyRows"></tbody></table></div>
1507
2001
  </div>
1508
2002
  <div data-pane="policies" hidden>
1509
2003
  <h1>Policies</h1>
1510
- <p class="muted">Enforcement stays on your machines: the gateway reads its Cedar file locally and writes the file's SHA-256 into every receipt as <code>policyDigest</code>. This page gives those digests names. Publish each version you deploy, byte for byte as the gateway loads it, and a receipt's digest reads as "refunds-v3" instead of a hash, here and in your export. We never evaluate a policy and nothing here is read by the gateway.</p>
1511
- <div class="panel"><form id="policyForm"><label>Name for this version<input id="policyName" placeholder="refunds-v3" maxlength="80" required></label><label>Policy text, exactly as the gateway's file<textarea id="policyText" rows="8" spellcheck="false" placeholder="permit(principal, action == Action::&quot;stripe.refund&quot;, resource) when { context.args.amount <= 100000 };" required></textarea></label><button type="submit">Publish version</button> <span class="muted" id="policyDigestPreview"></span></form></div>
2004
+ <p class="muted">Publish each <abbr title="Cedar is the policy language the gateway uses to allow or deny each tool call.">Cedar</abbr> policy version that your gateway loads, and the <code>policyDigest</code> of a receipt reads as its name, such as "refunds-v3". Enforcement stays on your machines: the gateway never reads this page. <a href="https://agent-custody.dev/reference/hosted#policies-names-for-the-digests-receipts-carry" target="_blank" rel="noopener">How policy names work</a></p>
2005
+ <p><button type="button" id="policyNew">Publish version</button></p>
2006
+ <div class="panel"><table><thead><tr><th>name</th><th>digest</th><th>bytes</th><th>published</th><th>by</th><th></th></tr></thead><tbody id="policyRows"></tbody></table></div>
1512
2007
  <div class="panel"><h2>Match a receipt</h2><p class="muted">Paste a receipt file, or just its <code>policyDigest</code>, to see which published version decided it.</p><form id="matchForm"><label>Receipt JSON or digest<textarea id="matchIn" rows="3" spellcheck="false"></textarea></label><button type="submit" class="quiet">Match</button></form><p class="msg" id="matchOut"></p></div>
1513
- <div class="panel"><table><thead><tr><th>name</th><th>digest</th><th>bytes</th><th>published</th><th>by</th><th></th></tr></thead><tbody id="policies"></tbody></table></div>
1514
- <div class="panel" id="policyView" hidden><h2 id="policyViewName"></h2><pre id="policyViewText"></pre></div>
1515
- <p class="msg" id="policiesMsg"></p>
2008
+ <dialog id="publishDialog" aria-labelledby="publishTitle"><form id="policyForm"><h2 id="publishTitle">Publish a policy version</h2><label>Name for this version<input id="policyName" placeholder="refunds-v3" maxlength="80" required></label><label>Policy text, exactly as the gateway's file<textarea id="policyText" rows="10" spellcheck="false" placeholder="permit(principal, action == Action::&quot;stripe.refund&quot;, resource) when { context.args.amount <= 100000 };" required></textarea></label><p class="muted" id="policyDigestPreview"></p><button type="submit">Publish</button> <button type="button" class="quiet" id="publishCancel">Cancel</button><p class="msg" id="publishMsg"></p></form></dialog>
2009
+ <dialog id="policyView" aria-labelledby="policyViewName"><h2 id="policyViewName"></h2><pre id="policyViewText"></pre><button type="button" class="quiet" id="policyViewClose">Close</button></dialog>
1516
2010
  </div>
1517
2011
  <div data-pane="members" hidden>
1518
2012
  <h1>Members</h1>
1519
- <p class="muted">An owner manages everything, billing and owners included. An admin manages keys and members below owner. A reviewer publishes policy versions. A read-only member only looks. An invited person creates an account with the invited address, verifies it, and accepts on the first screen. An invite is good for seven days.</p>
1520
- <div class="panel" id="inviteBox" hidden><form id="inviteForm" style="display:flex;gap:.6rem;align-items:end;flex-wrap:wrap"><label style="margin:0">Email<input id="inviteEmail" type="email" required></label><label style="margin:0">Role<select id="inviteRole"></select></label><button type="submit">Invite</button></form></div>
1521
- <div class="panel"><table><thead><tr><th>member</th><th>role</th><th>joined</th><th>two-step</th><th></th></tr></thead><tbody id="members"></tbody></table></div>
2013
+ <p class="muted">Each member has one role. The list of choices explains each role. An invited person creates an account with the invited address, verifies it, and accepts on the first screen. An invite is good for seven days.</p>
2014
+ <div class="panel" id="inviteBox" hidden><form id="inviteForm" style="display:flex;gap:.6rem;align-items:end;flex-wrap:wrap"><label style="margin:0">Email<input id="inviteEmail" type="email" required></label><label style="margin:0">Role<select id="inviteRole"></select></label><button type="submit">Invite</button></form><p class="muted" id="inviteRoleHint"></p></div>
2015
+ <div class="panel"><table><thead><tr><th>member</th><th>role</th><th>joined</th><th>two-step</th><th></th></tr></thead><tbody id="memberRows"></tbody></table></div>
1522
2016
  <h2>Pending invites</h2>
1523
2017
  <div class="panel"><table><thead><tr><th>email</th><th>role</th><th>invited by</th><th>sent</th><th></th></tr></thead><tbody id="inviteRows"></tbody></table></div>
1524
- <p class="msg" id="membersMsg"></p>
1525
2018
  </div>
1526
2019
  <div data-pane="account" hidden>
1527
- <h1>Two-step sign-in</h1>
2020
+ <h1>Account</h1>
2021
+ <h2>Two-step sign-in</h2>
1528
2022
  <p class="muted">Two-step sign-in is <b id="mfaState">off</b>. With it on, a password or a GitHub or Google sign-in is followed by a six-digit code from an authenticator app (TOTP).</p>
1529
2023
  <div class="panel">
1530
2024
  <button id="mfaStart" type="button">Set up</button>
1531
2025
  <div id="mfaSetupBox" hidden>
1532
- <p>Add this secret to your authenticator app (enter it by hand, or paste the address), then type a code from the app.</p>
1533
- <p class="tok" id="mfaSecret"></p><p class="tok" id="mfaUri"></p>
2026
+ <p>Scan this QR code with your authenticator app, then type a code from the app.</p>
2027
+ <div class="qr" id="mfaQr"></div>
2028
+ <p class="muted">Cannot scan? Type this secret into the app by hand:</p>
2029
+ <p class="tok" id="mfaSecret"></p>
2030
+ <details><summary class="muted">Show the setup address</summary><p class="tok" id="mfaUri"></p></details>
1534
2031
  <form id="mfaOnForm"><label>Code<input id="mfaOnCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label><button type="submit">Turn on</button></form>
1535
2032
  </div>
1536
- <form id="mfaOffForm" hidden><label>Current code<input id="mfaOffCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label><button type="submit" class="quiet">Turn off</button></form>
2033
+ <div id="recoveryBox" class="once" hidden><p><b>Your recovery codes, shown once.</b> Keep them in a safe place. Each code works one time in place of a code from the app, if you lose your phone. We keep only their hashes.</p><div class="snip"><pre class="codes" id="recoveryCodes"></pre><button type="button" class="quiet" data-copy>Copy</button></div></div>
2034
+ <form id="mfaOffForm" hidden><label>Current code or recovery code<input id="mfaOffCode" autocomplete="one-time-code" maxlength="20" required></label><button type="submit" class="quiet">Turn off</button></form>
2035
+ <form id="recoveryForm" hidden><p class="muted"><span id="recoveryLeft"></span> Make new codes to replace all of them.</p><label>Current code<input id="recoveryCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label><button type="submit" class="quiet">Make new recovery codes</button></form>
1537
2036
  </div>
1538
2037
  <p class="msg" id="accountMsg"></p>
2038
+ <h2>Password</h2>
2039
+ <div class="panel">
2040
+ <form id="pwForm"><label>Current password<input id="pwCurrent" type="password" autocomplete="current-password" required></label><label>New password<input id="pwNew" type="password" autocomplete="new-password" minlength="10" required><span class="hint">At least ten characters.</span></label><button type="submit">Change password</button></form>
2041
+ <p class="muted">A change signs out every other session of this account. An account made through GitHub, Google, or single sign-on has a random password that nobody knows<span id="pwNoMail">.</span><span id="pwMail" hidden>: to set one, sign out and use <b>Forgot password?</b> on the sign-in page.</span></p>
2042
+ <p class="msg" id="pwMsg"></p>
2043
+ </div>
1539
2044
  </div>
1540
2045
  <div data-pane="billing" hidden>
1541
2046
  <h1>Billing</h1>
1542
- <div class="panel" id="billingPanel"></div>
2047
+ <div class="panel" id="billingNow"></div>
2048
+ <div class="plans" id="plans"></div>
2049
+ <p class="muted">The prices and limits are the same as on the <a href="https://agent-custody.dev/pricing" target="_blank" rel="noopener">pricing page</a>. No plan has an availability commitment yet.</p>
1543
2050
  <p class="msg" id="billingMsg"></p>
1544
2051
  </div>
1545
2052
  <div data-pane="export" hidden>
1546
2053
  <h1>Export</h1>
1547
- <p class="muted">Everything the log holds about you, any time, with your key: every leaf hash as a log file the verifier reads offline, the signed head, the published keys, the checkpoints, your usage, and the actions taken on your tenant. It checks itself before writing.</p>
1548
- <pre id="exportCmd"></pre>
2054
+ <p class="muted">Everything the log holds about you, any time, with your key: every <abbr title="A leaf is one entry in the log: the hash of one receipt.">leaf</abbr> hash as a log file the verifier reads offline, the signed head, the published keys, the checkpoints, your usage, and the actions taken on your tenant. It checks itself before writing.</p>
2055
+ <div class="snip"><pre id="exportCmd"></pre><button type="button" class="quiet" data-copy>Copy</button></div>
1549
2056
  </div>
1550
2057
  <div data-pane="setup" hidden>
1551
2058
  <h1>Setup</h1>
@@ -1554,6 +2061,15 @@ const PORTAL_PAGE = `<!doctype html>
1554
2061
  </div>
1555
2062
  </main>
1556
2063
  </div>
2064
+ <div id="toast" class="toast" role="status" aria-live="polite"></div>
2065
+ <dialog id="dlg" class="confirm" aria-labelledby="dlgTitle" aria-describedby="dlgText">
2066
+ <form method="dialog">
2067
+ <h2 id="dlgTitle"></h2>
2068
+ <p id="dlgText" class="muted"></p>
2069
+ <div id="dlgChoices"></div>
2070
+ <div class="acts"><button type="submit" value="cancel" class="quiet" id="dlgNo" formnovalidate autofocus>Go back</button><button type="submit" value="ok" id="dlgOk"></button></div>
2071
+ </form>
2072
+ </dialog>
1557
2073
  <script>
1558
2074
  (() => {
1559
2075
  const $ = (id) => document.getElementById(id);
@@ -1571,22 +2087,117 @@ const PORTAL_PAGE = `<!doctype html>
1571
2087
  const ROLES = ["readonly", "reviewer", "admin", "owner"];
1572
2088
  const can = (least) => ROLES.indexOf(myRole) >= ROLES.indexOf(least);
1573
2089
  const note = (id, text, ok) => { $(id).className = "msg " + (ok ? "ok" : "err"); $(id).textContent = text; };
1574
- const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
2090
+ const toast = (text, ok) => {
2091
+ const t = $("toast"), s = String(text).charAt(0).toUpperCase() + String(text).slice(1);
2092
+ t.className = "toast " + (ok ? "ok" : "err"); t.textContent = /[.!?…]$/.test(s) ? s : s + ".";
2093
+ clearTimeout(toast.timer); toast.timer = setTimeout(() => { t.textContent = ""; }, ok ? 6000 : 10000);
2094
+ };
2095
+ const ask = (o) => new Promise((resolve) => {
2096
+ const d = $("dlg"), box = $("dlgChoices");
2097
+ $("dlgTitle").textContent = o.title; $("dlgText").textContent = o.text || ""; $("dlgOk").textContent = o.ok; $("dlgOk").className = o.danger ? "danger" : "";
2098
+ box.replaceChildren(...(o.choices || []).map(([v, label, desc]) => {
2099
+ const l = document.createElement("label"), r = document.createElement("input"), b = document.createElement("b"), t = document.createElement("span");
2100
+ l.className = "choice"; r.type = "radio"; r.name = "dlgChoice"; r.value = v; r.checked = v === o.current; b.textContent = label; t.textContent = desc; l.append(r, b, t); return l;
2101
+ }));
2102
+ d.returnValue = "";
2103
+ d.onclose = () => { const c = box.querySelector("input:checked"); resolve(d.returnValue !== "ok" ? null : o.choices ? c && c.value : true); };
2104
+ d.showModal();
2105
+ });
2106
+ $("dlg").addEventListener("click", (e) => { if (e.target === e.currentTarget) e.currentTarget.close(); });
2107
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
2108
+ const show = (id) => {
2109
+ for (const s of ["auth", "onboard", "welcome", "loadFail", "app"]) $(s).hidden = s !== id;
2110
+ $("menuBtn").hidden = id !== "app";
2111
+ for (const el of document.querySelectorAll("[data-acct]")) el.toggleAttribute("hidden", id !== "app");
2112
+ for (const el of document.querySelectorAll("[data-out]")) el.toggleAttribute("hidden", id === "app");
2113
+ if (id !== "app") { $("tenantTag").hidden = true; $("planTag").hidden = true; }
2114
+ $("userBtn").setAttribute("aria-label", id === "app" ? "Account menu for " + myEmail : "Appearance");
2115
+ if (id !== "app") { document.title = "agent-custody"; setDrawer(false); }
2116
+ };
1575
2117
  const PROVIDERS = __PROVIDERS__;
2118
+ const PLANS = __PLANS__;
2119
+ const PLAN_NAMES = Object.fromEntries(PLANS.map((p) => [p.plan, p.name]));
2120
+ let myEmail = "";
2121
+ let keyList = [];
2122
+ let activityNext = null;
2123
+ const when = (iso) => "<time datetime=\\"" + esc(iso) + "\\" title=\\"" + esc(iso.slice(0, 16).replace("T", " ")) + " UTC\\">" + esc(new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })) + "</time>";
2124
+ const actor = (a) => a === "portal:" + myEmail ? "You" : a.startsWith("portal:") ? a.slice(7) : a.startsWith("stripe:") ? "Stripe billing" : a.startsWith("cli:") ? "The operator" : a === "unattributed" ? "Someone" : a;
2125
+ const keyName = (prefix) => { const k = keyList.find((k) => prefix && k.hash.startsWith(String(prefix).slice(0, 12))); return k ? "the key '" + k.label + "'" : "the key " + prefix; };
2126
+ const SENTENCES = {
2127
+ "tenant.add": (d) => "created the tenant" + (d.logId ? " with the log id '" + d.logId + "'" : ""),
2128
+ "tenant.disable": () => "disabled the tenant",
2129
+ "tenant.plan": (d) => "moved the tenant to the " + (PLAN_NAMES[d.plan] || d.plan) + " plan",
2130
+ "token.add": (d) => "created the key '" + d.label + "'",
2131
+ "token.revoke": (d) => d.revoked === 0 ? "tried to revoke " + keyName(d.hashPrefix) + ", but no active key matched" : "revoked " + keyName(d.hashPrefix),
2132
+ "policy.add": (d) => "published the policy version '" + d.name + "'",
2133
+ "policy.remove": (d) => "removed the policy version '" + d.name + "'",
2134
+ "sso.set": (d) => "set up single sign-on" + (d.protocol ? " (" + String(d.protocol).toUpperCase() + ")" : ""),
2135
+ "sso.remove": () => "removed single sign-on",
2136
+ "user.mfa-reset": (d) => "turned off two-step sign-in for " + (d.email || "a member"),
2137
+ };
2138
+ const sentence = (e) => { const d = e.detail || {}; return actor(e.actor) + " " + (Object.hasOwn(SENTENCES, e.action) ? SENTENCES[e.action](d) : "did '" + e.action + "'" + (Object.keys(d).length ? " (" + Object.entries(d).map(([k, v]) => k + ": " + v).join(", ") + ")" : "")) + "."; };
2139
+ const feed = (entries) => entries.map((e) => "<li><span title=\\"" + esc(e.action + " " + JSON.stringify(e.detail || {})) + "\\">" + esc(sentence(e)) + "</span>" + when(e.at) + "</li>").join("");
2140
+ const loadActivity = async (older) => {
2141
+ try {
2142
+ const r = await api("GET", "/api/audit?limit=25" + (older ? "&before=" + activityNext : ""));
2143
+ if (older) $("activityFeed").insertAdjacentHTML("beforeend", feed(r.entries)); else $("activityFeed").innerHTML = feed(r.entries) || "<li class=muted>Nothing yet.</li>";
2144
+ activityNext = r.next; $("activityMore").hidden = r.next === null;
2145
+ } catch (err) { toast(err.message, false); }
2146
+ };
2147
+ $("activityMore").onclick = () => loadActivity(true);
2148
+ const meter = (bar, used, quota) => { bar.hidden = quota === null; if (quota === null) return; bar.max = quota; bar.value = Math.min(used, quota); bar.className = used >= quota ? "bad" : used >= .8 * quota ? "warn" : ""; };
2149
+ const resets = () => { const d = new Date(); return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1)).toLocaleDateString(undefined, { day: "numeric", month: "long", timeZone: "UTC" }); };
2150
+ const usedLine = (o) => fmt(o.used) + (o.quota === null ? " appends this month. Your plan has no limit." : " of " + fmt(o.quota) + " appends this month (" + Math.floor(100 * o.used / o.quota) + "%). The count resets on " + resets() + ", UTC.");
2151
+ const monthName = (m) => new Date(m + "-01T00:00:00Z").toLocaleDateString(undefined, { month: "short", year: "numeric", timeZone: "UTC" });
2152
+ const MAIL = __MAIL__;
1576
2153
  const ICONS = { github: "<svg viewBox='0 0 16 16' aria-hidden='true'><path fill='currentColor' d='M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z'/></svg>", google: "<svg viewBox='0 0 48 48' aria-hidden='true'><path fill='#EA4335' d='M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z'/><path fill='#4285F4' d='M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z'/><path fill='#FBBC05' d='M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z'/><path fill='#34A853' d='M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z'/></svg>" };
1577
2154
  if (PROVIDERS.length) { $("providers").innerHTML = PROVIDERS.map((p) => "<a href='/auth/" + p + "'>" + ICONS[p] + "Continue with " + (p === "github" ? "GitHub" : "Google") + "</a>").join("") + "<p class=or>or with email</p>"; $("providers").hidden = false; }
1578
- const view = (name) => {
2155
+ const TITLES = { overview: "Overview", usage: "Usage", activity: "Activity", setup: "Setup", keys: "API keys", policies: "Policies", export: "Export", members: "Members", billing: "Billing", account: "Security" };
2156
+ const route = () => {
2157
+ if ($("app").hidden) return;
2158
+ const h = location.hash.slice(1), name = Object.hasOwn(TITLES, h) ? h : "overview";
1579
2159
  for (const p of document.querySelectorAll("[data-pane]")) p.hidden = p.dataset.pane !== name;
1580
2160
  for (const a of document.querySelectorAll("nav a[data-view]")) a.classList.toggle("on", a.dataset.view === name);
1581
- location.hash = name;
2161
+ document.title = TITLES[name] + " \u00b7 agent-custody";
2162
+ if (h !== name) history.replaceState(null, "", "#" + name);
2163
+ scrollTo(0, 0);
2164
+ };
2165
+ addEventListener("hashchange", route);
2166
+ const setDrawer = (open, refocus) => {
2167
+ $("nav").classList.toggle("open", open); $("menuBtn").setAttribute("aria-expanded", open);
2168
+ if (open) $("nav").querySelector("a").focus(); else if (refocus) $("menuBtn").focus();
1582
2169
  };
2170
+ const drawerOpen = () => $("nav").classList.contains("open");
2171
+ $("menuBtn").onclick = () => setDrawer(!drawerOpen());
2172
+ matchMedia("(max-width: 48rem)").onchange = () => setDrawer(false);
2173
+ document.addEventListener("keydown", (e) => { if (e.key === "Escape" && drawerOpen()) setDrawer(false, true); });
2174
+ $("userMenu").addEventListener("beforetoggle", (e) => { if (e.newState === "open") { const r = $("userBtn").getBoundingClientRect(); $("userMenu").style.top = r.bottom + 6 + "px"; $("userMenu").style.right = document.documentElement.clientWidth - r.right + "px"; } });
2175
+ $("userMenu").addEventListener("toggle", (e) => $("userBtn").setAttribute("aria-expanded", e.newState === "open"));
1583
2176
  const LOG_BASE = $("tenantPreview").textContent.replace("t/<tenant>/", "");
1584
2177
  const slug = (s) => s.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
1585
2178
  let tenantEdited = false;
1586
2179
  const previewTenant = () => { $("tenantPreview").textContent = LOG_BASE + "t/" + ($("tenant").value || "<tenant>") + "/"; };
1587
2180
  $("company").oninput = () => { if (!tenantEdited) { $("tenant").value = slug($("company").value); previewTenant(); } };
1588
2181
  $("tenant").oninput = () => { tenantEdited = $("tenant").value !== ""; previewTenant(); };
1589
- $("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create an account" : "Sign in"; $("authGo").textContent = registering ? "Create account" : "Sign in"; $("authNote").hidden = !registering; $("password").autocomplete = registering ? "new-password" : "current-password"; $("authSwap").textContent = registering ? "I already have an account" : "Create an account instead"; };
2182
+ const authTab = (signUp) => {
2183
+ registering = signUp;
2184
+ $("tabSignIn").setAttribute("aria-selected", String(!signUp)); $("tabSignUp").setAttribute("aria-selected", String(signUp));
2185
+ $("authTitle").textContent = signUp ? "Sign up" : "Sign in"; $("authGo").textContent = signUp ? "Sign up" : "Sign in";
2186
+ $("authNote").hidden = !signUp; $("pwRule").hidden = !signUp; $("forgotOpen").hidden = signUp || !MAIL; $("ssoSwap").hidden = signUp; $("ssoForm").hidden = true;
2187
+ $("password").autocomplete = signUp ? "new-password" : "current-password";
2188
+ $("authForm").hidden = false; $("forgotForm").hidden = true; $("authMsg").textContent = "";
2189
+ };
2190
+ $("tabSignIn").onclick = () => authTab(false);
2191
+ $("tabSignUp").onclick = () => authTab(true);
2192
+ authTab(false);
2193
+ $("ssoOpen").onclick = () => { $("ssoSwap").hidden = true; $("ssoForm").hidden = false; $("ssoForm").querySelector("input").focus(); };
2194
+ $("forgotOpen").onclick = () => { $("authForm").hidden = true; $("ssoSwap").hidden = true; $("authTitle").textContent = "Reset your password"; $("forgotForm").hidden = false; $("forgotEmail").value = $("email").value; $("forgotMsg").textContent = ""; $("forgotEmail").focus(); };
2195
+ $("forgotBack").onclick = () => authTab(false);
2196
+ $("forgotForm").onsubmit = async (e) => {
2197
+ e.preventDefault();
2198
+ try { await api("POST", "/api/password/forgot", { email: $("forgotEmail").value }); note("forgotMsg", "If an account has this address, we sent it a link to set a new password. The link works for one hour.", true); }
2199
+ catch (err) { note("forgotMsg", err.message, false); }
2200
+ };
1590
2201
  $("authForm").onsubmit = async (e) => {
1591
2202
  e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
1592
2203
  try {
@@ -1595,7 +2206,7 @@ const PORTAL_PAGE = `<!doctype html>
1595
2206
  await enter();
1596
2207
  } catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
1597
2208
  };
1598
- const askCode = () => { $("authForm").hidden = true; $("ssoForm").hidden = true; $("providers").hidden = true; $("authSwap").parentElement.hidden = true; $("authTitle").textContent = "Enter your code"; $("mfaForm").hidden = false; $("mfaCode").focus(); };
2209
+ const askCode = () => { $("authForm").hidden = true; $("ssoForm").hidden = true; $("ssoSwap").hidden = true; $("providers").hidden = true; $("authTabs").hidden = true; $("authTitle").textContent = "Enter your code"; $("mfaForm").hidden = false; $("mfaCode").focus(); };
1599
2210
  $("mfaForm").onsubmit = async (e) => {
1600
2211
  e.preventDefault();
1601
2212
  try { await api("POST", "/api/login/mfa", { code: $("mfaCode").value }); location.href = "/"; }
@@ -1604,88 +2215,119 @@ const PORTAL_PAGE = `<!doctype html>
1604
2215
  $("onboardForm").onsubmit = async (e) => {
1605
2216
  e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
1606
2217
  try {
1607
- const r = await api("POST", "/api/onboard", { tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value, phone: $("phone").value, telegram: $("telegram").value });
1608
- $("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
2218
+ const r = await api("POST", "/api/onboard", { tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value });
2219
+ $("firstToken").textContent = r.token; renderSetup($("firstSetup"), Object.assign({}, r.setup, { env: "export AGENT_CUSTODY_LOG_TOKEN=" + r.token }), true); $("savedFirst").disabled = false; $("savedFirst").textContent = "I saved the key"; show("welcome");
1609
2220
  } catch (err) { $("onboardMsg").className = "msg err"; $("onboardMsg").textContent = err.message; }
1610
2221
  };
1611
2222
  $("signoutOnboard").onclick = async (e) => { e.preventDefault(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
1612
- $("copyFirst").onclick = () => navigator.clipboard.writeText($("firstToken").textContent);
1613
2223
  // Light or dark by choice, kept in this browser; unset, the page follows the system. The button says where it is going.
1614
2224
  const themeNow = () => document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
1615
- const themeLabel = () => { $("themeToggle").textContent = themeNow() === "dark" ? "Light mode" : "Dark mode"; };
2225
+ const themeLabel = () => { $("themeToggle").setAttribute("aria-pressed", String(themeNow() === "dark")); };
1616
2226
  $("themeToggle").onclick = () => { const next = themeNow() === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = next; try { localStorage.setItem("agent-custody-theme", next); } catch {} themeLabel(); };
1617
2227
  themeLabel();
1618
2228
  const snip = (text) => "<div class=snip><pre>" + esc(text) + "</pre><button type=button class=quiet data-copy>Copy</button></div>";
1619
2229
  const step = (n, title, body) => "<div class=step><span class=n>" + n + "</span><div><h3>" + title + "</h3>" + body + "</div></div>";
1620
2230
  const renderSetup = (el, s, atRegistration) => {
2231
+ const n = atRegistration ? 1 : 0;
1621
2232
  el.innerHTML =
1622
- step(1, "Keep the key where your gateway runs", (atRegistration ? "<p>Your first key is shown once; we keep only its hash. Put it in the environment of the machine that runs your gateway or SDK:</p>" : "<p>Your key was shown once at registration. If it is gone, mint another under <a href=\\"#keys\\" data-view=\\"keys\\">API keys</a>. It lives in the environment of the machine that runs your gateway or SDK:</p>") + snip(s.env)) +
1623
- step(2, "Point your gateway or SDK at your log", "<p>Add this to <code>gateway.json</code> or <code>sdk.json</code>. <code>hashOnly</code> means this log receives the hash of each receipt and never the receipt.</p>" + snip(s.config)) +
1624
- step(3, "Send the first receipt", "<p>Run your agent through the gateway once. The <a href=\\"#overview\\" data-view=\\"overview\\">Overview</a> shows the append within seconds, and the first signed checkpoint follows within minutes. New to the gateway? <a href=\\"https://agent-custody.dev/guide/getting-started\\">Getting started</a> takes ten minutes.</p>") +
1625
- step(4, "Hand this to whoever verifies your receipts", "<p>Both commands fetch this log's published keys and pin them; <code>--log-id</code> makes sure the tree heads are this log's.</p>" + snip(s.verify) + snip(s.audit)) +
1626
- step(5, "Take your data, any time", "<p>Every leaf hash, the signed head, the keys, the checkpoints, your usage, and the actions taken on your tenant, checked against each other and written as a log copy the verifier reads offline.</p>" + snip(s.export)) +
2233
+ step(n + 1, "Keep the key where your gateway runs", (atRegistration ? "<p>Your first key is shown once; we keep only its hash. Put it in the environment of the machine that runs your gateway or SDK. The command below holds your key:</p>" : "<p>Your key was shown once at registration. If it is gone, create another under <a href=\\"#keys\\" data-view=\\"keys\\">API keys</a>. It lives in the environment of the machine that runs your gateway or SDK:</p>") + snip(s.env)) +
2234
+ step(n + 2, "Point your gateway or SDK at your log", "<p>Add this to <code>gateway.json</code> or <code>sdk.json</code>. <code>hashOnly</code> means this log receives the hash of each receipt and never the receipt.</p>" + snip(s.config)) +
2235
+ step(n + 3, "Send the first receipt", "<p>Run your agent through the gateway once. The <a href=\\"#overview\\" data-view=\\"overview\\">Overview</a> shows the append within seconds, and the first signed checkpoint follows within minutes. New to the gateway? <a href=\\"https://agent-custody.dev/guide/getting-started\\" target=\\"_blank\\" rel=\\"noopener\\">Getting started</a> takes ten minutes.</p>") +
2236
+ "<h2>After the first receipt</h2>" + step("", "Hand this to whoever verifies your receipts", "<p>Both commands fetch this log's published keys and pin them; <code>--log-id</code> makes sure the tree heads are this log's.</p>" + snip(s.verify) + snip(s.audit)) +
2237
+ step("", "Take your data, any time", "<p>Every leaf hash, the signed head, the keys, the checkpoints, your usage, and the actions taken on your tenant, checked against each other and written as a log copy the verifier reads offline.</p>" + snip(s.export)) +
1627
2238
  "<h2>Your log's addresses</h2><div class=panel><table class=addr><tbody>" + [["Your log", s.log], ["Log id on tree heads", s.logId], ["Your checkpoints", s.checkpoints || "published after your first append"], ["The log's keys", s.keys + (s.keyid ? " (current keyid " + s.keyid.slice(0, 12) + "…)" : "")]].map(([k, v]) => "<tr><th>" + esc(k) + "</th><td class=mono>" + esc(v) + "</td></tr>").join("") + "</tbody></table></div>" +
1628
- "<h2>What this log does not do</h2><p class=muted>Hold receipt contents; forge a receipt, since your gateway key signs those; or, today, countersign with a second independent witness. <a href=\\"https://agent-custody.dev/receipts/#what-a-receipt-proves-and-what-it-does-not\\">What a receipt proves and what it does not.</a></p>";
2239
+ "<h2>What this log does not do</h2><p class=muted>Hold receipt contents; forge a receipt, since your gateway key signs those; or, today, countersign with a second independent witness. <a href=\\"https://github.com/svayatta/agent-custody/tree/main/packages/receipts#what-a-receipt-proves-and-what-it-does-not\\" target=\\"_blank\\" rel=\\"noopener\\">What a receipt proves and what it does not.</a></p>";
1629
2240
  };
1630
2241
  document.addEventListener("click", (e) => {
1631
- const b = e.target.closest("button[data-copy]"); if (b) { navigator.clipboard.writeText(b.previousElementSibling.textContent).then(() => { b.textContent = "Copied"; setTimeout(() => { b.textContent = "Copy"; }, 1500); }); return; }
1632
- const a = e.target.closest("a[data-view]"); if (a && a.closest("main")) { e.preventDefault(); view(a.dataset.view); }
2242
+ const b = e.target.closest("button[data-copy]"); if (b) { const was = b.dataset.was || b.textContent; b.dataset.was = was; navigator.clipboard.writeText(b.previousElementSibling.textContent).then(() => { b.textContent = "Copied"; setTimeout(() => { b.textContent = was; }, 1500); }, () => toast("Copy failed. Select the text and copy it by hand.", false)); return; }
2243
+ if (drawerOpen() && !e.target.closest("#menuBtn") && (!e.target.closest("nav") || e.target.closest("nav a"))) setDrawer(false);
2244
+ if (e.target.closest("#userMenu a")) $("userMenu").hidePopover();
1633
2245
  });
1634
- $("toDash").onclick = () => enter();
1635
- $("signout").onclick = async (e) => { e.preventDefault(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
1636
- for (const a of document.querySelectorAll("nav a[data-view]")) a.onclick = (e) => { e.preventDefault(); view(a.dataset.view); };
2246
+ $("savedFirst").onclick = () => { $("savedFirst").disabled = true; $("savedFirst").textContent = "Key saved"; };
2247
+ $("toDash").onclick = async () => { if (!$("savedFirst").disabled && !(await ask({ title: "Leave without saving the key?", text: "We show the key one time. If you did not copy it, create a new key under API keys.", ok: "Leave anyway" }))) return; enter(); };
2248
+ addEventListener("beforeunload", (e) => { if ((!$("welcome").hidden && !$("savedFirst").disabled) || !$("minted").hidden) e.preventDefault(); });
2249
+ $("signout").onclick = async () => { $("userMenu").hidePopover(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
1637
2250
  const render = (o) => {
1638
- $("tenantTag").textContent = o.tenant; $("tenantTag").hidden = false; $("planTag").textContent = o.plan + " plan"; $("planTag").hidden = false;
2251
+ $("tenantTag").textContent = o.tenant; $("tenantTag").hidden = false; $("planTag").textContent = cap(o.plan); $("planTag").hidden = false;
1639
2252
  const pct = o.quota ? o.used / o.quota : 0;
1640
2253
  $("cUsed").className = "card " + (o.quota === null ? "ok" : pct >= 1 ? "bad" : pct >= .8 ? "warn" : "ok");
1641
2254
  $("vUsed").textContent = fmt(o.used); $("sUsed").textContent = o.quota === null ? "no allowance on " + o.plan : "of " + fmt(o.quota) + " on " + o.plan + (pct >= 1 ? ": appends are refused until next month" : "");
1642
2255
  $("vSize").textContent = fmt(o.treeSize);
2256
+ $("firstReceipt").hidden = o.treeSize > 0; $("ovCards").hidden = o.treeSize === 0;
1643
2257
  const live = o.keys.filter((k) => !k.revokedAt).length; $("vKeys").textContent = live; $("sKeys").textContent = o.keys.length - live + " revoked"; $("nKeys").textContent = live;
1644
2258
  $("cCp").className = "card " + (o.latestCheckpoint ? (Date.now() - Date.parse(o.latestCheckpoint.signedAt) < 7 * 3600e3 ? "ok" : "warn") : "warn");
1645
2259
  $("vCp").textContent = o.latestCheckpoint ? "size " + fmt(o.latestCheckpoint.treeSize) : "none yet"; $("sCp").textContent = o.latestCheckpoint ? "signed " + ago(o.latestCheckpoint.signedAt) : "published after your first append";
1646
- $("urls").innerHTML = [["Append here", o.urls.log], ["Log id on tree heads", o.logId], ["The log's keys", o.urls.keys], ["Your checkpoints", o.urls.checkpoints || "(not published)"], ["Current root", o.rootHash || "(empty)"]].map(([k, v]) => "<tr><th>" + esc(k) + "</th><td class=mono>" + esc(v) + "</td></tr>").join("");
1647
- $("audit").innerHTML = o.audit.map((e) => "<tr><td>" + esc(e.at.replace("T", " ").slice(0, 16)) + "</td><td class=mono>" + esc(e.actor) + "</td><td>" + esc(e.action) + "</td><td class=muted>" + esc(Object.entries(e.detail).map(([k, v]) => k + "=" + v).join(" ")) + "</td></tr>").join("") || "<tr><td colspan=4 class=muted>nothing yet</td></tr>";
1648
- const max = Math.max(1, ...o.months.map((m) => m.appends));
1649
- $("bars").innerHTML = o.months.map((m) => "<div class=bar><span class=mono>" + fmt(m.appends) + "</span><i style=\\"height:" + Math.max(2, Math.round(100 * m.appends / max)) + "%\\"></i><b>" + esc(m.month.slice(2)) + "</b></div>").join("");
1650
- $("usageNote").textContent = "Appends per calendar month, UTC. Your plan allows " + (o.quota === null ? "any number" : fmt(o.quota)) + " a month; the count resets on the first.";
1651
- $("keys").innerHTML = o.keys.map((k) => "<tr><td>" + esc(k.label) + "</td><td class=mono>" + esc(k.hash) + "</td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "live") + "</td><td>" + (k.revokedAt || !can("admin") ? "" : "<button class=quiet data-revoke=\\"" + esc(k.hash) + "\\">Revoke</button>") + "</td></tr>").join("");
1652
- $("billingPanel").innerHTML = o.plan === "free"
1653
- ? "<p>You are on the <b>free</b> plan: ten thousand appends a month, no card.</p><p>The <b>team</b> plan is <b>$50 a month</b>: a million appends, email support within two working days, the same export and audit trail. No availability commitment yet, and the design fails closed: when the log is unreachable your gateway withholds pre-committed calls.</p>" + (o.stripe ? (can("owner") ? "<button id=upgrade>Upgrade to team, $50/month</button>" : "<p class=muted>An owner upgrades the plan.</p>") : "<p class=muted>Card payments are not switched on for this portal yet; email us and we move the plan by hand.</p>")
1654
- : "<p>You are on the <b>" + esc(o.plan) + "</b> plan" + (o.billing ? " (subscription " + esc(o.billing.status) + ")" : "") + ".</p>" + (o.stripe && o.billing && can("owner") ? "<button class=quiet id=manage>Manage billing</button>" : "");
2260
+ $("urls").innerHTML = [["Append here", o.urls.log], ["Log id on tree heads", o.logId], ["The log's keys", o.urls.keys], ["Your checkpoints", o.urls.checkpoints || "(not published)"], ["Current root", o.rootHash || "none until the first append"]].map(([k, v]) => "<tr><th>" + esc(k) + "</th><td class=mono>" + esc(v) + "</td></tr>").join("");
2261
+ keyList = o.keys;
2262
+ const max = 1.15 * Math.max(1, o.quota || 0, ...o.months.map((m) => m.appends));
2263
+ $("bars").innerHTML = o.months.map((m) => "<div class=bar><span class=mono>" + fmt(m.appends) + "</span><div class=col><i style=\\"height:" + Math.max(1, Math.round(100 * m.appends / max)) + "%\\"></i>" + (o.quota === null ? "" : "<s style=\\"bottom:" + (100 * o.quota / max) + "%\\"></s>") + "</div><b>" + esc(monthName(m.month)) + "</b></div>").join("");
2264
+ $("usageNote").textContent = "Appends per calendar month, UTC. " + (o.quota === null ? "Your plan has no limit." : "The dashed line is your plan limit, " + fmt(o.quota) + " appends a month.");
2265
+ $("usageNow").textContent = usedLine(o); meter($("usageBar"), o.used, o.quota);
2266
+ $("keyRows").innerHTML = o.keys.map((k) => "<tr><td><span title=\\"Hash " + esc(k.hash) + "\\">" + esc(k.label) + "</span></td><td>" + when(k.createdAt) + "</td><td>" + (k.lastUsedAt ? when(k.lastUsedAt) : "<span class=muted>never</span>") + "</td><td>" + (k.revokedAt ? "Revoked " + when(k.revokedAt) : "Active") + "</td><td>" + (k.revokedAt || !can("admin") ? "" : "<button class=quiet data-revoke=\\"" + esc(k.hash) + "\\" data-label=\\"" + esc(k.label) + "\\">Revoke</button>") + "</td></tr>").join("");
2267
+ $("billingNow").innerHTML = "<p>You are on the <b>" + esc(PLAN_NAMES[o.plan] || o.plan) + "</b> plan" + (o.billing ? " (subscription " + esc(o.billing.status) + ")" : "") + ". " + esc(usedLine(o)) + "</p><progress id=billingBar aria-label=\\"Appends this month against the plan limit\\"></progress>";
2268
+ meter($("billingBar"), o.used, o.quota);
2269
+ $("plans").innerHTML = PLANS.map((p) => {
2270
+ const now = p.plan === o.plan;
2271
+ const act = now ? (o.stripe && o.billing && can("owner") ? "<button class=quiet id=manage>Manage billing</button>" : "")
2272
+ : p.plan === "team" && o.plan === "free" ? (o.stripe ? (can("owner") ? "<button id=upgrade>Upgrade to Team</button>" : "<p class=muted>An owner upgrades the plan.</p>") : "<p class=muted>Card payments are off on this portal. Email us and we move the plan by hand.</p>")
2273
+ : p.plan === "enterprise" ? "<a class=\\"btn quiet\\" href=\\"https://agent-custody.dev/contact\\" target=\\"_blank\\" rel=\\"noopener\\">Contact us</a>" : "";
2274
+ return "<div class=\\"card plan" + (now ? " now" : "") + "\\"" + (now ? " aria-current=true" : "") + "><h2>" + esc(p.name) + (now ? " <span class=pill>Current plan</span>" : "") + "</h2><div class=price>" + esc(p.price) + "</div><div class=muted>" + (p.appends === null ? "No append limit" : fmt(p.appends) + " appends a month") + "</div><ul>" + p.points.map((x) => "<li>" + esc(x) + "</li>").join("") + "</ul><div class=act>" + act + "</div></div>";
2275
+ }).join("");
1655
2276
  $("exportCmd").textContent = o.exportCommand; renderSetup($("setupPane"), o.setup, false);
1656
2277
  const up = $("upgrade"); if (up) up.onclick = async () => { try { const r = await api("POST", "/api/checkout", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
1657
2278
  const mg = $("manage"); if (mg) mg.onclick = async () => { try { const r = await api("POST", "/api/billing-portal", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
1658
2279
  };
1659
- const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); await loadMembers(); };
1660
- const mfaShow = (on) => { $("mfaState").textContent = on ? "on" : "off"; $("mfaStart").hidden = on; $("mfaOffForm").hidden = !on; $("mfaSetupBox").hidden = true; };
1661
- $("mfaStart").onclick = async () => { try { const r = await api("POST", "/api/mfa/setup", {}); $("mfaSecret").textContent = r.secret; $("mfaUri").textContent = r.uri; $("mfaSetupBox").hidden = false; $("accountMsg").textContent = ""; } catch (err) { note("accountMsg", err.message, false); } };
1662
- $("mfaOnForm").onsubmit = async (e) => { e.preventDefault(); try { await api("POST", "/api/mfa/enable", { code: $("mfaOnCode").value }); $("mfaOnCode").value = ""; mfaShow(true); note("accountMsg", "Two-step sign-in is on.", true); } catch (err) { note("accountMsg", err.message, false); } };
2280
+ const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); await loadMembers(); await loadActivity(false); };
2281
+ const recoveryLeft = (n) => { $("recoveryLeft").textContent = n === 1 ? "1 recovery code is left." : n + " recovery codes are left."; };
2282
+ const showCodes = (codes) => { $("recoveryCodes").textContent = codes.join("\\n"); $("recoveryBox").hidden = false; recoveryLeft(codes.length); };
2283
+ const mfaShow = (on, left) => { $("mfaState").textContent = on ? "on" : "off"; $("mfaStart").hidden = on; $("mfaOffForm").hidden = !on; $("recoveryForm").hidden = !on; $("mfaSetupBox").hidden = true; if (!on) $("recoveryBox").hidden = true; if (left !== undefined) recoveryLeft(left); };
2284
+ $("mfaStart").onclick = async () => { try { const r = await api("POST", "/api/mfa/setup", {}); $("mfaQr").innerHTML = r.qr; $("mfaSecret").textContent = r.secret; $("mfaUri").textContent = r.uri; $("mfaSetupBox").hidden = false; $("mfaStart").hidden = true; $("accountMsg").textContent = ""; } catch (err) { note("accountMsg", err.message, false); } };
2285
+ $("mfaOnForm").onsubmit = async (e) => { e.preventDefault(); try { const r = await api("POST", "/api/mfa/enable", { code: $("mfaOnCode").value }); $("mfaOnCode").value = ""; mfaShow(true); showCodes(r.recoveryCodes); note("accountMsg", "Two-step sign-in is on.", true); } catch (err) { note("accountMsg", err.message, false); } };
1663
2286
  $("mfaOffForm").onsubmit = async (e) => { e.preventDefault(); try { await api("POST", "/api/mfa/disable", { code: $("mfaOffCode").value }); $("mfaOffCode").value = ""; mfaShow(false); note("accountMsg", "Two-step sign-in is off.", true); } catch (err) { note("accountMsg", err.message, false); } };
1664
- const roleOptions = (cur) => ROLES.filter((r) => r !== "owner" || can("owner")).map((r) => "<option" + (r === cur ? " selected" : "") + ">" + r + "</option>").join("");
2287
+ $("recoveryForm").onsubmit = async (e) => { e.preventDefault(); try { const r = await api("POST", "/api/mfa/recovery", { code: $("recoveryCode").value }); $("recoveryCode").value = ""; showCodes(r.recoveryCodes); note("accountMsg", "New recovery codes are made. The old codes no longer work.", true); } catch (err) { note("accountMsg", err.message, false); } };
2288
+ $("pwMail").hidden = !MAIL; $("pwNoMail").hidden = MAIL;
2289
+ $("pwForm").onsubmit = async (e) => { e.preventDefault(); try { await api("POST", "/api/password/change", { current: $("pwCurrent").value, password: $("pwNew").value }); $("pwCurrent").value = ""; $("pwNew").value = ""; note("pwMsg", "Your password is changed. Other sessions are signed out.", true); } catch (err) { note("pwMsg", err.message, false); } };
2290
+ const ROLE_LABEL = { readonly: "Read-only", reviewer: "Reviewer", admin: "Admin", owner: "Owner" };
2291
+ const ROLE_DESC = { readonly: "Looks at everything. Changes nothing.", reviewer: "Looks at everything and publishes policy versions.", admin: "Does what a reviewer does, and manages API keys and members below owner.", owner: "Manages everything, including billing and owners." };
2292
+ const roleChoices = () => ROLES.filter((r) => r !== "owner" || can("owner")).map((r) => [r, ROLE_LABEL[r], ROLE_DESC[r]]);
2293
+ const hint = () => { $("inviteRoleHint").textContent = ROLE_DESC[$("inviteRole").value]; };
2294
+ $("inviteRole").onchange = hint;
1665
2295
  const loadMembers = async () => {
1666
2296
  const r = await api("GET", "/api/members");
1667
2297
  $("nMembers").textContent = r.members.length;
1668
- $("inviteRole").innerHTML = roleOptions("readonly");
1669
- $("members").innerHTML = r.members.map((m) => "<tr><td>" + esc(m.email) + "</td><td>" + (can("admin") && (m.role !== "owner" || can("owner")) ? "<select data-setrole=" + m.id + ">" + roleOptions(m.role) + "</select>" : esc(m.role)) + "</td><td>" + esc(m.joinedAt.slice(0, 10)) + "</td><td>" + (m.mfa ? "on" : "off") + "</td><td>" + (can("admin") && (m.role !== "owner" || can("owner")) ? "<button class=link data-rmmember=" + m.id + ">Remove</button>" : "") + "</td></tr>").join("");
1670
- $("inviteRows").innerHTML = r.invites.map((i) => "<tr><td>" + esc(i.email) + "</td><td>" + esc(i.role) + "</td><td class=mono>" + esc(i.invitedBy) + "</td><td>" + esc(i.createdAt.slice(0, 10)) + "</td><td>" + (can("admin") ? "<button class=link data-rminvite=\\"" + esc(i.email) + "\\">Cancel</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>none</td></tr>";
2298
+ $("inviteRole").innerHTML = roleChoices().map(([v, label]) => "<option value=" + v + ">" + label + "</option>").join(""); hint();
2299
+ const owners = r.members.filter((m) => m.role === "owner").length;
2300
+ $("memberRows").innerHTML = r.members.map((m) => {
2301
+ const mine = can("admin") && (m.role !== "owner" || can("owner")), last = m.role === "owner" && owners === 1;
2302
+ return "<tr><td>" + esc(m.email) + "</td><td>" + esc(ROLE_LABEL[m.role]) + (mine && !last ? " <button class=link data-setrole=" + m.id + " data-role=" + m.role + ">Change</button>" : "") + "</td><td>" + esc(m.joinedAt.slice(0, 10)) + "</td><td>" + (m.mfa ? "on" : "off") + "</td><td>" + (last ? "<span class=muted>Last owner</span>" : mine ? "<button class=link data-rmmember=" + m.id + ">Remove</button>" : "") + "</td></tr>";
2303
+ }).join("");
2304
+ $("inviteRows").innerHTML = r.invites.map((i) => "<tr><td>" + esc(i.email) + "</td><td>" + esc(ROLE_LABEL[i.role]) + "</td><td class=mono>" + esc(i.invitedBy) + "</td><td>" + esc(i.createdAt.slice(0, 10)) + "</td><td>" + (can("admin") ? "<button class=link data-rminvite=\\"" + esc(i.email) + "\\">Cancel</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>none</td></tr>";
1671
2305
  };
1672
- const membersDo = async (path, body, done) => { try { await api("POST", path, body); note("membersMsg", done, true); await loadMembers(); } catch (err) { note("membersMsg", err.message, false); await loadMembers(); } };
1673
- $("inviteForm").onsubmit = (e) => { e.preventDefault(); membersDo("/api/members", { email: $("inviteEmail").value, role: $("inviteRole").value }, "Invite sent to " + $("inviteEmail").value + ".").then(() => { $("inviteEmail").value = ""; }); };
1674
- document.addEventListener("change", (e) => { const s = e.target.closest("select[data-setrole]"); if (s) membersDo("/api/members/" + s.dataset.setrole + "/role", { role: s.value }, "Role changed."); });
2306
+ const membersDo = async (path, body, done) => { try { await api("POST", path, body); toast(done, true); } catch (err) { toast(err.message, false); } await loadMembers(); };
2307
+ $("inviteForm").onsubmit = async (e) => { e.preventDefault(); const to = $("inviteEmail").value; try { const r = await api("POST", "/api/members", { email: to, role: $("inviteRole").value }); toast(r.emailSent ? "Invite sent to " + to + "." : "The invite is saved, but the email did not go out to " + to + ". Ask them to sign in at " + location.origin + "/ with that address and accept the invite.", r.emailSent); $("inviteEmail").value = ""; } catch (err) { toast(err.message, false); } await loadMembers(); };
1675
2308
  document.addEventListener("click", async (e) => {
1676
- const rm = e.target.closest("button[data-rmmember]"); if (rm && confirm("Remove this member? They lose access to the tenant at once.")) { membersDo("/api/members/" + rm.dataset.rmmember + "/remove", {}, "Member removed."); return; }
1677
- const ri = e.target.closest("button[data-rminvite]"); if (ri) { membersDo("/api/invites/remove", { email: ri.dataset.rminvite }, "Invite cancelled."); return; }
2309
+ const cell = (b) => b.closest("tr").cells[0].textContent;
2310
+ const ch = e.target.closest("button[data-setrole]");
2311
+ if (ch) { const who = cell(ch), role = await ask({ title: "Change the role of " + who, ok: "Save role", current: ch.dataset.role, choices: roleChoices() }); if (role && role !== ch.dataset.role) membersDo("/api/members/" + ch.dataset.setrole + "/role", { role }, "Role of " + who + " is now " + ROLE_LABEL[role] + "."); return; }
2312
+ const rm = e.target.closest("button[data-rmmember]");
2313
+ if (rm) { const who = cell(rm); if (await ask({ title: "Remove " + who + "?", text: "This member loses access to the tenant at once.", ok: "Remove member", danger: true })) membersDo("/api/members/" + rm.dataset.rmmember + "/remove", {}, who + " is removed."); return; }
2314
+ const ri = e.target.closest("button[data-rminvite]");
2315
+ if (ri) { if (await ask({ title: "Cancel the invite to " + ri.dataset.rminvite + "?", text: "This person can no longer accept it.", ok: "Cancel invite", danger: true })) membersDo("/api/invites/remove", { email: ri.dataset.rminvite }, "Invite to " + ri.dataset.rminvite + " is cancelled."); return; }
1678
2316
  const ac = e.target.closest("button[data-accept]"); if (ac) { try { await api("POST", "/api/invites/accept", { tenant: ac.dataset.accept }); await enter(); } catch (err) { note("onboardMsg", err.message, false); } }
1679
2317
  });
1680
2318
  const enter = async () => {
1681
2319
  try {
1682
2320
  const me = await api("GET", "/api/me");
1683
2321
  accountNotice(me);
1684
- if (me.tenant === null) { $("onboardWho").textContent = me.email; $("invites").hidden = !(me.invites || []).length; $("inviteList").innerHTML = (me.invites || []).map((i) => "<p>Join <b>" + esc(i.tenant) + "</b> as " + esc(i.role) + " <button type=button data-accept=\\"" + esc(i.tenant) + "\\">Accept</button></p>").join(""); if (me.profile) { for (const k of ["name", "company", "role", "phone", "telegram"]) if (me.profile[k]) $(k).value = me.profile[k]; } previewTenant(); show("onboard"); return; }
1685
- $("who").textContent = me.email; myRole = me.role; $("mintForm").hidden = !can("admin"); $("policyForm").hidden = !can("reviewer"); $("inviteBox").hidden = !can("admin") || !!(me.sso && me.sso.enforced); mfaShow(me.mfa); show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
2322
+ if (me.tenant === null) { $("onboardWho").textContent = me.email; $("invites").hidden = !(me.invites || []).length; $("inviteList").innerHTML = (me.invites || []).map((i) => "<p>Join <b>" + esc(i.tenant) + "</b> as " + esc(i.role) + " <button type=button data-accept=\\"" + esc(i.tenant) + "\\">Accept</button></p>").join(""); if (me.profile) { for (const k of ["name", "company", "role"]) if (me.profile[k]) $(k).value = me.profile[k]; } previewTenant(); show("onboard"); return; }
2323
+ $("who").textContent = me.email; myEmail = me.email; $("avatar").textContent = me.email.charAt(0); $("whoMeta").textContent = me.tenant + " \u00b7 " + ROLE_LABEL[me.role]; $("whoPlan").textContent = cap(me.plan) + " plan"; myRole = me.role; $("mintForm").hidden = !can("admin"); $("policyNew").hidden = !can("reviewer"); $("inviteBox").hidden = !can("admin") || !!(me.sso && me.sso.enforced); mfaShow(me.mfa, me.recoveryCodes); show("app"); await load(); route();
1686
2324
  }
1687
- catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); if (new URLSearchParams(location.search).get("mfa") === "1") askCode(); } else { show("app"); $("who").textContent = err.message; } }
2325
+ catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) authTab(true); if (new URLSearchParams(location.search).get("mfa") === "1") askCode(); } else { $("loadErr").textContent = err.message.charAt(0).toUpperCase() + err.message.slice(1) + "."; show("loadFail"); } }
1688
2326
  };
2327
+ $("retry").onclick = () => enter();
2328
+ const recheck = () => { if ($("resendVerify")) api("GET", "/api/me").then((me) => { if (me.emailVerified !== false) accountNotice(me); }, () => {}); };
2329
+ document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") recheck(); });
2330
+ addEventListener("focus", recheck);
1689
2331
  const accountNotice = (me) => {
1690
2332
  const parts = [];
1691
2333
  if (me.emailVerified === false && me.mail) parts.push("Verify your email address: we sent a link to " + me.email + ". <button type=button id=resendVerify>Send it again</button>");
@@ -1700,30 +2342,41 @@ const PORTAL_PAGE = `<!doctype html>
1700
2342
  const loadPolicies = async () => {
1701
2343
  const r = await api("GET", "/api/policies");
1702
2344
  $("nPolicies").textContent = r.policies.length || "";
1703
- $("policies").innerHTML = r.policies.map((p) => "<tr><td>" + esc(p.name) + "</td><td class=mono>" + esc(p.digest.slice(0, 16)) + "…</td><td>" + p.bytes + "</td><td>" + esc(p.createdAt.slice(0, 10)) + "</td><td class=mono>" + esc(p.createdBy.replace(/^portal:/, "")) + "</td><td><button class=link data-viewpol=\\"" + esc(p.id) + "\\">View</button>" + (can("reviewer") ? " <button class=link data-rmpol=\\"" + esc(p.id) + "\\">Remove</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>No versions published yet. Receipts keep their digests either way; a name is for the people reading them.</td></tr>";
2345
+ $("policyRows").innerHTML = r.policies.map((p) => "<tr><td>" + esc(p.name) + "</td><td class=mono>" + esc(p.digest.slice(0, 16)) + "…</td><td>" + p.bytes + "</td><td>" + esc(p.createdAt.slice(0, 10)) + "</td><td class=mono>" + esc(p.createdBy.replace(/^portal:/, "")) + "</td><td><button class=link data-viewpol=\\"" + esc(p.id) + "\\">View</button>" + (can("reviewer") ? " <button class=link data-rmpol=\\"" + esc(p.id) + "\\">Remove</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>No versions published yet. Receipts keep their digests either way; a name is for the people reading them.</td></tr>";
1704
2346
  };
1705
2347
  $("policyText").oninput = async () => { const t = $("policyText").value; $("policyDigestPreview").textContent = t ? "sha256 " + (await sha256hex(t)).slice(0, 16) + "…" : ""; };
2348
+ $("policyNew").onclick = () => { $("publishMsg").textContent = ""; $("publishDialog").showModal(); };
2349
+ $("publishCancel").onclick = () => $("publishDialog").close();
2350
+ $("policyViewClose").onclick = () => $("policyView").close();
1706
2351
  $("policyForm").onsubmit = async (e) => {
1707
- e.preventDefault(); $("policiesMsg").className = "msg";
1708
- try { const r = await api("POST", "/api/policies", { name: $("policyName").value, text: $("policyText").value }); $("policiesMsg").className = "msg ok"; $("policiesMsg").textContent = "Published " + r.policy.name + " as " + r.policy.digest.slice(0, 16) + "…"; $("policyName").value = ""; $("policyText").value = ""; $("policyDigestPreview").textContent = ""; await loadPolicies(); }
1709
- catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; }
2352
+ e.preventDefault(); $("publishMsg").textContent = "";
2353
+ try { const r = await api("POST", "/api/policies", { name: $("policyName").value, text: $("policyText").value }); $("publishDialog").close(); toast("Published version " + r.policy.name + " (digest " + r.policy.digest.slice(0, 16) + "…).", true); $("policyName").value = ""; $("policyText").value = ""; $("policyDigestPreview").textContent = ""; await loadPolicies(); await loadActivity(false); }
2354
+ catch (err) { note("publishMsg", err.message, false); }
1710
2355
  };
1711
2356
  $("matchForm").onsubmit = async (e) => {
1712
2357
  e.preventDefault(); $("matchOut").className = "msg";
1713
2358
  try {
1714
2359
  const raw = $("matchIn").value.trim(); let digest = raw;
1715
- if (!/^[0-9a-f]{64}$/i.test(raw)) { const b = JSON.parse(raw); const payload = b.envelope ? b.envelope.payload : b.payload; const st = JSON.parse(atob(payload)); digest = st.predicate && st.predicate.policy ? st.predicate.policy.policyDigest : ""; if (!digest) throw new Error("this receipt carries no policy decision"); }
2360
+ if (!/^[0-9a-f]{64}$/i.test(raw)) { try { const b = JSON.parse(raw); const st = JSON.parse(atob(b.envelope ? b.envelope.payload : b.payload)); digest = st.predicate && st.predicate.policy ? st.predicate.policy.policyDigest : ""; } catch { throw new Error("Paste a receipt file or a 64-character digest."); } if (!digest) throw new Error("This receipt carries no policy decision."); }
1716
2361
  const r = await api("GET", "/api/policies?digest=" + encodeURIComponent(digest));
1717
2362
  $("matchOut").className = r.match ? "msg ok" : "msg"; $("matchOut").textContent = r.match ? "Decided by \\"" + r.match.name + "\\", published " + r.match.createdAt.slice(0, 10) + " (" + digest.slice(0, 16) + "…)" : "No published version has digest " + digest.slice(0, 16) + "…; publish the file the gateway loaded to name it.";
1718
2363
  } catch (err) { $("matchOut").className = "msg err"; $("matchOut").textContent = err.message; }
1719
2364
  };
1720
2365
  document.addEventListener("click", async (e) => {
1721
- const v = e.target.closest("button[data-viewpol]"); if (v) { try { const r = await api("GET", "/api/policies/" + v.dataset.viewpol); $("policyViewName").textContent = r.policy.name + " · " + r.policy.digest; $("policyViewText").textContent = r.policy.text; $("policyView").hidden = false; } catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; } return; }
1722
- const rm = e.target.closest("button[data-rmpol]"); if (rm && confirm("Remove this published version? Receipts keep their digests; only the name goes.")) { try { await api("POST", "/api/policies/" + rm.dataset.rmpol + "/remove", {}); $("policyView").hidden = true; await loadPolicies(); } catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; } }
2366
+ const v = e.target.closest("button[data-viewpol]"); if (v) { try { const r = await api("GET", "/api/policies/" + v.dataset.viewpol); $("policyViewName").textContent = r.policy.name + " · " + r.policy.digest; $("policyViewText").textContent = r.policy.text; $("policyView").showModal(); } catch (err) { toast(err.message, false); } return; }
2367
+ const rm = e.target.closest("button[data-rmpol]"); if (rm && await ask({ title: "Remove version " + rm.closest("tr").cells[0].textContent + "?", text: "Receipts keep their digests. Only the name goes.", ok: "Remove version", danger: true })) { try { await api("POST", "/api/policies/" + rm.dataset.rmpol + "/remove", {}); await loadPolicies(); await loadActivity(false); toast("Version removed.", true); } catch (err) { toast(err.message, false); } }
2368
+ });
2369
+ $("mintForm").onsubmit = async (e) => {
2370
+ e.preventDefault();
2371
+ if (!$("minted").hidden && !(await ask({ title: "Replace the key that is still shown?", text: "You did not confirm that you saved it. We show a key one time.", ok: "Continue" }))) return;
2372
+ try { const r = await api("POST", "/api/keys", { label: $("label").value }); $("mintedTok").textContent = r.token; $("minted").hidden = false; toast("Key created" + (r.label ? ": " + r.label : "") + ". We keep only its hash, " + r.tokenHash + ".", true); await load(); } catch (err) { toast(err.message, false); }
2373
+ };
2374
+ $("savedMinted").onclick = () => { $("minted").hidden = true; $("mintedTok").textContent = ""; toast("Key hidden. We do not show it again.", true); };
2375
+ document.addEventListener("click", async (e) => {
2376
+ const b = e.target.closest("button[data-revoke]"); if (!b) return;
2377
+ if (!(await ask({ title: "Revoke key " + b.closest("tr").cells[0].textContent + " (" + b.dataset.revoke + ")?", text: "A gateway that uses it stops appending at once. You cannot undo this.", ok: "Revoke key", danger: true }))) return;
2378
+ try { await api("POST", "/api/keys/" + b.dataset.revoke + "/revoke", {}); toast("Key revoked.", true); await load(); } catch (err) { toast(err.message, false); }
1723
2379
  });
1724
- $("mintForm").onsubmit = async (e) => { e.preventDefault(); try { const r = await api("POST", "/api/keys", { label: $("label").value }); $("mintedTok").textContent = r.token; $("minted").hidden = false; $("keysMsg").className = "msg ok"; $("keysMsg").textContent = "minted " + r.label + ", stored as hash " + r.tokenHash; await load(); } catch (err) { $("keysMsg").className = "msg err"; $("keysMsg").textContent = err.message; } };
1725
- $("copyMinted").onclick = () => navigator.clipboard.writeText($("mintedTok").textContent);
1726
- document.addEventListener("click", async (e) => { const b = e.target.closest("button[data-revoke]"); if (!b) return; if (!confirm("Revoke key " + b.dataset.revoke + "? A gateway using it stops appending at once.")) return; try { await api("POST", "/api/keys/" + b.dataset.revoke + "/revoke", {}); $("keysMsg").className = "msg ok"; $("keysMsg").textContent = "revoked"; await load(); } catch (err) { $("keysMsg").className = "msg err"; $("keysMsg").textContent = err.message; } });
1727
2380
  if (new URLSearchParams(location.search).get("upgraded")) history.replaceState(null, "", "/#billing");
1728
2381
  enter();
1729
2382
  })();