@mostra/conformance 0.0.0-stage → 0.3.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.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * The host's ports, each with and without registration (HO-01): identity, trusted controls,
3
+ * secrets, and what server code raises for the host (D108, D131, D143, AC-05, H-05, H-14).
4
+ */
5
+ import { ACTIONS, FORM } from "../fixtures.ts";
6
+ import { check, type Scenario, same } from "../scenario.ts";
7
+ import { OpenError, resultOf } from "../viewer.ts";
8
+
9
+ /** D143: the identity port names the person behind a link minted without a viewer. */
10
+ export const identity: Scenario = {
11
+ id: "ports.identity",
12
+ title:
13
+ "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",
14
+ covers: ["HO-01", "HO-05", "H-05", "H-14"],
15
+ async run(context) {
16
+ await context.start();
17
+ const receipt = await context.published(FORM, { policy: { policy: "epochs" } });
18
+ // The exchange carries a cookie and a Mostra header, so the filter that keeps them from the
19
+ // host is really tested (Opus review of WP-12, finding 9).
20
+ const headers = {
21
+ "x-forwarded-user": "ada@example.com",
22
+ cookie: "elsewhere=1",
23
+ "x-mostra-csrf": "not-for-the-host",
24
+ };
25
+ const viewer = await context.viewer(receipt.artifactId, { headers });
26
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
27
+ same((await viewer.answer({ name: "Ada" }, channel)).status, 200, "the submit");
28
+ const read = await context.results(receipt.artifactId);
29
+ if (!context.host.serves("identity")) {
30
+ same(read.submission.viewer.kind, "local", "the viewer without an identity port");
31
+ return;
32
+ }
33
+ const calls = (await context.store()).identity;
34
+ const call = calls.at(-1);
35
+ check(call, "the host's identity port was never asked");
36
+ // The session acts as whoever the host named, in its own terms (D143 item 2): the kit judges
37
+ // the session by the host's answer, not by any one way of naming people.
38
+ check(
39
+ call.answer !== undefined,
40
+ "the host's store doesn't report what its identity port answered (harness/store)",
41
+ );
42
+ same(
43
+ call.answer === null
44
+ ? [read.submission.viewer.kind]
45
+ : [read.submission.viewer.kind, read.submission.viewer.ref],
46
+ call.answer === null ? ["local"] : ["host", call.answer.ref],
47
+ "the submission's viewer, by the host's answer",
48
+ );
49
+ same(call.via, "local", "how the request reached the gateway");
50
+ check(
51
+ call.headers.includes("x-forwarded-user"),
52
+ "the port didn't receive the request's headers",
53
+ );
54
+ check(
55
+ !call.headers.some((name) => name === "cookie" || name.startsWith("x-mostra-")),
56
+ `the port received Mostra's credentials (${call.headers.join(", ")})`,
57
+ );
58
+ // A link minted for a person keeps that person; the port isn't asked (D104).
59
+ const minted = await context.viewer(receipt.artifactId, {
60
+ link: { viewer: { ref: "grace@example.com", name: "Grace" } },
61
+ headers,
62
+ });
63
+ same(
64
+ (await context.store()).identity.length,
65
+ calls.length,
66
+ "identity calls for a link with a viewer",
67
+ );
68
+ same((await minted.answer({ name: "Grace" }, channel)).status, 200, "the minted link's submit");
69
+ const graces = await context.results(receipt.artifactId);
70
+ same(
71
+ [graces.submission.viewer.kind, graces.submission.viewer.ref],
72
+ ["token", "grace@example.com"],
73
+ "the viewer a link was minted for",
74
+ );
75
+ if (context.host.supports("faults")) {
76
+ // A host that can't answer refuses the link rather than guess (D143).
77
+ await context.host.script({ port: "identity", answer: "fail" });
78
+ const refused = await context.viewer(receipt.artifactId, { headers }).then(
79
+ () => undefined,
80
+ (error: unknown) => error,
81
+ );
82
+ check(refused instanceof OpenError, "a failing identity port still opened the link");
83
+ same(
84
+ [refused.status, refused.code],
85
+ [503, "MOSTRA_HOST_IDENTITY_UNAVAILABLE"],
86
+ "the refusal",
87
+ );
88
+ await context.host.script({ port: "identity", answer: null });
89
+ const local = await context.viewer(receipt.artifactId, { headers });
90
+ same(
91
+ (await local.answer({ name: "local" }, channel)).status,
92
+ 200,
93
+ "a submit as the local user",
94
+ );
95
+ same(
96
+ (await context.results(receipt.artifactId)).submission.viewer.kind,
97
+ "local",
98
+ "a null answer's viewer",
99
+ );
100
+ }
101
+ },
102
+ };
103
+
104
+ /** D108, H-05, SH-02: the host decides the channels; the artifact can't submit where it may not. */
105
+ export const trustedControls: Scenario = {
106
+ id: "ports.trusted-controls",
107
+ title:
108
+ "The host's trustedControls policy decides each view's channels: the artifact channel is refused with MOSTRA_SUBMIT_CHANNEL_DENIED, the shell's trusted Submit records the shell channel, and the host hears it was used",
109
+ covers: ["HO-01", "HO-05", "SH-02", "H-05"],
110
+ async run(context) {
111
+ await context.start();
112
+ if (!context.host.serves("trustedControls")) {
113
+ const receipt = await context.published(FORM);
114
+ const viewer = await context.viewer(receipt.artifactId);
115
+ same(
116
+ [...viewer.ticket.submitChannels].sort(),
117
+ ["artifact", "shell"],
118
+ "the standalone channels (D40)",
119
+ );
120
+ same(
121
+ (await viewer.answer({ name: "Ada" }, "artifact")).status,
122
+ 200,
123
+ "an artifact-channel submit",
124
+ );
125
+ same(
126
+ (await context.results(receipt.artifactId)).submission.channel,
127
+ "artifact",
128
+ "the recorded channel",
129
+ );
130
+ return;
131
+ }
132
+ // A host that can script its policy is asked for shell-only, the case hosts that need
133
+ // provenance use (H-05); any other host is judged by the policy it answered itself.
134
+ const scripted = context.host.supports("faults")
135
+ ? { submitChannels: ["shell"], controls: ["submit"] }
136
+ : undefined;
137
+ if (scripted) await context.host.script({ port: "trustedControls", answer: scripted });
138
+ const receipt = await context.published(FORM);
139
+ const viewer = await context.viewer(receipt.artifactId);
140
+ const asked = (await context.store()).policies.find(
141
+ (entry) => entry.artifactId === receipt.artifactId,
142
+ );
143
+ check(asked, "the host's policy wasn't asked when the view opened");
144
+ const policy = scripted ?? asked.answer;
145
+ check(
146
+ policy,
147
+ "the host's store doesn't report what its trustedControls policy answered (harness/store)",
148
+ );
149
+ same(
150
+ [...viewer.ticket.submitChannels].sort(),
151
+ [...policy.submitChannels].sort(),
152
+ "the view's channels under the host's policy",
153
+ );
154
+ const written = await viewer.write({ name: "Ada" });
155
+ const revision = written.json<{ revision: string }>().revision;
156
+ const artifactAllowed = policy.submitChannels.includes("artifact");
157
+ if (!artifactAllowed) {
158
+ const denied = await viewer.submit(revision);
159
+ same(
160
+ [denied.status, denied.json<{ code?: string }>().code],
161
+ [403, "MOSTRA_SUBMIT_CHANNEL_DENIED"],
162
+ "the artifact channel's submit",
163
+ );
164
+ }
165
+ if (!policy.submitChannels.includes("shell")) {
166
+ // A host that allows the artifact channel alone: the page's submit is recorded as such.
167
+ same((await viewer.submit(revision)).status, 200, "the artifact channel's submit");
168
+ same(
169
+ (await context.results(receipt.artifactId)).submission.channel,
170
+ "artifact",
171
+ "the recorded channel",
172
+ );
173
+ return;
174
+ }
175
+ const trusted = await viewer.shellSubmit(revision);
176
+ same(trusted.status, 200, "the shell's trusted Submit");
177
+ same(
178
+ (await context.results(receipt.artifactId)).submission.channel,
179
+ "shell",
180
+ "the recorded channel",
181
+ );
182
+ const activation = await context.eventually(
183
+ "the host hears the trusted Submit was used",
184
+ async () =>
185
+ (await context.store()).activations.find(
186
+ (entry) => entry.artifactId === receipt.artifactId,
187
+ ),
188
+ );
189
+ same([activation.control, activation.viewId], ["submit", viewer.viewId], "the activation");
190
+ if (context.host.supports("faults")) {
191
+ // A policy that fails narrows the view to the shell channel (D108).
192
+ await context.host.script({ port: "trustedControls", answer: "fail" });
193
+ const other = await context.published(FORM);
194
+ const narrowed = await context.viewer(other.artifactId);
195
+ same(narrowed.ticket.submitChannels, ["shell"], "the channels when the host's policy fails");
196
+ }
197
+ },
198
+ };
199
+
200
+ /** D131: secret() asks the host first; the value never reaches events or results. */
201
+ export const secrets: Scenario = {
202
+ id: "ports.secrets",
203
+ title:
204
+ "secret() in server code asks the host's secrets port first and falls back to the home's store on null; the value appears in no event",
205
+ covers: ["HO-01", "HO-05"],
206
+ async run(context) {
207
+ await context.start();
208
+ await context.host.call("secret/set", { name: "HOME_ONLY", value: "from-the-home-store" });
209
+ const receipt = await context.published(ACTIONS);
210
+ const viewer = await context.viewer(receipt.artifactId);
211
+ const fromHome = await viewer.run("actions.ts#secretLength", ["HOME_ONLY"]);
212
+ same(
213
+ fromHome.status,
214
+ "succeeded",
215
+ `a run reading the home's secret (${JSON.stringify(fromHome["error"] ?? "")})`,
216
+ );
217
+ same(await resultOf(fromHome), "from-the-home-store".length, "the home secret's length");
218
+ if (context.host.serves("secrets") && context.host.supports("faults")) {
219
+ await context.host.script({ port: "secrets", answer: { API_KEY: "s3cret-from-the-host" } });
220
+ const fromHost = await viewer.run("actions.ts#secretLength", ["API_KEY"]);
221
+ same(await resultOf(fromHost), "s3cret-from-the-host".length, "the host secret's length");
222
+ check(
223
+ (await context.store()).secrets.some((entry) => entry.name === "API_KEY"),
224
+ "the host's secrets port wasn't asked",
225
+ );
226
+ const events = await context.events({ artifacts: [receipt.artifactId] });
227
+ check(
228
+ !JSON.stringify(events).includes("s3cret-from-the-host"),
229
+ "a secret reached the event log",
230
+ );
231
+ }
232
+ },
233
+ };
234
+
235
+ /** AC-05, IN-09: server code's signals and host events reach the host as events, with the run. */
236
+ export const serverEvents: Scenario = {
237
+ id: "ports.server-events",
238
+ title:
239
+ "An action's signal() and emit() reach the host as signal.raised (source action) and host.* events caused by the run; Mostra wakes nobody for them",
240
+ covers: ["HO-05", "IN-09", "AC-05", "H-09"],
241
+ async run(context) {
242
+ await context.start();
243
+ const receipt = await context.published(ACTIONS);
244
+ const viewer = await context.viewer(receipt.artifactId);
245
+ const before = await context.store();
246
+ const run = await viewer.run("actions.ts#notify", ["ada@example.com"]);
247
+ same(run.status, "succeeded", `the action run (${JSON.stringify(run["error"] ?? "")})`);
248
+ const read = await context.events({
249
+ artifacts: [receipt.artifactId],
250
+ types: ["signal.raised", "host.*", "action.*"],
251
+ });
252
+ const types = read.events.map((event) => event.type as string);
253
+ const signal = read.events.find((event) => event.type === "signal.raised");
254
+ const emitted = read.events.find((event) => event.type === "host.mail.sent");
255
+ check(signal && emitted, `the run's signal or host event is missing (${types.join(", ")})`);
256
+ same([signal.payload["name"], signal.payload["source"]], ["mail.sent", "action"], "the signal");
257
+ same(signal.causation?.["runId"], run.runId, "the signal's causing run");
258
+ same(emitted.payload["data"], { to: "ada@example.com" }, "the host event's data");
259
+ const started = types.indexOf("action.started");
260
+ const ended = types.indexOf("action.succeeded");
261
+ check(
262
+ started >= 0 &&
263
+ ended > types.indexOf("host.mail.sent") &&
264
+ started < types.indexOf("signal.raised"),
265
+ `the order of the run's events (${types.join(", ")})`,
266
+ );
267
+ const after = await context.store();
268
+ same(after.deliveries.length, before.deliveries.length, "deliveries the run caused");
269
+ },
270
+ };
271
+
272
+ /** The port scenarios. */
273
+ export const PORT_SCENARIOS: readonly Scenario[] = [
274
+ identity,
275
+ trustedControls,
276
+ secrets,
277
+ serverEvents,
278
+ ];
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The session, process models, the home and privacy: what every host gets right before anything
3
+ * else (HO-02, HO-08, RT-06, H-11, H-12, H-13, H-16).
4
+ */
5
+ import { readFileSync, realpathSync, rmSync, statSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { HOST_PROTOCOL_REVISIONS } from "@mostra/protocol";
8
+ import { FORM } from "../fixtures.ts";
9
+ import { codeOf } from "../harness/client.ts";
10
+ import { check, connectSocket, rpcCode, type Scenario, same } from "../scenario.ts";
11
+ import { send } from "../viewer.ts";
12
+
13
+ /** The session: a revision both sides speak, every registered port supported, order enforced. */
14
+ export const negotiation: Scenario = {
15
+ id: "session.negotiation",
16
+ title:
17
+ "The host negotiates a revision the instance speaks, registers only ports it supports, and an instance refuses a client with no common revision",
18
+ covers: ["HO-02", "HO-05", "H-13", "H-15"],
19
+ async run(context) {
20
+ const started = await context.start();
21
+ check(
22
+ (HOST_PROTOCOL_REVISIONS as readonly string[]).includes(started.revision),
23
+ `the negotiated revision ${started.revision} isn't one this kit knows (${HOST_PROTOCOL_REVISIONS.join(", ")})`,
24
+ );
25
+ const unsupported = started.warnings.filter(
26
+ (warning) => warning.code === "MOSTRA_HOST_PORT_UNSUPPORTED",
27
+ );
28
+ check(
29
+ unsupported.length === 0,
30
+ "the host registers a port the instance doesn't support (MOSTRA_HOST_PORT_UNSUPPORTED)",
31
+ );
32
+ // mostra/initialize is sent once per connection; the host's client surfaces the refusal.
33
+ const again = await context.host.callRaw("mostra/initialize", {
34
+ client: { name: "again", version: "0" },
35
+ revisions: [...HOST_PROTOCOL_REVISIONS],
36
+ capabilities: {},
37
+ ports: [],
38
+ });
39
+ check("error" in again, "a second mostra/initialize on the host's connection was accepted");
40
+ same(again.error.data.code, "MOSTRA_HOST_INITIALIZE_ORDER", "a second initialize's code");
41
+ // A client with no revision in common is refused with a typed error; one with any is served.
42
+ const socket = context.socket();
43
+ check(socket, "the instance's home has no instance.json naming its socket (D81)");
44
+ const old = await connectSocket(socket, ["2020-01-01"]);
45
+ const refused = await old.initialize.then(
46
+ () => undefined,
47
+ (error: unknown) => rpcCode(error),
48
+ );
49
+ old.close();
50
+ same(refused, "MOSTRA_HOST_REVISION_UNSUPPORTED", "a client offering only 2020-01-01");
51
+ const mixed = await connectSocket(socket, ["2020-01-01", ...HOST_PROTOCOL_REVISIONS]);
52
+ const answer = (await mixed.initialize) as { revision: string };
53
+ mixed.close();
54
+ same(
55
+ answer.revision,
56
+ started.revision,
57
+ "the revision negotiated with an older and a current one",
58
+ );
59
+ },
60
+ };
61
+
62
+ /** One supervisor per home: a second host of the same home meets the lock, attached ones share it. */
63
+ export const processModels: Scenario = {
64
+ id: "session.process-models",
65
+ title:
66
+ "A host spawns its instance over stdio or attaches to the home's daemon; a second spawn of the same home is refused with MOSTRA_HOME_LOCKED",
67
+ covers: ["HO-05", "RT-06", "H-12"],
68
+ async run(context) {
69
+ const second = await context.anotherHost();
70
+ if (context.host.supports("attach")) {
71
+ const first = await context.start({ mode: "attach" });
72
+ same(first.instance.mode, "daemon", "an attached host's instance mode");
73
+ const other = await context.start({ mode: "attach", host: second });
74
+ same(other.instance.pid, first.instance.pid, "the daemon two attached hosts reach");
75
+ const third = await context.anotherHost();
76
+ const locked = await context.start({ host: third }).then(
77
+ () => undefined,
78
+ (error: unknown) => codeOf(error),
79
+ );
80
+ same(locked, "MOSTRA_HOME_LOCKED", "a spawn while the daemon owns the home");
81
+ await second.stopInstance();
82
+ await context.host.stopInstance();
83
+ return;
84
+ }
85
+ const first = await context.start();
86
+ same(first.instance.mode, "host", "a spawned instance's mode");
87
+ same(first.instance.pid > 0, true, "the instance reports its PID");
88
+ const locked = await context.start({ host: second }).then(
89
+ () => undefined,
90
+ (error: unknown) => codeOf(error),
91
+ );
92
+ same(locked, "MOSTRA_HOME_LOCKED", "a second spawn of the same home");
93
+ },
94
+ };
95
+
96
+ /**
97
+ * HO-08 and H-11: the host chooses the home, and what was published stays readable after the
98
+ * authoring directory is removed and the instance restarts.
99
+ */
100
+ export const authoringRemoved: Scenario = {
101
+ id: "home.authoring-removed",
102
+ title:
103
+ "The host chooses the home; artifacts, versions and submissions stay readable after the authoring directory is removed",
104
+ covers: ["HO-05", "HO-08", "H-11"],
105
+ async run(context) {
106
+ const started = await context.start();
107
+ same(started.instance.home, realpathSync(context.home), "the home the instance owns");
108
+ const receipt = await context.published(FORM);
109
+ const viewer = await context.viewer(receipt.artifactId);
110
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
111
+ const submitted = await viewer.answer({ name: "Ada", comment: "kept" }, channel);
112
+ same(submitted.status, 200, "the submit's status");
113
+ const before = await context.results(receipt.artifactId);
114
+ rmSync(receipt.dir, { recursive: true, force: true });
115
+ await context.restart();
116
+ const byId = await context.host.call<{ id: string; versions: { id: string }[] }>(
117
+ "artifact/get",
118
+ { artifact: { artifactId: receipt.artifactId } },
119
+ );
120
+ same(byId.versions[0]?.id, receipt.versionId, "the version, by artifact ID");
121
+ const byPath = await context.host.call<{ id: string }>("artifact/get", {
122
+ artifact: { path: receipt.dir },
123
+ });
124
+ same(byPath.id, receipt.artifactId, "the artifact its deleted path still names");
125
+ const after = await context.results(receipt.artifactId);
126
+ same(after.submission.digest, before.submission.digest, "the submission's digest");
127
+ same(after.answers, before.answers, "the submission's answers");
128
+ // The version still serves: its files live in the home, not in the authoring directory.
129
+ const again = await context.viewer(receipt.artifactId);
130
+ const page = await again.browser.ask({
131
+ url: `${again.ticket.artifactOrigin}/`,
132
+ headers: { accept: "text/html", "sec-fetch-site": "same-origin", "sec-fetch-dest": "iframe" },
133
+ });
134
+ same(page.status, 200, "the version's page after the source is gone");
135
+ check(
136
+ statSync(join(context.home, "sources", receipt.artifactId)).isDirectory(),
137
+ "the home keeps the version's source snapshot (DATA_MODEL §1)",
138
+ );
139
+ },
140
+ };
141
+
142
+ /** H-16: a host-embedded instance sends no telemetry, keeps its home private, binds loopback. */
143
+ export const privacy: Scenario = {
144
+ id: "home.privacy",
145
+ title:
146
+ "A host's home is marked host-configured (no telemetry), owner-only (0700, secrets 0600), and its gateway binds loopback",
147
+ covers: ["HO-05", "H-16", "EN-08"],
148
+ async run(context) {
149
+ const started = await context.start();
150
+ const config = JSON.parse(readFileSync(join(context.home, "config.json"), "utf8")) as {
151
+ hostConfigured?: { client: string };
152
+ };
153
+ check(config.hostConfigured, "config.json has no hostConfigured mark (D140 item 4)");
154
+ same(statSync(context.home).mode & 0o777, 0o700, "the home's mode");
155
+ await context.host.call("secret/set", { name: "CONFORMANCE_TOKEN", value: "kept-private-123" });
156
+ same(
157
+ statSync(join(context.home, "secrets", "home", "CONFORMANCE_TOKEN")).mode & 0o777,
158
+ 0o600,
159
+ "a secret's mode",
160
+ );
161
+ const status = await context.host.call<{ gateway?: { bind: string; shell: string } }>(
162
+ "instance/status",
163
+ {},
164
+ );
165
+ same(status.gateway?.bind, "127.0.0.1", "the gateway's bind address");
166
+ // Nothing answers on any address but loopback: the shell's port on the machine's name fails.
167
+ const shell = new URL(status.gateway?.shell ?? "http://127.0.0.1:1");
168
+ const elsewhere = await send({ url: `http://localhost:${shell.port}/` }).catch(() => undefined);
169
+ check(
170
+ elsewhere === undefined || elsewhere.status === 421,
171
+ `the shell answered a request for another host name (${elsewhere?.status})`,
172
+ );
173
+ same(started.instance.mode === "host" || started.instance.mode === "daemon", true, "the mode");
174
+ },
175
+ };
176
+
177
+ /** The session scenarios. */
178
+ export const SESSION_SCENARIOS: readonly Scenario[] = [
179
+ negotiation,
180
+ processModels,
181
+ authoringRemoved,
182
+ privacy,
183
+ ];
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Viewing: capability links the host mints, and the gateway's hygiene against strangers (H-07,
3
+ * H-14, HY-01, HY-03), then the shell and its bridge in a real browser (D108, SH-02).
4
+ */
5
+ import { FORM, FORM_V2 } from "../fixtures.ts";
6
+ import { check, NotApplicable, type Scenario, same } from "../scenario.ts";
7
+ import { OpenError, parseLink, send, Viewer } from "../viewer.ts";
8
+
9
+ /** H-07, H-14: publish answers a durable receipt with a link; links are scoped, revoked, rotated. */
10
+ export const links: Scenario = {
11
+ id: "viewing.links",
12
+ title:
13
+ "Publish returns a durable receipt with the artifact's link; view/url mints scoped links, a link without submit can't submit, and revoked or rotated links answer 410",
14
+ covers: ["HO-05", "H-07", "H-14", "HY-03"],
15
+ async run(context) {
16
+ await context.start();
17
+ const receipt = await context.published(FORM);
18
+ check(receipt.url && receipt.tokenId, "the publish receipt has no link (H-07)");
19
+ check(/^\d+$/.test(receipt.cursor), `the receipt's cursor (${receipt.cursor})`);
20
+ const viewOnly = await context.viewer(receipt.artifactId, { link: { scopes: ["view"] } });
21
+ const written = await viewOnly.write({ name: "x" });
22
+ same(
23
+ [written.status, written.json<{ code?: string }>().code],
24
+ [403, "MOSTRA_HYGIENE_SCOPE_DENIED"],
25
+ "a view-only link's write",
26
+ );
27
+ const minted = await context.host.call<{ url: string; tokenId: string }>("view/url", {
28
+ artifact: { artifactId: receipt.artifactId },
29
+ });
30
+ await context.host.call("view/revoke", { tokenId: minted.tokenId });
31
+ const revoked = await Viewer.open(minted.url).then(
32
+ () => undefined,
33
+ (error: unknown) => error,
34
+ );
35
+ check(revoked instanceof OpenError, "a revoked link still opened");
36
+ same([revoked.status, revoked.code], [410, "MOSTRA_HYGIENE_TOKEN_REVOKED"], "a revoked link");
37
+ const rotated = await context.host.call<{ url: string }>("view/rotate", {
38
+ tokenId: receipt.tokenId,
39
+ });
40
+ const old = await Viewer.open(receipt.url).then(
41
+ () => undefined,
42
+ (error: unknown) => error,
43
+ );
44
+ check(
45
+ old instanceof OpenError && old.status === 410,
46
+ "the default link still opens after its rotation",
47
+ );
48
+ await Viewer.open(rotated.url);
49
+ // A link that names a version opens that version, also after a newer one.
50
+ context.rewrite(receipt.dir, FORM_V2);
51
+ await context.publish(receipt.dir);
52
+ const pinned = await context.viewer(receipt.artifactId, { link: { version: 1 } });
53
+ same(pinned.ticket.version.number, 1, "the version a pinned link opens");
54
+ same(pinned.ticket.latest.number, 2, "the latest version it reports");
55
+ },
56
+ };
57
+
58
+ /** HY-01: the gateway refuses strangers: wrong Host, wrong Origin, no token, no CSRF token. */
59
+ export const hygiene: Scenario = {
60
+ id: "viewing.hygiene",
61
+ title:
62
+ "The host's instance refuses requests from strangers: an unknown Host (421), a foreign Origin (403), a wrong token (401), a mutation without its CSRF token (403)",
63
+ covers: ["HO-05", "HY-01"],
64
+ async run(context) {
65
+ await context.start();
66
+ const receipt = await context.published(FORM);
67
+ const link = parseLink(await context.link(receipt.artifactId));
68
+ const exchange = `${link.origin}/a/${link.artifactId}/_mostra/session`;
69
+ const post = (headers: Record<string, string>, body: unknown) =>
70
+ send({
71
+ method: "POST",
72
+ url: exchange,
73
+ headers: {
74
+ "content-type": "application/json",
75
+ "sec-fetch-site": "same-origin",
76
+ origin: link.origin,
77
+ ...headers,
78
+ },
79
+ body: JSON.stringify(body),
80
+ });
81
+ const host = await post({ host: "evil.example" }, { token: link.secret });
82
+ same(host.status, 421, "an unknown Host");
83
+ const origin = await post({ origin: "http://evil.example" }, { token: link.secret });
84
+ same(origin.status, 403, "a foreign Origin");
85
+ const token = await post({}, { token: "A".repeat(26) });
86
+ same(token.status, 401, "a wrong token");
87
+ const viewer = await Viewer.open(await context.link(receipt.artifactId));
88
+ const noCsrf = await viewer.browser.ask({
89
+ method: "POST",
90
+ url: `${viewer.ticket.artifactOrigin}/_mostra/v/2026-10-15/signal`,
91
+ headers: {
92
+ "content-type": "application/json",
93
+ origin: viewer.ticket.artifactOrigin,
94
+ "sec-fetch-site": "same-origin",
95
+ },
96
+ body: JSON.stringify({ viewId: viewer.viewId, name: "ping" }),
97
+ });
98
+ same(noCsrf.status, 403, "a mutation without its CSRF token");
99
+ for (const answer of [host, origin, token, noCsrf]) {
100
+ check(
101
+ !Object.keys(answer.headers).some((name) => name.startsWith("access-control-")),
102
+ "a refusal carries a CORS header",
103
+ );
104
+ }
105
+ },
106
+ };
107
+
108
+ /**
109
+ * D108, SH-02, SH-04: the shell and the page in a real browser. The trusted Submit carries the
110
+ * label the page asked for (`mostra/controls.request`), lists the required answer by label
111
+ * (`mostra/fields`) and focuses it in the page (`mostra/field.focus`), submits only after the page
112
+ * flushed its saves, the defaults it showed included (`mostra/flush`, D110), and a new version
113
+ * shows the trusted banner (`mostra/version.available`).
114
+ */
115
+ export const shellBridge: Scenario = {
116
+ id: "viewing.shell-bridge",
117
+ title:
118
+ "In a browser, the shell and the page speak the bridge: a labelled trusted Submit, blockers by label that focus the field, a flush before submit, and the new-version banner",
119
+ covers: ["HO-05", "SH-02", "SH-04", "H-05"],
120
+ async run(context) {
121
+ let chromium: typeof import("playwright-core").chromium;
122
+ try {
123
+ ({ chromium } = await import("playwright-core"));
124
+ } catch {
125
+ throw new NotApplicable("playwright-core isn't installed");
126
+ }
127
+ const browser = await chromium.launch().catch((error: unknown) => {
128
+ throw new NotApplicable(
129
+ `no browser to run the shell in (${(error as Error).message.split("\n")[0]})`,
130
+ );
131
+ });
132
+ try {
133
+ await context.start();
134
+ const receipt = await context.published(FORM);
135
+ const page = await browser.newPage();
136
+ await page.goto(await context.link(receipt.artifactId));
137
+ await page.waitForSelector('html[data-shell="ready"]', { timeout: 60_000 });
138
+ const frame = page.frameLocator("iframe");
139
+ const submit = page.locator("#mostra-submit");
140
+ await submit.waitFor();
141
+ check(
142
+ (await submit.textContent())?.includes("Send answers"),
143
+ "the trusted Submit's label isn't the one the page asked for",
144
+ );
145
+ // The required answer is listed by label, and picking it focuses the field in the page.
146
+ await page.waitForTimeout(600);
147
+ await submit.click();
148
+ const blocker = page.locator("[data-mostra-blocker=name]");
149
+ await blocker.waitFor({ timeout: 10_000 });
150
+ same((await blocker.textContent())?.trim(), "Your name", "the blocker's label");
151
+ await blocker.click();
152
+ await frame.getByLabel("Your name").waitFor();
153
+ await context.eventually(
154
+ "picking the blocker focuses the field in the page (mostra/field.focus)",
155
+ () =>
156
+ frame
157
+ .locator('[name="name"]')
158
+ .evaluate(
159
+ (element: { ownerDocument: { activeElement: unknown } }) =>
160
+ element === element.ownerDocument.activeElement,
161
+ ),
162
+ 10_000,
163
+ );
164
+ await frame.getByLabel("Your name").fill("Ada");
165
+ await context.eventually("the trusted Submit submits", async () => {
166
+ if ((await submit.textContent())?.includes("Submitted")) return true;
167
+ await submit.click().catch(() => undefined);
168
+ return (await submit.textContent())?.includes("Submitted");
169
+ });
170
+ const read = await context.results(receipt.artifactId);
171
+ same(read["submission"].channel, "shell", "the trusted Submit's channel");
172
+ // The page flushed first: the answer typed, and the default it showed for "comment".
173
+ same(read["answers"], { name: "Ada", comment: "" }, "the answers, defaults included (D110)");
174
+ context.rewrite(receipt.dir, FORM_V2);
175
+ await context.publish(receipt.dir);
176
+ await page.locator('[data-mostra-banner="2"]').waitFor({ timeout: 15_000 });
177
+ } finally {
178
+ await browser.close();
179
+ }
180
+ },
181
+ };
182
+
183
+ /** The viewing scenarios. */
184
+ export const VIEWING_SCENARIOS: readonly Scenario[] = [links, hygiene, shellBridge];
package/src/version.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** The kit's own release, from its package.json (found upwards from this module). */
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ let found: string | undefined;
7
+
8
+ /** This kit's release: what it reports to a host's shim and to an instance. */
9
+ export function kitVersion(): string {
10
+ if (found !== undefined) return found;
11
+ let dir = dirname(fileURLToPath(import.meta.url));
12
+ for (;;) {
13
+ try {
14
+ const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as {
15
+ name?: string;
16
+ version?: string;
17
+ };
18
+ if (manifest.name === "@mostra/conformance" && manifest.version) {
19
+ found = manifest.version;
20
+ return found;
21
+ }
22
+ } catch {
23
+ // Keep looking upwards.
24
+ }
25
+ const parent = dirname(dir);
26
+ if (parent === dir) throw new Error("Couldn't find @mostra/conformance's package.json.");
27
+ dir = parent;
28
+ }
29
+ }