@botiverse/porthole 0.13.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 (77) hide show
  1. package/CHANGELOG.md +770 -0
  2. package/dist/annotate/types.d.ts +36 -4
  3. package/dist/annotate/types.js +6 -0
  4. package/dist/annotate/validate.d.ts +2 -1
  5. package/dist/annotate/validate.js +30 -6
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/compile/policy.d.ts +7 -0
  8. package/dist/compile/policy.js +13 -1
  9. package/dist/config/schema.d.ts +11 -0
  10. package/dist/config/validate.js +19 -0
  11. package/dist/conformance/harness-source.js +1 -1
  12. package/dist/displays/displays.js +3 -1
  13. package/dist/guide/limits.js +1 -1
  14. package/dist/host/create-host.d.ts +2 -0
  15. package/dist/host/create-host.js +78 -3
  16. package/dist/host/pass-on.d.ts +15 -0
  17. package/dist/host/pass-on.js +65 -0
  18. package/dist/host/types.d.ts +29 -0
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.js +4 -1
  21. package/dist/isolation/types.d.ts +8 -0
  22. package/dist/isolation/types.js +8 -0
  23. package/dist/platform/focus-guard.d.ts +71 -2
  24. package/dist/platform/focus-guard.js +187 -12
  25. package/dist/platform/types.d.ts +8 -1
  26. package/dist/platform/web.js +60 -4
  27. package/dist/presets/presets.d.ts +2 -0
  28. package/dist/presets/presets.js +1 -0
  29. package/dist/react/frame.d.ts +4 -3
  30. package/dist/server/files.js +19 -3
  31. package/dist/server/index.d.ts +1 -0
  32. package/dist/server/index.js +5 -0
  33. package/dist/server/naming.js +4 -0
  34. package/dist/server/nested.d.ts +59 -0
  35. package/dist/server/nested.js +96 -0
  36. package/dist/server/server.js +193 -23
  37. package/dist/server/types.d.ts +5 -0
  38. package/dist/shell/annotate.d.ts +4 -3
  39. package/dist/shell/annotate.js +179 -9
  40. package/dist/shell/frame.d.ts +45 -0
  41. package/dist/shell/frame.js +250 -0
  42. package/dist/shell/plan.js +2 -1
  43. package/dist/shell/runtime.d.ts +6 -0
  44. package/dist/shell/runtime.js +60 -15
  45. package/docs/ADOPTING.md +85 -2
  46. package/docs/ARCHITECTURE.md +28 -0
  47. package/docs/DECISIONS.md +416 -1
  48. package/docs/DESIGN.md +21 -4
  49. package/docs/THREAT_MODEL.md +102 -5
  50. package/package.json +6 -5
  51. package/src/annotate/types.ts +32 -4
  52. package/src/annotate/validate.ts +34 -8
  53. package/src/compile/policy.ts +14 -1
  54. package/src/config/schema.ts +11 -0
  55. package/src/config/validate.ts +23 -0
  56. package/src/displays/displays.ts +3 -1
  57. package/src/guide/limits.ts +1 -1
  58. package/src/host/create-host.ts +81 -4
  59. package/src/host/pass-on.ts +73 -0
  60. package/src/host/types.ts +27 -0
  61. package/src/index.ts +4 -1
  62. package/src/isolation/types.ts +12 -0
  63. package/src/platform/focus-guard.ts +258 -15
  64. package/src/platform/types.ts +8 -1
  65. package/src/platform/web.ts +81 -9
  66. package/src/presets/presets.ts +3 -0
  67. package/src/react/frame.tsx +4 -3
  68. package/src/server/files.ts +19 -3
  69. package/src/server/index.ts +14 -0
  70. package/src/server/naming.ts +4 -0
  71. package/src/server/nested.ts +116 -0
  72. package/src/server/server.ts +224 -21
  73. package/src/server/types.ts +5 -0
  74. package/src/shell/annotate.ts +179 -9
  75. package/src/shell/frame.ts +268 -0
  76. package/src/shell/plan.ts +2 -1
  77. package/src/shell/runtime.ts +61 -15
