@mostra/runtime 0.11.0 → 0.13.0

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 (50) hide show
  1. package/dist/bin.js +930 -458
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{instance-DCiUHvgZ.js → instance-D5gh-sMM.js} +1231 -46
  5. package/dist/instance-D5gh-sMM.js.map +1 -0
  6. package/dist/reference/cli.md +112 -2
  7. package/dist/reference/diagnostics.json +29 -2
  8. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +2 -2
  9. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  10. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  11. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  12. package/dist/reference/self-hosting.md +1 -1
  13. package/dist/skill/SKILL.md +5 -3
  14. package/dist/skill/references/answers.md +3 -1
  15. package/dist/skill/references/mcp.md +2 -2
  16. package/dist/skill/references/teams.md +78 -0
  17. package/package.json +6 -6
  18. package/src/actions/index.ts +5 -2
  19. package/src/gateway/actions.ts +6 -1
  20. package/src/gateway/browser.ts +84 -1
  21. package/src/gateway/capabilities.ts +5 -1
  22. package/src/gateway/index.ts +43 -1
  23. package/src/gateway/team.ts +181 -0
  24. package/src/instance/index.ts +2 -1
  25. package/src/interaction/ephemeral.ts +21 -0
  26. package/src/interaction/events.ts +17 -0
  27. package/src/interaction/index.ts +265 -20
  28. package/src/interaction/roster.ts +585 -0
  29. package/src/interaction/team.ts +426 -0
  30. package/src/interaction/wait.ts +150 -0
  31. package/src/ledger/migrations.ts +44 -0
  32. package/src/link/hosted.ts +14 -3
  33. package/src/link/manager.ts +31 -1
  34. package/src/server/api.ts +1 -1
  35. package/src/server/auth.ts +83 -16
  36. package/src/server/authorize.ts +27 -4
  37. package/src/server/config.ts +53 -0
  38. package/src/server/directory.ts +73 -0
  39. package/src/server/feed.ts +89 -3
  40. package/src/server/hosted-pages.ts +19 -6
  41. package/src/server/hosted.ts +108 -49
  42. package/src/server/index.ts +72 -15
  43. package/src/server/metering.ts +117 -12
  44. package/src/server/operator.ts +87 -28
  45. package/src/server/providers.ts +61 -9
  46. package/src/server/relay.ts +258 -107
  47. package/src/share/index.ts +50 -2
  48. package/src/verify/index.ts +7 -0
  49. package/src/verify/runner.ts +5 -1
  50. package/dist/instance-DCiUHvgZ.js.map +0 -1
@@ -41,6 +41,7 @@ import {
41
41
  remoteLogoutMethod,
42
42
  remoteStatusMethod,
43
43
  remoteTokenMethod,
44
+ rosterAddMethod,
44
45
  type ServerLiveValueParams,
45
46
  SubmissionEnvelope,
46
47
  type SubmissionPolicy,
@@ -335,6 +336,17 @@ export function createLink(options: LinkOptions): Link {
335
336
  const secret = /#t=([^&]+)/.exec(url)?.[1];
336
337
  if (secret !== undefined) options.protect(secret);
337
338
  };
339
+ /** Protects every capability link a value holds, at any depth. */
340
+ const protectLinksIn = (value: unknown, depth = 0): void => {
341
+ if (depth > 16) return;
342
+ if (typeof value === "string") {
343
+ if (value.includes("#t=")) protectLink(value);
344
+ } else if (Array.isArray(value)) {
345
+ for (const item of value) protectLinksIn(item, depth + 1);
346
+ } else if (value !== null && typeof value === "object") {
347
+ for (const item of Object.values(value)) protectLinksIn(item, depth + 1);
348
+ }
349
+ };
338
350
 
339
351
  const linkRow = (db: LedgerDb, server: string): LinkRow | undefined =>
340
352
  db.get<LinkRow>("SELECT * FROM remote_link WHERE server = ?", server);
@@ -1452,7 +1464,12 @@ export function createLink(options: LinkOptions): Link {
1452
1464
  }),
1453
1465
  );
1454
1466
  }
1455
- return session.call(definition, params, { timeoutMs: 30_000 });
1467
+ const answer = await session.call(definition, params, { timeoutMs: 30_000 });
1468
+ // A forwarded answer may carry the hosted home's capability links (`roster/add`'s personal
1469
+ // links, D168): whatever it carries is protected from the logs here, as the share's own link
1470
+ // is (Opus review 3).
1471
+ protectLinksIn(answer);
1472
+ return answer;
1456
1473
  },
