@botiverse/porthole 0.5.1 → 0.7.0

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 (167) hide show
  1. package/README.md +41 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +208 -13
  4. package/dist/bridge/navigation.d.ts +1 -6
  5. package/dist/bridge/navigation.js +11 -0
  6. package/dist/bridge/refusal.d.ts +5 -1
  7. package/dist/bridge/refusal.js +16 -0
  8. package/dist/bridge/types.d.ts +41 -4
  9. package/dist/check/check.d.ts +19 -3
  10. package/dist/check/check.js +55 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/instrument.d.ts +3 -0
  14. package/dist/check/lint.js +31 -12
  15. package/dist/check/page-source.js +1 -1
  16. package/dist/check/page.js +14 -0
  17. package/dist/check/tools.d.ts +23 -0
  18. package/dist/check/tools.js +27 -3
  19. package/dist/compile/policy.d.ts +34 -0
  20. package/dist/compile/policy.js +74 -0
  21. package/dist/config/capabilities.d.ts +62 -3
  22. package/dist/config/capabilities.js +20 -0
  23. package/dist/config/schema.d.ts +32 -0
  24. package/dist/config/validate.d.ts +1 -1
  25. package/dist/config/validate.js +74 -5
  26. package/dist/conformance/harness-source.js +1 -1
  27. package/dist/conformance/index.d.ts +1 -0
  28. package/dist/conformance/index.js +2 -0
  29. package/dist/conformance/runtime.d.ts +58 -0
  30. package/dist/conformance/runtime.js +314 -0
  31. package/dist/files/paths.d.ts +99 -0
  32. package/dist/files/paths.js +263 -0
  33. package/dist/files/types.d.ts +24 -0
  34. package/dist/files/types.js +83 -0
  35. package/dist/guide/gates.d.ts +3 -0
  36. package/dist/guide/gates.js +19 -0
  37. package/dist/guide/guide.d.ts +2 -0
  38. package/dist/guide/guide.js +44 -32
  39. package/dist/guide/limits.js +4 -4
  40. package/dist/guide/runtime.d.ts +13 -0
  41. package/dist/guide/runtime.js +202 -0
  42. package/dist/host/create-host.js +45 -0
  43. package/dist/host/locate.js +8 -0
  44. package/dist/host/locator.js +7 -0
  45. package/dist/host/types.d.ts +18 -0
  46. package/dist/index.d.ts +13 -4
  47. package/dist/index.js +16 -3
  48. package/dist/isolation/types.d.ts +8 -0
  49. package/dist/presets/presets.d.ts +6 -0
  50. package/dist/presets/presets.js +1 -0
  51. package/dist/protocol/adapter.d.ts +4 -0
  52. package/dist/protocol/mcp-apps.d.ts +6 -0
  53. package/dist/protocol/mcp-apps.js +6 -0
  54. package/dist/protocol/runtime-calls.d.ts +28 -0
  55. package/dist/protocol/runtime-calls.js +113 -0
  56. package/dist/protocol/shell-adapter.js +52 -3
  57. package/dist/react/dialog.js +31 -0
  58. package/dist/react/frame.d.ts +13 -0
  59. package/dist/react/frame.js +6 -0
  60. package/dist/runtime/contract.d.ts +193 -0
  61. package/dist/runtime/contract.js +216 -0
  62. package/dist/runtime/db.d.ts +153 -0
  63. package/dist/runtime/db.js +398 -0
  64. package/dist/runtime/declaration.d.ts +86 -0
  65. package/dist/runtime/declaration.js +266 -0
  66. package/dist/runtime/levels.d.ts +33 -0
  67. package/dist/runtime/levels.js +41 -0
  68. package/dist/runtime/requests.d.ts +125 -0
  69. package/dist/runtime/requests.js +199 -0
  70. package/dist/runtime/segments.d.ts +8 -0
  71. package/dist/runtime/segments.js +14 -0
  72. package/dist/runtime/types.generated.d.ts +1 -0
  73. package/dist/runtime/types.generated.js +19 -0
  74. package/dist/server/files.d.ts +57 -0
  75. package/dist/server/files.js +338 -0
  76. package/dist/server/host.d.ts +44 -2
  77. package/dist/server/host.js +42 -2
  78. package/dist/server/index.d.ts +5 -2
  79. package/dist/server/index.js +5 -1
  80. package/dist/server/keys.d.ts +8 -0
  81. package/dist/server/keys.js +34 -0
  82. package/dist/server/pseudonym.d.ts +9 -0
  83. package/dist/server/pseudonym.js +20 -0
  84. package/dist/server/server.d.ts +0 -5
  85. package/dist/server/server.js +468 -24
  86. package/dist/server/types.d.ts +118 -5
  87. package/dist/shell/document.d.ts +27 -0
  88. package/dist/shell/document.js +46 -2
  89. package/dist/shell/legacy.d.ts +21 -0
  90. package/dist/shell/legacy.js +63 -0
  91. package/dist/shell/plan.d.ts +17 -1
  92. package/dist/shell/plan.js +13 -2
  93. package/dist/shell/runtime.d.ts +2 -1
  94. package/dist/shell/runtime.js +114 -46
  95. package/dist/shell/use.d.ts +15 -0
  96. package/dist/shell/use.js +235 -0
  97. package/docs/ADOPTING.md +142 -5
  98. package/docs/ARCHITECTURE.md +34 -5
  99. package/docs/DECISIONS.md +716 -7
  100. package/docs/DESIGN.md +97 -3
  101. package/package.json +3 -1
  102. package/src/bridge/bridge.ts +281 -17
  103. package/src/bridge/navigation.ts +12 -0
  104. package/src/bridge/refusal.ts +16 -0
  105. package/src/bridge/types.ts +46 -4
  106. package/src/check/check.ts +100 -14
  107. package/src/check/files.ts +384 -0
  108. package/src/check/instrument.ts +3 -0
  109. package/src/check/lint.ts +33 -12
  110. package/src/check/page.ts +14 -0
  111. package/src/check/tools.ts +52 -3
  112. package/src/compile/policy.ts +92 -0
  113. package/src/config/capabilities.ts +49 -2
  114. package/src/config/schema.ts +32 -0
  115. package/src/config/validate.ts +107 -5
  116. package/src/conformance/index.ts +7 -0
  117. package/src/conformance/runtime.ts +573 -0
  118. package/src/files/paths.ts +323 -0
  119. package/src/files/types.ts +101 -0
  120. package/src/guide/gates.ts +25 -0
  121. package/src/guide/guide.ts +78 -52
  122. package/src/guide/limits.ts +4 -4
  123. package/src/guide/runtime.ts +244 -0
  124. package/src/host/create-host.ts +55 -0
  125. package/src/host/locate.ts +10 -0
  126. package/src/host/locator.ts +11 -0
  127. package/src/host/types.ts +18 -0
  128. package/src/index.ts +121 -0
  129. package/src/isolation/types.ts +8 -0
  130. package/src/presets/presets.ts +7 -0
  131. package/src/protocol/adapter.ts +3 -1
  132. package/src/protocol/mcp-apps.ts +7 -0
  133. package/src/protocol/runtime-calls.ts +138 -0
  134. package/src/protocol/shell-adapter.ts +56 -2
  135. package/src/react/dialog.tsx +33 -0
  136. package/src/react/frame.tsx +19 -0
  137. package/src/runtime/contract.ts +305 -0
  138. package/src/runtime/db.ts +530 -0
  139. package/src/runtime/declaration.ts +378 -0
  140. package/src/runtime/levels.ts +69 -0
  141. package/src/runtime/requests.ts +339 -0
  142. package/src/runtime/segments.ts +17 -0
  143. package/src/runtime/types.generated.ts +19 -0
  144. package/src/server/files.ts +425 -0
  145. package/src/server/host.ts +84 -3
  146. package/src/server/index.ts +22 -0
  147. package/src/server/keys.ts +53 -0
  148. package/src/server/pseudonym.ts +21 -0
  149. package/src/server/server.ts +565 -26
  150. package/src/server/types.ts +124 -4
  151. package/src/shell/document.ts +74 -4
  152. package/src/shell/legacy.ts +64 -0
  153. package/src/shell/plan.ts +37 -3
  154. package/src/shell/runtime.ts +114 -46
  155. package/src/shell/use.ts +235 -0
  156. package/types/runtime/v1/artifact.d.ts +50 -0
  157. package/types/runtime/v1/assets.d.ts +43 -0
  158. package/types/runtime/v1/chat.d.ts +13 -0
  159. package/types/runtime/v1/clipboard.d.ts +14 -0
  160. package/types/runtime/v1/comments.d.ts +24 -0
  161. package/types/runtime/v1/context.d.ts +16 -0
  162. package/types/runtime/v1/data.d.ts +29 -0
  163. package/types/runtime/v1/db.d.ts +110 -0
  164. package/types/runtime/v1/downloads.d.ts +22 -0
  165. package/types/runtime/v1/links.d.ts +13 -0
  166. package/types/runtime/v1/porthole.d.ts +44 -0
  167. package/types/runtime/v1/user.d.ts +19 -0
