@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
@@ -359,6 +359,11 @@ export function createHost(config, options = {}) {
359
359
  tracking = null;
360
360
  toFrame(ANNOTATE_METHODS.clear, {});
361
361
  },
362
+ clearSelection() {
363
+ // Host → frame only, and kept for no later frame (P115).
364
+ needsAnnotate("clearSelection");
365
+ toFrame(ANNOTATE_METHODS.clearSelection, {});
366
+ },
362
367
  };
363
368
  const hostContext = () => {
364
369
  const width = container.getBoundingClientRect().width;
@@ -252,6 +252,13 @@ export interface AnnotationControls {
252
252
  track(id: string | null): void;
253
253
  /** Removes every mark. */
254
254
  clear(): void;
255
+ /**
256
+ * Takes the page's text selection away (P115), its highlight with it: for when the host has
257
+ * used it (a comment posted, a draft added). No `unselected` follows; marks (posted and drafts),
258
+ * the mode and a followed mark stay as they are. Nothing selected: nothing happens. Not kept for
259
+ * a frame that runs later (it has no selection to clear).
260
+ */
261
+ clearSelection(): void;
255
262
  }
256
263
  export interface DisplayControls {
257
264
  readonly displayId: string;
@@ -160,10 +160,11 @@ export interface PortholeFrameProps {
160
160
  readonly instance?: InstanceRef;
161
161
  /**
162
162
  * What the page declared (P086), as the host stored it with the artifact: the capabilities it
163
- * reaches through `porthole.use`, and its pinned runtime. By value: a change makes the display
164
- * again.
163
+ * reaches through `porthole.use`, and its pinned runtime. Under `config.runtime`, `null` says
164
+ * the page was published before 0.7 and has 0.6's surface (`MountOptions.declaration`). By
165
+ * value: a change makes the display again.
165
166
  */
166
- readonly declaration?: PageDeclaration;
167
+ readonly declaration?: PageDeclaration | null;
167
168
  /**
168
169
  * Who is viewing (P087), for an opaque frame or one whose issue gave none. By value: a change
169
170
  * makes the display again.
@@ -37,7 +37,7 @@ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, type ContentHealthVie
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
40
- export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.ts";
40
+ export { isNestedLabel, NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedLabelOf, nestedShellCsp, nestedShellResponse, PORTHOLE_LABEL_PREFIX, } from "./nested.ts";
41
41
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
42
42
  export { conformancePage } from "../conformance/page.ts";
43
43
  export type { PortholeConfig } from "../config/schema.ts";
@@ -38,9 +38,10 @@ export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domai
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.js";
40
40
  // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
41
- // sealed prefix. `/server` serves them for a config with `nested`; a content Worker of its own
42
- // answers the same (docs/ADOPTING.md, "Nested pages").
43
- export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.js";
41
+ // sealed prefix, all on the shell's own label (P114, `nestedLabelOf`). `/server` serves them for a
42
+ // config with `nested`; a content Worker of its own answers the same (docs/ADOPTING.md, "Nested
43
+ // pages").
44
+ export { isNestedLabel, NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedLabelOf, nestedShellCsp, nestedShellResponse, PORTHOLE_LABEL_PREFIX, } from "./nested.js";
44
45
  export { isHostLabel, prefixedName } from "./naming.js";
45
46
  // The page an app serves in conformance test mode (P071).
46
47
  export { conformancePage } from "../conformance/page.js";
@@ -17,6 +17,10 @@ export function prefixedName(prefix) {
17
17
  if (!PREFIX.test(prefix)) {
18
18
  throw new TypeError("A name prefix is a lowercase letter, then letters or digits, then '-' (a-)");
19
19
  }
20
+ // Porthole's own labels (a nested page's shell's, P114) are never a scope's.
21
+ if (prefix === "porthole-") {
22
+ throw new TypeError("The name prefix porthole- is Porthole's own: choose another (a-)");
23
+ }
20
24
  const name = (scope) => {
21
25
  const label = `${prefix}${scope}`;
22
26
  if (!ID.test(scope) || !isHostLabel(label)) {
@@ -5,7 +5,29 @@ import { type FrameShellOptions } from "../shell/frame.ts";
5
5
  * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
6
6
  * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
7
7
  * a host serving its own content origin (its own Worker) answers the same.
8
+ *
9
+ * All of it is served on the shell's own label (P114, `nestedLabelOf`), never on the scope's: every
10
+ * other display of the scope runs agent-made content on the scope's origin with
11
+ * `allow-same-origin`, which would be same-origin with the shell, its realm and the page's sealed
12
+ * address.
8
13
  */
14
+ /**
15
+ * The start of every label Porthole serves for itself on a content domain (P114): no host's naming
16
+ * may make one (`content.name` is refused one, and `prefixedName` won't take the prefix).
17
+ */
18
+ export declare const PORTHOLE_LABEL_PREFIX = "porthole-";
19
+ /**
20
+ * The label a nested page's shell is served on (P114), for its scope's label: `porthole-` and 24
21
+ * base32 characters of the label's SHA-256, one per scope, the same for every nested page of it. No
22
+ * content label is ever one (a keyed label has no hyphen, a host's is refused the prefix), so
23
+ * nothing but a nested page's shell, its opaque page, that page's files and Porthole's status pages
24
+ * is ever served on it: no other display's content runs there with `allow-same-origin`. Not a
25
+ * secret: anyone who knows the scope's label may work it out. A content Worker of a host's own
26
+ * serves its nested pages on it too.
27
+ */
28
+ export declare function nestedLabelOf(label: string): string;
29
+ /** Whether a label is a nested page's shell's own (`nestedLabelOf`'s form). */
30
+ export declare const isNestedLabel: (label: string) => boolean;
9
31
  /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
10
32
  export declare const NESTED_FILES_PREFIX = "/__porthole/f/";
11
33
  /**
@@ -24,8 +46,8 @@ export declare function nestedShellResponse(compiled: CompiledConfig, options: F
24
46
  readonly method?: string;
25
47
  }): Response;
26
48
  /**
27
- * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
28
- * it, the host origins (`frame-ancestors` names every ancestor).
49
+ * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
50
+ * above it, the host origins (`frame-ancestors` names every ancestor).
29
51
  */
30
52
  export declare const nestedAncestors: (origin: string, frameAncestors: string) => string;
31
53
  /**
@@ -1,12 +1,38 @@
1
1
  import { servedPermissionsPolicy, serializeCsp } from "../compile/policy.js";
2
2
  import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
3
  import { sha256, utf8 } from "./crypto.js";
4
+ import { base32 } from "./keys.js";
4
5
  /**
5
6
  * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
6
7
  * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
7
8
  * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
8
9
  * a host serving its own content origin (its own Worker) answers the same.
10
+ *
11
+ * All of it is served on the shell's own label (P114, `nestedLabelOf`), never on the scope's: every
12
+ * other display of the scope runs agent-made content on the scope's origin with
13
+ * `allow-same-origin`, which would be same-origin with the shell, its realm and the page's sealed
14
+ * address.
9
15
  */
16
+ /**
17
+ * The start of every label Porthole serves for itself on a content domain (P114): no host's naming
18
+ * may make one (`content.name` is refused one, and `prefixedName` won't take the prefix).
19
+ */
20
+ export const PORTHOLE_LABEL_PREFIX = "porthole-";
21
+ const NESTED_LABEL = /^porthole-[a-z2-7]{24}$/u;
22
+ /**
23
+ * The label a nested page's shell is served on (P114), for its scope's label: `porthole-` and 24
24
+ * base32 characters of the label's SHA-256, one per scope, the same for every nested page of it. No
25
+ * content label is ever one (a keyed label has no hyphen, a host's is refused the prefix), so
26
+ * nothing but a nested page's shell, its opaque page, that page's files and Porthole's status pages
27
+ * is ever served on it: no other display's content runs there with `allow-same-origin`. Not a
28
+ * secret: anyone who knows the scope's label may work it out. A content Worker of a host's own
29
+ * serves its nested pages on it too.
30
+ */
31
+ export function nestedLabelOf(label) {
32
+ return `${PORTHOLE_LABEL_PREFIX}${base32(sha256(utf8(`porthole/nested/${label}`)).subarray(0, 15))}`;
33
+ }
34
+ /** Whether a label is a nested page's shell's own (`nestedLabelOf`'s form). */
35
+ export const isNestedLabel = (label) => NESTED_LABEL.test(label);
10
36
  /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
11
37
  export const NESTED_FILES_PREFIX = "/__porthole/f/";
12
38
  const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
@@ -54,8 +80,8 @@ export function nestedShellResponse(compiled, options) {
54
80
  });
55
81
  }
56
82
  /**
57
- * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
58
- * it, the host origins (`frame-ancestors` names every ancestor).
83
+ * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
84
+ * above it, the host origins (`frame-ancestors` names every ancestor).
59
85
  */
60
86
  export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
61
87
  /**
@@ -7,7 +7,7 @@ import { isHostLabel, reservedLabels } from "./naming.js";
7
7
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.js";
8
8
  import { libraryFile } from "./libraries.js";
9
9
  import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.js";
10
- import { nestedAncestors, nestedShellResponse } from "./nested.js";
10
+ import { isNestedLabel, nestedAncestors, nestedLabelOf, nestedShellResponse, PORTHOLE_LABEL_PREFIX, } from "./nested.js";
11
11
  import { DEFAULT_ENTRY } from "../files/paths.js";
12
12
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
13
13
  import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
@@ -43,6 +43,19 @@ const BASE = /^\/(?:(?!\.{1,2}\/)[A-Za-z0-9._:~-]{1,200}\/){0,16}$/u;
43
43
  const ENTER_PATH = "/__porthole/enter";
44
44
  /** Where a redirect entry's code is redeemed, before its clean address (P068). */
45
45
  const ENTRY_PATH = "/__porthole/entry";
46
+ /** How long a nested page's ticket from its clean address to its shell's label lasts (P114). */
47
+ const HOP_SECONDS = 60;
48
+ /**
49
+ * A path below a file set's base, as a hop's ticket carries it (P114): a relative path of URL path
50
+ * characters, no empty segment but a last one, no dot segment (encoded or not), no query.
51
+ */
52
+ const isPageRest = (rest) => typeof rest === "string" &&
53
+ rest.length > 0 &&
54
+ rest.length <= MAX_PATH &&
55
+ /^[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/u.test(rest) &&
56
+ rest
57
+ .split("/")
58
+ .every((segment, index, all) => (segment !== "" || index === all.length - 1) && !/^(?:\.|%2e){1,2}$/iu.test(segment));
46
59
  /** How long a redirect entry may take (the person may sign in on the way), and its code. */
47
60
  const ENTRY_STATE_MS = 5 * 60_000;
48
61
  const ENTRY_CODE_SECONDS = 60;
@@ -235,13 +248,34 @@ export function createServer(options) {
235
248
  return keys.label(scope);
236
249
  }
237
250
  const label = content.name(scope);
238
- if (!isHostLabel(label) || isReserved(label)) {
239
- throw new TypeError(`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`);
251
+ if (!isHostLabel(label) || isReserved(label) || label.startsWith(PORTHOLE_LABEL_PREFIX)) {
252
+ throw new TypeError(`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}…)`);
240
253
  }
241
254
  return label;
242
255
  };
243
- /** Whether a request's label may be one this server named. */
244
- const ours = (label) => !isReserved(label) && (content.name === undefined ? LABEL.test(label) : isHostLabel(label));
256
+ /**
257
+ * The label an instance is served on: its scope's, or a nested page's shell's own (P114), on
258
+ * which nothing but nested pages' shells, their pages and those pages' files is ever served.
259
+ * Every other display of the scope runs agent-made content on the scope's origin with
260
+ * `allow-same-origin`: on that origin, the shell's realm (its word to the host, the page's
261
+ * sealed address) would be theirs.
262
+ */
263
+ const labelFor = (instance) => {
264
+ const label = nameOf(instance.scope);
265
+ if (instance.document.kind !== "artifact" || compiledFor(instance)?.config.nested !== true) {
266
+ return label;
267
+ }
268
+ const own = nestedLabelOf(label);
269
+ if (isReserved(own)) {
270
+ throw new TypeError(`content.reserved holds ${own}, a nested page's shell's label: reserve no ${PORTHOLE_LABEL_PREFIX} label`);
271
+ }
272
+ return own;
273
+ };
274
+ /** Whether a request's label may be one this server named (a nested page's shell's, P114). */
275
+ const ours = (label) => !isReserved(label) &&
276
+ (isNestedLabel(label) ||
277
+ (!label.startsWith(PORTHOLE_LABEL_PREFIX) &&
278
+ (content.name === undefined ? LABEL.test(label) : isHostLabel(label))));
245
279
  const secure = content.scheme === "https";
246
280
  const defaultPort = secure ? 443 : 80;
247
281
  const portPart = content.port === undefined || content.port === defaultPort ? "" : `:${content.port}`;
@@ -249,6 +283,7 @@ export function createServer(options) {
249
283
  const contentSource = `${content.scheme}://*.${domain}${portPart}`;
250
284
  const sampleHost = `${keys.label("")}.${domain}`;
251
285
  const sampleOrigin = originOfLabel(keys.label(""));
286
+ const sampleNestedOrigin = originOfLabel(nestedLabelOf(keys.label("")));
252
287
  const authorize = options.authorize;
253
288
  const authorizeTtl = authorize?.ttlSeconds ?? 0;
254
289
  if (!Number.isInteger(authorizeTtl) || authorizeTtl < 0 || authorizeTtl > 300) {
@@ -356,7 +391,9 @@ export function createServer(options) {
356
391
  if (config.isolation !== "domain" || !MODES[kind].includes(config.mode)) {
357
392
  throw new TypeError(`The config ${JSON.stringify(name)} (${config.mode}, ${config.isolation}) can't serve a ${kind}: it needs ${MODES[kind].join(" or ")} mode with domain isolation`);
358
393
  }
359
- if (!config.contentOrigins.some((source) => originMatchesSource(sampleOrigin, source))) {
394
+ // A nested page's shell is on a label of its own (P114): its frame source is the same.
395
+ const samples = config.nested === true ? [sampleOrigin, sampleNestedOrigin] : [sampleOrigin];
396
+ if (!samples.every((sample) => config.contentOrigins.some((source) => originMatchesSource(sample, source)))) {
360
397
  throw new TypeError(`The config ${JSON.stringify(name)}'s contentOrigins don't include this server's (${contentSource})`);
361
398
  }
362
399
  return each;
@@ -540,7 +577,7 @@ export function createServer(options) {
540
577
  }
541
578
  let named;
542
579
  try {
543
- named = nameOf(instance.scope);
580
+ named = labelFor(instance);
544
581
  }
545
582
  catch {
546
583
  continue;
@@ -634,8 +671,11 @@ export function createServer(options) {
634
671
  }
635
672
  return best;
636
673
  }
637
- /** A taken ticket, if it is good for `label`'s origin. */
638
- async function take(ticket, label) {
674
+ /**
675
+ * A taken ticket, if it is good for `label`'s origin: its instance's own (a nested page's shell's,
676
+ * P114), or for an entry code (`entry`) its scope's, where a clean address is.
677
+ */
678
+ async function take(ticket, label, entry = false) {
639
679
  if (ticket === null || ticket.length === 0 || ticket.length > 128) {
640
680
  return null;
641
681
  }
@@ -645,7 +685,9 @@ export function createServer(options) {
645
685
  }
646
686
  try {
647
687
  const instance = cleanInstance(record.instance);
648
- return nameOf(instance.scope) === label ? { ...record, instance } : null;
688
+ return (entry ? nameOf(instance.scope) : labelFor(instance)) === label
689
+ ? { ...record, instance }
690
+ : null;
649
691
  }
650
692
  catch {
651
693
  return null;
@@ -685,7 +727,14 @@ export function createServer(options) {
685
727
  catch {
686
728
  return null;
687
729
  }
688
- if (!open || instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
730
+ let named;
731
+ try {
732
+ named = labelFor(instance);
733
+ }
734
+ catch {
735
+ return null;
736
+ }
737
+ if (!open || instance.document.kind !== "artifact" || named !== label) {
689
738
  return null;
690
739
  }
691
740
  return {
@@ -741,7 +790,8 @@ export function createServer(options) {
741
790
  // sends a frame's path, where some send no Referer that names it.
742
791
  const blob = SEALED_ASSET.exec(rest)?.[1];
743
792
  if (blob !== undefined) {
744
- if (options.assets === undefined) {
793
+ // A nested page loads no assets (its config refuses them): none on its shell's label (P114).
794
+ if (options.assets === undefined || isNestedLabel(label)) {
745
795
  return page(404, "Not found", "This address names no content.", method);
746
796
  }
747
797
  return ((await assetFor(request, label, access, blob)) ??
@@ -787,7 +837,9 @@ export function createServer(options) {
787
837
  // The ticket's own answer carries the document: an engine that keeps no cookie in a frame
788
838
  // still shows it. The cookie serves what follows (a reload), where the engine keeps it.
789
839
  const record = method === "GET" ? await take(url.searchParams.get("ticket"), label) : null;
840
+ // An entry code opens its clean address alone, through its own browser's nonce (P068, P114).
790
841
  if (record !== null &&
842
+ record.entry === undefined &&
791
843
  record.instance.document.kind !== "external" &&
792
844
  keys.instanceKey(record.instance) === key) {
793
845
  cookie = sessionCookie(request, record);
@@ -804,13 +856,18 @@ export function createServer(options) {
804
856
  if (access === null) {
805
857
  return page(401, "This link has been used", "Content here opens once per link. Open it again from the app that showed it.", method, "session");
806
858
  }
807
- return serveAccess(request, access, cookie);
859
+ // A nested page's hop from its clean address (P114): the page below its base it was entered at.
860
+ const asked = cookie === null ? undefined : record?.page;
861
+ const rest = isPageRest(asked) ? asked : undefined;
862
+ return serveAccess(request, access, cookie, undefined, rest);
808
863
  }
809
864
  /**
810
865
  * The document an access opens, once the host's check lets it in: at its document's path, or
811
866
  * (`at`) a path under a file set's base (P081).
812
867
  */
813
- async function serveAccess(request, access, cookie, at) {
868
+ async function serveAccess(request, access, cookie, at,
869
+ /** A nested page's path below its files' base, from its hop's ticket (P114). */
870
+ pageAt) {
814
871
  const method = request.method.toUpperCase();
815
872
  const refusal = await denied(request, access);
816
873
  if (refusal !== null) {
@@ -829,19 +886,27 @@ export function createServer(options) {
829
886
  if (!isNavigation(request)) {
830
887
  return page(404, "Not found", "This page's files are at its own address.", method);
831
888
  }
889
+ // Its shell is served on its own label alone (P114): a clean address, entered on the scope's
890
+ // label (P068), goes there with a one-time ticket of its own, for what is left of its session.
891
+ const own = originOfLabel(labelFor(access.instance));
892
+ if (access.origin !== own) {
893
+ return hop(access, own, "files" in served && at !== undefined ? at.rest : "");
894
+ }
832
895
  const sealed = await sealFiles(access);
833
896
  let rest = "";
834
897
  if ("files" in served) {
835
898
  const entry = served.files.entry ?? DEFAULT_ENTRY;
836
899
  rest =
837
- at !== undefined && at.rest !== ""
838
- ? at.rest
839
- : entry.includes("/")
840
- ? entry
841
- .split("/")
842
- .map((segment) => encodeURIComponent(segment))
843
- .join("/")
844
- : "";
900
+ pageAt !== undefined
901
+ ? pageAt
902
+ : at !== undefined && at.rest !== ""
903
+ ? at.rest
904
+ : entry.includes("/")
905
+ ? entry
906
+ .split("/")
907
+ .map((segment) => encodeURIComponent(segment))
908
+ .join("/")
909
+ : "";
845
910
  }
846
911
  const shell = nestedShellResponse(served.compiled, {
847
912
  origin: access.origin,
@@ -915,6 +980,35 @@ export function createServer(options) {
915
980
  : served.html;
916
981
  return new Response(method === "HEAD" ? null : html, { status: 200, headers });
917
982
  }
983
+ /**
984
+ * A nested page entered at its clean address (P114), whose shell is never served there: on to the
985
+ * shell's own label, with a one-time ticket for the same access (its viewer, its subject, what is
986
+ * left of its session) and the path below its base it was entered at. Only this server's own
987
+ * answer carries the ticket, as `issue`'s frame address does; the host's check already let the
988
+ * request in.
989
+ */
990
+ async function hop(access, own, rest) {
991
+ const now = Date.now();
992
+ const ticket = newTicket();
993
+ await tickets.put(ticketId(ticket), {
994
+ instance: access.instance,
995
+ viewer: access.viewer,
996
+ expiresAt: now + HOP_SECONDS * 1_000,
997
+ sessionSeconds: Math.min(MAX_SESSION_SECONDS, Math.max(1, Math.floor((access.expiresAt - now) / 1_000))),
998
+ ...(access.anonymous === true ? { anonymous: true } : {}),
999
+ ...(access.subject === undefined ? {} : { subject: access.subject }),
1000
+ ...(isPageRest(rest) ? { page: rest } : {}),
1001
+ });
1002
+ return new Response(null, {
1003
+ status: 303,
1004
+ headers: {
1005
+ location: `${own}${PREFIX}d/${keys.instanceKey(access.instance)}?ticket=${ticket}`,
1006
+ "cache-control": "no-store",
1007
+ "referrer-policy": "no-referrer",
1008
+ "x-robots-tag": "noindex, nofollow",
1009
+ },
1010
+ });
1011
+ }
918
1012
  /**
919
1013
  * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
920
1014
  * artifact of this origin (its page's sealed files' address, as its `Referer` says, P091; or a
@@ -1045,7 +1139,7 @@ export function createServer(options) {
1045
1139
  let instance;
1046
1140
  try {
1047
1141
  instance = cleanInstance(session.i);
1048
- if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
1142
+ if (instance.document.kind !== "artifact" || labelFor(instance) !== label) {
1049
1143
  continue;
1050
1144
  }
1051
1145
  }
@@ -1144,7 +1238,7 @@ export function createServer(options) {
1144
1238
  if (method !== "GET") {
1145
1239
  return page(405, "Not allowed", "Open this link in a browser.", method);
1146
1240
  }
1147
- const record = await take(url.searchParams.get("code"), label);
1241
+ const record = await take(url.searchParams.get("code"), label, true);
1148
1242
  if (record?.entry === undefined) {
1149
1243
  return page(403, "This sign-in link has been used", "It works once, for a short time. Open the address again.", method, "session");
1150
1244
  }
@@ -1282,6 +1376,28 @@ export function createServer(options) {
1282
1376
  return page(502, "The app didn't answer", "Its server couldn't be reached.", method);
1283
1377
  }
1284
1378
  }
1379
+ /**
1380
+ * A nested page's shell's own label (P114): Porthole's shell at a frame's address, its page and
1381
+ * that page's files below the sealed prefix, and Porthole's status pages (and their script).
1382
+ * Nothing else: no clean address, entry, asset, library or app, so no agent-made content ever
1383
+ * runs on this origin with it (every file below the prefix carries a sandbox without it).
1384
+ */
1385
+ async function serveShellLabel(request, url, label) {
1386
+ const method = request.method.toUpperCase();
1387
+ const script = pageScript(url.pathname);
1388
+ if (script !== null) {
1389
+ return script;
1390
+ }
1391
+ const document = DOCUMENT_PATH.exec(url.pathname);
1392
+ if (document?.[1] !== undefined) {
1393
+ return serveDocument(request, url, label, document[1]);
1394
+ }
1395
+ const sealed = FILES_PATH.exec(url.pathname);
1396
+ if (sealed?.[1] !== undefined) {
1397
+ return serveSealed(request, url, label, sealed[1], sealed[2]);
1398
+ }
1399
+ return page(404, "Nothing here", "This address names no content.", method);
1400
+ }
1285
1401
  /** A one-time ticket (or entry code) for an instance the host decided a viewer may see. */
1286
1402
  async function mint(instance, grant, entry) {
1287
1403
  const clean = cleanInstance(instance);
@@ -1381,7 +1497,8 @@ export function createServer(options) {
1381
1497
  originFor: (scope) => originOfLabel(nameOf(scope)),
1382
1498
  async issue(instance, grant) {
1383
1499
  const { clean, key, ticket } = await mint(instance, grant);
1384
- const origin = originOfLabel(nameOf(clean.scope));
1500
+ // A nested page's frame is its shell, on the shell's own label (P114).
1501
+ const origin = originOfLabel(labelFor(clean));
1385
1502
  const path = clean.document.kind === "external"
1386
1503
  ? `${ENTER_PATH}?ticket=${ticket}`
1387
1504
  : `${PREFIX}d/${key}?ticket=${ticket}`;
@@ -1494,6 +1611,9 @@ export function createServer(options) {
1494
1611
  if (!ours(label)) {
1495
1612
  return page(404, "Nothing here", "This address names no content.", method);
1496
1613
  }
1614
+ if (isNestedLabel(label)) {
1615
+ return await serveShellLabel(request, url, label);
1616
+ }
1497
1617
  if (url.pathname === ENTER_PATH) {
1498
1618
  return await enter(request, url, label);
1499
1619
  }
@@ -98,6 +98,11 @@ export interface TicketRecord {
98
98
  /** Whether that address names this version and no other: its files are immutable there. */
99
99
  readonly pinned?: boolean;
100
100
  };
101
+ /**
102
+ * A nested page's ticket from its clean address to its shell's own label (P114): the path below
103
+ * its files' base the shell opens (the entry page when absent).
104
+ */
105
+ readonly page?: string;
101
106
  }
102
107
  /** Where tickets live between `issue` and their one use. Default: in memory (one process). */
103
108
  export interface TicketStore {
@@ -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
@@ -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,9 @@
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 declare const HELD_BACK: string;
1
7
  /**
2
8
  * The shell's runtime: the code that runs first in the frame, before any content. Plain ES2020,
3
9
  * no imports and no build step, so every engine (a browser frame now, a native web view later)
@@ -1,3 +1,12 @@
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
+ }`;
1
10
  /**
2
11
  * The shell's runtime: the code that runs first in the frame, before any content. Plain ES2020,
3
12
  * no imports and no build step, so every engine (a browser frame now, a native web view later)
@@ -1423,11 +1432,12 @@ export const SHELL_RUNTIME = String.raw `(() => {
1423
1432
  }
1424
1433
  };
1425
1434
  let drafted = false;
1435
+ const heldBack = ${HELD_BACK};
1426
1436
  const draft = (input) => {
1427
1437
  if (rendered || root === null || input === null || typeof input !== "object" || plan.content === "document") {
1428
1438
  return;
1429
1439
  }
1430
- morph(root, inert(parseInert(input.html || "")));
1440
+ morph(root, inert(parseInert(heldBack(String(input.html || "")))));
1431
1441
  drafted = true;
1432
1442
  drawn = true;
1433
1443
  schedule();