@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/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as uninstallService, i as serviceStatus, n as startInstance, o as checkPlatform, r as installService, s as resolveHomePath, t as runtimeVersion } from "./instance-D7_UVdoN.js";
2
+ import { a as uninstallService, i as serviceStatus, n as startInstance, o as checkPlatform, r as installService, s as resolveHomePath, t as runtimeVersion } from "./instance-CzBkUyHu.js";
3
3
  import { mkdirSync, realpathSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { LineSplitter, RpcError, RpcPeer, createDiagnostic, encodeLine } from "@mostra/protocol";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/log.ts","../src/home/record.ts","../src/processes/child.ts","../src/processes/manager.ts","../src/instance/index.ts"],"mappings":";;;;KAmLY,cAAc,SAAS;;;;UCpKlB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;UCfM;;WAEN,aAAa,gBAAgB;;WAE7B,kBAAkB,gBAAgB;;;UAI5B;;EAEf,QAAQ,gBAAgB,SAAS,gBAAgB;;EAEjD,OAAO,gBAAgB,SAAS;;;;;;;wBAQlB,oBACd,UAAS,8BACR;;;;UCIc;;WAEN;;WAEA;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,MAAM;;;;;WAKN;;;;;;WAMA,YAAY;;;;;WAKZ;aACE,aAAa,gBAAgB;aAC7B,kBAAkB,gBAAgB;;;;;;;WAOpC;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;EAET,QACE,gBACA,SAAS,eACT;IAAY;MACX;;WAEM,UAAU;;WAEV,QAAQ,QAAQ;;EAEzB,KAAK,mBAAmB,QAAQ;;;UAIjB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAgBM;;EAEf,MAAM,MAAM,YAAY,QAAQ;;EAEhC;IAAmB;IAAa;IAAc;IAAkB;;;EAEhE,QAAQ,mBAAmB;;;;;UC5BZ;;WAEN;;WAEA;;WAEA,MAAM;;WAEN;aAAmB,OAAO;aAAmB,QAAQ;;;WAErD;;WAEA;;WAEA,UAAU;;WAEV;;WAEA;;;;;WAKA;;;UAIM;;WAEN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,MAAM;;WAEN;;WAEA,WAAW;;WAEX,iBAAiB;;WAEjB,SAAS,QAAQ;;EAE1B,KAAK,gBAAgB,mBAAmB,aAAa,aAAa,QAAQ;;;KAIhE;WACG;WAAwB,UAAU;;WAElC;;WAEA,QAAQ;WACR,QAAQ;;;wBAKP;;;;;;wBA6BM,cAAc,SAAS,uBAAuB,QAAQ"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/log.ts","../src/home/record.ts","../src/processes/child.ts","../src/processes/manager.ts","../src/instance/index.ts"],"mappings":";;;;KAmLY,cAAc,SAAS;;;;UCpKlB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;UCfM;;WAEN,aAAa,gBAAgB;;WAE7B,kBAAkB,gBAAgB;;;UAI5B;;EAEf,QAAQ,gBAAgB,SAAS,gBAAgB;;EAEjD,OAAO,gBAAgB,SAAS;;;;;;;wBAQlB,oBACd,UAAS,8BACR;;;;UCIc;;WAEN;;WAEA;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,MAAM;;;;;WAKN;;;;;;WAMA,YAAY;;;;;WAKZ;aACE,aAAa,gBAAgB;aAC7B,kBAAkB,gBAAgB;;;;;;;WAOpC;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;EAET,QACE,gBACA,SAAS,eACT;IAAY;MACX;;WAEM,UAAU;;WAEV,QAAQ,QAAQ;;EAEzB,KAAK,mBAAmB,QAAQ;;;UAIjB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAgBM;;EAEf,MAAM,MAAM,YAAY,QAAQ;;EAEhC;IAAmB;IAAa;IAAc;IAAkB;;;EAEhE,QAAQ,mBAAmB;;;;;UCzBZ;;WAEN;;WAEA;;WAEA,MAAM;;WAEN;aAAmB,OAAO;aAAmB,QAAQ;;;WAErD;;WAEA;;WAEA,UAAU;;WAEV;;WAEA;;;;;WAKA;;;UAIM;;WAEN;;WAEA;;WAEA,aAAa;;;UAIP;;WAEN,MAAM;;WAEN;;WAEA,WAAW;;WAEX,iBAAiB;;WAEjB,SAAS,QAAQ;;EAE1B,KAAK,gBAAgB,mBAAmB,aAAa,aAAa,QAAQ;;;KAIhE;WACG;WAAwB,UAAU;;WAElC;;WAEA,QAAQ;WACR,QAAQ;;;wBAKP;;;;;;wBAsCM,cAAc,SAAS,uBAAuB,QAAQ"}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as startInstance, t as runtimeVersion } from "./instance-D7_UVdoN.js";