@@ -13,15 +13,25 @@ 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";
17
+ import {
18
+ assetCodeRuns,
19
+ assetCspDirectives,
20
+ INERT_FILE_CSP,
21
+ serializeCsp,
22
+ } from "../compile/policy.ts";
23
+ import { parseViewer, type ViewerInfo } from "../runtime/levels.ts";
16
24
  import type { FrameBlock } from "../host/types.ts";
17
25
  import { memoryTicketStore } from "./tickets.ts";
18
26
  import type {
19
27
  Access,
20
28
  AuthorizeAnswer,
21
- EntryState,
22
29
  Grant,
30
+ StoredAsset,
23
31
  PortholeServer,
24
32
  ServerOptions,
33
+ StoredFiles,
34
+ StoredVersion,
25
35
  TicketRecord,
26
36
  TicketStore,
27
37
  } from "./types.ts";
@@ -33,6 +43,25 @@ import type {
33
43
  const PREFIX = "/__porthole/";
34
44
  /** A served document (shell, artifact page, sandbox proxy), by its instance's key. */
35
45
  const DOCUMENT_PATH = /^\/__porthole\/d\/([a-z2-7]{16})$/u;
46
+ /**
47
+ * A file set's files in a frame (P083): `/__porthole/f/<sealed access>/<path>`. The access is
48
+ * in the path, so a frame whose engine keeps no cookie (WebKit, P025) loads them too.
49
+ */
50
+ const FILES_PATH = /^\/__porthole\/f\/([A-Za-z0-9_-]{40,4096})(\/.*)?$/u;
51
+ const FILES_PREFIX = "/__porthole/f/";
52
+ /** An asset's address (P089): `/_blob/` and 32 lowercase hex characters (`ASSET_ID`). */
53
+ const ASSET_ROUTE = /^\/_blob\/([0-9a-f]{32})$/u;
54
+ /** The same, under a frame's sealed files' address (P091): `<base>__porthole/blob/<id>`. */
55
+ const SEALED_ASSET = /^\/__porthole\/blob\/([0-9a-f]{32})$/u;
56
+ /** How long a sealed files' address opens a page's files on its own (P083); the shell renews it. */
57
+ const FILES_ADDRESS_MS = 3_600_000;
58
+ /** Below a sealed address: where the page's shell renews it (no file has a `__porthole/` path). */
59
+ const RENEW_PATH = "/__porthole/renew";
60
+ /**
61
+ * A clean address's base (P081): a path ending in `/`, each segment of letters, digits and
62
+ * `. _ : ~ -` (nothing a CSP source or a header would read otherwise), never `.` or `..`.
63
+ */
64
+ const BASE = /^\/(?:(?!\.{1,2}\/)[A-Za-z0-9._:~-]{1,200}\/){0,16}$/u;
36
65
  /** Where a url-mode app's ticket is taken, before the app's own landing path. */
37
66
  const ENTER_PATH = "/__porthole/enter";
38
67
  /** Where a redirect entry's code is redeemed, before its clean address (P068). */
@@ -83,11 +112,30 @@ interface Session {
83
112
  readonly s?: string;
84
113
  /** The clean path a document was entered at (P068): it is served there by this cookie. */
85
114
  readonly p?: string;
115
+ /** A file set's base (P081): every path under it is served by this cookie. */
116
+ readonly b?: string;
117
+ /** Whether the base is the version's own address (the app said so): its files are immutable. */
118
+ readonly k?: 1;
119
+ }
120
+
121
+ /** Where a request falls under a file set's base: the base, and the path below it. */
122
+ interface FilesAt {
123
+ readonly base: string;
124
+ readonly rest: string;
125
+ readonly search: string;
126
+ readonly pinned: boolean;
127
+ /** The CSP source the version's files load from (P082). */
128
+ readonly source: string;
86
129
  }
87
130
 
88
131
  const isRecord = (value: unknown): value is Record<string, unknown> =>
89
132
  value !== null && typeof value === "object" && !Array.isArray(value);
90
133
 
134
+ const isStoredFiles = (stored: StoredVersion): stored is StoredFiles =>
135
+ isRecord(stored) &&
136
+ isRecord((stored as Partial<StoredFiles>).files) &&
137
+ typeof (stored as Partial<StoredFiles>).read === "function";
138
+
91
139
  /** Which configs a kind of served document may be served under. */
92
140
  const MODES: Readonly<Record<Exclude<ServedDocument["kind"], "external">, readonly DisplayMode[]>> =
93
141
  {
@@ -201,6 +249,26 @@ function cookiesOf(request: Request): [string, string][] {
201
249
  * fetch-style handler a host's backend mounts in front of its own routes, plus `issue`, which the
202
250
  * host's authenticated API calls once it has decided a viewer may see an instance.
203
251
  */
252
+ /** A grant's viewer for the display's bridge (P087), checked; null without a level. */
253
+ function viewerOfGrant(grant: Grant): ViewerInfo | null {
254
+ if (grant.level === undefined) {
255
+ if (grant.user !== undefined) {
256
+ throw new TypeError("A grant's user comes with its level");
257
+ }
258
+ return null;
259
+ }
260
+ const viewer = parseViewer({
261
+ level: grant.level,
262
+ ...(grant.user === undefined ? {} : { id: grant.user.id, name: grant.user.name }),
263
+ });
264
+ if (viewer === null) {
265
+ throw new TypeError(
266
+ "A grant's level is view, interact, admin or owner; its user's id and name 1 to 256 characters",
267
+ );
268
+ }
269
+ return viewer;
270
+ }
271
+
204
272
  export function createServer(options: ServerOptions): PortholeServer {
205
273
  const { content } = options;
206
274
  const domain = content.domain;
@@ -438,7 +506,11 @@ export function createServer(options: ServerOptions): PortholeServer {
438
506
 
439
507
  async function documentOf(
440
508
  instance: InstanceRef,
441
- ): Promise<{ readonly html: string; readonly csp: string } | null> {
509
+ ): Promise<
510
+ | { readonly html: string; readonly csp: string; readonly compiled?: CompiledConfig }
511
+ | { readonly files: StoredFiles; readonly compiled: CompiledConfig }
512
+ | null
513
+ > {
442
514
  const { document } = instance;
443
515
  const config = compiledFor(instance);
444
516
  if (config === null) {
@@ -450,12 +522,20 @@ export function createServer(options: ServerOptions): PortholeServer {
450
522
  return { html: config.shellDocument({ origins, cspMeta: false }), csp: config.csp };
451
523
  case "artifact": {
452
524
  const stored = await options.artifacts?.get(document.id, document.version);
453
- if (stored === null || stored === undefined || typeof stored.html !== "string") {
525
+ if (stored === null || stored === undefined) {
526
+ return null;
527
+ }
528
+ // A version made of files (P081): served file by file under its base.
529
+ if (isStoredFiles(stored)) {
530
+ return { files: stored, compiled: config };
531
+ }
532
+ if (typeof stored.html !== "string") {
454
533
  return null;
455
534
  }
456
535
  return {
457
536
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
458
537
  csp: config.csp,
538
+ compiled: config,
459
539
  };
460
540
  }
461
541
  case "mcp-proxy":
@@ -476,7 +556,11 @@ export function createServer(options: ServerOptions): PortholeServer {
476
556
  * page that frames it; on a tab of its own, `Lax`. (Engines that keep no cookie in a cross-site
477
557
  * frame, measured: WebKit, still get the document, which comes with the ticket's answer.)
478
558
  */
479
- function sessionCookie(request: Request, record: TicketRecord, path?: string): string {
559
+ function sessionCookie(
560
+ request: Request,
561
+ record: TicketRecord,
562
+ at: { readonly p?: string; readonly b?: string; readonly k?: 1 } = {},
563
+ ): string {
480
564
  const sessionSeconds = record.sessionSeconds ?? DEFAULT_SESSION_SECONDS;
481
565
  const session: Session = {
482
566
  i: record.instance,
@@ -484,7 +568,9 @@ export function createServer(options: ServerOptions): PortholeServer {
484
568
  x: Date.now() + sessionSeconds * 1_000,
485
569
  ...(record.anonymous === true ? { a: 1 as const } : {}),
486
570
  ...(record.subject === undefined ? {} : { s: record.subject }),
487
- ...(path === undefined ? {} : { p: path }),
571
+ ...(at.p === undefined ? {} : { p: at.p }),
572
+ ...(at.b === undefined ? {} : { b: at.b }),
573
+ ...(at.k === undefined ? {} : { k: at.k }),
488
574
  };
489
575
  return [
490
576
  `${cookieName(keys.instanceKey(record.instance))}=${keys.sign(session)}`,
@@ -557,17 +643,35 @@ export function createServer(options: ServerOptions): PortholeServer {
557
643
  return best;
558
644
  }
559
645
 
560
- /** The access a request's cookies give to the document entered at `pathname` (P068). */
561
- function accessAtPath(request: Request, label: string, pathname: string): Access | null {
562
- let best: Access | null = null;
646
+ /**
647
+ * The access a request's cookies give to the document entered at `pathname` (P068), or to a
648
+ * file set's path under the base it was entered at (P081): with where the path falls under the
649
+ * base, or the base itself to go to (`/v/3` → `/v/3/`).
650
+ */
651
+ function accessAtPath(
652
+ request: Request,
653
+ label: string,
654
+ url: URL,
655
+ ): {
656
+ readonly access: Access;
657
+ readonly at?: FilesAt;
658
+ readonly redirect?: string;
659
+ } | null {
660
+ const { pathname } = url;
661
+ let best: { rank: number; access: Access; at?: FilesAt; redirect?: string } | null = null;
563
662
  for (const [name, value] of cookiesOf(request)) {
564
663
  if (!ourCookie(name)) {
565
664
  continue;
566
665
  }
567
666
  const session = keys.verify(value);
667
+ if (!isRecord(session)) {
668
+ continue;
669
+ }
670
+ const base = typeof session.b === "string" && BASE.test(session.b) ? session.b : null;
671
+ const under = base !== null && pathname.startsWith(base);
672
+ const atBase = base !== null && `${pathname}/` === base;
568
673
  if (
569
- !isRecord(session) ||
570
- session.p !== pathname ||
674
+ (session.p !== pathname && !under && !atBase) ||
571
675
  typeof session.w !== "string" ||
572
676
  typeof session.x !== "number" ||
573
677
  session.x <= Date.now() ||
@@ -584,14 +688,39 @@ export function createServer(options: ServerOptions): PortholeServer {
584
688
  } catch {
585
689
  continue;
586
690
  }
587
- if (best === null || session.x > best.expiresAt) {
691
+ // The most specific first: the path entered itself, then the longest base, then the
692
+ // latest to end.
693
+ const rank = session.p === pathname ? Number.MAX_SAFE_INTEGER : (base?.length ?? 0);
694
+ if (
695
+ best === null ||
696
+ rank > best.rank ||
697
+ (rank === best.rank && session.x > best.access.expiresAt)
698
+ ) {
699
+ const origin = originOfLabel(label);
588
700
  best = {
589
- instance,
590
- viewer: session.w,
591
- origin: originOfLabel(label),
592
- expiresAt: session.x,
593
- ...(session.a === 1 ? { anonymous: true } : {}),
594
- ...(typeof session.s === "string" ? { subject: session.s } : {}),
701
+ rank,
702
+ access: {
703
+ instance,
704
+ viewer: session.w,
705
+ origin,
706
+ expiresAt: session.x,
707
+ ...(session.a === 1 ? { anonymous: true } : {}),
708
+ ...(typeof session.s === "string" ? { subject: session.s } : {}),
709
+ },
710
+ ...(base !== null && under
711
+ ? {
712
+ at: {
713
+ base,
714
+ rest: pathname.slice(base.length),
715
+ search: url.search,
716
+ pinned: session.k === 1,
717
+ source: new URL(base, origin).href,
718
+ },
719
+ }
720
+ : {}),
721
+ ...(base !== null && atBase && session.p !== pathname
722
+ ? { redirect: `${origin}${base}${url.search}` }
723
+ : {}),
595
724
  };
596
725
  }
597
726
  }
@@ -626,6 +755,145 @@ export function createServer(options: ServerOptions): PortholeServer {
626
755
  });
627
756
  }
628
757
 
758
+ /**
759
+ * The access a sealed files' address carries (P083), if it holds for this origin now: on its own
760
+ * for its hour (`x`), then only for the running page's own loads until the session ends (`e`).
761
+ */
762
+ async function sealedAccess(
763
+ request: Request,
764
+ label: string,
765
+ token: string,
766
+ ): Promise<Access | null> {
767
+ const session = await keys.unseal(token);
768
+ const now = Date.now();
769
+ if (
770
+ !isRecord(session) ||
771
+ typeof session.w !== "string" ||
772
+ typeof session.x !== "number" ||
773
+ typeof session.e !== "number" ||
774
+ (session.s !== undefined && typeof session.s !== "string")
775
+ ) {
776
+ return null;
777
+ }
778
+ const open = session.x > now || (session.e > now && ownLoad(request));
779
+ let instance: InstanceRef;
780
+ try {
781
+ instance = cleanInstance(session.i);
782
+ } catch {
783
+ return null;
784
+ }
785
+ if (!open || instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
786
+ return null;
787
+ }
788
+ return {
789
+ instance,
790
+ viewer: session.w,
791
+ origin: originOfLabel(label),
792
+ expiresAt: session.e,
793
+ ...(session.a === 1 ? { anonymous: true } : {}),
794
+ ...(typeof session.s === "string" ? { subject: session.s } : {}),
795
+ };
796
+ }
797
+
798
+ /**
799
+ * A file set's file in a frame (P083): the sealed access in its path opens it, once it holds
800
+ * for this origin and the host's check lets it in; every path under it is the same version's.
801
+ */
802
+ /** A files' address for an access (P083): sealed, its own end within the session's. */
803
+ async function sealFiles(
804
+ access: Access,
805
+ ): Promise<{ readonly base: string; readonly expires: number }> {
806
+ const expires = Math.min(access.expiresAt, Date.now() + FILES_ADDRESS_MS);
807
+ const token = await keys.seal({
808
+ i: access.instance,
809
+ w: access.viewer,
810
+ x: expires,
811
+ e: access.expiresAt,
812
+ ...(access.anonymous === true ? { a: 1 } : {}),
813
+ ...(access.subject === undefined ? {} : { s: access.subject }),
814
+ });
815
+ return { base: `${FILES_PREFIX}${token}/`, expires };
816
+ }
817
+
818
+ /**
819
+ * A file set's file in a frame (P083): the sealed access in its path opens it, once it holds
820
+ * for this origin and the host's check lets it in; every path under it is the same version's.
821
+ * The address opens on its own for an hour (its `x`); after that, until the session's end (its
822
+ * `e`), only the running page's own loads (same-origin, not a navigation), from addresses it
823
+ * already holds, while its shell renews the address (`__porthole/renew`).
824
+ */
825
+ async function serveSealed(
826
+ request: Request,
827
+ url: URL,
828
+ label: string,
829
+ token: string,
830
+ rest: string | undefined,
831
+ ): Promise<Response> {
832
+ const method = request.method.toUpperCase();
833
+ const origin = originOfLabel(label);
834
+ const base = `${FILES_PREFIX}${token}/`;
835
+ if (rest === undefined) {
836
+ return new Response(null, {
837
+ status: 307,
838
+ headers: { location: `${origin}${base}${url.search}`, "cache-control": "no-store" },
839
+ });
840
+ }
841
+ const access = await sealedAccess(request, label, token);
842
+ if (access === null) {
843
+ return page(
844
+ 401,
845
+ "This has ended",
846
+ "Content here opens for a while. Open it again from the app that showed it.",
847
+ method,
848
+ "session",
849
+ );
850
+ }
851
+ // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
852
+ // sends a frame's path, where some send no Referer that names it.
853
+ const blob = SEALED_ASSET.exec(rest)?.[1];
854
+ if (blob !== undefined) {
855
+ if (options.assets === undefined) {
856
+ return page(404, "Not found", "This address names no content.", method);
857
+ }
858
+ return (
859
+ (await assetFor(request, label, access, blob)) ??
860
+ page(404, "Not found", "This address names no content.", method)
861
+ );
862
+ }
863
+ if (rest === RENEW_PATH) {
864
+ // Only the page itself renews its address, while its session lasts and the host lets it.
865
+ if (method !== "GET" || !ownLoad(request)) {
866
+ return page(403, "Not allowed", "Only the page renews its own address.", method);
867
+ }
868
+ const refusal = await denied(request, access);
869
+ if (refusal !== null) {
870
+ return refusal;
871
+ }
872
+ const renewed = await sealFiles(access);
873
+ return Response.json(
874
+ { base: `${origin}${renewed.base}`, expires: renewed.expires },
875
+ {
876
+ headers: {
877
+ "cache-control": "no-store",
878
+ "x-content-type-options": "nosniff",
879
+ "cross-origin-resource-policy": "same-origin",
880
+ "content-security-policy": `${INERT_FILE_CSP}; frame-ancestors ${frameAncestors}`,
881
+ "referrer-policy": "no-referrer",
882
+ },
883
+ },
884
+ );
885
+ }
886
+ return serveAccess(request, access, null, {
887
+ base,
888
+ rest: rest.slice(1),
889
+ search: url.search,
890
+ pinned: true,
891
+ // Every frame's files on this origin share the prefix (the scope's, P082): a page knows
892
+ // only its own access.
893
+ source: `${origin}${FILES_PREFIX}`,
894
+ });
895
+ }
896
+
629
897
  async function serveDocument(
630
898
  request: Request,
631
899
  url: URL,
@@ -669,11 +937,15 @@ export function createServer(options: ServerOptions): PortholeServer {
669
937
  return serveAccess(request, access, cookie);
670
938
  }
671
939
 
672
- /** The document an access opens, once the host's check lets it in. */
940
+ /**
941
+ * The document an access opens, once the host's check lets it in: at its document's path, or
942
+ * (`at`) a path under a file set's base (P081).
943
+ */
673
944
  async function serveAccess(
674
945
  request: Request,
675
946
  access: Access,
676
947
  cookie: string | null,
948
+ at?: FilesAt,
677
949
  ): Promise<Response> {
678
950
  const method = request.method.toUpperCase();
679
951
  const refusal = await denied(request, access);
@@ -684,13 +956,200 @@ export function createServer(options: ServerOptions): PortholeServer {
684
956
  if (served === null) {
685
957
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
686
958
  }
687
- const headers = documentHeaders(served.csp);
959
+ if ("files" in served) {
960
+ if (at !== undefined) {
961
+ return serveFile({
962
+ request,
963
+ set: served.files,
964
+ rest: at.rest,
965
+ search: at.search,
966
+ base: at.base,
967
+ origin: access.origin,
968
+ pinned: at.pinned,
969
+ source: at.source,
970
+ compiled: served.compiled,
971
+ hostOrigins: options.hostOrigins,
972
+ frameAncestors,
973
+ });
974
+ }
975
+ // A frame's document (a ticket's): its files carry its access in their path (P083). The
976
+ // entry comes in the ticket's own answer (P025), its shell moving the frame to its address
977
+ // there before anything loads, and renewing it before it ends.
978
+ const sealed = await sealFiles(access);
979
+ return serveFile({
980
+ request,
981
+ set: served.files,
982
+ rest: "",
983
+ search: "",
984
+ base: sealed.base,
985
+ origin: access.origin,
986
+ pinned: true,
987
+ source: `${access.origin}${FILES_PREFIX}`,
988
+ compiled: served.compiled,
989
+ hostOrigins: options.hostOrigins,
990
+ frameAncestors,
991
+ ticket: { expires: sealed.expires },
992
+ });
993
+ }
994
+ // One page at a file set's base (P081): its base is the page, nothing under it is.
995
+ if (at !== undefined && at.rest !== "") {
996
+ return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
997
+ }
998
+ // A page that may use its artifact's assets loads them from its own origin (P089).
999
+ const headers = documentHeaders(
1000
+ served.compiled === undefined
1001
+ ? served.csp
1002
+ : serializeCsp(
1003
+ assetCspDirectives(
1004
+ served.compiled.config,
1005
+ served.compiled.cspDirectives,
1006
+ access.origin,
1007
+ ),
1008
+ ),
1009
+ );
688
1010
  if (cookie !== null) {
689
1011
  headers.set("set-cookie", cookie);
690
1012
  }
691
1013
  return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
692
1014
  }
693
1015
 
1016
+ /**
1017
+ * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
1018
+ * artifact of this origin (its page's sealed files' address, as its `Referer` says, P091; or a
1019
+ * session cookie), then the host's check for that access, then the host's store asked with it;
1020
+ * served only when the asset is that artifact's, on its scope's origin. Never an entry. By id
1021
+ * alone only where the host opted into it (`assets.bearer`).
1022
+ */
1023
+ async function serveAssetAt(request: Request, label: string, id: string): Promise<Response> {
1024
+ const method = request.method.toUpperCase();
1025
+ const store = options.assets;
1026
+ const none = () => page(404, "Not found", "This address names no content.", method);
1027
+ if (store === undefined) {
1028
+ return none();
1029
+ }
1030
+ const scoped = (asset: StoredAsset | null): asset is StoredAsset => {
1031
+ try {
1032
+ return asset !== null && nameOf(asset.scope) === label;
1033
+ } catch {
1034
+ return false;
1035
+ }
1036
+ };
1037
+ if (store.bearer === true) {
1038
+ const asset = await store.get(id, null);
1039
+ return scoped(asset)
1040
+ ? serveAsset({ request, asset, frameAncestors, code: asset.trusted === true })
1041
+ : none();
1042
+ }
1043
+ const accesses = await assetAccessesOf(request, label);
1044
+ if (accesses.length === 0) {
1045
+ return new Response(null, { status: 401, headers: { "cache-control": "no-store" } });
1046
+ }
1047
+ for (const access of accesses) {
1048
+ const answer = await assetFor(request, label, access, id);
1049
+ if (answer !== null) {
1050
+ return answer;
1051
+ }
1052
+ }
1053
+ return none();
1054
+ }
1055
+
1056
+ /**
1057
+ * An asset for one access (P089, P091): the store asked with it, served only when the asset is
1058
+ * its artifact's on its scope's origin, after the host's check; its code only where it was
1059
+ * trusted and the artifact's config still lets uploaded code run. Null: not this access's.
1060
+ */
1061
+ async function assetFor(
1062
+ request: Request,
1063
+ label: string,
1064
+ access: Access,
1065
+ id: string,
1066
+ ): Promise<Response | null> {
1067
+ const store = options.assets;
1068
+ if (store === undefined || access.instance.document.kind !== "artifact") {
1069
+ return null;
1070
+ }
1071
+ const asset = await store.get(id, access);
1072
+ let named: string | null = null;
1073
+ try {
1074
+ named = asset === null ? null : nameOf(asset.scope);
1075
+ } catch {
1076
+ named = null;
1077
+ }
1078
+ if (asset === null || named !== label || asset.artifact !== access.instance.document.id) {
1079
+ return null;
1080
+ }
1081
+ const refusal = await denied(request, access);
1082
+ if (refusal !== null) {
1083
+ return refusal;
1084
+ }
1085
+ const config = compiledFor(access.instance)?.config;
1086
+ const code = asset.trusted === true && config !== undefined && assetCodeRuns(config);
1087
+ return serveAsset({ request, asset, frameAncestors, code });
1088
+ }
1089
+
1090
+ /**
1091
+ * The accesses a request carries to artifacts of `label`'s origin, most specific first: the
1092
+ * sealed files' address its page is at (a frame's, which keeps no cookie, P083), as its
1093
+ * same-origin `Referer` names it; then its session cookies.
1094
+ */
1095
+ async function assetAccessesOf(request: Request, label: string): Promise<Access[]> {
1096
+ const found: Access[] = [];
1097
+ const referer = request.headers.get("referer");
1098
+ if (referer !== null) {
1099
+ try {
1100
+ const from = new URL(referer);
1101
+ const token = FILES_PATH.exec(from.pathname)?.[1];
1102
+ if (from.origin === originOfLabel(label) && token !== undefined) {
1103
+ const sealed = await sealedAccess(request, label, token);
1104
+ if (sealed !== null) {
1105
+ found.push(sealed);
1106
+ }
1107
+ }
1108
+ } catch {
1109
+ // Not an address: no access from it.
1110
+ }
1111
+ }
1112
+ return [...found, ...artifactAccessesOf(request, label)];
1113
+ }
1114
+
1115
+ /** The accesses a request's cookies give to artifacts of `label`'s origin, latest first. */
1116
+ function artifactAccessesOf(request: Request, label: string): Access[] {
1117
+ const found: Access[] = [];
1118
+ for (const [name, value] of cookiesOf(request)) {
1119
+ if (!ourCookie(name)) {
1120
+ continue;
1121
+ }
1122
+ const session = keys.verify(value);
1123
+ if (
1124
+ !isRecord(session) ||
1125
+ typeof session.w !== "string" ||
1126
+ typeof session.x !== "number" ||
1127
+ session.x <= Date.now() ||
1128
+ (session.s !== undefined && typeof session.s !== "string")
1129
+ ) {
1130
+ continue;
1131
+ }
1132
+ let instance: InstanceRef;
1133
+ try {
1134
+ instance = cleanInstance(session.i);
1135
+ if (instance.document.kind !== "artifact" || nameOf(instance.scope) !== label) {
1136
+ continue;
1137
+ }
1138
+ } catch {
1139
+ continue;
1140
+ }
1141
+ found.push({
1142
+ instance,
1143
+ viewer: session.w,
1144
+ origin: originOfLabel(label),
1145
+ expiresAt: session.x,
1146
+ ...(session.a === 1 ? { anonymous: true } : {}),
1147
+ ...(typeof session.s === "string" ? { subject: session.s } : {}),
1148
+ });
1149
+ }
1150
+ return found.sort((a, b) => b.expiresAt - a.expiresAt);
1151
+ }
1152
+
694
1153
  /**
695
1154
  * A clean address without a cookie for it (P068): off to the host's authorize route with a
696
1155
  * signed state, the browser holding the state's nonce in a cookie of this origin. A path just
@@ -707,6 +1166,22 @@ export function createServer(options: ServerOptions): PortholeServer {
707
1166
  ) {
708
1167
  return page(404, "Nothing here", "This address names no content.", method);
709
1168
  }
1169
+ // Only a page opening is sent to sign in (a browser's navigation; a client that sends no fetch
1170
+ // metadata may be one): a browser's subresource without a session is refused here, with no
1171
+ // state of its own (no nonce cookie, nothing cached).
1172
+ const mode = request.headers.get("sec-fetch-mode");
1173
+ const dest = request.headers.get("sec-fetch-dest") ?? "";
1174
+ if (mode !== null && mode !== "navigate" && !["document", "iframe", "frame"].includes(dest)) {
1175
+ return new Response(method === "HEAD" ? null : "Open this address in a browser.", {
1176
+ status: 401,
1177
+ headers: {
1178
+ "content-type": "text/plain; charset=utf-8",
1179
+ "cache-control": "no-store",
1180
+ "x-content-type-options": "nosniff",
1181
+ "x-robots-tag": "noindex, nofollow",
1182
+ },
1183
+ });
1184
+ }
710
1185
  if (method !== "GET" && method !== "HEAD") {
711
1186
  return page(
712
1187
  401,
@@ -780,7 +1255,7 @@ export function createServer(options: ServerOptions): PortholeServer {
780
1255
  "session",
781
1256
  );
782
1257
  }
783
- const { nonce, path } = record.entry;
1258
+ const { nonce, path, base, pinned } = record.entry;
784
1259
  const named = nonceCookie(nonce);
785
1260
  if (!cookiesOf(request).some(([name, value]) => name === named && value === "1")) {
786
1261
  return page(
@@ -812,9 +1287,19 @@ export function createServer(options: ServerOptions): PortholeServer {
812
1287
  "referrer-policy": "no-referrer",
813
1288
  "x-robots-tag": "noindex, nofollow",
814
1289
  });
1290
+ // A file set's address (P081): the session serves every path under its base, the version's
1291
+ // own address. Else the path it was entered at, alone (P068).
815
1292
  headers.append(
816
1293
  "set-cookie",
817
- sessionCookie(request, record, external ? undefined : target.pathname),
1294
+ sessionCookie(
1295
+ request,
1296
+ record,
1297
+ external
1298
+ ? {}
1299
+ : base !== undefined
1300
+ ? { b: base, ...(pinned === true ? { k: 1 as const } : {}) }
1301
+ : { p: target.pathname },
1302
+ ),
818
1303
  );
819
1304
  headers.append(
820
1305
  "set-cookie",
@@ -982,6 +1467,9 @@ export function createServer(options: ServerOptions): PortholeServer {
982
1467
  ...(anonymous ? { a: 1 } : {}),
983
1468
  ...(grant.subject === undefined ? {} : { s: grant.subject }),
984
1469
  ...(entry === undefined ? {} : { p: entry.path }),
1470
+ ...(entry?.base === undefined
1471
+ ? {}
1472
+ : { b: entry.base, ...(entry.pinned === true ? { k: 1 } : {}) }),
985
1473
  });
986
1474
  if (cookieName(key).length + probe.length + 120 > MAX_COOKIE_BYTES) {
987
1475
  throw new TypeError("This instance is too large to carry in a cookie (fewer origins?)");
@@ -1058,7 +1546,9 @@ export function createServer(options: ServerOptions): PortholeServer {
1058
1546
  clean.document.kind === "external"
1059
1547
  ? `${ENTER_PATH}?ticket=${ticket}`
1060
1548
  : `${PREFIX}d/${key}?ticket=${ticket}`;
1061
- return { url: `${origin}${path}`, origin, reports: true };
1549
+ // The viewer's level, as the host's access decided it now (P087): for the display's bridge.
1550
+ const viewer = viewerOfGrant(grant);
1551
+ return { url: `${origin}${path}`, origin, reports: true, ...(viewer ? { viewer } : {}) };
1062
1552
  },
1063
1553
 
1064
1554
  forget(filter = {}) {
@@ -1104,7 +1594,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1104
1594
  };
1105
1595
  },
1106
1596
 
1107
- async enterBy(state: EntryState, instance: InstanceRef, grant: Grant): Promise<string> {
1597
+ async enterBy(state, instance, grant, address): Promise<string> {
1108
1598
  if (state.expired) {
1109
1599
  throw new TypeError("This entry's state has expired: start again from the clean address");
1110
1600
  }
@@ -1112,12 +1602,45 @@ export function createServer(options: ServerOptions): PortholeServer {
1112
1602
  if (nameOf(clean.scope) !== state.label) {
1113
1603
  throw new TypeError("The instance isn't served on the address the entry began at");
1114
1604
  }
1605
+ let path = state.path;
1606
+ if (address !== undefined) {
1607
+ // A file set's own address (P081): a path ending in /, not Porthole's own. An address
1608
+ // that isn't under it (the latest's) goes to the same file under it, which must stay
1609
+ // under it: no dot segment, no backslash, nothing the URL parser would resolve away.
1610
+ const { base, file = "" } = address;
1611
+ const segments = typeof file === "string" ? file.split("/") : [];
1612
+ if (
1613
+ typeof base !== "string" ||
1614
+ !BASE.test(base) ||
1615
+ base.startsWith(PREFIX) ||
1616
+ typeof file !== "string" ||
1617
+ file.length > MAX_PATH ||
1618
+ file.startsWith("/") ||
1619
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
1620
+ /[?#\\\u0000-\u001f\u007f]/u.test(file) ||
1621
+ segments.some((each) => /^(?:\.|%2e){1,2}$/iu.test(each))
1622
+ ) {
1623
+ throw new TypeError(
1624
+ "An entry's base is a path ending in / (not Porthole's own), its file a relative path below it",
1625
+ );
1626
+ }
1627
+ const asked = new URL(state.path, "https://x.invalid");
1628
+ if (!asked.pathname.startsWith(base)) {
1629
+ path = `${base}${file}${asked.search}`;
1630
+ }
1631
+ if (!new URL(path, "https://x.invalid").pathname.startsWith(base)) {
1632
+ throw new TypeError("An entry's file must stay below its base");
1633
+ }
1634
+ }
1115
1635
  const { ticket } = await mint(
1116
1636
  clean,
1117
1637
  { ...grant, ttlSeconds: ENTRY_CODE_SECONDS },
1118
1638
  {
1119
- path: state.path,
1639
+ path,
1120
1640
  nonce: state.nonce,
1641
+ ...(address === undefined
1642
+ ? {}
1643
+ : { base: address.base, ...(address.pinned === true ? { pinned: true } : {}) }),
1121
1644
  },
1122
1645
  );
1123
1646
  return `${originOfLabel(state.label)}${ENTRY_PATH}?code=${ticket}`;
@@ -1168,18 +1691,34 @@ export function createServer(options: ServerOptions): PortholeServer {
1168
1691
  access === null ? 401 : (await denied(request, access)) === null ? 204 : 403;
1169
1692
  return new Response(null, { status, headers: { "cache-control": "no-store" } });
1170
1693
  }
1694
+ // An artifact's asset library (P089), outside every version: `/_blob/<id>` only; any
1695
+ // other path there is a clean address as before (after the review).
1696
+ const asset = options.assets === undefined ? null : ASSET_ROUTE.exec(url.pathname);
1697
+ if (asset?.[1] !== undefined) {
1698
+ return await serveAssetAt(request, label, asset[1]);
1699
+ }
1171
1700
  const document = DOCUMENT_PATH.exec(url.pathname);
1172
1701
  if (document?.[1] !== undefined) {
1173
1702
  return await serveDocument(request, url, label, document[1]);
1174
1703
  }
1704
+ const sealed = FILES_PATH.exec(url.pathname);
1705
+ if (sealed?.[1] !== undefined) {
1706
+ return await serveSealed(request, url, label, sealed[1], sealed[2]);
1707
+ }
1175
1708
  if (url.pathname.startsWith(PREFIX)) {
1176
1709
  return page(404, "Nothing here", "This address names no content.", method);
1177
1710
  }
1178
1711
  // A clean address (P068): the document entered here, else the app, else entry.
1179
1712
  if (authorizeUrl !== null) {
1180
- const entered = accessAtPath(request, label, url.pathname);
1713
+ const entered = accessAtPath(request, label, url);
1714
+ if (entered?.redirect !== undefined) {
1715
+ return new Response(null, {
1716
+ status: 307,
1717
+ headers: { location: entered.redirect, "cache-control": "no-store" },
1718
+ });
1719
+ }
1181
1720
  if (entered !== null) {
1182
- return await serveAccess(request, entered, null);
1721
+ return await serveAccess(request, entered.access, null, entered.at);
1183
1722
  }
1184
1723
  if (options.upstream === undefined || accessOf(request, label, null) === null) {
1185
1724
  return await beginEntry(request, url, label, authorizeUrl);