1457
1474
  shares: () => ({
1458
1475
  mint: async (input) => {
@@ -1475,6 +1492,19 @@ export function createLink(options: LinkOptions): Link {
1475
1492
  ...(minted.expiresAt !== undefined ? { expiresAt: minted.expiresAt } : {}),
1476
1493
  };
1477
1494
  },
1495
+ respondents: async (input) => {
1496
+ // The roster is the hosted home's, its personal links hosted links (D168): each is
1497
+ // protected from the logs here as the share's own link is.
1498
+ const session = await self.session(input.server);
1499
+ const added = await session.call(rosterAddMethod, {
1500
+ artifact: { artifactId: input.artifactId },
1501
+ respondents: [...input.respondents],
1502
+ ...(input.scopes !== undefined ? { scopes: input.scopes } : {}),
1503
+ ...(input.ttl !== undefined ? { ttl: input.ttl } : {}),
1504
+ });
1505
+ for (const entry of added.links) protectLink(entry.link.url);
1506
+ return added.links;
1507
+ },
1478
1508
  url: (server, tokenId) => readLinks(server)[tokenId],
1479
1509
  revoke: async (server, tokenId) => {
1480
1510
  const session = await self.session(server);
package/src/server/api.ts CHANGED
@@ -418,7 +418,7 @@ export function createApi(options: ApiOptions): Api {
418
418
  }
419
419
  if (existsSync(target)) await rm(scratch, { force: true });
420
420
  else renameSync(scratch, target);
421
- home.uploaded(sha);
421
+ home.uploaded(sha, size);
422
422
  options.stored?.(who.homeId, size);
423
423
  send(response, 201, { sha256: sha, size });
424
424
  };
@@ -16,7 +16,7 @@ import { AccountId, HomeId, LinkId } from "@mostra/protocol";
16
16
  import type { SignInIdentity } from "@mostra/protocol/operator";
17
17
  import type { Ledger, LedgerDb } from "../ledger/index.ts";
18
18
  import type { Log } from "../log.ts";
19
- import type { RemoteServerConfig } from "./config.ts";
19
+ import { configuredVerifier, type RemoteServerConfig } from "./config.ts";
20
20
  import type { Operator } from "./operator.ts";
21
21
 
22
22
  /** The CLI's client ID: a first-party public client (§18.5). */
@@ -224,9 +224,24 @@ export interface Authorization {
224
224
  * `accounts.resolve` when it has one, else the server's own accounts; `steps` counts the first
225
225
  * sign-in steps already taken.
226
226
  */
227
- resolveAccount(identity: SignInIdentity, steps: number): Promise<ResolvedAccount>;
228
- /** An account's display name, and the provider that verified it (its first identity's). */
229
- accountName(accountId: string): { readonly name?: string; readonly provider?: string };
227
+ resolveAccount(
228
+ identity: SignInIdentity,
229
+ steps: number,
230
+ /**
231
+ * The label of the provider's verifier (`IdentityProvider.verifies`), recorded on the identity
232
+ * as it links or signs in; absent: the provider verified no name (MT-03).
233
+ */
234
+ verifiedBy?: string,
235
+ ): Promise<ResolvedAccount>;
236
+ /**
237
+ * An account's display name, its first identity's provider, and the label of that identity's
238
+ * verifier as it was recorded when the provider last named the person (MT-03).
239
+ */
240
+ accountName(accountId: string): {
241
+ readonly name?: string;
242
+ readonly provider?: string;
243
+ readonly verifiedBy?: string;
244
+ };
230
245
  /** Mints an authorization code (one minute, single use; only its hash is kept). */
231
246
  issueCode(grant: CodeGrant): string;
232
247
  /**
@@ -290,6 +305,29 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
290
305
  JSON.stringify({ client_name: "Mostra CLI" }),
291
306
  iso(now()),
292
307
  );
308
+ // Identities linked before the server recorded who verified each (MT-03) take, once, the
309
+ // verifier the configuration names for their provider now, as their sender lines showed it
310
+ // until then; any other (a provider retired, or one an operator module supplied) none. The
311
+ // configuration may since have given a provider's ID to another kind, so a row keeps none
312
+ // unless its shape is that kind's (its Opus review): never one the development provider made
313
+ // (whose subject is the typed name, lower-cased), and for GitHub only a numeric subject (its
314
+ // user ID). From then on the recorded label is the one shown, whatever the configuration says.
315
+ const at = iso(now());
316
+ for (const provider of config.identityProviders ?? []) {
317
+ const label = configuredVerifier(provider);
318
+ if (label === undefined) continue;
319
+ db.run(
320
+ `UPDATE identity SET verified_by = ?, verified_recorded_at = ?
321
+ WHERE provider = ? AND verified_recorded_at IS NULL
322
+ AND (name IS NULL OR subject != lower(name))
323
+ AND (? != 'github' OR (subject != '' AND subject NOT GLOB '*[^0-9]*'))`,
324
+ label,
325
+ at,
326
+ provider.id,
327
+ provider.kind,
328
+ );
329
+ }
330
+ db.run("UPDATE identity SET verified_recorded_at = ? WHERE verified_recorded_at IS NULL", at);
293
331
  });
294
332
 
295
333
  const deviceRow = (db: LedgerDb, hash: string) =>
@@ -305,6 +343,7 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
305
343
  account: string,
306
344
  name: string | undefined,
307
345
  status: "active" | "suspended",
346
+ verifiedBy: string | undefined,
308
347
  ): void => {
309
348
  db.run(
310
349
  `INSERT INTO account (id, name, status, created_at) VALUES (?, ?, ?, ?)
@@ -315,29 +354,47 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
315
354
  iso(now()),
316
355
  );
317
356
  db.run(
318
- `INSERT INTO identity (provider, subject, account_id, email, name, linked_at) VALUES (?, ?, ?, ?, ?, ?)
357
+ `INSERT INTO identity (provider, subject, account_id, email, name, linked_at, verified_by, verified_recorded_at)
358
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
319
359
  ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id,
320
- email = excluded.email, name = excluded.name`,
360
+ email = excluded.email, name = excluded.name, verified_by = excluded.verified_by,
361
+ verified_recorded_at = excluded.verified_recorded_at`,
321
362
  identity.provider,
322
363
  identity.subject,
323
364
  account,
324
365
  identity.email ?? null,
325
366
  identity.name ?? null,
326
367
  iso(now()),
368
+ verifiedBy ?? null,
369
+ iso(now()),
327
370
  );
328
371
  };
329
372
 
330
- /** The account for a sign-in identity, made on the first sign-in. */
373
+ /**
374
+ * The account for a sign-in identity, made on the first sign-in. The identity records who
375
+ * verified the person's name as it signs in (`verifiedBy`, the provider's verifier label, or none),
376
+ * so a provider renamed or retired later changes no sender line (MT-03).
377
+ */
331
378
  const accountFor = (
332
379
  db: LedgerDb,
333
380
  identity: { provider: string; subject: string; name?: string },
381
+ verifiedBy: string | undefined,
334
382
  ): string => {
335
383
  const found = db.get<{ account_id: string }>(
336
384
  "SELECT account_id FROM identity WHERE provider = ? AND subject = ?",
337
385
  identity.provider,
338
386
  identity.subject,
339
387
  );
340
- if (found) return found.account_id;
388
+ if (found) {
389
+ db.run(
390
+ "UPDATE identity SET verified_by = ?, verified_recorded_at = ? WHERE provider = ? AND subject = ?",
391
+ verifiedBy ?? null,
392
+ iso(now()),
393
+ identity.provider,
394
+ identity.subject,
395
+ );
396
+ return found.account_id;
397
+ }
341
398
  const account = AccountId.create();
342
399
  db.run(
343
400
  "INSERT INTO account (id, name, status, created_at) VALUES (?, ?, 'active', ?)",
@@ -346,12 +403,14 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
346
403
  iso(now()),
347
404
  );
348
405
  db.run(
349
- "INSERT INTO identity (provider, subject, account_id, name, linked_at) VALUES (?, ?, ?, ?, ?)",
406
+ "INSERT INTO identity (provider, subject, account_id, name, linked_at, verified_by, verified_recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
350
407
  identity.provider,
351
408
  identity.subject,
352
409
  account,
353
410
  identity.name ?? null,
354
411
  iso(now()),
412
+ verifiedBy ?? null,
413
+ iso(now()),
355
414
  );
356
415
  return account;
357
416
  };
@@ -866,13 +925,13 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
866
925
  });
867
926
  },
