@botiverse/porthole 0.14.0 → 0.14.1

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 (41) hide show
  1. package/CHANGELOG.md +770 -0
  2. package/dist/annotate/types.d.ts +4 -1
  3. package/dist/annotate/types.js +2 -0
  4. package/dist/annotate/validate.d.ts +2 -1
  5. package/dist/annotate/validate.js +11 -4
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/compile/policy.js +2 -2
  8. package/dist/conformance/harness-source.js +1 -1
  9. package/dist/host/create-host.js +5 -0
  10. package/dist/host/types.d.ts +7 -0
  11. package/dist/react/frame.d.ts +4 -3
  12. package/dist/server/index.d.ts +1 -1
  13. package/dist/server/index.js +4 -3
  14. package/dist/server/naming.js +4 -0
  15. package/dist/server/nested.d.ts +24 -2
  16. package/dist/server/nested.js +28 -2
  17. package/dist/server/server.js +145 -25
  18. package/dist/server/types.d.ts +5 -0
  19. package/dist/shell/annotate.d.ts +3 -2
  20. package/dist/shell/annotate.js +22 -2
  21. package/dist/shell/runtime.d.ts +6 -0
  22. package/dist/shell/runtime.js +11 -1
  23. package/docs/ADOPTING.md +36 -7
  24. package/docs/ARCHITECTURE.md +10 -5
  25. package/docs/DECISIONS.md +207 -1
  26. package/docs/DESIGN.md +12 -4
  27. package/docs/THREAT_MODEL.md +30 -3
  28. package/package.json +6 -5
  29. package/src/annotate/types.ts +4 -1
  30. package/src/annotate/validate.ts +11 -6
  31. package/src/compile/policy.ts +2 -2
  32. package/src/host/create-host.ts +5 -0
  33. package/src/host/types.ts +7 -0
  34. package/src/react/frame.tsx +4 -3
  35. package/src/server/index.ts +6 -2
  36. package/src/server/naming.ts +4 -0
  37. package/src/server/nested.ts +32 -2
  38. package/src/server/server.ts +168 -24
  39. package/src/server/types.ts +5 -0
  40. package/src/shell/annotate.ts +22 -2
  41. package/src/shell/runtime.ts +12 -1
@@ -71,14 +71,18 @@ export {
71
71
  } from "./tickets.ts";
72
72
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
73
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").
74
+ // sealed prefix, all on the shell's own label (P114, `nestedLabelOf`). `/server` serves them for a
75
+ // config with `nested`; a content Worker of its own answers the same (docs/ADOPTING.md, "Nested
76
+ // pages").
76
77
  export {
78
+ isNestedLabel,
77
79
  NESTED_FILE_HEADERS,
78
80
  NESTED_FILES_PREFIX,
79
81
  nestedAncestors,
82
+ nestedLabelOf,
80
83
  nestedShellCsp,
81
84
  nestedShellResponse,
85
+ PORTHOLE_LABEL_PREFIX,
82
86
  } from "./nested.ts";
83
87
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
84
88
  // The page an app serves in conformance test mode (P071).
@@ -42,6 +42,10 @@ export function prefixedName(prefix: string): Naming & {
42
42
  "A name prefix is a lowercase letter, then letters or digits, then '-' (a-)",
43
43
  );
44
44
  }
