@botiverse/porthole 0.6.0 → 0.8.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 (208) hide show
  1. package/README.md +25 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -0,0 +1,594 @@
1
+ import { createBridge } from "../bridge/bridge.ts";
2
+ import type { CallOutcome, CapabilityHandlers } from "../bridge/types.ts";
3
+ import { isRefused } from "../bridge/refusal.ts";
4
+ import type { CapabilityName } from "../config/capabilities.ts";
5
+ import type { PortholeConfig } from "../config/schema.ts";
6
+ import type { InstanceRef } from "../isolation/types.ts";
7
+ import { RUNTIME_VERSION } from "../runtime/contract.ts";
8
+ import { checkDeclaration, type CapabilityDeclaration } from "../runtime/declaration.ts";
9
+ import type { DbSnapshot } from "../runtime/db.ts";
10
+ import type { ViewerInfo } from "../runtime/levels.ts";
11
+ import { ASSET_ID, assetUrl, type AssetInfo } from "../runtime/requests.ts";
12
+ import type { Access, AssetStore } from "../server/types.ts";
13
+
14
+ /**
15
+ * The capability runtime's host conformance (P085–P090): cases an app runs against its own
16
+ * handlers (the ones it gives `createHost`), through Porthole's real bridge, as a page would call
17
+ * them, and straight to the handler, as a page that got past the bridge would (the app's API is
18
+ * its data's wall). No browser and no test runner: each case is a function that throws on a
19
+ * failure; register them with yours (P041), `for (const each of cases) test(each.name, each.run)`.
20
+ *
21
+ * What a host's services must do: `db` versions every write and refuses a stale one (`conflict`),
22
+ * applies a batch whole or not at all, follows a document, keeps each person's `data/users/<id>`
23
+ * theirs and the page's rules; `artifact` answers its current version and refuses a publish from
24
+ * a base that moved, or by someone below admin; `assets` stores an upload where `/server` serves
25
+ * it, lists it, and removes it; `comments` answers only whether the composer opened.
26
+ */
27
+
28
+ export interface RuntimeConformanceOptions {
29
+ /** The config the handlers serve under, its runtime capabilities declared. */
30
+ readonly config: PortholeConfig;
31
+ /**
32
+ * Fresh handlers for one artifact, made for each case (a new artifact, a clean store): the
33
+ * functions the app passes `createHost`.
34
+ */
35
+ readonly handlers: () => CapabilityHandlers | Promise<CapabilityHandlers>;
36
+ /** People at each level; `other` is a second person at interact (whose data isn't `interact`'s). */
37
+ readonly viewers: {
38
+ readonly view: ViewerInfo;
39
+ readonly interact: ViewerInfo;
40
+ readonly admin: ViewerInfo;
41
+ readonly other: ViewerInfo;
42
+ };
43
+ /** The instance the handlers act on, as the app's mount names it. */
44
+ readonly instance?: InstanceRef;
45
+ /** The asset store `/server` serves from (`ServerOptions.assets`), to see an upload served. */
46
+ readonly assets?: (handlers: CapabilityHandlers) => AssetStore;
47
+ /**
48
+ * The app's own API for the same artifact, signed in as `viewer` with that person's real session
49
+ * (after the review): the raw mode. The cases that go past the bridge then call it with a
50
+ * forged context (a viewer claiming to be the owner, no rules), as a page that got past the
51
+ * bridge could, so an API that trusts `context.viewer` or `context.declared` fails them. Without
52
+ * it they call `handlers` with an honest context, which can't catch that: never trust
53
+ * `context.viewer` or `context.declared` for what your data allows.
54
+ */
55
+ readonly api?: (
56
+ handlers: CapabilityHandlers,
57
+ viewer: ViewerInfo,
58
+ ) => CapabilityHandlers | Promise<CapabilityHandlers>;
59
+ /** The page's db rules the cases declare (default: `config` writable by admins only). */
60
+ readonly rules?: Readonly<
61
+ Record<string, { read?: ViewerInfo["level"]; write?: ViewerInfo["level"] }>
62
+ >;
63
+ }
64
+
65
+ export interface RuntimeCase {
66
+ readonly name: string;
67
+ run(): Promise<void>;
68
+ }
69
+
70
+ class ConformanceFailure extends Error {
71
+ override name = "ConformanceFailure";
72
+ }
73
+
74
+ function expect(condition: boolean, message: string): asserts condition {
75
+ if (!condition) {
76
+ throw new ConformanceFailure(message);
77
+ }
78
+ }
79
+
80
+ const codeOf = (outcome: CallOutcome<unknown>): string | null =>
81
+ outcome.ok ? null : (outcome.reason?.code ?? null);
82
+
83
+ const ok = <T>(outcome: CallOutcome<T>, what: string): T => {
84
+ if (!outcome.ok) {
85
+ throw new ConformanceFailure(
86
+ `${what}: refused (${outcome.refusal}, ${outcome.reason?.code ?? "no code"}): ${outcome.message ?? ""}`,
87
+ );
88
+ }
89
+ return outcome.value;
90
+ };
91
+
92
+ /** The runtime's conformance cases for an app's handlers. */
93
+ export function defineRuntimeConformance(
94
+ options: RuntimeConformanceOptions,
95
+ ): readonly RuntimeCase[] {
96
+ const { config, viewers } = options;
97
+ const rules = options.rules ?? { config: { write: "admin" } };
98
+ const declared: CapabilityDeclaration = {
99
+ ...(config.capabilities.db === undefined ? {} : { db: { rules } }),
100
+ ...(config.capabilities.artifact === undefined ? {} : { artifact: {} }),
101
+ ...(config.capabilities.assets === undefined ? {} : { assets: {} }),
102
+ };
103
+ const declaration = checkDeclaration(
104
+ { capabilities: declared, runtime: RUNTIME_VERSION },
105
+ config,
106
+ );
107
+ const display = {
108
+ id: "conformance",
109
+ title: "Runtime conformance",
110
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
111
+ };
112
+
113
+ /** A page's calls as `viewer`, through the bridge. */
114
+ const as = (handlers: CapabilityHandlers, viewer: ViewerInfo) => {
115
+ const bridge = createBridge({
116
+ config,
117
+ display,
118
+ handlers,
119
+ declaration,
120
+ viewer,
121
+ // Gates the person answers are the app's UI: a yes here, so the services are what's tested.
122
+ confirm: () => Promise.resolve(true),
123
+ consent: () => true,
124
+ show: () => {},
125
+ userActivation: () => true,
126
+ onEvent: () => {},
127
+ });
128
+ return (
129
+ capability: CapabilityName,
130
+ args: unknown,
131
+ subscription?: Parameters<typeof bridge.call>[2],
132
+ ) => bridge.call(capability, args, subscription);
133
+ };
134
+
135
+ /** A call straight to the handler, as a page past the bridge would make it (the app's wall). */
136
+ const direct = async (
137
+ handlers: CapabilityHandlers,
138
+ capability: "db" | "artifact" | "assets",
139
+ args: unknown,
140
+ viewer: ViewerInfo,
141
+ ): Promise<{ ok: true; value: unknown } | { ok: false; code: string | null }> => {
142
+ const raw = options.api === undefined ? null : await options.api(handlers, viewer);
143
+ const handler = (raw ?? handlers)[capability] as
144
+ | ((args: unknown, context: unknown) => unknown)
145
+ | undefined;
146
+ if (handler === undefined) {
147
+ throw new ConformanceFailure(`no ${capability} handler`);
148
+ }
149
+ try {
150
+ const value = await handler(args, {
151
+ displayId: display.id,
152
+ title: display.title,
153
+ capability,
154
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
155
+ // The raw mode forges what a page past the bridge would claim; else the honest context.
156
+ ...(raw === null
157
+ ? { viewer, ...(capability === "db" ? { declared: { rules } } : {}) }
158
+ : {
159
+ viewer: { level: "owner", ...(viewer.id === undefined ? {} : { id: viewer.id }) },
160
+ declared: {},
161
+ }),
162
+ });
163
+ return { ok: true, value };
164
+ } catch (error) {
165
+ return { ok: false, code: isRefused(error) ? error.code : null };
166
+ }
167
+ };
168
+
169
+ /** An access for the instance, as `/server` asks the store with it. */
170
+ const access: Access = {
171
+ instance: options.instance ?? {
172
+ scope: "conformance",
173
+ document: { kind: "artifact", id: "page", version: "1" },
174
+ },
175
+ viewer: "conformance",
176
+ origin: "https://conformance.invalid",
177
+ expiresAt: Date.now() + 3_600_000,
178
+ };
179
+
180
+ const cases: RuntimeCase[] = [];
181
+ const add = (name: string, run: (handlers: CapabilityHandlers) => Promise<void>) => {
182
+ cases.push({ name, run: async () => run(await options.handlers()) });
183
+ };
184
+
185
+ if (config.capabilities.db !== undefined) {
186
+ add("db: a set is read back, versioned from 1", async (handlers) => {
187
+ const call = as(handlers, viewers.interact);
188
+ const set = ok(await call("db", { op: "set", path: "notes/a", data: { text: "hi" } }), "set");
189
+ expect((set as { version: number }).version === 1, "a first write is version 1");
190
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get") as DbSnapshot;
191
+ expect(got.exists && got.version === 1 && got.data?.text === "hi", "get reads it back");
192
+ const missing = ok(await call("db", { op: "get", path: "notes/none" }), "get") as DbSnapshot;
193
+ expect(
194
+ !missing.exists && missing.version === 0,
195
+ "a missing document: exists false, version 0",
196
+ );
197
+ });
198
+ add(
199
+ "db: a write that names a stale version, or none for a document that exists, is a conflict",
200
+ async (handlers) => {
201
+ const call = as(handlers, viewers.interact);
202
+ ok(await call("db", { op: "set", path: "notes/a", data: { n: 1 } }), "set");
203
+ expect(
204
+ codeOf(await call("db", { op: "set", path: "notes/a", data: { n: 2 } })) === "conflict",
205
+ "set without ifVersion over an existing document: conflict",
206
+ );
207
+ expect(
208
+ codeOf(
209
+ await call("db", { op: "update", path: "notes/a", data: { n: 2 }, ifVersion: 7 }),
210
+ ) === "conflict",
211
+ "update with a stale ifVersion: conflict",
212
+ );
213
+ const updated = ok(
214
+ await call("db", { op: "update", path: "notes/a", data: { m: 3 }, ifVersion: 1 }),
215
+ "update",
216
+ ) as { version: number };
217
+ expect(updated.version === 2, "an update with the right version is the next one");
218
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get") as DbSnapshot;
219
+ expect(got.data?.n === 1 && got.data?.m === 3, "update merges fields");
220
+ expect(
221
+ codeOf(await call("db", { op: "set", path: "notes/b", data: {}, ifVersion: 0 })) === null,
222
+ "ifVersion 0 creates",
223
+ );
224
+ ok(await call("db", { op: "delete", path: "notes/a", ifVersion: 2 }), "delete");
225
+ const gone = ok(await call("db", { op: "get", path: "notes/a" }), "get") as DbSnapshot;
226
+ expect(!gone.exists, "a deleted document is gone");
227
+ },
228
+ );
229
+ add(
230
+ "db: a query answers a collection's documents, filtered, ordered, limited",
231
+ async (handlers) => {
232
+ const call = as(handlers, viewers.interact);
233
+ for (const [id, score] of [
234
+ ["a", 3],
235
+ ["b", 1],
236
+ ["c", 2],
237
+ ] as const) {
238
+ ok(await call("db", { op: "set", path: `scores/${id}`, data: { score } }), "set");
239
+ }
240
+ ok(await call("db", { op: "set", path: "scores/a/history/1", data: { score: 9 } }), "set");
241
+ const found = ok(
242
+ await call("db", {
243
+ op: "query",
244
+ collection: "scores",
245
+ where: [["score", ">=", 2]],
246
+ orderBy: { field: "score", direction: "desc" },
247
+ limit: 5,
248
+ }),
249
+ "query",
250
+ ) as { docs: DbSnapshot[] };
251
+ expect(
252
+ JSON.stringify(found.docs.map((each) => each.id)) === '["a","c"]',
253
+ `a query answers its collection's own documents, filtered and ordered: ${JSON.stringify(found.docs.map((each) => each.id))}`,
254
+ );
255
+ },
256
+ );
257
+ add("db: a batch is applied whole or not at all", async (handlers) => {
258
+ const call = as(handlers, viewers.interact);
259
+ ok(await call("db", { op: "set", path: "items/x", data: { n: 1 } }), "set");
260
+ const refused = await call("db", {
261
+ op: "batch",
262
+ writes: [
263
+ { op: "set", path: "items/y", data: { n: 1 } },
264
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 9 },
265
+ ],
266
+ });
267
+ expect(codeOf(refused) === "conflict", "a batch with a stale write: conflict");
268
+ const y = ok(await call("db", { op: "get", path: "items/y" }), "get") as DbSnapshot;
269
+ expect(!y.exists, "nothing of a refused batch is written");
270
+ const done = ok(
271
+ await call("db", {
272
+ op: "batch",
273
+ writes: [
274
+ { op: "set", path: "items/y", data: { n: 1 } },
275
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 1 },
276
+ ],
277
+ }),
278
+ "batch",
279
+ ) as { versions: (number | null)[] };
280
+ expect(JSON.stringify(done.versions) === "[1,2]", "a batch answers each write's version");
281
+ });
282
+ add("db: a watch hears the document now and at each change", async (handlers) => {
283
+ const heard: DbSnapshot[] = [];
284
+ const controller = new AbortController();
285
+ const watching = as(handlers, viewers.view);
286
+ ok(
287
+ await watching(
288
+ "db",
289
+ { op: "watch", path: "notes/w" },
290
+ {
291
+ subscription: {
292
+ changed: (state) => heard.push(state as DbSnapshot),
293
+ signal: controller.signal,
294
+ },
295
+ },
296
+ ),
297
+ "watch",
298
+ );
299
+ ok(
300
+ await as(handlers, viewers.interact)("db", { op: "set", path: "notes/w", data: { n: 1 } }),
301
+ "set",
302
+ );
303
+ await new Promise((resolve) => setTimeout(resolve, 50));
304
+ controller.abort();
305
+ ok(
306
+ await as(handlers, viewers.interact)("db", {
307
+ op: "set",
308
+ path: "notes/w",
309
+ data: { n: 2 },
310
+ ifVersion: 1,
311
+ }),
312
+ "set",
313
+ );
314
+ await new Promise((resolve) => setTimeout(resolve, 50));
315
+ expect(
316
+ heard.length >= 1 && heard.some((each) => each.exists && each.data?.n === 1),
317
+ "a watch hears a write",
318
+ );
319
+ expect(!heard.some((each) => each.data?.n === 2), "a watch ends with its signal");
320
+ });
321
+ add(
322
+ "db: a person's own data is theirs: data/users/me is them, another's is refused, even past the bridge",
323
+ async (handlers) => {
324
+ const mine = as(handlers, viewers.interact);
325
+ ok(
326
+ await mine("db", { op: "set", path: "data/users/me/prefs", data: { dark: true } }),
327
+ "set own",
328
+ );
329
+ const own = ok(
330
+ await mine("db", { op: "get", path: `data/users/${viewers.interact.id}/prefs` }),
331
+ "get own",
332
+ ) as DbSnapshot;
333
+ expect(own.exists, "me is the viewer's own id");
334
+ const theirs = as(handlers, viewers.other);
335
+ const path = `data/users/${viewers.interact.id}/prefs`;
336
+ expect(
337
+ codeOf(await theirs("db", { op: "get", path })) === "forbidden",
338
+ "another person's data: forbidden",
339
+ );
340
+ const past = await direct(handlers, "db", { op: "get", path }, viewers.other);
341
+ expect(!past.ok, "the app's handler refuses another person's data itself");
342
+ const listed = await direct(
343
+ handlers,
344
+ "db",
345
+ { op: "query", collection: `data/users/${viewers.interact.id}` },
346
+ viewers.other,
347
+ );
348
+ expect(!listed.ok, "and their collections");
349
+ },
350
+ );
351
+ add("db: a person's own paths come back as data/users/me, never their id", async (handlers) => {
352
+ const mine = as(handlers, viewers.interact);
353
+ ok(await mine("db", { op: "set", path: "data/users/me/prefs", data: { n: 1 } }), "set own");
354
+ const got = ok(
355
+ await mine("db", { op: "get", path: "data/users/me/prefs" }),
356
+ "get",
357
+ ) as DbSnapshot;
358
+ const listed = ok(
359
+ await mine("db", { op: "query", collection: "data/users/me" }),
360
+ "query",
361
+ ) as {
362
+ docs: DbSnapshot[];
363
+ };
364
+ const said = JSON.stringify([got, listed]);
365
+ expect(got.path === "data/users/me/prefs", `a snapshot says me: ${got.path}`);
366
+ expect(
367
+ viewers.interact.id === undefined || !said.includes(viewers.interact.id),
368
+ "no answer names the viewer's id",
369
+ );
370
+ });
371
+ add("db: the page's rules hold, at the bridge and in the app", async (handlers) => {
372
+ expect(
373
+ codeOf(
374
+ await as(handlers, viewers.interact)("db", { op: "set", path: "config/main", data: {} }),
375
+ ) === "forbidden",
376
+ "a rule's write level holds at the bridge",
377
+ );
378
+ const past = await direct(
379
+ handlers,
380
+ "db",
381
+ { op: "set", path: "config/main", data: {} },
382
+ viewers.interact,
383
+ );
384
+ expect(!past.ok, "the app's handler applies the page's rules itself");
385
+ const view = await direct(
386
+ handlers,
387
+ "db",
388
+ { op: "set", path: "notes/v", data: {} },
389
+ viewers.view,
390
+ );
391
+ expect(!view.ok, "a view-only person writes nothing, even past the bridge");
392
+ ok(
393
+ await as(handlers, viewers.admin)("db", { op: "set", path: "config/main", data: {} }),
394
+ "an admin writes it",
395
+ );
396
+ });
397
+ // P093: a store that folds case keeps `Config/main` where `config/main` is.
398
+ add(
399
+ "db: a rule holds for its collection in any case, at the bridge and in the app",
400
+ async (handlers) => {
401
+ for (const path of ["Config/main", "CONFIG/main"]) {
402
+ expect(
403
+ codeOf(await as(handlers, viewers.interact)("db", { op: "set", path, data: {} })) ===
404
+ "forbidden",
405
+ `the rule for config holds at the bridge for ${path}`,
406
+ );
407
+ const past = await direct(
408
+ handlers,
409
+ "db",
410
+ { op: "set", path, data: {} },
411
+ viewers.interact,
412
+ );
413
+ expect(!past.ok, `the app's handler holds the rule for config for ${path} itself`);
414
+ }
415
+ },
416
+ );
417
+ }
418
+
419
+ if (config.capabilities.artifact !== undefined) {
420
+ add(
421
+ "artifact: get answers the current version; a publish from it makes the next",
422
+ async (handlers) => {
423
+ const call = as(handlers, viewers.admin);
424
+ const current = ok(await call("artifact", { op: "get" }), "get") as {
425
+ version: string;
426
+ files: { path: string }[];
427
+ };
428
+ expect(
429
+ typeof current.version === "string" && Array.isArray(current.files),
430
+ "get: { version, files }",
431
+ );
432
+ const published = ok(
433
+ await call("artifact", {
434
+ op: "publish",
435
+ base: current.version,
436
+ files: { "notes.txt": { text: "new" } },
437
+ label: "From the page",
438
+ }),
439
+ "publish",
440
+ ) as { version: string };
441
+ expect(published.version !== current.version, "a publish makes a new version");
442
+ const after = ok(await call("artifact", { op: "get" }), "get") as {
443
+ version: string;
444
+ files: { path: string }[];
445
+ };
446
+ expect(after.version === published.version, "the new version is current");
447
+ expect(
448
+ after.files.some((each) => each.path === "notes.txt"),
449
+ "with the patch applied",
450
+ );
451
+ expect(
452
+ current.files.every((file) => after.files.some((each) => each.path === file.path)),
453
+ "and the base's other files kept",
454
+ );
455
+ },
456
+ );
457
+ add(
458
+ "artifact: a publish from a base that moved is a conflict; below admin, refused even past the bridge",
459
+ async (handlers) => {
460
+ const call = as(handlers, viewers.admin);
461
+ const current = ok(await call("artifact", { op: "get" }), "get") as { version: string };
462
+ ok(
463
+ await call("artifact", {
464
+ op: "publish",
465
+ base: current.version,
466
+ files: { "a.txt": { text: "1" } },
467
+ }),
468
+ "publish",
469
+ );
470
+ expect(
471
+ codeOf(
472
+ await call("artifact", {
473
+ op: "publish",
474
+ base: current.version,
475
+ files: { "a.txt": { text: "2" } },
476
+ }),
477
+ ) === "conflict",
478
+ "a stale base: conflict",
479
+ );
480
+ expect(
481
+ codeOf(
482
+ await as(handlers, viewers.interact)("artifact", {
483
+ op: "publish",
484
+ base: "x",
485
+ files: { "a.txt": { text: "3" } },
486
+ }),
487
+ ) === "forbidden",
488
+ "below admin: forbidden at the bridge",
489
+ );
490
+ const now = ok(await call("artifact", { op: "get" }), "get") as { version: string };
491
+ const past = await direct(
492
+ handlers,
493
+ "artifact",
494
+ { op: "publish", base: now.version, files: { "a.txt": { text: "4" } } },
495
+ viewers.interact,
496
+ );
497
+ expect(!past.ok, "the app's handler refuses a publish below admin itself");
498
+ },
499
+ );
500
+ }
501
+
502
+ if (config.capabilities.artifact !== undefined) {
503
+ add("artifact: a publish whose merged files make no page is refused", async (handlers) => {
504
+ const call = as(handlers, viewers.admin);
505
+ const current = ok(await call("artifact", { op: "get" }), "get") as {
506
+ version: string;
507
+ entry: string;
508
+ };
509
+ const refused = await call("artifact", {
510
+ op: "publish",
511
+ base: current.version,
512
+ files: { [current.entry]: null },
513
+ });
514
+ expect(!refused.ok, "a publish that removes the entry is refused (check the merged set)");
515
+ });
516
+ }
517
+
518
+ if (config.capabilities.assets !== undefined) {
519
+ add("assets: an upload is listed, served by its id, and removed", async (handlers) => {
520
+ const call = as(handlers, viewers.admin);
521
+ const bytes = "R0lGODlhAQABAAAAACw="; // a small GIF's start: its bytes, as base64
522
+ const asset = ok(
523
+ await call("assets", { op: "upload", name: "pixel.gif", base64: bytes }),
524
+ "upload",
525
+ ) as AssetInfo;
526
+ expect(ASSET_ID.test(asset.id), "an asset's id is 32 lowercase hex characters");
527
+ expect(asset.url === assetUrl(asset.id), "its url is /_blob/<id>");
528
+ expect(
529
+ asset.type === "image/gif" && asset.size === 14,
530
+ "its type is the name's; its size the bytes'",
531
+ );
532
+ const listed = ok(
533
+ await as(handlers, viewers.view)("assets", { op: "list" }),
534
+ "list",
535
+ ) as AssetInfo[];
536
+ expect(
537
+ listed.some((each) => each.id === asset.id),
538
+ "the library lists it",
539
+ );
540
+ const store = options.assets?.(handlers);
541
+ if (store !== undefined) {
542
+ const stored = await store.get(asset.id, access);
543
+ expect(stored !== null && stored.size === 14, "the server's store has it");
544
+ const body = await stored?.read();
545
+ const length =
546
+ body instanceof Uint8Array
547
+ ? body.length
548
+ : body === null || body === undefined
549
+ ? -1
550
+ : (await new Response(body).arrayBuffer()).byteLength;
551
+ expect(length === 14, "with its bytes");
552
+ }
553
+ ok(await call("assets", { op: "delete", id: asset.id }), "delete");
554
+ const after = ok(await call("assets", { op: "list" }), "list") as AssetInfo[];
555
+ expect(!after.some((each) => each.id === asset.id), "a removed asset isn't listed");
556
+ if (store !== undefined) {
557
+ expect((await store.get(asset.id, access)) === null, "nor served");
558
+ }
559
+ });
560
+ add("assets: removing is the admins', even past the bridge", async (handlers) => {
561
+ const asset = ok(
562
+ await as(handlers, viewers.admin)("assets", {
563
+ op: "upload",
564
+ name: "a.txt",
565
+ base64: "aGk=",
566
+ }),
567
+ "upload",
568
+ ) as AssetInfo;
569
+ expect(
570
+ codeOf(await as(handlers, viewers.interact)("assets", { op: "delete", id: asset.id })) ===
571
+ "forbidden",
572
+ "below admin: forbidden at the bridge",
573
+ );
574
+ const past = await direct(handlers, "assets", { op: "delete", id: asset.id }, viewers.view);
575
+ expect(
576
+ !past.ok || past.value !== true,
577
+ "the app's handler refuses a removal below admin itself",
578
+ );
579
+ });
580
+ }
581
+
582
+ if (config.capabilities.comments !== undefined) {
583
+ add("comments: content hears only whether the composer opened", async (handlers) => {
584
+ const opened = ok(
585
+ await as(handlers, viewers.view)("comments", {
586
+ anchor: { name: "slide-3", label: "Slide 3" },
587
+ }),
588
+ "open",
589
+ );
590
+ expect(typeof opened === "boolean", "comments.open answers a boolean");
591
+ });
592
+ }
593
+ return cases;
594
+ }