868
927
 
869
- async resolveAccount(identity, steps) {
928
+ async resolveAccount(identity, steps, verifiedBy) {
870
929
  const verdict = options.operator
871
930
  ? await options.operator.resolve(identity, steps)
872
931
  : ({ default: true } as const);
873
932
  if (verdict === "unavailable") return { kind: "unavailable" };
874
933
  if ("default" in verdict) {
875
- const accountId = directory.write((db) => accountFor(db, identity));
934
+ const accountId = directory.write((db) => accountFor(db, identity, verifiedBy));
876
935
  const status = directory.read(
877
936
  (db) =>
878
937
  db.get<{ status: string }>("SELECT status FROM account WHERE id = ?", accountId)
@@ -884,7 +943,7 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
884
943
  if ("step" in verdict) return { kind: "step", url: verdict.step.url };
885
944
  if ("refused" in verdict) return { kind: "refused", message: verdict.refused.message };
886
945
  directory.write((db) =>
887
- operatorAccount(db, identity, verdict.account, verdict.name, verdict.status),
946
+ operatorAccount(db, identity, verdict.account, verdict.name, verdict.status, verifiedBy),
888
947
  );
889
948
  if (verdict.status === "suspended") return { kind: "suspended" };
890
949
  return { kind: "account", accountId: verdict.account, name: verdict.name ?? identity.name };
@@ -892,14 +951,21 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
892
951
 
893
952
  accountName(accountId) {
894
953
  return directory.read((db) => {
895
- const row = db.get<{ name: string | null; provider: string | null }>(
896
- `SELECT a.name, (SELECT i.provider FROM identity i WHERE i.account_id = a.id
897
- ORDER BY i.linked_at LIMIT 1) AS provider FROM account a WHERE a.id = ?`,
954
+ const row = db.get<{
955
+ name: string | null;
956
+ provider: string | null;
957
+ verified_by: string | null;
958
+ }>(
959
+ `SELECT a.name, i.provider, i.verified_by FROM account a
960
+ LEFT JOIN identity i ON i.rowid = (SELECT rowid FROM identity WHERE account_id = a.id
961
+ ORDER BY linked_at, rowid LIMIT 1)
962
+ WHERE a.id = ?`,
898
963
  accountId,
899
964
  );
900
965
  return {
901
966
  ...(row?.name ? { name: row.name } : {}),
902
967
  ...(row?.provider ? { provider: row.provider } : {}),
968
+ ...(row?.verified_by ? { verifiedBy: row.verified_by } : {}),
903
969
  };
904
970
  });
905
971
  },
@@ -1120,7 +1186,8 @@ export function createAuthorization(options: AuthorizationOptions): Authorizatio
1120
1186
  );
1121
1187
  return { ok: true as const };
1122
1188
  }
1123
- const account = accountFor(db, input.identity);
1189
+ // The development sign-in's name is taken on trust: no verifier (D161).
1190
+ const account = accountFor(db, input.identity, undefined);
1124
1191
  db.run(
1125
1192
  "INSERT INTO consent (account_id, client_id, granted_at) VALUES (?, ?, ?) ON CONFLICT (account_id, client_id) DO UPDATE SET revoked_at = NULL",
1126
1193
  account,
@@ -26,6 +26,7 @@ import {
26
26
  import type { Ledger } from "../ledger/index.ts";
27
27
  import type { Log } from "../log.ts";
28
28
  import { type Authorization, canonicalResource, hashSecret } from "./auth.ts";
29
+ import { verifierLabel } from "./config.ts";
29
30
  import { type Clients, type OAuthClient, redirectAllowed } from "./oauth-clients.ts";
30
31
  import type { Operator } from "./operator.ts";
31
32
 
@@ -253,6 +254,19 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
253
254
 
254
255
  // ── providers ───────────────────────────────────────────────────────────────────────────
255
256
 
257
+ /**
258
+ * The label a provider's verified names carry (`IdentityProvider.verifies`, MT-03): text of 1 to
259
+ * 64 characters, else none, since an operator's provider is checked as every operator answer is.
260
+ */
261
+ const verifierOf = (provider: IdentityProvider): string | undefined => {
262
+ const raw: unknown = (provider as { verifies?: { label?: unknown } }).verifies?.label;
263
+ const label = verifierLabel(raw);
264
+ if (label === undefined && provider.verifies !== undefined) {
265
+ log.warn("signin.verifier_refused", { provider: provider.id });
266
+ }
267
+ return label;
268
+ };
269
+
256
270
  /** The providers now: configured ones, then the operator's (asked each time, D167). */
257
271
  const providers = async (): Promise<IdentityProvider[]> => {
258
272
  const supplied = await operator.providers();
@@ -270,6 +284,8 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
270
284
  }
271
285
  interface StepRecord {
272
286
  readonly identity: SignInIdentity;
287
+ /** The verifier label of the provider that named the person (MT-03). */
288
+ readonly verifiedBy?: string;
273
289
  readonly steps: number;
274
290
  readonly flow: string;
275
291
  readonly next: string;
@@ -306,11 +322,12 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
306
322
  const resolved = async (
307
323
  response: ServerResponse,
308
324
  identity: SignInIdentity,
325
+ verifiedBy: string | undefined,
309
326
  steps: number,
310
327
  flow: string,
311
328
  next: string,
312
329
  ): Promise<void> => {
313
- const account = await auth.resolveAccount(identity, steps);
330
+ const account = await auth.resolveAccount(identity, steps, verifiedBy);
314
331
  if (account.kind === "unavailable") {
315
332
  problem(response, 503, "Sign-in is unavailable for a moment; try again shortly.");
316
333
  return;
@@ -329,7 +346,13 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
329
346
  return;
330
347
  }
331
348
  const handle = token();
332
- keep("step", handle, { identity, steps: steps + 1, flow, next } satisfies StepRecord);
349
+ keep("step", handle, {
350
+ identity,
351
+ ...(verifiedBy !== undefined ? { verifiedBy } : {}),
352
+ steps: steps + 1,
353
+ flow,
354
+ next,
355
+ } satisfies StepRecord);
333
356
  const url = new URL(account.url);
334
357
  url.searchParams.set("mostra_return", `${apiOrigin}/signin/return?step=${handle}`);
335
358
  redirect(response, url.href);
@@ -792,7 +815,7 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
792
815
  );
793
816
  return true;
794
817
  }
795
- await resolved(response, identity, 0, pending.flow, pending.next);
818
+ await resolved(response, identity, verifierOf(provider), 0, pending.flow, pending.next);
796
819
  return true;
797
820
  }
798
821
  if (method === "GET" && path === "/signin/return") {
@@ -807,7 +830,7 @@ export function createAuthorize(options: AuthorizeOptions): Authorize {
807
830
  );
808
831
  return true;
809
832
  }
810
- await resolved(response, step.identity, step.steps, step.flow, step.next);
833
+ await resolved(response, step.identity, step.verifiedBy, step.steps, step.flow, step.next);
811
834
  return true;
812
835
  }
813
836
  return false;
@@ -64,8 +64,39 @@ export interface IdentityProviderConfig {
64
64
  readonly issuer?: string | undefined;
65
65
  readonly clientId?: string | undefined;
66
66
  readonly clientSecretFile?: string | undefined;
67
+ /**
68
+ * An `oidc` provider's ID-token claims that go into `SignInIdentity.facts` under their own names,
69
+ * when present (a Google Workspace account's domain, `hd`): at most 8 short names (MT-03).
70
+ */
71
+ readonly claims?: string[] | undefined;
67
72
  }
68
73
 
74
+ /**
75
+ * The label a configured provider's verified names carry on a hosted page's sender line ("verified
76
+ * with GitHub"): its `label`, else GitHub's name or its ID; none for the development provider, which
77
+ * takes the typed name on trust (D161). Recorded on each identity the provider links (MT-03).
78
+ */
79
+ export function configuredVerifier(provider: IdentityProviderConfig): string | undefined {
80
+ if (provider.kind === "development") return undefined;
81
+ return verifierLabel(provider.label ?? (provider.kind === "github" ? "GitHub" : provider.id));
82
+ }
83
+
84
+ /**
85
+ * A verifier's label as the sender line may show it (MT-03, and its Opus review): text of 1 to 64
86
+ * characters with no control, format (bidirectional overrides, zero-width joiners), line or
87
+ * paragraph separator characters, which could make one label read as another's ("verified with
88
+ * GitHub" from reversed text); anything else is no label.
89
+ */
90
+ export function verifierLabel(label: unknown): string | undefined {
91
+ if (typeof label !== "string") return undefined;
92
+ if (label.trim() === "" || label.length > 64) return undefined;
93
+ if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(label)) return undefined;
94
+ return label;
95
+ }
96
+
97
+ /** Claim names that would reach an object's prototype rather than a key of its own. */
98
+ const RESERVED_CLAIMS = new Set(["__proto__", "constructor", "prototype"]);
99
+
69
100
  /** The configuration a remote server runs with (INTERFACES §18.1). */
70
101
  export interface RemoteServerConfig {
71
102
  readonly apiOrigin: string;
@@ -120,6 +151,20 @@ const Config: z.ZodType<RemoteServerConfig> & { readonly shape: Record<string, u
120
151
  issuer: z.string().optional(),
121
152
  clientId: z.string().optional(),
122
153
  clientSecretFile: z.string().optional(),
154
+ claims: z
155
+ .array(
156
+ z
157
+ .string()
158
+ .regex(/^[A-Za-z_][A-Za-z0-9_.:-]{0,63}$/, {
159
+ message: "must be claim names of at most 64 letters, digits and `_.:-`",
160
+ })
161
+ .refine((name) => !RESERVED_CLAIMS.has(name), {
162
+ message: "can't name `__proto__`, `constructor` or `prototype`",
163
+ }),
164
+ )
165
+ .min(1)
166
+ .max(8)
167
+ .optional(),
123
168
  }),
124
169
  )
125
170
  .optional(),
@@ -215,6 +260,14 @@ export function readServerConfig(file: string | undefined, env: Environment): Re
215
260
  "The configuration key `apiOrigin` can't be on a user-content domain: sign-in and the binding live apart from tenant pages (D165 item 7).",
216
261
  );
