@botiverse/porthole 0.13.0 → 0.14.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.
Files changed (68) hide show
  1. package/dist/annotate/types.d.ts +32 -3
  2. package/dist/annotate/types.js +4 -0
  3. package/dist/annotate/validate.js +19 -2
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/compile/policy.d.ts +7 -0
  6. package/dist/compile/policy.js +13 -1
  7. package/dist/config/schema.d.ts +11 -0
  8. package/dist/config/validate.js +19 -0
  9. package/dist/conformance/harness-source.js +1 -1
  10. package/dist/displays/displays.js +3 -1
  11. package/dist/guide/limits.js +1 -1
  12. package/dist/host/create-host.d.ts +2 -0
  13. package/dist/host/create-host.js +73 -3
  14. package/dist/host/pass-on.d.ts +15 -0
  15. package/dist/host/pass-on.js +65 -0
  16. package/dist/host/types.d.ts +22 -0
  17. package/dist/index.d.ts +4 -1
  18. package/dist/index.js +4 -1
  19. package/dist/isolation/types.d.ts +8 -0
  20. package/dist/isolation/types.js +8 -0
  21. package/dist/platform/focus-guard.d.ts +71 -2
  22. package/dist/platform/focus-guard.js +187 -12
  23. package/dist/platform/types.d.ts +8 -1
  24. package/dist/platform/web.js +60 -4
  25. package/dist/presets/presets.d.ts +2 -0
  26. package/dist/presets/presets.js +1 -0
  27. package/dist/server/files.js +19 -3
  28. package/dist/server/index.d.ts +1 -0
  29. package/dist/server/index.js +4 -0
  30. package/dist/server/nested.d.ts +37 -0
  31. package/dist/server/nested.js +70 -0
  32. package/dist/server/server.js +57 -7
  33. package/dist/shell/annotate.d.ts +1 -1
  34. package/dist/shell/annotate.js +157 -7
  35. package/dist/shell/frame.d.ts +45 -0
  36. package/dist/shell/frame.js +250 -0
  37. package/dist/shell/plan.js +2 -1
  38. package/dist/shell/runtime.js +49 -14
  39. package/docs/ADOPTING.md +56 -2
  40. package/docs/ARCHITECTURE.md +23 -0
  41. package/docs/DECISIONS.md +209 -0
  42. package/docs/DESIGN.md +9 -0
  43. package/docs/THREAT_MODEL.md +75 -5
  44. package/package.json +1 -1
  45. package/src/annotate/types.ts +28 -3
  46. package/src/annotate/validate.ts +23 -2
  47. package/src/compile/policy.ts +14 -1
  48. package/src/config/schema.ts +11 -0
  49. package/src/config/validate.ts +23 -0
  50. package/src/displays/displays.ts +3 -1
  51. package/src/guide/limits.ts +1 -1
  52. package/src/host/create-host.ts +76 -4
  53. package/src/host/pass-on.ts +73 -0
  54. package/src/host/types.ts +20 -0
  55. package/src/index.ts +4 -1
  56. package/src/isolation/types.ts +12 -0
  57. package/src/platform/focus-guard.ts +258 -15
  58. package/src/platform/types.ts +8 -1
  59. package/src/platform/web.ts +81 -9
  60. package/src/presets/presets.ts +3 -0
  61. package/src/server/files.ts +19 -3
  62. package/src/server/index.ts +10 -0
  63. package/src/server/nested.ts +86 -0
  64. package/src/server/server.ts +65 -6
  65. package/src/shell/annotate.ts +157 -7
  66. package/src/shell/frame.ts +268 -0
  67. package/src/shell/plan.ts +2 -1
  68. package/src/shell/runtime.ts +49 -14
@@ -11,6 +11,7 @@ import { DEFAULT_ENTRY, lookupFile, requestFilePath, type FileLookup } from "../
11
11
  import { fileTypeOf } from "../files/types.ts";
