@mostra/conformance 0.6.1 → 0.7.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.
@@ -1,10 +1,11 @@
1
- import { a as HARNESS_METHODS, d as StoreResult, f as kitVersion, i as EventsResult, n as CallResult, o as HARNESS_REVISIONS, s as InitializeResult, u as StartResult } from "./protocol-RQ9lbehE.js";
1
+ import { a as HARNESS_METHODS, d as StoreResult, f as kitVersion, i as EventsResult, n as CallResult, o as HARNESS_REVISIONS, s as InitializeResult, u as StartResult } from "./protocol-Bi4gZzsu.js";
2
2
  import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import * as z from "zod";
4
4
  import { spawn, spawnSync } from "node:child_process";
5
5
  import { BROWSER_PROTOCOL_REVISIONS, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, createDiagnostic, deserializeAll, encodeLine, serializeAll } from "@mostra/protocol";
6
6
  import { connectControl, resolveRuntime, windowsHelper } from "@mostra/sdk";
7
7
  import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
8
9
  import { tmpdir } from "node:os";
9
10
  import { request } from "node:http";
10
11
  //#region src/baseline.ts
@@ -390,7 +391,9 @@ async function windowsHelperOrNone() {
390
391
  * a shell session, a frame ticket, the frame's entry) and speaks the browser protocol the way a
391
392
  * page does, with a per-host cookie jar (browsers keep cookies per host, not per port, D98) and the
392
393
  * `Origin`, `Sec-Fetch-*` and CSRF headers a browser sends. It also sends what no browser would,
393
- * for the hygiene scenarios. It never follows redirects.
394
+ * for the hygiene scenarios. It never follows redirects. Where the shell and the artifact are two
395
+ * sites (a host's external bases, a Cloudflare share), it enters the frame as the bootstrap page
396
+ * does and signs the frame's requests as Mostra's service worker does (D70, D158 item 5).
394
397
  */
395
398
  /** The browser-protocol revision the kit speaks: the first, which every gateway serves. */
396
399
  const REVISION = BROWSER_PROTOCOL_REVISIONS[0];
@@ -399,11 +402,14 @@ function send(ask) {
399
402
  const url = new URL(ask.url);
400
403
  return new Promise((resolve, reject) => {
401
404
  const req = request({
402
- host: url.hostname.replace(/^\[|\]$/g, ""),
405
+ host: /(^|\.)localhost$/i.test(url.hostname) ? "127.0.0.1" : url.hostname.replace(/^\[|\]$/g, ""),
403
406
  port: url.port,
404
407
  method: ask.method ?? "GET",
405
408
  path: `${url.pathname}${url.search}`,
406
- headers: ask.headers,
409
+ headers: {
410
+ host: url.host,
411
+ ...ask.headers
412
+ },
407
413
  agent: false
408
414
  }, (res) => {
409
415
  const chunks = [];
@@ -453,6 +459,16 @@ function parseLink(link) {
453
459
  /** A browser-like client with a per-host cookie jar. */
454
460
  var Browser = class {
455
461
  #jar = /* @__PURE__ */ new Map();
462
+ /** Worker-mode frame sessions by origin: the header Mostra's service worker adds (D70). */
463
+ #frames = /* @__PURE__ */ new Map();
464
+ /** Signs every later request to `origin` with a worker-mode frame session, as its worker does. */
465
+ enterFrame(origin, secret) {
466
+ this.#frames.set(origin, secret);
467
+ }
468
+ /** Whether `origin` has a worker-mode frame session in this browser. */
469
+ workerFrame(origin) {
470
+ return this.#frames.has(origin);
471
+ }
456
472
  /** The cookies the jar sends to `url`: every cookie of the host whose path matches. */
457
473
  cookiesFor(url) {
458
474
  const { pathname } = new URL(url);
@@ -464,10 +480,13 @@ var Browser = class {
464
480
  /** Sends a request with the jar's cookies and keeps the ones that come back. */
465
481
  async ask(ask) {
466
482
  const cookie = ask.noCookies ? "" : this.cookiesFor(ask.url);
483
+ const url = new URL(ask.url);
484
+ const frame = url.searchParams.has("ticket") ? void 0 : this.#frames.get(url.origin);
467
485
  const answer = await send({
468
486
  ...ask,
469
487
  headers: {
470
488
  ...cookie ? { cookie } : {},
489
+ ...frame !== void 0 ? { "x-mostra-frame": frame } : {},
471
490
  ...ask.headers
472
491
  }
473
492
  });
@@ -554,6 +573,25 @@ var Viewer = class Viewer {
554
573
  });
555
574
  if (ticketAnswer.status !== 200) throw new OpenError("ticket", ticketAnswer);
556
575
  const ticket = ticketAnswer.json();
576
+ if (ticket.mode === "worker") {
577
+ const page = await browser.ask({
578
+ url: ticket.src.replace(/#.*$/, ""),
579
+ headers: {
580
+ accept: "text/html",
581
+ "sec-fetch-mode": "navigate",
582
+ "sec-fetch-dest": "iframe",
583
+ "sec-fetch-site": "cross-site"
584
+ }
585
+ });
586
+ if (page.status !== 200) throw new OpenError("bootstrap", page);
587
+ const fragment = new URLSearchParams(new URL(ticket.src).hash.slice(1)).get("t") ?? "";
588
+ const entered = await browser.fetchJson(ticket.artifactOrigin, "/_mostra/enter", { body: { ticket: fragment } });
589
+ if (entered.status !== 200) throw new OpenError("enter", entered);
590
+ browser.enterFrame(ticket.artifactOrigin, entered.json().session);
591
+ const session = await browser.fetchJson(ticket.artifactOrigin, "/_mostra/session");
592
+ if (session.status !== 200) throw new OpenError("frame session", session);
593
+ return new Viewer(browser, parsed, ticket, shellCsrf, session.json().csrf);
594
+ }
557
595
  const enter = await browser.ask({
558
596
  url: ticket.src,
559
597
  headers: {
@@ -659,9 +697,14 @@ var Viewer = class Viewer {
659
697
  await new Promise((done) => setTimeout(done, 100));
660
698
  }
661
699
  }
662
- /** The page's long poll: events after `cursor` (D47). */
663
- poll(cursor) {
664
- const query = `view=${this.viewId}&wait=0${cursor !== void 0 ? `&cursor=${cursor}` : ""}`;
700
+ /** The page's long poll: events after `cursor` (D47); in worker mode with its ticket (D70). */
701
+ async poll(cursor) {
702
+ let query = `view=${this.viewId}&wait=0${cursor !== void 0 ? `&cursor=${cursor}` : ""}`;
703
+ if (this.browser.workerFrame(this.ticket.artifactOrigin)) {
704
+ const ticket = await this.page("ticket", { purpose: "stream" });
705
+ if (ticket.status !== 200) return ticket;
706
+ query += `&ticket=${ticket.json().ticket}`;
707
+ }
665
708
  return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/events/poll?${query}`);
666
709
  }
667
710
  };
@@ -676,6 +719,11 @@ async function resultOf(state) {
676
719
  * have, checked through the host's own client and ports (the harness) and a viewer playing the
677
720
  * browser. Each runs against a fresh home in its own directory, with a fresh host shim.
678
721
  */
722
+ /**
723
+ * The local stand-ins for `tailscale` and `cloudflared` the share scenarios start instances with
724
+ * (`MOSTRA_TEST_TUNNELS`, D158): shipped in the kit's package beside `src` and `dist`.
725
+ */
726
+ const TUNNELS = fileURLToPath(new URL("../tunnels/", import.meta.url));
679
727
  /** A property that didn't hold. */
680
728
  var ScenarioFailure = class extends Error {
681
729
  constructor(message) {
@@ -1502,67 +1550,213 @@ const INTERACTION_SCENARIOS = [
1502
1550
  }
1503
1551
  }
1504
1552
  ];
1553
+ //#endregion
1554
+ //#region src/scenarios/ports.ts
1555
+ /**
1556
+ * The host's ports, each with and without registration (HO-01): identity, addressing, trusted
1557
+ * controls, secrets, and what server code raises for the host (D108, D131, D143, D158, AC-05,
1558
+ * H-05, H-14).
1559
+ */
1560
+ /** The person the stand-in for Tailscale Serve names on every tailnet request (D158 item 2). */
1561
+ const TAILNET_PERSON = {
1562
+ ref: "ada@example.com",
1563
+ name: "Ada Lövelace"
1564
+ };
1565
+ /** Starts the host's instance with the stand-ins for `tailscale` and `cloudflared` (D158). */
1566
+ function startWithTunnels(context) {
1567
+ return context.start({ env: {
1568
+ MOSTRA_TEST_TUNNELS: TUNNELS,
1569
+ MOSTRA_FAKE_TAILNET_USER: `${TAILNET_PERSON.ref}|${TAILNET_PERSON.name}`
1570
+ } });
1571
+ }
1572
+ /**
1573
+ * Opens a share of `artifactId` through `via`, answers on it, and returns the submission's viewer
1574
+ * with the identity calls the host saw meanwhile.
1575
+ */
1576
+ async function answeredThrough(context, artifactId, via) {
1577
+ const before = context.host.serves("identity") ? (await context.store()).identity.length : 0;
1578
+ const shared = await context.host.call("share/start", {
1579
+ artifact: { artifactId },
1580
+ via
1581
+ }, 12e4);
1582
+ try {
1583
+ const viewer = await Viewer.open(shared.url);
1584
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1585
+ same((await viewer.answer({ name: via }, channel)).status, 200, `the submit through ${via}`);
1586
+ const read = await context.results(artifactId);
1587
+ const calls = context.host.serves("identity") ? (await context.store()).identity.slice(before) : [];
1588
+ return {
1589
+ shared,
1590
+ viewer: read.submission.viewer,
1591
+ calls
1592
+ };
1593
+ } finally {
1594
+ await context.host.call("share/stop", { shareId: shared.shareId });
1595
+ }
1596
+ }
1597
+ /** D143: the identity port names the person behind a link minted without a viewer. */
1598
+ const identity = {
1599
+ id: "ports.identity",
1600
+ title: "With an identity port, a link minted without a viewer acts as the person the host names from the request's headers (never its cookies); without one, as the home's local user",
1601
+ covers: [
1602
+ "HO-01",
1603
+ "HO-05",
1604
+ "H-05",
1605
+ "H-14"
1606
+ ],
1607
+ async run(context) {
1608
+ await context.start();
1609
+ const receipt = await context.published(FORM, { policy: { policy: "epochs" } });
1610
+ const headers = {
1611
+ "x-forwarded-user": "ada@example.com",
1612
+ cookie: "elsewhere=1",
1613
+ "x-mostra-csrf": "not-for-the-host"
1614
+ };
1615
+ const viewer = await context.viewer(receipt.artifactId, { headers });
1616
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1617
+ same((await viewer.answer({ name: "Ada" }, channel)).status, 200, "the submit");
1618
+ const read = await context.results(receipt.artifactId);
1619
+ if (!context.host.serves("identity")) {
1620
+ same(read.submission.viewer.kind, "local", "the viewer without an identity port");
1621
+ return;
1622
+ }
1623
+ const calls = (await context.store()).identity;
1624
+ const call = calls.at(-1);
1625
+ check(call, "the host's identity port was never asked");
1626
+ check(call.answer !== void 0, "the host's store doesn't report what its identity port answered (harness/store)");
1627
+ same(call.answer === null ? [read.submission.viewer.kind] : [read.submission.viewer.kind, read.submission.viewer.ref], call.answer === null ? ["local"] : ["host", call.answer.ref], "the submission's viewer, by the host's answer");
1628
+ same(call.via, "local", "how the request reached the gateway");
1629
+ check(call.headers.includes("x-forwarded-user"), "the port didn't receive the request's headers");
1630
+ check(!call.headers.some((name) => name === "cookie" || name.startsWith("x-mostra-")), `the port received Mostra's credentials (${call.headers.join(", ")})`);
1631
+ const minted = await context.viewer(receipt.artifactId, {
1632
+ link: { viewer: {
1633
+ ref: "grace@example.com",
1634
+ name: "Grace"
1635
+ } },
1636
+ headers
1637
+ });
1638
+ same((await context.store()).identity.length, calls.length, "identity calls for a link with a viewer");
1639
+ same((await minted.answer({ name: "Grace" }, channel)).status, 200, "the minted link's submit");
1640
+ const graces = await context.results(receipt.artifactId);
1641
+ same([graces.submission.viewer.kind, graces.submission.viewer.ref], ["token", "grace@example.com"], "the viewer a link was minted for");
1642
+ await sharedIdentity(context);
1643
+ if (context.host.supports("faults")) {
1644
+ await context.host.script({
1645
+ port: "identity",
1646
+ answer: "fail"
1647
+ });
1648
+ const refused = await context.viewer(receipt.artifactId, { headers }).then(() => void 0, (error) => error);
1649
+ check(refused instanceof OpenError, "a failing identity port still opened the link");
1650
+ same([refused.status, refused.code], [503, "MOSTRA_HOST_IDENTITY_UNAVAILABLE"], "the refusal");
1651
+ await context.host.script({
1652
+ port: "identity",
1653
+ answer: null
1654
+ });
1655
+ same((await (await context.viewer(receipt.artifactId, { headers })).answer({ name: "local" }, channel)).status, 200, "a submit as the local user");
1656
+ same((await context.results(receipt.artifactId)).submission.viewer.kind, "local", "a null answer's viewer");
1657
+ }
1658
+ }
1659
+ };
1660
+ /**
1661
+ * D143 item 2, D158 item 2: through Tailscale Serve the identity port hears `via: "tailnet"` with
1662
+ * Serve's identity headers, and through a public share `via: "token"`; a host's answer names the
1663
+ * person, and without one the tailnet person, or the link itself, is the viewer, never the home's
1664
+ * local user.
1665
+ */
1666
+ async function sharedIdentity(context) {
1667
+ await context.host.stopInstance();
1668
+ await startWithTunnels(context);
1669
+ const receipt = await context.published(FORM, { policy: { policy: "epochs" } });
1670
+ for (const via of ["tailnet", "cloudflare"]) {
1671
+ const { shared, viewer, calls } = await answeredThrough(context, receipt.artifactId, via);
1672
+ const call = calls.at(-1);
1673
+ const expected = via === "tailnet" ? "tailnet" : "token";
1674
+ if (call !== void 0) {
1675
+ same(call.via, expected, `how a request through ${via} reached the gateway`);
1676
+ if (via === "tailnet") check(call.headers.includes("tailscale-user-login"), "the port didn't receive Tailscale Serve's identity headers");
1677
+ } else check(!context.host.serves("identity"), `the identity port wasn't asked through ${via}`);
1678
+ if (call?.answer) same([viewer.kind, viewer.ref], ["host", call.answer.ref], `the viewer the host named (${via})`);
1679
+ else if (via === "tailnet") same([viewer.kind, viewer.ref], ["tailnet", TAILNET_PERSON.ref], "the tailnet person");
1680
+ else same([viewer.kind, viewer.ref], ["token", `link:${shared.tokenId}`], "the public link's viewer");
1681
+ }
1682
+ }
1505
1683
  /** The port scenarios. */
1506
1684
  const PORT_SCENARIOS = [
1685
+ identity,
1507
1686
  {
1508
- id: "ports.identity",
1509
- title: "With an identity port, a link minted without a viewer acts as the person the host names from the request's headers (never its cookies); without one, as the home's local user",
1687
+ id: "ports.addressing",
1688
+ title: "With an addressing port, the links Mostra mints use the host's external base, which passes the Host and Origin checks and opens a frame on another site in worker mode; a withdrawn base stops working; without the port, links stay on loopback",
1510
1689
  covers: [
1511
1690
  "HO-01",
1512
1691
  "HO-05",
1513
- "H-05",
1692
+ "HO-10",
1693
+ "HY-07",
1514
1694
  "H-14"
1515
1695
  ],
1516
1696
  async run(context) {
1517
1697
  await context.start();
1518
1698
  const receipt = await context.published(FORM, { policy: { policy: "epochs" } });
1519
- const headers = {
1520
- "x-forwarded-user": "ada@example.com",
1521
- cookie: "elsewhere=1",
1522
- "x-mostra-csrf": "not-for-the-host"
1523
- };
1524
- const viewer = await context.viewer(receipt.artifactId, { headers });
1525
- const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1526
- same((await viewer.answer({ name: "Ada" }, channel)).status, 200, "the submit");
1527
- const read = await context.results(receipt.artifactId);
1528
- if (!context.host.serves("identity")) {
1529
- same(read.submission.viewer.kind, "local", "the viewer without an identity port");
1699
+ const loopback = (link) => ["127.0.0.1", "[::1]"].includes(new URL(link).hostname);
1700
+ if (!context.host.serves("addressing")) {
1701
+ check(receipt.url !== void 0 && loopback(receipt.url), "the publish receipt's link");
1702
+ check(loopback(await context.link(receipt.artifactId)), "a minted link without the port");
1530
1703
  return;
1531
1704
  }
1532
- const calls = (await context.store()).identity;
1533
- const call = calls.at(-1);
1534
- check(call, "the host's identity port was never asked");
1535
- check(call.answer !== void 0, "the host's store doesn't report what its identity port answered (harness/store)");
1536
- same(call.answer === null ? [read.submission.viewer.kind] : [read.submission.viewer.kind, read.submission.viewer.ref], call.answer === null ? ["local"] : ["host", call.answer.ref], "the submission's viewer, by the host's answer");
1537
- same(call.via, "local", "how the request reached the gateway");
1538
- check(call.headers.includes("x-forwarded-user"), "the port didn't receive the request's headers");
1539
- check(!call.headers.some((name) => name === "cookie" || name.startsWith("x-mostra-")), `the port received Mostra's credentials (${call.headers.join(", ")})`);
1540
- const minted = await context.viewer(receipt.artifactId, {
1541
- link: { viewer: {
1542
- ref: "grace@example.com",
1543
- name: "Grace"
1544
- } },
1545
- headers
1705
+ if (context.host.supports("faults")) await context.host.script({
1706
+ port: "addressing",
1707
+ answer: {
1708
+ shellHost: "localhost",
1709
+ artifactHost: "127.0.0.1"
1710
+ }
1546
1711
  });
1547
- same((await context.store()).identity.length, calls.length, "identity calls for a link with a viewer");
1548
- same((await minted.answer({ name: "Grace" }, channel)).status, 200, "the minted link's submit");
1549
- const graces = await context.results(receipt.artifactId);
1550
- same([graces.submission.viewer.kind, graces.submission.viewer.ref], ["token", "grace@example.com"], "the viewer a link was minted for");
1551
- if (context.host.supports("faults")) {
1552
- await context.host.script({
1553
- port: "identity",
1554
- answer: "fail"
1555
- });
1556
- const refused = await context.viewer(receipt.artifactId, { headers }).then(() => void 0, (error) => error);
1557
- check(refused instanceof OpenError, "a failing identity port still opened the link");
1558
- same([refused.status, refused.code], [503, "MOSTRA_HOST_IDENTITY_UNAVAILABLE"], "the refusal");
1559
- await context.host.script({
1560
- port: "identity",
1561
- answer: null
1562
- });
1563
- same((await (await context.viewer(receipt.artifactId, { headers })).answer({ name: "local" }, channel)).status, 200, "a submit as the local user");
1564
- same((await context.results(receipt.artifactId)).submission.viewer.kind, "local", "a null answer's viewer");
1712
+ const link = await context.link(receipt.artifactId);
1713
+ const asked = ((await context.store()).addressing ?? []).filter((call) => call.artifactId === receipt.artifactId && call.listener === "shell");
1714
+ const answer = asked.at(-1)?.answer;
1715
+ check(asked.length > 0, "the host's addressing port wasn't asked for the link's base");
1716
+ if (!answer) {
1717
+ check(loopback(link), "a link whose host gave no base");
1718
+ return;
1719
+ }
1720
+ same(new URL(link).origin, answer.origin, "the minted link's base");
1721
+ const local = asked.at(-1)?.local;
1722
+ check(loopback(local), `the loopback origin the host forwards to (${local})`);
1723
+ const viewer = await Viewer.open(link);
1724
+ const frameBase = (await context.store()).addressing?.findLast((call) => call.artifactId === receipt.artifactId && call.listener === "artifact")?.answer;
1725
+ if (frameBase) {
1726
+ same(viewer.ticket.artifactOrigin, frameBase.origin, "the frame's base");
1727
+ const crossSite = new URL(frameBase.origin).hostname !== new URL(answer.origin).hostname;
1728
+ same(viewer.ticket.mode ?? "cookie", frameBase.mode ?? (crossSite ? "worker" : "cookie"), "the frame's session mode");
1565
1729
  }
1730
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1731
+ same((await viewer.answer({ name: "Ada" }, channel)).status, 200, "a submit at the base");
1732
+ same((await viewer.poll()).status, 200, "the page's long poll at the base");
1733
+ const parsed = new URL(link);
1734
+ same((await send({
1735
+ url: `${parsed.origin}/a/${receipt.artifactId}`,
1736
+ headers: {
1737
+ host: `evil.example:${parsed.port}`,
1738
+ accept: "text/html"
1739
+ }
1740
+ })).status, 421, "another Host at the base");
1741
+ same((await new Browser().ask({
1742
+ method: "POST",
1743
+ url: `${parsed.origin}/a/${receipt.artifactId}/_mostra/session`,
1744
+ headers: {
1745
+ origin: local,
1746
+ "content-type": "application/json",
1747
+ "sec-fetch-site": "cross-site"
1748
+ },
1749
+ body: JSON.stringify({ token: new URLSearchParams(parsed.hash.slice(1)).get("t") })
1750
+ })).status, 403, "an exchange from another origin");
1751
+ if (!context.host.supports("faults")) return;
1752
+ await context.host.script({
1753
+ port: "addressing",
1754
+ answer: null
1755
+ });
1756
+ const after = await context.link(receipt.artifactId);
1757
+ check(loopback(after), `a link minted after the base was withdrawn (${after})`);
1758
+ check(await Viewer.open(link).then(() => "opened", (error) => error instanceof OpenError ? error.status : "unreachable") !== "opened", "a link at a withdrawn base still opened");
1759
+ same((await (await Viewer.open(after)).answer({ name: "Grace" }, channel)).status, 200, "a submit on loopback");
1566
1760
  }
1567
1761
  },
1568
1762
  {
@@ -2164,4 +2358,4 @@ async function runConformance(options) {
2164
2358
  //#endregion
2165
2359
  export { FIXTURES as _, ScenarioFailure as a, Browser as c, parseLink as d, resultOf as f, codeOf as g, InstanceError as h, ScenarioContext as i, OpenError as l, HostUnderTest as m, SCENARIOS as n, check as o, send as p, NotApplicable as r, same as s, runConformance as t, Viewer as u, NO_BASELINE as v, readBaseline as y };
2166
2360
 
2167
- //# sourceMappingURL=runner-C8SO70qb.js.map
2361
+ //# sourceMappingURL=runner-DYbtXiL9.js.map