@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
@@ -102,4 +102,5 @@ export { defineLeakSuite, leakTests, PROBES, type ConformanceFixtures, type Conf
102
102
  export { httpOracle, settle, udpOracle, type HttpOracle, type UdpOracle } from "./oracles.ts";
103
103
  export { defineServedSuite, servedTests, type ServedConformanceHost, type ServedDisplay, type ServedSuiteOptions, } from "./served.ts";
104
104
  export { entryTests, type EntryConformanceHost, type EntrySuiteOptions } from "./entry.ts";
105
+ export { defineRuntimeConformance, type RuntimeCase, type RuntimeConformanceOptions, } from "./runtime.ts";
105
106
  export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, type ConformanceProject, type ConformanceProjectsOptions, type HostConformance, type HostConformanceOptions, } from "./host-kit.ts";
@@ -4,5 +4,7 @@ export { httpOracle, settle, udpOracle } from "./oracles.js";
4
4
  export { defineServedSuite, servedTests, } from "./served.js";
5
5
  // Redirect entry's cases (P068).
6
6
  export { entryTests } from "./entry.js";
7
+ // The capability runtime's cases an app runs against its own handlers (P085-P090): no browser.
8
+ export { defineRuntimeConformance, } from "./runtime.js";
7
9
  // The runner an app points at its real page and issue endpoint (P066).
8
10
  export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, } from "./host-kit.js";
