@botiverse/porthole 0.14.18 → 0.15.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.
@@ -2,6 +2,7 @@ import { compile, type CompiledConfig } from "../compile/compile.ts";
2
2
  import type { DisplayMode, EgressConfig } from "../config/schema.ts";
3
3
  import {
4
4
  framedByProblem,
5
+ includesOrigin,
5
6
  hostOriginProblem,
6
7
  maybeSameSite,
7
8
  originMatchesSource,
@@ -132,6 +133,8 @@ const DEFAULT_SESSION_SECONDS = 3_600;
132
133
  const MAX_SESSION_SECONDS = 30 * 24 * 3_600;
133
134
  /** Browsers keep a cookie of up to 4 KB, name and attributes included. */
134
135
  const MAX_COOKIE_BYTES = 3_800;
136
+ /** Who may frame an embed session's answers (P143): any page. That session's alone. */
137
+ const EMBED_ANCESTORS = "*";
135
138
 
136
139
  /** A host (and port) as it compares: lowercase, no trailing dot, no default port. */
137
140
  function normalHost(value: string, protocol: string): string {
@@ -161,6 +164,11 @@ interface Session {
161
164
  readonly b?: string;
162
165
  /** Whether the base is the version's own address (the app said so): its files are immutable. */
163
166
  readonly k?: 1;
167
+ /**
168
+ * An embed session (P143): framed by any page, its documents hostless. Not `e`: a sealed
169
+ * address's `e` is its session's end, and a redirect entry's state is marked `e`.
170
+ */
171
+ readonly m?: 1;
164
172
  }
165
173
 
166
174
  /** Where a request falls under a file set's base: the base, and the path below it. */
@@ -446,7 +454,7 @@ export function createServer(options: ServerOptions): PortholeServer {
446
454
  if (problem !== null) {
447
455
  throw new TypeError(`framedBy: ${problem}`);
448
456
  }
449
- if (options.hostOrigins.includes(origin)) {
457
+ if (includesOrigin(options.hostOrigins, origin)) {
450
458
  throw new TypeError(
451
459
  `framedBy: ${origin} is a host origin already: framedBy names an ancestor that never talks to a frame`,
452
460
  );
@@ -462,13 +470,22 @@ export function createServer(options: ServerOptions): PortholeServer {
462
470
  `framedBy: ${origin} may be the same site as the content domain ${domain}: serve content from a registrable domain the host uses for nothing else`,
463
471
  );
464
472
  }
465
- if (!framedBy.includes(origin)) {
473
+ if (!includesOrigin(framedBy, origin)) {
466
474
  framedBy.push(origin);
467
475
  }
468
476
  }
469
477
  // Who may be an ancestor of a frame served here: the host origins, then the outer pages' (P141).
470
478
  // Every frame's `frame-ancestors` is this; whom a frame hears and tells is `hostOrigins` alone.
471
479
  const frameAncestors = [...options.hostOrigins, ...framedBy].join(" ");
480
+ // Embed grants (P143): taken only where the host opted in. Off, a session or sealed address
481
+ // that says it is one opens nothing.
482
+ if (options.embeds !== undefined && typeof options.embeds !== "boolean") {
483
+ throw new TypeError("embeds is true or false");
484
+ }
485
+ const embeds = options.embeds === true;
486
+ /** Who may frame an access's answers: any page for an embed session (P143), else the list. */
487
+ const ancestorsFor = (access: Access): string =>
488
+ access.embed === true ? EMBED_ANCESTORS : frameAncestors;
472
489
  let authorizeUrl: URL | null = null;
473
490
  if (options.entry !== undefined) {
474
491
  try {
@@ -489,7 +506,10 @@ export function createServer(options: ServerOptions): PortholeServer {
489
506
  }
490
507
  const tickets: TicketStore = options.tickets ?? memoryTicketStore();
491
508
 
492
- /** A page saying why there is nothing to show, told to the host too (its reason, P040). */
509
+ /**
510
+ * A page saying why there is nothing to show, told to the host too (its reason, P040). An embed
511
+ * session's (P143, `embed`): framed by any page, and told to no one (it names no host).
512
+ */
493
513
  const page = (
494
514
  status: number,
495
515
  title: string,
@@ -497,8 +517,20 @@ export function createServer(options: ServerOptions): PortholeServer {
497
517
  method?: string,
498
518
  reason: FrameBlock = status === 404 ? "not-found" : status === 502 ? "upstream" : "error",
499
519
  code?: string,
520
+ embed = false,
500
521
  ): Response =>
501
- statusPage(status, title, detail, frameAncestors, method, reason, options.hostOrigins, code);
522
+ embed
523
+ ? statusPage(status, title, detail, EMBED_ANCESTORS, method, reason, [], code)
524
+ : statusPage(
525
+ status,
526
+ title,
527
+ detail,
528
+ frameAncestors,
529
+ method,
530
+ reason,
531
+ options.hostOrigins,
532
+ code,
533
+ );
502
534
 
503
535
  /**
504
536
  * The host's check on a request its cookie (or ticket) let in (P050): null to go on, or the
@@ -515,6 +547,7 @@ export function createServer(options: ServerOptions): PortholeServer {
515
547
  request.method.toUpperCase(),
516
548
  "denied",
517
549
  refused.code,
550
+ access.embed === true,
518
551
  );
519
552
  }
520
553
 
@@ -531,6 +564,8 @@ export function createServer(options: ServerOptions): PortholeServer {
531
564
  access.viewer,
532
565
  access.subject ?? null,
533
566
  access.expiresAt,
567
+ // An embed session's answer is its own (P143): never reused for another session.
568
+ ...(access.embed === true ? ["embed"] : []),
534
569
  ]);
535
570
  const at = Date.now();
536
571
  let answer = authorizeTtl > 0 ? answers.get(key) : undefined;
@@ -543,6 +578,7 @@ export function createServer(options: ServerOptions): PortholeServer {
543
578
  viewer: access.viewer,
544
579
  anonymous: access.anonymous === true,
545
580
  ...(access.subject === undefined ? {} : { subject: access.subject }),
581
+ ...(access.embed === true ? { embed: true as const } : {}),
546
582
  request,
547
583
  });
548
584
  } catch {
@@ -636,7 +672,11 @@ export function createServer(options: ServerOptions): PortholeServer {
636
672
  }
637
673
  }
638
674
 
639
- async function documentOf(instance: InstanceRef): Promise<
675
+ async function documentOf(
676
+ instance: InstanceRef,
677
+ /** An embed session's (P143): its shell's plan names no host. */
678
+ embed = false,
679
+ ): Promise<
640
680
  | {
641
681
  readonly html: string;
642
682
  /** An artifact's own page, before the shell (a nested page's is made apart, P111). */
@@ -653,7 +693,7 @@ export function createServer(options: ServerOptions): PortholeServer {
653
693
  if (config === null) {
654
694
  return null;
655
695
  }
656
- const origins = options.hostOrigins;
696
+ const origins = embed ? [] : options.hostOrigins;
657
697
  switch (document.kind) {
658
698
  case "shell":
659
699
  return {
@@ -704,6 +744,15 @@ export function createServer(options: ServerOptions): PortholeServer {
704
744
  */
705
745
  const ourCookie = (name: string): boolean =>
706
746
  name.startsWith(secure ? "__Host-porthole-" : "porthole-");
747
+ /**
748
+ * A session's cookie name, by its instance's key: an embed session's (P143) is a name of its own
749
+ * (`e-<key>`), so it never takes the place of another session of the same instance, which the
750
+ * same browser may hold where it partitions no cookies, and is never read as one.
751
+ */
752
+ const sessionName = (key: string, embed: boolean): string => cookieName(embed ? `e-${key}` : key);
753
+ /** Whether a verified session says it is an embed session (P143), checked: `m` is 1 or absent. */
754
+ const embedOf = (session: Record<string, unknown>): boolean | null =>
755
+ session.m === undefined ? false : session.m === 1 ? true : null;
707
756
 
708
757
  /**
709
758
  * The cookie a taken ticket buys: this origin only (`__Host-` over https), never readable by the
@@ -717,6 +766,7 @@ export function createServer(options: ServerOptions): PortholeServer {
717
766
  at: { readonly p?: string; readonly b?: string; readonly k?: 1 } = {},
718
767
  ): string {
719
768
  const sessionSeconds = record.sessionSeconds ?? DEFAULT_SESSION_SECONDS;
769
+ const embed = record.embed === true;
720
770
  const session: Session = {
721
771
  i: record.instance,
722
772
  w: record.viewer,
@@ -726,9 +776,10 @@ export function createServer(options: ServerOptions): PortholeServer {
726
776
  ...(at.p === undefined ? {} : { p: at.p }),
727
777
  ...(at.b === undefined ? {} : { b: at.b }),
728
778
  ...(at.k === undefined ? {} : { k: at.k }),
779
+ ...(embed ? { m: 1 as const } : {}),
729
780
  };
730
781
  return [
731
- `${cookieName(keys.instanceKey(record.instance))}=${keys.sign(session)}`,
782
+ `${sessionName(keys.instanceKey(record.instance), embed)}=${keys.sign(session)}`,
732
783
  "Path=/",
733
784
  "HttpOnly",
734
785
  `Max-Age=${sessionSeconds}`,
@@ -783,7 +834,10 @@ export function createServer(options: ServerOptions): PortholeServer {
783
834
  function accessOf(request: Request, label: string, key: string | null): Access | null {
784
835
  let best: Access | null = null;
785
836
  for (const [name, value] of cookiesOf(request)) {
786
- if (!(key === null ? ourCookie(name) : name === cookieName(key))) {
837
+ // An embed session (P143) only by its own name, for an instance's document, where embeds
838
+ // are on; every other session by the instance's name (or, for an app, any of ours).
839
+ const embedName = key !== null && embeds && name === sessionName(key, true);
840
+ if (!(embedName || (key === null ? ourCookie(name) : name === sessionName(key, false)))) {
787
841
  continue;
788
842
  }
789
843
  const session = keys.verify(value);
@@ -792,7 +846,8 @@ export function createServer(options: ServerOptions): PortholeServer {
792
846
  typeof session.w !== "string" ||
793
847
  typeof session.x !== "number" ||
794
848
  session.x <= Date.now() ||
795
- (session.s !== undefined && typeof session.s !== "string")
849
+ (session.s !== undefined && typeof session.s !== "string") ||
850
+ embedOf(session) !== embedName
796
851
  ) {
797
852
  continue;
798
853
  }
@@ -814,7 +869,13 @@ export function createServer(options: ServerOptions): PortholeServer {
814
869
  ) {
815
870
  continue;
816
871
  }
817
- if (best === null || session.x > best.expiresAt) {
872
+ // Any other session before an embed session (P143), then the latest to end: where a browser
873
+ // holds both (it partitions no cookies), the other session is never changed by it.
874
+ if (
875
+ best === null ||
876
+ (best.embed === true && !embedName) ||
877
+ ((best.embed === true) === embedName && session.x > best.expiresAt)
878
+ ) {
818
879
  best = {
819
880
  instance,
820
881
  viewer: session.w,
@@ -822,6 +883,7 @@ export function createServer(options: ServerOptions): PortholeServer {
822
883
  expiresAt: session.x,
823
884
  ...(session.a === 1 ? { anonymous: true } : {}),
824
885
  ...(typeof session.s === "string" ? { subject: session.s } : {}),
886
+ ...(embedName ? { embed: true as const } : {}),
825
887
  };
826
888
  }
827
889
  }
@@ -855,7 +917,9 @@ export function createServer(options: ServerOptions): PortholeServer {
855
917
  const base = typeof session.b === "string" && BASE.test(session.b) ? session.b : null;
856
918
  const under = base !== null && pathname.startsWith(base);
857
919
  const atBase = base !== null && `${pathname}/` === base;
920
+ // A clean address is never an embed session's (P143): only an entry code opens one.
858
921
  if (
922
+ embedOf(session) !== false ||
859
923
  (session.p !== pathname && !under && !atBase) ||
860
924
  typeof session.w !== "string" ||
861
925
  typeof session.x !== "number" ||
@@ -976,6 +1040,11 @@ export function createServer(options: ServerOptions): PortholeServer {
976
1040
  return null;
977
1041
  }
978
1042
  const open = session.x > now || (session.e > now && ownLoad(request));
1043
+ // An embed session's address (P143) opens only where embeds are on.
1044
+ const embed = embedOf(session);
1045
+ if (embed === null || (embed && !embeds)) {
1046
+ return null;
1047
+ }
979
1048
  let instance: InstanceRef;
980
1049
  try {
981
1050
  instance = cleanInstance(session.i);
@@ -998,9 +1067,30 @@ export function createServer(options: ServerOptions): PortholeServer {
998
1067
  expiresAt: session.e,
999
1068
  ...(session.a === 1 ? { anonymous: true } : {}),
1000
1069
  ...(typeof session.s === "string" ? { subject: session.s } : {}),
1070
+ ...(embed ? { embed: true as const } : {}),
1001
1071
  };
1002
1072
  }
1003
1073
 
1074
+ /**
1075
+ * Whether a sealed address that no longer opens was an embed session's of this origin (P143):
1076
+ * sealed by this server (so its `m` is this server's word), where embeds are on. Its ended
1077
+ * access is then said where its frame is, below any page.
1078
+ */
1079
+ async function sealedEmbed(label: string, token: string): Promise<boolean> {
1080
+ if (!embeds) {
1081
+ return false;
1082
+ }
1083
+ const session = await keys.unseal(token);
1084
+ if (!isRecord(session) || embedOf(session) !== true) {
1085
+ return false;
1086
+ }
1087
+ try {
1088
+ return labelFor(cleanInstance(session.i)) === label;
1089
+ } catch {
1090
+ return false;
1091
+ }
1092
+ }
1093
+
1004
1094
  /**
1005
1095
  * A file set's file in a frame (P083): the sealed access in its path opens it, once it holds
1006
1096
  * for this origin and the host's check lets it in; every path under it is the same version's.
@@ -1017,6 +1107,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1017
1107
  e: access.expiresAt,
1018
1108
  ...(access.anonymous === true ? { a: 1 } : {}),
1019
1109
  ...(access.subject === undefined ? {} : { s: access.subject }),
1110
+ ...(access.embed === true ? { m: 1 } : {}),
1020
1111
  });
1021
1112
  return { base: `${FILES_PREFIX}${token}/`, expires };
1022
1113
  }
@@ -1046,6 +1137,18 @@ export function createServer(options: ServerOptions): PortholeServer {
1046
1137
  }
1047
1138
  const access = await sealedAccess(request, label, token);
1048
1139
  if (access === null) {
1140
+ // An embed session's ended access (P143): where its frame is, below any page, told no one.
1141
+ if (await sealedEmbed(label, token)) {
1142
+ return page(
1143
+ 401,
1144
+ "This has ended",
1145
+ "Content here opens for a while. Open it again from the page that showed it.",
1146
+ method,
1147
+ "session",
1148
+ undefined,
1149
+ true,
1150
+ );
1151
+ }
1049
1152
  // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
1050
1153
  // config without nesting never frames this address but at the host.
1051
1154
  return statusPage(
@@ -1063,18 +1166,33 @@ export function createServer(options: ServerOptions): PortholeServer {
1063
1166
  const blob = SEALED_ASSET.exec(rest)?.[1];
1064
1167
  if (blob !== undefined) {
1065
1168
  // A nested page loads no assets (its config refuses them): none on its shell's label (P114).
1169
+ const none = () =>
1170
+ page(
1171
+ 404,
1172
+ "Not found",
1173
+ "This address names no content.",
1174
+ method,
1175
+ undefined,
1176
+ undefined,
1177
+ access.embed === true,
1178
+ );
1066
1179
  if (options.assets === undefined || isNestedLabel(label)) {
1067
- return page(404, "Not found", "This address names no content.", method);
1180
+ return none();
1068
1181
  }
1069
- return (
1070
- (await assetFor(request, label, access, blob)) ??
1071
- page(404, "Not found", "This address names no content.", method)
1072
- );
1182
+ return (await assetFor(request, label, access, blob)) ?? none();
1073
1183
  }
1074
1184
  if (rest === RENEW_PATH) {
1075
1185
  // Only the page itself renews its address, while its session lasts and the host lets it.
1076
1186
  if (method !== "GET" || !ownLoad(request)) {
1077
- return page(403, "Not allowed", "Only the page renews its own address.", method);
1187
+ return page(
1188
+ 403,
1189
+ "Not allowed",
1190
+ "Only the page renews its own address.",
1191
+ method,
1192
+ undefined,
1193
+ undefined,
1194
+ access.embed === true,
1195
+ );
1078
1196
  }
1079
1197
  const refusal = await denied(request, access);
1080
1198
  if (refusal !== null) {
@@ -1088,7 +1206,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1088
1206
  "cache-control": "no-store",
1089
1207
  "x-content-type-options": "nosniff",
1090
1208
  "cross-origin-resource-policy": "same-origin",
1091
- "content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${frameAncestors}`,
1209
+ "content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${ancestorsFor(access)}`,
1092
1210
  "referrer-policy": "no-referrer",
1093
1211
  },
1094
1212
  },
@@ -1122,10 +1240,12 @@ export function createServer(options: ServerOptions): PortholeServer {
1122
1240
  const record = method === "GET" ? await take(url.searchParams.get("ticket"), label) : null;
1123
1241
  // An entry code opens its clean address alone, through its own browser's nonce (P068, P114).
1124
1242
  // A door's ticket is the door's alone (P125): here it is no ticket.
1243
+ // An embed grant's ticket (P143) opens only where embeds are on.
1125
1244
  if (
1126
1245
  record !== null &&
1127
1246
  record.entry === undefined &&
1128
1247
  record.door !== true &&
1248
+ (record.embed !== true || embeds) &&
1129
1249
  record.instance.document.kind !== "external" &&
1130
1250
  keys.instanceKey(record.instance) === key
1131
1251
  ) {
@@ -1137,6 +1257,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1137
1257
  expiresAt: Date.now() + (record.sessionSeconds ?? DEFAULT_SESSION_SECONDS) * 1_000,
1138
1258
  ...(record.anonymous === true ? { anonymous: true } : {}),
1139
1259
  ...(record.subject === undefined ? {} : { subject: record.subject }),
1260
+ ...(record.embed === true ? { embed: true as const } : {}),
1140
1261
  };
1141
1262
  }
1142
1263
  access ??= accessOf(request, label, key);
@@ -1188,6 +1309,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1188
1309
  if (
1189
1310
  record === null ||
1190
1311
  record.door !== true ||
1312
+ record.embed === true ||
1191
1313
  record.entry !== undefined ||
1192
1314
  record.instance.document.kind === "external" ||
1193
1315
  keys.instanceKey(record.instance) !== key ||
@@ -1268,14 +1390,26 @@ export function createServer(options: ServerOptions): PortholeServer {
1268
1390
  if (refusal !== null) {
1269
1391
  return refusal;
1270
1392
  }
1271
- const served = await documentOf(access.instance);
1393
+ // An embed session (P143): every answer below framed by any page, its documents hostless.
1394
+ const embed = access.embed === true;
1395
+ const missing = () =>
1396
+ page(
1397
+ 404,
1398
+ "Not found",
1399
+ "This page, or this version of it, doesn't exist.",
1400
+ method,
1401
+ undefined,
1402
+ undefined,
1403
+ embed,
1404
+ );
1405
+ const served = await documentOf(access.instance, embed);
1272
1406
  if (served === null) {
1273
- return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1407
+ return missing();
1274
1408
  }
1275
1409
  // A frame's document opens at its file set's entry, which is a page (P125, P124-2): a set
1276
1410
  // stored before that was checked shows Porthole's word, never an inert file that says nothing.
1277
1411
  if ("files" in served && at === undefined && !entryIsPage(served.files)) {
1278
- return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1412
+ return missing();
1279
1413
  }
1280
1414
  // A page below a base (P125) names a file set's page: for one page alone, nothing; for a set,
1281
1415
  // the page the frame opens at (its entry, or the page it was issued for) must be one of its
@@ -1284,7 +1418,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1284
1418
  at === undefined &&
1285
1419
  ("files" in served ? ticketPage(served.files, pageAt) === null : pageAt !== undefined)
1286
1420
  ) {
1287
- return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1421
+ return missing();
1288
1422
  }
1289
1423
  // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
1290
1424
  // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
@@ -1330,13 +1464,19 @@ export function createServer(options: ServerOptions): PortholeServer {
1330
1464
  }
1331
1465
  return shell;
1332
1466
  }
1333
- // Below the sealed prefix, a nested page and its files are framed by its shell too.
1334
- const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
1467
+ // Below the sealed prefix, a nested page and its files are framed by its shell too. An embed
1468
+ // session is never nested (`issue`): its answers are framed by any page (P143).
1469
+ const ancestors = nested
1470
+ ? nestedAncestors(access.origin, frameAncestors)
1471
+ : ancestorsFor(access);
1472
+ // Whom its pages hear and tell: the host origins, or no one for an embed session (P143).
1473
+ const hostOrigins = embed ? [] : options.hostOrigins;
1335
1474
  if ("files" in served) {
1336
1475
  if (at !== undefined) {
1337
1476
  // A page's own frames (P128): its files below the base are framed by its own pages too,
1338
- // on this origin (`frame-ancestors` names every ancestor). Never another origin's.
1339
- const own = served.compiled.config.nestedFrames === "own";
1477
+ // on this origin (`frame-ancestors` names every ancestor). Never another origin's. Any
1478
+ // page already frames an embed session's (P143).
1479
+ const own = served.compiled.config.nestedFrames === "own" && !embed;
1340
1480
  return serveFile({
1341
1481
  request,
1342
1482
  set: served.files,
@@ -1347,7 +1487,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1347
1487
  pinned: at.pinned,
1348
1488
  source: at.source,
1349
1489
  compiled: served.compiled,
1350
- hostOrigins: options.hostOrigins,
1490
+ hostOrigins,
1351
1491
  frameAncestors: own ? `${access.origin} ${ancestors}` : ancestors,
1352
1492
  ...versionOf(access.instance),
1353
1493
  });
@@ -1366,15 +1506,15 @@ export function createServer(options: ServerOptions): PortholeServer {
1366
1506
  pinned: true,
1367
1507
  source: `${access.origin}${FILES_PREFIX}`,
1368
1508
  compiled: served.compiled,
1369
- hostOrigins: options.hostOrigins,
1370
- frameAncestors,
1509
+ hostOrigins,
1510
+ frameAncestors: ancestors,
1371
1511
  ticket: { expires: sealed.expires, ...(pageAt === undefined ? {} : { page: pageAt }) },
1372
1512
  ...versionOf(access.instance),
1373
1513
  });
1374
1514
  }
1375
1515
  // One page at a file set's base (P081): its base is the page, nothing under it is.
1376
1516
  if (at !== undefined && at.rest !== "") {
1377
- return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1517
+ return missing();
1378
1518
  }
1379
1519
  // A page that may use its artifact's assets loads them from its own origin (P089); every
1380
1520
  // served page carries its frame's sandbox, a tab of its own included (P099).
@@ -1503,7 +1643,12 @@ export function createServer(options: ServerOptions): PortholeServer {
1503
1643
  if (refusal !== null) {
1504
1644
  return refusal;
1505
1645
  }
1506
- return serveAsset({ request, asset, frameAncestors, code: runsAsCode(asset, access) });
1646
+ return serveAsset({
1647
+ request,
1648
+ asset,
1649
+ frameAncestors: ancestorsFor(access),
1650
+ code: runsAsCode(asset, access),
1651
+ });
1507
1652
  }
1508
1653
 
1509
1654
  /**
@@ -1560,19 +1705,27 @@ export function createServer(options: ServerOptions): PortholeServer {
1560
1705
  continue;
1561
1706
  }
1562
1707
  const session = keys.verify(value);
1708
+ // An embed session (P143) only where embeds are on, and only by its own name.
1709
+ const embed = isRecord(session) ? embedOf(session) : null;
1563
1710
  if (
1564
1711
  !isRecord(session) ||
1565
1712
  typeof session.w !== "string" ||
1566
1713
  typeof session.x !== "number" ||
1567
1714
  session.x <= Date.now() ||
1568
- (session.s !== undefined && typeof session.s !== "string")
1715
+ (session.s !== undefined && typeof session.s !== "string") ||
1716
+ embed === null ||
1717
+ (embed && !embeds)
1569
1718
  ) {
1570
1719
  continue;
1571
1720
  }
1572
1721
  let instance: InstanceRef;
1573
1722
  try {
1574
1723
  instance = cleanInstance(session.i);
1575
- if (instance.document.kind !== "artifact" || labelFor(instance) !== label) {
1724
+ if (
1725
+ instance.document.kind !== "artifact" ||
1726
+ labelFor(instance) !== label ||
1727
+ (embed && name !== sessionName(keys.instanceKey(instance), true))
1728
+ ) {
1576
1729
  continue;
1577
1730
  }
1578
1731
  } catch {
@@ -1585,9 +1738,13 @@ export function createServer(options: ServerOptions): PortholeServer {
1585
1738
  expiresAt: session.x,
1586
1739
  ...(session.a === 1 ? { anonymous: true } : {}),
1587
1740
  ...(typeof session.s === "string" ? { subject: session.s } : {}),
1741
+ ...(embed ? { embed: true as const } : {}),
1588
1742
  });
1589
1743
  }
1590
- return found.sort((a, b) => b.expiresAt - a.expiresAt);
1744
+ // Any other session before an embed session (P143), then the latest first.
1745
+ return found.sort(
1746
+ (a, b) => Number(a.embed === true) - Number(b.embed === true) || b.expiresAt - a.expiresAt,
1747
+ );
1591
1748
  }
1592
1749
 
1593
1750
  /**
@@ -1905,8 +2062,34 @@ export function createServer(options: ServerOptions): PortholeServer {
1905
2062
  function checkGrant(
1906
2063
  clean: InstanceRef,
1907
2064
  grant: Grant,
1908
- ): { readonly anonymous: boolean; readonly viewer: string } {
2065
+ ): { readonly anonymous: boolean; readonly viewer: string; readonly embed: boolean } {
1909
2066
  const anonymous = grant.anonymous === true;
2067
+ // An embedded document (P143): a public page with no host, which any page may frame. Only
2068
+ // where the host opted in, and only as narrow as that: anonymous, no level, no user, an
2069
+ // artifact's page that isn't nested.
2070
+ // Read as given: a host's grant is checked here, not trusted to its type.
2071
+ const asked: unknown = grant.embed;
2072
+ const embed = asked !== undefined;
2073
+ if (embed) {
2074
+ if (asked !== true) {
2075
+ throw new TypeError("A grant's embed is true or absent");
2076
+ }
2077
+ if (!embeds) {
2078
+ throw new TypeError(
2079
+ "An embed grant needs the server's opt-in (embeds: true): every page could frame it (P143)",
2080
+ );
2081
+ }
2082
+ if (!anonymous || grant.level !== undefined || grant.user !== undefined) {
2083
+ throw new TypeError(
2084
+ "An embed grant is anonymous, with no viewer, level or user: it has no host to give them to (P143)",
2085
+ );
2086
+ }
2087
+ if (clean.document.kind !== "artifact" || compiledFor(clean)?.config.nested === true) {
2088
+ throw new TypeError(
2089
+ "An embed grant opens an artifact's page that isn't nested: never a url-mode app, a served shell, the sandbox proxy or a nested display (P143)",
2090
+ );
2091
+ }
2092
+ }
1910
2093
  if (anonymous) {
1911
2094
  if (grant.viewer !== undefined) {
1912
2095
  throw new TypeError("An anonymous grant names no viewer");
@@ -1927,7 +2110,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1927
2110
  ) {
1928
2111
  throw new TypeError(`A grant's subject is a string of at most ${SUBJECT_MAX} characters`);
1929
2112
  }
1930
- return { anonymous, viewer: anonymous ? "" : (grant.viewer ?? "") };
2113
+ return { anonymous, viewer: anonymous ? "" : (grant.viewer ?? ""), embed };
1931
2114
  }
1932
2115
 
1933
2116
  /** How long a grant's session lasts, checked (`sessionSeconds`). */
@@ -1950,7 +2133,12 @@ export function createServer(options: ServerOptions): PortholeServer {
1950
2133
  }> {
1951
2134
  const clean = cleanInstance(instance);
1952
2135
  check(clean);
1953
- const { anonymous, viewer } = checkGrant(clean, grant);
2136
+ const { anonymous, viewer, embed } = checkGrant(clean, grant);
2137
+ if (embed && entry !== undefined) {
2138
+ throw new TypeError(
2139
+ "An embed grant opens a frame, never a clean address (redirect entry is for a tab, P143)",
2140
+ );
2141
+ }
1954
2142
  const ttl = seconds(grant.ttlSeconds, DEFAULT_TICKET_SECONDS, MAX_TICKET_SECONDS, "ttlSeconds");
1955
2143
  const sessionSeconds = sessionOf(grant);
1956
2144
  const key = keys.instanceKey(clean);
@@ -1964,8 +2152,9 @@ export function createServer(options: ServerOptions): PortholeServer {
1964
2152
  ...(entry?.base === undefined
1965
2153
  ? {}
1966
2154
  : { b: entry.base, ...(entry.pinned === true ? { k: 1 } : {}) }),
2155
+ ...(embed ? { m: 1 } : {}),
1967
2156
  });
1968
- if (cookieName(key).length + probe.length + 120 > MAX_COOKIE_BYTES) {
2157
+ if (sessionName(key, embed).length + probe.length + 120 > MAX_COOKIE_BYTES) {
1969
2158
  throw new TypeError("This instance is too large to carry in a cookie (fewer origins?)");
1970
2159
  }
1971
2160
  const ticket = newTicket();
@@ -1978,11 +2167,13 @@ export function createServer(options: ServerOptions): PortholeServer {
1978
2167
  ...(grant.subject === undefined ? {} : { subject: grant.subject }),
1979
2168
  ...(entry === undefined ? {} : { entry }),
1980
2169
  ...(below === undefined ? {} : { page: below }),
2170
+ ...(embed ? { embed: true as const } : {}),
1981
2171
  };
1982
2172
  await tickets.put(ticketId(ticket), record);
1983
2173
  // A frame on its scope's origin has a door (P125): its ticket, for the same grant and as long.
2174
+ // An embed grant's has none (P143): a door tells a host how loading went, and there is none.
1984
2175
  let door: string | null = null;
1985
- if (entry === undefined && hasDoor(clean)) {
2176
+ if (entry === undefined && !embed && hasDoor(clean)) {
1986
2177
  door = newTicket();
1987
2178
  await tickets.put(ticketId(door), { ...record, door: true });
1988
2179
  }
@@ -2070,7 +2261,8 @@ export function createServer(options: ServerOptions): PortholeServer {
2070
2261
  return {
2071
2262
  url: `${origin}${path}`,
2072
2263
  origin,
2073
- reports: true,
2264
+ // An embed session's pages tell no one how loading went (P143): they name no host.
2265
+ reports: grant.embed !== true,
2074
2266
  ...(viewer ? { viewer } : {}),
2075
2267
  // Its door (P125): the host frames it first, and takes its word alone.
2076
2268
  ...(door === null ? {} : { door: { url: `${origin}${DOOR_PATH}${key}?ticket=${door}` } }),
@@ -2092,7 +2284,12 @@ export function createServer(options: ServerOptions): PortholeServer {
2092
2284
  "A frame's page is a relative path below an artifact's files (no . or ..)",
2093
2285
  );
2094
2286
  }
2095
- const { anonymous, viewer } = checkGrant(clean, grant);
2287
+ const { anonymous, viewer, embed } = checkGrant(clean, grant);
2288
+ if (embed) {
2289
+ throw new TypeError(
2290
+ "An embed grant has no door (P143): a door tells a host how loading went, and there is none",
2291
+ );
2292
+ }
2096
2293
  const sessionSeconds = sessionOf(grant);
2097
2294
  const origin = originOfLabel(labelFor(clean));
2098
2295
  return answerDoor(