@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,502 @@
1
+ import { atLeast, higher, isViewerLevel } from "./levels.js";
2
+ import { SEGMENT, isDbSegment } from "./segments.js";
3
+ export { isDbSegment };
4
+ /**
5
+ * The `db` capability's contract (P088): a document store the host keeps for an artifact, which
6
+ * its page reads and writes as the person viewing it. Porthole checks what crosses the frame (the
7
+ * shape, the sizes, the paths), resolves `me`, keeps a viewer to their own per-user data
8
+ * (`data/users/<id>`), and applies the page's per-level rules; the host stores, versions and
9
+ * evaluates them again on its own side (`dbAccess`), since its API is the wall for its data.
10
+ *
11
+ * Paths are slash-separated: a collection is an odd number of segments (`votes`,
12
+ * `rooms/r1/messages`), a document an even number (`votes/ada`). Every write to a document that
13
+ * exists names the version it read (`ifVersion`); a mismatch is a `conflict`.
14
+ */
15
+ export const DB_LIMITS = {
16
+ /** The most a document's data holds, JSON bytes. */
17
+ maxDocBytes: 1_048_576,
18
+ /** The most writes one batch holds, and their bytes together. */
19
+ maxBatchWrites: 50,
20
+ maxBatchBytes: 1_048_576,
21
+ /** The most documents one query answers. */
22
+ maxQueryLimit: 500,
23
+ maxWhere: 10,
24
+ /** The most values an `in` holds. */
25
+ maxIn: 30,
26
+ /** The most segments a path holds (a document: 16; a collection: 15). */
27
+ maxSegments: 16,
28
+ /** The deepest a document's data nests. */
29
+ maxDepth: 32,
30
+ /** The most watches one frame keeps at once. */
31
+ maxWatches: 50,
32
+ /** The most values (objects, arrays, scalars) one document holds, and one batch. */
33
+ maxNodes: 100_000,
34
+ /** The most a `where` operand holds: values, and JSON bytes. */
35
+ maxOperandNodes: 1_000,
36
+ maxOperandBytes: 16_384,
37
+ };
38
+ /** The per-user subtree: `data/users/<id>/…`, the viewer's own; `me` names the viewer. */
39
+ export const DB_USERS_PREFIX = "data/users/";
40
+ /** A path's segments, or null for one that names nothing (empty, dot segments, odd characters). */
41
+ export function dbSegments(path) {
42
+ if (typeof path !== "string" || path === "" || path.length > 2_048) {
43
+ return null;
44
+ }
45
+ const segments = path.split("/");
46
+ if (segments.length > DB_LIMITS.maxSegments ||
47
+ segments.some((each) => !SEGMENT.test(each) || each === "." || each === "..")) {
48
+ return null;
49
+ }
50
+ return segments;
51
+ }
52
+ /** Whether `path` names a document (`even`) or a collection (`odd`). */
53
+ export function dbPathKind(segments) {
54
+ return segments.length % 2 === 0 ? "doc" : "collection";
55
+ }
56
+ /** Field names a document never holds: a host merging them could set a prototype (P088). */
57
+ const RESERVED_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
58
+ /**
59
+ * Whether `value` is plain JSON data within `budget` nodes, no deeper than the limit, with no
60
+ * object or array reached twice (P088, after the review: structured clone keeps shared
61
+ * references, so a walk without this is exponential in a message of a few dozen objects). Each
62
+ * node is visited once: linear in what was sent, and stopped at the budget.
63
+ */
64
+ function plainJson(value, budget, depth) {
65
+ budget.nodes -= 1;
66
+ if (budget.nodes < 0 || depth > DB_LIMITS.maxDepth) {
67
+ return false;
68
+ }
69
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
70
+ return true;
71
+ }
72
+ if (typeof value === "number") {
73
+ return Number.isFinite(value);
74
+ }
75
+ if (typeof value !== "object") {
76
+ return false;
77
+ }
78
+ if (budget.seen.has(value)) {
79
+ return false;
80
+ }
81
+ budget.seen.add(value);
82
+ if (Array.isArray(value)) {
83
+ for (const each of value) {
84
+ if (!plainJson(each, budget, depth + 1)) {
85
+ return false;
86
+ }
87
+ }
88
+ return true;
89
+ }
90
+ const proto = Object.getPrototypeOf(value);
91
+ if (proto !== Object.prototype && proto !== null) {
92
+ return false;
93
+ }
94
+ for (const field of Object.keys(value)) {
95
+ if (field === "" || field.length > 256 || RESERVED_FIELDS.has(field)) {
96
+ return false;
97
+ }
98
+ if (!plainJson(value[field], budget, depth + 1)) {
99
+ return false;
100
+ }
101
+ }
102
+ return true;
103
+ }
104
+ /** Whether `value` is plain JSON within `nodes` nodes (a document's, a `where` operand's). */
105
+ export function isPlainJson(value, nodes = DB_LIMITS.maxNodes) {
106
+ return plainJson(value, { nodes, seen: new WeakSet() }, 0);
107
+ }
108
+ const encoder = new TextEncoder();
109
+ /**
110
+ * The fewest bytes checked plain JSON takes written out: each string's and key's characters (a
111
+ * character is a byte or more in UTF-8, an escape more), a byte a scalar. Stops past `max`.
112
+ */
113
+ function leastJsonBytes(value, max) {
114
+ if (typeof value === "string") {
115
+ return value.length + 2;
116
+ }
117
+ if (value === null || typeof value !== "object") {
118
+ return 1;
119
+ }
120
+ // The brackets, and a separator before each value but the first.
121
+ let total = 2;
122
+ let first = true;
123
+ if (Array.isArray(value)) {
124
+ for (const each of value) {
125
+ total += (first ? 0 : 1) + leastJsonBytes(each, max - total);
126
+ first = false;
127
+ if (total > max) {
128
+ return total;
129
+ }
130
+ }
131
+ return total;
132
+ }
133
+ for (const [field, each] of Object.entries(value)) {
134
+ // `"field":` and the value.
135
+ total += (first ? 0 : 1) + field.length + 3 + leastJsonBytes(each, max - total);
136
+ first = false;
137
+ if (total > max) {
138
+ return total;
139
+ }
140
+ }
141
+ return total;
142
+ }
143
+ /**
144
+ * The bytes checked plain JSON takes (`plainJson` first: no cycles, bounded nodes and depth), or
145
+ * `max + 1` once it surely takes more: written out only within its limit (P095: a string of
146
+ * control characters is six times its length as JSON, and could pass a string's longest).
147
+ */
148
+ export const jsonBytes = (value, max) => leastJsonBytes(value, max) > max ? max + 1 : encoder.encode(JSON.stringify(value)).length;
149
+ /** A document's data: a plain object, within the limits; "too_large" past them. */
150
+ function dbData(value, budget = {
151
+ nodes: DB_LIMITS.maxNodes,
152
+ seen: new WeakSet(),
153
+ }) {
154
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
155
+ return null;
156
+ }
157
+ if (!plainJson(value, budget, 0)) {
158
+ return null;
159
+ }
160
+ return jsonBytes(value, DB_LIMITS.maxDocBytes) > DB_LIMITS.maxDocBytes
161
+ ? "too_large"
162
+ : value;
163
+ }
164
+ const version = (value) => value === undefined
165
+ ? undefined
166
+ : typeof value === "number" && Number.isSafeInteger(value) && value >= 0
167
+ ? value
168
+ : null;
169
+ const WHERE_OPS = ["==", "!=", "<", "<=", ">", ">=", "in", "array-contains"];
170
+ function parseWrite(value, op, budget) {
171
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
172
+ return null;
173
+ }
174
+ const raw = value;
175
+ const kind = op ?? raw.op;
176
+ const segments = dbSegments(raw.path);
177
+ const ifVersion = version(raw.ifVersion);
178
+ if (segments === null || dbPathKind(segments) !== "doc" || ifVersion === null) {
179
+ return null;
180
+ }
181
+ const path = segments.join("/");
182
+ const at = ifVersion === undefined ? {} : { ifVersion };
183
+ if (kind === "delete") {
184
+ return { op: "delete", path, ...at };
185
+ }
186
+ if (kind !== "set" && kind !== "update") {
187
+ return null;
188
+ }
189
+ const data = dbData(raw.data, budget);
190
+ if (data === null || data === "too_large") {
191
+ return data;
192
+ }
193
+ return { op: kind, path, data, ...at };
194
+ }
195
+ function parseWhere(value) {
196
+ if (value === undefined) {
197
+ return undefined;
198
+ }
199
+ if (!Array.isArray(value) || value.length > DB_LIMITS.maxWhere) {
200
+ return null;
201
+ }
202
+ const out = [];
203
+ for (const each of value) {
204
+ if (!Array.isArray(each) || each.length !== 3) {
205
+ return null;
206
+ }
207
+ const [field, op, operand] = each;
208
+ if (typeof field !== "string" ||
209
+ field === "" ||
210
+ field.length > 256 ||
211
+ !WHERE_OPS.includes(op) ||
212
+ !isPlainJson(operand, DB_LIMITS.maxOperandNodes) ||
213
+ jsonBytes(operand, DB_LIMITS.maxOperandBytes) > DB_LIMITS.maxOperandBytes ||
214
+ (op === "in" && (!Array.isArray(operand) || operand.length > DB_LIMITS.maxIn))) {
215
+ return null;
216
+ }
217
+ out.push([field, op, operand]);
218
+ }
219
+ return out;
220
+ }
221
+ /** A `db` call's arguments as content sent them, checked: null (malformed), "too_large", or the call. */
222
+ export function parseDbRequest(args) {
223
+ if (args === null || typeof args !== "object" || Array.isArray(args)) {
224
+ return null;
225
+ }
226
+ const raw = args;
227
+ switch (raw.op) {
228
+ case "get":
229
+ case "watch": {
230
+ const segments = dbSegments(raw.path);
231
+ if (segments === null || (raw.op === "get" && dbPathKind(segments) !== "doc")) {
232
+ return null;
233
+ }
234
+ return { op: raw.op, path: segments.join("/") };
235
+ }
236
+ case "set":
237
+ case "update":
238
+ case "delete":
239
+ return parseWrite(raw, raw.op);
240
+ case "query": {
241
+ const segments = dbSegments(raw.collection);
242
+ const where = parseWhere(raw.where);
243
+ if (segments === null || dbPathKind(segments) !== "collection" || where === null) {
244
+ return null;
245
+ }
246
+ let orderBy;
247
+ if (raw.orderBy !== undefined) {
248
+ const order = raw.orderBy;
249
+ if (order === null ||
250
+ typeof order !== "object" ||
251
+ typeof order.field !== "string" ||
252
+ order.field === "" ||
253
+ order.field.length > 256 ||
254
+ (order.direction !== undefined && order.direction !== "asc" && order.direction !== "desc")) {
255
+ return null;
256
+ }
257
+ orderBy = { field: order.field, direction: order.direction === "desc" ? "desc" : "asc" };
258
+ }
259
+ const limit = raw.limit;
260
+ if (limit !== undefined &&
261
+ (typeof limit !== "number" ||
262
+ !Number.isInteger(limit) ||
263
+ limit < 1 ||
264
+ limit > DB_LIMITS.maxQueryLimit)) {
265
+ return null;
266
+ }
267
+ return {
268
+ op: "query",
269
+ collection: segments.join("/"),
270
+ ...(where === undefined ? {} : { where }),
271
+ ...(orderBy === undefined ? {} : { orderBy }),
272
+ ...(limit === undefined ? {} : { limit }),
273
+ };
274
+ }
275
+ case "batch": {
276
+ const writes = raw.writes;
277
+ if (!Array.isArray(writes) || writes.length === 0) {
278
+ return null;
279
+ }
280
+ if (writes.length > DB_LIMITS.maxBatchWrites) {
281
+ return "too_large";
282
+ }
283
+ const parsed = [];
284
+ // One budget for the whole batch, and one write a path: a batch is checked against one
285
+ // state, so two writes to a path would both pass it.
286
+ const budget = { nodes: DB_LIMITS.maxNodes, seen: new WeakSet() };
287
+ const paths = new Set();
288
+ for (const each of writes) {
289
+ const write = parseWrite(each, undefined, budget);
290
+ if (write === null || write === "too_large") {
291
+ return write;
292
+ }
293
+ if (paths.has(write.path)) {
294
+ return null;
295
+ }
296
+ paths.add(write.path);
297
+ parsed.push(write);
298
+ }
299
+ if (jsonBytes(parsed, DB_LIMITS.maxBatchBytes) > DB_LIMITS.maxBatchBytes) {
300
+ return "too_large";
301
+ }
302
+ return { op: "batch", writes: parsed };
303
+ }
304
+ default:
305
+ return null;
306
+ }
307
+ }
308
+ /**
309
+ * The most collections a page's rules name (P086). At publish, `DB_MAX_RULES`; where a
310
+ * declaration is shown (a mount, `intersectDeclarations`), an intersection of two: twice that, and
311
+ * `*` (P093, after its review).
312
+ */
313
+ export const DB_MAX_RULES = 100;
314
+ export const DB_MAX_SHOWN_RULES = 2 * DB_MAX_RULES + 1;
315
+ /** A collection's name, ASCII case folded: a store that folds case keeps `Votes` where `votes` is. */
316
+ export const foldCollection = (name) => name.replace(/[A-Z]+/gu, (run) => run.toLowerCase());
317
+ /** The level a rule asks to read or write (absent: the contract's, read view and write interact). */
318
+ export function dbRuleLevel(rule, write) {
319
+ const base = write ? "interact" : "view";
320
+ const asked = write ? rule?.write : rule?.read;
321
+ return asked === undefined ? base : higher(base, asked);
322
+ }
323
+ /** The stricter of two rules, read and write each (absent: the contract's level). */
324
+ export function stricterDbRule(x, y) {
325
+ const out = Object.create(null);
326
+ for (const field of ["read", "write"]) {
327
+ const p = x?.[field];
328
+ const q = y?.[field];
329
+ const level = p === undefined ? q : q === undefined ? p : higher(p, q);
330
+ if (level !== undefined) {
331
+ out[field] = level;
332
+ }
333
+ }
334
+ return out;
335
+ }
336
+ /**
337
+ * The rule a top-level collection is under (P086, P093): the rule object the rules give its exact
338
+ * name, else `*`'s, whole; never field by field (a collection's `{}` is the contract's levels,
339
+ * whatever `*` says). Then made stricter by every rule that names it in another ASCII case (a
340
+ * store that folds case keeps `Votes` where `votes` is): never looser than the exact name's
341
+ * lookup, and the same where nothing names it in another case. Own names only: a collection
342
+ * named `constructor` or `__proto__` is no rule unless the rules name it (P091). `dbAccess` and
343
+ * `intersectDeclarations` both read rules through this.
344
+ */
345
+ export function dbRuleOf(rules, collection) {
346
+ if (rules === undefined) {
347
+ return undefined;
348
+ }
349
+ const own = (key) => (Object.hasOwn(rules, key) ? rules[key] : undefined);
350
+ // After the re-review: `*` counts whenever the exact name is absent, variants or not.
351
+ let rule = own(collection) ?? own("*");
352
+ if (collection === "*") {
353
+ return rule;
354
+ }
355
+ const folded = foldCollection(collection);
356
+ for (const name of Object.keys(rules)) {
357
+ const each = rules[name];
358
+ if (name !== "*" &&
359
+ name !== collection &&
360
+ typeof each === "object" &&
361
+ foldCollection(name) === folded) {
362
+ rule = stricterDbRule(rule, each);
363
+ }
364
+ }
365
+ return rule;
366
+ }
367
+ /**
368
+ * A rules object's problem, or null. At publish (the default) at most `DB_MAX_RULES` names, none
369
+ * two that differ only in case (P093); where shown, an intersection's `DB_MAX_SHOWN_RULES`, and
370
+ * names in more than one case as a page from before P093 may have them.
371
+ */
372
+ export function dbRulesProblem(value, stage = "publish") {
373
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
374
+ return "must be an object of { read?, write } levels by collection";
375
+ }
376
+ const entries = Object.entries(value);
377
+ const most = stage === "publish" ? DB_MAX_RULES : DB_MAX_SHOWN_RULES;
378
+ if (entries.length > most) {
379
+ return `may name at most ${most} collections`;
380
+ }
381
+ const folded = new Map();
382
+ for (const [collection, rule] of entries) {
383
+ if (collection !== "*" && !SEGMENT.test(collection)) {
384
+ return `${JSON.stringify(collection)} is not a collection name (or "*")`;
385
+ }
386
+ const other = folded.get(foldCollection(collection));
387
+ if (stage === "publish" && other !== undefined) {
388
+ return `${JSON.stringify(other)} and ${JSON.stringify(collection)} differ only in case: name a collection once (a rule holds for its name in any case)`;
389
+ }
390
+ folded.set(foldCollection(collection), collection);
391
+ if (rule === null || typeof rule !== "object" || Array.isArray(rule)) {
392
+ return `${collection}: must be { read?, write? }`;
393
+ }
394
+ for (const [key, level] of Object.entries(rule)) {
395
+ if ((key !== "read" && key !== "write") || !isViewerLevel(level)) {
396
+ return `${collection}.${key}: must be read or write, a level (view, interact, admin, owner)`;
397
+ }
398
+ }
399
+ }
400
+ return null;
401
+ }
402
+ /** Whether an op reads or writes. */
403
+ const writes = (op) => op === "set" || op === "update" || op === "delete" || op === "batch";
404
+ /** The paths a call touches. */
405
+ function pathsOf(request) {
406
+ switch (request.op) {
407
+ case "query":
408
+ return [request.collection];
409
+ case "batch":
410
+ return request.writes.map((each) => each.path);
411
+ default:
412
+ return [request.path];
413
+ }
414
+ }
415
+ /** `path` with `me` resolved to the viewer, or null where it names someone else's data. */
416
+ function ownPath(path, viewer) {
417
+ const segments = path.split("/");
418
+ // `data`, however a store folds its case (after the review: `Data/users/<id>` is no way round).
419
+ if (segments[0]?.toLowerCase() !== "data") {
420
+ return path;
421
+ }
422
+ if (segments[0] !== "data") {
423
+ return null;
424
+ }
425
+ // `data` holds only per-user trees: `data/users/<id>/…`, the viewer's own.
426
+ if (segments[1] !== "users" || segments.length < 3) {
427
+ return null;
428
+ }
429
+ if (!isDbSegment(viewer?.id)) {
430
+ return null;
431
+ }
432
+ const id = segments[2] === "me" ? viewer?.id : segments[2];
433
+ if (id === undefined || viewer?.id === undefined || id !== viewer.id) {
434
+ return null;
435
+ }
436
+ segments[2] = id;
437
+ return segments.join("/");
438
+ }
439
+ /** The least level a rule asks for `path`. */
440
+ function ruleLevel(rules, path, write) {
441
+ return dbRuleLevel(dbRuleOf(rules, path.split("/")[0] ?? ""), write);
442
+ }
443
+ /**
444
+ * Whether `viewer` may make `request` under `rules` (P088), and the call with `me` resolved:
445
+ * someone else's per-user data is refused at every level, and so is any path under `data` that
446
+ * isn't `data/users/<own id>/…`; then each path's rule. The bridge applies it before the host's
447
+ * handler; a host applies it again in its own API (its data's wall).
448
+ */
449
+ export function dbAccess(request, viewer, rules) {
450
+ if (viewer === undefined) {
451
+ return { ok: false };
452
+ }
453
+ const resolve = (path) => ownPath(path, viewer);
454
+ for (const path of pathsOf(request)) {
455
+ const own = resolve(path);
456
+ if (own === null || !atLeast(viewer.level, ruleLevel(rules, own, writes(request.op)))) {
457
+ return { ok: false };
458
+ }
459
+ }
460
+ switch (request.op) {
461
+ case "query":
462
+ return { ok: true, request: { ...request, collection: resolve(request.collection) ?? "" } };
463
+ case "batch":
464
+ return {
465
+ ok: true,
466
+ request: {
467
+ op: "batch",
468
+ writes: request.writes.map((each) => ({ ...each, path: resolve(each.path) ?? "" })),
469
+ },
470
+ };
471
+ default:
472
+ return { ok: true, request: { ...request, path: resolve(request.path) ?? "" } };
473
+ }
474
+ }
475
+ /**
476
+ * A `db` answer as content gets it (P088, after the review): every path in the viewer's own tree
477
+ * says `data/users/me`, never their id, so a page that didn't declare `user` doesn't learn who is
478
+ * viewing from its own data's paths. Snapshots and `{ docs }`; anything else as it is.
479
+ */
480
+ export function withMe(value, viewer) {
481
+ const id = viewer?.id;
482
+ if (id === undefined || value === null || typeof value !== "object") {
483
+ return value;
484
+ }
485
+ const own = `${DB_USERS_PREFIX}${id}`;
486
+ const path = (each) => {
487
+ if (each === null || typeof each !== "object" || Array.isArray(each)) {
488
+ return each;
489
+ }
490
+ const snapshot = each;
491
+ if (typeof snapshot.path === "string" &&
492
+ (snapshot.path === own || snapshot.path.startsWith(`${own}/`))) {
493
+ return { ...snapshot, path: `${DB_USERS_PREFIX}me${snapshot.path.slice(own.length)}` };
494
+ }
495
+ return each;
496
+ };
497
+ const docs = value.docs;
498
+ if (Array.isArray(docs)) {
499
+ return { ...value, docs: docs.map(path) };
500
+ }
501
+ return path(value);
502
+ }
@@ -0,0 +1,100 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import { type RuntimeVersion } from "./contract.ts";
3
+ import { type DbRules } from "./db.ts";
4
+ import { type ViewerLevel } from "./levels.ts";
5
+ /**
6
+ * A page's declaration (P086): the capabilities it uses, by name, each with its own config,
7
+ * stored with the artifact when it is published and handed to `mount` when it is shown; and the
8
+ * runtime contract it was written against, pinned. Built-ins are never declared.
9
+ *
10
+ * At publish (`declareCapabilities`): omitted carries the stored declaration forward (and its
11
+ * pin); `{}` clears it; a non-empty object replaces it whole. A page can't change its own: a
12
+ * publish from the page (`artifact.publish`) carries none.
13
+ */
14
+ /** Every capability's config may raise its methods' levels (never lower them). */
15
+ export interface DeclaredCapability {
16
+ readonly levels?: Readonly<Record<string, ViewerLevel>>;
17
+ }
18
+ /** `data`: which of the host's resources and tools the page uses (absent: all it serves). */
19
+ export interface DeclaredData extends DeclaredCapability {
20
+ /** URIs, exact, or a prefix ending in `*` (`app://tasks/*`). */
21
+ readonly resources?: readonly string[];
22
+ readonly tools?: readonly string[];
23
+ }
24
+ /** `db`: the page's rules for its data, by top-level collection (`DbRules`). */
25
+ export interface DeclaredDb extends DeclaredCapability {
26
+ readonly rules?: DbRules;
27
+ }
28
+ /** What a page declares, by runtime capability name. */
29
+ export interface CapabilityDeclaration {
30
+ readonly user?: DeclaredCapability;
31
+ readonly chat?: DeclaredCapability;
32
+ readonly data?: DeclaredData;
33
+ readonly context?: DeclaredCapability;
34
+ readonly artifact?: DeclaredCapability;
35
+ readonly assets?: DeclaredCapability;
36
+ readonly db?: DeclaredDb;
37
+ }
38
+ /** A declaration as an artifact stores it and a mount is given it. */
39
+ export interface PageDeclaration {
40
+ readonly capabilities: CapabilityDeclaration;
41
+ readonly runtime: RuntimeVersion;
42
+ }
43
+ export interface DeclarationProblem {
44
+ /** Where, as `capabilities.db.rules.votes`. */
45
+ readonly path: string;
46
+ readonly message: string;
47
+ }
48
+ /**
49
+ * The problems with a declaration, against the host's offer (`config`): each name one the
50
+ * runtime knows, the config offers and isn't built in; each config of its own shape. Empty: fine.
51
+ */
52
+ export declare function declarationProblems(given: unknown, config: PortholeConfig, runtime?: RuntimeVersion): DeclarationProblem[];
53
+ /** A declaration checked (a host's stored one, given to `mount`); throws a `TypeError` naming its problems. */
54
+ export declare function checkDeclaration(given: unknown, config: PortholeConfig): PageDeclaration;
55
+ /**
56
+ * At publish (P086): the declaration a new version leaves the artifact with.
57
+ * - `given` undefined: the stored one, unchanged (its pin too); none stored: an empty one.
58
+ * - `given` `{}`: cleared.
59
+ * - `given` non-empty: it replaces the stored one whole (anything not restated is revoked).
60
+ * The pin moves only when the author asks (`runtime`). Checked against the host's offer.
61
+ */
62
+ export declare function declareCapabilities(options: {
63
+ readonly stored?: PageDeclaration | null;
64
+ readonly given?: unknown;
65
+ readonly config: PortholeConfig;
66
+ readonly runtime?: unknown;
67
+ }): {
68
+ readonly ok: true;
69
+ readonly declaration: PageDeclaration;
70
+ /** Whether it differs from the stored one. */
71
+ readonly changed: boolean;
72
+ } | {
73
+ readonly ok: false;
74
+ readonly problems: readonly DeclarationProblem[];
75
+ };
76
+ /** Whether `name` matches a declared list's entry (exact, or a prefix ending in `*`). */
77
+ export declare function declaredMatch(list: readonly string[] | undefined, name: string): boolean;
78
+ /**
79
+ * What a version may do when it is shown (after the review): what it declared when it was
80
+ * published AND what the artifact declares now. A host stores each version's declaration with
81
+ * it (`declareCapabilities` at its publish) and mounts a version with this, so an old version
82
+ * never keeps what the artifact has since revoked, nor gains what it declared later. Each
83
+ * capability only where both declare it, at the stricter levels, the narrower `data` names and
84
+ * the stricter `db` rules (each side read as `dbAccess` reads it, P093); the version's own pinned
85
+ * runtime. Whatever the result allows, each side allows alone; a mount takes it (two pages at
86
+ * the publish limits make one within a mount's). Objects without a prototype.
87
+ *
88
+ * Answers its problems (P093, after its review) where either side isn't a declaration's shape
89
+ * (or the two make one past a mount's limits): show the version as an error, never with `null`
90
+ * (that is 0.6's surface) or with either side alone.
91
+ */
92
+ export declare function tryIntersectDeclarations(version: PageDeclaration, current: PageDeclaration): {
93
+ readonly ok: true;
94
+ readonly declaration: PageDeclaration;
95
+ } | {
96
+ readonly ok: false;
97
+ readonly problems: readonly DeclarationProblem[];
98
+ };
99
+ /** `tryIntersectDeclarations`, a `TypeError` naming the problems where it answers some. */
100
+ export declare function intersectDeclarations(version: PageDeclaration, current: PageDeclaration): PageDeclaration;