45
+ // Porthole's own labels (a nested page's shell's, P114) are never a scope's.
46
+ if (prefix === "porthole-") {
47
+ throw new TypeError("The name prefix porthole- is Porthole's own: choose another (a-)");
48
+ }
45
49
  const name = (scope: string): string => {
46
50
  const label = `${prefix}${scope}`;
47
51
  if (!ID.test(scope) || !isHostLabel(label)) {
@@ -2,14 +2,44 @@ import type { CompiledConfig } from "../compile/compile.ts";
2
2
  import { servedPermissionsPolicy, serializeCsp, type CspDirective } from "../compile/policy.ts";
3
3
  import { frameShellDocument, frameShellScript, type FrameShellOptions } from "../shell/frame.ts";
4
4
  import { sha256, utf8 } from "./crypto.ts";
5
+ import { base32 } from "./keys.ts";
5
6
 
6
7
  /**
7
8
  * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
8
9
  * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
9
10
  * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
10
11
  * a host serving its own content origin (its own Worker) answers the same.
12
+ *
13
+ * All of it is served on the shell's own label (P114, `nestedLabelOf`), never on the scope's: every
14
+ * other display of the scope runs agent-made content on the scope's origin with
15
+ * `allow-same-origin`, which would be same-origin with the shell, its realm and the page's sealed
16
+ * address.
11
17
  */
12
18
 
19
+ /**
20
+ * The start of every label Porthole serves for itself on a content domain (P114): no host's naming
21
+ * may make one (`content.name` is refused one, and `prefixedName` won't take the prefix).
22
+ */
23
+ export const PORTHOLE_LABEL_PREFIX = "porthole-";
24
+
25
+ const NESTED_LABEL = /^porthole-[a-z2-7]{24}$/u;
26
+
27
+ /**
28
+ * The label a nested page's shell is served on (P114), for its scope's label: `porthole-` and 24
29
+ * base32 characters of the label's SHA-256, one per scope, the same for every nested page of it. No
30
+ * content label is ever one (a keyed label has no hyphen, a host's is refused the prefix), so
31
+ * nothing but a nested page's shell, its opaque page, that page's files and Porthole's status pages
32
+ * is ever served on it: no other display's content runs there with `allow-same-origin`. Not a
33
+ * secret: anyone who knows the scope's label may work it out. A content Worker of a host's own
34
+ * serves its nested pages on it too.
35
+ */
36
+ export function nestedLabelOf(label: string): string {
37
+ return `${PORTHOLE_LABEL_PREFIX}${base32(sha256(utf8(`porthole/nested/${label}`)).subarray(0, 15))}`;
38
+ }
39
+
40
+ /** Whether a label is a nested page's shell's own (`nestedLabelOf`'s form). */
41
+ export const isNestedLabel = (label: string): boolean => NESTED_LABEL.test(label);
42
+
13
43
  /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
14
44
  export const NESTED_FILES_PREFIX = "/__porthole/f/";
15
45
 
@@ -68,8 +98,8 @@ export function nestedShellResponse(
68
98
  }
69
99
 
70
100
  /**
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).
101
+ * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
102
+ * above it, the host origins (`frame-ancestors` names every ancestor).
73
103
  */
74
104
  export const nestedAncestors = (origin: string, frameAncestors: string): string =>
75
105
  `${origin} ${frameAncestors}`;
@@ -14,7 +14,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
16
  import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.ts";
17
- import { nestedAncestors, nestedShellResponse } from "./nested.ts";
17
+ import {
18
+ isNestedLabel,
19
+ nestedAncestors,
20
+ nestedLabelOf,
21
+ nestedShellResponse,
22
+ PORTHOLE_LABEL_PREFIX,
23
+ } from "./nested.ts";
18
24
  import { DEFAULT_ENTRY } from "../files/paths.ts";
19
25
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.ts";
20
26
  import {
@@ -70,6 +76,23 @@ const BASE = /^\/(?:(?!\.{1,2}\/)[A-Za-z0-9._:~-]{1,200}\/){0,16}$/u;
70
76
  const ENTER_PATH = "/__porthole/enter";
71
77
  /** Where a redirect entry's code is redeemed, before its clean address (P068). */
72
78
  const ENTRY_PATH = "/__porthole/entry";
79
+ /** How long a nested page's ticket from its clean address to its shell's label lasts (P114). */
80
+ const HOP_SECONDS = 60;
81
+ /**
82
+ * A path below a file set's base, as a hop's ticket carries it (P114): a relative path of URL path
83
+ * characters, no empty segment but a last one, no dot segment (encoded or not), no query.
84
+ */
85
+ const isPageRest = (rest: unknown): rest is string =>
86
+ typeof rest === "string" &&
87
+ rest.length > 0 &&
88
+ rest.length <= MAX_PATH &&
89
+ /^[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/u.test(rest) &&
90
+ rest
91
+ .split("/")
92
+ .every(
93
+ (segment, index, all) =>
94
+ (segment !== "" || index === all.length - 1) && !/^(?:\.|%2e){1,2}$/iu.test(segment),
95
+ );
73
96
  /** How long a redirect entry may take (the person may sign in on the way), and its code. */
74
97
  const ENTRY_STATE_MS = 5 * 60_000;
75
98
  const ENTRY_CODE_SECONDS = 60;
@@ -311,16 +334,39 @@ export function createServer(options: ServerOptions): PortholeServer {
311
334
  return keys.label(scope);
312
335
  }
313
336
  const label = content.name(scope);
314
- if (!isHostLabel(label) || isReserved(label)) {
337
+ if (!isHostLabel(label) || isReserved(label) || label.startsWith(PORTHOLE_LABEL_PREFIX)) {
315
338
  throw new TypeError(
316
- `content.name gave ${JSON.stringify(label)} for a scope: it must be one lowercase DNS label (a-z 0-9 -, at most 63, not xn--), not reserved`,
339
+ `content.name gave ${JSON.stringify(label)} for a scope: it must be one lowercase DNS label (a-z 0-9 -, at most 63, not xn--), not reserved, not Porthole's own (${PORTHOLE_LABEL_PREFIX}…)`,
317
340
  );
318
341
  }
319
342
  return label;
320
343
  };
321
- /** Whether a request's label may be one this server named. */
344
+ /**
345
+ * The label an instance is served on: its scope's, or a nested page's shell's own (P114), on
346
+ * which nothing but nested pages' shells, their pages and those pages' files is ever served.
347
+ * Every other display of the scope runs agent-made content on the scope's origin with
348
+ * `allow-same-origin`: on that origin, the shell's realm (its word to the host, the page's
349
+ * sealed address) would be theirs.
350
+ */
351
+ const labelFor = (instance: InstanceRef): string => {
352
+ const label = nameOf(instance.scope);
353
+ if (instance.document.kind !== "artifact" || compiledFor(instance)?.config.nested !== true) {
354
+ return label;
355
+ }
356
+ const own = nestedLabelOf(label);
357
+ if (isReserved(own)) {
358
+ throw new TypeError(
359
+ `content.reserved holds ${own}, a nested page's shell's label: reserve no ${PORTHOLE_LABEL_PREFIX} label`,
360
+ );
361
+ }
362
+ return own;
363
+ };
364
+ /** Whether a request's label may be one this server named (a nested page's shell's, P114). */
322
365
  const ours = (label: string): boolean =>
323
- !isReserved(label) && (content.name === undefined ? LABEL.test(label) : isHostLabel(label));
366
+ !isReserved(label) &&
367
+ (isNestedLabel(label) ||
368
+ (!label.startsWith(PORTHOLE_LABEL_PREFIX) &&
369
+ (content.name === undefined ? LABEL.test(label) : isHostLabel(label))));
324
370
  const secure = content.scheme === "https";
325
371
  const defaultPort = secure ? 443 : 80;
326
372
  const portPart =
@@ -330,6 +376,7 @@ export function createServer(options: ServerOptions): PortholeServer {
330
376
  const contentSource = `${content.scheme}://*.${domain}${portPart}`;
331
377
  const sampleHost = `${keys.label("")}.${domain}`;
332
378
  const sampleOrigin = originOfLabel(keys.label(""));
379
+ const sampleNestedOrigin = originOfLabel(nestedLabelOf(keys.label("")));
333
380
  const authorize = options.authorize;
334
381
  const authorizeTtl = authorize?.ttlSeconds ?? 0;
335
382
  if (!Number.isInteger(authorizeTtl) || authorizeTtl < 0 || authorizeTtl > 300) {
@@ -471,7 +518,13 @@ export function createServer(options: ServerOptions): PortholeServer {
471
518
  `The config ${JSON.stringify(name)} (${config.mode}, ${config.isolation}) can't serve a ${kind}: it needs ${MODES[kind].join(" or ")} mode with domain isolation`,
472
519
  );
473
520
  }
474
- if (!config.contentOrigins.some((source) => originMatchesSource(sampleOrigin, source))) {
521
+ // A nested page's shell is on a label of its own (P114): its frame source is the same.
522
+ const samples = config.nested === true ? [sampleOrigin, sampleNestedOrigin] : [sampleOrigin];
523
+ if (
524
+ !samples.every((sample) =>
525
+ config.contentOrigins.some((source) => originMatchesSource(sample, source)),
526
+ )
527
+ ) {
475
528
  throw new TypeError(
476
529
  `The config ${JSON.stringify(name)}'s contentOrigins don't include this server's (${contentSource})`,
477
530
  );
@@ -687,7 +740,7 @@ export function createServer(options: ServerOptions): PortholeServer {
687
740
  }
688
741
  let named: string;
689
742
  try {
690
- named = nameOf(instance.scope);
743
+ named = labelFor(instance);
691
744
  } catch {
692
745
  continue;
693
746
  }
@@ -795,8 +848,15 @@ export function createServer(options: ServerOptions): PortholeServer {
795
848
  return best;
796
849
  }
797
850
 
798
- /** A taken ticket, if it is good for `label`'s origin. */
799
- async function take(ticket: string | null, label: string): Promise<TicketRecord | null> {
851
+ /**
852
+ * A taken ticket, if it is good for `label`'s origin: its instance's own (a nested page's shell's,
853
+ * P114), or for an entry code (`entry`) its scope's, where a clean address is.
854
+ */
855
+ async function take(
856
+ ticket: string | null,
857
+ label: string,
858
+ entry = false,
859
+ ): Promise<TicketRecord | null> {
800
860
  if (ticket === null || ticket.length === 0 || ticket.length > 128) {
801
861
  return null;
802
862
  }
@@ -806,7 +866,9 @@ export function createServer(options: ServerOptions): PortholeServer {
806
866
  }
807
867
  try {
808
868
  const instance = cleanInstance(record.instance);
809
- return nameOf(instance.scope) === label ? { ...record, instance } : null;
869
+ return (entry ? nameOf(instance.scope) : labelFor(instance)) === label
870
+ ? { ...record, instance }
871
+ : null;
810
872
  } catch {
811
873
  return null;
812
874
  }
@@ -856,7 +918,13 @@ export function createServer(options: ServerOptions): PortholeServer {
856
918
  } catch {
857
919
  return null;
858
920
  }
859
- if (!open || instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
921
+ let named: string;
922
+ try {
923
+ named = labelFor(instance);
924
+ } catch {
925
+ return null;
926
+ }
927
+ if (!open || instance.document.kind !== "artifact" || named !== label) {
860
928
  return null;
861
929
  }
862
930
  return {
@@ -930,7 +998,8 @@ export function createServer(options: ServerOptions): PortholeServer {
930
998
  // sends a frame's path, where some send no Referer that names it.
931
999
  const blob = SEALED_ASSET.exec(rest)?.[1];
932
1000
  if (blob !== undefined) {
933
- if (options.assets === undefined) {
1001
+ // A nested page loads no assets (its config refuses them): none on its shell's label (P114).
1002
+ if (options.assets === undefined || isNestedLabel(label)) {
934
1003
  return page(404, "Not found", "This address names no content.", method);
935
1004
  }
936
1005
  return (
@@ -987,8 +1056,10 @@ export function createServer(options: ServerOptions): PortholeServer {
987
1056
  // The ticket's own answer carries the document: an engine that keeps no cookie in a frame
988
1057
  // still shows it. The cookie serves what follows (a reload), where the engine keeps it.
989
1058
  const record = method === "GET" ? await take(url.searchParams.get("ticket"), label) : null;
1059
+ // An entry code opens its clean address alone, through its own browser's nonce (P068, P114).
990
1060
  if (
991
1061
  record !== null &&
1062
+ record.entry === undefined &&
992
1063
  record.instance.document.kind !== "external" &&
993
1064
  keys.instanceKey(record.instance) === key
994
1065
  ) {
@@ -1012,7 +1083,10 @@ export function createServer(options: ServerOptions): PortholeServer {
1012
1083
  "session",
1013
1084
  );
1014
1085
  }
1015
- return serveAccess(request, access, cookie);
1086
+ // A nested page's hop from its clean address (P114): the page below its base it was entered at.
1087
+ const asked = cookie === null ? undefined : record?.page;
1088
+ const rest = isPageRest(asked) ? asked : undefined;
1089
+ return serveAccess(request, access, cookie, undefined, rest);
1016
1090
  }
1017
1091
 
1018
1092
  /**
@@ -1024,6 +1098,8 @@ export function createServer(options: ServerOptions): PortholeServer {
1024
1098
  access: Access,
1025
1099
  cookie: string | null,
1026
1100
  at?: FilesAt,
1101
+ /** A nested page's path below its files' base, from its hop's ticket (P114). */
1102
+ pageAt?: string,
1027
1103
  ): Promise<Response> {
1028
1104
  const method = request.method.toUpperCase();
1029
1105
  const refusal = await denied(request, access);
@@ -1043,19 +1119,27 @@ export function createServer(options: ServerOptions): PortholeServer {
1043
1119
  if (!isNavigation(request)) {
1044
1120
  return page(404, "Not found", "This page's files are at its own address.", method);
1045
1121
  }
1122
+ // Its shell is served on its own label alone (P114): a clean address, entered on the scope's
1123
+ // label (P068), goes there with a one-time ticket of its own, for what is left of its session.
1124
+ const own = originOfLabel(labelFor(access.instance));
1125
+ if (access.origin !== own) {
1126
+ return hop(access, own, "files" in served && at !== undefined ? at.rest : "");
1127
+ }
1046
1128
  const sealed = await sealFiles(access);
1047
1129
  let rest = "";
1048
1130
  if ("files" in served) {
1049
1131
  const entry = served.files.entry ?? DEFAULT_ENTRY;
1050
1132
  rest =
1051
- at !== undefined && at.rest !== ""
1052
- ? at.rest
1053
- : entry.includes("/")
1054
- ? entry
1055
- .split("/")
1056
- .map((segment) => encodeURIComponent(segment))
1057
- .join("/")
1058
- : "";
1133
+ pageAt !== undefined
1134
+ ? pageAt
1135
+ : at !== undefined && at.rest !== ""
1136
+ ? at.rest
1137
+ : entry.includes("/")
1138
+ ? entry
1139
+ .split("/")
1140
+ .map((segment) => encodeURIComponent(segment))
1141
+ .join("/")
1142
+ : "";
1059
1143
  }
1060
1144
  const shell = nestedShellResponse(served.compiled, {
1061
1145
  origin: access.origin,
@@ -1137,6 +1221,39 @@ export function createServer(options: ServerOptions): PortholeServer {
1137
1221
  return new Response(method === "HEAD" ? null : html, { status: 200, headers });
1138
1222
  }
1139
1223
 
1224
+ /**
1225
+ * A nested page entered at its clean address (P114), whose shell is never served there: on to the
1226
+ * shell's own label, with a one-time ticket for the same access (its viewer, its subject, what is
1227
+ * left of its session) and the path below its base it was entered at. Only this server's own
1228
+ * answer carries the ticket, as `issue`'s frame address does; the host's check already let the
1229
+ * request in.
1230
+ */
1231
+ async function hop(access: Access, own: string, rest: string): Promise<Response> {
1232
+ const now = Date.now();
1233
+ const ticket = newTicket();
1234
+ await tickets.put(ticketId(ticket), {
1235
+ instance: access.instance,
1236
+ viewer: access.viewer,
1237
+ expiresAt: now + HOP_SECONDS * 1_000,
1238
+ sessionSeconds: Math.min(
1239
+ MAX_SESSION_SECONDS,
1240
+ Math.max(1, Math.floor((access.expiresAt - now) / 1_000)),
1241
+ ),
1242
+ ...(access.anonymous === true ? { anonymous: true } : {}),
1243
+ ...(access.subject === undefined ? {} : { subject: access.subject }),
1244
+ ...(isPageRest(rest) ? { page: rest } : {}),
1245
+ });
1246
+ return new Response(null, {
1247
+ status: 303,
1248
+ headers: {
1249
+ location: `${own}${PREFIX}d/${keys.instanceKey(access.instance)}?ticket=${ticket}`,
1250
+ "cache-control": "no-store",
1251
+ "referrer-policy": "no-referrer",
1252
+ "x-robots-tag": "noindex, nofollow",
1253
+ },
1254
+ });
1255
+ }
1256
+
1140
1257
  /**
1141
1258
  * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
1142
1259
  * artifact of this origin (its page's sealed files' address, as its `Referer` says, P091; or a
@@ -1275,7 +1392,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1275
1392
  let instance: InstanceRef;
1276
1393
  try {
1277
1394
  instance = cleanInstance(session.i);
1278
- if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
1395
+ if (instance.document.kind !== "artifact" || labelFor(instance) !== label) {
1279
1396
  continue;
1280
1397
  }
1281
1398
  } catch {
@@ -1389,7 +1506,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1389
1506
  if (method !== "GET") {
1390
1507
  return page(405, "Not allowed", "Open this link in a browser.", method);
1391
1508
  }
1392
- const record = await take(url.searchParams.get("code"), label);
1509
+ const record = await take(url.searchParams.get("code"), label, true);
1393
1510
  if (record?.entry === undefined) {
1394
1511
  return page(
1395
1512
  403,
@@ -1574,6 +1691,29 @@ export function createServer(options: ServerOptions): PortholeServer {
1574
1691
  }
1575
1692
  }
1576
1693
 
1694
+ /**
1695
+ * A nested page's shell's own label (P114): Porthole's shell at a frame's address, its page and
1696
+ * that page's files below the sealed prefix, and Porthole's status pages (and their script).
1697
+ * Nothing else: no clean address, entry, asset, library or app, so no agent-made content ever
1698
+ * runs on this origin with it (every file below the prefix carries a sandbox without it).
1699
+ */
1700
+ async function serveShellLabel(request: Request, url: URL, label: string): Promise<Response> {
1701
+ const method = request.method.toUpperCase();
1702
+ const script = pageScript(url.pathname);
1703
+ if (script !== null) {
1704
+ return script;
1705
+ }
1706
+ const document = DOCUMENT_PATH.exec(url.pathname);
1707
+ if (document?.[1] !== undefined) {
1708
+ return serveDocument(request, url, label, document[1]);
1709
+ }
1710
+ const sealed = FILES_PATH.exec(url.pathname);
1711
+ if (sealed?.[1] !== undefined) {
1712
+ return serveSealed(request, url, label, sealed[1], sealed[2]);
1713
+ }
1714
+ return page(404, "Nothing here", "This address names no content.", method);
1715
+ }
1716
+
1577
1717
  /** A one-time ticket (or entry code) for an instance the host decided a viewer may see. */
1578
1718
  async function mint(
1579
1719
  instance: InstanceRef,
@@ -1693,7 +1833,8 @@ export function createServer(options: ServerOptions): PortholeServer {
1693
1833
 
1694
1834
  async issue(instance, grant): Promise<FrameLocation> {
1695
1835
  const { clean, key, ticket } = await mint(instance, grant);
1696
- const origin = originOfLabel(nameOf(clean.scope));
1836
+ // A nested page's frame is its shell, on the shell's own label (P114).
1837
+ const origin = originOfLabel(labelFor(clean));
1697
1838
  const path =
1698
1839
  clean.document.kind === "external"
1699
1840
  ? `${ENTER_PATH}?ticket=${ticket}`
@@ -1832,6 +1973,9 @@ export function createServer(options: ServerOptions): PortholeServer {
1832
1973
  if (!ours(label)) {
1833
1974
  return page(404, "Nothing here", "This address names no content.", method);
1834
1975
  }
1976
+ if (isNestedLabel(label)) {
1977
+ return await serveShellLabel(request, url, label);
1978
+ }
1835
1979
  if (url.pathname === ENTER_PATH) {
1836
1980
  return await enter(request, url, label);
1837
1981
  }
@@ -101,6 +101,11 @@ export interface TicketRecord {
101
101
  /** Whether that address names this version and no other: its files are immutable there. */
102
102
  readonly pinned?: boolean;
103
103
  };
104
+ /**
105
+ * A nested page's ticket from its clean address to its shell's own label (P114): the path below
106
+ * its files' base the shell opens (the entry page when absent).
107
+ */
108
+ readonly page?: string;
104
109
  }
105
110
 
106
111
  /** Where tickets live between `issue` and their one use. Default: in memory (one process). */
@@ -4,12 +4,13 @@
4
4
  * functions as they were. Plain ES2020 like the rest of the shell; no template literals (it sits
5
5
  * in one).
6
6
  *
7
- * The host drives it (`porthole/annotate.start|stop|show|focus|clear`) and it reports
8
- * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
7
+ * The host drives it (`porthole/annotate.start|stop|show|focus|clear|track|clearSelection`) and it
8
+ * reports (`porthole/annotate.selected|unselected|cancelled|anchored|activated|tracked`):
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
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
+ * the host's `clearSelection` (P115) takes the page's selection away and tells nothing back;
13
14
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
14
15
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the
15
16
  * shell's own (a closed shadow root), again whenever the content changes; what can't be found
@@ -41,6 +42,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
41
42
  activated: "porthole/annotate.activated",
42
43
  track: "porthole/annotate.track",
43
44
  tracked: "porthole/annotate.tracked",
45
+ clearSelection: "porthole/annotate.clearSelection",
44
46
  };
45
47
  // The DOM's own functions, taken before content runs.
46
48
  const elementFromPoint = Document.prototype.elementFromPoint;
@@ -50,6 +52,7 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
50
52
  const createElement = Document.prototype.createElement;
51
53
  const createElementNS = Document.prototype.createElementNS;
52
54
  const selectionOf = Document.prototype.getSelection;
55
+ const removeAllRanges = Selection.prototype.removeAllRanges;
53
56
  const elementRect = Element.prototype.getBoundingClientRect;
54
57
  const rangeRect = Range.prototype.getBoundingClientRect;
55
58
  const rangeRects = Range.prototype.getClientRects;
@@ -1425,6 +1428,23 @@ export const ANNOTATE_RUNTIME = String.raw`if (declared("annotate")) {
1425
1428
  case M.track:
1426
1429
  track(params.id);
1427
1430
  break;
1431
+ case M.clearSelection: {
1432
+ // The host used the person's selection (P115): it goes, and with it what the shell
1433
+ // held of it (a report waiting to settle, the one last told, a scroll's follow-up), so
1434
+ // nothing is told back: the host knows, and the selectionchange this makes finds
1435
+ // nothing to report. Marks, a pick and the mode stay as they are. With nothing
1436
+ // selected, nothing changes.
1437
+ cancelLater(selectionTimer);
1438
+ selectionTimer = 0;
1439
+ reported = null;
1440
+ reportedBox = null;
1441
+ selectionScrolled = false;
1442
+ const selection = selectionOf.call(document);
1443
+ if (selection !== null) {
1444
+ removeAllRanges.call(selection);
1445
+ }
1446
+ break;
1447
+ }
1428
1448
  case M.clear:
1429
1449
  track(null);
1430
1450
  pendingFocus = null;
@@ -1,3 +1,13 @@
1
+ /**
2
+ * What a draft holds back (P117), spliced into the runtime: a tag start the content was cut in
3
+ * (a trailing `<`, `</`, or `<` and a tag's name or attributes, with no `>` yet) is left out until
4
+ * more comes. Parsed as it is, a cut right after `<` or `</` draws them as text.
5
+ */
6
+ export const HELD_BACK = String.raw`(html) => {
7
+ const at = html.lastIndexOf("<");
8
+ return at !== -1 && /^\/?(?:[A-Za-z][^>]*)?$/.test(html.slice(at + 1)) ? html.slice(0, at) : html;
9
+ }`;
10
+
1
11
  /**
2
12
  * The shell's runtime: the code that runs first in the frame, before any content. Plain ES2020,
3
13
  * no imports and no build step, so every engine (a browser frame now, a native web view later)
@@ -1423,11 +1433,12 @@ export const SHELL_RUNTIME = String.raw`(() => {
1423
1433
  }
1424
1434
  };
1425
1435
  let drafted = false;
1436
+ const heldBack = ${HELD_BACK};
1426
1437
  const draft = (input) => {
1427
1438
  if (rendered || root === null || input === null || typeof input !== "object" || plan.content === "document") {
1428
1439
  return;
1429
1440
  }
1430
- morph(root, inert(parseInert(input.html || "")));
1441
+ morph(root, inert(parseInert(heldBack(String(input.html || "")))));
1431
1442
  drafted = true;
1432
1443
  drawn = true;
1433
1444
  schedule();