1
+ import { n as startInstance, t as runtimeVersion } from "./instance-CzBkUyHu.js";
2
2
  import { t as connectToSupervisor } from "./child-xrHmytks.js";
3
3
  export { connectToSupervisor, runtimeVersion, startInstance };
@@ -3,7 +3,7 @@ import { builtinModules, createRequire } from "node:module";
3
3
  import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
4
4
  import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
6
+ import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
7
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
8
8
  import { connect, createConnection, createServer, isIP } from "node:net";
9
9
  import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, utimes, writeFile } from "node:fs/promises";
@@ -1620,6 +1620,15 @@ const MIGRATIONS = [
1620
1620
  BEGIN
1621
1621
  SELECT RAISE(ABORT, 'a version row is kept forever, collected or not');
1622
1622
  END;
1623
+ `);
1624
+ }
1625
+ },
1626
+ {
1627
+ version: 10,
1628
+ name: "session viewers",
1629
+ up(db) {
1630
+ db.exec(`
1631
+ ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
1623
1632
  `);
1624
1633
  }
1625
1634
  }
@@ -3977,6 +3986,10 @@ var ProtocolServer = class {
3977
3986
  if (!registrant) return Promise.reject(/* @__PURE__ */ new Error(`No connection registered the ${port} port.`));
3978
3987
  return registrant.peer.request(method, params, options);
3979
3988
  }
3989
+ /** The names of the clients connected now (initialized sessions). */
3990
+ connectedClients() {
3991
+ return new Set([...this.#connections].filter((connection) => connection.session.initialized).map((connection) => connection.session.client?.name ?? ""));
3992
+ }
3980
3993
  /**
3981
3994
  * The initialized connections that registered `port`, oldest first, with their clients' names:
3982
3995
  * the hosts a port call can reach (D105).
@@ -4750,13 +4763,23 @@ function localViewerId(db) {
4750
4763
  * a `name` given again replaces the stored one.
4751
4764
  */
4752
4765
  function viewerForSpec(db, spec) {
4753
- const found = db.get("SELECT * FROM viewer WHERE kind = 'token' AND external_ref = ?", spec.ref);
4766
+ return viewerByRef(db, "token", spec);
4767
+ }
4768
+ /**
4769
+ * The viewer a host's identity port named (D143 item 2): one viewer of kind `host` per `ref`,
4770
+ * kept apart from `view/url`'s viewers, which a host names for links it mints.
4771
+ */
4772
+ function viewerForHost(db, spec) {
4773
+ return viewerByRef(db, "host", spec);
4774
+ }
4775
+ function viewerByRef(db, kind, spec) {
4776
+ const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
4754
4777
  if (found) {
4755
4778
  if (spec.name !== void 0 && spec.name !== found.name) db.run("UPDATE viewer SET name = ? WHERE id = ?", spec.name, found.id);
4756
4779
  return found.id;
4757
4780
  }
4758
4781
  const id = ViewerId.create();
4759
- db.run("INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'token', ?, ?, ?)", id, spec.ref, spec.name ?? null, (/* @__PURE__ */ new Date()).toISOString());
4782
+ db.run("INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)", id, kind, spec.ref, spec.name ?? null, (/* @__PURE__ */ new Date()).toISOString());
4760
4783
  return id;
4761
4784
  }
4762
4785
  /** A viewer by ID; throws for an unknown one, which would be a defect. */
@@ -6331,6 +6354,7 @@ function createInteraction(options) {
6331
6354
  },
6332
6355
  viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
6333
6356
  viewerForSpec,
6357
+ viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
6334
6358
  openView(input) {
6335
6359
  return ledger.write((db) => openView(db, input));
6336
6360
  },
@@ -7475,7 +7499,7 @@ function actionRoutes(options) {
7475
7499
  if (!session || artifactId === void 0) throw new Error("session route without a session");
7476
7500
  return {
7477
7501
  artifactId,
7478
- viewerId: interaction.viewerOf(session.grant.viewerId),
7502
+ viewerId: interaction.viewerOf(session.viewerId),
7479
7503
  tokenId: session.grant.tokenId,
7480
7504
  scopes: session.grant.scopes
7481
7505
  };
@@ -7685,7 +7709,7 @@ function browserRoutes(options) {
7685
7709
  if (!session || artifactId === void 0) throw new Error("session route without a session");
7686
7710
  return {
7687
7711
  artifactId,
7688
- viewerId: interaction.viewerOf(session.grant.viewerId),
7712
+ viewerId: interaction.viewerOf(session.viewerId),
7689
7713
  tokenId: session.grant.tokenId,
7690
7714
  scopes: session.grant.scopes
7691
7715
  };
@@ -8377,7 +8401,7 @@ var Capabilities = class {
8377
8401
  const csrf = csrfOf(cookie);
8378
8402
  const id = hashSecret(cookie);
8379
8403
  const now = this.#iso(this.#now());
8380
- this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?)", id, input.tokenId, input.origin, hashSecret(csrf), input.versionId ?? null, now, now));
8404
+ this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?, ?)", id, input.tokenId, input.origin, hashSecret(csrf), input.versionId ?? null, now, now, input.viewerId ?? null));
8381
8405
  return {
8382
8406
  cookie,
8383
8407
  csrf,
@@ -8410,11 +8434,14 @@ var Capabilities = class {
8410
8434
  const csrf = csrfOf(value);
8411
8435
  if (!safeEqual(hashSecret(csrf), found.session.csrf)) continue;
8412
8436
  this.#touch(found.session.id);
8437
+ const grant = grantOf(found.token);
8438
+ const viewerId = grant.viewerId ?? found.session.viewer_id ?? void 0;
8413
8439
  return {
8414
8440
  id: found.session.id,
8415
8441
  csrf,
8416
8442
  ...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
8417
- grant: grantOf(found.token)
8443
+ grant,
8444
+ ...viewerId !== void 0 ? { viewerId } : {}
8418
8445
  };
8419
8446
  }
8420
8447
  return revoked ? refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link this session came from was revoked or has expired.") : refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The request carries no session for this origin.");
@@ -8506,9 +8533,14 @@ var Capabilities = class {
8506
8533
  const { live: _live, ...rest } = grant;
8507
8534
  return rest;
8508
8535
  }
8509
- /** Spends a launch ticket that started a session. */
8536
+ /**
8537
+ * Spends a launch ticket that started a session: `true` only for the caller that spent it, so
8538
+ * two exchanges that both presented it while a host's identity port was answering get one
8539
+ * session between them (GPT review of WP-12, finding 1).
8540
+ */
8510
8541
  spendLaunch(ticket) {
8511
- if (looksLikeSecret(ticket)) this.#launches.delete(hashSecret(ticket));
8542
+ this.#sweepTickets();
8543
+ return looksLikeSecret(ticket) && this.#launches.delete(hashSecret(ticket));
8512
8544
  }
8513
8545
  /** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
8514
8546
  prune() {
@@ -9124,6 +9156,73 @@ function normalize(policy) {
9124
9156
  };
9125
9157
  }
9126
9158
  //#endregion
9159
+ //#region src/gateway/identity.ts
9160
+ /**
9161
+ * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
9162
+ * nothing. For a link without one, a host that registered the `identity` port names the person
9163
+ * from the request's headers; without such a host, the session acts as the home's local user.
9164
+ */
9165
+ /** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
9166
+ const IDENTITY_TIMEOUT_MS = 5e3;
9167
+ /**
9168
+ * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
9169
+ * other page's of this host) and without Mostra's own `x-mostra-*` headers.
9170
+ */
9171
+ function identityHeaders(headers) {
9172
+ const seen = {};
9173
+ headers.forEach((value, name) => {
9174
+ const key = name.toLowerCase();
9175
+ if (key === "cookie" || key.startsWith("x-mostra-")) return;
9176
+ seen[key] = value;
9177
+ });
9178
+ return seen;
9179
+ }
9180
+ /**
9181
+ * Asks the host that took identity over. Its outage never makes the session someone else: a
9182
+ * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
9183
+ * `unavailable`, and the exchange is refused.
9184
+ */
9185
+ async function resolveIdentity(input) {
9186
+ const registrant = input.registrant();
9187
+ const unavailable = (message) => ({
9188
+ kind: "unavailable",
9189
+ diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
9190
+ });
9191
+ if (registrant) try {
9192
+ const answer = await input.call(registrant.session, {
9193
+ artifactId: input.artifactId,
9194
+ via: input.via,
9195
+ headers: identityHeaders(input.headers)
9196
+ });
9197
+ const parsed = portIdentityResolveMethod.result.safeParse(answer);
9198
+ if (parsed.success) return parsed.data === null ? { kind: "default" } : {
9199
+ kind: "person",
9200
+ viewer: parsed.data
9201
+ };
9202
+ input.log.warn("gateway.identity_invalid", {
9203
+ owner: registrant.owner,
9204
+ artifactId: input.artifactId
9205
+ });
9206
+ return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
9207
+ } catch (error) {
9208
+ input.log.warn("gateway.identity_failed", {
9209
+ owner: registrant.owner,
9210
+ artifactId: input.artifactId,
9211
+ error: error.message
9212
+ });
9213
+ return unavailable(`The host ${registrant.owner} didn't say who this is.`);
9214
+ }
9215
+ const away = input.expected();
9216
+ if (away.length > 0) {
9217
+ input.log.warn("gateway.identity_host_away", {
9218
+ owners: away,
9219
+ artifactId: input.artifactId
9220
+ });
9221
+ return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
9222
+ }
9223
+ return { kind: "default" };
9224
+ }
9225
+ //#endregion
9127
9226
  //#region src/gateway/index.ts
