@mostra/conformance 0.0.0-placeholder → 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/src/viewer.ts ADDED
@@ -0,0 +1,380 @@
1
+ /**
2
+ * A viewer as the kit plays one: it opens a capability link the way the shell does (the token for
3
+ * a shell session, a frame ticket, the frame's entry) and speaks the browser protocol the way a
4
+ * page does, with a per-host cookie jar (browsers keep cookies per host, not per port, D98) and the
5
+ * `Origin`, `Sec-Fetch-*` and CSRF headers a browser sends. It also sends what no browser would,
6
+ * for the hygiene scenarios. It never follows redirects.
7
+ */
8
+ import { request as httpRequest } from "node:http";
9
+ import {
10
+ BROWSER_PROTOCOL_REVISIONS,
11
+ deserializeAll,
12
+ type Frame,
13
+ type FrameTicket,
14
+ MutationId,
15
+ serializeAll,
16
+ } from "@mostra/protocol";
17
+
18
+ /** The browser-protocol revision the kit speaks: the first, which every gateway serves. */
19
+ const REVISION: string = BROWSER_PROTOCOL_REVISIONS[0] as string;
20
+
21
+ /** One HTTP answer. */
22
+ export interface Answer {
23
+ /** The HTTP status. */
24
+ readonly status: number;
25
+ /** Each header (lowercase name) with every value it was sent with. */
26
+ readonly headers: Readonly<Record<string, readonly string[]>>;
27
+ /** The body as text. */
28
+ readonly body: string;
29
+ /** The body as JSON (`{}` when it isn't). */
30
+ json<T = Record<string, unknown>>(): T;
31
+ }
32
+
33
+ /** One request. */
34
+ export interface Ask {
35
+ /** The HTTP method; default `GET`. */
36
+ readonly method?: string;
37
+ /** The full URL. */
38
+ readonly url: string;
39
+ /** The request's headers, exactly as sent. */
40
+ readonly headers?: Readonly<Record<string, string>>;
41
+ /** The body, if any. */
42
+ readonly body?: string;
43
+ /** Leave out the jar's cookies. */
44
+ readonly noCookies?: boolean;
45
+ }
46
+
47
+ /** Sends one request, never following a redirect. */
48
+ export function send(ask: Ask): Promise<Answer> {
49
+ const url = new URL(ask.url);
50
+ return new Promise((resolve, reject) => {
51
+ const req = httpRequest(
52
+ {
53
+ host: url.hostname.replace(/^\[|\]$/g, ""),
54
+ port: url.port,
55
+ method: ask.method ?? "GET",
56
+ path: `${url.pathname}${url.search}`,
57
+ headers: ask.headers,
58
+ agent: false,
59
+ },
60
+ (res) => {
61
+ const chunks: Buffer[] = [];
62
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
63
+ res.on("end", () => {
64
+ const headers: Record<string, string[]> = {};
65
+ for (let index = 0; index + 1 < res.rawHeaders.length; index += 2) {
66
+ const name = (res.rawHeaders[index] as string).toLowerCase();
67
+ const values = headers[name] ?? [];
68
+ values.push(res.rawHeaders[index + 1] as string);
69
+ headers[name] = values;
70
+ }
71
+ const body = Buffer.concat(chunks).toString("utf8");
72
+ resolve({
73
+ status: res.statusCode ?? 0,
74
+ headers,
75
+ body,
76
+ json: <T>() => {
77
+ try {
78
+ return JSON.parse(body) as T;
79
+ } catch {
80
+ return {} as T;
81
+ }
82
+ },
83
+ });
84
+ });
85
+ },
86
+ );
87
+ req.setTimeout(60_000, () => req.destroy(new Error(`${ask.url} didn't answer in 60 s`)));
88
+ req.on("error", reject);
89
+ if (ask.body !== undefined) req.write(ask.body);
90
+ req.end();
91
+ });
92
+ }
93
+
94
+ /** A link's parts: its shell origin, artifact, token secret and pinned version. */
95
+ export interface ParsedLink {
96
+ /** The shell's origin. */
97
+ readonly origin: string;
98
+ /** The artifact the link opens. */
99
+ readonly artifactId: string;
100
+ /** The token's secret, from the fragment. */
101
+ readonly secret: string;
102
+ /** The version number the link pins, if it pins one. */
103
+ readonly version?: string;
104
+ }
105
+
106
+ /** Reads a capability link (`http://host:port/a/<artifactId>[/v/<n>]#t=<secret>`). */
107
+ export function parseLink(link: string): ParsedLink {
108
+ const url = new URL(link);
109
+ const match = /^\/a\/(art_[0-9A-Z]{26})(?:\/v\/(\d+))?$/.exec(url.pathname);
110
+ const secret = new URLSearchParams(url.hash.slice(1)).get("t");
111
+ if (!match?.[1] || !secret)
112
+ throw new Error(`${url.origin}${url.pathname} isn't a capability link.`);
113
+ return {
114
+ origin: url.origin,
115
+ artifactId: match[1],
116
+ secret,
117
+ ...(match[2] !== undefined ? { version: match[2] } : {}),
118
+ };
119
+ }
120
+
121
+ /** A browser-like client with a per-host cookie jar. */
122
+ export class Browser {
123
+ readonly #jar = new Map<string, { value: string; path: string }>();
124
+
125
+ /** The cookies the jar sends to `url`: every cookie of the host whose path matches. */
126
+ cookiesFor(url: string): string {
127
+ const { pathname } = new URL(url);
128
+ return [...this.#jar]
129
+ .filter(([, cookie]) => {
130
+ const prefix = cookie.path.endsWith("/") ? cookie.path : `${cookie.path}/`;
131
+ return pathname === cookie.path || pathname.startsWith(prefix);
132
+ })
133
+ .map(([key, cookie]) => `${key.split(" ")[0]}=${cookie.value}`)
134
+ .join("; ");
135
+ }
136
+
137
+ /** Sends a request with the jar's cookies and keeps the ones that come back. */
138
+ async ask(ask: Ask): Promise<Answer> {
139
+ const cookie = ask.noCookies ? "" : this.cookiesFor(ask.url);
140
+ const answer = await send({
141
+ ...ask,
142
+ headers: { ...(cookie ? { cookie } : {}), ...ask.headers },
143
+ });
144
+ for (const line of answer.headers["set-cookie"] ?? []) {
145
+ const [pair = "", ...attributes] = line.split(";").map((part) => part.trim());
146
+ const at = pair.indexOf("=");
147
+ const path =
148
+ attributes.find((attribute) => attribute.toLowerCase().startsWith("path="))?.slice(5) ??
149
+ "/";
150
+ this.#jar.set(`${pair.slice(0, at)} ${path}`, { value: pair.slice(at + 1), path });
151
+ }
152
+ return answer;
153
+ }
154
+
155
+ /** A page on `origin` posting or fetching JSON from its own origin. */
156
+ fetchJson(
157
+ origin: string,
158
+ path: string,
159
+ init: { method?: string; body?: unknown; csrf?: string; headers?: Record<string, string> } = {},
160
+ ): Promise<Answer> {
161
+ const method = init.method ?? (init.body === undefined ? "GET" : "POST");
162
+ return this.ask({
163
+ method,
164
+ url: `${origin}${path}`,
165
+ headers: {
166
+ "sec-fetch-site": "same-origin",
167
+ "sec-fetch-mode": "cors",
168
+ "sec-fetch-dest": "empty",
169
+ ...(method === "GET" ? {} : { origin, "content-type": "application/json" }),
170
+ ...(init.csrf ? { "x-mostra-csrf": init.csrf } : {}),
171
+ ...init.headers,
172
+ },
173
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
174
+ });
175
+ }
176
+ }
177
+
178
+ /** Why a viewer couldn't open its link: the step and the gateway's answer. */
179
+ export class OpenError extends Error {
180
+ /** The HTTP status of the refused step. */
181
+ readonly status: number;
182
+ /** The diagnostic code (`MOSTRA_…`). */
183
+ readonly code: string | undefined;
184
+
185
+ constructor(step: string, answer: Answer) {
186
+ const code = answer.json<{ code?: string }>().code;
187
+ super(`${step}: HTTP ${answer.status}${code ? ` ${code}` : ""}`);
188
+ this.name = "OpenError";
189
+ this.status = answer.status;
190
+ this.code = code;
191
+ }
192
+ }
193
+
194
+ /** A run's state, as `runs` and `runs/attach` answer it. */
195
+ export interface RunState {
196
+ /** The run's ID (`run_…`). */
197
+ readonly runId: string;
198
+ /** `queued`, `running`, `succeeded`, `failed` or `cancelled` (D130). */
199
+ readonly status: string;
200
+ /** Its result, as serializer batches. */
201
+ readonly batches: readonly Frame[][];
202
+ /** The rest of the run's state (progress, log, error). */
203
+ readonly [key: string]: unknown;
204
+ }
205
+
206
+ /** One opened view: a shell session, a frame session and the view they show. */
207
+ export class Viewer {
208
+ /** The cookie jar this viewer's requests use. */
209
+ readonly browser: Browser;
210
+ /** The link it opened. */
211
+ readonly link: ParsedLink;
212
+ /** The frame ticket the shell got: the view, its version, channels and controls. */
213
+ readonly ticket: FrameTicket;
214
+ readonly #shellCsrf: string;
215
+ readonly #frameCsrf: string;
216
+
217
+ private constructor(
218
+ browser: Browser,
219
+ link: ParsedLink,
220
+ ticket: FrameTicket,
221
+ shellCsrf: string,
222
+ frameCsrf: string,
223
+ ) {
224
+ this.browser = browser;
225
+ this.link = link;
226
+ this.ticket = ticket;
227
+ this.#shellCsrf = shellCsrf;
228
+ this.#frameCsrf = frameCsrf;
229
+ }
230
+
231
+ /**
232
+ * Opens `link` as the shell does. `headers` go with the session exchange (the request the
233
+ * `identity` port judges, D143). Throws an {@link OpenError} for a refused step.
234
+ */
235
+ static async open(
236
+ link: string,
237
+ options: { browser?: Browser; headers?: Record<string, string> } = {},
238
+ ): Promise<Viewer> {
239
+ const browser = options.browser ?? new Browser();
240
+ const parsed = parseLink(link);
241
+ const api = `/a/${parsed.artifactId}/_mostra`;
242
+ const exchange = await browser.fetchJson(parsed.origin, `${api}/session`, {
243
+ body: { token: parsed.secret },
244
+ ...(options.headers ? { headers: options.headers } : {}),
245
+ });
246
+ if (exchange.status !== 200) throw new OpenError("exchange", exchange);
247
+ const shellCsrf = exchange.json<{ csrf: string }>().csrf;
248
+ const ticketAnswer = await browser.fetchJson(parsed.origin, `${api}/ticket`, {
249
+ body: parsed.version !== undefined ? { version: Number(parsed.version) } : {},
250
+ csrf: shellCsrf,
251
+ });
252
+ if (ticketAnswer.status !== 200) throw new OpenError("ticket", ticketAnswer);
253
+ const ticket = ticketAnswer.json<FrameTicket>();
254
+ const enter = await browser.ask({
255
+ url: ticket.src,
256
+ headers: {
257
+ accept: "text/html",
258
+ "sec-fetch-mode": "navigate",
259
+ "sec-fetch-dest": "iframe",
260
+ "sec-fetch-site": "same-site",
261
+ },
262
+ });
263
+ if (enter.status !== 303) throw new OpenError("enter", enter);
264
+ const session = await browser.fetchJson(ticket.artifactOrigin, "/_mostra/session");
265
+ if (session.status !== 200) throw new OpenError("frame session", session);
266
+ return new Viewer(browser, parsed, ticket, shellCsrf, session.json<{ csrf: string }>().csrf);
267
+ }
268
+
269
+ /** The view this frame load is (D104). */
270
+ get viewId(): string {
271
+ return this.ticket.viewId;
272
+ }
273
+
274
+ /** A browser-protocol request from the page. */
275
+ page(path: string, body: unknown): Promise<Answer> {
276
+ return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/${path}`, {
277
+ body,
278
+ csrf: this.#frameCsrf,
279
+ });
280
+ }
281
+
282
+ /** A request of the shell (its own origin, under `/a/<artifactId>`). */
283
+ shell(path: string, body?: unknown, method?: string): Promise<Answer> {
284
+ return this.browser.fetchJson(this.link.origin, `/a/${this.link.artifactId}/_mostra/${path}`, {
285
+ ...(body === undefined ? {} : { body }),
286
+ ...(method ? { method } : {}),
287
+ csrf: this.#shellCsrf,
288
+ });
289
+ }
290
+
291
+ /**
292
+ * Writes fields of the viewer's draft (or, with `scope: "artifact"`, the artifact state), with
293
+ * the labels a page sends for them (D106).
294
+ */
295
+ write(
296
+ fields: Record<string, unknown>,
297
+ options: {
298
+ baseRevision?: string;
299
+ scope?: "viewer" | "artifact";
300
+ labels?: Readonly<Record<string, string>>;
301
+ } = {},
302
+ ): Promise<Answer> {
303
+ return this.page("fields", {
304
+ mutationId: MutationId.create(),
305
+ scope: options.scope ?? "viewer",
306
+ baseRevision: options.baseRevision ?? "0",
307
+ viewId: this.viewId,
308
+ ops: Object.entries(fields).map(([id, value]) => ({
309
+ id,
310
+ value,
311
+ ...(options.labels?.[id] !== undefined ? { label: options.labels[id] } : {}),
312
+ })),
313
+ });
314
+ }
315
+
316
+ /** Submits on the artifact channel (D40). */
317
+ submit(expectedRevision: string): Promise<Answer> {
318
+ return this.page("submit", { viewId: this.viewId, expectedRevision, channel: "artifact" });
319
+ }
320
+
321
+ /** The trusted Submit, on the shell channel (D40, D108). */
322
+ shellSubmit(expectedRevision: string): Promise<Answer> {
323
+ return this.shell(`v/${REVISION}/submit`, { viewId: this.viewId, expectedRevision });
324
+ }
325
+
326
+ /** Writes `fields`, then submits on `channel`; answers the submit. */
327
+ async answer(
328
+ fields: Record<string, unknown>,
329
+ channel: "artifact" | "shell" = "artifact",
330
+ labels?: Readonly<Record<string, string>>,
331
+ ): Promise<Answer> {
332
+ const written = await this.write(fields, labels ? { labels } : {});
333
+ if (written.status !== 200) return written;
334
+ const { revision } = written.json<{ revision: string }>();
335
+ return channel === "artifact" ? this.submit(revision) : this.shellSubmit(revision);
336
+ }
337
+
338
+ /** Raises a signal from the page (IN-09). */
339
+ signal(name: string, payload?: unknown): Promise<Answer> {
340
+ return this.page("signal", {
341
+ viewId: this.viewId,
342
+ name,
343
+ ...(payload === undefined ? {} : { payload }),
344
+ });
345
+ }
346
+
347
+ /** Starts an action run (D130) and follows it until it ends. */
348
+ async run(fnId: string, args: unknown[], timeoutMs = 60_000): Promise<RunState> {
349
+ const started = await this.page("runs", {
350
+ viewId: this.viewId,
351
+ fnId,
352
+ args: await serializeAll(args, { mode: "argument" }),
353
+ clientKey: `ck-${MutationId.create()}`,
354
+ });
355
+ if (started.status !== 200) throw new OpenError("run", started);
356
+ const runId = started.json<{ runId: string }>().runId;
357
+ const deadline = Date.now() + timeoutMs;
358
+ for (;;) {
359
+ const attached = await this.page("runs/attach", { viewId: this.viewId, runIds: [runId] });
360
+ const state = attached.json<{ runs: RunState[] }>().runs?.[0];
361
+ if (state && ["succeeded", "failed", "cancelled"].includes(state.status)) return state;
362
+ if (Date.now() > deadline) throw new Error(`run ${runId} didn't end in ${timeoutMs} ms`);
363
+ await new Promise((done) => setTimeout(done, 100));
364
+ }
365
+ }
366
+
367
+ /** The page's long poll: events after `cursor` (D47). */
368
+ poll(cursor?: string): Promise<Answer> {
369
+ const query = `view=${this.viewId}&wait=0${cursor !== undefined ? `&cursor=${cursor}` : ""}`;
370
+ return this.browser.fetchJson(
371
+ this.ticket.artifactOrigin,
372
+ `/_mostra/v/${REVISION}/events/poll?${query}`,
373
+ );
374
+ }
375
+ }
376
+
377
+ /** A run's result, from its stored batches. */
378
+ export async function resultOf(state: RunState): Promise<unknown> {
379
+ return state.batches.length === 0 ? undefined : deserializeAll([...state.batches]);
380
+ }