@botiverse/porthole 0.7.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.
- package/README.md +9 -2
- package/THIRD_PARTY_NOTICES.md +421 -0
- package/dist/bridge/bounded-text.d.ts +34 -0
- package/dist/bridge/bounded-text.js +188 -0
- package/dist/bridge/bridge.d.ts +25 -5
- package/dist/bridge/bridge.js +311 -73
- package/dist/bridge/json-data.d.ts +28 -0
- package/dist/bridge/json-data.js +86 -0
- package/dist/bridge/navigation.d.ts +5 -0
- package/dist/bridge/navigation.js +7 -0
- package/dist/bridge/refusal.js +1 -0
- package/dist/bridge/types.d.ts +32 -1
- package/dist/check/page-source.js +1 -1
- package/dist/check/page.js +2 -0
- package/dist/compile/compile.d.ts +6 -0
- package/dist/compile/compile.js +3 -1
- package/dist/compile/policy.d.ts +38 -2
- package/dist/compile/policy.js +122 -7
- package/dist/config/capabilities.d.ts +23 -4
- package/dist/config/capabilities.js +12 -2
- package/dist/config/schema.d.ts +11 -0
- package/dist/config/validate.d.ts +8 -2
- package/dist/config/validate.js +28 -6
- package/dist/config/warnings.d.ts +20 -0
- package/dist/config/warnings.js +25 -0
- package/dist/conformance/behavior.js +46 -1
- package/dist/conformance/cookies.d.ts +15 -0
- package/dist/conformance/cookies.js +80 -0
- package/dist/conformance/harness/page.d.ts +1 -0
- package/dist/conformance/harness/page.js +9 -2
- package/dist/conformance/harness-source.js +1 -1
- package/dist/conformance/host-kit.js +5 -1
- package/dist/conformance/index.d.ts +10 -0
- package/dist/conformance/limits.js +38 -1
- package/dist/conformance/runtime.js +10 -0
- package/dist/conformance/served.d.ts +2 -0
- package/dist/conformance/served.js +737 -4
- package/dist/files/paths.js +4 -0
- package/dist/guide/gates.d.ts +7 -1
- package/dist/guide/gates.js +12 -0
- package/dist/guide/guide.js +2 -2
- package/dist/guide/runtime.js +11 -3
- package/dist/host/create-host.js +49 -37
- package/dist/host/pages-of-set.d.ts +43 -0
- package/dist/host/pages-of-set.js +196 -0
- package/dist/host/types.d.ts +8 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.js +3 -2
- package/dist/mcp/adapter.js +11 -15
- package/dist/node/index.d.ts +36 -4
- package/dist/node/index.js +402 -101
- package/dist/presets/presets.d.ts +16 -8
- package/dist/presets/presets.js +39 -8
- package/dist/protocol/live-data.d.ts +6 -2
- package/dist/protocol/live-data.js +20 -1
- package/dist/protocol/mcp-apps.d.ts +13 -2
- package/dist/protocol/mcp-apps.js +10 -2
- package/dist/protocol/message-text.d.ts +8 -0
- package/dist/protocol/message-text.js +29 -0
- package/dist/protocol/runtime-calls.js +3 -0
- package/dist/protocol/shell-adapter.js +16 -22
- package/dist/react/context-notice.d.ts +32 -0
- package/dist/react/context-notice.js +28 -0
- package/dist/react/dialog.js +62 -18
- package/dist/react/frame.d.ts +12 -1
- package/dist/react/frame.js +79 -2
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +2 -1
- package/dist/runtime/contract.d.ts +9 -1
- package/dist/runtime/contract.js +31 -2
- package/dist/runtime/db.d.ts +41 -6
- package/dist/runtime/db.js +120 -16
- package/dist/runtime/declaration.d.ts +15 -1
- package/dist/runtime/declaration.js +184 -87
- package/dist/runtime/requests.js +27 -11
- package/dist/runtime/types.generated.js +1 -1
- package/dist/server/files.d.ts +5 -0
- package/dist/server/files.js +22 -7
- package/dist/server/host.d.ts +18 -1
- package/dist/server/host.js +132 -2
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/peer.d.ts +4 -0
- package/dist/server/peer.js +19 -0
- package/dist/server/proxy.d.ts +6 -0
- package/dist/server/proxy.js +12 -3
- package/dist/server/server.js +113 -26
- package/dist/server/types.d.ts +6 -3
- package/dist/shell/document.d.ts +8 -0
- package/dist/shell/document.js +3 -0
- package/dist/shell/runtime.js +361 -14
- package/docs/ADOPTING.md +119 -14
- package/docs/ARCHITECTURE.md +13 -3
- package/docs/DECISIONS.md +1455 -8
- package/docs/DESIGN.md +79 -25
- package/docs/THREAT_MODEL.md +616 -0
- package/package.json +14 -3
- package/src/bridge/bounded-text.ts +240 -0
- package/src/bridge/bridge.ts +373 -84
- package/src/bridge/json-data.ts +95 -0
- package/src/bridge/navigation.ts +10 -0
- package/src/bridge/refusal.ts +1 -0
- package/src/bridge/types.ts +30 -1
- package/src/check/page.ts +2 -0
- package/src/compile/compile.ts +9 -1
- package/src/compile/policy.ts +130 -7
- package/src/config/capabilities.ts +22 -3
- package/src/config/schema.ts +11 -0
- package/src/config/validate.ts +43 -5
- package/src/config/warnings.ts +42 -0
- package/src/conformance/behavior.ts +54 -1
- package/src/conformance/cookies.ts +93 -0
- package/src/conformance/harness/page.ts +11 -2
- package/src/conformance/host-kit.ts +10 -1
- package/src/conformance/index.ts +10 -0
- package/src/conformance/limits.ts +39 -1
- package/src/conformance/runtime.ts +21 -0
- package/src/conformance/served.ts +888 -4
- package/src/files/paths.ts +4 -0
- package/src/guide/gates.ts +13 -1
- package/src/guide/guide.ts +3 -3
- package/src/guide/runtime.ts +12 -3
- package/src/host/create-host.ts +54 -36
- package/src/host/pages-of-set.ts +226 -0
- package/src/host/types.ts +15 -1
- package/src/index.ts +5 -0
- package/src/mcp/adapter.ts +16 -20
- package/src/node/index.ts +507 -116
- package/src/presets/presets.ts +60 -17
- package/src/protocol/live-data.ts +31 -3
- package/src/protocol/mcp-apps.ts +11 -2
- package/src/protocol/message-text.ts +36 -0
- package/src/protocol/runtime-calls.ts +3 -0
- package/src/protocol/shell-adapter.ts +27 -23
- package/src/react/context-notice.tsx +95 -0
- package/src/react/dialog.tsx +77 -17
- package/src/react/frame.tsx +101 -0
- package/src/react/index.ts +8 -1
- package/src/runtime/contract.ts +36 -2
- package/src/runtime/db.ts +140 -20
- package/src/runtime/declaration.ts +227 -89
- package/src/runtime/requests.ts +27 -11
- package/src/runtime/types.generated.ts +1 -1
- package/src/server/files.ts +29 -11
- package/src/server/host.ts +158 -3
- package/src/server/index.ts +1 -0
- package/src/server/peer.ts +21 -0
- package/src/server/proxy.ts +13 -3
- package/src/server/server.ts +139 -36
- package/src/server/types.ts +6 -3
- package/src/shell/document.ts +8 -0
- package/src/shell/runtime.ts +361 -14
- package/types/runtime/v1/context.d.ts +13 -2
package/src/react/frame.tsx
CHANGED
|
@@ -28,6 +28,7 @@ import type {
|
|
|
28
28
|
DataCache,
|
|
29
29
|
Proceed,
|
|
30
30
|
Refusal,
|
|
31
|
+
Show,
|
|
31
32
|
} from "../bridge/types.ts";
|
|
32
33
|
import { isRefused, reasonOf, Refused, type RefusalReason } from "../bridge/refusal.ts";
|
|
33
34
|
import type { CapabilityName } from "../config/capabilities.ts";
|
|
@@ -37,6 +38,7 @@ import { createHost } from "../host/create-host.ts";
|
|
|
37
38
|
import type { DisplayEvents, DisplayHandle, FrameOutcome, HostErrorKind } from "../host/types.ts";
|
|
38
39
|
import type { InstanceLocator, InstanceRef } from "../isolation/types.ts";
|
|
39
40
|
import { ConfirmDialog } from "./dialog.tsx";
|
|
41
|
+
import { ContextNotice, type ContextUpdate } from "./context-notice.tsx";
|
|
40
42
|
import { createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
|
|
41
43
|
import { CopyToast, type CopyNotice } from "./toast.tsx";
|
|
42
44
|
import type { PortholeClient } from "../host/client.ts";
|
|
@@ -48,6 +50,10 @@ import type { PortholeClient } from "../host/client.ts";
|
|
|
48
50
|
* its height. All the isolation is the core's (`createHost`); this is mounting and lifecycle.
|
|
49
51
|
*/
|
|
50
52
|
|
|
53
|
+
/** Why a model context update didn't go: it was never drawn (the review of P100). */
|
|
54
|
+
const REPLACED_UNSEEN = "a later update of this display replaced it before the person saw it";
|
|
55
|
+
const HIDDEN_UNSEEN = "the person hid this display's notice before the update was drawn";
|
|
56
|
+
|
|
51
57
|
/** How far off screen a frame starts (and keeps) running. */
|
|
52
58
|
const NEAR_SCREEN = "800px 0px";
|
|
53
59
|
/** The height a display holds before it has reported its own. */
|
|
@@ -77,6 +83,8 @@ interface PageState {
|
|
|
77
83
|
readonly locate?: InstanceLocator["locate"];
|
|
78
84
|
/** The default `copyText`: copies on the host's page and shows the toast (P052). */
|
|
79
85
|
readonly copyText?: CapabilityHandler<"copyText">;
|
|
86
|
+
/** Who shows the person `show`-gated calls: the provider's own, or its notice (P100). */
|
|
87
|
+
readonly show?: Show;
|
|
80
88
|
}
|
|
81
89
|
|
|
82
90
|
/** Without a provider: one registry for the page, and no one to confirm (gated calls refused). */
|
|
@@ -136,6 +144,13 @@ export interface PortholeProviderProps {
|
|
|
136
144
|
* refuses them all with its reason, and their handlers may be left out (P080).
|
|
137
145
|
*/
|
|
138
146
|
readonly consent?: Consent | Refused;
|
|
147
|
+
/**
|
|
148
|
+
* Shows the person each `show`-gated call, outside every frame, before its handler has it
|
|
149
|
+
* (P100): by default, a frame's model context update (`setModelContext`), the content's text for
|
|
150
|
+
* the agent's next turn. Omitted: Porthole's `ContextNotice`. A host that shows it its own way (a
|
|
151
|
+
* chip by its composer) passes this; the update replaces the display's last.
|
|
152
|
+
*/
|
|
153
|
+
readonly show?: Show;
|
|
139
154
|
/** What the host last had for a resource, answered stale first (P079). */
|
|
140
155
|
readonly cached?: DataCache;
|
|
141
156
|
/** How the host names itself in the handshake. */
|
|
@@ -146,6 +161,8 @@ export interface PortholeProviderProps {
|
|
|
146
161
|
readonly dialogClassName?: string;
|
|
147
162
|
/** A class for the default copy toast, to restyle it. */
|
|
148
163
|
readonly toastClassName?: string;
|
|
164
|
+
/** A class for the default model context notice, to restyle it. */
|
|
165
|
+
readonly contextClassName?: string;
|
|
149
166
|
/**
|
|
150
167
|
* The page's CSP nonce, where its `script-src` is nonce-based: opaque frames inherit the page's
|
|
151
168
|
* policy, so their shell carries it (P054). `"auto"`: read from the page (a `<meta
|
|
@@ -240,6 +257,69 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
|
|
|
240
257
|
return copied;
|
|
241
258
|
}, []);
|
|
242
259
|
const closeNotice = useCallback(() => setNotice(null), []);
|
|
260
|
+
// The default show (P100): each display's latest model context update, in the notice, outside
|
|
261
|
+
// every frame; the host's own `show` replaces it.
|
|
262
|
+
const [contexts, setContexts] = useState<readonly ContextUpdate[]>([]);
|
|
263
|
+
// Each show waiting for its own update to be on the page (after the review: React may draw two
|
|
264
|
+
// updates of a display in one render, the latest only). The number orders a display's shows.
|
|
265
|
+
const unseen = useRef<
|
|
266
|
+
{ entry: ContextUpdate; seq: number; resolve: () => void; reject: (error: Error) => void }[]
|
|
267
|
+
>([]);
|
|
268
|
+
const latest = useRef(new Map<string, number>());
|
|
269
|
+
const sequence = useRef(0);
|
|
270
|
+
useLayoutEffect(() => {
|
|
271
|
+
unseen.current = unseen.current.filter((each) => {
|
|
272
|
+
const drawn = contexts.find((one) => one.displayId === each.entry.displayId);
|
|
273
|
+
if (drawn === each.entry) {
|
|
274
|
+
each.resolve();
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
// A later update of the display replaced it before it was drawn: never seen, never sent.
|
|
278
|
+
if ((latest.current.get(each.entry.displayId) ?? 0) > each.seq) {
|
|
279
|
+
each.reject(new Error(REPLACED_UNSEEN));
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
return true;
|
|
283
|
+
});
|
|
284
|
+
}, [contexts]);
|
|
285
|
+
const ownShow = useRef(props.show);
|
|
286
|
+
useLayoutEffect(() => {
|
|
287
|
+
ownShow.current = props.show;
|
|
288
|
+
});
|
|
289
|
+
const show = useCallback<Show>((request) => {
|
|
290
|
+
if (ownShow.current !== undefined) {
|
|
291
|
+
return ownShow.current(request);
|
|
292
|
+
}
|
|
293
|
+
if (request.capability !== "setModelContext") {
|
|
294
|
+
// The notice words model context only: anything else it would show unworded, so it isn't
|
|
295
|
+
// shown, and doesn't go (fail closed).
|
|
296
|
+
throw new Error(`Porthole's notice shows model context only, not ${request.capability}`);
|
|
297
|
+
}
|
|
298
|
+
const entry: ContextUpdate = {
|
|
299
|
+
displayId: request.display.id,
|
|
300
|
+
title: request.display.title,
|
|
301
|
+
update: request.args,
|
|
302
|
+
};
|
|
303
|
+
sequence.current += 1;
|
|
304
|
+
const seq = sequence.current;
|
|
305
|
+
latest.current.set(entry.displayId, seq);
|
|
306
|
+
// The call goes once this very update is on the page, so the handler never has it first.
|
|
307
|
+
return new Promise<void>((resolve, reject) => {
|
|
308
|
+
unseen.current.push({ entry, seq, resolve, reject });
|
|
309
|
+
setContexts((each) => [...each.filter((one) => one.displayId !== entry.displayId), entry]);
|
|
310
|
+
});
|
|
311
|
+
}, []);
|
|
312
|
+
const hideContext = useCallback((displayId: string) => {
|
|
313
|
+
// Hidden by the person: an update of the display not drawn yet never will be.
|
|
314
|
+
unseen.current = unseen.current.filter((each) => {
|
|
315
|
+
if (each.entry.displayId !== displayId) {
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
each.reject(new Error(HIDDEN_UNSEEN));
|
|
319
|
+
return false;
|
|
320
|
+
});
|
|
321
|
+
setContexts((each) => each.filter((one) => one.displayId !== displayId));
|
|
322
|
+
}, []);
|
|
243
323
|
// Compared by value, and read when used: an inline hostInfo or locator doesn't start every
|
|
244
324
|
// frame again on each render.
|
|
245
325
|
const hostInfo = useByValue(props.hostInfo);
|
|
@@ -297,6 +377,7 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
|
|
|
297
377
|
heights,
|
|
298
378
|
confirm,
|
|
299
379
|
copyText,
|
|
380
|
+
show,
|
|
300
381
|
...(consents ? { consent } : {}),
|
|
301
382
|
...(refusesAll === undefined ? {} : { refusesAll }),
|
|
302
383
|
...(caches ? { cached } : {}),
|
|
@@ -314,6 +395,7 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
|
|
|
314
395
|
heights,
|
|
315
396
|
confirm,
|
|
316
397
|
copyText,
|
|
398
|
+
show,
|
|
317
399
|
consents,
|
|
318
400
|
consent,
|
|
319
401
|
refusesAll,
|
|
@@ -366,6 +448,13 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
|
|
|
366
448
|
}}
|
|
367
449
|
/>
|
|
368
450
|
) : null}
|
|
451
|
+
{props.show !== undefined ? null : (
|
|
452
|
+
<ContextNotice
|
|
453
|
+
updates={contexts}
|
|
454
|
+
onHide={hideContext}
|
|
455
|
+
{...(props.contextClassName === undefined ? {} : { className: props.contextClassName })}
|
|
456
|
+
/>
|
|
457
|
+
)}
|
|
369
458
|
{props.notify !== undefined ? null : (
|
|
370
459
|
<CopyToast
|
|
371
460
|
notice={notice}
|
|
@@ -696,6 +785,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
|
|
|
696
785
|
copyText: pageCopyText,
|
|
697
786
|
confirm: pageConfirm,
|
|
698
787
|
consent: pageConsent,
|
|
788
|
+
show: pageShow,
|
|
699
789
|
cached: pageCached,
|
|
700
790
|
hostInfo,
|
|
701
791
|
locate,
|
|
@@ -828,6 +918,16 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
|
|
|
828
918
|
},
|
|
829
919
|
}
|
|
830
920
|
: {}),
|
|
921
|
+
// Shown as the latest props name the display (P100).
|
|
922
|
+
...(pageShow === undefined
|
|
923
|
+
? {}
|
|
924
|
+
: {
|
|
925
|
+
show: (request: ConfirmRequest) =>
|
|
926
|
+
pageShow({
|
|
927
|
+
...request,
|
|
928
|
+
display: { ...request.display, id: latest().displayId, title: latest().title },
|
|
929
|
+
}),
|
|
930
|
+
}),
|
|
831
931
|
...(caches
|
|
832
932
|
? {
|
|
833
933
|
cached: (args: { readonly uri: string }, context: CallContext) =>
|
|
@@ -895,6 +995,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
|
|
|
895
995
|
pageCopyText,
|
|
896
996
|
pageConfirm,
|
|
897
997
|
pageConsent,
|
|
998
|
+
pageShow,
|
|
898
999
|
pageCached,
|
|
899
1000
|
refusesAll,
|
|
900
1001
|
hostInfo,
|
package/src/react/index.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* `@botiverse/porthole/react`: the thin React binding (TSX: a host's bundler compiles it, or the
|
|
3
3
|
* package's `dist`). Peer: `react` (19.2+, for `useEffectEvent`).
|
|
4
4
|
*
|
|
5
|
-
* <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast
|
|
5
|
+
* <PortholeProvider> // per page: live-frame cap, heights, the dialog, the copy toast, the context notice
|
|
6
6
|
* <PortholeFrame config={widgetConfig} displayId={id} title={title} scheme={scheme}
|
|
7
7
|
* content={code} partial={streaming} handlers={{ sendPrompt, openLink }}
|
|
8
8
|
* theme={tokensFor} onError={report} />
|
|
@@ -18,6 +18,13 @@ export {
|
|
|
18
18
|
type PortholeProviderProps,
|
|
19
19
|
} from "./frame.tsx";
|
|
20
20
|
export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
|
|
21
|
+
export {
|
|
22
|
+
ContextNotice,
|
|
23
|
+
contextSize,
|
|
24
|
+
contextText,
|
|
25
|
+
type ContextNoticeProps,
|
|
26
|
+
type ContextUpdate,
|
|
27
|
+
} from "./context-notice.tsx";
|
|
21
28
|
export {
|
|
22
29
|
cssVariableTheme,
|
|
23
30
|
PortholeView,
|
package/src/runtime/contract.ts
CHANGED
|
@@ -204,11 +204,43 @@ export function methodOf(serves: CapabilityName, args: unknown): string | null {
|
|
|
204
204
|
return typeof op === "string" && family.methods.includes(op) ? op : null;
|
|
205
205
|
}
|
|
206
206
|
|
|
207
|
+
/**
|
|
208
|
+
* The runtime methods a validated call runs, each as often as it runs it: its own, and for a db
|
|
209
|
+
* batch each of its writes' (`set`, `update`, `delete`), for a db watch the read it repeats (`get`
|
|
210
|
+
* for a document, `query` for a collection). Each one's level and gates apply to the call (P091
|
|
211
|
+
* item 4 for levels, P094 for gates): a batch is its writes, a watch its read.
|
|
212
|
+
*/
|
|
213
|
+
export function methodsOfCall(serves: CapabilityName, args: unknown): readonly string[] {
|
|
214
|
+
const own = methodOf(serves, args);
|
|
215
|
+
if (own === null) {
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
if (serves !== "db") {
|
|
219
|
+
return [own];
|
|
220
|
+
}
|
|
221
|
+
const request = args as {
|
|
222
|
+
readonly op: string;
|
|
223
|
+
readonly path?: string;
|
|
224
|
+
readonly writes?: readonly { readonly op: string }[];
|
|
225
|
+
};
|
|
226
|
+
if (request.op === "batch") {
|
|
227
|
+
return [own, ...(request.writes ?? []).map((write) => write.op)];
|
|
228
|
+
}
|
|
229
|
+
if (request.op === "watch") {
|
|
230
|
+
return [own, (request.path ?? "").split("/").length % 2 === 0 ? "get" : "query"];
|
|
231
|
+
}
|
|
232
|
+
return [own];
|
|
233
|
+
}
|
|
234
|
+
|
|
207
235
|
/**
|
|
208
236
|
* Whether a config's asset uploads are its admins' alone (`assets.upload` at admin or above,
|
|
209
|
-
* P089): only then may scripts and styles an admin uploaded run from the library.
|
|
237
|
+
* P089): only then may scripts and styles an admin uploaded run from the library. Never where
|
|
238
|
+
* the config serves no assets (P103: a config that dropped them runs nothing of its library).
|
|
210
239
|
*/
|
|
211
240
|
export function assetCodeRuns(config: PortholeConfig): boolean {
|
|
241
|
+
if (config.capabilities.assets === undefined) {
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
212
244
|
const level = methodLevel(config, "assets", "upload");
|
|
213
245
|
return level !== null && atLeast(level, "admin");
|
|
214
246
|
}
|
|
@@ -259,7 +291,9 @@ export function methodLevel(
|
|
|
259
291
|
}
|
|
260
292
|
const host = config.capabilities[spec.serves]?.levels?.[name];
|
|
261
293
|
const base = host === undefined ? spec.level : higher(host, spec.floor);
|
|
262
|
-
|
|
294
|
+
// The page's own names only (P093): a declaration a host passes unchecked may be a plain object.
|
|
295
|
+
const levels = declared?.levels;
|
|
296
|
+
const page = levels !== undefined && Object.hasOwn(levels, name) ? levels[name] : undefined;
|
|
263
297
|
return page === undefined ? base : higher(base, page);
|
|
264
298
|
}
|
|
265
299
|
|
package/src/runtime/db.ts
CHANGED
|
@@ -134,8 +134,48 @@ export function isPlainJson(value: unknown, nodes: number = DB_LIMITS.maxNodes):
|
|
|
134
134
|
|
|
135
135
|
const encoder = new TextEncoder();
|
|
136
136
|
|
|
137
|
-
/**
|
|
138
|
-
|
|
137
|
+
/**
|
|
138
|
+
* The fewest bytes checked plain JSON takes written out: each string's and key's characters (a
|
|
139
|
+
* character is a byte or more in UTF-8, an escape more), a byte a scalar. Stops past `max`.
|
|
140
|
+
*/
|
|
141
|
+
function leastJsonBytes(value: unknown, max: number): number {
|
|
142
|
+
if (typeof value === "string") {
|
|
143
|
+
return value.length + 2;
|
|
144
|
+
}
|
|
145
|
+
if (value === null || typeof value !== "object") {
|
|
146
|
+
return 1;
|
|
147
|
+
}
|
|
148
|
+
// The brackets, and a separator before each value but the first.
|
|
149
|
+
let total = 2;
|
|
150
|
+
let first = true;
|
|
151
|
+
if (Array.isArray(value)) {
|
|
152
|
+
for (const each of value as readonly unknown[]) {
|
|
153
|
+
total += (first ? 0 : 1) + leastJsonBytes(each, max - total);
|
|
154
|
+
first = false;
|
|
155
|
+
if (total > max) {
|
|
156
|
+
return total;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return total;
|
|
160
|
+
}
|
|
161
|
+
for (const [field, each] of Object.entries(value)) {
|
|
162
|
+
// `"field":` and the value.
|
|
163
|
+
total += (first ? 0 : 1) + field.length + 3 + leastJsonBytes(each, max - total);
|
|
164
|
+
first = false;
|
|
165
|
+
if (total > max) {
|
|
166
|
+
return total;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return total;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The bytes checked plain JSON takes (`plainJson` first: no cycles, bounded nodes and depth), or
|
|
174
|
+
* `max + 1` once it surely takes more: written out only within its limit (P095: a string of
|
|
175
|
+
* control characters is six times its length as JSON, and could pass a string's longest).
|
|
176
|
+
*/
|
|
177
|
+
export const jsonBytes = (value: unknown, max: number): number =>
|
|
178
|
+
leastJsonBytes(value, max) > max ? max + 1 : encoder.encode(JSON.stringify(value)).length;
|
|
139
179
|
|
|
140
180
|
/** A document's data: a plain object, within the limits; "too_large" past them. */
|
|
141
181
|
function dbData(
|
|
@@ -151,7 +191,9 @@ function dbData(
|
|
|
151
191
|
if (!plainJson(value, budget, 0)) {
|
|
152
192
|
return null;
|
|
153
193
|
}
|
|
154
|
-
return jsonBytes(value) > DB_LIMITS.maxDocBytes
|
|
194
|
+
return jsonBytes(value, DB_LIMITS.maxDocBytes) > DB_LIMITS.maxDocBytes
|
|
195
|
+
? "too_large"
|
|
196
|
+
: (value as DbData);
|
|
155
197
|
}
|
|
156
198
|
|
|
157
199
|
const version = (value: unknown): number | null | undefined =>
|
|
@@ -272,7 +314,7 @@ function parseWhere(value: unknown): readonly DbWhere[] | undefined | null {
|
|
|
272
314
|
field.length > 256 ||
|
|
273
315
|
!(WHERE_OPS as readonly unknown[]).includes(op) ||
|
|
274
316
|
!isPlainJson(operand, DB_LIMITS.maxOperandNodes) ||
|
|
275
|
-
jsonBytes(operand) > DB_LIMITS.maxOperandBytes ||
|
|
317
|
+
jsonBytes(operand, DB_LIMITS.maxOperandBytes) > DB_LIMITS.maxOperandBytes ||
|
|
276
318
|
(op === "in" && (!Array.isArray(operand) || operand.length > DB_LIMITS.maxIn))
|
|
277
319
|
) {
|
|
278
320
|
return null;
|
|
@@ -364,7 +406,7 @@ export function parseDbRequest(args: unknown): Parsed<DbRequest> {
|
|
|
364
406
|
paths.add(write.path);
|
|
365
407
|
parsed.push(write);
|
|
366
408
|
}
|
|
367
|
-
if (jsonBytes(parsed) > DB_LIMITS.maxBatchBytes) {
|
|
409
|
+
if (jsonBytes(parsed, DB_LIMITS.maxBatchBytes) > DB_LIMITS.maxBatchBytes) {
|
|
368
410
|
return "too_large";
|
|
369
411
|
}
|
|
370
412
|
return { op: "batch", writes: parsed };
|
|
@@ -379,23 +421,108 @@ export function parseDbRequest(args: unknown): Parsed<DbRequest> {
|
|
|
379
421
|
* the least level that may read and write it. They only raise the contract's (read: view, write:
|
|
380
422
|
* interact); the host evaluates them again on its side (`dbAccess`).
|
|
381
423
|
*/
|
|
382
|
-
export type DbRules = Readonly<
|
|
383
|
-
|
|
384
|
-
|
|
424
|
+
export type DbRules = Readonly<Record<string, DbRule>>;
|
|
425
|
+
|
|
426
|
+
/** One collection's rule: the least level that may read it, and write it (absent: the contract's). */
|
|
427
|
+
export interface DbRule {
|
|
428
|
+
readonly read?: ViewerLevel;
|
|
429
|
+
readonly write?: ViewerLevel;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* The most collections a page's rules name (P086). At publish, `DB_MAX_RULES`; where a
|
|
434
|
+
* declaration is shown (a mount, `intersectDeclarations`), an intersection of two: twice that, and
|
|
435
|
+
* `*` (P093, after its review).
|
|
436
|
+
*/
|
|
437
|
+
export const DB_MAX_RULES = 100;
|
|
438
|
+
export const DB_MAX_SHOWN_RULES = 2 * DB_MAX_RULES + 1;
|
|
385
439
|
|
|
386
|
-
/**
|
|
387
|
-
export
|
|
440
|
+
/** Where a declaration is checked: at publish, or where it is shown (a mount, an intersection). */
|
|
441
|
+
export type DeclarationStage = "publish" | "shown";
|
|
442
|
+
|
|
443
|
+
/** A collection's name, ASCII case folded: a store that folds case keeps `Votes` where `votes` is. */
|
|
444
|
+
export const foldCollection = (name: string): string =>
|
|
445
|
+
name.replace(/[A-Z]+/gu, (run) => run.toLowerCase());
|
|
446
|
+
|
|
447
|
+
/** The level a rule asks to read or write (absent: the contract's, read view and write interact). */
|
|
448
|
+
export function dbRuleLevel(rule: DbRule | undefined, write: boolean): ViewerLevel {
|
|
449
|
+
const base: ViewerLevel = write ? "interact" : "view";
|
|
450
|
+
const asked = write ? rule?.write : rule?.read;
|
|
451
|
+
return asked === undefined ? base : higher(base, asked);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The stricter of two rules, read and write each (absent: the contract's level). */
|
|
455
|
+
export function stricterDbRule(x: DbRule | undefined, y: DbRule | undefined): DbRule {
|
|
456
|
+
const out = Object.create(null) as { read?: ViewerLevel; write?: ViewerLevel };
|
|
457
|
+
for (const field of ["read", "write"] as const) {
|
|
458
|
+
const p = x?.[field];
|
|
459
|
+
const q = y?.[field];
|
|
460
|
+
const level = p === undefined ? q : q === undefined ? p : higher(p, q);
|
|
461
|
+
if (level !== undefined) {
|
|
462
|
+
out[field] = level;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return out;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* The rule a top-level collection is under (P086, P093): the rule object the rules give its exact
|
|
470
|
+
* name, else `*`'s, whole; never field by field (a collection's `{}` is the contract's levels,
|
|
471
|
+
* whatever `*` says). Then made stricter by every rule that names it in another ASCII case (a
|
|
472
|
+
* store that folds case keeps `Votes` where `votes` is): never looser than the exact name's
|
|
473
|
+
* lookup, and the same where nothing names it in another case. Own names only: a collection
|
|
474
|
+
* named `constructor` or `__proto__` is no rule unless the rules name it (P091). `dbAccess` and
|
|
475
|
+
* `intersectDeclarations` both read rules through this.
|
|
476
|
+
*/
|
|
477
|
+
export function dbRuleOf(rules: DbRules | undefined, collection: string): DbRule | undefined {
|
|
478
|
+
if (rules === undefined) {
|
|
479
|
+
return undefined;
|
|
480
|
+
}
|
|
481
|
+
const own = (key: string) => (Object.hasOwn(rules, key) ? rules[key] : undefined);
|
|
482
|
+
// After the re-review: `*` counts whenever the exact name is absent, variants or not.
|
|
483
|
+
let rule = own(collection) ?? own("*");
|
|
484
|
+
if (collection === "*") {
|
|
485
|
+
return rule;
|
|
486
|
+
}
|
|
487
|
+
const folded = foldCollection(collection);
|
|
488
|
+
for (const name of Object.keys(rules)) {
|
|
489
|
+
const each = rules[name];
|
|
490
|
+
if (
|
|
491
|
+
name !== "*" &&
|
|
492
|
+
name !== collection &&
|
|
493
|
+
typeof each === "object" &&
|
|
494
|
+
foldCollection(name) === folded
|
|
495
|
+
) {
|
|
496
|
+
rule = stricterDbRule(rule, each);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return rule;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* A rules object's problem, or null. At publish (the default) at most `DB_MAX_RULES` names, none
|
|
504
|
+
* two that differ only in case (P093); where shown, an intersection's `DB_MAX_SHOWN_RULES`, and
|
|
505
|
+
* names in more than one case as a page from before P093 may have them.
|
|
506
|
+
*/
|
|
507
|
+
export function dbRulesProblem(value: unknown, stage: DeclarationStage = "publish"): string | null {
|
|
388
508
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
389
509
|
return "must be an object of { read?, write } levels by collection";
|
|
390
510
|
}
|
|
391
511
|
const entries = Object.entries(value as Record<string, unknown>);
|
|
392
|
-
|
|
393
|
-
|
|
512
|
+
const most = stage === "publish" ? DB_MAX_RULES : DB_MAX_SHOWN_RULES;
|
|
513
|
+
if (entries.length > most) {
|
|
514
|
+
return `may name at most ${most} collections`;
|
|
394
515
|
}
|
|
516
|
+
const folded = new Map<string, string>();
|
|
395
517
|
for (const [collection, rule] of entries) {
|
|
396
518
|
if (collection !== "*" && !SEGMENT.test(collection)) {
|
|
397
519
|
return `${JSON.stringify(collection)} is not a collection name (or "*")`;
|
|
398
520
|
}
|
|
521
|
+
const other = folded.get(foldCollection(collection));
|
|
522
|
+
if (stage === "publish" && other !== undefined) {
|
|
523
|
+
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)`;
|
|
524
|
+
}
|
|
525
|
+
folded.set(foldCollection(collection), collection);
|
|
399
526
|
if (rule === null || typeof rule !== "object" || Array.isArray(rule)) {
|
|
400
527
|
return `${collection}: must be { read?, write? }`;
|
|
401
528
|
}
|
|
@@ -451,14 +578,7 @@ function ownPath(path: string, viewer: ViewerInfo | undefined): string | null {
|
|
|
451
578
|
|
|
452
579
|
/** The least level a rule asks for `path`. */
|
|
453
580
|
function ruleLevel(rules: DbRules | undefined, path: string, write: boolean): ViewerLevel {
|
|
454
|
-
|
|
455
|
-
const top = path.split("/")[0] ?? "";
|
|
456
|
-
// Own rules only: a collection named `constructor` or `__proto__` is no rule (after the review).
|
|
457
|
-
const own = (key: string) =>
|
|
458
|
-
rules !== undefined && Object.hasOwn(rules, key) ? rules[key] : undefined;
|
|
459
|
-
const rule = own(top) ?? own("*");
|
|
460
|
-
const asked = write ? rule?.write : rule?.read;
|
|
461
|
-
return asked === undefined ? base : higher(base, asked);
|
|
581
|
+
return dbRuleLevel(dbRuleOf(rules, path.split("/")[0] ?? ""), write);
|
|
462
582
|
}
|
|
463
583
|
|
|
464
584
|
/**
|