screw-bugs 0.1.7 → 0.1.9

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.
Files changed (58) hide show
  1. package/README.md +83 -13
  2. package/dist/browser-playwright/launch.js +27 -10
  3. package/dist/browser-playwright/page.d.ts +50 -28
  4. package/dist/browser-playwright/page.js +101 -91
  5. package/dist/browser-playwright/recorder.d.ts +154 -0
  6. package/dist/browser-playwright/recorder.js +382 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli/commands.js +56 -11
  9. package/dist/cli/mcp.d.ts +11 -4
  10. package/dist/cli/mcp.js +86 -23
  11. package/dist/cli/operations.d.ts +30 -2
  12. package/dist/cli/operations.js +126 -20
  13. package/dist/cli/report-links.js +2 -2
  14. package/dist/cli/report-server.d.ts +41 -9
  15. package/dist/cli/report-server.js +139 -23
  16. package/dist/cli/share.d.ts +71 -4
  17. package/dist/cli/share.js +540 -109
  18. package/dist/cli/sign-in.d.ts +22 -10
  19. package/dist/cli/sign-in.js +23 -23
  20. package/dist/core/engine.js +54 -13
  21. package/dist/core/liveness.js +3 -1
  22. package/dist/core/services.d.ts +29 -4
  23. package/dist/core/share.d.ts +31 -0
  24. package/dist/core/share.js +139 -0
  25. package/dist/core/steps.d.ts +5 -0
  26. package/dist/core/steps.js +15 -1
  27. package/dist/core/video.d.ts +6 -0
  28. package/dist/core/video.js +8 -0
  29. package/dist/report/html.d.ts +4 -2
  30. package/dist/report/html.js +36 -13
  31. package/dist/report/icons.d.ts +3 -0
  32. package/dist/report/icons.js +5 -1
  33. package/dist/report/index.d.ts +3 -1
  34. package/dist/report/index.js +3 -1
  35. package/dist/report/live.d.ts +7 -0
  36. package/dist/report/live.js +135 -0
  37. package/dist/report/menu-bar.d.ts +3 -3
  38. package/dist/report/menu-bar.js +3 -3
  39. package/dist/report/player.d.ts +3 -3
  40. package/dist/report/player.js +3 -3
  41. package/dist/report/share-page.d.ts +48 -0
  42. package/dist/report/share-page.js +291 -0
  43. package/dist/report/styles.d.ts +2 -0
  44. package/dist/report/styles.js +2 -2
  45. package/dist/report/view.js +2 -0
  46. package/dist/report/walkthrough.d.ts +5 -2
  47. package/dist/report/walkthrough.js +17 -5
  48. package/dist/schema/accounts.js +10 -1
  49. package/dist/schema/evidence.d.ts +15 -8
  50. package/dist/schema/evidence.js +9 -4
  51. package/dist/schema/findings.js +1 -1
  52. package/dist/schema/job.d.ts +205 -65
  53. package/dist/schema/job.js +63 -11
  54. package/dist/schema/ledger.d.ts +80 -16
  55. package/dist/schema/ledger.js +36 -0
  56. package/dist/schema/share.d.ts +17 -0
  57. package/dist/schema/share.js +22 -0
  58. package/package.json +1 -1
package/dist/cli/share.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { NodeHttpClient } from '@effect/platform-node';
2
- import { Clock, Config, Context, Data, Duration, Effect, FileSystem, Layer, Option, Path, Ref, Schema, Stream, } from 'effect';
2
+ import { Clock, Config, Context, Data, Duration, Effect, FileSystem, Layer, Option, Path, Queue, Ref, Schema, Stream, } from 'effect';
3
3
  import { SecureRandom } from 'effect/crypto';
4
4
  import { HttpBody, HttpClient, HttpClientRequest, HttpClientResponse, HttpIncomingMessage, HttpServerResponse, } from 'effect/http';
5
- import { Engine, scrubBundle, shareable, shareFiles } from '../core/index.js';
6
- import { hex, SHARE_START_PATH } from '../report/index.js';
7
- import { CompletedShare, CreatedShare, JobId, ShareCallback, ShareErrorReply, ShareState, } from '../schema/index.js';
5
+ import { encodableFiles, Engine, PNG_HEADER_BYTES, pngSize, renameFiles, scrubBundle, shareable, shareFiles, WEBP_MAX_SIDE, webpPath, webpSize, } from '../core/index.js';
6
+ import { base64, hex, renderSharePage, SHARE_START_PATH, sha256, sharePageCsp, } from '../report/index.js';
7
+ import { CompletedShare, CreatedShare, JobId, ShareCallback, ShareClaimed, ShareErrorReply, ShareRequestCreated, ShareState, } from '../schema/index.js';
8
8
  /*
9
9
  * The Share button's local side: routes of the report server that put a run on screw-bugs Cloud,
10
10
  * following Cloud's upload protocol (see `src/schema/share.ts`). Only a person can share: it
@@ -14,17 +14,45 @@ import { CompletedShare, CreatedShare, JobId, ShareCallback, ShareErrorReply, Sh
14
14
  * browser to Cloud's `/share/new` with it and this server's callback
15
15
  * callback where Cloud sends the browser back, with the `state` and a one-time upload ticket:
16
16
  * starts the upload in the background and sends the browser to `progress`
17
- * progress a page that reloads itself while the files upload, then sends the browser to the
18
- * share's page on Cloud, or says what went wrong
17
+ * progress the page that follows the upload live (`renderSharePage` with `follow`), then
18
+ * sends the browser to the share's page on Cloud, or says what went wrong; without
19
+ * script it reloads itself
20
+ * status how the share is going, as JSON, for that page's script
21
+ * source a screenshot of the share, for the page to encode (only while it prepares)
22
+ * encoded where the page hands that screenshot back as WebP (POST; only while it prepares)
23
+ *
24
+ * That is for a report opened on this machine (127.0.0.1, localhost), the only callback Cloud
25
+ * takes. A report opened from another device (`http://pop-os:<port>`, over a tailnet) can only use
26
+ * the pairing hand-off instead (see `ShareRequestCreated`): start asks Cloud for a share request
27
+ * with the SHA-256 of a secret it keeps and sends the browser to `progress`, which shows the pairing
28
+ * code and a link to Cloud's confirm page; in the background the server claims the request with
29
+ * the secret until Cloud gives the ticket, and uploads as above.
19
30
  *
20
31
  * The upload is the run's report bundle with secrets taken out (`scrubBundle`) and the screenshots
21
32
  * and videos it links to (`shareFiles`). The ticket only ever goes to the Cloud origin this
22
33
  * process was configured with (`cloudOrigin`), and the browser only to pages there.
34
+ *
35
+ * Smaller screenshots: Node has no image encoder, the person's browser does. Before it starts the
36
+ * share on Cloud (whose file list names every file), the upload prepares: it offers its PNG
37
+ * screenshots (`encodableFiles`) to the progress page, which encodes each as WebP at its own size
38
+ * and hands it back. The server takes a WebP only from its own page (the post's `Origin` is this
39
+ * server's, as on a tailnet address that has no `Sec-Fetch-Site`), only when it is one whole file,
40
+ * of the screenshot's exact size in pixels, and smaller than the PNG; it then goes up as
41
+ * `<name>.webp`, and the bundle names it so (`renameFiles`). It waits for the page
42
+ * `ENCODE_FIRST_WAIT` to show up, then `ENCODE_IDLE` after each screenshot it hands back,
43
+ * `ENCODE_WINDOW` in all; whatever the page has not handed back by then (it was closed, has no
44
+ * script, the browser cannot encode WebP) goes up as the original PNG. So the share never depends
45
+ * on the page staying open.
46
+ *
47
+ * Up to `UPLOAD_CONCURRENCY` files upload at a time; the first one that fails stops the rest.
23
48
  */