9128
9227
  /**
9129
9228
  * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99): the HTTP side of an instance. It serves
@@ -9370,8 +9469,20 @@ function createGateway(options) {
9370
9469
  ...access(grant)
9371
9470
  };
9372
9471
  };
9472
+ /**
9473
+ * The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
9474
+ * origin's storage and sent with every exchange), each with the order it was made in. An
9475
+ * exchange that waited (the identity port answering) checks here whether another link's
9476
+ * session was made for the same browser meanwhile: its request carried no cookie of that session,
9477
+ * so D98 item 8's check alone would let the later answer silently replace it (Opus review of
9478
+ * WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
9479
+ */
9480
+ const madeSessions = /* @__PURE__ */ new Map();
9481
+ let exchangeOrder = 0;
9482
+ const browserKey = (artifactId, browser) => typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser) ? `${artifactId}\u0000${browser}` : void 0;
9373
9483
  const exchange = async (context) => {
9374
9484
  const artifactId = context.artifactId;
9485
+ const startedAt = exchangeOrder;
9375
9486
  const meta = {
9376
9487
  method: "POST",
9377
9488
  path: new URL(context.request.url).pathname,
@@ -9380,7 +9491,8 @@ function createGateway(options) {
9380
9491
  const body = await readJsonObject(context.request);
9381
9492
  if (isRefusal(body)) return refuse(shellChecks, body, meta);
9382
9493
  const launch = body["token"] === void 0 && body["launch"] !== void 0;
9383
- const grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false) : capabilities.presentToken(body["token"], artifactId);
9494
+ const browser = browserKey(artifactId, body["browser"]);
9495
+ let grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false) : capabilities.presentToken(body["token"], artifactId);
9384
9496
  if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
9385
9497
  const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()), shellOrigin(), artifactId);