12
12
  import { isCodeAsset } from "../runtime/requests.ts";
13
13
  import { sha256, utf8 } from "./crypto.ts";
14
+ import { NESTED_FILE_HEADERS } from "./nested.ts";
14
15
  import type { FileBody, StoredAsset, StoredFiles } from "./types.ts";
15
16
 
16
17
  /**
@@ -226,6 +227,8 @@ export async function serveFile(serving: FileServing): Promise<Response> {
226
227
  return nothing(serving, 404, method);
227
228
  }
228
229
  const { type, role } = fileTypeOf(found.path);
230
+ // A nested page (P111): in its shell's child, an opaque origin.
231
+ const nested = serving.compiled.config.nested === true;
229
232
  // In a frame, the version's files are at a sealed address (P083), which their own loads of the
230
233
  // artifact's assets carry as their `Referer` (P091): to this origin only, never another.
231
234
  const referrer =
@@ -242,12 +245,18 @@ export async function serveFile(serving: FileServing): Promise<Response> {
242
245
  // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
243
246
  // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
244
247
  // its own.
248
+ // A nested page's files are on its shell's origin (P111, after the review): every one carries a
249
+ // sandbox, so none opened as a document on its own (a tab, "open image in new tab") runs on that
250
+ // origin. Pages run their scripts, opaque; anything else runs nothing (a file's is inert already,
251
+ // a script's gets one too).
245
252
  const csp =
246
253
  role === "file"
247
254
  ? INERT_FILE_CSP
248
255
  : role === "page"
249
256
  ? servedDocumentCsp(serving.compiled.config, directives)
250
- : serializeCsp(directives);
257
+ : nested
258
+ ? `${serializeCsp(directives)}; sandbox`
259
+ : serializeCsp(directives);
251
260
  const headers = new Headers({
252
261
  "content-type": type,
253
262
  "x-content-type-options": "nosniff",
@@ -263,7 +272,8 @@ export async function serveFile(serving: FileServing): Promise<Response> {
263
272
  if (role === "page") {
264
273
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
265
274
  const html = serving.compiled.shellDocument({
266
- origins: serving.hostOrigins,
275
+ // A nested page hears its shell, on its own origin, never the host (P111).
276
+ origins: nested ? [serving.origin] : serving.hostOrigins,
267
277
  document: await textOf(body),
268
278
  cspMeta: false,
269
279
  ...(referrer === "same-origin" ? { referrer } : {}),
@@ -303,8 +313,14 @@ export async function serveFile(serving: FileServing): Promise<Response> {
303
313
  serving.pinned ? `private, max-age=${YEAR}, immutable` : "private, no-cache",
304
314
  );
305
315
  // Only this origin's own pages load it: no other content origin (a sibling, same-site without
306
- // the public suffix list) can embed it with the viewer's cookie.
316
+ // the public suffix list) can embed it with the viewer's cookie. A nested page's origin is
317
+ // opaque, and its files carry their access in their path, never a cookie (P111).
307
318
  headers.set("cross-origin-resource-policy", "same-origin");
319
+ if (nested) {
320
+ for (const [name, value] of Object.entries(NESTED_FILE_HEADERS)) {
321
+ headers.set(name, value);
322
+ }
323
+ }
308
324
  headers.set("accept-ranges", "bytes");
309
325
  if (role === "file" && type === "application/octet-stream") {
310
326
  headers.set("content-disposition", "attachment");
@@ -70,6 +70,16 @@ export {
70
70
  type D1StatementLike,
71
71
  } from "./tickets.ts";
72
72
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
73
+ // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
74
+ // sealed prefix. `/server` serves them for a config with `nested`; a content Worker of its own
75
+ // answers the same (docs/ADOPTING.md, "Nested pages").
76
+ export {
77
+ NESTED_FILE_HEADERS,
78
+ NESTED_FILES_PREFIX,
79
+ nestedAncestors,
80
+ nestedShellCsp,
81
+ nestedShellResponse,
82
+ } from "./nested.ts";
73
83
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
74
84
  // The page an app serves in conformance test mode (P071).
75
85
  export { conformancePage } from "../conformance/page.ts";
@@ -0,0 +1,86 @@
1
+ import type { CompiledConfig } from "../compile/compile.ts";
2
+ import { servedPermissionsPolicy, serializeCsp, type CspDirective } from "../compile/policy.ts";
3
+ import { frameShellDocument, frameShellScript, type FrameShellOptions } from "../shell/frame.ts";
4
+ import { sha256, utf8 } from "./crypto.ts";
5
+
6
+ /**
7
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
8
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
9
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
10
+ * a host serving its own content origin (its own Worker) answers the same.
11
+ */
12
+
13
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
14
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
15
+
16
+ const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
17
+
18
+ /**
19
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
20
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
21
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
22
+ * this (a framed URL's document never does).
23
+ */
24
+ export function nestedShellCsp(
25
+ script: string,
26
+ origin: string,
27
+ hostOrigins: readonly string[],
28
+ ): string {
29
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
30
+ const directives: CspDirective[] = [
31
+ ["default-src", "'none'"],
32
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
33
+ ["frame-src", files],
34
+ ["connect-src", files],
35
+ ["base-uri", "'none'"],
36
+ ["form-action", "'none'"],
37
+ ["frame-ancestors", ...hostOrigins],
38
+ ];
39
+ return serializeCsp(directives);
40
+ }
41
+
42
+ /**
43
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
44
+ * stored (it carries the page's sealed address), its page at `options.page`.
45
+ */
46
+ export function nestedShellResponse(
47
+ compiled: CompiledConfig,
48
+ options: FrameShellOptions & { readonly origin: string; readonly method?: string },
49
+ ): Response {
50
+ const script = frameShellScript(options);
51
+ const headers = new Headers({
52
+ "content-type": "text/html; charset=utf-8",
53
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
54
+ "cache-control": "no-store",
55
+ "referrer-policy": "no-referrer",
56
+ "x-content-type-options": "nosniff",
57
+ "x-robots-tag": "noindex, nofollow",
58
+ });
59
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
60
+ const permissions = servedPermissionsPolicy(compiled.config);
61
+ if (permissions !== null) {
62
+ headers.set("permissions-policy", permissions);
63
+ }
64
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
65
+ status: 200,
66
+ headers,
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
72
+ * it, the host origins (`frame-ancestors` names every ancestor).
73
+ */
74
+ export const nestedAncestors = (origin: string, frameAncestors: string): string =>
75
+ `${origin} ${frameAncestors}`;
76
+
77
+ /**
78
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
79
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
80
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
81
+ * is their access, never the request's origin.
82
+ */
83
+ export const NESTED_FILE_HEADERS: Readonly<Record<string, string>> = {
84
+ "cross-origin-resource-policy": "cross-origin",
85
+ "access-control-allow-origin": "*",
86
+ };
@@ -13,7 +13,9 @@ import { randomBytes } from "./crypto.ts";
13
13
  import { isHostLabel, reservedLabels } from "./naming.ts";
14
14
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.ts";
15
15
  import { libraryFile } from "./libraries.ts";
16
- import { ownLoad, serveAsset, serveFile } from "./files.ts";
16
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.ts";
17
+ import { nestedAncestors, nestedShellResponse } from "./nested.ts";
18
+ import { DEFAULT_ENTRY } from "../files/paths.ts";
17
19
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.ts";
18
20
  import {
19
21
  assetCodeRuns,
@@ -520,6 +522,8 @@ export function createServer(options: ServerOptions): PortholeServer {
520
522
  async function documentOf(instance: InstanceRef): Promise<
521
523
  | {
522
524
  readonly html: string;
525
+ /** An artifact's own page, before the shell (a nested page's is made apart, P111). */
526
+ readonly document?: string;
523
527
  readonly compiled: CompiledConfig;
524
528
  /** Whether its CSP opens its artifact's asset library (P089): an artifact's page. */
525
529
  readonly assets: boolean;
@@ -554,6 +558,7 @@ export function createServer(options: ServerOptions): PortholeServer {
554
558
  }
555
559
  return {
556
560
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
561
+ document: stored.html,
557
562
  compiled: config,
558
563
  assets: true,
559
564
  };
@@ -807,10 +812,14 @@ export function createServer(options: ServerOptions): PortholeServer {
807
812
  }
808
813
  }
809
814
 
810
- function documentHeaders(csp: string, permissions: string | null): Headers {
815
+ function documentHeaders(
816
+ csp: string,
817
+ permissions: string | null,
818
+ ancestors: string = frameAncestors,
819
+ ): Headers {
811
820
  return new Headers({
812
821
  "content-type": "text/html; charset=utf-8",
813
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
822
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
814
823
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
815
824
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
816
825
  "cache-control": "no-store",
@@ -905,12 +914,16 @@ export function createServer(options: ServerOptions): PortholeServer {
905
914
  }
906
915
  const access = await sealedAccess(request, label, token);
907
916
  if (access === null) {
908
- return page(
917
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
918
+ // config without nesting never frames this address but at the host.
919
+ return statusPage(
909
920
  401,
910
921
  "This has ended",
911
922
  "Content here opens for a while. Open it again from the app that showed it.",
923
+ nestedAncestors(origin, frameAncestors),
912
924
  method,
913
925
  "session",
926
+ [...options.hostOrigins, origin],
914
927
  );
915
928
  }
916
929
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
@@ -1021,6 +1034,43 @@ export function createServer(options: ServerOptions): PortholeServer {
1021
1034
  if (served === null) {
1022
1035
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1023
1036
  }
1037
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
1038
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
1039
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
1040
+ const nested = served.compiled.config.nested === true;
1041
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
1042
+ if (nested && !sealedAt) {
1043
+ if (!isNavigation(request)) {
1044
+ return page(404, "Not found", "This page's files are at its own address.", method);
1045
+ }
1046
+ const sealed = await sealFiles(access);
1047
+ let rest = "";
1048
+ if ("files" in served) {
1049
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
1050
+ rest =
1051
+ at !== undefined && at.rest !== ""
1052
+ ? at.rest
1053
+ : entry.includes("/")
1054
+ ? entry
1055
+ .split("/")
1056
+ .map((segment) => encodeURIComponent(segment))
1057
+ .join("/")
1058
+ : "";
1059
+ }
1060
+ const shell = nestedShellResponse(served.compiled, {
1061
+ origin: access.origin,
1062
+ origins: options.hostOrigins,
1063
+ page: `${access.origin}${sealed.base}${rest}`,
1064
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
1065
+ method,
1066
+ });
1067
+ if (cookie !== null) {
1068
+ shell.headers.set("set-cookie", cookie);
1069
+ }
1070
+ return shell;
1071
+ }
1072
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
1073
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
1024
1074
  if ("files" in served) {
1025
1075
  if (at !== undefined) {
1026
1076
  return serveFile({
@@ -1034,7 +1084,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1034
1084
  source: at.source,
1035
1085
  compiled: served.compiled,
1036
1086
  hostOrigins: options.hostOrigins,
1037
- frameAncestors,
1087
+ frameAncestors: ancestors,
1038
1088
  ...versionOf(access.instance),
1039
1089
  });
1040
1090
  }
@@ -1071,11 +1121,20 @@ export function createServer(options: ServerOptions): PortholeServer {
1071
1121
  served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives,
1072
1122
  ),
1073
1123
  servedPermissionsPolicy(config),
1124
+ ancestors,
1074
1125
  );
1075
1126
  if (cookie !== null) {
1076
1127
  headers.set("set-cookie", cookie);
1077
1128
  }
1078
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
1129
+ // A nested page's document takes messages from its shell, on its own origin (P111).
1130
+ const html = nested
1131
+ ? served.compiled.shellDocument({
1132
+ origins: [access.origin],
1133
+ document: served.document ?? "",
1134
+ cspMeta: false,
1135
+ })
1136
+ : served.html;
1137
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
1079
1138
  }
1080
1139
 
1081
1140
  /**
@@ -8,7 +8,7 @@
8
8
  * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
9
9
  * - picking an element: the element under the pointer (or finger) is outlined with its name; a
10
10
  * click or tap picks it, and the content's own handlers never see that click (unless the content
11
- * patched the DOM's built-ins, P105); Escape cancels;
11
+ * patched the DOM's built-ins, P105); Escape cancels (while selecting text too, P112);
12
12
  * - selecting text: each selection that settles is reported, with where it is, and its clearing;
13
13
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
14
14
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the
@@ -39,6 +39,8 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
39
39
  cancelled: "porthole/annotate.cancelled",
40
40
  anchored: "porthole/annotate.anchored",
41
41
  activated: "porthole/annotate.activated",
42
+ track: "porthole/annotate.track",
43
+ tracked: "porthole/annotate.tracked",
42
44
  };
43
45
  // The DOM's own functions, taken before content runs.
44
46
  const elementFromPoint = Document.prototype.elementFromPoint;
@@ -51,6 +53,9 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
51
53
  const elementRect = Element.prototype.getBoundingClientRect;
52
54
  const rangeRect = Range.prototype.getBoundingClientRect;
53
55
  const rangeRects = Range.prototype.getClientRects;
56
+ const setStart = Range.prototype.setStart;
57
+ const setStartBefore = Range.prototype.setStartBefore;
58
+ const compareBoundaryPoints = Range.prototype.compareBoundaryPoints;
54
59
  const attachShadow = Element.prototype.attachShadow;
55
60
  const getAttribute = Element.prototype.getAttribute;
56
61
  const listenOn = EventTarget.prototype.addEventListener;
@@ -389,7 +394,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
389
394
  return shadow;
390
395
  };
391
396
 
392
- let mode = { elements: false, text: false };
397
+ let mode = { elements: false, text: false, hold: false };
393
398
  let hover = null;
394
399
  let marks = [];
395
400
  // The markers as last drawn, for a click to find: { id, element }. Each mark keeps its
@@ -817,7 +822,76 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
817
822
  }
818
823
  };
819
824
 
820
- const resultOf = (mark) => (mark.found === null ? { id: mark.id, state: "orphaned" } : { id: mark.id, state: "attached", rect: box(rectOf(mark.found)) });
825
+ // The mark the host follows (P112): its box at each animation frame where it moved, at most
826
+ // one every 16 ms, read through the platform's own frame clock (taken before content runs).
827
+ const nextFrame = window.requestAnimationFrame.bind(window);
828
+ let tracking = null;
829
+ let trackedBox = null;
830
+ let trackedAt = 0;
831
+ let trackFrame = 0;
832
+ const trackTick = () => {
833
+ trackFrame = 0;
834
+ if (tracking === null) {
835
+ return;
836
+ }
837
+ const mark = marks.find((each) => each.id === tracking);
838
+ if (mark !== undefined && mark.found !== null) {
839
+ const rect = box(rectOf(mark.found));
840
+ const now = performance.now();
841
+ if (apart(trackedBox, rect) && now - trackedAt >= 16) {
842
+ trackedBox = rect;
843
+ trackedAt = now;
844
+ tell(M.tracked, { id: tracking, rect });
845
+ }
846
+ }
847
+ trackFrame = nextFrame(trackTick);
848
+ };
849
+ const track = (id) => {
850
+ tracking = typeof id === "string" ? id : null;
851
+ trackedBox = null;
852
+ if (tracking !== null && trackFrame === 0) {
853
+ trackFrame = nextFrame(trackTick);
854
+ }
855
+ };
856
+
857
+ // Where each found mark starts in the document, in order (P112): its place in a list the host
858
+ // sorts, offscreen ones too. Read now, every time results are told.
859
+ const startOf = (found) => {
860
+ const range = createRange.call(document);
861
+ if (found.range) {
862
+ setStart.call(range, found.range.startContainer, found.range.startOffset);
863
+ } else {
864
+ setStartBefore.call(range, found.element);
865
+ }
866
+ return range;
867
+ };
868
+ const ordersOf = () => {
869
+ const placed = [];
870
+ for (const mark of marks) {
871
+ if (mark.found !== null) {
872
+ try {
873
+ placed.push({ mark, start: startOf(mark.found) });
874
+ } catch (_) {}
875
+ }
876
+ }
877
+ placed.sort((a, b) => {
878
+ try {
879
+ return compareBoundaryPoints.call(a.start, Range.START_TO_START, b.start);
880
+ } catch (_) {
881
+ return 0;
882
+ }
883
+ });
884
+ const orders = new Map();
885
+ placed.forEach((each, at) => orders.set(each.mark, at));
886
+ return orders;
887
+ };
888
+ const resultOf = (mark, orders) => {
889
+ if (mark.found === null) {
890
+ return { id: mark.id, state: "orphaned" };
891
+ }
892
+ const order = (orders || ordersOf()).get(mark);
893
+ return Object.assign({ id: mark.id, state: "attached", rect: box(rectOf(mark.found)) }, order === undefined ? {} : { order });
894
+ };
821
895
  // Two boxes more than 0.5 px apart on any side (or one of them unknown).
822
896
  const apart = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.5 || Math.abs(a.y - b.y) > 0.5 || Math.abs(a.width - b.width) > 0.5 || Math.abs(a.height - b.height) > 0.5;
823
897
  // What the host was last told of each mark (mark.told), so a settle tells only what moved.
@@ -826,7 +900,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
826
900
  if (!told || told.state !== result.state) {
827
901
  return true;
828
902
  }
829
- return result.state === "attached" && apart(told.rect, result.rect);
903
+ return result.state === "attached" && (apart(told.rect, result.rect) || told.order !== result.order);
830
904
  };
831
905
  const report = (pairs) => {
832
906
  if (pairs.length > 0) {
@@ -836,7 +910,10 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
836
910
  tell(M.anchored, { results: pairs.map((pair) => pair.result) });
837
911
  }
838
912
  };
839
- const resultsOf = (only) => marks.map((mark) => ({ mark, result: resultOf(mark) })).filter((pair) => !only || moved(pair.mark, pair.result));
913
+ const resultsOf = (only) => {
914
+ const orders = ordersOf();
915
+ return marks.map((mark) => ({ mark, result: resultOf(mark, orders) })).filter((pair) => !only || moved(pair.mark, pair.result));
916
+ };
840
917
  // Finds every mark again; tells the host every result (after show, or when a state changed),
841
918
  // only the marks that moved (once the content is quiet), or nothing.
842
919
  const anchorAll = (all, quiet) => {
@@ -1142,6 +1219,66 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1142
1219
  redraw();
1143
1220
  }
1144
1221
  }, true);
1222
+
1223
+ // Holding a block (P112, hold mode): a finger held still for 500 ms selects the block under
1224
+ // it, and the click its release makes is the shell's; every other tap is the page's, as is
1225
+ // any mouse. On the platform's own timer (taken before content runs).
1226
+ const later = window.setTimeout.bind(window);
1227
+ const cancelLater = window.clearTimeout.bind(window);
1228
+ const HOLD_MS = 500;
1229
+ const HOLD_SLOP = 10;
1230
+ let holding = null;
1231
+ let swallowUntil = 0;
1232
+ const endHold = () => {
1233
+ if (holding !== null) {
1234
+ cancelLater(holding.timer);
1235
+ holding = null;
1236
+ }
1237
+ };
1238
+ window.addEventListener("pointerdown", (event) => {
1239
+ if (!mode.hold || mode.elements || event.pointerType !== "touch" || !event.isPrimary) {
1240
+ return;
1241
+ }
1242
+ endHold();
1243
+ const x = event.clientX;
1244
+ const y = event.clientY;
1245
+ holding = {
1246
+ x,
1247
+ y,
1248
+ timer: later(() => {
1249
+ holding = null;
1250
+ if (!mode.hold) {
1251
+ return;
1252
+ }
1253
+ const element = under(x, y);
1254
+ const anchor = element === null ? null : elementAnchor(element, textIndex());
1255
+ if (anchor === null) {
1256
+ return;
1257
+ }
1258
+ swallowUntil = performance.now() + 2000;
1259
+ tell(M.selected, { anchor, rect: box(elementRect.call(element)) });
1260
+ }, HOLD_MS),
1261
+ };
1262
+ }, true);
1263
+ window.addEventListener("pointermove", (event) => {
1264
+ if (holding !== null && event.pointerType === "touch" && Math.abs(event.clientX - holding.x) + Math.abs(event.clientY - holding.y) > HOLD_SLOP) {
1265
+ endHold();
1266
+ }
1267
+ }, true);
1268
+ for (const type of ["pointerup", "pointercancel"]) {
1269
+ window.addEventListener(type, endHold, true);
1270
+ }
1271
+ for (const type of ["click", "contextmenu"]) {
1272
+ window.addEventListener(type, (event) => {
1273
+ if (swallowUntil > performance.now()) {
1274
+ if (type === "click") {
1275
+ swallowUntil = 0;
1276
+ }
1277
+ event.preventDefault();
1278
+ event.stopImmediatePropagation();
1279
+ }
1280
+ }, true);
1281
+ }
1145
1282
  window.addEventListener("click", (event) => {
1146
1283
  if (!mode.elements) {
1147
1284
  return;
@@ -1170,7 +1307,10 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1170
1307
  tell(M.selected, { anchor, rect: box(elementRect.call(element)) });
1171
1308
  }, true);
1172
1309
  window.addEventListener("keydown", (event) => {
1173
- if (mode.elements && event.key === "Escape") {
1310
+ if (event.key !== "Escape") {
1311
+ return;
1312
+ }
1313
+ if (mode.elements) {
1174
1314
  event.preventDefault();
1175
1315
  event.stopImmediatePropagation();
1176
1316
  mode = { elements: false, text: mode.text };
@@ -1178,6 +1318,12 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1178
1318
  setCursor(false);
1179
1319
  draw();
1180
1320
  tell(M.cancelled, {});
1321
+ return;
1322
+ }
1323
+ // Selecting text (P112): the person wants out too. The key stays the page's (a page that
1324
+ // closes its own dialog on Escape still does); the host decides what ends.
1325
+ if (mode.text) {
1326
+ tell(M.cancelled, {});
1181
1327
  }
1182
1328
  }, true);
1183
1329
 
@@ -1244,7 +1390,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1244
1390
  const params = data.params !== null && typeof data.params === "object" ? data.params : {};
1245
1391
  switch (data.method) {
1246
1392
  case M.start:
1247
- mode = { elements: params.elements === true, text: params.text === true };
1393
+ mode = { elements: params.elements === true, text: params.text === true, hold: params.elements === "hold" };
1248
1394
  hover = null;
1249
1395
  reported = null;
1250
1396
  reportedBox = null;
@@ -1276,7 +1422,11 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1276
1422
  case M.focus:
1277
1423
  focus(String(params.id));
1278
1424
  break;
1425
+ case M.track:
1426
+ track(params.id);
1427
+ break;
1279
1428
  case M.clear:
1429
+ track(null);
1280
1430
  pendingFocus = null;
1281
1431
  marks = [];
1282
1432
  active = null;