@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
package/src/daemon.js
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Type API client: what a type server started by the daemon calls back
|
|
3
|
+
* (`/api/open-artifacts.type.*`, Bearer `OPEN_ARTIFACTS_TYPE_TOKEN`).
|
|
4
|
+
*
|
|
5
|
+
* It reads `OPEN_ARTIFACTS_DAEMON_URL` and `OPEN_ARTIFACTS_TYPE_TOKEN`. A server without them
|
|
6
|
+
* (started by hand, or remote) gets a client whose calls fail with
|
|
7
|
+
* `no_daemon`; its pages simply cannot wake the agent.
|
|
8
|
+
*/
|
|
9
|
+
import { OpenArtifactsError, SAMPLE_STREAM_CONTENT_TYPE, TYPE_API_ROUTES, adoptLegacyEnvNames, fetchCurrentOrLegacy, readSse, } from '@openartifactsai/protocol';
|
|
10
|
+
// A daemon from before the rename starts type servers with `OPEN_ARTIFACT_*` only: read as the new names everywhere
|
|
11
|
+
// in this process (only names not set are added).
|
|
12
|
+
adoptLegacyEnvNames(process.env);
|
|
13
|
+
/** The `OPEN_ARTIFACTS_*` variable names of {@link TypeServerEnv}. */
|
|
14
|
+
const ENV_KEYS = ['OPEN_ARTIFACTS_PROTOCOL', 'OPEN_ARTIFACTS_TYPE', 'OPEN_ARTIFACTS_TYPE_DIR', 'OPEN_ARTIFACTS_PORT', 'OPEN_ARTIFACTS_SECRET', 'OPEN_ARTIFACTS_DAEMON_URL', 'OPEN_ARTIFACTS_TYPE_TOKEN', 'OPEN_ARTIFACTS_STATE_DIR'];
|
|
15
|
+
/**
|
|
16
|
+
* The `OPEN_ARTIFACTS_*` variables the daemon passed, without empty ones. Every field is
|
|
17
|
+
* missing when the server was started by hand.
|
|
18
|
+
*/
|
|
19
|
+
export function typeServerEnv(env = process.env) {
|
|
20
|
+
const out = {};
|
|
21
|
+
const named = adoptLegacyEnvNames({ ...env });
|
|
22
|
+
for (const key of ENV_KEYS) {
|
|
23
|
+
const value = named[key];
|
|
24
|
+
if (value)
|
|
25
|
+
out[key] = value;
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
/** A failed `type.mcp.call`: the connector's code, and whether trying again may help. */
|
|
30
|
+
export class TypeApiMcpError extends OpenArtifactsError {
|
|
31
|
+
retryable;
|
|
32
|
+
constructor(code, message, retryable, status) {
|
|
33
|
+
super(code, message, status === undefined ? {} : { status });
|
|
34
|
+
this.retryable = retryable;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** The Type API client. */
|
|
38
|
+
export class TypeApi {
|
|
39
|
+
/** Base URL of the daemon without a trailing slash, or `null` when standalone. */
|
|
40
|
+
url;
|
|
41
|
+
/** Bearer token, or `null` when standalone. */
|
|
42
|
+
token;
|
|
43
|
+
/** Per-request timeout, ms. */
|
|
44
|
+
timeoutMs;
|
|
45
|
+
/** Whether the daemon is from before the rename (answers `/api/open-artifact.type.*` only); learned on the first 404. */
|
|
46
|
+
names = {};
|
|
47
|
+
/** Reads the daemon address and token from `options`, else from the environment. */
|
|
48
|
+
constructor(options = {}) {
|
|
49
|
+
const url = options.url === undefined ? process.env.OPEN_ARTIFACTS_DAEMON_URL : options.url;
|
|
50
|
+
const token = options.token === undefined ? process.env.OPEN_ARTIFACTS_TYPE_TOKEN : options.token;
|
|
51
|
+
this.url = url ? url.replace(/\/+$/, '') : null;
|
|
52
|
+
this.token = token || null;
|
|
53
|
+
this.timeoutMs = options.timeoutMs ?? 15_000;
|
|
54
|
+
}
|
|
55
|
+
/** A Type API request: the new path first, the older one when a daemon from before the rename answers 404. */
|
|
56
|
+
fetchApi(url, init) {
|
|
57
|
+
return fetchCurrentOrLegacy(fetch, url, init, this.names);
|
|
58
|
+
}
|
|
59
|
+
/** True when the server was started by a daemon and can call it. */
|
|
60
|
+
get available() {
|
|
61
|
+
return !!(this.url && this.token);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Calls `open-artifacts.type.<name>`: `GET` with `query`, or `POST` with `body`.
|
|
65
|
+
* Throws an {@link OpenArtifactsError} (`no_daemon`, `daemon_failed`, or the daemon's
|
|
66
|
+
* own code) on failure.
|
|
67
|
+
*/
|
|
68
|
+
async call(name, init = {}) {
|
|
69
|
+
if (!this.available) {
|
|
70
|
+
throw new OpenArtifactsError('no_daemon', 'This server was not started by an Open Artifacts daemon (no OPEN_ARTIFACTS_DAEMON_URL / OPEN_ARTIFACTS_TYPE_TOKEN).');
|
|
71
|
+
}
|
|
72
|
+
const url = new URL(`${this.url}/api/open-artifacts.type.${name}`);
|
|
73
|
+
for (const [key, value] of Object.entries(init.query ?? {}))
|
|
74
|
+
url.searchParams.set(key, String(value));
|
|
75
|
+
const post = init.body !== undefined;
|
|
76
|
+
let response;
|
|
77
|
+
try {
|
|
78
|
+
response = await this.fetchApi(url.href, {
|
|
79
|
+
method: post ? 'POST' : 'GET',
|
|
80
|
+
headers: { authorization: `Bearer ${this.token}`, ...(post ? { 'content-type': 'application/json' } : {}) },
|
|
81
|
+
...(post ? { body: JSON.stringify(init.body) } : {}),
|
|
82
|
+
signal: AbortSignal.timeout(init.timeoutMs ?? this.timeoutMs),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
throw new OpenArtifactsError('daemon_failed', `The Open Artifacts daemon did not answer (${error instanceof Error ? error.message : String(error)}).`);
|
|
87
|
+
}
|
|
88
|
+
const out = (await response.json().catch(() => ({})));
|
|
89
|
+
if (!response.ok) {
|
|
90
|
+
throw new OpenArtifactsError(typeof out.code === 'string' ? out.code : 'daemon_failed', typeof out.message === 'string' ? out.message : `open-artifacts.type.${name}: HTTP ${response.status}`, typeof out.fix === 'string' ? { fix: out.fix } : {});
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
/** The daemon's record of an artifact. */
|
|
95
|
+
artifact(id) {
|
|
96
|
+
return this.call(TYPE_API_ROUTES.artifact, { query: { id } });
|
|
97
|
+
}
|
|
98
|
+
/** Hands comment threads and page requests to the owner's session. */
|
|
99
|
+
wake(id, { threads, requests, stage } = {}) {
|
|
100
|
+
const body = { id, ...(threads ? { threads } : {}), ...(requests ? { requests } : {}), ...(stage ? { stage: true } : {}) };
|
|
101
|
+
return this.call(TYPE_API_ROUTES.wake, { body });
|
|
102
|
+
}
|
|
103
|
+
/** Reports that the agent's work on the artifact stopped: nothing was written to it for a while. */
|
|
104
|
+
quiet(id) {
|
|
105
|
+
return this.call(TYPE_API_ROUTES.quiet, { body: { id } });
|
|
106
|
+
}
|
|
107
|
+
/** Whether an agent is there to receive, and whether it is busy. */
|
|
108
|
+
presence(id) {
|
|
109
|
+
return this.call(TYPE_API_ROUTES.presence, { query: { id } });
|
|
110
|
+
}
|
|
111
|
+
/** Reports a write: `author` is a viewer name, `guest:<name>` or `agent`. */
|
|
112
|
+
touch(id, { author, paths, title }) {
|
|
113
|
+
const body = { id, author, paths, ...(title ? { title } : {}) };
|
|
114
|
+
return this.call(TYPE_API_ROUTES.touch, { body });
|
|
115
|
+
}
|
|
116
|
+
/** Reports that the owner's view context of an artifact changed (`at`: when, ISO); the daemon tells adapters. */
|
|
117
|
+
context(id, at) {
|
|
118
|
+
return this.call(TYPE_API_ROUTES.context, { body: { id, at } });
|
|
119
|
+
}
|
|
120
|
+
/** Reports progress or the end of a long action. */
|
|
121
|
+
task(task, report = {}) {
|
|
122
|
+
const body = { task, ...report };
|
|
123
|
+
return this.call(TYPE_API_ROUTES.task, { body });
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Starts one `sample` call (`open-artifacts.type.sample`): resolves with the answer's NDJSON body (one
|
|
127
|
+
* `SampleStreamEvent` per line, open until `done` or `error`) once the daemon answered 200. No timeout of its own:
|
|
128
|
+
* the daemon ends an over-long call; aborting `signal` cancels it. Throws an {@link OpenArtifactsError} when the call
|
|
129
|
+
* could not be started (`no_daemon`, `daemon_failed`, or the daemon's own code).
|
|
130
|
+
*/
|
|
131
|
+
async sampleStream(body, signal) {
|
|
132
|
+
if (!this.available)
|
|
133
|
+
throw new OpenArtifactsError('no_daemon', 'This server was not started by an Open Artifacts daemon.');
|
|
134
|
+
let response;
|
|
135
|
+
try {
|
|
136
|
+
response = await this.fetchApi(`${this.url}/api/open-artifacts.type.${TYPE_API_ROUTES.sample}`, {
|
|
137
|
+
method: 'POST',
|
|
138
|
+
headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json', accept: SAMPLE_STREAM_CONTENT_TYPE },
|
|
139
|
+
body: JSON.stringify(body),
|
|
140
|
+
signal,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
throw new OpenArtifactsError('daemon_failed', `The Open Artifacts daemon did not answer (${error instanceof Error ? error.message : String(error)}).`);
|
|
145
|
+
}
|
|
146
|
+
if (!response.ok || !response.body) {
|
|
147
|
+
const out = (await response.json().catch(() => ({})));
|
|
148
|
+
throw new OpenArtifactsError(typeof out.code === 'string' ? out.code : 'daemon_failed', typeof out.message === 'string' ? out.message : `open-artifacts.type.${TYPE_API_ROUTES.sample}: HTTP ${response.status}`);
|
|
149
|
+
}
|
|
150
|
+
const reader = response.body.getReader();
|
|
151
|
+
return (async function* chunks() {
|
|
152
|
+
try {
|
|
153
|
+
for (;;) {
|
|
154
|
+
const { value, done } = await reader.read();
|
|
155
|
+
if (done)
|
|
156
|
+
return;
|
|
157
|
+
yield value;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
// Ended early (the relay stopped after the last event, or the inner shell went away): drop the rest.
|
|
162
|
+
reader.cancel().catch(() => { });
|
|
163
|
+
}
|
|
164
|
+
})();
|
|
165
|
+
}
|
|
166
|
+
/** Hands back one round's tool results of a running `sample` call. */
|
|
167
|
+
sampleTool(body) {
|
|
168
|
+
return this.call(TYPE_API_ROUTES.sampleTool, { body });
|
|
169
|
+
}
|
|
170
|
+
/** A view's `sample` limits. */
|
|
171
|
+
sampleLimits(query) {
|
|
172
|
+
return this.call(TYPE_API_ROUTES.sampleLimits, { query: { ...query } });
|
|
173
|
+
}
|
|
174
|
+
/** The daemon's connectors and their tools (all, or `server`), for this type's own editor. */
|
|
175
|
+
mcpTools(server) {
|
|
176
|
+
return this.call(TYPE_API_ROUTES.mcpTools, { ...(server === undefined ? {} : { query: { server } }), timeoutMs: 60_000 });
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* One tool call of this type's own editor on the daemon's connectors. Rejects with an {@link OpenArtifactsError}
|
|
180
|
+
* ({@link TypeApiMcpError}) whose `code` is the connector's (`server_not_connected`, `needs_reauth`,
|
|
181
|
+
* `upstream_error`, ...). Aborting `signal` cancels it on the connector.
|
|
182
|
+
*/
|
|
183
|
+
async mcpCall(body, signal) {
|
|
184
|
+
if (!this.available)
|
|
185
|
+
throw new OpenArtifactsError('no_daemon', 'This server was not started by an Open Artifacts daemon.');
|
|
186
|
+
let response;
|
|
187
|
+
try {
|
|
188
|
+
response = await this.fetchApi(`${this.url}/api/open-artifacts.type.${TYPE_API_ROUTES.mcpCall}`, {
|
|
189
|
+
method: 'POST',
|
|
190
|
+
headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json' },
|
|
191
|
+
body: JSON.stringify(body),
|
|
192
|
+
...(signal ? { signal } : {}),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (signal?.aborted)
|
|
197
|
+
throw signal.reason;
|
|
198
|
+
throw new OpenArtifactsError('daemon_failed', `The Open Artifacts daemon did not answer (${error instanceof Error ? error.message : String(error)}).`);
|
|
199
|
+
}
|
|
200
|
+
const out = (await response.json().catch(() => ({})));
|
|
201
|
+
if (!response.ok) {
|
|
202
|
+
throw new TypeApiMcpError(typeof out.code === 'string' ? out.code : 'daemon_failed', typeof out.message === 'string' ? out.message : `open-artifacts.type.${TYPE_API_ROUTES.mcpCall}: HTTP ${response.status}`, out.retryable === true, response.status);
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* A page's `mcp` call, as the daemon answers it: NDJSON `McpStreamEvent`s (page-mcp.ts) until `done` or `error`.
|
|
208
|
+
* Aborting `signal` cancels the call.
|
|
209
|
+
*/
|
|
210
|
+
async mcpPageStream(body, signal) {
|
|
211
|
+
if (!this.available)
|
|
212
|
+
throw new OpenArtifactsError('no_daemon', 'This server was not started by an Open Artifacts daemon.');
|
|
213
|
+
let response;
|
|
214
|
+
try {
|
|
215
|
+
response = await this.fetchApi(`${this.url}/api/open-artifacts.type.${TYPE_API_ROUTES.mcpPageCall}`, {
|
|
216
|
+
method: 'POST',
|
|
217
|
+
headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json', accept: SAMPLE_STREAM_CONTENT_TYPE },
|
|
218
|
+
body: JSON.stringify(body),
|
|
219
|
+
signal,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
throw new OpenArtifactsError('daemon_failed', `The Open Artifacts daemon did not answer (${error instanceof Error ? error.message : String(error)}).`);
|
|
224
|
+
}
|
|
225
|
+
if (!response.ok || !response.body) {
|
|
226
|
+
const out = (await response.json().catch(() => ({})));
|
|
227
|
+
throw new OpenArtifactsError(typeof out.code === 'string' ? out.code : 'daemon_failed', typeof out.message === 'string' ? out.message : `open-artifacts.type.${TYPE_API_ROUTES.mcpPageCall}: HTTP ${response.status}`);
|
|
228
|
+
}
|
|
229
|
+
const reader = response.body.getReader();
|
|
230
|
+
return (async function* chunks() {
|
|
231
|
+
try {
|
|
232
|
+
for (;;) {
|
|
233
|
+
const { value, done } = await reader.read();
|
|
234
|
+
if (done)
|
|
235
|
+
return;
|
|
236
|
+
yield value;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
reader.cancel().catch(() => { });
|
|
241
|
+
}
|
|
242
|
+
})();
|
|
243
|
+
}
|
|
244
|
+
/** A page's `mcp.listTools`: its declared connectors and tools, as much as the person allowed it to see. */
|
|
245
|
+
mcpPageTools(body) {
|
|
246
|
+
return this.call(TYPE_API_ROUTES.mcpPageTools, { body, timeoutMs: 60_000 });
|
|
247
|
+
}
|
|
248
|
+
/** A page's `mcp.describeTool`. */
|
|
249
|
+
mcpPageDescribe(body) {
|
|
250
|
+
return this.call(TYPE_API_ROUTES.mcpPageDescribe, { body, timeoutMs: 60_000 });
|
|
251
|
+
}
|
|
252
|
+
/** Whether each declared connector of a page is allowed (`permissions.state("mcp:<server>")`), never asking. */
|
|
253
|
+
mcpPageState(id, view) {
|
|
254
|
+
return this.call(TYPE_API_ROUTES.mcpPageState, { query: { id, view } });
|
|
255
|
+
}
|
|
256
|
+
/** Whether the person's grants already cover artifact `id`'s `sample` calls (no consent dialog would open). */
|
|
257
|
+
sampleState(id) {
|
|
258
|
+
return this.call(TYPE_API_ROUTES.sampleState, { query: { id } });
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Follows presence and artifact events of some artifacts (server-sent
|
|
262
|
+
* events). Calls `onEvent` for each one and reconnects after a drop until
|
|
263
|
+
* the returned function is called. Does nothing when standalone.
|
|
264
|
+
*/
|
|
265
|
+
events(ids, onEvent) {
|
|
266
|
+
let stopped = false;
|
|
267
|
+
let controller = null;
|
|
268
|
+
const run = async () => {
|
|
269
|
+
while (!stopped) {
|
|
270
|
+
controller = new AbortController();
|
|
271
|
+
try {
|
|
272
|
+
const url = `${this.url}/api/open-artifacts.type.${TYPE_API_ROUTES.events}?ids=${encodeURIComponent(ids.join(','))}`;
|
|
273
|
+
const response = await this.fetchApi(url, { headers: { authorization: `Bearer ${this.token}` }, signal: controller.signal });
|
|
274
|
+
if (!response.ok || !response.body)
|
|
275
|
+
throw new Error(`HTTP ${response.status}`);
|
|
276
|
+
for await (const { data } of readSse(response.body)) {
|
|
277
|
+
if (!data)
|
|
278
|
+
continue;
|
|
279
|
+
try {
|
|
280
|
+
onEvent(JSON.parse(data));
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
// A listener's error is its own.
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// Dropped or refused: try again.
|
|
289
|
+
}
|
|
290
|
+
if (!stopped)
|
|
291
|
+
await new Promise((done) => setTimeout(done, 2000).unref());
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
if (this.available)
|
|
295
|
+
void run();
|
|
296
|
+
return () => {
|
|
297
|
+
stopped = true;
|
|
298
|
+
controller?.abort();
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may do what in a frame artifact: the viewer levels and the declaration's access settings, as pure functions the
|
|
3
|
+
* core (core.ts) calls on every request. No I/O and no imports beyond types, so a test can run every level against
|
|
4
|
+
* every rule kind (test/frame-levels.test.ts).
|
|
5
|
+
*
|
|
6
|
+
* The semantics are the Frame Runtime contract's (0.2.92):
|
|
7
|
+
*
|
|
8
|
+
* - Levels, lowest first: `view` (reads), `interact` (also writes shared data), `admin` (also publishes files and
|
|
9
|
+
* assets), `owner` (the artifact's own owner). `self` is a fifth word for db rules that nobody holds, not even the
|
|
10
|
+
* owner: it only ever opens a viewer's own `{self}` subtree.
|
|
11
|
+
* - `db` rules (`capabilities.db.rules`: `[{path, read?, write?}]`): a rule applies to its path and everything below,
|
|
12
|
+
* a deeper rule overrides it there, an unset level inherits from the nearest rule above, and the root defaults to
|
|
13
|
+
* `read: "view", write: "interact"`. A path ending in `/{self}` names each viewer's own subtree under that prefix:
|
|
14
|
+
* on one's own subtree the better of the prefix rule and the `{self}` rule applies; on someone else's only the
|
|
15
|
+
* prefix rule does, and with no rule declared AT the prefix that subtree is private (nobody else reads or writes
|
|
16
|
+
* it, the owner included). `data/users/{self}` is always there, so `data/users/<id>/` is private unless a rule at
|
|
17
|
+
* `data/users` opens it, or a rule at `data` beside `data/{self}` does: `data/users` is then a sibling's subtree
|
|
18
|
+
* (the one named `users`), at the `data` rule's levels, and a {self} rule inside a subtree so opened does not make
|
|
19
|
+
* it private again (the contract: unless a version declared "a rule at `data/users`, or at `data` beside
|
|
20
|
+
* `data/{self}`, nobody else has ever reached it"). Writing implies reading: a write level is never below the read level in force.
|
|
21
|
+
* - A declaration whose rules break the contract's grammar is refused at publish there; here it fails closed: only
|
|
22
|
+
* the owner reads or writes (see {@link compileDbRules}).
|
|
23
|
+
*/
|
|
24
|
+
import type { FrameLevel } from './env.js';
|
|
25
|
+
/** A level a rule may ask for: a viewer level, or `self` (nobody holds it). */
|
|
26
|
+
export type RuleLevel = FrameLevel | 'self';
|
|
27
|
+
/** At most this many rules (the contract's limit). */
|
|
28
|
+
export declare const RULES_MAX = 64;
|
|
29
|
+
/** Whether `level` meets `min`. `self` is met by nobody. */
|
|
30
|
+
export declare function meets(level: FrameLevel, min: RuleLevel): boolean;
|
|
31
|
+
interface RuleLevels {
|
|
32
|
+
read?: RuleLevel;
|
|
33
|
+
write?: RuleLevel;
|
|
34
|
+
}
|
|
35
|
+
/** A declaration's db rules, ready to check paths against. */
|
|
36
|
+
export interface DbRules {
|
|
37
|
+
/** Rules on a plain path (`''` is the root), by path. */
|
|
38
|
+
plain: ReadonlyMap<string, RuleLevels>;
|
|
39
|
+
/** `{self}` rules, by their prefix (`votes` for `votes/{self}`); `data/users` is always one. */
|
|
40
|
+
self: ReadonlyMap<string, RuleLevels>;
|
|
41
|
+
/** Why the declared rules were refused (they then fail closed), or null. */
|
|
42
|
+
problem: string | null;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Reads `capabilities.db` (`true`, `{}` or `{rules: [...]}`). No rules: the defaults. Rules that break the contract
|
|
46
|
+
* (a bad level or path, `{self}` not last, `self` where it may not go, a prefix rule beside a `{self}` rule missing a
|
|
47
|
+
* level, a write below its read, a path twice, more than {@link RULES_MAX}) fail closed, with `problem` saying why.
|
|
48
|
+
*/
|
|
49
|
+
export declare function compileDbRules(db: unknown): DbRules;
|
|
50
|
+
/** The levels a db path asks of one viewer (`id`): to read it and to write it. `self` means nobody may. */
|
|
51
|
+
export declare function dbLevels(rules: DbRules, viewerId: string, segs: readonly string[]): {
|
|
52
|
+
read: RuleLevel;
|
|
53
|
+
write: RuleLevel;
|
|
54
|
+
};
|
|
55
|
+
/** Whether a viewer (`id`, `level`) may read / write the db path `segs` (a document's, or a collection's). */
|
|
56
|
+
export declare function dbAllows(rules: DbRules, viewer: {
|
|
57
|
+
id: string;
|
|
58
|
+
level: FrameLevel;
|
|
59
|
+
}, segs: readonly string[], action: 'read' | 'write'): boolean;
|
|
60
|
+
/** The level a room topic asks to send on: `capabilities.room.topics[topic]` when it is `interact`, else `admin`. */
|
|
61
|
+
export declare function topicLevel(room: unknown, topic: string): FrameLevel;
|
|
62
|
+
/** The level uploads ask: `admin`, or `interact` when `capabilities.assets.upload` is `"interact"`. */
|
|
63
|
+
export declare function uploadLevel(assets: unknown): FrameLevel;
|
|
64
|
+
/** The `user` scopes a declaration grants: `profile` (names, avatars, search) and `email`. */
|
|
65
|
+
export declare function userScopes(user: unknown): {
|
|
66
|
+
profile: boolean;
|
|
67
|
+
email: boolean;
|
|
68
|
+
};
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may do what in a frame artifact: the viewer levels and the declaration's access settings, as pure functions the
|
|
3
|
+
* core (core.ts) calls on every request. No I/O and no imports beyond types, so a test can run every level against
|
|
4
|
+
* every rule kind (test/frame-levels.test.ts).
|
|
5
|
+
*
|
|
6
|
+
* The semantics are the Frame Runtime contract's (0.2.92):
|
|
7
|
+
*
|
|
8
|
+
* - Levels, lowest first: `view` (reads), `interact` (also writes shared data), `admin` (also publishes files and
|
|
9
|
+
* assets), `owner` (the artifact's own owner). `self` is a fifth word for db rules that nobody holds, not even the
|
|
10
|
+
* owner: it only ever opens a viewer's own `{self}` subtree.
|
|
11
|
+
* - `db` rules (`capabilities.db.rules`: `[{path, read?, write?}]`): a rule applies to its path and everything below,
|
|
12
|
+
* a deeper rule overrides it there, an unset level inherits from the nearest rule above, and the root defaults to
|
|
13
|
+
* `read: "view", write: "interact"`. A path ending in `/{self}` names each viewer's own subtree under that prefix:
|
|
14
|
+
* on one's own subtree the better of the prefix rule and the `{self}` rule applies; on someone else's only the
|
|
15
|
+
* prefix rule does, and with no rule declared AT the prefix that subtree is private (nobody else reads or writes
|
|
16
|
+
* it, the owner included). `data/users/{self}` is always there, so `data/users/<id>/` is private unless a rule at
|
|
17
|
+
* `data/users` opens it, or a rule at `data` beside `data/{self}` does: `data/users` is then a sibling's subtree
|
|
18
|
+
* (the one named `users`), at the `data` rule's levels, and a {self} rule inside a subtree so opened does not make
|
|
19
|
+
* it private again (the contract: unless a version declared "a rule at `data/users`, or at `data` beside
|
|
20
|
+
* `data/{self}`, nobody else has ever reached it"). Writing implies reading: a write level is never below the read level in force.
|
|
21
|
+
* - A declaration whose rules break the contract's grammar is refused at publish there; here it fails closed: only
|
|
22
|
+
* the owner reads or writes (see {@link compileDbRules}).
|
|
23
|
+
*/
|
|
24
|
+
const RANK = { view: 0, interact: 1, admin: 2, owner: 3, self: 4 };
|
|
25
|
+
const RULE_LEVELS = new Set(['view', 'interact', 'admin', 'owner', 'self']);
|
|
26
|
+
/** The db path grammar's segment (as db.ts checks it). */
|
|
27
|
+
const SEGMENT = /^[A-Za-z0-9_\-.~:@+]+$/;
|
|
28
|
+
/** At most this many rules (the contract's limit). */
|
|
29
|
+
export const RULES_MAX = 64;
|
|
30
|
+
/** The prefix whose `{self}` rule is always there. */
|
|
31
|
+
const USERS = 'data/users';
|
|
32
|
+
/** Whether `level` meets `min`. `self` is met by nobody. */
|
|
33
|
+
export function meets(level, min) {
|
|
34
|
+
return min !== 'self' && RANK[level] >= RANK[min];
|
|
35
|
+
}
|
|
36
|
+
const easier = (a, b) => (RANK[a] <= RANK[b] ? a : b);
|
|
37
|
+
const harder = (a, b) => (RANK[a] >= RANK[b] ? a : b);
|
|
38
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
39
|
+
/** The rules nobody but the owner gets past: what a refused declaration falls back to. */
|
|
40
|
+
function closed(problem) {
|
|
41
|
+
return { plain: new Map([['', { read: 'owner', write: 'owner' }]]), self: new Map([[USERS, {}]]), problem };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Reads `capabilities.db` (`true`, `{}` or `{rules: [...]}`). No rules: the defaults. Rules that break the contract
|
|
45
|
+
* (a bad level or path, `{self}` not last, `self` where it may not go, a prefix rule beside a `{self}` rule missing a
|
|
46
|
+
* level, a write below its read, a path twice, more than {@link RULES_MAX}) fail closed, with `problem` saying why.
|
|
47
|
+
*/
|
|
48
|
+
export function compileDbRules(db) {
|
|
49
|
+
const rules = isObject(db) ? db.rules : undefined;
|
|
50
|
+
const plain = new Map();
|
|
51
|
+
const self = new Map();
|
|
52
|
+
if (rules === undefined || rules === null) {
|
|
53
|
+
self.set(USERS, {});
|
|
54
|
+
return { plain, self, problem: null };
|
|
55
|
+
}
|
|
56
|
+
if (!Array.isArray(rules))
|
|
57
|
+
return closed('db.rules is a list.');
|
|
58
|
+
if (rules.length > RULES_MAX)
|
|
59
|
+
return closed(`db.rules holds at most ${RULES_MAX} rules.`);
|
|
60
|
+
for (const [i, raw] of rules.entries()) {
|
|
61
|
+
if (!isObject(raw) || typeof raw.path !== 'string')
|
|
62
|
+
return closed(`db.rules[${i}] needs a path.`);
|
|
63
|
+
const path = raw.path.replace(/^\/+|\/+$/g, '');
|
|
64
|
+
const segs = path === '' ? [] : path.split('/');
|
|
65
|
+
const selfAt = segs.indexOf('{self}');
|
|
66
|
+
if (selfAt !== -1 && selfAt !== segs.length - 1)
|
|
67
|
+
return closed(`db.rules[${i}]: {self} is the last segment.`);
|
|
68
|
+
const named = selfAt === -1 ? segs : segs.slice(0, -1);
|
|
69
|
+
if (named.some((s) => !SEGMENT.test(s) || s === '.' || s === '..'))
|
|
70
|
+
return closed(`db.rules[${i}]: ${JSON.stringify(raw.path)} is not a db path.`);
|
|
71
|
+
if (selfAt === 0)
|
|
72
|
+
return closed(`db.rules[${i}]: {self} needs a prefix.`);
|
|
73
|
+
const levels = {};
|
|
74
|
+
for (const action of ['read', 'write']) {
|
|
75
|
+
const v = raw[action];
|
|
76
|
+
if (v === undefined)
|
|
77
|
+
continue;
|
|
78
|
+
if (typeof v !== 'string' || !RULE_LEVELS.has(v))
|
|
79
|
+
return closed(`db.rules[${i}].${action}: one of view, interact, admin, owner, self.`);
|
|
80
|
+
levels[action] = v;
|
|
81
|
+
}
|
|
82
|
+
if (levels.read && levels.write && RANK[levels.write] < RANK[levels.read])
|
|
83
|
+
return closed(`db.rules[${i}]: write is never below read.`);
|
|
84
|
+
if (levels.read === 'self' && levels.write !== 'self')
|
|
85
|
+
return closed(`db.rules[${i}]: read "self" goes only with write "self".`);
|
|
86
|
+
const key = named.join('/');
|
|
87
|
+
const into = selfAt === -1 ? plain : self;
|
|
88
|
+
if (into.has(key))
|
|
89
|
+
return closed(`db.rules: ${JSON.stringify(raw.path)} is there twice.`);
|
|
90
|
+
into.set(key, levels);
|
|
91
|
+
}
|
|
92
|
+
// `self` goes only on the rule AT the prefix of a declared {self} rule, and that rule then sets both levels.
|
|
93
|
+
for (const [key, levels] of plain) {
|
|
94
|
+
const usesSelf = levels.read === 'self' || levels.write === 'self';
|
|
95
|
+
if (usesSelf && (key === '' || !self.has(key)))
|
|
96
|
+
return closed(`db.rules: "self" goes only on the rule at the prefix of a {self} rule (${JSON.stringify(key)}).`);
|
|
97
|
+
if (self.has(key) && (!levels.read || !levels.write))
|
|
98
|
+
return closed(`db.rules: the rule at ${JSON.stringify(key)}, beside ${key}/{self}, sets both read and write.`);
|
|
99
|
+
}
|
|
100
|
+
for (const [key, levels] of self) {
|
|
101
|
+
if (levels.read === 'self' || levels.write === 'self')
|
|
102
|
+
return closed(`db.rules: "self" does not go on ${key}/{self} itself.`);
|
|
103
|
+
const prefix = plain.get(key);
|
|
104
|
+
if (prefix && (prefix.read === 'self' || prefix.write === 'self') && (!levels.read || !levels.write)) {
|
|
105
|
+
return closed(`db.rules: beside a prefix rule that uses "self", ${key}/{self} states both levels.`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!self.has(USERS))
|
|
109
|
+
self.set(USERS, {});
|
|
110
|
+
return { plain, self, problem: null };
|
|
111
|
+
}
|
|
112
|
+
/** The levels a db path asks of one viewer (`id`): to read it and to write it. `self` means nobody may. */
|
|
113
|
+
export function dbLevels(rules, viewerId, segs) {
|
|
114
|
+
let read = 'view';
|
|
115
|
+
let write = 'interact';
|
|
116
|
+
const root = rules.plain.get('');
|
|
117
|
+
if (root) {
|
|
118
|
+
read = root.read ?? read;
|
|
119
|
+
write = root.write ?? write;
|
|
120
|
+
}
|
|
121
|
+
// Inside someone else's subtree that a rule at its prefix opened: a {self} rule further down (the built-in
|
|
122
|
+
// `data/users/{self}` below `data/{self}`) no longer makes it private; the opened levels and plain rules go on.
|
|
123
|
+
let opened = false;
|
|
124
|
+
for (let k = 1; k <= segs.length; k++) {
|
|
125
|
+
const prefix = segs.slice(0, k - 1).join('/');
|
|
126
|
+
const own = rules.self.get(prefix);
|
|
127
|
+
if (own) {
|
|
128
|
+
if (segs[k - 1] === viewerId) {
|
|
129
|
+
// One's own subtree: whichever of the prefix's rule and the {self} rule gives more (unset: the prefix's).
|
|
130
|
+
read = easier(read, own.read ?? read);
|
|
131
|
+
write = easier(write, own.write ?? write);
|
|
132
|
+
}
|
|
133
|
+
else if (rules.plain.has(prefix)) {
|
|
134
|
+
opened = true;
|
|
135
|
+
}
|
|
136
|
+
else if (!opened) {
|
|
137
|
+
// Someone else's subtree with no rule at the prefix: private, whatever is declared below it.
|
|
138
|
+
return { read: 'self', write: 'self' };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const here = rules.plain.get(segs.slice(0, k).join('/'));
|
|
142
|
+
if (here) {
|
|
143
|
+
read = here.read ?? read;
|
|
144
|
+
write = here.write ?? write;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { read, write: harder(write, read) };
|
|
148
|
+
}
|
|
149
|
+
/** Whether a viewer (`id`, `level`) may read / write the db path `segs` (a document's, or a collection's). */
|
|
150
|
+
export function dbAllows(rules, viewer, segs, action) {
|
|
151
|
+
return meets(viewer.level, dbLevels(rules, viewer.id, segs)[action]);
|
|
152
|
+
}
|
|
153
|
+
/** The level a room topic asks to send on: `capabilities.room.topics[topic]` when it is `interact`, else `admin`. */
|
|
154
|
+
export function topicLevel(room, topic) {
|
|
155
|
+
const topics = isObject(room) && isObject(room.topics) ? room.topics : {};
|
|
156
|
+
const v = Object.prototype.hasOwnProperty.call(topics, topic) ? topics[topic] : undefined;
|
|
157
|
+
// The contract opens a topic to `interact` only; `view` (or anything else) keeps it admin-only.
|
|
158
|
+
return v === 'interact' ? 'interact' : 'admin';
|
|
159
|
+
}
|
|
160
|
+
/** The level uploads ask: `admin`, or `interact` when `capabilities.assets.upload` is `"interact"`. */
|
|
161
|
+
export function uploadLevel(assets) {
|
|
162
|
+
return isObject(assets) && assets.upload === 'interact' ? 'interact' : 'admin';
|
|
163
|
+
}
|
|
164
|
+
/** The `user` scopes a declaration grants: `profile` (names, avatars, search) and `email`. */
|
|
165
|
+
export function userScopes(user) {
|
|
166
|
+
const scopes = isObject(user) && Array.isArray(user.scopes) ? user.scopes : [];
|
|
167
|
+
return { profile: scopes.includes('profile'), email: scopes.includes('email') };
|
|
168
|
+
}
|