24
49
  export const SHARE_PATHS = {
25
50
  start: SHARE_START_PATH,
26
51
  callback: '/.screw-bugs/share/callback',
27
52
  progress: '/.screw-bugs/share/progress',
53
+ status: '/.screw-bugs/share/status',
54
+ source: '/.screw-bugs/share/source',
55
+ encoded: '/.screw-bugs/share/encoded',
28
56
  };
29
57
  /**
30
58
  * Where screw-bugs Cloud is: `SCREW_BUGS_CLOUD_URL`, by default `https://screwbugs.dev`. An
@@ -57,8 +85,33 @@ export const CLOUD_ANSWER_TIMEOUT = Duration.seconds(60);
57
85
  export const FILE_UPLOAD_TIMEOUT = Duration.minutes(15);
58
86
  /** How long a whole upload may take: Cloud refuses files once an upload is an hour old. */
59
87
  export const UPLOAD_DEADLINE = Duration.hours(1);
88
+ /** How often the page with the pairing code reloads itself, to move on once it was typed. */
89
+ export const PAIRING_REFRESH_S = 2;
90
+ /** The longest and shortest wait between claims of a share request, whatever Cloud asks. */
91
+ const CLAIM_INTERVAL_S = { min: 1, max: 10 };
92
+ /** Whether the browser reached this server on this machine, the only callback Cloud takes. */
93
+ export const onThisMachine = (base) => {
94
+ try {
95
+ return ['127.0.0.1', 'localhost', '[::1]'].includes(new URL(base).hostname);
96
+ }
97
+ catch {
98
+ return false;
99
+ }
100
+ };
101
+ /** base64url without padding, as Cloud's tokens and the request's challenge are written. */
102
+ export const base64url = (bytes) => base64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
103
+ /** The challenge of a share request's `secret`, as PKCE's S256: base64url(SHA-256(ASCII)). */
104
+ export const challengeOf = (secret) => base64url(sha256(new TextEncoder().encode(secret)));
60
105
  /** How often the progress page reloads itself while files upload, in seconds. */
61
106
  export const PROGRESS_REFRESH_S = 1;
107
+ /** How many files upload at a time. */
108
+ export const UPLOAD_CONCURRENCY = 4;
109
+ /** How long the upload waits for the progress page to ask for the screenshots to encode. */
110
+ export const ENCODE_FIRST_WAIT = Duration.seconds(5);
111
+ /** How long the upload waits for the page's next screenshot once it has started encoding. */
112
+ export const ENCODE_IDLE = Duration.seconds(5);
113
+ /** The longest the upload waits for the page's screenshots in all. */
114
+ export const ENCODE_WINDOW = Duration.minutes(1);
62
115
  /**
63
116
  * What sharing needs from the app: a run's report bundle, as `screw-bugs report` builds it (its
64
117
  * `generator` names this screw-bugs' version, which picks the renderer Cloud shows it with).
@@ -72,32 +125,45 @@ export class ShareSource extends Context.Service()('screw-bugs/ShareSource') {
72
125
  /** Why a share failed, in one sentence for the person who clicked Share. */
73
126
  class ShareFailed extends Data.TaggedError('ShareFailed') {
74
127
  }
