@agent-custody/receipts 0.6.13 → 0.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -267,9 +267,24 @@ async function main(argv) {
267
267
  return 0;
268
268
  }
269
269
  case "portal": {
270
- const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
270
+ const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
271
271
  if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
272
272
  throw new Error("portal needs --db-env, --secret-env, and --public-url");
273
+ let oauth;
274
+ for (const p of ["github", "google"]) {
275
+ const id = values[`${p}-client-id`];
276
+ const env = values[`${p}-secret-env`];
277
+ if (!id && !env)
278
+ continue;
279
+ if (!id || !env)
280
+ throw new Error(`${p} sign-in needs both --${p}-client-id and --${p}-secret-env`);
281
+ const clientSecret = process.env[env];
282
+ if (!clientSecret)
283
+ throw new Error(`portal: environment variable ${env} is not set`);
284
+ if (!values["portal-url"])
285
+ throw new Error("provider sign-in needs --portal-url, the callback is built from it");
286
+ oauth = { ...(oauth ?? {}), [p]: { clientId: id, clientSecret } };
287
+ }
273
288
  let mail;
274
289
  if (values["mail-key-env"] || values["mail-from"]) {
275
290
  if (!values["mail-key-env"] || !values["mail-from"])
@@ -301,7 +316,7 @@ async function main(argv) {
301
316
  catch {
302
317
  // the log may not be reachable from here at start; the sheet then omits the keyid
303
318
  }
304
- const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
319
+ const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
305
320
  console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
306
321
  await new Promise((resolve) => process.once("SIGINT", resolve));
307
322
  await running.close();
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export { openExporter, otlpExporter, spanFor } from "./otel.ts";
6
6
  export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
8
8
  export { PortalStore, portalHandler, readSession, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
9
- export type { MailOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
9
+ export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
10
10
  export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
11
11
  export { exportLog, formatExport } from "./log-export.ts";
12
12
  export type { ExportOptions, ExportResult } from "./log-export.ts";
package/dist/portal.d.ts CHANGED
@@ -18,6 +18,18 @@ export interface MailOptions {
18
18
  url?: string;
19
19
  fetch?: typeof fetch;
20
20
  }
21
+ /** Sign in through GitHub or Google: the OAuth web flow over fetch, no library. The callback is `<portalUrl>auth/<provider>/callback`. */
22
+ export interface OAuthOptions {
23
+ github?: {
24
+ clientId: string;
25
+ clientSecret: string;
26
+ };
27
+ google?: {
28
+ clientId: string;
29
+ clientSecret: string;
30
+ };
31
+ fetch?: typeof fetch;
32
+ }
21
33
  export interface PortalOptions {
22
34
  tenancy: PostgresTenancy;
23
35
  /** the Postgres client the tenancy uses; the portal's own tables live beside the log's */
@@ -33,6 +45,7 @@ export interface PortalOptions {
33
45
  portalUrl?: string;
34
46
  stripe?: StripeOptions;
35
47
  mail?: MailOptions;
48
+ oauth?: OAuthOptions;
36
49
  /** key throttles by X-Forwarded-For; only behind a proxy you run. Also marks cookies Secure. */
37
50
  trustProxy?: boolean;
38
51
  /** table prefix; default portal_ */
@@ -62,6 +75,15 @@ export declare class PortalStore {
62
75
  static hashPassword(password: string): string;
63
76
  static checkPassword(password: string, stored: string): boolean;
64
77
  createUser(email: string, password: string, profile?: Profile): Promise<PortalUser>;
78
+ userByEmail(email: string): Promise<PortalUser | null>;
79
+ /** the account's profile, for the onboarding screen and the operator's note */
80
+ profile(userId: string): Promise<Profile>;
81
+ updateProfile(userId: string, profile: Profile): Promise<void>;
82
+ /**
83
+ * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
84
+ * now on), else a new account with a random password nobody knows. The provider's email must be verified.
85
+ */
86
+ findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
65
87
  authenticate(email: string, password: string): Promise<PortalUser | null>;
66
88
  user(id: string): Promise<PortalUser | null>;
67
89
  addMember(userId: string, tenantId: string): Promise<void>;
package/dist/portal.js CHANGED
@@ -39,6 +39,8 @@ export class PortalStore {
39
39
  // who the account belongs to: added after the first tenants registered, so the columns are optional
40
40
  for (const c of PROFILE_COLUMNS)
41
41
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS ${c} TEXT`);
42
+ // a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
43
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}identities (provider TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES ${p}users(id), email TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (provider, subject))`);
42
44
  })();
43
45
  }
44
46
  return this.ready;
@@ -63,6 +65,42 @@ export class PortalStore {
63
65
  throw new Error("an account with this email already exists");
64
66
  return { id, email, createdAt: new Date(rows[0].created_at).toISOString() };
65
67
  }
68
+ async userByEmail(email) {
69
+ await this.init();
70
+ const rows = (await this.client.query(`SELECT id, email, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
71
+ const r = rows[0];
72
+ return r ? { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() } : null;
73
+ }
74
+ /** the account's profile, for the onboarding screen and the operator's note */
75
+ async profile(userId) {
76
+ await this.init();
77
+ const rows = (await this.client.query(`SELECT name, company, role, phone, telegram FROM ${this.p}users WHERE id = $1`, [userId])).rows;
78
+ const r = rows[0] ?? {};
79
+ const str = (v) => (v == null ? null : String(v));
80
+ return { name: str(r.name), company: str(r.company), role: str(r.role), phone: str(r.phone), telegram: str(r.telegram) };
81
+ }
82
+ async updateProfile(userId, profile) {
83
+ await this.init();
84
+ await this.client.query(`UPDATE ${this.p}users SET name = $2, company = $3, role = $4, phone = $5, telegram = $6 WHERE id = $1`, [userId, profile.name ?? null, profile.company ?? null, profile.role ?? null, profile.phone ?? null, profile.telegram ?? null]);
85
+ }
86
+ /**
87
+ * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
88
+ * now on), else a new account with a random password nobody knows. The provider's email must be verified.
89
+ */
90
+ async findOrCreateOAuthUser(provider, subject, email) {
91
+ await this.init();
92
+ const linked = (await this.client.query(`SELECT user_id FROM ${this.p}identities WHERE provider = $1 AND subject = $2`, [provider, subject])).rows;
93
+ if (linked[0]) {
94
+ const u = await this.user(linked[0].user_id);
95
+ if (u)
96
+ return u;
97
+ }
98
+ let user = await this.userByEmail(email);
99
+ if (!user)
100
+ user = await this.createUser(email, randomBytes(32).toString("hex"));
101
+ await this.client.query(`INSERT INTO ${this.p}identities (provider, subject, user_id, email) VALUES ($1, $2, $3, $4) ON CONFLICT (provider, subject) DO UPDATE SET user_id = EXCLUDED.user_id, email = EXCLUDED.email`, [provider, subject, user.id, email]);
102
+ return user;
103
+ }
66
104
  async authenticate(email, password) {
67
105
  await this.init();
68
106
  const rows = (await this.client.query(`SELECT id, email, password_hash, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
@@ -247,7 +285,8 @@ export function portalHandler(o) {
247
285
  }
248
286
  if (req.method === "GET" && url.pathname === "/") {
249
287
  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'" });
250
- return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])));
288
+ const providers = JSON.stringify(["github", "google"].filter((p) => !!o.oauth?.[p]));
289
+ return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])).replace("__PROVIDERS__", providers));
251
290
  }