9386
9498
  if (!isRefusal(existing)) {
@@ -9403,11 +9515,51 @@ function createGateway(options) {
9403
9515
  }, { status: 409 });
9404
9516
  }
9405
9517
  }
9518
+ let viewerId;
9519
+ if (grant.viewerId === void 0 && options.identity) {
9520
+ const outcome = await options.identity({
9521
+ artifactId,
9522
+ via: "local",
9523
+ headers: context.request.headers
9524
+ });
9525
+ if (outcome.kind === "unavailable") {
9526
+ log.warn("gateway.session_refused", {
9527
+ artifactId,
9528
+ code: outcome.diagnostic.code
9529
+ });
9530
+ return jsonResponse(outcome.diagnostic, { status: 503 });
9531
+ }
9532
+ if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
9533
+ }
9534
+ const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true) : capabilities.presentToken(body["token"], artifactId);
9535
+ if (isRefusal(now)) return refuse(shellChecks, now, meta);
9536
+ grant = now;
9537
+ const made = browser === void 0 ? void 0 : madeSessions.get(browser);
9538
+ if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
9539
+ log.info("gateway.session_conflict", {
9540
+ artifactId,
9541
+ origin: shellOrigin()
9542
+ });
9543
+ return jsonResponse({
9544
+ ...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
9545
+ current: access(made.grant),
9546
+ offered: access(grant)
9547
+ }, { status: 409 });
9548
+ }
9406
9549
  const session = capabilities.createSession({
9407
9550
  tokenId: grant.tokenId,
9408
- origin: shellOrigin()
9551
+ origin: shellOrigin(),
9552
+ viewerId
9409
9553
  });