@@ -0,0 +1,96 @@
1
+ import { servedPermissionsPolicy, serializeCsp } from "../compile/policy.js";
2
+ import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
+ import { sha256, utf8 } from "./crypto.js";
4
+ import { base32 } from "./keys.js";
5
+ /**
6
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
7
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
8
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
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.
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);
36
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
37
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
38
+ const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
39
+ /**
40
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
41
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
42
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
43
+ * this (a framed URL's document never does).
44
+ */
45
+ export function nestedShellCsp(script, origin, hostOrigins) {
46
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
47
+ const directives = [
48
+ ["default-src", "'none'"],
49
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
50
+ ["frame-src", files],
51
+ ["connect-src", files],
52
+ ["base-uri", "'none'"],
53
+ ["form-action", "'none'"],
54
+ ["frame-ancestors", ...hostOrigins],
55
+ ];
56
+ return serializeCsp(directives);
57
+ }
58
+ /**
59
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
60
+ * stored (it carries the page's sealed address), its page at `options.page`.
61
+ */
62
+ export function nestedShellResponse(compiled, options) {
63
+ const script = frameShellScript(options);
64
+ const headers = new Headers({
65
+ "content-type": "text/html; charset=utf-8",
66
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
67
+ "cache-control": "no-store",
68
+ "referrer-policy": "no-referrer",
69
+ "x-content-type-options": "nosniff",
70
+ "x-robots-tag": "noindex, nofollow",
71
+ });
72
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
73
+ const permissions = servedPermissionsPolicy(compiled.config);
74
+ if (permissions !== null) {
75
+ headers.set("permissions-policy", permissions);
76
+ }
77
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
78
+ status: 200,
79
+ headers,
80
+ });
81
+ }
82
+ /**
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).
85
+ */
86
+ export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
87
+ /**
88
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
89
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
90
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
91
+ * is their access, never the request's origin.
92
+ */
93
+ export const NESTED_FILE_HEADERS = {
94
+ "cross-origin-resource-policy": "cross-origin",
95
+ "access-control-allow-origin": "*",
96
+ };
@@ -6,7 +6,9 @@ import { randomBytes } from "./crypto.js";
6
6
  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
- import { ownLoad, serveAsset, serveFile } from "./files.js";
9
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.js";
10
+ import { isNestedLabel, nestedAncestors, nestedLabelOf, nestedShellResponse, PORTHOLE_LABEL_PREFIX, } from "./nested.js";
11
+ import { DEFAULT_ENTRY } from "../files/paths.js";
10
12
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
11
13
  import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
12
14
  import { parseViewer } from "../runtime/levels.js";
@@ -41,6 +43,19 @@ const BASE = /^\/(?:(?!\.{1,2}\/)[A-Za-z0-9._:~-]{1,200}\/){0,16}$/u;
41
43
  const ENTER_PATH = "/__porthole/enter";
42
44
  /** Where a redirect entry's code is redeemed, before its clean address (P068). */
43
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));
44
59
  /** How long a redirect entry may take (the person may sign in on the way), and its code. */
45
60
  const ENTRY_STATE_MS = 5 * 60_000;
46
61
  const ENTRY_CODE_SECONDS = 60;
@@ -233,13 +248,34 @@ export function createServer(options) {
233
248
  return keys.label(scope);
234
249
  }
235
250
  const label = content.name(scope);
236
- if (!isHostLabel(label) || isReserved(label)) {
237
- 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}…)`);
238
253
  }
239
254
  return label;
240
255
  };
241
- /** Whether a request's label may be one this server named. */
242
- 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))));
243
279
  const secure = content.scheme === "https";
244
280
  const defaultPort = secure ? 443 : 80;
245
281
  const portPart = content.port === undefined || content.port === defaultPort ? "" : `:${content.port}`;
@@ -247,6 +283,7 @@ export function createServer(options) {
247
283
  const contentSource = `${content.scheme}://*.${domain}${portPart}`;
248
284
  const sampleHost = `${keys.label("")}.${domain}`;
249
285
  const sampleOrigin = originOfLabel(keys.label(""));
286
+ const sampleNestedOrigin = originOfLabel(nestedLabelOf(keys.label("")));
250
287
  const authorize = options.authorize;
251
288
  const authorizeTtl = authorize?.ttlSeconds ?? 0;
