@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,116 @@
1
+ import type { CompiledConfig } from "../compile/compile.ts";
2
+ import { servedPermissionsPolicy, serializeCsp, type CspDirective } from "../compile/policy.ts";
3
+ import { frameShellDocument, frameShellScript, type FrameShellOptions } from "../shell/frame.ts";
4
+ import { sha256, utf8 } from "./crypto.ts";
5
+ import { base32 } from "./keys.ts";
6
+
7
+ /**
8
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
9
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
10
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
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.
17
+ */
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
+
43
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
44
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
45
+
46
+ const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
47
+
48
+ /**
49
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
50
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
51
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
52
+ * this (a framed URL's document never does).
53
+ */
54
+ export function nestedShellCsp(
55
+ script: string,
56
+ origin: string,
57
+ hostOrigins: readonly string[],
58
+ ): string {
59
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
60
+ const directives: CspDirective[] = [
61
+ ["default-src", "'none'"],
62
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
63
+ ["frame-src", files],
64
+ ["connect-src", files],
65
+ ["base-uri", "'none'"],
66
+ ["form-action", "'none'"],
67
+ ["frame-ancestors", ...hostOrigins],
68
+ ];
69
+ return serializeCsp(directives);
70
+ }
71
+
72
+ /**
73
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
74
+ * stored (it carries the page's sealed address), its page at `options.page`.
75
+ */
76
+ export function nestedShellResponse(
77
+ compiled: CompiledConfig,
78
+ options: FrameShellOptions & { readonly origin: string; readonly method?: string },
79
+ ): Response {
80
+ const script = frameShellScript(options);
81
+ const headers = new Headers({
82
+ "content-type": "text/html; charset=utf-8",
83
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
84
+ "cache-control": "no-store",
85
+ "referrer-policy": "no-referrer",
86
+ "x-content-type-options": "nosniff",
87
+ "x-robots-tag": "noindex, nofollow",
88
+ });
89
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
90
+ const permissions = servedPermissionsPolicy(compiled.config);
91
+ if (permissions !== null) {
92
+ headers.set("permissions-policy", permissions);
93
+ }
94
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
95
+ status: 200,
96
+ headers,
97
+ });
98
+ }
99
+
100
+ /**
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).
103
+ */
104
+ export const nestedAncestors = (origin: string, frameAncestors: string): string =>
105
+ `${origin} ${frameAncestors}`;
106
+
107
+ /**
108
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
109
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
110
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
111
+ * is their access, never the request's origin.
112
+ */
113
+ export const NESTED_FILE_HEADERS: Readonly<Record<string, string>> = {
114
+ "cross-origin-resource-policy": "cross-origin",
115
+ "access-control-allow-origin": "*",
116
+ };
@@ -13,7 +13,15 @@ import { randomBytes } from "./crypto.ts";
13
13
  import { isHostLabel, reservedLabels } from "./naming.ts";
14
14
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.ts";
15
15
  import { libraryFile } from "./libraries.ts";
16
- import { ownLoad, serveAsset, serveFile } from "./files.ts";
16
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.ts";
17
+ import {
18
+ isNestedLabel,
19
+ nestedAncestors,
20
+ nestedLabelOf,
21
+ nestedShellResponse,
22
+ PORTHOLE_LABEL_PREFIX,
23
+ } from "./nested.ts";
24
+ import { DEFAULT_ENTRY } from "../files/paths.ts";
17
25
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.ts";
18
26
  import {
19
27
  assetCodeRuns,
@@ -68,6 +76,23 @@ const BASE = /^\/(?:(?!\.{1,2}\/)[A-Za-z0-9._:~-]{1,200}\/){0,16}$/u;
68
76
  const ENTER_PATH = "/__porthole/enter";
69
77
  /** Where a redirect entry's code is redeemed, before its clean address (P068). */
70
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
+ );
71
96
  /** How long a redirect entry may take (the person may sign in on the way), and its code. */
72
97
  const ENTRY_STATE_MS = 5 * 60_000;
73
98
  const ENTRY_CODE_SECONDS = 60;
@@ -309,16 +334,39 @@ export function createServer(options: ServerOptions): PortholeServer {
309
334
  return keys.label(scope);
310
335
  }
311
336
  const label = content.name(scope);
312
- if (!isHostLabel(label) || isReserved(label)) {
337
+ if (!isHostLabel(label) || isReserved(label) || label.startsWith(PORTHOLE_LABEL_PREFIX)) {
313
338
  throw new TypeError(
314
- `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}…)`,
315
340
  );
316
341
  }
317
342
  return label;
318
343
  };
319
- /** 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). */
320
365
  const ours = (label: string): boolean =>
321
- !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))));
322
370
  const secure = content.scheme === "https";
323
371
  const defaultPort = secure ? 443 : 80;
324
372
  const portPart =