252
291
  // ---- Stripe's webhook: the only caller that is not a browser with a session ----
253
292
  if (req.method === "POST" && url.pathname === "/stripe/webhook") {
@@ -279,47 +318,132 @@ export function portalHandler(o) {
279
318
  }
280
319
  return json(200, { received: true });
281
320
  }
282
- // ---- registration and login ----
283
- if (req.method === "POST" && url.pathname === "/api/register") {
284
- const b = await jsonBody();
285
- const email = String(b.email ?? "").trim().toLowerCase();
286
- const password = String(b.password ?? "");
321
+ // What the tenant setup needs, checked before anything is created: a mistyped form leaves nothing behind.
322
+ const parseOnboarding = async (b) => {
287
323
  const tenant = String(b.tenant ?? "").trim().toLowerCase();
288
- if (!EMAIL.test(email))
289
- return json(400, { error: "a valid email address is needed" });
290
- if (password.length < 10)
291
- return json(400, { error: "the password needs at least ten characters" });
292
324
  if (!TENANT_ID.test(tenant) || RESERVED.has(tenant))
293
- return json(400, { error: "the tenant id is the name in your log's URL: three to forty lowercase letters, digits, or hyphens, and not a reserved word" });
325
+ return { status: 400, body: { error: "the tenant id is the name in your log's URL: three to forty lowercase letters, digits, or hyphens, and not a reserved word" } };
294
326
  const text = (k, max) => String(b[k] ?? "").trim().slice(0, max);
295
327
  const profile = { name: text("name", 120), company: text("company", 160), role: text("role", 120) || null, phone: text("phone", 40) || null, telegram: text("telegram", 40).replace(/^@/, "") || null };
296
328
  if (!profile.name)
297
- return json(400, { error: "your name is needed, so we know who to write to" });
329
+ return { status: 400, body: { error: "your name is needed, so we know who to write to" } };
298
330
  if (!profile.company)
299
- return json(400, { error: "the company or organisation the tenant is for is needed" });
331
+ return { status: 400, body: { error: "the company or organisation the tenant is for is needed" } };
300
332
  if (profile.telegram && !/^[A-Za-z0-9_]{5,32}$/.test(profile.telegram))
301
- return json(400, { error: "a Telegram username is five to thirty-two letters, digits, or underscores, with or without the @" });
333
+ return { status: 400, body: { error: "a Telegram username is five to thirty-two letters, digits, or underscores, with or without the @" } };
302
334
  if (profile.phone && !/^[+0-9 ()./-]{6,40}$/.test(profile.phone))
303
- return json(400, { error: "a phone number is digits, with an optional + and spaces" });
335
+ return { status: 400, body: { error: "a phone number is digits, with an optional + and spaces" } };
304
336
  if (await o.tenancy.tenant(tenant))
305
- return json(409, { error: "that tenant id is taken" });
337
+ return { status: 409, body: { error: "that tenant id is taken" } };
338
+ return { tenant, profile };
339
+ };
340
+ const onboard = async (user, parsed) => {
341
+ const { tenant, profile } = parsed;
342
+ if (await store.tenantOf(user.id))
343
+ return { status: 409, body: { error: "this account already has a tenant" } };
344
+ await store.updateProfile(user.id, profile);
345
+ const t = await o.tenancy.addTenant(tenant, tenant, `portal:${user.email}`);
346
+ await store.addMember(user.id, tenant);
347
+ const minted = await o.tenancy.addToken(tenant, "first key", `portal:${user.email}`);
348
+ log(`agent-custody portal: ${user.email} registered tenant ${tenant}`);
349
+ void welcomeMail(user.email, profile.name, t.id, t.logId);
350
+ void notifyMail({ ...profile, email: user.email, tenant: t.id });
351
+ 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) } };
352
+ };
353
+ if (req.method === "POST" && url.pathname === "/api/register") {
354
+ const b = await jsonBody();
355
+ const email = String(b.email ?? "").trim().toLowerCase();
356
+ const password = String(b.password ?? "");
357
+ if (!EMAIL.test(email))
358
+ return json(400, { error: "a valid email address is needed" });
359
+ if (password.length < 10)
360
+ return json(400, { error: "the password needs at least ten characters" });
361
+ const oneStep = "tenant" in b || "company" in b || "name" in b;
362
+ let parsed = null;
363
+ if (oneStep) {
364
+ const p = await parseOnboarding(b);
365
+ if ("status" in p)
366
+ return json(p.status, p.body);
367
+ parsed = p;
368
+ }
306
369
  // throttled once the request is well formed: a mistyped form costs nothing, five real registrations from one address, then one every ten minutes
307
370
  if (!registrations.take(`reg:${addr}`))
308
371
  return json(429, { error: "too many registrations from this address; try again later" });
309
372
  let user;
310
373
  try {
311
- user = await store.createUser(email, password, profile);
374
+ user = await store.createUser(email, password);
312
375
  }
313
376
  catch (e) {
314
377
  return json(409, { error: e instanceof Error ? e.message : String(e) });
315
378
  }
316
- const t = await o.tenancy.addTenant(tenant, tenant, `portal:${email}`);
317
- await store.addMember(user.id, tenant);
318
- const minted = await o.tenancy.addToken(tenant, "first key", `portal:${email}`);
319
- log(`agent-custody portal: ${email} registered tenant ${tenant}`);
320
- void welcomeMail(email, profile.name, t.id, t.logId);
321
- void notifyMail({ ...profile, email, tenant: t.id });
322
- return json(200, { 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) }, { "set-cookie": setCookie(signSession(o.secret, user.id)) });
379
+ const cookie = { "set-cookie": setCookie(signSession(o.secret, user.id)) };
380
+ if (!parsed) {
381
+ log(`agent-custody portal: ${email} created an account`);
382
+ return json(200, { email, tenant: null }, cookie);
383
+ }
384
+ const r = await onboard(user, parsed);
385
+ return json(r.status, r.body, cookie);
386
+ }
387
+ // ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
388
+ const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
389
+ if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
390
+ const name = provider[1];
391
+ const conf = o.oauth[name];
392
+ const redirectUri = `${portalBase}auth/${name}/callback`;
393
+ const stateCookie = (value) => `custody_oauth=${value ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 600 : 0}`;
394
+ if (!provider[2]) {
395
+ const state = signSession(o.secret, `oauth:${name}:${randomBytes(16).toString("hex")}`, 600_000);
396
+ const authorize = name === "github"
397
+ ? `https://github.com/login/oauth/authorize?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, scope: "user:email", state })}`
398
+ : `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, response_type: "code", scope: "openid email", state, prompt: "select_account" })}`;
399
+ res.writeHead(302, { location: authorize, "set-cookie": stateCookie(state), "cache-control": "no-store" });
400
+ return void res.end();
401
+ }
402
+ const state = url.searchParams.get("state") ?? "";
403
+ const code = url.searchParams.get("code") ?? "";
404
+ const expected = cookies.custody_oauth;
405
+ const stateUser = readSession(o.secret, state);
406
+ if (!code || !state || state !== expected || !stateUser?.startsWith(`oauth:${name}:`))
407
+ return json(400, { error: "the sign-in did not start here, or took too long; go back and try again" }, { "set-cookie": stateCookie(null) });
408
+ const f = o.oauth.fetch ?? fetch;
409
+ let subject = "";
410
+ let email = "";
411
+ try {
412
+ if (name === "github") {
413
+ const tok = (await (await f("https://github.com/login/oauth/access_token", { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, body: JSON.stringify({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri }), signal: AbortSignal.timeout(10_000) })).json());
414
+ if (!tok.access_token)
415
+ throw new Error(tok.error ?? "no access token");
416
+ const gh = { authorization: `Bearer ${tok.access_token}`, accept: "application/vnd.github+json", "user-agent": "agent-custody-portal" };
417
+ const me = (await (await f("https://api.github.com/user", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
418
+ const emails = (await (await f("https://api.github.com/user/emails", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
419
+ const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
420
+ if (me.id === undefined || !primary)
421
+ throw new Error("GitHub gave no verified email; add one to your GitHub account or use email and password");
422
+ subject = String(me.id);
423
+ email = primary.email.toLowerCase();
424
+ }
425
+ else {
426
+ const tok = (await (await f("https://oauth2.googleapis.com/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri, grant_type: "authorization_code" }), signal: AbortSignal.timeout(10_000) })).json());
427
+ if (!tok.id_token)
428
+ throw new Error(tok.error ?? "no id token");
429
+ // the id token came straight from Google's token endpoint over TLS in this exchange, so its claims are read without a second signature check
430
+ const claims = JSON.parse(Buffer.from(tok.id_token.split(".")[1] ?? "", "base64url").toString());
431
+ if (!claims.sub || !claims.email || claims.email_verified !== true)
432
+ throw new Error("Google gave no verified email");
433
+ subject = claims.sub;
434
+ email = claims.email.toLowerCase();
435
+ }
436
+ }
437
+ catch (e) {
438
+ log(`agent-custody portal: ${name} sign-in failed: ${e instanceof Error ? e.message : String(e)}`);
439
+ return json(502, { error: `${name === "github" ? "GitHub" : "Google"} sign-in failed: ${e instanceof Error ? e.message : String(e)}` }, { "set-cookie": stateCookie(null) });
440
+ }
441
+ const user = await store.findOrCreateOAuthUser(name, subject, email);
442
+ log(`agent-custody portal: ${email} signed in with ${name}`);
443
+ // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
444
+ // would not carry it. The page's own navigation to / does.
445
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "set-cookie": [setCookie(signSession(o.secret, user.id)), stateCookie(null)], "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
446
+ return void res.end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/"><title>Signed in</title><p style="font:15px system-ui;padding:2rem">Signed in as ${email.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])}. <a href="/">Continue</a>.</p>`);
323
447
  }
324
448
  if (req.method === "POST" && url.pathname === "/api/login") {
325
449
  if (!loginFailures.take(`login:${addr}`))
@@ -338,14 +462,23 @@ export function portalHandler(o) {
338
462
  const user = userId ? await store.user(userId) : null;
339
463
  if (!user)
340
464
  return json(401, { error: "sign in first" });
465
+ if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
466
+ return json(415, { error: "expected a JSON body" });
341
467
  const tenantId = await store.tenantOf(user.id);
468
+ if (req.method === "GET" && url.pathname === "/api/me" && !tenantId)
469
+ return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe });
470
+ if (req.method === "POST" && url.pathname === "/api/onboard") {
471
+ const p = await parseOnboarding(await jsonBody());
472
+ if ("status" in p)
473
+ return json(p.status, p.body);
474
+ const r = await onboard(user, p);
475
+ return json(r.status, r.body);
476
+ }
342
477
  if (!tenantId)
343
- return json(409, { error: "this account has no tenant" });
478
+ return json(409, { error: "this account has no tenant yet; finish setting it up" });
344
479
  const tenant = await o.tenancy.tenant(tenantId);
345
480
  if (!tenant)
346
481
  return json(409, { error: "the tenant no longer exists" });
347
- if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
348
- return json(415, { error: "expected a JSON body" });
349
482
  if (req.method === "GET" && url.pathname === "/api/me") {
350
483
  const q = await o.tenancy.quota(tenantId);
351
484
  return json(200, { email: user.email, tenant: tenantId, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, disabled: !!tenant.disabledAt, billing: !!o.stripe });
@@ -509,6 +642,8 @@ const PORTAL_PAGE = `<!doctype html>
509
642
  button.link { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; }
510
643
  .auth { max-width: 26rem; margin: 4rem auto; }
511
644
  .auth.wide { max-width: 44rem; }
645
+ .providers { display: grid; gap: .5rem; margin: 0 0 1rem; } .providers a { display: block; text-align: center; padding: .55rem .9rem; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); text-decoration: none; font-weight: 600; }
646
+ .providers a:hover { border-color: var(--accent); } .or { text-align: center; color: var(--ink2); font-size: .82rem; margin: 0 0 .8rem; }
512
647
  .step { display: grid; grid-template-columns: 2rem 1fr; gap: .2rem .8rem; padding: 1rem 0; border-top: 1px solid var(--line); }
513
648
  .step .n { font: 700 .85rem/1.6 var(--mono); color: var(--accent); }
514
649
  .step h3 { margin: 0 0 .3rem; font-size: 1rem; } .step p { margin: 0 0 .5rem; color: var(--ink2); font-size: .92rem; }
@@ -525,25 +660,32 @@ const PORTAL_PAGE = `<!doctype html>
525
660
  <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>
526
661
  <section id="auth" class="auth" hidden>
527
662
  <h1 id="authTitle">Sign in</h1>
663
+ <div id="providers" class="providers" hidden></div>
528
664
  <form id="authForm">
529
- <div id="regFields" hidden>
530
- <label>Your name<input id="name" autocomplete="name" maxlength="120"></label>
531
- <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160"></label>
532
- <label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
533
- </div>
534
665
  <label>Work email<input id="email" type="email" autocomplete="email" required></label>
535
- <div id="regFields2" hidden>
536
- <label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
537
- <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>
538
- </div>
539
666
  <label>Password<input id="password" type="password" autocomplete="current-password" minlength="10" required></label>
540
- <label id="tenantField" hidden>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]"><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>
541
667
  <button id="authGo" type="submit">Sign in</button>
542
668
  <p class="msg" id="authMsg"></p>
543
669
  </form>
544
- <p class="muted"><button class="link" id="authSwap" type="button">Create an account and a tenant instead</button></p>
670
+ <p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
671
+ <p class="muted"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
545
672
  <p class="muted">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>
546
673
  </section>
674
+ <section id="onboard" class="auth" hidden>
675
+ <h1>Set up your tenant</h1>
676
+ <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>
677
+ <form id="onboardForm">
678
+ <label>Your name<input id="name" autocomplete="name" maxlength="120" required></label>
679
+ <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
680
+ <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>
681
+ <label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
682
+ <label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
683
+ <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>
684
+ <button type="submit">Create tenant</button>
685
+ <p class="msg" id="onboardMsg"></p>
686
+ </form>
687
+ <p class="muted"><a href="#" id="signoutOnboard">Sign out</a></p>
688
+ </section>
547
689
  <section id="welcome" class="auth wide" hidden>
548
690
  <h1>Your tenant is ready</h1>
549
691
  <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>
@@ -632,7 +774,9 @@ const PORTAL_PAGE = `<!doctype html>
632
774
  const fmt = (n) => Number(n).toLocaleString();
633
775
  const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 60 ? m + " min ago" : m < 1440 ? Math.round(m / 60) + " h ago" : Math.round(m / 1440) + " d ago"; };
634
776
  let registering = false;
635
- const show = (id) => { for (const s of ["auth", "welcome", "app"]) $(s).hidden = s !== id; };
777
+ const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
778
+ const PROVIDERS = __PROVIDERS__;
779
+ if (PROVIDERS.length) { $("providers").innerHTML = PROVIDERS.map((p) => "<a href='/auth/" + p + "'>Continue with " + (p === "github" ? "GitHub" : "Google") + "</a>").join("") + "<p class=or>or with email</p>"; $("providers").hidden = false; }
636
780
  const view = (name) => {
637
781
  for (const p of document.querySelectorAll("[data-pane]")) p.hidden = p.dataset.pane !== name;
638
782
  for (const a of document.querySelectorAll("nav a[data-view]")) a.classList.toggle("on", a.dataset.view === name);
@@ -644,16 +788,22 @@ const PORTAL_PAGE = `<!doctype html>
644
788
  const previewTenant = () => { $("tenantPreview").textContent = LOG_BASE + "t/" + ($("tenant").value || "<tenant>") + "/"; };
645
789
  $("company").oninput = () => { if (!tenantEdited) { $("tenant").value = slug($("company").value); previewTenant(); } };
646
790
  $("tenant").oninput = () => { tenantEdited = $("tenant").value !== ""; previewTenant(); };
647
- $("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create your tenant" : "Sign in"; $("authGo").textContent = registering ? "Create tenant" : "Sign in"; for (const id of ["regFields", "regFields2", "tenantField"]) $(id).hidden = !registering; for (const id of ["name", "company", "tenant"]) $(id).required = registering; $("password").autocomplete = registering ? "new-password" : "current-password"; $("authSwap").textContent = registering ? "I already have an account" : "Create an account and a tenant instead"; previewTenant(); };
791
+ $("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"; };
648
792
  $("authForm").onsubmit = async (e) => {
649
793
  e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
650
794
  try {
651
- if (registering) {
652
- const r = await api("POST", "/api/register", { email: $("email").value, password: $("password").value, tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value, phone: $("phone").value, telegram: $("telegram").value });
653
- $("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
654
- } else { await api("POST", "/api/login", { email: $("email").value, password: $("password").value }); await enter(); }
795
+ await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
796
+ await enter();
655
797
  } catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
656
798
  };
799
+ $("onboardForm").onsubmit = async (e) => {
800
+ e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
801
+ try {
802
+ 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 });
803
+ $("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
804
+ } catch (err) { $("onboardMsg").className = "msg err"; $("onboardMsg").textContent = err.message; }
805
+ };
806
+ $("signoutOnboard").onclick = async (e) => { e.preventDefault(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
657
807
  $("copyFirst").onclick = () => navigator.clipboard.writeText($("firstToken").textContent);
658
808
  // Light or dark by choice, kept in this browser; unset, the page follows the system. The button says where it is going.
659
809
  const themeNow = () => document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
@@ -703,7 +853,11 @@ const PORTAL_PAGE = `<!doctype html>
703
853
  };
704
854
  const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
705
855
  const enter = async () => {
706
- try { const me = await api("GET", "/api/me"); $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview"); }
856
+ try {
857
+ const me = await api("GET", "/api/me");
858
+ if (me.tenant === null) { $("onboardWho").textContent = me.email; 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; }
859
+ $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
860
+ }
707
861
  catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
708
862
  };
709
863
  const sha256hex = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.6.13",
3
+ "version": "0.6.14",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
6
6
  "license": "Apache-2.0",