75
- const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
76
- /** The pages these routes answer with: no script, nothing loaded, inline styles only. */
77
- const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
78
- /** A small page of its own (`text` is plain text), reloading itself every `refresh` seconds. */
79
- export const sharePage = (title, text, options = {}) => HttpServerResponse.text(`<!doctype html><html lang="en"><head><meta charset="utf-8">` +
80
- `<meta name="viewport" content="width=device-width, initial-scale=1">` +
81
- (options.refresh === undefined
82
- ? ''
83
- : `<meta http-equiv="refresh" content="${options.refresh}">`) +
84
- `<title>${escapeHtml(title)}</title><style>` +
85
- 'body{font:16px/1.5 system-ui,sans-serif;max-width:36em;margin:15vh auto;padding:0 16px;' +
86
- 'color:#1d211c;background:#fff}h1{font-size:20px}a{color:inherit}' +
87
- '@media (prefers-color-scheme: dark){body{color:#eceeec;background:#111210}}' +
88
- `</style></head><body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(text)}</p>` +
89
- (options.back === undefined
90
- ? ''
91
- : `<p><a href="${escapeHtml(options.back)}">Back to the report</a></p>`) +
92
- '</body></html>', {
93
- status: options.status ?? 200,
94
- contentType: 'text/html; charset=utf-8',
95
- headers: {
96
- 'content-security-policy': PAGE_CSP,
97
- 'cache-control': 'no-store',
98
- 'referrer-policy': 'no-referrer',
99
- },
100
- });
128
+ /**
129
+ * A page of these routes (`renderSharePage`: the reports' look, one card), `text` plain text. A
130
+ * status of 400 or more shows as a failure. With `code`, `refresh` is how often it checks whether
131
+ * the code was used. A page with a form sends its origin as its referrer, so its post carries this
132
+ * server's `Origin` (`no-referrer` would make it `null`), and may follow the post's redirect to
133
+ * `form.cloud`. No page is ever shown in a frame.
134
+ */
135
+ export const sharePage = (title, text, options = {}) => {
136
+ const status = options.status ?? 200;
137
+ return HttpServerResponse.text(renderSharePage({
138
+ title,
139
+ text,
140
+ failed: status >= 400,
141
+ ...(options.code === undefined
142
+ ? options.refresh === undefined
143
+ ? {}
144
+ : { refresh: options.refresh }
145
+ : {
146
+ code: options.code,
147
+ ...(options.refresh === undefined ? {} : { wait: options.refresh }),
148
+ }),
149
+ ...(options.link === undefined ? {} : { link: options.link }),
150
+ ...(options.form === undefined
151
+ ? {}
152
+ : { form: { action: options.form.action, label: options.form.label } }),
153
+ ...(options.back === undefined ? {} : { back: options.back }),
154
+ ...(options.follow === undefined ? {} : { follow: options.follow }),
155
+ }), {
156
+ status,
157
+ contentType: 'text/html; charset=utf-8',
158
+ headers: {
159
+ 'content-security-policy': sharePageCsp(options.form?.cloud),
160
+ 'cache-control': 'no-store',
161
+ 'referrer-policy': options.form === undefined ? 'no-referrer' : 'same-origin',
162
+ 'x-frame-options': 'DENY',
163
+ 'x-content-type-options': 'nosniff',
164
+ },
165
+ });
166
+ };
101
167
  const redirect = (location) => HttpServerResponse.redirect(location, {
102
168
  status: 303,
103
169
  headers: { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' },
@@ -122,10 +188,10 @@ const answer = (response, schema) => response.status >= 200 && response.status <
122
188
  /** How much of a file is read at a time while it uploads. */
123
189
  const CHUNK = 64 * 1024;
124
190
  /**
125
- * A request body of the file at `path`, read from a handle opened here (without following a
126
- * symlink at its end), but only when that handle is the very file `checked` described: the same
127
- * device, inode and size. Otherwise undefined: something replaced it, or a folder on its way,
128
- * since it was checked. Reads exactly its checked size; the handle closes with the scope.
191
+ * A handle on the file at `path`, opened here (without following a symlink at its end), but only
192
+ * when it is the very file `checked` described: the same device, inode and size. Otherwise
193
+ * undefined: something replaced it, or a folder on its way, since it was checked. The handle
194
+ * closes with the scope.
129
195
  */
130
196
  const openChecked = (fs, path, checked) => Effect.gen(function* () {
131
197
  const handle = yield* fs.open(path, { flag: 'r', noFollow: true });
@@ -136,20 +202,33 @@ const openChecked = (fs, path, checked) => Effect.gen(function* () {
136
202
  Option.isSome(checked.ino) &&
137
203
  info.ino.value === checked.ino.value &&
138
204
  info.size === checked.size;
139
- if (!same)
140
- return undefined;
141
- const size = Number(info.size);
142
- const bytes = Stream.unfold(size, (left) => left <= 0
143
- ? Effect.succeed(undefined)
144
- : handle.readAlloc(Math.min(CHUNK, left)).pipe(Effect.flatMap(Option.match({
145
- onNone: () => Effect.fail(new Error('The file got shorter while it was read')),
146
- onSome: (chunk) => Effect.succeed([chunk, left - chunk.length]),
147
- }))));
148
- return HttpBody.stream(bytes, 'application/octet-stream', size);
205
+ return same ? handle : undefined;
149
206
  });
207
+ /** The first `size` bytes of `handle`, as a stream; it fails when the file is shorter. */
208
+ const bytesOf = (handle, size) => Stream.unfold(size, (left) => left <= 0
209
+ ? Effect.succeed(undefined)
210
+ : handle.readAlloc(Math.min(CHUNK, left)).pipe(Effect.flatMap(Option.match({
211
+ onNone: () => Effect.fail(new Error('The file got shorter while it was read')),
212
+ onSome: (chunk) => Effect.succeed([chunk, left - chunk.length]),
213
+ }))));
214
+ /** All of the checked file at `path` (see `openChecked`), or undefined when it changed. */
215
+ const readChecked = (fs, path, checked) => Effect.gen(function* () {
216
+ const handle = yield* openChecked(fs, path, checked);
217
+ if (handle === undefined)
218
+ return undefined;
219
+ const size = Number(checked.size);
220
+ const bytes = new Uint8Array(size);
221
+ let at = 0;
222
+ yield* Stream.runForEach(bytesOf(handle, size), (chunk) => Effect.sync(() => {
223
+ bytes.set(chunk, at);
224
+ at += chunk.length;
225
+ }));
226
+ return bytes;
227
+ }).pipe(Effect.scoped, Effect.orElseSucceed(() => undefined));
150
228
  /**
151
- * Uploads the run `jobId` of the runs folder `root` with `ticket`: the scrubbed bundle, then each
152
- * file, then completes it; the share's page on Cloud. `progress` hears how many files are up.
229
+ * Uploads the run `jobId` of the runs folder `root` with `ticket`: the scrubbed bundle, then its
230
+ * files, then completes it; the share's page on Cloud. With `encode`, its PNG screenshots may go
231
+ * up as the WebP copies that gives back first. `progress` hears how far it is.
153
232
  */
154
233
  export const uploadShare = (input) => Effect.gen(function* () {
155
234
  const fs = yield* FileSystem.FileSystem;
@@ -166,22 +245,23 @@ export const uploadShare = (input) => Effect.gen(function* () {
166
245
  message: `Screw Bugs Cloud at ${input.cloud} stopped answering; the share was not made.`,
167
246
  })),
168
247
  }));
169
- const bundle = scrubBundle(yield* source
248
+ const scrubbed = scrubBundle(yield* source
170
249
  .bundle(input.jobId)
171
250
  .pipe(Effect.mapError(() => new ShareFailed({ message: `Could not read the run ${input.jobId}.` }))));
172
- if (bundle.generator === undefined)
251
+ if (scrubbed.generator === undefined)
173
252
  return yield* new ShareFailed({
174
253
  message: 'This screw-bugs build does not know its version, which Screw Bugs Cloud needs to show the report.',
175
254
  });
176
- const generator = bundle.generator;
255
+ const generator = scrubbed.generator;
177
256
  // Each file by its real path, and only one that really is a file Cloud takes inside the run
178
257
  // folder, itself inside the runs folder: a symlink never brings in a file from elsewhere. Its
179
258
  // identity (device and inode) is taken from a handle opened there (not following a symlink at
180
259
  // its end), and its real path checked again once it is open; the upload then reads from a
181
260
  // handle proven to be that same file (`openChecked`), so a symlink swapped in later uploads
182
- // nothing. What this cannot stop: another process of the same user that swaps a folder on the
183
- // path back and forth in the moment between those checks. Such a process can already read
184
- // and send anything the user can; Node has no `openat` to walk the path by handles.
261
+ // nothing. The page encodes a screenshot from bytes read the same way (`readChecked`). What
262
+ // this cannot stop: another process of the same user that swaps a folder on the path back and
263
+ // forth in the moment between those checks. Such a process can already read and send anything
264
+ // the user can; Node has no `openat` to walk the path by handles.
185
265
  const unreadable = new ShareFailed({ message: `Could not read the run ${input.jobId}.` });
186
266
  const realRoot = yield* fs.realPath(input.root).pipe(Effect.mapError(() => unreadable));
187
267
  const runDir = yield* fs
@@ -189,32 +269,73 @@ export const uploadShare = (input) => Effect.gen(function* () {
189
269
  .pipe(Effect.mapError(() => unreadable));
190
270
  if (!runDir.startsWith(realRoot + path.sep))
191
271
  return yield* unreadable;
192
- const files = [];
272
+ const encodable = encodableFiles(scrubbed);
193
273
  /** Each file to upload, by its path in the bundle: its real path and what it was. */
194
274
  const real = new Map();
275
+ const screenshots = [];
195
276
  const realInside = (file) => fs.realPath(path.join(runDir, ...file.split('/'))).pipe(Effect.option, Effect.map(Option.filter((found) => {
196
277
  const inside = path.relative(runDir, found);
197
278
  return !path.isAbsolute(inside) && shareable(inside.split(path.sep).join('/'));
198
279
  })));
199
- for (const file of shareFiles(bundle)) {
280
+ for (const file of shareFiles(scrubbed)) {
200
281
  const found = yield* realInside(file);
201
282
  if (Option.isNone(found))
202
283
  continue;
203
- const info = yield* Effect.scoped(Effect.gen(function* () {
284
+ const checked = yield* Effect.scoped(Effect.gen(function* () {
204
285
  const handle = yield* fs.open(found.value, { flag: 'r', noFollow: true });
205
286
  const info = yield* handle.stat;
206
287
  // Still the same place once open: nothing on the way was swapped meanwhile.
207
288
  const again = yield* realInside(file);
208
- return Option.isSome(again) && again.value === found.value && info.type === 'File'
209
- ? Option.some(info)
210
- : Option.none();
289
+ if (Option.isNone(again) || again.value !== found.value || info.type !== 'File')
290
+ return Option.none();
291
+ // A screenshot's size in pixels, which its WebP copy must have too.
292
+ const pixels = encodable.has(file)
293
+ ? pngSize(Option.getOrElse(yield* handle.readAlloc(PNG_HEADER_BYTES), () => new Uint8Array()))
294
+ : undefined;
295
+ return Option.some({ info, pixels });
211
296
  })).pipe(Effect.orElseSucceed(() => Option.none()));
212
- if (Option.isNone(info))
297
+ if (Option.isNone(checked))
213
298
  continue;
214
- files.push({ path: file, size: Number(info.value.size) });
215
- real.set(file, { path: found.value, info: info.value });
299
+ const { info, pixels } = checked.value;
300
+ real.set(file, { path: found.value, info });
301
+ if (pixels !== undefined && Math.max(pixels.width, pixels.height) <= WEBP_MAX_SIDE)
302
+ screenshots.push({ path: file, size: Number(info.size), ...pixels });
216
303
  }
217
- yield* input.progress(0, files.length);
304
+ // Smaller copies of the screenshots, from the page while it is there; a copy's path must be
305
+ // one no other file of the share has.
306
+ const copies = input.encode === undefined || screenshots.length === 0
307
+ ? new Map()
308
+ : yield* input.encode({
309
+ files: screenshots,
310
+ read: (file) => {
311
+ const checked = real.get(file);
312
+ return checked === undefined
313
+ ? Effect.succeed(undefined)
314
+ : readChecked(fs, checked.path, checked.info);
315
+ },
316
+ });
317
+ const renames = new Map();
318
+ const uploads = new Map();
319
+ for (const [file, checked] of real) {
320
+ const copy = copies.get(file);
321
+ const renamed = webpPath(file);
322
+ if (copy !== undefined && renamed !== file && !real.has(renamed) && !uploads.has(renamed)) {
323
+ renames.set(file, renamed);
324
+ uploads.set(renamed, { _tag: 'bytes', local: file, bytes: copy });
325
+ }
326
+ else
327
+ uploads.set(file, { _tag: 'file', local: file, ...checked });
328
+ }
329
+ const bundle = renameFiles(scrubbed, renames);
330
+ const files = [...uploads].map(([file, upload]) => ({
331
+ path: file,
332
+ size: upload._tag === 'bytes' ? upload.bytes.length : Number(upload.info.size),
333
+ }));
334
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
335
+ const current = new Set();
336
+ let done = 0;
337
+ const report = Effect.suspend(() => input.progress({ done, total: files.length, current: [...current] }));
338
+ yield* report;
218
339
  const authorized = HttpClientRequest.bearerToken(input.ticket);
219
340
  const created = yield* client
220
341
  .execute(HttpClientRequest.post(`${input.cloud}/api/shares`).pipe(authorized, HttpClientRequest.bodyJsonUnsafe({
@@ -226,25 +347,37 @@ export const uploadShare = (input) => Effect.gen(function* () {
226
347
  const wrongPlace = new ShareFailed({
227
348
  message: 'Screw Bugs Cloud asked for an upload somewhere else; nothing more was sent.',
228
349
  });
229
- let done = 0;
230
- for (const upload of created.uploads) {
231
- const file = real.get(upload.path);
232
- if (file === undefined || !onOrigin(upload.url, input.cloud))
350
+ // Every place is checked before anything goes up.
351
+ const places = [];
352
+ for (const place of created.uploads) {
353
+ const upload = uploads.get(place.path);
354
+ if (upload === undefined || !onOrigin(place.url, input.cloud))
233
355
  return yield* wrongPlace;
234
- const changed = new ShareFailed({
235
- message: `${upload.path} changed while it was being shared; the share was not made.`,
236
- });
237
- yield* Effect.gen(function* () {
238
- const body = yield* openChecked(fs, file.path, file.info).pipe(Effect.mapError(() => changed), Effect.flatMap((body) => body === undefined ? Effect.fail(changed) : Effect.succeed(body)));
239
- yield* client
240
- .execute(HttpClientRequest.put(upload.url).pipe(authorized, HttpClientRequest.setBody(body)))
241
- .pipe(Effect.mapError(unreachable), Effect.flatMap((response) => response.status >= 200 && response.status < 300 ? Effect.void : refusal(response)), answeredWithin(FILE_UPLOAD_TIMEOUT));
242
- }).pipe(Effect.scoped);
243
- done++;
244
- yield* input.progress(done, files.length);
356
+ places.push({ url: place.url, upload });
245
357
  }
246
358
  if (!onOrigin(created.completeUrl, input.cloud))
247
359
  return yield* wrongPlace;
360
+ yield* Effect.forEach(places, ({ url, upload }) => Effect.gen(function* () {
361
+ const changed = new ShareFailed({
362
+ message: `${upload.local} changed while it was being shared; the share was not made.`,
363
+ });
364
+ const body = upload._tag === 'bytes'
365
+ ? HttpBody.uint8Array(upload.bytes, 'image/webp')
366
+ : yield* openChecked(fs, upload.path, upload.info).pipe(Effect.mapError(() => changed), Effect.flatMap((handle) => handle === undefined
367
+ ? Effect.fail(changed)
368
+ : Effect.succeed(HttpBody.stream(bytesOf(handle, Number(upload.info.size)), 'application/octet-stream', Number(upload.info.size)))));
369
+ yield* client
370
+ .execute(HttpClientRequest.put(url).pipe(authorized, HttpClientRequest.setBody(body)))
371
+ .pipe(Effect.mapError(unreachable), Effect.flatMap((response) => response.status >= 200 && response.status < 300 ? Effect.void : refusal(response)), answeredWithin(FILE_UPLOAD_TIMEOUT));
372
+ }).pipe(Effect.scoped, Effect.onExit((exit) => Effect.suspend(() => {
373
+ current.delete(upload.local);
374
+ if (exit._tag === 'Success')
375
+ done++;
376
+ return report;
377
+ })), (send) => Effect.suspend(() => {
378
+ current.add(upload.local);
379
+ return report;
380
+ }).pipe(Effect.andThen(send))), { concurrency: UPLOAD_CONCURRENCY, discard: true });
248
381
  const completed = yield* client
249
382
  .execute(HttpClientRequest.post(created.completeUrl).pipe(authorized))
250
383
  .pipe(Effect.mapError(unreachable), Effect.flatMap((response) => answer(response, CompletedShare)), answeredWithin(CLOUD_ANSWER_TIMEOUT));
@@ -257,6 +390,8 @@ export const uploadShare = (input) => Effect.gen(function* () {
257
390
  message: 'The upload took longer than Screw Bugs Cloud allows; the share was not made.',
258
391
  })),
259
392
  }));
393
+ /** A small answer of a share route, never cached. */
394
+ const reply = (status, body = {}) => HttpServerResponse.jsonUnsafe(body, { status, headers: { 'cache-control': 'no-store' } });
260
395
  /**
261
396
  * The share routes of a report server for the runs folder `root`, while `scope` is open (uploads
262
397
  * run in it); none when sharing is off (no `ShareSource`, or no usable Cloud URL).
@@ -277,13 +412,21 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
277
412
  return entry === undefined ? map : new Map(map).set(state, { ...entry, phase });
278
413
  });
279
414
  const back = (jobId) => `/${encodeURIComponent(jobId)}/report.html`;
280
- const start = (query, headers, base) => Effect.gen(function* () {
281
- // A click in a page of this server; another site cannot start a share in its name.
415
+ const start = (method, query, headers, base) => Effect.gen(function* () {
416
+ // Only a click in a page of this server starts a share; another site cannot start one
417
+ // in its name. A browser tells where a click came from (`Sec-Fetch-Site`) only to a
418
+ // trustworthy origin, such as 127.0.0.1 or localhost; on an `http:` tailnet address it
419
+ // says nothing. Then the link only asks first ("Share this run?"), and the share starts
420
+ // from that page's form, whose post must carry this server's own `Origin`.
282
421
  const site = headers['sec-fetch-site'];
283
- if (site !== undefined && site !== 'same-origin' && site !== 'none')
284
- return sharePage('Share from the report', 'Click Share in a report to share it.', {
285
- status: 403,
286
- });
422
+ const refused = sharePage('Share from the report', 'Click Share in a report to share it.', {
423
+ status: 403,
424
+ });
425
+ if (method === 'POST'
426
+ ? headers['origin'] !== base
427
+ : site !== undefined && site !== 'same-origin' && site !== 'none')
428
+ return refused;
429
+ const ask = method === 'GET' && site === undefined;
287
430
  const jobId = Schema.decodeUnknownOption(JobId)(query.get('run'));
288
431
  if (Option.isNone(jobId))
289
432
  return sharePage('No such run', 'This link does not name a run.', { status: 404 });
@@ -293,23 +436,161 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
293
436
  const ended = ['finished', 'errored'].includes(bundle.value.ledger.state);
294
437
  if (!ended)
295
438
  return sharePage('The run has not ended', 'A run can be shared once it has ended. Try again when it has.', { status: 409, back: back(jobId.value) });
296
- const state = hex(yield* SecureRandom.SecureRandom.use((random) => random.randomBytes(32)).pipe(Effect.provide(SecureRandom.layerWebCrypto)));
439
+ if (ask)
440
+ return sharePage('Share this run on Screw Bugs Cloud?', `Run ${jobId.value} goes to Screw Bugs Cloud: a link anyone can open for 7 days, after you confirm there.`, {
441
+ form: {
442
+ action: `${SHARE_PATHS.start}?run=${encodeURIComponent(jobId.value)}`,
443
+ label: 'Share',
444
+ cloud,
445
+ },
446
+ back: back(jobId.value),
447
+ });
448
+ const random = (bytes) => SecureRandom.SecureRandom.use((random) => random.randomBytes(bytes)).pipe(Effect.provide(SecureRandom.layerWebCrypto));
449
+ const state = hex(yield* random(32));
450
+ const pairing = onThisMachine(base)
451
+ ? undefined
452
+ : yield* requestPairing(base64url(yield* random(32)));
453
+ if (pairing !== undefined && pairing._tag === 'refused')
454
+ return sharePage('Share not started', pairing.message, {
455
+ status: 502,
456
+ back: back(jobId.value),
457
+ });
297
458
  const now = yield* Clock.currentTimeMillis;
459
+ const phase = pairing === undefined
460
+ ? { _tag: 'waiting' }
461
+ : {
462
+ _tag: 'pairing',
463
+ code: pairing.request.code,
464
+ confirmUrl: pairing.request.confirmUrl,
465
+ };
298
466
  yield* Ref.update(shares, (map) => {
299
- const running = (entry) => entry.phase._tag === 'uploading';
467
+ const running = (entry) => entry.phase._tag === 'uploading' || entry.phase._tag === 'preparing';
300
468
  const kept = [...map].filter(([, entry]) => running(entry) || now - entry.created < SHARE_WAIT_MS);
301
469
  const others = kept.filter(([, entry]) => !running(entry));
302
470
  return new Map([
303
471
  ...kept.filter(([, entry]) => running(entry)),
304
472
  ...others.slice(-(SHARES_KEPT - 2)),
305
- [state, { jobId: jobId.value, created: now, phase: { _tag: 'waiting' } }],
473
+ [state, { jobId: jobId.value, created: now, phase }],
306
474
  ]);
307
475
  });
476
+ if (pairing !== undefined) {
477
+ yield* claim(state, jobId.value, pairing.secret, pairing.request).pipe(Effect.provide(NodeHttpClient.layerNodeHttp), Effect.forkIn(scope));
478
+ return redirect(`${SHARE_PATHS.progress}?state=${state}`);
479
+ }
308
480
  const target = new URL('/share/new', cloud);
309
481
  target.searchParams.set('callback', `${base}${SHARE_PATHS.callback}`);
310
482
  target.searchParams.set('state', state);
311
483
  return redirect(target.href);
312
484
  });
485
+ /**
486
+ * A share request on Cloud for the pairing hand-off, made with the challenge of `secret`; or
487
+ * the sentence for the person when Cloud cannot make one.
488
+ */
489
+ const requestPairing = (secret) => Effect.gen(function* () {
490
+ const client = yield* HttpClient.HttpClient;
491
+ const response = yield* client
492
+ .execute(HttpClientRequest.post(`${cloud}/api/share-requests`).pipe(HttpClientRequest.bodyJsonUnsafe({ challenge: challengeOf(secret) })))
493
+ .pipe(Effect.mapError((error) => new ShareFailed({
494
+ message: `Could not reach Screw Bugs Cloud at ${cloud}: ${String(error)}.`,
495
+ })), Effect.flatMap((response) => response.status === 404 || response.status === 405
496
+ ? Effect.fail(new ShareFailed({
497
+ message: `Screw Bugs Cloud at ${cloud} cannot take a share from a report opened on another device yet. Open the report on this computer (127.0.0.1) to share it.`,
498
+ }))
499
+ : answer(response, ShareRequestCreated)), Effect.timeoutOrElse({
500
+ duration: CLOUD_ANSWER_TIMEOUT,
501
+ orElse: () => Effect.fail(new ShareFailed({ message: `Screw Bugs Cloud at ${cloud} did not answer.` })),
502
+ }));
503
+ if (!onOrigin(response.confirmUrl, cloud))
504
+ return yield* new ShareFailed({
505
+ message: 'Screw Bugs Cloud gave a confirm page somewhere else; nothing was shared.',
506
+ });
507
+ return { _tag: 'requested', secret, request: response };
508
+ }).pipe(Effect.catchTag('ShareFailed', (error) => Effect.succeed({ _tag: 'refused', message: error.message })), Effect.provide(NodeHttpClient.layerNodeHttp));
509
+ /**
510
+ * Claims the share request `request` with `secret` every `interval` seconds while its entry
511
+ * `state` waits for the person to type the code, then uploads with the ticket Cloud gives.
512
+ * Stops when the entry is gone (dropped for newer shares) or no longer pairing, and fails the
513
+ * share on Cloud's refusal (a 4xx: expired, cancelled, a limit). An unreachable Cloud or a
514
+ * 5xx is tried again, until the share has waited `SHARE_WAIT_MS`.
515
+ */
516
+ const claim = (state, jobId, secret, request) => Effect.gen(function* () {
517
+ const client = yield* HttpClient.HttpClient;
518
+ const interval = Number.isFinite(request.interval)
519
+ ? Math.min(Math.max(request.interval, CLAIM_INTERVAL_S.min), CLAIM_INTERVAL_S.max)
520
+ : CLAIM_INTERVAL_S.min;
521
+ const url = `${cloud}/api/share-requests/${request.id}/claim`;
522
+ const fail = (message) => set(state, { _tag: 'failed', message });
523
+ while (true) {
524
+ yield* Effect.sleep(Duration.seconds(interval));
525
+ const entry = (yield* Ref.get(shares)).get(state);
526
+ if (entry === undefined || entry.phase._tag !== 'pairing')
527
+ return;
528
+ if ((yield* Clock.currentTimeMillis) - entry.created >= SHARE_WAIT_MS)
529
+ return yield* fail('The code was not typed on Screw Bugs Cloud in time. Click Share in the report again.');
530
+ // One claim, its answer read whole within `CLOUD_ANSWER_TIMEOUT`: the ticket, Cloud's
531
+ // refusal, or nothing yet (pending, unreachable, a 5xx, too slow), to try again.
532
+ const outcome = yield* client
533
+ .execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe({ secret })))
534
+ .pipe(Effect.flatMap((response) => response.status === 202 || response.status >= 500
535
+ ? Effect.succeed(undefined)
536
+ : answer(response, ShareClaimed)), Effect.map((claimed) => claimed === undefined
537
+ ? undefined
538
+ : { _tag: 'claimed', ticket: claimed.ticket, api: claimed.api }), Effect.catchTag('ShareFailed', (error) => Effect.succeed({ _tag: 'refused', message: error.message })), Effect.orElseSucceed(() => undefined), Effect.timeoutOrElse({
539
+ duration: CLOUD_ANSWER_TIMEOUT,
540
+ orElse: () => Effect.succeed(undefined),
541
+ }));
542
+ if (outcome === undefined)
543
+ continue;
544
+ if (outcome._tag === 'refused')
545
+ return yield* fail(outcome.message);
546
+ if (originOf(outcome.api) !== cloud)
547
+ return yield* fail(`The ticket is for another Screw Bugs Cloud than ${cloud}; nothing was sent.`);
548
+ const started = yield* beginUpload(state, 'pairing', outcome.ticket);
549
+ if (started === 'busy')
550
+ return yield* fail('Another share was uploading, and this server uploads one at a time. Click Share in the report again once it is done.');
551
+ return;
552
+ }
553
+ });
554
+ /**
555
+ * Starts uploading the share `state` with `ticket` in the background, only while it is still
556
+ * remembered, in phase `from` and not too old (checked and moved to uploading in one step, so
557
+ * a share dropped meanwhile never uploads unseen): `gone` when it is not; `busy` when another
558
+ * upload is running (one at a time).
559
+ */
560
+ const beginUpload = (state, from, ticket) => Effect.gen(function* () {
561
+ const free = yield* Ref.modify(uploading, (busy) => [!busy, true]);
562
+ if (!free)
563
+ return 'busy';
564
+ const now = yield* Clock.currentTimeMillis;
565
+ const jobId = yield* Ref.modify(shares, (map) => {
566
+ const entry = map.get(state);
567
+ if (entry === undefined ||
568
+ entry.phase._tag !== from ||
569
+ now - entry.created >= SHARE_WAIT_MS)
570
+ return [undefined, map];
571
+ const phase = { _tag: 'uploading', done: 0, total: 0, current: [] };
572
+ return [entry.jobId, new Map(map).set(state, { ...entry, phase })];
573
+ });
574
+ if (jobId === undefined) {
575
+ yield* Ref.set(uploading, false);
576
+ return 'gone';
577
+ }
578
+ yield* uploadShare({
579
+ root,
580
+ jobId,
581
+ ticket,
582
+ cloud,
583
+ progress: (progress) => set(state, { _tag: 'uploading', ...progress }),
584
+ encode: encoder(state),
585
+ }).pipe(Effect.matchEffect({
586
+ onSuccess: (completed) => set(state, { _tag: 'done', resultUrl: completed.resultUrl }),
587
+ onFailure: (error) => set(state, {
588
+ _tag: 'failed',
589
+ message: error instanceof ShareFailed ? error.message : 'The upload failed.',
590
+ }),
591
+ }), Effect.ensuring(Ref.set(uploading, false)), Effect.provideService(ShareSource, source.value), Effect.provide(NodeHttpClient.layerNodeHttp), Effect.provide(services), Effect.forkIn(scope));
592
+ return 'started';
593
+ });
313
594
  const callback = (query) => Effect.gen(function* () {
314
595
  const params = Schema.decodeUnknownOption(ShareCallback)(Object.fromEntries(query));
315
596
  if (Option.isNone(params))
@@ -325,36 +606,178 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
325
606
  return sharePage('Share not started', 'This share was not started here, was already used, or waited too long. Click Share in the report again.', { status: 410 });
326
607
  if (originOf(api) !== cloud)
327
608
  return sharePage('Share not started', `The ticket is for another Screw Bugs Cloud than ${cloud}; nothing was sent.`, { status: 400, back: back(entry.jobId) });
328
- const free = yield* Ref.modify(uploading, (busy) => [!busy, true]);
329
- if (!free)
609
+ const started = yield* beginUpload(state, 'waiting', ticket);
610
+ if (started === 'gone')
611
+ return sharePage('Share not started', 'This share was not started here, was already used, or waited too long. Click Share in the report again.', { status: 410 });
612
+ if (started === 'busy')
330
613
  return sharePage('Another share is uploading', 'This server uploads one share at a time. Reload this page once the other one is done.', { status: 409, back: back(entry.jobId) });
331
- yield* set(state, { _tag: 'uploading', done: 0, total: 0 });
332
- yield* uploadShare({
333
- root,
334
- jobId: entry.jobId,
335
- ticket,
336
- cloud,
337
- progress: (done, total) => set(state, { _tag: 'uploading', done, total }),
338
- }).pipe(Effect.matchEffect({
339
- onSuccess: (completed) => set(state, { _tag: 'done', resultUrl: completed.resultUrl }),
340
- onFailure: (error) => set(state, {
341
- _tag: 'failed',
342
- message: error instanceof ShareFailed ? error.message : 'The upload failed.',
343
- }),
344
- }), Effect.ensuring(Ref.set(uploading, false)), Effect.provideService(ShareSource, source.value), Effect.provide(NodeHttpClient.layerNodeHttp), Effect.provide(services), Effect.forkIn(scope));
345
614
  return redirect(`${SHARE_PATHS.progress}?state=${state}`);
346
615
  });
616
+ /**
617
+ * The encoder of the share `state`: it offers the screenshots to the progress page and takes
618
+ * what the page hands back, while the page keeps at it (see the top of this file).
619
+ */
620
+ const encoder = (state) => ({ files, read }) => Effect.gen(function* () {
621
+ const events = yield* Queue.unbounded();
622
+ const copies = new Map();
623
+ const settled = new Set();
624
+ yield* set(state, { _tag: 'preparing', files, settled: 0, read, events });
625
+ const start = yield* Clock.currentTimeMillis;
626
+ const window = Duration.toMillis(ENCODE_WINDOW);
627
+ /** When it stops waiting unless the page hands something back first. */
628
+ let until = start + Duration.toMillis(ENCODE_FIRST_WAIT);
629
+ let seen = false;
630
+ while (settled.size < files.length) {
631
+ const now = yield* Clock.currentTimeMillis;
632
+ const left = Math.min(until, start + window) - now;
633
+ if (left <= 0)
634
+ break;
635
+ const event = yield* Queue.take(events).pipe(Effect.timeoutOption(left));
636
+ if (Option.isNone(event))
637
+ break;
638
+ const at = yield* Clock.currentTimeMillis;
639
+ if (event.value._tag === 'seen') {
640
+ if (!seen)
641
+ until = at + Duration.toMillis(ENCODE_IDLE);
642
+ seen = true;
643
+ continue;
644
+ }
645
+ seen = true;
646
+ until = at + Duration.toMillis(ENCODE_IDLE);
647
+ settled.add(event.value.path);
648
+ if (event.value.webp !== undefined)
649
+ copies.set(event.value.path, event.value.webp);
650
+ yield* set(state, { _tag: 'preparing', files, settled: settled.size, read, events });
651
+ }
652
+ // Whatever the page sends from now on is refused (410): the phase moves on.
653
+ yield* set(state, { _tag: 'uploading', done: 0, total: 0, current: [] });
654
+ return copies;
655
+ });
656
+ /** The share a request's `state` names, while it prepares, and its screenshot `path`. */
657
+ const preparing = (query) => Effect.gen(function* () {
658
+ const state = Schema.decodeUnknownOption(ShareState)(query.get('state'));
659
+ if (Option.isNone(state))
660
+ return undefined;
661
+ const entry = (yield* Ref.get(shares)).get(state.value);
662
+ if (entry === undefined)
663
+ return undefined;
664
+ const phase = entry.phase;
665
+ return { entry, phase, file: query.get('path') };
666
+ });
667
+ const status = (query) => Effect.gen(function* () {
668
+ const found = yield* preparing(query);
669
+ if (found === undefined || found.phase._tag === 'waiting')
670
+ return reply(404);
671
+ const phase = found.phase;
672
+ switch (phase._tag) {
673
+ case 'preparing':
674
+ yield* Queue.offer(phase.events, { _tag: 'seen' });
675
+ return reply(200, {
676
+ phase: 'preparing',
677
+ settled: phase.settled,
678
+ files: phase.files.map((file) => ({ path: file.path, size: file.size })),
679
+ });
680
+ case 'uploading':
681
+ return reply(200, {
682
+ phase: 'uploading',
683
+ done: phase.done,
684
+ total: phase.total,
685
+ current: phase.current,
686
+ });
687
+ default:
688
+ return reply(200, { phase: phase._tag });
689
+ }
690
+ });
691
+ /**
692
+ * A request from a page of this server. A browser says where a request came from
693
+ * (`Sec-Fetch-Site`) only to a trustworthy origin, never on an `http:` tailnet address; a post
694
+ * always carries its `Origin`, which must then be this server's own.
695
+ */
696
+ const fromOwnPage = (headers, base, post) => {
697
+ const site = headers['sec-fetch-site'];
698
+ if (site !== undefined && site !== 'same-origin')
699
+ return false;
700
+ return !post || headers['origin'] === base;
701
+ };
702
+ const screenshot = (query, headers, base) => Effect.gen(function* () {
703
+ if (!fromOwnPage(headers, base, false))
704
+ return reply(403);
705
+ const found = yield* preparing(query);
706
+ if (found === undefined)
707
+ return reply(404);
708
+ if (found.phase._tag !== 'preparing')
709
+ return reply(410);
710
+ const file = found.phase.files.find((f) => f.path === found.file);
711
+ if (file === undefined)
712
+ return reply(404);
713
+ const bytes = yield* found.phase.read(file.path);
714
+ if (bytes === undefined)
715
+ return reply(410);
716
+ return HttpServerResponse.uint8Array(bytes, {
717
+ contentType: 'image/png',
718
+ headers: { 'cache-control': 'no-store' },
719
+ });
720
+ });
721
+ const encoded = (query, headers, base, body) => Effect.gen(function* () {
722
+ // Only the progress page: a fetch from this origin, as WebP (which no form can send).
723
+ if (!fromOwnPage(headers, base, true))
724
+ return reply(403);
725
+ if (headers['content-type'] !== 'image/webp')
726
+ return reply(415);
727
+ const found = yield* preparing(query);
728
+ if (found === undefined)
729
+ return reply(404);
730
+ const phase = found.phase;
731
+ if (phase._tag !== 'preparing')
732
+ return reply(410);
733
+ const file = phase.files.find((f) => f.path === found.file);
734
+ if (file === undefined)
735
+ return reply(404);
736
+ // A copy must be smaller than the screenshot; nothing longer is read.
737
+ const declared = Number(headers['content-length'] ?? '0');
738
+ const bytes = declared >= file.size ? undefined : yield* body(file.size - 1).pipe(Effect.option);
739
+ if (bytes === undefined || Option.isNone(bytes)) {
740
+ yield* Queue.offer(phase.events, { _tag: 'handed', path: file.path, webp: undefined });
741
+ return reply(413);
742
+ }
743
+ if (bytes.value.length === 0) {
744
+ yield* Queue.offer(phase.events, { _tag: 'handed', path: file.path, webp: undefined });
745
+ return reply(204);
746
+ }
747
+ const size = webpSize(bytes.value);
748
+ const fits = size !== undefined &&
749
+ size.width === file.width &&
750
+ size.height === file.height &&
751
+ bytes.value.length < file.size;
752
+ yield* Queue.offer(phase.events, {
753
+ _tag: 'handed',
754
+ path: file.path,
755
+ webp: fits ? bytes.value : undefined,
756
+ });
757
+ return reply(fits ? 204 : 422);
758
+ });
347
759
  const progress = (query) => Effect.gen(function* () {
348
760
  const state = Schema.decodeUnknownOption(ShareState)(query.get('state'));
349
761
  const entry = Option.isSome(state) ? (yield* Ref.get(shares)).get(state.value) : undefined;
350
- if (entry === undefined || entry.phase._tag === 'waiting')
762
+ if (entry === undefined || entry.phase._tag === 'waiting' || Option.isNone(state))
351
763
  return sharePage('No such share', 'There is no share in progress here.', { status: 404 });
352
764
  const phase = entry.phase;
353
765
  switch (phase._tag) {
766
+ case 'pairing':
767
+ return sharePage('Type this code on Screw Bugs Cloud', 'Open Screw Bugs Cloud, sign in, and type this code to share the report. This page moves on by itself once you confirm there.', {
768
+ code: phase.code,
769
+ link: { href: phase.confirmUrl, text: 'Open Screw Bugs Cloud' },
770
+ refresh: PAIRING_REFRESH_S,
771
+ back: back(entry.jobId),
772
+ });
773
+ case 'preparing':
354
774
  case 'uploading':
355
- return sharePage('Sharing on Screw Bugs Cloud', phase.total === 0
775
+ return sharePage('Sharing on Screw Bugs Cloud', phase._tag === 'preparing' || phase.total === 0
356
776
  ? 'Uploading the report…'
357
- : `Uploading screenshots and videos: ${phase.done} of ${phase.total}.`, { refresh: PROGRESS_REFRESH_S });
777
+ : `Uploading screenshots and videos: ${phase.done} of ${phase.total}.`, {
778
+ refresh: PROGRESS_REFRESH_S,
779
+ follow: { state: state.value, run: entry.jobId, routes: SHARE_PATHS },
780
+ });
358
781
  case 'done':
359
782
  return redirect(phase.resultUrl);
360
783
  case 'failed':
@@ -364,15 +787,23 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
364
787
  });
365
788
  }
366
789
  });
367
- const routes = ({ url, headers, base }) => {
790
+ const routes = ({ method, url, headers, base, body }) => {
368
791
  const parsed = new URL(url, base);
792
+ if (method === 'POST' && parsed.pathname === SHARE_PATHS.encoded)
793
+ return encoded(parsed.searchParams, headers, base, body);
794
+ if (method === 'POST' && parsed.pathname !== SHARE_PATHS.start)
795
+ return Effect.succeed(undefined);
369
796
  switch (parsed.pathname) {
370
797
  case SHARE_PATHS.start:
371
- return start(parsed.searchParams, headers, base);
798
+ return start(method, parsed.searchParams, headers, base);
372
799
  case SHARE_PATHS.callback:
373
800
  return callback(parsed.searchParams);
374
801
  case SHARE_PATHS.progress:
375
802
  return progress(parsed.searchParams);
803
+ case SHARE_PATHS.status:
804
+ return status(parsed.searchParams);
805
+ case SHARE_PATHS.source:
806
+ return screenshot(parsed.searchParams, headers, base);
376
807
  default:
377
808
  return Effect.succeed(undefined);
378
809
  }