@@ -0,0 +1,58 @@
1
+ import type { CapabilityHandlers } from "../bridge/types.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ import type { InstanceRef } from "../isolation/types.ts";
4
+ import type { ViewerInfo } from "../runtime/levels.ts";
5
+ import type { AssetStore } from "../server/types.ts";
6
+ /**
7
+ * The capability runtime's host conformance (P085–P090): cases an app runs against its own
8
+ * handlers (the ones it gives `createHost`), through Porthole's real bridge, as a page would call
9
+ * them, and straight to the handler, as a page that got past the bridge would (the app's API is
10
+ * its data's wall). No browser and no test runner: each case is a function that throws on a
11
+ * failure; register them with yours (P041), `for (const each of cases) test(each.name, each.run)`.
12
+ *
13
+ * What a host's services must do: `db` versions every write and refuses a stale one (`conflict`),
14
+ * applies a batch whole or not at all, follows a document, keeps each person's `data/users/<id>`
15
+ * theirs and the page's rules; `artifact` answers its current version and refuses a publish from
16
+ * a base that moved, or by someone below admin; `assets` stores an upload where `/server` serves
17
+ * it, lists it, and removes it; `comments` answers only whether the composer opened.
18
+ */
19
+ export interface RuntimeConformanceOptions {
20
+ /** The config the handlers serve under, its runtime capabilities declared. */
21
+ readonly config: PortholeConfig;
22
+ /**
23
+ * Fresh handlers for one artifact, made for each case (a new artifact, a clean store): the
24
+ * functions the app passes `createHost`.
25
+ */
26
+ readonly handlers: () => CapabilityHandlers | Promise<CapabilityHandlers>;
27
+ /** People at each level; `other` is a second person at interact (whose data isn't `interact`'s). */
28
+ readonly viewers: {
29
+ readonly view: ViewerInfo;
30
+ readonly interact: ViewerInfo;
31
+ readonly admin: ViewerInfo;
32
+ readonly other: ViewerInfo;
33
+ };
34
+ /** The instance the handlers act on, as the app's mount names it. */
35
+ readonly instance?: InstanceRef;
36
+ /** The asset store `/server` serves from (`ServerOptions.assets`), to see an upload served. */
37
+ readonly assets?: (handlers: CapabilityHandlers) => AssetStore;
38
+ /**
39
+ * The app's own API for the same artifact, signed in as `viewer` with that person's real session
40
+ * (after the review): the raw mode. The cases that go past the bridge then call it with a
41
+ * forged context (a viewer claiming to be the owner, no rules), as a page that got past the
42
+ * bridge could, so an API that trusts `context.viewer` or `context.declared` fails them. Without
43
+ * it they call `handlers` with an honest context, which can't catch that: never trust
44
+ * `context.viewer` or `context.declared` for what your data allows.
45
+ */
46
+ readonly api?: (handlers: CapabilityHandlers, viewer: ViewerInfo) => CapabilityHandlers | Promise<CapabilityHandlers>;
47
+ /** The page's db rules the cases declare (default: `config` writable by admins only). */
48
+ readonly rules?: Readonly<Record<string, {
49
+ read?: ViewerInfo["level"];
50
+ write?: ViewerInfo["level"];
51
+ }>>;
52
+ }
53
+ export interface RuntimeCase {
54
+ readonly name: string;
55
+ run(): Promise<void>;
56
+ }
57
+ /** The runtime's conformance cases for an app's handlers. */
58
+ export declare function defineRuntimeConformance(options: RuntimeConformanceOptions): readonly RuntimeCase[];
@@ -0,0 +1,314 @@
1
+ import { createBridge } from "../bridge/bridge.js";
2
+ import { isRefused } from "../bridge/refusal.js";
3
+ import { RUNTIME_VERSION } from "../runtime/contract.js";
4
+ import { checkDeclaration } from "../runtime/declaration.js";
5
+ import { ASSET_ID, assetUrl } from "../runtime/requests.js";
6
+ class ConformanceFailure extends Error {
7
+ name = "ConformanceFailure";
8
+ }
9
+ function expect(condition, message) {
10
+ if (!condition) {
11
+ throw new ConformanceFailure(message);
12
+ }
13
+ }
14
+ const codeOf = (outcome) => outcome.ok ? null : (outcome.reason?.code ?? null);
15
+ const ok = (outcome, what) => {
16
+ if (!outcome.ok) {
17
+ throw new ConformanceFailure(`${what}: refused (${outcome.refusal}, ${outcome.reason?.code ?? "no code"}): ${outcome.message ?? ""}`);
18
+ }
19
+ return outcome.value;
20
+ };
21
+ /** The runtime's conformance cases for an app's handlers. */
22
+ export function defineRuntimeConformance(options) {
23
+ const { config, viewers } = options;
24
+ const rules = options.rules ?? { config: { write: "admin" } };
25
+ const declared = {
26
+ ...(config.capabilities.db === undefined ? {} : { db: { rules } }),
27
+ ...(config.capabilities.artifact === undefined ? {} : { artifact: {} }),
28
+ ...(config.capabilities.assets === undefined ? {} : { assets: {} }),
29
+ };
30
+ const declaration = checkDeclaration({ capabilities: declared, runtime: RUNTIME_VERSION }, config);
31
+ const display = {
32
+ id: "conformance",
33
+ title: "Runtime conformance",
34
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
35
+ };
36
+ /** A page's calls as `viewer`, through the bridge. */
37
+ const as = (handlers, viewer) => {
38
+ const bridge = createBridge({
39
+ config,
40
+ display,
41
+ handlers,
42
+ declaration,
43
+ viewer,
44
+ // Gates the person answers are the app's UI: a yes here, so the services are what's tested.
45
+ confirm: () => Promise.resolve(true),
46
+ consent: () => true,
47
+ userActivation: () => true,
48
+ onEvent: () => { },
49
+ });
50
+ return (capability, args, subscription) => bridge.call(capability, args, subscription);
51
+ };
52
+ /** A call straight to the handler, as a page past the bridge would make it (the app's wall). */
53
+ const direct = async (handlers, capability, args, viewer) => {
54
+ const raw = options.api === undefined ? null : await options.api(handlers, viewer);
55
+ const handler = (raw ?? handlers)[capability];
56
+ if (handler === undefined) {
57
+ throw new ConformanceFailure(`no ${capability} handler`);
58
+ }
59
+ try {
60
+ const value = await handler(args, {
61
+ displayId: display.id,
62
+ title: display.title,
63
+ capability,
64
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
65
+ // The raw mode forges what a page past the bridge would claim; else the honest context.
66
+ ...(raw === null
67
+ ? { viewer, ...(capability === "db" ? { declared: { rules } } : {}) }
68
+ : {
69
+ viewer: { level: "owner", ...(viewer.id === undefined ? {} : { id: viewer.id }) },
70
+ declared: {},
71
+ }),
72
+ });
73
+ return { ok: true, value };
74
+ }
75
+ catch (error) {
76
+ return { ok: false, code: isRefused(error) ? error.code : null };
77
+ }
78
+ };
79
+ /** An access for the instance, as `/server` asks the store with it. */
80
+ const access = {
81
+ instance: options.instance ?? {
82
+ scope: "conformance",
83
+ document: { kind: "artifact", id: "page", version: "1" },
84
+ },
85
+ viewer: "conformance",
86
+ origin: "https://conformance.invalid",
87
+ expiresAt: Date.now() + 3_600_000,
88
+ };
89
+ const cases = [];
90
+ const add = (name, run) => {
91
+ cases.push({ name, run: async () => run(await options.handlers()) });
92
+ };
93
+ if (config.capabilities.db !== undefined) {
94
+ add("db: a set is read back, versioned from 1", async (handlers) => {
95
+ const call = as(handlers, viewers.interact);
96
+ const set = ok(await call("db", { op: "set", path: "notes/a", data: { text: "hi" } }), "set");
97
+ expect(set.version === 1, "a first write is version 1");
98
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get");
99
+ expect(got.exists && got.version === 1 && got.data?.text === "hi", "get reads it back");
100
+ const missing = ok(await call("db", { op: "get", path: "notes/none" }), "get");
101
+ expect(!missing.exists && missing.version === 0, "a missing document: exists false, version 0");
102
+ });
103
+ add("db: a write that names a stale version, or none for a document that exists, is a conflict", async (handlers) => {
104
+ const call = as(handlers, viewers.interact);
105
+ ok(await call("db", { op: "set", path: "notes/a", data: { n: 1 } }), "set");
106
+ expect(codeOf(await call("db", { op: "set", path: "notes/a", data: { n: 2 } })) === "conflict", "set without ifVersion over an existing document: conflict");
107
+ expect(codeOf(await call("db", { op: "update", path: "notes/a", data: { n: 2 }, ifVersion: 7 })) === "conflict", "update with a stale ifVersion: conflict");
108
+ const updated = ok(await call("db", { op: "update", path: "notes/a", data: { m: 3 }, ifVersion: 1 }), "update");
109
+ expect(updated.version === 2, "an update with the right version is the next one");
110
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get");
111
+ expect(got.data?.n === 1 && got.data?.m === 3, "update merges fields");
112
+ expect(codeOf(await call("db", { op: "set", path: "notes/b", data: {}, ifVersion: 0 })) === null, "ifVersion 0 creates");
113
+ ok(await call("db", { op: "delete", path: "notes/a", ifVersion: 2 }), "delete");
114
+ const gone = ok(await call("db", { op: "get", path: "notes/a" }), "get");
115
+ expect(!gone.exists, "a deleted document is gone");
116
+ });
117
+ add("db: a query answers a collection's documents, filtered, ordered, limited", async (handlers) => {
118
+ const call = as(handlers, viewers.interact);
119
+ for (const [id, score] of [
120
+ ["a", 3],
121
+ ["b", 1],
122
+ ["c", 2],
123
+ ]) {
124
+ ok(await call("db", { op: "set", path: `scores/${id}`, data: { score } }), "set");
125
+ }
126
+ ok(await call("db", { op: "set", path: "scores/a/history/1", data: { score: 9 } }), "set");
127
+ const found = ok(await call("db", {
128
+ op: "query",
129
+ collection: "scores",
130
+ where: [["score", ">=", 2]],
131
+ orderBy: { field: "score", direction: "desc" },
132
+ limit: 5,
133
+ }), "query");
134
+ expect(JSON.stringify(found.docs.map((each) => each.id)) === '["a","c"]', `a query answers its collection's own documents, filtered and ordered: ${JSON.stringify(found.docs.map((each) => each.id))}`);
135
+ });
136
+ add("db: a batch is applied whole or not at all", async (handlers) => {
137
+ const call = as(handlers, viewers.interact);
138
+ ok(await call("db", { op: "set", path: "items/x", data: { n: 1 } }), "set");
139
+ const refused = await call("db", {
140
+ op: "batch",
141
+ writes: [
142
+ { op: "set", path: "items/y", data: { n: 1 } },
143
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 9 },
144
+ ],
145
+ });
146
+ expect(codeOf(refused) === "conflict", "a batch with a stale write: conflict");
147
+ const y = ok(await call("db", { op: "get", path: "items/y" }), "get");
148
+ expect(!y.exists, "nothing of a refused batch is written");
149
+ const done = ok(await call("db", {
150
+ op: "batch",
151
+ writes: [
152
+ { op: "set", path: "items/y", data: { n: 1 } },
153
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 1 },
154
+ ],
155
+ }), "batch");
156
+ expect(JSON.stringify(done.versions) === "[1,2]", "a batch answers each write's version");
157
+ });
158
+ add("db: a watch hears the document now and at each change", async (handlers) => {
159
+ const heard = [];
160
+ const controller = new AbortController();
161
+ const watching = as(handlers, viewers.view);
162
+ ok(await watching("db", { op: "watch", path: "notes/w" }, {
163
+ subscription: {
164
+ changed: (state) => heard.push(state),
165
+ signal: controller.signal,
166
+ },
167
+ }), "watch");
168
+ ok(await as(handlers, viewers.interact)("db", { op: "set", path: "notes/w", data: { n: 1 } }), "set");
169
+ await new Promise((resolve) => setTimeout(resolve, 50));
170
+ controller.abort();
171
+ ok(await as(handlers, viewers.interact)("db", {
172
+ op: "set",
173
+ path: "notes/w",
174
+ data: { n: 2 },
175
+ ifVersion: 1,
176
+ }), "set");
177
+ await new Promise((resolve) => setTimeout(resolve, 50));
178
+ expect(heard.length >= 1 && heard.some((each) => each.exists && each.data?.n === 1), "a watch hears a write");
179
+ expect(!heard.some((each) => each.data?.n === 2), "a watch ends with its signal");
180
+ });
181
+ add("db: a person's own data is theirs: data/users/me is them, another's is refused, even past the bridge", async (handlers) => {
182
+ const mine = as(handlers, viewers.interact);
183
+ ok(await mine("db", { op: "set", path: "data/users/me/prefs", data: { dark: true } }), "set own");
184
+ const own = ok(await mine("db", { op: "get", path: `data/users/${viewers.interact.id}/prefs` }), "get own");
185
+ expect(own.exists, "me is the viewer's own id");
186
+ const theirs = as(handlers, viewers.other);
187
+ const path = `data/users/${viewers.interact.id}/prefs`;
188
+ expect(codeOf(await theirs("db", { op: "get", path })) === "forbidden", "another person's data: forbidden");
189
+ const past = await direct(handlers, "db", { op: "get", path }, viewers.other);
190
+ expect(!past.ok, "the app's handler refuses another person's data itself");
191
+ const listed = await direct(handlers, "db", { op: "query", collection: `data/users/${viewers.interact.id}` }, viewers.other);
192
+ expect(!listed.ok, "and their collections");
193
+ });
194
+ add("db: a person's own paths come back as data/users/me, never their id", async (handlers) => {
195
+ const mine = as(handlers, viewers.interact);
196
+ ok(await mine("db", { op: "set", path: "data/users/me/prefs", data: { n: 1 } }), "set own");
197
+ const got = ok(await mine("db", { op: "get", path: "data/users/me/prefs" }), "get");
198
+ const listed = ok(await mine("db", { op: "query", collection: "data/users/me" }), "query");
199
+ const said = JSON.stringify([got, listed]);
200
+ expect(got.path === "data/users/me/prefs", `a snapshot says me: ${got.path}`);
201
+ expect(viewers.interact.id === undefined || !said.includes(viewers.interact.id), "no answer names the viewer's id");
202
+ });
203
+ add("db: the page's rules hold, at the bridge and in the app", async (handlers) => {
204
+ expect(codeOf(await as(handlers, viewers.interact)("db", { op: "set", path: "config/main", data: {} })) === "forbidden", "a rule's write level holds at the bridge");
205
+ const past = await direct(handlers, "db", { op: "set", path: "config/main", data: {} }, viewers.interact);
206
+ expect(!past.ok, "the app's handler applies the page's rules itself");
207
+ const view = await direct(handlers, "db", { op: "set", path: "notes/v", data: {} }, viewers.view);
208
+ expect(!view.ok, "a view-only person writes nothing, even past the bridge");
209
+ ok(await as(handlers, viewers.admin)("db", { op: "set", path: "config/main", data: {} }), "an admin writes it");
210
+ });
211
+ }
212
+ if (config.capabilities.artifact !== undefined) {
213
+ add("artifact: get answers the current version; a publish from it makes the next", async (handlers) => {
214
+ const call = as(handlers, viewers.admin);
215
+ const current = ok(await call("artifact", { op: "get" }), "get");
216
+ expect(typeof current.version === "string" && Array.isArray(current.files), "get: { version, files }");
217
+ const published = ok(await call("artifact", {
218
+ op: "publish",
219
+ base: current.version,
220
+ files: { "notes.txt": { text: "new" } },
221
+ label: "From the page",
222
+ }), "publish");
223
+ expect(published.version !== current.version, "a publish makes a new version");
224
+ const after = ok(await call("artifact", { op: "get" }), "get");
225
+ expect(after.version === published.version, "the new version is current");
226
+ expect(after.files.some((each) => each.path === "notes.txt"), "with the patch applied");
227
+ expect(current.files.every((file) => after.files.some((each) => each.path === file.path)), "and the base's other files kept");
228
+ });
229
+ add("artifact: a publish from a base that moved is a conflict; below admin, refused even past the bridge", async (handlers) => {
230
+ const call = as(handlers, viewers.admin);
231
+ const current = ok(await call("artifact", { op: "get" }), "get");
232
+ ok(await call("artifact", {
233
+ op: "publish",
234
+ base: current.version,
235
+ files: { "a.txt": { text: "1" } },
236
+ }), "publish");
237
+ expect(codeOf(await call("artifact", {
238
+ op: "publish",
239
+ base: current.version,
240
+ files: { "a.txt": { text: "2" } },
241
+ })) === "conflict", "a stale base: conflict");
242
+ expect(codeOf(await as(handlers, viewers.interact)("artifact", {
243
+ op: "publish",
244
+ base: "x",
245
+ files: { "a.txt": { text: "3" } },
246
+ })) === "forbidden", "below admin: forbidden at the bridge");
247
+ const now = ok(await call("artifact", { op: "get" }), "get");
248
+ const past = await direct(handlers, "artifact", { op: "publish", base: now.version, files: { "a.txt": { text: "4" } } }, viewers.interact);
249
+ expect(!past.ok, "the app's handler refuses a publish below admin itself");
250
+ });
251
+ }
252
+ if (config.capabilities.artifact !== undefined) {
253
+ add("artifact: a publish whose merged files make no page is refused", async (handlers) => {
254
+ const call = as(handlers, viewers.admin);
255
+ const current = ok(await call("artifact", { op: "get" }), "get");
256
+ const refused = await call("artifact", {
257
+ op: "publish",
258
+ base: current.version,
259
+ files: { [current.entry]: null },
260
+ });
261
+ expect(!refused.ok, "a publish that removes the entry is refused (check the merged set)");
262
+ });
263
+ }
264
+ if (config.capabilities.assets !== undefined) {
265
+ add("assets: an upload is listed, served by its id, and removed", async (handlers) => {
266
+ const call = as(handlers, viewers.admin);
267
+ const bytes = "R0lGODlhAQABAAAAACw="; // a small GIF's start: its bytes, as base64
268
+ const asset = ok(await call("assets", { op: "upload", name: "pixel.gif", base64: bytes }), "upload");
269
+ expect(ASSET_ID.test(asset.id), "an asset's id is 32 lowercase hex characters");
270
+ expect(asset.url === assetUrl(asset.id), "its url is /_blob/<id>");
271
+ expect(asset.type === "image/gif" && asset.size === 14, "its type is the name's; its size the bytes'");
272
+ const listed = ok(await as(handlers, viewers.view)("assets", { op: "list" }), "list");
273
+ expect(listed.some((each) => each.id === asset.id), "the library lists it");
274
+ const store = options.assets?.(handlers);
275
+ if (store !== undefined) {
276
+ const stored = await store.get(asset.id, access);
277
+ expect(stored !== null && stored.size === 14, "the server's store has it");
278
+ const body = await stored?.read();
279
+ const length = body instanceof Uint8Array
280
+ ? body.length
281
+ : body === null || body === undefined
282
+ ? -1
283
+ : (await new Response(body).arrayBuffer()).byteLength;
284
+ expect(length === 14, "with its bytes");
285
+ }
286
+ ok(await call("assets", { op: "delete", id: asset.id }), "delete");
287
+ const after = ok(await call("assets", { op: "list" }), "list");
288
+ expect(!after.some((each) => each.id === asset.id), "a removed asset isn't listed");
289
+ if (store !== undefined) {
290
+ expect((await store.get(asset.id, access)) === null, "nor served");
291
+ }
292
+ });
293
+ add("assets: removing is the admins', even past the bridge", async (handlers) => {
294
+ const asset = ok(await as(handlers, viewers.admin)("assets", {
295
+ op: "upload",
296
+ name: "a.txt",
297
+ base64: "aGk=",
298
+ }), "upload");
299
+ expect(codeOf(await as(handlers, viewers.interact)("assets", { op: "delete", id: asset.id })) ===
300
+ "forbidden", "below admin: forbidden at the bridge");
301
+ const past = await direct(handlers, "assets", { op: "delete", id: asset.id }, viewers.view);
302
+ expect(!past.ok || past.value !== true, "the app's handler refuses a removal below admin itself");
303
+ });
304
+ }
305
+ if (config.capabilities.comments !== undefined) {
306
+ add("comments: content hears only whether the composer opened", async (handlers) => {
307
+ const opened = ok(await as(handlers, viewers.view)("comments", {
308
+ anchor: { name: "slide-3", label: "Slide 3" },
309
+ }), "open");
310
+ expect(typeof opened === "boolean", "comments.open answers a boolean");
311
+ });
312
+ }
313
+ return cases;
314
+ }
@@ -0,0 +1,99 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * A version made of files (P081): the rules a published path follows, the limits a version is
4
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
5
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
6
+ * only, never on a filesystem.
7
+ */
8
+ /** The most files a version holds, by default. */
9
+ export declare const DEFAULT_MAX_FILES = 1000;
10
+ /** The largest file of a version, bytes, by default (25 MiB). */
11
+ export declare const DEFAULT_MAX_FILE_BYTES: number;
12
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
13
+ export declare const DEFAULT_MAX_VERSION_BYTES: number;
14
+ /** The longest path, characters, and the longest segment of one. */
15
+ export declare const MAX_FILE_PATH_CHARS = 512;
16
+ export declare const MAX_SEGMENT_CHARS = 255;
17
+ /** The page a version opens at by default. */
18
+ export declare const DEFAULT_ENTRY = "index.html";
19
+ /**
20
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
21
+ * origin of its own. Opaque frames have no origin to serve them from.
22
+ */
23
+ export declare const servesFiles: (config: PortholeConfig) => boolean;
24
+ export interface FileLimits {
25
+ readonly maxFiles: number;
26
+ readonly maxFileBytes: number;
27
+ readonly maxVersionBytes: number;
28
+ }
29
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
30
+ export declare function fileLimits(limits?: Partial<Limits> | null): FileLimits;
31
+ /**
32
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
33
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
34
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
35
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
36
+ */
37
+ export declare function filePathProblem(path: unknown): string | null;
38
+ /** A published path's metadata, as far as the checks read it. */
39
+ export interface FileSetEntryLike {
40
+ readonly size: number;
41
+ }
42
+ export interface FileSetProblem {
43
+ /** The path it is about, where it is about one. */
44
+ readonly path?: string;
45
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
46
+ /** What to change, for the agent or the person publishing. */
47
+ readonly message: string;
48
+ }
49
+ /**
50
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
51
+ * two paths that differ only in case, and no path that is both a file and a directory; the
52
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
53
+ * `fileLimits`). Empty when it may be published.
54
+ */
55
+ export declare function checkFileSet(files: Readonly<Record<string, FileSetEntryLike>>, options?: {
56
+ readonly entry?: string;
57
+ readonly limits?: FileLimits;
58
+ }): FileSetProblem[];
59
+ /**
60
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
61
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
62
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
63
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
64
+ * `/` stays (a directory).
65
+ */
66
+ export declare function requestFilePath(raw: string): string | null;
67
+ /** What a request's path finds in a version's manifest. */
68
+ export type FileLookup =
69
+ /** The file to answer with, and its status (404 for a `404.html`). */
70
+ {
71
+ readonly kind: "file";
72
+ readonly path: string;
73
+ readonly status: 200 | 404;
74
+ }
75
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
76
+ | {
77
+ readonly kind: "redirect";
78
+ readonly to: string;
79
+ }
80
+ /** Nothing: a plain 404. */
81
+ | {
82
+ readonly kind: "none";
83
+ };
84
+ export interface LookupOptions {
85
+ /** The page the version opens at (default `index.html`). */
86
+ readonly entry?: string;
87
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
88
+ readonly spa?: boolean;
89
+ /** Whether the request is a navigation (a page loading), not a subresource. */
90
+ readonly navigation: boolean;
91
+ }
92
+ /**
93
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
94
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
95
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
96
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
97
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
98
+ */
99
+ export declare function lookupFile(has: (path: string) => boolean, path: string, options: LookupOptions): FileLookup;