9410
- if (launch) capabilities.spendLaunch(body["launch"]);
9554
+ if (browser !== void 0) {
9555
+ exchangeOrder += 1;
9556
+ madeSessions.delete(browser);
9557
+ madeSessions.set(browser, {
9558
+ order: exchangeOrder,
9559
+ grant
9560
+ });
9561
+ if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
9562
+ }
9411
9563
  log.info("gateway.session_started", {
9412
9564
  origin: shellOrigin(),
9413
9565
  artifactId,
@@ -9457,10 +9609,11 @@ function createGateway(options) {
9457
9609
  versionId: version.id,
9458
9610
  origin: artifactOrigin,
9459
9611
  shellOrigin: shellOrigin(),
9460
- shellSessionId: session.id
9612
+ shellSessionId: session.id,
9613
+ viewerId: session.viewerId
9461
9614
  });
9462
9615
  const controls = await options.controls(detail);
9463
- const viewerId = interaction.viewerOf(session.grant.viewerId);
9616
+ const viewerId = interaction.viewerOf(session.viewerId);
9464
9617
  return jsonResponse({
9465
9618
  artifactId,
9466
9619
  viewId: interaction.openView({
@@ -9622,12 +9775,13 @@ function createGateway(options) {
9622
9775
  location: "/"
9623
9776
  };
9624
9777
  const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks().cookieName()), origin(), artifactId);
9625
- if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId) capabilities.enterVersion(existing.id, redeemed.versionId);
9778
+ if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) capabilities.enterVersion(existing.id, redeemed.versionId);
9626
9779
  else {
9627
9780
  const session = capabilities.createSession({
9628
9781
  tokenId: redeemed.tokenId,
9629
9782
  origin: origin(),
9630
- versionId: redeemed.versionId
9783
+ versionId: redeemed.versionId,
9784
+ viewerId: redeemed.viewerId
9631
9785
  });
9632
9786
  headers["set-cookie"] = sessionCookie(checks().cookieName(), session.cookie, "/", SESSION_MAX_AGE_S);
9633
9787
  log.info("gateway.session_started", {
@@ -9650,7 +9804,7 @@ function createGateway(options) {
9650
9804
  artifactId,
9651
9805
  shellOrigin: shellOrigin(),
9652
9806
  scopes: session.grant.scopes,
9653
- viewer: interaction.viewer(interaction.viewerOf(session.grant.viewerId)),
9807
+ viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
9654
9808
  ...version ? { version: {
9655
9809
  id: version.id,
9656
9810
  number: version.number
@@ -14649,7 +14803,7 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
14649
14803
  * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
14650
14804
  * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
14651
14805
  * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
14652
- * A host may supply secrets through its `secrets` port instead (Jcode's credential store).
14806
+ * A host may supply secrets through its `secrets` port instead (a host's own credential store).
14653
14807
  *
14654
14808
  * Every value Mostra holds or hands out is registered with the instance's redactor, so it never
14655
14809
  * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is
@@ -15085,6 +15239,14 @@ const CLIENT = {
15085
15239
  name: "mostra-runtime",
15086
15240
  version: ""
15087
15241
  };
15242
+ /** Every port this instance calls when a client registers it (`capabilities.ports`). */
15243
+ const SUPPORTED_PORTS = [
15244
+ "identity",
15245
+ "submissions",
15246
+ "drafts",
15247
+ "trustedControls",
15248
+ "secrets"
15249
+ ];
15088
15250
  /**
15089
15251
  * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
15090
15252
  * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
@@ -15260,6 +15422,7 @@ async function assemble(home, options) {
15260
15422
  });
15261
15423
  return verifier;
15262
15424
  };
15425
+ const expectedOwners = (port) => Object.entries(readHomeSettings(home.path).expectedPorts ?? {}).filter(([, ports]) => ports.includes(port)).map(([owner]) => owner);
15263
15426
  const clockOffset = testClockOffset(environment["MOSTRA_TEST_CLOCK_OFFSET_MS"], log);
15264
15427
  const addressing = createAddressing({
15265
15428
  ledger: home.ledger,
@@ -15452,10 +15615,20 @@ async function assemble(home, options) {
15452
15615
  artifact,
15453
15616
  log,
15454
15617
  home: () => readHomeSettings(home.path).submitChannels,
15455
- expected: () => Object.entries(readHomeSettings(home.path).expectedPorts ?? {}).filter(([, ports]) => ports.includes("trustedControls")).map(([owner]) => owner),
15618
+ expected: () => expectedOwners("trustedControls"),
15456
15619
  registrant: () => server.registrants("trustedControls").at(-1),
15457
15620
  call: (session, params) => server.callSession(session, portTrustedControlsPolicyMethod.method, params, CONTROLS_POLICY_TIMEOUT_MS)
15458
15621
  }),
15622
+ identity: (input) => resolveIdentity({
15623
+ ...input,
15624
+ log,
15625
+ expected: () => {
15626
+ const connected = server.connectedClients();
15627
+ return expectedOwners("identity").filter((owner) => !connected.has(owner));
15628
+ },
15629
+ registrant: () => server.registrants("identity").at(-1),
15630
+ call: (session, params) => server.callSession(session, portIdentityResolveMethod.method, params, IDENTITY_TIMEOUT_MS)
15631
+ }),
15459
15632
  activated: (event) => {
15460
15633
  for (const registrant of server.registrants("trustedControls")) {
15461
15634
  const params = {
@@ -15527,12 +15700,7 @@ async function assemble(home, options) {
15527
15700
  markHostConfigured: (client) => {
15528
15701
  if (markHostConfigured(home.path, client.name)) log.info("home.host_configured", { client: client.name });
15529
15702
  },
15530
- supportedPorts: [
15531
- "submissions",
15532
- "drafts",
15533
- "trustedControls",
15534
- "secrets"
15535
- ],
15703
+ supportedPorts: SUPPORTED_PORTS,
15536
15704
  notifications: [
15537
15705
  EVENTS_NOTIFY,
15538
15706
  ARTIFACT_PROGRESS,
@@ -15749,4 +15917,4 @@ function sourceDirectory(path) {
15749
15917
  //#endregion
15750
15918
  export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
15751
15919
 
15752
- //# sourceMappingURL=instance-D7_UVdoN.js.map
15920
+ //# sourceMappingURL=instance-CzBkUyHu.js.map