@@ -328,6 +376,7 @@ export function createServer(options: ServerOptions): PortholeServer {
328
376
  const contentSource = `${content.scheme}://*.${domain}${portPart}`;
329
377
  const sampleHost = `${keys.label("")}.${domain}`;
330
378
  const sampleOrigin = originOfLabel(keys.label(""));
379
+ const sampleNestedOrigin = originOfLabel(nestedLabelOf(keys.label("")));
331
380
  const authorize = options.authorize;
332
381
  const authorizeTtl = authorize?.ttlSeconds ?? 0;
333
382
  if (!Number.isInteger(authorizeTtl) || authorizeTtl < 0 || authorizeTtl > 300) {
@@ -469,7 +518,13 @@ export function createServer(options: ServerOptions): PortholeServer {
469
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`,
470
519
  );
471
520
  }
472
- 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
+ ) {
473
528
  throw new TypeError(
474
529
  `The config ${JSON.stringify(name)}'s contentOrigins don't include this server's (${contentSource})`,
475
530
  );
@@ -520,6 +575,8 @@ export function createServer(options: ServerOptions): PortholeServer {
520
575
  async function documentOf(instance: InstanceRef): Promise<
521
576
  | {
522
577
  readonly html: string;
578
+ /** An artifact's own page, before the shell (a nested page's is made apart, P111). */
579
+ readonly document?: string;
523
580
  readonly compiled: CompiledConfig;
524
581
  /** Whether its CSP opens its artifact's asset library (P089): an artifact's page. */
525
582
  readonly assets: boolean;
@@ -554,6 +611,7 @@ export function createServer(options: ServerOptions): PortholeServer {
554
611
  }
555
612
  return {
556
613
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
614
+ document: stored.html,
557
615
  compiled: config,
558
616
  assets: true,
559
617
  };
@@ -682,7 +740,7 @@ export function createServer(options: ServerOptions): PortholeServer {
682
740
  }
683
741
  let named: string;
684
742
  try {
685
- named = nameOf(instance.scope);
743
+ named = labelFor(instance);
686
744
  } catch {
687
745
  continue;
688
746
  }
@@ -790,8 +848,15 @@ export function createServer(options: ServerOptions): PortholeServer {
790
848
  return best;
791
849
  }
792
850
 
793
- /** A taken ticket, if it is good for `label`'s origin. */
794
- 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> {
795
860
  if (ticket === null || ticket.length === 0 || ticket.length > 128) {
796
861
  return null;
797
862
  }
@@ -801,16 +866,22 @@ export function createServer(options: ServerOptions): PortholeServer {
801
866
  }
802
867
  try {
803
868
  const instance = cleanInstance(record.instance);
804
- return nameOf(instance.scope) === label ? { ...record, instance } : null;
869
+ return (entry ? nameOf(instance.scope) : labelFor(instance)) === label
870
+ ? { ...record, instance }
871
+ : null;
805
872
  } catch {
806
873
  return null;
807
874
  }
808
875
  }
809
876
 
810
- function documentHeaders(csp: string, permissions: string | null): Headers {
877
+ function documentHeaders(
878
+ csp: string,
879
+ permissions: string | null,
880
+ ancestors: string = frameAncestors,
881
+ ): Headers {
811
882
  return new Headers({
812
883
  "content-type": "text/html; charset=utf-8",
813
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
884
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
814
885
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
815
886
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
816
887
  "cache-control": "no-store",
@@ -847,7 +918,13 @@ export function createServer(options: ServerOptions): PortholeServer {
847
918
  } catch {
848
919
  return null;
849
920
  }
850
- 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) {
851
928
  return null;
852
929
  }
853
930
  return {
@@ -905,19 +982,24 @@ export function createServer(options: ServerOptions): PortholeServer {
905
982
  }
906
983
  const access = await sealedAccess(request, label, token);
907
984
  if (access === null) {
908
- return page(
985
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
986
+ // config without nesting never frames this address but at the host.
987
+ return statusPage(
909
988
  401,
910
989
  "This has ended",
911
990
  "Content here opens for a while. Open it again from the app that showed it.",
991
+ nestedAncestors(origin, frameAncestors),
912
992
  method,
913
993
  "session",
994
+ [...options.hostOrigins, origin],
914
995
  );
915
996
  }
916
997
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
917
998
  // sends a frame's path, where some send no Referer that names it.
918
999
  const blob = SEALED_ASSET.exec(rest)?.[1];
919
1000
  if (blob !== undefined) {
920
- 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)) {
921
1003
  return page(404, "Not found", "This address names no content.", method);
922
1004
  }
923
1005
  return (
@@ -974,8 +1056,10 @@ export function createServer(options: ServerOptions): PortholeServer {
974
1056
  // The ticket's own answer carries the document: an engine that keeps no cookie in a frame
975
1057
  // still shows it. The cookie serves what follows (a reload), where the engine keeps it.
976
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).
977
1060
  if (
978
1061
  record !== null &&
1062
+ record.entry === undefined &&
979
1063
  record.instance.document.kind !== "external" &&
980
1064
  keys.instanceKey(record.instance) === key
981
1065
  ) {
@@ -999,7 +1083,10 @@ export function createServer(options: ServerOptions): PortholeServer {
999
1083
  "session",
1000
1084
  );
1001
1085
  }
1002
- 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);
1003
1090
  }
1004
1091
 
1005
1092
  /**
@@ -1011,6 +1098,8 @@ export function createServer(options: ServerOptions): PortholeServer {
1011
1098
  access: Access,
1012
1099
  cookie: string | null,
1013
1100
  at?: FilesAt,
1101
+ /** A nested page's path below its files' base, from its hop's ticket (P114). */
1102
+ pageAt?: string,
1014
1103
  ): Promise<Response> {
1015
1104
  const method = request.method.toUpperCase();
1016
1105
  const refusal = await denied(request, access);
@@ -1021,6 +1110,51 @@ export function createServer(options: ServerOptions): PortholeServer {
1021
1110
  if (served === null) {
1022
1111
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1023
1112
  }
1113
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
1114
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
1115
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
1116
+ const nested = served.compiled.config.nested === true;
1117
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
1118
+ if (nested && !sealedAt) {
1119
+ if (!isNavigation(request)) {
1120
+ return page(404, "Not found", "This page's files are at its own address.", method);
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
+ }
1128
+ const sealed = await sealFiles(access);
1129
+ let rest = "";
1130
+ if ("files" in served) {
1131
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
1132
+ rest =
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
+ : "";
1143
+ }
1144
+ const shell = nestedShellResponse(served.compiled, {
1145
+ origin: access.origin,
1146
+ origins: options.hostOrigins,
1147
+ page: `${access.origin}${sealed.base}${rest}`,
1148
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
1149
+ method,
1150
+ });
1151
+ if (cookie !== null) {
1152
+ shell.headers.set("set-cookie", cookie);
1153
+ }
1154
+ return shell;
1155
+ }
1156
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
1157
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
1024
1158
  if ("files" in served) {
1025
1159
  if (at !== undefined) {
1026
1160
  return serveFile({
@@ -1034,7 +1168,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1034
1168
  source: at.source,
1035
1169
  compiled: served.compiled,
1036
1170
  hostOrigins: options.hostOrigins,
1037
- frameAncestors,
1171
+ frameAncestors: ancestors,
1038
1172
  ...versionOf(access.instance),
1039
1173
  });
1040
1174
  }
@@ -1071,11 +1205,53 @@ export function createServer(options: ServerOptions): PortholeServer {
1071
1205
  served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives,
1072
1206
  ),
1073
1207
  servedPermissionsPolicy(config),
1208
+ ancestors,
1074
1209
  );
1075
1210
  if (cookie !== null) {
1076
1211
  headers.set("set-cookie", cookie);
1077
1212
  }
1078
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
1213
+ // A nested page's document takes messages from its shell, on its own origin (P111).
1214
+ const html = nested
1215
+ ? served.compiled.shellDocument({
1216
+ origins: [access.origin],
1217
+ document: served.document ?? "",
1218
+ cspMeta: false,
1219
+ })
1220
+ : served.html;
1221
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
1222
+ }
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
+ });
1079
1255
  }
1080
1256
 
1081
1257
  /**
@@ -1216,7 +1392,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1216
1392
  let instance: InstanceRef;
1217
1393
  try {
1218
1394
  instance = cleanInstance(session.i);
1219
- if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
1395
+ if (instance.document.kind !== "artifact" || labelFor(instance) !== label) {
1220
1396
  continue;
1221
1397
  }
1222
1398
  } catch {
@@ -1330,7 +1506,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1330
1506
  if (method !== "GET") {
1331
1507
  return page(405, "Not allowed", "Open this link in a browser.", method);
1332
1508
  }
1333
- const record = await take(url.searchParams.get("code"), label);
1509
+ const record = await take(url.searchParams.get("code"), label, true);
1334
1510
  if (record?.entry === undefined) {
1335
1511
  return page(
1336
1512
  403,
@@ -1515,6 +1691,29 @@ export function createServer(options: ServerOptions): PortholeServer {
1515
1691
  }
1516
1692
  }
1517
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
+
1518
1717
  /** A one-time ticket (or entry code) for an instance the host decided a viewer may see. */
1519
1718
  async function mint(
1520
1719
  instance: InstanceRef,
@@ -1634,7 +1833,8 @@ export function createServer(options: ServerOptions): PortholeServer {
1634
1833
 
1635
1834
  async issue(instance, grant): Promise<FrameLocation> {
1636
1835
  const { clean, key, ticket } = await mint(instance, grant);
1637
- 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));
1638
1838
  const path =
1639
1839
  clean.document.kind === "external"
1640
1840
  ? `${ENTER_PATH}?ticket=${ticket}`
@@ -1773,6 +1973,9 @@ export function createServer(options: ServerOptions): PortholeServer {
1773
1973
  if (!ours(label)) {
1774
1974
  return page(404, "Nothing here", "This address names no content.", method);
1775
1975
  }
1976
+ if (isNestedLabel(label)) {
1977
+ return await serveShellLabel(request, url, label);
1978
+ }
1776
1979
  if (url.pathname === ENTER_PATH) {
1777
1980
  return await enter(request, url, label);
1778
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). */