217
262
  }
263
+ const claimed = (config.identityProviders ?? []).findIndex(
264
+ (provider) => provider.claims !== undefined && provider.kind !== "oidc",
265
+ );
266
+ if (claimed >= 0) {
267
+ throw invalid(
268
+ `The configuration key \`identityProviders.${claimed}.claims\` can't be used: only an \`oidc\` provider passes on its ID token's claims.`,
269
+ );
270
+ }
218
271
  const proxy = validProxies(config.trustedProxies ?? []);
219
272
  if (proxy !== undefined) {
220
273
  throw invalid(
@@ -207,4 +207,77 @@ export const SERVER_MIGRATIONS: readonly Migration[] = [
207
207
  db.exec("ALTER TABLE artifact_route ADD COLUMN removing_json TEXT");
208
208
  },
209
209
  },
210
+ {
211
+ version: 4,
212
+ name: "invitations in the outbound queue",
213
+ up(db) {
214
+ // WP-31 (D168): the operator's `invitations` port is delivered like `events` and `metering`,
215
+ // at least once from the same queue; a row keeps the link's token, never its URL. SQLite
216
+ // can't widen a CHECK in place, so the table is rebuilt with every row it holds.
217
+ db.exec(`
218
+ CREATE TABLE outbound_next (
219
+ id TEXT PRIMARY KEY,
220
+ port TEXT NOT NULL CHECK (port IN ('metering', 'events', 'invitations')),
221
+ payload_json TEXT NOT NULL,
222
+ attempts INTEGER NOT NULL DEFAULT 0,
223
+ next_attempt_at TEXT NOT NULL
224
+ );
225
+ INSERT INTO outbound_next (rowid, id, port, payload_json, attempts, next_attempt_at)
226
+ SELECT rowid, id, port, payload_json, attempts, next_attempt_at FROM outbound;
227
+ DROP TABLE outbound;
228
+ ALTER TABLE outbound_next RENAME TO outbound;
229
+ `);
230
+ },
231
+ },
232
+ {
233
+ version: 5,
234
+ name: "the verifier on each identity",
235
+ up(db) {
236
+ // MT-03 (DATA_MODEL §7.1, additive). Who verified the person's name, as the provider that
237
+ // links or signs in an identity says (`IdentityProvider.verifies`), recorded on the identity:
238
+ // a hosted page's sender line reads it from here, so renaming or retiring a provider later
239
+ // turns no verified name into an unverified one. `verified_recorded_at` is when it was
240
+ // recorded; an identity linked before this has none until the server, at its next start,
241
+ // gives it the verifier its configuration names for its provider then (the server's own
242
+ // accounts' sender lines unchanged by the upgrade).
243
+ db.exec(`
244
+ ALTER TABLE identity ADD COLUMN verified_by TEXT;
245
+ ALTER TABLE identity ADD COLUMN verified_recorded_at TEXT;
246
+ `);
247
+ },
248
+ },
249
+ {
250
+ version: 6,
251
+ name: "what each home holds",
252
+ up(db) {
253
+ // MT-03 (DATA_MODEL §7.1, additive). The bytes of each version file a home holds, as its push
254
+ // gave them (held to the bytes uploaded), and each home's running total, kept by triggers in
255
+ // the transaction of every change to `home_file`, so metering's `bytes.held` reads one row a
256
+ // home and falls when a removal frees files. `held_dirty` marks a home whose total changed
257
+ // since `held_reported` (the level last queued for the operator), so a change is reported
258
+ // after a restart too. A row from before this has no size until the server, at its next
259
+ // start, reads the stored file's (0 for one that is gone, so it is read once).
260
+ db.exec(`
261
+ ALTER TABLE home_file ADD COLUMN size INTEGER CHECK (size IS NULL OR size >= 0);
262
+ ALTER TABLE home ADD COLUMN held_bytes INTEGER NOT NULL DEFAULT 0 CHECK (held_bytes >= 0);
263
+ ALTER TABLE home ADD COLUMN held_reported INTEGER;
264
+ ALTER TABLE home ADD COLUMN held_dirty INTEGER NOT NULL DEFAULT 0 CHECK (held_dirty IN (0, 1));
265
+ CREATE INDEX home_held_dirty ON home (held_dirty) WHERE held_dirty = 1;
266
+ CREATE TRIGGER home_file_held_insert AFTER INSERT ON home_file WHEN NEW.size IS NOT NULL
267
+ BEGIN
268
+ UPDATE home SET held_bytes = held_bytes + NEW.size, held_dirty = 1 WHERE id = NEW.home_id;
269
+ END;
270
+ CREATE TRIGGER home_file_held_delete AFTER DELETE ON home_file WHEN OLD.size IS NOT NULL
271
+ BEGIN
272
+ UPDATE home SET held_bytes = held_bytes - OLD.size, held_dirty = 1 WHERE id = OLD.home_id;
273
+ END;
274
+ CREATE TRIGGER home_file_held_size AFTER UPDATE OF size ON home_file
275
+ WHEN COALESCE(OLD.size, -1) != COALESCE(NEW.size, -1)
276
+ BEGIN
277
+ UPDATE home SET held_bytes = held_bytes - COALESCE(OLD.size, 0) + COALESCE(NEW.size, 0),
278
+ held_dirty = 1 WHERE id = NEW.home_id;
279
+ END;
280
+ `);
281
+ },
282
+ },
210
283
  ];
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * A hosted home's events for its operator (INTERFACES §18.6, D165 item 9): `submission.accepted`
3
- * (with the submission's Results), `version.pushed` and `run.ended`, read from the home's own
3
+ * (with the submission's Results), `version.pushed`, `run.ended` and `roster.completed` (D168), and
4
+ * an invitation for each expected respondent with an email whom the roster added or gave a new
5
+ * personal link (`roster.changed`'s `added` and `relinked`), read from the home's own
4
6
  * event log after `operator_cursor` and handed to the server's durable outbound queue, so each is
5
7
  * delivered at least once with a stable ID (`<home>:<incarnation>:<cursor>`). The cursor moves
6
8
  * only after the queue holds what was read; a crash between them hands the same events again,
@@ -28,6 +30,8 @@ export interface OperatorFeedOptions {
28
30
  readonly operator: Operator;
29
31
  readonly meter: Meter;
30
32
  readonly account: () => string;
33
+ /** Who sends the home's invitations: its owner's name and how it was verified. */
34
+ readonly sender?: () => { readonly name?: string; readonly verifiedBy?: string };
31
35
  readonly routeOf: (
32
36
  artifactId: string,
33
37
  ) => { readonly id: string; readonly label: string } | undefined;
@@ -60,7 +64,7 @@ const RUN_ENDS = new Map([
60
64
  /** Starts the feed of a home. */
61
65
  export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
62
66
  const { ledger, operator, meter, log } = options;
63
- const wanted = operator.has.events || meter.on;
67
+ const wanted = operator.has.events || meter.on || operator.has.invitations;
64
68
  let stopped = false;
65
69
  let scheduled = false;
66
70
 
@@ -113,6 +117,17 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
113
117
  payload: { versionId: payload["versionId"], number: payload["number"] },
114
118
  };
115
119
  }
120
+ if (row.type === "roster.completed") {
121
+ return {
122
+ ...base,
123
+ kind: "roster.completed",
124
+ payload: {
125
+ round: payload["round"],
126
+ respondents: payload["respondents"],
127
+ submissions: payload["submissions"],
128
+ },
129
+ };
130
+ }
116
131
  const status = RUN_ENDS.get(row.type);
117
132
  if (status !== undefined) {
118
133
  return {
@@ -124,6 +139,72 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
124
139
  return undefined;
125
140
  };
126
141
 
142
+ /**
143
+ * The invitations a roster change calls for (D168): one per respondent it added or gave a new
144
+ * link, who has an email and is still expected, keyed by their link's token, so a repeated read
145
+ * enqueues nothing new and a later link gets an invitation of its own.
146
+ */
147
+ const invite = (row: EventRow): void => {
148
+ if (row.artifact_id === null) return;
149
+ const route = options.routeOf(row.artifact_id);
150
+ if (!route) return;
151
+ const payload = JSON.parse(row.payload_json) as {
152
+ added?: readonly { ref?: unknown }[];
153
+ relinked?: readonly unknown[];
154
+ };
155
+ const refs = new Set<string>([
156
+ ...(payload.added ?? []).flatMap((entry) =>
157
+ typeof entry.ref === "string" ? [entry.ref] : [],
158
+ ),
159
+ ...(payload.relinked ?? []).filter((ref): ref is string => typeof ref === "string"),
160
+ ]);
161
+ if (refs.size === 0) return;
162
+ const artifactId = row.artifact_id;
163
+ const found = ledger.read((db) => ({
164
+ title: db.get<{ title: string }>("SELECT title FROM artifact WHERE id = ?", artifactId)
165
+ ?.title,
166
+ entries: [...refs].flatMap((ref) => {
167
+ const entry = db.get<{
168
+ ref: string;
169
+ name: string | null;
170
+ email: string | null;
171
+ token_id: string | null;
172
+ }>(
173
+ "SELECT ref, name, email, token_id FROM roster_entry WHERE artifact_id = ? AND ref = ?",
174
+ artifactId,
175
+ ref,
176
+ );
177
+ return entry && entry.email !== null && entry.token_id !== null ? [entry] : [];
178
+ }),
179
+ }));
180
+ const sender = options.sender?.() ?? {};
181
+ for (const entry of found.entries) {
182
+ operator.enqueue({
183
+ port: "invitations",
184
+ invitation: {
185
+ invitationId: `${options.homeId}:${entry.token_id}`,
186
+ account: options.account(),
187
+ home: options.homeId,
188
+ routeId: route.id,
189
+ label: route.label,
190
+ artifactId,
191
+ title: found.title ?? "",
192
+ respondent: {
193
+ ref: entry.ref,
194
+ ...(entry.name !== null ? { name: entry.name } : {}),
195
+ email: entry.email as string,
196
+ },
197
+ sender: {
198
+ ...(sender.name !== undefined ? { name: sender.name } : {}),
199
+ ...(sender.verifiedBy !== undefined ? { verifiedBy: sender.verifiedBy } : {}),
200
+ },
201
+ tokenId: entry.token_id as string,
202
+ at: row.at,
203
+ },
204
+ });
205
+ }
206
+ };
207
+
127
208
  const scan = (): void => {
128
209
  scheduled = false;
129
210
  if (stopped) return;
@@ -140,13 +221,18 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
140
221
  db.all<EventRow>(
141
222
  `SELECT cursor, artifact_id, type, payload_json, at FROM event WHERE cursor > ?
142
223
  AND type IN ('submission.created', 'version.published', 'action.succeeded',
143
- 'action.failed', 'action.cancelled', 'action.unknown')
224
+ 'action.failed', 'action.cancelled', 'action.unknown',
225
+ 'roster.changed', 'roster.completed')
144
226
  ORDER BY cursor LIMIT ?`,
145
227
  cursor,
146
228
  PAGE,
147
229
  ),
148
230
  );
149
231
  for (const row of rows) {
232
+ if (row.type === "roster.changed") {
233
+ if (operator.has.invitations) invite(row);
234
+ continue;
235
+ }
150
236
  const event = toEvent(row);
151
237
  if (!event) continue;
152
238
  if (event.kind === "submission.accepted") {