252
289
  if (!Number.isInteger(authorizeTtl) || authorizeTtl < 0 || authorizeTtl > 300) {
@@ -354,7 +391,9 @@ export function createServer(options) {
354
391
  if (config.isolation !== "domain" || !MODES[kind].includes(config.mode)) {
355
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`);
356
393
  }
357
- 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)))) {
358
397
  throw new TypeError(`The config ${JSON.stringify(name)}'s contentOrigins don't include this server's (${contentSource})`);
359
398
  }
360
399
  return each;
@@ -425,6 +464,7 @@ export function createServer(options) {
425
464
  }
426
465
  return {
427
466
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
467
+ document: stored.html,
428
468
  compiled: config,
429
469
  assets: true,
430
470
  };
@@ -537,7 +577,7 @@ export function createServer(options) {
537
577
  }
538
578
  let named;
539
579
  try {
540
- named = nameOf(instance.scope);
580
+ named = labelFor(instance);
541
581
  }
542
582
  catch {
543
583
  continue;
@@ -631,8 +671,11 @@ export function createServer(options) {
631
671
  }
632
672
  return best;
633
673
  }
634
- /** A taken ticket, if it is good for `label`'s origin. */
635
- 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) {
636
679
  if (ticket === null || ticket.length === 0 || ticket.length > 128) {
637
680
  return null;
638
681
  }
@@ -642,16 +685,18 @@ export function createServer(options) {
642
685
  }
643
686
  try {
644
687
  const instance = cleanInstance(record.instance);
645
- return nameOf(instance.scope) === label ? { ...record, instance } : null;
688
+ return (entry ? nameOf(instance.scope) : labelFor(instance)) === label
689
+ ? { ...record, instance }
690
+ : null;
646
691
  }
647
692
  catch {
648
693
  return null;
649
694
  }
650
695
  }
651
- function documentHeaders(csp, permissions) {
696
+ function documentHeaders(csp, permissions, ancestors = frameAncestors) {
652
697
  return new Headers({
653
698
  "content-type": "text/html; charset=utf-8",
654
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
699
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
655
700
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
656
701
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
657
702
  "cache-control": "no-store",
@@ -682,7 +727,14 @@ export function createServer(options) {
682
727
  catch {
683
728
  return null;
684
729
  }
685
- 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) {
686
738
  return null;
687
739
  }
688
740
  return {
@@ -730,13 +782,16 @@ export function createServer(options) {
730
782
  }
731
783
  const access = await sealedAccess(request, label, token);
732
784
  if (access === null) {
733
- return page(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", method, "session");
785
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
786
+ // config without nesting never frames this address but at the host.
787
+ return statusPage(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", nestedAncestors(origin, frameAncestors), method, "session", [...options.hostOrigins, origin]);
734
788
  }
735
789
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
736
790
  // sends a frame's path, where some send no Referer that names it.
737
791
  const blob = SEALED_ASSET.exec(rest)?.[1];
738
792
  if (blob !== undefined) {
739
- 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)) {
740
795
  return page(404, "Not found", "This address names no content.", method);
741
796
  }
742
797
  return ((await assetFor(request, label, access, blob)) ??
@@ -782,7 +837,9 @@ export function createServer(options) {
782
837
  // The ticket's own answer carries the document: an engine that keeps no cookie in a frame
783
838
  // still shows it. The cookie serves what follows (a reload), where the engine keeps it.
784
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).
785
841
  if (record !== null &&
842
+ record.entry === undefined &&
786
843
  record.instance.document.kind !== "external" &&
787
844
  keys.instanceKey(record.instance) === key) {
788
845
  cookie = sessionCookie(request, record);
@@ -799,13 +856,18 @@ export function createServer(options) {
799
856
  if (access === null) {
800
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");
801
858
  }
802
- 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);
803
863
  }
804
864
  /**
805
865
  * The document an access opens, once the host's check lets it in: at its document's path, or
806
866
  * (`at`) a path under a file set's base (P081).
807
867
  */
808
- 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) {
809
871
  const method = request.method.toUpperCase();
810
872
  const refusal = await denied(request, access);
811
873
  if (refusal !== null) {
@@ -815,6 +877,51 @@ export function createServer(options) {
815
877
  if (served === null) {
816
878
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
817
879
  }
880
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
881
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
882
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
883
+ const nested = served.compiled.config.nested === true;
884
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
885
+ if (nested && !sealedAt) {
886
+ if (!isNavigation(request)) {
887
+ return page(404, "Not found", "This page's files are at its own address.", method);
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
+ }
895
+ const sealed = await sealFiles(access);
896
+ let rest = "";
897
+ if ("files" in served) {
898
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
899
+ rest =
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
+ : "";
910
+ }
911
+ const shell = nestedShellResponse(served.compiled, {
912
+ origin: access.origin,
913
+ origins: options.hostOrigins,
914
+ page: `${access.origin}${sealed.base}${rest}`,
915
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
916
+ method,
917
+ });
918
+ if (cookie !== null) {
919
+ shell.headers.set("set-cookie", cookie);
920
+ }
921
+ return shell;
922
+ }
923
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
924
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
818
925
  if ("files" in served) {
819
926
  if (at !== undefined) {
820
927
  return serveFile({
@@ -828,7 +935,7 @@ export function createServer(options) {
828
935
  source: at.source,
829
936
  compiled: served.compiled,
830
937
  hostOrigins: options.hostOrigins,
831
- frameAncestors,
938
+ frameAncestors: ancestors,
832
939
  ...versionOf(access.instance),
833
940
  });
834
941
  }
@@ -859,11 +966,48 @@ export function createServer(options) {
859
966
  // A page that may use its artifact's assets loads them from its own origin (P089); every
860
967
  // served page carries its frame's sandbox, a tab of its own included (P099).
861
968
  const { config, cspDirectives } = served.compiled;
862
- const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config));
969
+ const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config), ancestors);
863
970
  if (cookie !== null) {
864
971
  headers.set("set-cookie", cookie);
865
972
  }
866
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
973
+ // A nested page's document takes messages from its shell, on its own origin (P111).
974
+ const html = nested
975
+ ? served.compiled.shellDocument({
976
+ origins: [access.origin],
977
+ document: served.document ?? "",
978
+ cspMeta: false,
979
+ })
980
+ : served.html;
981
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
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
+ });
867
1011
  }
868
1012
  /**
869
1013
  * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
@@ -995,7 +1139,7 @@ export function createServer(options) {
995
1139
  let instance;
996
1140
  try {
997
1141
  instance = cleanInstance(session.i);
998
- if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
1142
+ if (instance.document.kind !== "artifact" || labelFor(instance) !== label) {
999
1143
  continue;
1000
1144
  }
1001
1145
  }
@@ -1094,7 +1238,7 @@ export function createServer(options) {
1094
1238
  if (method !== "GET") {
1095
1239
  return page(405, "Not allowed", "Open this link in a browser.", method);
1096
1240
  }
1097
- const record = await take(url.searchParams.get("code"), label);
1241
+ const record = await take(url.searchParams.get("code"), label, true);
1098
1242
  if (record?.entry === undefined) {
1099
1243
  return page(403, "This sign-in link has been used", "It works once, for a short time. Open the address again.", method, "session");
1100
1244
  }
@@ -1232,6 +1376,28 @@ export function createServer(options) {
1232
1376
  return page(502, "The app didn't answer", "Its server couldn't be reached.", method);
1233
1377
  }
1234
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
+ }
1235
1401
  /** A one-time ticket (or entry code) for an instance the host decided a viewer may see. */
1236
1402
  async function mint(instance, grant, entry) {
1237
1403
  const clean = cleanInstance(instance);
@@ -1331,7 +1497,8 @@ export function createServer(options) {
1331
1497
  originFor: (scope) => originOfLabel(nameOf(scope)),
1332
1498
  async issue(instance, grant) {
1333
1499
  const { clean, key, ticket } = await mint(instance, grant);
1334
- 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));
1335
1502
  const path = clean.document.kind === "external"
1336
1503
  ? `${ENTER_PATH}?ticket=${ticket}`
1337
1504
  : `${PREFIX}d/${key}?ticket=${ticket}`;
@@ -1444,6 +1611,9 @@ export function createServer(options) {
1444
1611
  if (!ours(label)) {
1445
1612
  return page(404, "Nothing here", "This address names no content.", method);
1446
1613
  }
1614
+ if (isNestedLabel(label)) {
1615
+ return await serveShellLabel(request, url, label);
1616
+ }
1447
1617
  if (url.pathname === ENTER_PATH) {
1448
1618
  return await enter(request, url, label);
1449
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
- * 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
+ * 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