@mostra/runtime 0.1.0 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.3",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.1.0",
39
+ "@mostra/protocol": "0.2.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.1",
42
42
  "better-sqlite3": "13.0.3",
@@ -54,11 +54,11 @@
54
54
  "zod": "4.6.5"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.1.0",
57
+ "@mostra/shell": "0.2.0",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.1.0",
59
+ "@mostra/verify": "0.2.0",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.1.0",
61
+ "@mostra/worker": "0.2.0",
62
62
  "@types/better-sqlite3": "9.6.0",
63
63
  "@types/node": "24.19.1",
64
64
  "@types/semver": "7.8.0",
@@ -127,7 +127,7 @@ export function actionRoutes(options: ActionRoutesOptions): ActionRoutes {
127
127
  if (!session || artifactId === undefined) throw new Error("session route without a session");
128
128
  return {
129
129
  artifactId,
130
- viewerId: interaction.viewerOf(session.grant.viewerId),
130
+ viewerId: interaction.viewerOf(session.viewerId),
131
131
  tokenId: session.grant.tokenId,
132
132
  scopes: session.grant.scopes,
133
133
  };
@@ -199,7 +199,7 @@ export function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {
199
199
  if (!session || artifactId === undefined) throw new Error("session route without a session");
200
200
  return {
201
201
  artifactId,
202
- viewerId: interaction.viewerOf(session.grant.viewerId),
202
+ viewerId: interaction.viewerOf(session.viewerId),
203
203
  // A page names only views its own link opened (Claude review finding 11).
204
204
  tokenId: session.grant.tokenId,
205
205
  scopes: session.grant.scopes,
@@ -162,6 +162,11 @@ export interface ResolvedSession {
162
162
  /** The version a frame session entered (D98 item 5). */
163
163
  readonly versionId?: string;
164
164
  readonly grant: Grant;
165
+ /**
166
+ * The viewer the session acts as: its link's viewer (D104), else the one the host's identity
167
+ * port named when the link was exchanged (D143 item 2); absent: the home's local user.
168
+ */
169
+ readonly viewerId?: string;
165
170
  }
166
171
 
167
172
  /** What a redeemed frame ticket carries. */
@@ -175,6 +180,8 @@ export interface TicketGrant {
175
180
  readonly shellOrigin: string;
176
181
  /** The shell session that asked for it: the ticket works only while that session lives. */
177
182
  readonly shellSessionId: string;
183
+ /** The viewer that shell session acts as, which the frame's session acts as too (D143). */
184
+ readonly viewerId?: string | undefined;
178
185
  }
179
186
 
180
187
  interface TokenRow {
@@ -196,6 +203,7 @@ interface SessionRow {
196
203
  origin: string;
197
204
  csrf: string;
198
205
  version_id: string | null;
206
+ viewer_id: string | null;
199
207
  }
200
208
 
201
209
  const grantOf = (row: TokenRow): Grant => ({
@@ -522,6 +530,8 @@ export class Capabilities {
522
530
  readonly tokenId: string;
523
531
  readonly origin: string;
524
532
  readonly versionId?: string;
533
+ /** The person the host's identity port named, for a link without a viewer (D143 item 2). */
534
+ readonly viewerId?: string | undefined;
525
535
  }): {
526
536
  readonly cookie: string;
527
537
  readonly csrf: string;
@@ -533,7 +543,7 @@ export class Capabilities {
533
543
  const now = this.#iso(this.#now());
534
544
  this.#ledger.write((db) =>
535
545
  db.run(
536
- "INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?)",
546
+ "INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?, ?)",
537
547
  id,
538
548
  input.tokenId,
539
549
  input.origin,
@@ -541,6 +551,7 @@ export class Capabilities {
541
551
  input.versionId ?? null,
542
552
  now,
543
553
  now,
554
+ input.viewerId ?? null,
544
555
  ),
545
556
  );
546
557
  return { cookie, csrf, id };
@@ -574,11 +585,15 @@ export class Capabilities {
574
585
  // A row whose CSRF hash doesn't match was not made by this code: it doesn't count.
575
586
  if (!safeEqual(hashSecret(csrf), found.session.csrf)) continue;
576
587
  this.#touch(found.session.id);
588
+ const grant = grantOf(found.token);
589
+ // A link's own viewer always wins: a token's viewer never changes (D104).
590
+ const viewerId = grant.viewerId ?? found.session.viewer_id ?? undefined;
577
591
  return {
578
592
  id: found.session.id,
579
593
  csrf,
580
594
  ...(found.session.version_id !== null ? { versionId: found.session.version_id } : {}),
581
- grant: grantOf(found.token),
595
+ grant,
596
+ ...(viewerId !== undefined ? { viewerId } : {}),
582
597
  };
583
598
  }
584
599
  return revoked
@@ -724,9 +739,15 @@ export class Capabilities {
724
739
  return rest;
725
740
  }
726
741
 
727
- /** Spends a launch ticket that started a session. */
728
- spendLaunch(ticket: unknown): void {
729
- if (looksLikeSecret(ticket)) this.#launches.delete(hashSecret(ticket));
742
+ /**
743
+ * Spends a launch ticket that started a session: `true` only for the caller that spent it, so
744
+ * two exchanges that both presented it while a host's identity port was answering get one
745
+ * session between them (GPT review of WP-12, finding 1).
746
+ */
747
+ spendLaunch(ticket: unknown): boolean {
748
+ // An expired ticket is swept first, so it can't be spent (Opus review of WP-12, finding 3).
749
+ this.#sweepTickets();
750
+ return looksLikeSecret(ticket) && this.#launches.delete(hashSecret(ticket));
730
751
  }
731
752
 
732
753
  /** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
3
+ * nothing. For a link without one, a host that registered the `identity` port names the person
4
+ * from the request's headers; without such a host, the session acts as the home's local user.
5
+ */
6
+ import {
7
+ createDiagnostic,
8
+ type Diagnostic,
9
+ type IdentityVia,
10
+ portIdentityResolveMethod,
11
+ type ViewerSpec,
12
+ } from "@mostra/protocol";
13
+ import type { Log } from "../log.ts";
14
+
15
+ /** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
16
+ export const IDENTITY_TIMEOUT_MS = 5_000;
17
+
18
+ /** What {@link resolveIdentity} reads. */
19
+ export interface IdentityInput {
20
+ /** The artifact whose link is being exchanged. */
21
+ readonly artifactId: string;
22
+ /** How the request reached the gateway. */
23
+ readonly via: IdentityVia;
24
+ /** The request's headers. */
25
+ readonly headers: Headers;
26
+ readonly log: Log;
27
+ /** Hosts that always provide `identity` (`HomeConfig.ports`), by client name. */
28
+ readonly expected: () => readonly string[];
29
+ /** The newest connection that registered `identity`, if any. */
30
+ readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;
31
+ /** Calls the port on that connection; rejects on a transport failure or the timeout. */
32
+ readonly call: (session: number, params: unknown) => Promise<unknown>;
33
+ }
34
+
35
+ /** The person a host named, the standalone default, or why nobody can be named. */
36
+ export type IdentityOutcome =
37
+ | { readonly kind: "person"; readonly viewer: ViewerSpec }
38
+ | { readonly kind: "default" }
39
+ | { readonly kind: "unavailable"; readonly diagnostic: Diagnostic };
40
+
41
+ /**
42
+ * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
43
+ * other page's of this host) and without Mostra's own `x-mostra-*` headers.
44
+ */
45
+ export function identityHeaders(headers: Headers): Record<string, string> {
46
+ const seen: Record<string, string> = {};
47
+ headers.forEach((value, name) => {
48
+ const key = name.toLowerCase();
49
+ if (key === "cookie" || key.startsWith("x-mostra-")) return;
50
+ seen[key] = value;
51
+ });
52
+ return seen;
53
+ }
54
+
55
+ /**
56
+ * Asks the host that took identity over. Its outage never makes the session someone else: a
57
+ * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
58
+ * `unavailable`, and the exchange is refused.
59
+ */
60
+ export async function resolveIdentity(input: IdentityInput): Promise<IdentityOutcome> {
61
+ const registrant = input.registrant();
62
+ const unavailable = (message: string): IdentityOutcome => ({
63
+ kind: "unavailable",
64
+ diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message }),
65
+ });
66
+ if (registrant) {
67
+ try {
68
+ const answer = await input.call(registrant.session, {
69
+ artifactId: input.artifactId,
70
+ via: input.via,
71
+ headers: identityHeaders(input.headers),
72
+ });
73
+ const parsed = portIdentityResolveMethod.result.safeParse(answer);
74
+ if (parsed.success) {
75
+ return parsed.data === null ? { kind: "default" } : { kind: "person", viewer: parsed.data };
76
+ }
77
+ input.log.warn("gateway.identity_invalid", {
78
+ owner: registrant.owner,
79
+ artifactId: input.artifactId,
80
+ });
81
+ return unavailable(
82
+ `The host ${registrant.owner} answered who this is in a form Mostra refuses.`,
83
+ );
84
+ } catch (error) {
85
+ input.log.warn("gateway.identity_failed", {
86
+ owner: registrant.owner,
87
+ artifactId: input.artifactId,
88
+ error: (error as Error).message,
89
+ });
90
+ return unavailable(`The host ${registrant.owner} didn't say who this is.`);
91
+ }
92
+ }
93
+ const away = input.expected();
94
+ if (away.length > 0) {
95
+ input.log.warn("gateway.identity_host_away", { owners: away, artifactId: input.artifactId });
96
+ return unavailable(
97
+ `The host that identifies this home's viewers (${away.join(", ")}) isn't running.`,
98
+ );
99
+ }
100
+ return { kind: "default" };
101
+ }
@@ -30,6 +30,7 @@ import {
30
30
  type Diagnostic,
31
31
  durationMs,
32
32
  type FrameTicket,
33
+ type IdentityVia,
33
34
  type Refusal,
34
35
  RpcError,
35
36
  refusal,
@@ -76,6 +77,7 @@ import {
76
77
  refusalResponse,
77
78
  sessionCookie,
78
79
  } from "./http.ts";
80
+ import type { IdentityOutcome } from "./identity.ts";
79
81
  import { versionIntegrity } from "./integrity.ts";
80
82
  import { createListener, type Listener } from "./listener.ts";
81
83
  import { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from "./routes.ts";
@@ -84,6 +86,7 @@ import { fileResponse, findFile } from "./serve.ts";
84
86
  export { Capabilities, capabilityKey } from "./capabilities.ts";
85
87
  export { CONTROLS_POLICY_TIMEOUT_MS, controlsPolicy } from "./controls.ts";
86
88
  export type { DevUpstream } from "./dev.ts";
89
+ export { IDENTITY_TIMEOUT_MS, resolveIdentity } from "./identity.ts";
87
90
 
88
91
  /** What the gateway reads about artifacts and versions. */
89
92
  export interface GatewayArtifacts {
@@ -113,6 +116,15 @@ export interface GatewayOptions {
113
116
  readonly controls: (artifact: ArtifactDetail) => Promise<ControlsPolicy>;
114
117
  /** Tells hosts with a `trustedControls` port that a trusted control was used (D108). */
115
118
  readonly activated: BrowserRoutesOptions["activated"];
119
+ /**
120
+ * Who a browser is that exchanges a link minted without a viewer (D143 item 2): the person a
121
+ * host's identity port names, the standalone default, or a refusal. Absent: the default.
122
+ */
123
+ readonly identity?: (input: {
124
+ readonly artifactId: string;
125
+ readonly via: IdentityVia;
126
+ readonly headers: Headers;
127
+ }) => Promise<IdentityOutcome>;
116
128
  /** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */
117
129
  readonly revisions?: readonly string[];
118
130
  /**
@@ -434,15 +446,32 @@ export function createGateway(options: GatewayOptions): Gateway {
434
446
  return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };
435
447
  };
436
448
 
449
+ /**
450
+ * The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
451
+ * origin's storage and sent with every exchange), each with the order it was made in. An
452
+ * exchange that waited (the identity port answering) checks here whether another link's
453
+ * session was made for the same browser meanwhile: its request carried no cookie of that session,
454
+ * so D98 item 8's check alone would let the later answer silently replace it (Opus review of
455
+ * WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
456
+ */
457
+ const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();
458
+ let exchangeOrder = 0;
459
+ const browserKey = (artifactId: string, browser: unknown): string | undefined =>
460
+ typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)
461
+ ? `${artifactId}\u0000${browser}`
462
+ : undefined;
463
+
437
464
  const exchange = async (context: RouteContext): Promise<Response> => {
438
465
  const artifactId = context.artifactId as string;
466
+ const startedAt = exchangeOrder;
439
467
  const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
440
468
  const body = await readJsonObject(context.request);
441
469
  if (isRefusal(body)) return refuse(shellChecks, body, meta);
442
470
  // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
443
471
  // spent only once it started (or reused) a session.
444
472
  const launch = body["token"] === undefined && body["launch"] !== undefined;
445
- const grant = launch
473
+ const browser = browserKey(artifactId, body["browser"]);
474
+ let grant = launch
446
475
  ? capabilities.presentLaunch(body["launch"], artifactId, false)
447
476
  : capabilities.presentToken(body["token"], artifactId);
448
477
  if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
@@ -473,8 +502,61 @@ export function createGateway(options: GatewayOptions): Gateway {
473
502
  );
474
503
  }
475
504
  }
476
- const session = capabilities.createSession({ tokenId: grant.tokenId, origin: shellOrigin() });
477
- if (launch) capabilities.spendLaunch(body["launch"]);
505
+ // A link without a viewer acts for whoever the host's identity port names (D143 item 2);
506
+ // a host that took identity over and can't answer refuses the link, never a guess.
507
+ let viewerId: string | undefined;
508
+ if (grant.viewerId === undefined && options.identity) {
509
+ const outcome = await options.identity({
510
+ artifactId,
511
+ via: "local",
512
+ headers: context.request.headers,
513
+ });
514
+ if (outcome.kind === "unavailable") {
515
+ log.warn("gateway.session_refused", { artifactId, code: outcome.diagnostic.code });
516
+ return jsonResponse(outcome.diagnostic, { status: 503 });
517
+ }
518
+ if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
519
+ }
520
+ // Everything is judged again after the await, in one synchronous step with the session's
521
+ // creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,
522
+ // finding 3), and a launch ticket is spent here, so it opens one session however many
523
+ // exchanges presented it while the identity port answered (GPT review finding 1).
524
+ const now = launch
525
+ ? capabilities.presentLaunch(body["launch"], artifactId, true)
526
+ : capabilities.presentToken(body["token"], artifactId);
527
+ if (isRefusal(now)) return refuse(shellChecks, now, meta);
528
+ grant = now;
529
+ const made = browser === undefined ? undefined : madeSessions.get(browser);
530
+ if (
531
+ made !== undefined &&
532
+ made.order > startedAt &&
533
+ made.grant.tokenId !== grant.tokenId &&
534
+ body["replace"] !== true
535
+ ) {
536
+ log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
537
+ return jsonResponse(
538
+ {
539
+ ...refusal(
540
+ "MOSTRA_HYGIENE_SESSION_CONFLICT",
541
+ "This browser already has this artifact open from another link.",
542
+ ).diagnostic,
543
+ current: access(made.grant),
544
+ offered: access(grant),
545
+ },
546
+ { status: 409 },
547
+ );
548
+ }
549
+ const session = capabilities.createSession({
550
+ tokenId: grant.tokenId,
551
+ origin: shellOrigin(),
552
+ viewerId,
553
+ });
554
+ if (browser !== undefined) {
555
+ exchangeOrder += 1;
556
+ madeSessions.delete(browser);
557
+ madeSessions.set(browser, { order: exchangeOrder, grant });
558
+ if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value as string);
559
+ }
478
560
  log.info("gateway.session_started", {
479
561
  origin: shellOrigin(),
480
562
  artifactId,
@@ -566,11 +648,12 @@ export function createGateway(options: GatewayOptions): Gateway {
566
648
  origin: artifactOrigin,
567
649
  shellOrigin: shellOrigin(),
568
650
  shellSessionId: session.id,
651
+ viewerId: session.viewerId,
569
652
  });
570
653
  // One frame load is one view, of exactly this version, by this link's viewer (D104), with
571
654
  // the channels and controls in force for it (D108).
572
655
  const controls = await options.controls(detail);
573
- const viewerId = interaction.viewerOf(session.grant.viewerId);
656
+ const viewerId = interaction.viewerOf(session.viewerId);
574
657
  const viewId = interaction.openView({
575
658
  artifactId,
576
659
  versionId: version.id,
@@ -732,13 +815,20 @@ export function createGateway(options: GatewayOptions): Gateway {
732
815
  origin(),
733
816
  artifactId,
734
817
  );
735
- if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId) {
818
+ // The frame acts as its shell session's viewer (D143 item 2): a session of the same link
819
+ // for someone else (the identity port named another person) is never reused.
820
+ if (
821
+ !isRefusal(existing) &&
822
+ existing.grant.tokenId === redeemed.tokenId &&
823
+ existing.viewerId === redeemed.viewerId
824
+ ) {
736
825
  capabilities.enterVersion(existing.id, redeemed.versionId);
737
826
  } else {
738
827
  const session = capabilities.createSession({
739
828
  tokenId: redeemed.tokenId,
740
829
  origin: origin(),
741
830
  versionId: redeemed.versionId,
831
+ viewerId: redeemed.viewerId,
742
832
  });
743
833
  headers["set-cookie"] = sessionCookie(
744
834
  checks().cookieName(),
@@ -767,7 +857,7 @@ export function createGateway(options: GatewayOptions): Gateway {
767
857
  scopes: session.grant.scopes,
768
858
  // The viewer the page acts as, so edits made before its first snapshot are journaled
769
859
  // under it (WP-07; Claude review finding 4).
770
- viewer: interaction.viewer(interaction.viewerOf(session.grant.viewerId)),
860
+ viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
771
861
  ...(version ? { version: { id: version.id, number: version.number } } : {}),
772
862
  });
773
863
  };
@@ -24,6 +24,7 @@ import {
24
24
  type JsonRpcParams,
25
25
  type MostraInitializeResult,
26
26
  type PortTrustedControlsActivatedParams,
27
+ portIdentityResolveMethod,
27
28
  portSecretsGetMethod,
28
29
  portTrustedControlsActivatedMethod,
29
30
  portTrustedControlsPolicyMethod,
@@ -56,7 +57,9 @@ import {
56
57
  controlsPolicy,
57
58
  createGateway,
58
59
  type Gateway,
60
+ IDENTITY_TIMEOUT_MS,
59
61
  locateShell,
62
+ resolveIdentity,
60
63
  } from "../gateway/index.ts";
61
64
  import { createGc, gcMethods } from "../gc/index.ts";
62
65
  import {
@@ -205,6 +208,15 @@ export function runtimeVersion(): string {
205
208
 
206
209
  const CLIENT: ClientInfo = { name: "mostra-runtime", version: "" };
207
210
 
211
+ /** Every port this instance calls when a client registers it (`capabilities.ports`). */
212
+ export const SUPPORTED_PORTS: readonly string[] = [
213
+ "identity",
214
+ "submissions",
215
+ "drafts",
216
+ "trustedControls",
217
+ "secrets",
218
+ ];
219
+
208
220
  /**
209
221
  * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
210
222
  * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
@@ -383,6 +395,11 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
383
395
  });
384
396
  return verifier;
385
397
  };
398
+ // The hosts that always provide a port (`HomeConfig.ports`, D105), by client name.
399
+ const expectedOwners = (port: string): string[] =>
400
+ Object.entries(readHomeSettings(home.path).expectedPorts ?? {})
401
+ .filter(([, ports]) => ports.includes(port))
402
+ .map(([owner]) => owner);
386
403
  // The gateway (WP-05): leased ports, capability links and sessions, static versions.
387
404
  const clockOffset = testClockOffset(environment["MOSTRA_TEST_CLOCK_OFFSET_MS"], log);
388
405
  const addressing = createAddressing({
@@ -608,10 +625,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
608
625
  artifact,
609
626
  log,
610
627
  home: () => readHomeSettings(home.path).submitChannels,
611
- expected: () =>
612
- Object.entries(readHomeSettings(home.path).expectedPorts ?? {})
613
- .filter(([, ports]) => ports.includes("trustedControls"))
614
- .map(([owner]) => owner),
628
+ expected: () => expectedOwners("trustedControls"),
615
629
  registrant: () => server.registrants("trustedControls").at(-1),
616
630
  call: (session, params) =>
617
631
  server.callSession(
@@ -621,6 +635,27 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
621
635
  CONTROLS_POLICY_TIMEOUT_MS,
622
636
  ),
623
637
  }),
638
+ // Who a browser is, for links without a viewer (D143 item 2).
639
+ identity: (input) =>
640
+ resolveIdentity({
641
+ ...input,
642
+ log,
643
+ // A host that is connected but serves no identity port (it stopped serving one, and its
644
+ // record says it still does) isn't away: the home's default holds (Opus review of
645
+ // WP-12, finding 7).
646
+ expected: () => {
647
+ const connected = server.connectedClients();
648
+ return expectedOwners("identity").filter((owner) => !connected.has(owner));
649
+ },
650
+ registrant: () => server.registrants("identity").at(-1),
651
+ call: (session, params) =>
652
+ server.callSession(
653
+ session,
654
+ portIdentityResolveMethod.method,
655
+ params as JsonRpcParams,
656
+ IDENTITY_TIMEOUT_MS,
657
+ ),
658
+ }),
624
659
  activated: (event) => {
625
660
  // Best effort and never retried, like draft mirrors (D105, D108): the change is durable.
626
661
  for (const registrant of server.registrants("trustedControls")) {
@@ -713,7 +748,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
713
748
  if (markHostConfigured(home.path, client.name))
714
749
  log.info("home.host_configured", { client: client.name });
715
750
  },
716
- supportedPorts: ["submissions", "drafts", "trustedControls", "secrets"],
751
+ // The ports this instance calls (D143 item 1); `addressing` arrives with WP-13, `reviews` and
752
+ // `capture` with WP-20, `pty` with WP-23.
753
+ supportedPorts: SUPPORTED_PORTS,
717
754
  notifications: [EVENTS_NOTIFY, ARTIFACT_PROGRESS, DEV_NOTIFY],
718
755
  onInitialized: (session) => interaction.connected(session),
719
756
  onClosed: (session) => interaction.disconnected(session),
@@ -90,6 +90,7 @@ import {
90
90
  openView,
91
91
  viewControls,
92
92
  viewer,
93
+ viewerForHost,
93
94
  viewerForSpec,
94
95
  viewFor,
95
96
  } from "./viewers.ts";
@@ -154,6 +155,8 @@ export interface Interaction {
154
155
  viewer(viewerId: string): Viewer;
155
156
  /** The viewer for `view/url`'s `viewer`, inside the caller's transaction. */
156
157
  viewerForSpec(db: LedgerDb, spec: ViewerSpec): string;
158
+ /** The viewer a host's identity port named (D143 item 2), in a transaction of its own. */
159
+ viewerForHost(spec: ViewerSpec): string;
157
160
  /** Records a frame load of a version (D104), with the controls in force (D108); returns its ID. */
158
161
  openView(input: {
159
162
  readonly artifactId: string;
@@ -500,6 +503,7 @@ export function createInteraction(options: InteractionOptions): Interaction {
500
503
  },
501
504
  viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
502
505
  viewerForSpec,
506
+ viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
503
507
  openView(input) {
504
508
  return ledger.write((db) => openView(db, input));
505
509
  },
@@ -80,8 +80,21 @@ export function localViewerId(db: LedgerDb): string {
80
80
  * a `name` given again replaces the stored one.
81
81
  */
82
82
  export function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {
83
+ return viewerByRef(db, "token", spec);
84
+ }
85
+
86
+ /**
87
+ * The viewer a host's identity port named (D143 item 2): one viewer of kind `host` per `ref`,
88
+ * kept apart from `view/url`'s viewers, which a host names for links it mints.
89
+ */
90
+ export function viewerForHost(db: LedgerDb, spec: ViewerSpec): string {
91
+ return viewerByRef(db, "host", spec);
92
+ }
93
+
94
+ function viewerByRef(db: LedgerDb, kind: "token" | "host", spec: ViewerSpec): string {
83
95
  const found = db.get<ViewerRow>(
84
- "SELECT * FROM viewer WHERE kind = 'token' AND external_ref = ?",
96
+ "SELECT * FROM viewer WHERE kind = ? AND external_ref = ?",
97
+ kind,
85
98
  spec.ref,
86
99
  );
87
100
  if (found) {
@@ -92,8 +105,9 @@ export function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {
92
105
  }
93
106
  const id = ViewerId.create();
94
107
  db.run(
95
- "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'token', ?, ?, ?)",
108
+ "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)",
96
109
  id,
110
+ kind,
97
111
  spec.ref,
98
112
  spec.name ?? null,
99
113
  new Date().toISOString(),
@@ -580,4 +580,17 @@ export const MIGRATIONS: readonly Migration[] = [
580
580
  `);
581
581
  },
582
582
  },
583
+ {
584
+ version: 10,
585
+ name: "session viewers",
586
+ up(db) {
587
+ // D143 item 2: a link minted without a viewer acts as the person a host's identity port
588
+ // names, decided once when the browser exchanges the link. The session keeps that viewer,
589
+ // and a frame session made from its tickets keeps the same one. NULL: the link's own viewer,
590
+ // or the home's local user.
591
+ db.exec(`
592
+ ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
593
+ `);
594
+ },
595
+ },
583
596
  ];
@@ -284,6 +284,15 @@ export class ProtocolServer {
284
284
  return registrant.peer.request(method, params, options);
285
285
  }
286
286
 
287
+ /** The names of the clients connected now (initialized sessions). */
288
+ connectedClients(): ReadonlySet<string> {
289
+ return new Set(
290
+ [...this.#connections]
291
+ .filter((connection) => connection.session.initialized)
292
+ .map((connection) => connection.session.client?.name ?? ""),
293
+ );
294
+ }
295
+
287
296
  /**
288
297
  * The initialized connections that registered `port`, oldest first, with their clients' names:
289
298
  * the hosts a port call can reach (D105).
@@ -2,7 +2,7 @@
2
2
  * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
3
3
  * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
4
4
  * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
5
- * A host may supply secrets through its `secrets` port instead (Jcode's credential store).
5
+ * A host may supply secrets through its `secrets` port instead (a host's own credential store).
6
6
  *
7
7
  * Every value Mostra holds or hands out is registered with the instance's redactor, so it never
8
8
  * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is