@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
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `snapshot` action's camera: headless Chrome over the DevTools protocol,
|
|
3
|
+
* driven with Node's own WebSocket (nothing to install). It loads a page at a
|
|
4
|
+
* given size, waits for it to draw, and returns a PNG.
|
|
5
|
+
*
|
|
6
|
+
* Chrome is `$OPEN_ARTIFACTS_CHROME`, else the usual install places; `findChrome()`
|
|
7
|
+
* answers `null` when there is none, and the action says so.
|
|
8
|
+
*
|
|
9
|
+
* Shared by the type server's `snapshot` action (`@openartifactsai/type-server`
|
|
10
|
+
* re-exports it) and frame-host's (frame/snapshot-action.ts). Node only: the
|
|
11
|
+
* frame core and a hosted site never import it.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Where those browsers install on Windows, in order of preference: Chrome before Edge, and for each, the machine-wide
|
|
15
|
+
* install under both Program Files roots (64-bit, as Edge's own installer and every ARM64 Windows put it, and (x86)),
|
|
16
|
+
* then the per-user one under LOCALAPPDATA (Chrome's installer when the user is no administrator). The roots come
|
|
17
|
+
* from the environment, so Windows on another drive is found too; C:\ stands in only when a variable is unset.
|
|
18
|
+
*/
|
|
19
|
+
export declare function windowsCandidates(env?: NodeJS.ProcessEnv): string[];
|
|
20
|
+
export declare const CANDIDATES: readonly string[];
|
|
21
|
+
/** The Chrome to run: `$OPEN_ARTIFACTS_CHROME` when set, else the first one found; `null` when there is none. */
|
|
22
|
+
export declare function findChrome(): string | null;
|
|
23
|
+
/** What to photograph. */
|
|
24
|
+
export interface SnapshotRequest {
|
|
25
|
+
url: string;
|
|
26
|
+
width: number;
|
|
27
|
+
height: number;
|
|
28
|
+
/** An expression that is truthy once the page has drawn (default: loaded and something on screen). */
|
|
29
|
+
ready?: string;
|
|
30
|
+
/** Wait this long after `ready`, for frames and fonts, ms. Default 1500. */
|
|
31
|
+
settleMs?: number;
|
|
32
|
+
/** Give up after this long, ms. Default 45 s. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
/**
|
|
35
|
+
* The `prefers-color-scheme` the page is drawn with (`Emulation.setEmulatedMedia`, every frame of the page). Default:
|
|
36
|
+
* none emulated, which headless Chrome draws as light.
|
|
37
|
+
*/
|
|
38
|
+
scheme?: 'light' | 'dark';
|
|
39
|
+
}
|
|
40
|
+
/** Loads `request.url` in a fresh headless Chrome and returns the PNG of the viewport. */
|
|
41
|
+
export declare function snapshotPage(chrome: string, request: SnapshotRequest): Promise<Buffer>;
|
package/src/snapshot.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `snapshot` action's camera: headless Chrome over the DevTools protocol,
|
|
3
|
+
* driven with Node's own WebSocket (nothing to install). It loads a page at a
|
|
4
|
+
* given size, waits for it to draw, and returns a PNG.
|
|
5
|
+
*
|
|
6
|
+
* Chrome is `$OPEN_ARTIFACTS_CHROME`, else the usual install places; `findChrome()`
|
|
7
|
+
* answers `null` when there is none, and the action says so.
|
|
8
|
+
*
|
|
9
|
+
* Shared by the type server's `snapshot` action (`@openartifactsai/type-server`
|
|
10
|
+
* re-exports it) and frame-host's (frame/snapshot-action.ts). Node only: the
|
|
11
|
+
* frame core and a hosted site never import it.
|
|
12
|
+
*/
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs';
|
|
15
|
+
import { tmpdir } from 'node:os';
|
|
16
|
+
import { join, win32 } from 'node:path';
|
|
17
|
+
import { stopChild } from "./child.js";
|
|
18
|
+
/** Chromium browsers on Windows, each as its folder under a Program Files root (or under LOCALAPPDATA) and its program. */
|
|
19
|
+
const WINDOWS_BROWSERS = [
|
|
20
|
+
['Google\\Chrome\\Application', 'chrome.exe'],
|
|
21
|
+
['Microsoft\\Edge\\Application', 'msedge.exe'],
|
|
22
|
+
];
|
|
23
|
+
/**
|
|
24
|
+
* Where those browsers install on Windows, in order of preference: Chrome before Edge, and for each, the machine-wide
|
|
25
|
+
* install under both Program Files roots (64-bit, as Edge's own installer and every ARM64 Windows put it, and (x86)),
|
|
26
|
+
* then the per-user one under LOCALAPPDATA (Chrome's installer when the user is no administrator). The roots come
|
|
27
|
+
* from the environment, so Windows on another drive is found too; C:\ stands in only when a variable is unset.
|
|
28
|
+
*/
|
|
29
|
+
export function windowsCandidates(env = process.env) {
|
|
30
|
+
const roots = [
|
|
31
|
+
env.ProgramW6432,
|
|
32
|
+
env.ProgramFiles,
|
|
33
|
+
env['ProgramFiles(x86)'],
|
|
34
|
+
'C:\\Program Files',
|
|
35
|
+
'C:\\Program Files (x86)',
|
|
36
|
+
env.LOCALAPPDATA,
|
|
37
|
+
].filter((root) => !!root);
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
const paths = [];
|
|
40
|
+
for (const [folder, program] of WINDOWS_BROWSERS) {
|
|
41
|
+
for (const root of roots) {
|
|
42
|
+
const path = win32.join(root, folder, program);
|
|
43
|
+
// Windows paths ignore case, and ProgramW6432 is ProgramFiles in a 64-bit process.
|
|
44
|
+
if (seen.has(path.toLowerCase()))
|
|
45
|
+
continue;
|
|
46
|
+
seen.add(path.toLowerCase());
|
|
47
|
+
paths.push(path);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return paths;
|
|
51
|
+
}
|
|
52
|
+
export const CANDIDATES = [
|
|
53
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
54
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
55
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
56
|
+
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
|
57
|
+
'/usr/bin/google-chrome',
|
|
58
|
+
'/usr/bin/google-chrome-stable',
|
|
59
|
+
'/usr/bin/chromium',
|
|
60
|
+
'/usr/bin/chromium-browser',
|
|
61
|
+
'/usr/bin/microsoft-edge',
|
|
62
|
+
...windowsCandidates(),
|
|
63
|
+
];
|
|
64
|
+
/** The Chrome to run: `$OPEN_ARTIFACTS_CHROME` when set, else the first one found; `null` when there is none. */
|
|
65
|
+
export function findChrome() {
|
|
66
|
+
const given = process.env.OPEN_ARTIFACTS_CHROME;
|
|
67
|
+
if (given)
|
|
68
|
+
return existsSync(given) ? given : null;
|
|
69
|
+
return CANDIDATES.find((path) => existsSync(path)) ?? null;
|
|
70
|
+
}
|
|
71
|
+
const DEFAULT_READY = "document.readyState === 'complete' && !!document.body && (document.body.innerText.trim().length > 0 || document.querySelector('img,canvas,svg,iframe,video') !== null)";
|
|
72
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
73
|
+
/**
|
|
74
|
+
* How long to wait for Chrome to print its DevTools address. A cold start on a loaded CI runner can take 20 s or more
|
|
75
|
+
* (the Linux runner also logs a D-Bus warning while it starts), so 20 s failed intermittently. A real failure still
|
|
76
|
+
* shows up: a Chrome that exits is reported at once, and the whole picture stays under the 45 s budget.
|
|
77
|
+
*/
|
|
78
|
+
const CHROME_START_MS = 40_000;
|
|
79
|
+
/** Loads `request.url` in a fresh headless Chrome and returns the PNG of the viewport. */
|
|
80
|
+
export async function snapshotPage(chrome, request) {
|
|
81
|
+
const profile = mkdtempSync(join(tmpdir(), 'open-artifacts-snapshot-'));
|
|
82
|
+
const stderr = join(profile, 'chrome-stderr.log');
|
|
83
|
+
const fd = openSync(stderr, 'a');
|
|
84
|
+
const child = spawn(chrome, [
|
|
85
|
+
'--headless=new',
|
|
86
|
+
'--remote-debugging-port=0',
|
|
87
|
+
`--user-data-dir=${profile}`,
|
|
88
|
+
// Keep this temporary profile independent of the macOS login keychain.
|
|
89
|
+
...(process.platform === 'darwin' ? ['--use-mock-keychain'] : []),
|
|
90
|
+
`--window-size=${request.width},${request.height}`,
|
|
91
|
+
'--hide-scrollbars',
|
|
92
|
+
'--no-first-run',
|
|
93
|
+
'--no-default-browser-check',
|
|
94
|
+
'--disable-extensions',
|
|
95
|
+
'--disable-background-networking',
|
|
96
|
+
'--disable-sync',
|
|
97
|
+
'--disable-component-update',
|
|
98
|
+
'--mute-audio',
|
|
99
|
+
'about:blank',
|
|
100
|
+
], { stdio: ['ignore', 'ignore', fd] });
|
|
101
|
+
closeSync(fd);
|
|
102
|
+
let ws = null;
|
|
103
|
+
let timer;
|
|
104
|
+
const removeProfile = () => {
|
|
105
|
+
try {
|
|
106
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const cleanup = async () => {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
try {
|
|
116
|
+
ws?.close();
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
/* already closed */
|
|
120
|
+
}
|
|
121
|
+
// Chrome's helper processes can still be writing into the profile just after the browser is killed: wait for it
|
|
122
|
+
// to exit before removing the folder, and never fail a picture already taken over a temporary folder.
|
|
123
|
+
await stopChild(child, { graceMs: 0, settleMs: 3000 });
|
|
124
|
+
if (!removeProfile())
|
|
125
|
+
setTimeout(removeProfile, 2000).unref();
|
|
126
|
+
};
|
|
127
|
+
const work = async () => {
|
|
128
|
+
const endpoint = await new Promise((resolveEndpoint, reject) => {
|
|
129
|
+
const started = Date.now();
|
|
130
|
+
const poll = setInterval(() => {
|
|
131
|
+
let text = '';
|
|
132
|
+
try {
|
|
133
|
+
text = readFileSync(stderr, 'utf8');
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* not written yet */
|
|
137
|
+
}
|
|
138
|
+
const found = /DevTools listening on (ws:\/\/\S+)/.exec(text);
|
|
139
|
+
if (found) {
|
|
140
|
+
clearInterval(poll);
|
|
141
|
+
resolveEndpoint(found[1]);
|
|
142
|
+
}
|
|
143
|
+
else if (child.exitCode !== null || Date.now() - started > CHROME_START_MS) {
|
|
144
|
+
clearInterval(poll);
|
|
145
|
+
reject(new Error(`Chrome did not start: ${text.slice(-300)}`));
|
|
146
|
+
}
|
|
147
|
+
}, 50);
|
|
148
|
+
});
|
|
149
|
+
const socket = new WebSocket(endpoint);
|
|
150
|
+
ws = socket;
|
|
151
|
+
await new Promise((opened, failed) => {
|
|
152
|
+
socket.addEventListener('open', () => opened(), { once: true });
|
|
153
|
+
socket.addEventListener('error', () => failed(new Error('could not connect to Chrome')), { once: true });
|
|
154
|
+
});
|
|
155
|
+
let nextId = 1;
|
|
156
|
+
const pending = new Map();
|
|
157
|
+
const listeners = new Set();
|
|
158
|
+
socket.addEventListener('message', (event) => {
|
|
159
|
+
const message = JSON.parse(String(event.data));
|
|
160
|
+
if (message.id !== undefined) {
|
|
161
|
+
const waiting = pending.get(message.id);
|
|
162
|
+
pending.delete(message.id);
|
|
163
|
+
if (!waiting)
|
|
164
|
+
return;
|
|
165
|
+
if (message.error)
|
|
166
|
+
waiting.reject(new Error(`${waiting.method}: ${message.error.message}`));
|
|
167
|
+
else
|
|
168
|
+
waiting.resolve(message.result ?? {});
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
for (const listener of listeners)
|
|
172
|
+
listener(message);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
const send = (method, params = {}, sessionId) => new Promise((resolveSend, reject) => {
|
|
176
|
+
const id = nextId++;
|
|
177
|
+
pending.set(id, { resolve: resolveSend, reject, method });
|
|
178
|
+
socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
179
|
+
});
|
|
180
|
+
const { targetId } = (await send('Target.createTarget', { url: 'about:blank' }));
|
|
181
|
+
const { sessionId } = (await send('Target.attachToTarget', { targetId, flatten: true }));
|
|
182
|
+
await send('Page.enable', {}, sessionId);
|
|
183
|
+
await send('Emulation.setDeviceMetricsOverride', { width: request.width, height: request.height, deviceScaleFactor: 1, mobile: false }, sessionId);
|
|
184
|
+
if (request.scheme)
|
|
185
|
+
await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: request.scheme }] }, sessionId);
|
|
186
|
+
// A page that starts a download while it is photographed saves nothing on this computer.
|
|
187
|
+
await send('Browser.setDownloadBehavior', { behavior: 'deny' }).catch(() => undefined);
|
|
188
|
+
const loaded = new Promise((done) => {
|
|
189
|
+
const listener = (message) => {
|
|
190
|
+
if (message.sessionId === sessionId && message.method === 'Page.loadEventFired') {
|
|
191
|
+
listeners.delete(listener);
|
|
192
|
+
done();
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
listeners.add(listener);
|
|
196
|
+
});
|
|
197
|
+
const navigated = (await send('Page.navigate', { url: request.url }, sessionId));
|
|
198
|
+
if (navigated.errorText)
|
|
199
|
+
throw new Error(`the page did not load: ${navigated.errorText}`);
|
|
200
|
+
await Promise.race([loaded, sleep(15_000)]);
|
|
201
|
+
const ready = request.ready ?? DEFAULT_READY;
|
|
202
|
+
const until = Date.now() + 10_000;
|
|
203
|
+
while (Date.now() < until) {
|
|
204
|
+
const out = (await send('Runtime.evaluate', { expression: `!!(${ready})`, returnByValue: true }, sessionId).catch(() => null));
|
|
205
|
+
if (out?.result?.value === true)
|
|
206
|
+
break;
|
|
207
|
+
await sleep(150);
|
|
208
|
+
}
|
|
209
|
+
await sleep(request.settleMs ?? 1500);
|
|
210
|
+
const shot = (await send('Page.captureScreenshot', { format: 'png' }, sessionId));
|
|
211
|
+
return Buffer.from(shot.data, 'base64');
|
|
212
|
+
};
|
|
213
|
+
try {
|
|
214
|
+
return await Promise.race([
|
|
215
|
+
work(),
|
|
216
|
+
new Promise((_, reject) => {
|
|
217
|
+
timer = setTimeout(() => reject(new Error('the page took too long to draw')), request.timeoutMs ?? 45_000);
|
|
218
|
+
}),
|
|
219
|
+
]);
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
await cleanup();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a type package (`<id>-<version>.oatype`) before anything of it is kept: the one set of checks behind a local
|
|
3
|
+
* `open-artifacts types install` and a site's `types.import`, so both refuse the same packages for the same reasons.
|
|
4
|
+
*
|
|
5
|
+
* The whole zip is read first (`checkZip`: one top folder, plain files, no `..`, absolute path, backslash, NUL or
|
|
6
|
+
* name given twice by case or Unicode form, the package limits on what it declares), then the entries' paths and kinds
|
|
7
|
+
* (`packageEntryProblems`, as `types check --for-share`), the manifest (`manifestPackageProblems`: the fields, no
|
|
8
|
+
* `entry.start` or `entry.url`, the network list), the id (a type id, not built in, not reserved) and the declaration
|
|
9
|
+
* of `index.html` (`readStaticDeclaration`: literal data, never run). Nothing is written and nothing from the package
|
|
10
|
+
* runs; the caller unpacks `files` with `unpackZip` once it has decided to keep it.
|
|
11
|
+
*/
|
|
12
|
+
import { type ArtifactTypeManifest } from '@openartifactsai/protocol';
|
|
13
|
+
import { type CheckedZipFile } from './zip.js';
|
|
14
|
+
/** A package read and checked: what it is, and its files (not unpacked). */
|
|
15
|
+
export interface CheckedTypePackage {
|
|
16
|
+
/** The id it would install under (`as`, else the manifest's `slug`). */
|
|
17
|
+
id: string;
|
|
18
|
+
uid: string;
|
|
19
|
+
name: string;
|
|
20
|
+
version: string;
|
|
21
|
+
description: string;
|
|
22
|
+
manifest: ArtifactTypeManifest & Record<string, unknown>;
|
|
23
|
+
/** The zip's one top folder. */
|
|
24
|
+
top: string;
|
|
25
|
+
files: CheckedZipFile[];
|
|
26
|
+
/** Whether `index.html` is there and carries a `// artifact.json` declaration (a frame type). */
|
|
27
|
+
declared: boolean;
|
|
28
|
+
/** The capabilities the declaration names. */
|
|
29
|
+
capabilities: string[];
|
|
30
|
+
/** The https origins `openArtifacts.network` lets its pages reach. */
|
|
31
|
+
network: string[];
|
|
32
|
+
/** The type's instructions (`SKILL.md`, or the manifest's `skill`), or null. */
|
|
33
|
+
skill: {
|
|
34
|
+
path: string;
|
|
35
|
+
text: string;
|
|
36
|
+
} | null;
|
|
37
|
+
sha256: string;
|
|
38
|
+
bytes: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Reads and checks a package's bytes (see the module comment). `source` names it in messages; `as` takes another id;
|
|
42
|
+
* `fix` is the hint a refused id gets (default: install it under another id). Refusals are `OpenArtifactsError`s:
|
|
43
|
+
* `too_large`, `bad_archive`, `invalid_argument`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function checkTypePackage(bytes: Uint8Array, source: string, o?: {
|
|
46
|
+
as?: string | null;
|
|
47
|
+
idFix?: string;
|
|
48
|
+
}): Promise<CheckedTypePackage>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a type package (`<id>-<version>.oatype`) before anything of it is kept: the one set of checks behind a local
|
|
3
|
+
* `open-artifacts types install` and a site's `types.import`, so both refuse the same packages for the same reasons.
|
|
4
|
+
*
|
|
5
|
+
* The whole zip is read first (`checkZip`: one top folder, plain files, no `..`, absolute path, backslash, NUL or
|
|
6
|
+
* name given twice by case or Unicode form, the package limits on what it declares), then the entries' paths and kinds
|
|
7
|
+
* (`packageEntryProblems`, as `types check --for-share`), the manifest (`manifestPackageProblems`: the fields, no
|
|
8
|
+
* `entry.start` or `entry.url`, the network list), the id (a type id, not built in, not reserved) and the declaration
|
|
9
|
+
* of `index.html` (`readStaticDeclaration`: literal data, never run). Nothing is written and nothing from the package
|
|
10
|
+
* runs; the caller unpacks `files` with `unpackZip` once it has decided to keep it.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { adoptLegacyManifest, BUILTIN_TYPE_IDS, DeclarationError, OpenArtifactsError, RESERVED_TYPE_IDS, TYPE_ID, TYPE_PACKAGE_LIMITS, manifestPackageProblems, networkOrigins, packageEntryProblems, readStaticDeclaration, } from '@openartifactsai/protocol';
|
|
14
|
+
import { checkZip, unpackZipFile, ZipRefusal } from "./zip.js";
|
|
15
|
+
const listed = (problems) => problems.map((p) => ` - ${p.message}`).join('\n');
|
|
16
|
+
/**
|
|
17
|
+
* Reads and checks a package's bytes (see the module comment). `source` names it in messages; `as` takes another id;
|
|
18
|
+
* `fix` is the hint a refused id gets (default: install it under another id). Refusals are `OpenArtifactsError`s:
|
|
19
|
+
* `too_large`, `bad_archive`, `invalid_argument`.
|
|
20
|
+
*/
|
|
21
|
+
export async function checkTypePackage(bytes, source, o = {}) {
|
|
22
|
+
let checked;
|
|
23
|
+
try {
|
|
24
|
+
checked = checkZip(bytes, { noun: 'a type package', maxFiles: TYPE_PACKAGE_LIMITS.files, maxBytes: TYPE_PACKAGE_LIMITS.totalBytes, maxFileBytes: TYPE_PACKAGE_LIMITS.fileBytes, folders: true });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error instanceof ZipRefusal)
|
|
28
|
+
throw new OpenArtifactsError(error.code === 'too_large' ? 'too_large' : 'bad_archive', `${source}: ${error.message}`);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
const paths = checked.files.map((f) => f.path);
|
|
32
|
+
const entryProblems = packageEntryProblems([
|
|
33
|
+
{ path: `${checked.top}/`, kind: 'dir', size: 0 },
|
|
34
|
+
...checked.files.map((f) => ({ path: `${checked.top}/${f.path}`, kind: 'file', size: f.entry.size })),
|
|
35
|
+
]);
|
|
36
|
+
if (entryProblems.length)
|
|
37
|
+
throw new OpenArtifactsError('bad_archive', `${source} is not a type package that can be installed:\n${listed(entryProblems)}`);
|
|
38
|
+
const read = async (path) => {
|
|
39
|
+
const item = checked.files.find((f) => f.path === path);
|
|
40
|
+
if (!item)
|
|
41
|
+
return null;
|
|
42
|
+
try {
|
|
43
|
+
return (await unpackZipFile(bytes, item)).toString('utf8');
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof ZipRefusal)
|
|
47
|
+
throw new OpenArtifactsError('bad_archive', `${source}: ${error.message}`);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const manifestText = await read('artifact-type.json');
|
|
52
|
+
if (manifestText === null)
|
|
53
|
+
throw new OpenArtifactsError('bad_archive', `${source} has no artifact-type.json in its folder ${checked.top}/.`);
|
|
54
|
+
let manifest;
|
|
55
|
+
try {
|
|
56
|
+
const parsed = JSON.parse(manifestText);
|
|
57
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
58
|
+
throw new Error('not a JSON object');
|
|
59
|
+
// A package made before the rename keeps its hints under `openArtifact`: read as `openArtifacts`.
|
|
60
|
+
manifest = adoptLegacyManifest(parsed);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
throw new OpenArtifactsError('bad_archive', `${source}: artifact-type.json does not parse (${error.message}).`);
|
|
64
|
+
}
|
|
65
|
+
const manifestProblems = manifestPackageProblems(manifest, paths);
|
|
66
|
+
if (manifestProblems.length)
|
|
67
|
+
throw new OpenArtifactsError('bad_archive', `${source} is not a type package that can be installed:\n${listed(manifestProblems)}`);
|
|
68
|
+
const id = o.as ?? String(manifest.slug);
|
|
69
|
+
const fix = o.idFix ?? 'Install it under another id with --as <id>.';
|
|
70
|
+
const refuse = (message) => new OpenArtifactsError('invalid_argument', message, { fix });
|
|
71
|
+
if (!TYPE_ID.test(id))
|
|
72
|
+
throw refuse(`${JSON.stringify(id)} is not a type id: letters, digits, ".", "_" and "-", at most 64.`);
|
|
73
|
+
if (BUILTIN_TYPE_IDS.includes(id))
|
|
74
|
+
throw refuse(`${id} is a built-in type's id: an installed type never takes one.`);
|
|
75
|
+
if (RESERVED_TYPE_IDS.includes(id))
|
|
76
|
+
throw refuse(`${id} is reserved.`);
|
|
77
|
+
let capabilities = [];
|
|
78
|
+
let declared = false;
|
|
79
|
+
const html = await read('index.html');
|
|
80
|
+
if (html !== null) {
|
|
81
|
+
try {
|
|
82
|
+
const decl = readStaticDeclaration(html);
|
|
83
|
+
if (decl) {
|
|
84
|
+
if (decl.lexical.length)
|
|
85
|
+
throw new DeclarationError(`${decl.lexical.join(', ')} declared with let or const`, 0, 0);
|
|
86
|
+
capabilities = Object.keys(decl.capabilities);
|
|
87
|
+
declared = true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error instanceof DeclarationError)
|
|
92
|
+
throw new OpenArtifactsError('bad_archive', `${source}: the // artifact.json declaration of index.html is not literal data (${error.message}).`);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const skillPath = manifest.skill === false ? null : typeof manifest.skill === 'string' ? manifest.skill : 'SKILL.md';
|
|
97
|
+
const skillText = skillPath ? await read(skillPath) : null;
|
|
98
|
+
return {
|
|
99
|
+
id,
|
|
100
|
+
uid: String(manifest.uid),
|
|
101
|
+
name: String(manifest.name),
|
|
102
|
+
version: String(manifest.version),
|
|
103
|
+
description: String(manifest.description),
|
|
104
|
+
manifest,
|
|
105
|
+
top: checked.top,
|
|
106
|
+
files: checked.files,
|
|
107
|
+
declared,
|
|
108
|
+
capabilities,
|
|
109
|
+
network: networkOrigins(manifest),
|
|
110
|
+
skill: skillText !== null && skillPath ? { path: skillPath, text: skillText } : null,
|
|
111
|
+
sha256: createHash('sha256').update(bytes).digest('hex'),
|
|
112
|
+
bytes: bytes.byteLength,
|
|
113
|
+
};
|
|
114
|
+
}
|
package/src/ws.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small WebSocket server side (RFC 6455) on Node built-ins only: text
|
|
3
|
+
* frames, ping/pong and close. Type servers use it for the event streams of
|
|
4
|
+
* mounted sites and for their own upgrades, and the daemon for the Harness API
|
|
5
|
+
* (`/__harness`).
|
|
6
|
+
*/
|
|
7
|
+
import type { IncomingMessage } from 'node:http';
|
|
8
|
+
import type { Duplex } from 'node:stream';
|
|
9
|
+
/** What a {@link WebSocketConnection} calls back. */
|
|
10
|
+
export interface WebSocketHandlers {
|
|
11
|
+
/** A complete text (or binary, decoded as UTF-8) message arrived. */
|
|
12
|
+
message?: (text: string) => void;
|
|
13
|
+
/** The connection closed, from either side. Called once. */
|
|
14
|
+
close?: () => void;
|
|
15
|
+
}
|
|
16
|
+
/** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
|
|
17
|
+
export declare function acceptKey(key: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
|
|
20
|
+
* subprotocol when the client asked for it; with a list, the first one the
|
|
21
|
+
* client asked for, in the list's order (an older name after the current one).
|
|
22
|
+
* Returns the connection, or `null` after refusing a request that is not a
|
|
23
|
+
* WebSocket handshake.
|
|
24
|
+
*/
|
|
25
|
+
export declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, head: Buffer, protocol?: string | readonly string[]): WebSocketConnection | null;
|
|
26
|
+
/** One accepted WebSocket connection (server side: frames it sends are unmasked). */
|
|
27
|
+
export declare class WebSocketConnection {
|
|
28
|
+
/** The underlying socket. */
|
|
29
|
+
readonly socket: Duplex;
|
|
30
|
+
/** Set once the connection closed. */
|
|
31
|
+
closed: boolean;
|
|
32
|
+
/** Callbacks; assign them right after accepting. */
|
|
33
|
+
handlers: WebSocketHandlers;
|
|
34
|
+
private buffer;
|
|
35
|
+
private fragments;
|
|
36
|
+
private fragmentBytes;
|
|
37
|
+
private readonly pinger;
|
|
38
|
+
/** Wraps an upgraded socket; `head` is what the upgrade event already read. */
|
|
39
|
+
constructor(socket: Duplex, head?: Buffer);
|
|
40
|
+
/** Parses every complete frame in the buffer. */
|
|
41
|
+
private read;
|
|
42
|
+
/** Sends one unfragmented frame. */
|
|
43
|
+
private frame;
|
|
44
|
+
/** Sends a text message. */
|
|
45
|
+
sendText(text: string): void;
|
|
46
|
+
/** Sends a close frame with `code` and ends the connection. */
|
|
47
|
+
close(code?: number): void;
|
|
48
|
+
/** Ends the socket and calls the close handler once. */
|
|
49
|
+
private finish;
|
|
50
|
+
}
|
package/src/ws.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small WebSocket server side (RFC 6455) on Node built-ins only: text
|
|
3
|
+
* frames, ping/pong and close. Type servers use it for the event streams of
|
|
4
|
+
* mounted sites and for their own upgrades, and the daemon for the Harness API
|
|
5
|
+
* (`/__harness`).
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
/** The GUID RFC 6455 appends to the client key. */
|
|
9
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
10
|
+
/** Largest frame accepted, bytes. Bigger frames close the connection with 1009. */
|
|
11
|
+
const MAX_FRAME = 16 * 1024 * 1024;
|
|
12
|
+
/** Interval of keep-alive pings, ms. */
|
|
13
|
+
const PING_MS = 25_000;
|
|
14
|
+
/** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
|
|
15
|
+
export function acceptKey(key) {
|
|
16
|
+
return createHash('sha1').update(key + GUID).digest('base64');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
|
|
20
|
+
* subprotocol when the client asked for it; with a list, the first one the
|
|
21
|
+
* client asked for, in the list's order (an older name after the current one).
|
|
22
|
+
* Returns the connection, or `null` after refusing a request that is not a
|
|
23
|
+
* WebSocket handshake.
|
|
24
|
+
*/
|
|
25
|
+
export function acceptWebSocket(request, socket, head, protocol) {
|
|
26
|
+
const key = request.headers['sec-websocket-key'];
|
|
27
|
+
if (typeof key !== 'string' || !key.trim() || String(request.headers.upgrade).toLowerCase() !== 'websocket') {
|
|
28
|
+
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const asked = String(request.headers['sec-websocket-protocol'] ?? '')
|
|
32
|
+
.split(',')
|
|
33
|
+
.map((p) => p.trim())
|
|
34
|
+
.filter(Boolean);
|
|
35
|
+
const lines = ['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${acceptKey(key)}`];
|
|
36
|
+
const chosen = (typeof protocol === 'string' ? [protocol] : (protocol ?? [])).find((p) => asked.includes(p));
|
|
37
|
+
if (chosen)
|
|
38
|
+
lines.push(`Sec-WebSocket-Protocol: ${chosen}`);
|
|
39
|
+
socket.write(`${lines.join('\r\n')}\r\n\r\n`);
|
|
40
|
+
return new WebSocketConnection(socket, head);
|
|
41
|
+
}
|
|
42
|
+
/** One accepted WebSocket connection (server side: frames it sends are unmasked). */
|
|
43
|
+
export class WebSocketConnection {
|
|
44
|
+
/** The underlying socket. */
|
|
45
|
+
socket;
|
|
46
|
+
/** Set once the connection closed. */
|
|
47
|
+
closed = false;
|
|
48
|
+
/** Callbacks; assign them right after accepting. */
|
|
49
|
+
handlers = {};
|
|
50
|
+
buffer;
|
|
51
|
+
fragments = [];
|
|
52
|
+
fragmentBytes = 0;
|
|
53
|
+
pinger;
|
|
54
|
+
/** Wraps an upgraded socket; `head` is what the upgrade event already read. */
|
|
55
|
+
constructor(socket, head) {
|
|
56
|
+
this.socket = socket;
|
|
57
|
+
this.buffer = head && head.length ? Buffer.from(head) : Buffer.alloc(0);
|
|
58
|
+
socket.setNoDelay?.(true);
|
|
59
|
+
socket.on('data', (chunk) => {
|
|
60
|
+
if (this.closed)
|
|
61
|
+
return;
|
|
62
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
63
|
+
this.read();
|
|
64
|
+
});
|
|
65
|
+
const end = () => this.finish();
|
|
66
|
+
socket.on('close', end);
|
|
67
|
+
socket.on('end', end);
|
|
68
|
+
socket.on('error', end);
|
|
69
|
+
if (this.buffer.length)
|
|
70
|
+
setImmediate(() => this.read());
|
|
71
|
+
this.pinger = setInterval(() => this.frame(0x9, Buffer.alloc(0)), PING_MS);
|
|
72
|
+
this.pinger.unref();
|
|
73
|
+
}
|
|
74
|
+
/** Parses every complete frame in the buffer. */
|
|
75
|
+
read() {
|
|
76
|
+
for (;;) {
|
|
77
|
+
if (this.closed)
|
|
78
|
+
return;
|
|
79
|
+
const b = this.buffer;
|
|
80
|
+
if (b.length < 2)
|
|
81
|
+
return;
|
|
82
|
+
const fin = (b[0] & 0x80) !== 0;
|
|
83
|
+
const op = b[0] & 0x0f;
|
|
84
|
+
const masked = (b[1] & 0x80) !== 0;
|
|
85
|
+
let len = b[1] & 0x7f;
|
|
86
|
+
let at = 2;
|
|
87
|
+
if (len === 126) {
|
|
88
|
+
if (b.length < 4)
|
|
89
|
+
return;
|
|
90
|
+
len = b.readUInt16BE(2);
|
|
91
|
+
at = 4;
|
|
92
|
+
}
|
|
93
|
+
else if (len === 127) {
|
|
94
|
+
if (b.length < 10)
|
|
95
|
+
return;
|
|
96
|
+
len = Number(b.readBigUInt64BE(2));
|
|
97
|
+
at = 10;
|
|
98
|
+
}
|
|
99
|
+
if (op >= 0x8 && (!fin || len > 125))
|
|
100
|
+
return this.close(1002);
|
|
101
|
+
if (len > MAX_FRAME)
|
|
102
|
+
return this.close(1009);
|
|
103
|
+
const maskAt = at;
|
|
104
|
+
if (masked)
|
|
105
|
+
at += 4;
|
|
106
|
+
if (b.length < at + len)
|
|
107
|
+
return;
|
|
108
|
+
let payload = b.subarray(at, at + len);
|
|
109
|
+
if (masked) {
|
|
110
|
+
const mask = b.subarray(maskAt, maskAt + 4);
|
|
111
|
+
payload = Buffer.from(payload);
|
|
112
|
+
for (let i = 0; i < payload.length; i++)
|
|
113
|
+
payload[i] = payload[i] ^ mask[i & 3];
|
|
114
|
+
}
|
|
115
|
+
this.buffer = b.subarray(at + len);
|
|
116
|
+
if (op === 0x8)
|
|
117
|
+
return this.close(1000);
|
|
118
|
+
if (op === 0x9) {
|
|
119
|
+
this.frame(0xa, payload);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (op === 0xa)
|
|
123
|
+
continue;
|
|
124
|
+
if (op === 0x1 || op === 0x2 || op === 0x0) {
|
|
125
|
+
const continuing = this.fragments.length > 0;
|
|
126
|
+
if ((op === 0x0 && !continuing) || (op !== 0x0 && continuing))
|
|
127
|
+
return this.close(1002);
|
|
128
|
+
if (this.fragmentBytes + payload.length > MAX_FRAME)
|
|
129
|
+
return this.close(1009);
|
|
130
|
+
this.fragments.push(payload);
|
|
131
|
+
this.fragmentBytes += payload.length;
|
|
132
|
+
if (fin) {
|
|
133
|
+
const text = Buffer.concat(this.fragments).toString('utf8');
|
|
134
|
+
this.fragments = [];
|
|
135
|
+
this.fragmentBytes = 0;
|
|
136
|
+
try {
|
|
137
|
+
this.handlers.message?.(text);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// A handler's error is its own.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** Sends one unfragmented frame. */
|
|
147
|
+
frame(op, payload) {
|
|
148
|
+
if (this.closed)
|
|
149
|
+
return;
|
|
150
|
+
const len = payload.length;
|
|
151
|
+
let header;
|
|
152
|
+
if (len < 126)
|
|
153
|
+
header = Buffer.from([0x80 | op, len]);
|
|
154
|
+
else if (len < 65536) {
|
|
155
|
+
header = Buffer.alloc(4);
|
|
156
|
+
header[0] = 0x80 | op;
|
|
157
|
+
header[1] = 126;
|
|
158
|
+
header.writeUInt16BE(len, 2);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
header = Buffer.alloc(10);
|
|
162
|
+
header[0] = 0x80 | op;
|
|
163
|
+
header[1] = 127;
|
|
164
|
+
header.writeBigUInt64BE(BigInt(len), 2);
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
this.socket.write(Buffer.concat([header, payload]));
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
this.finish();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Sends a text message. */
|
|
174
|
+
sendText(text) {
|
|
175
|
+
this.frame(0x1, Buffer.from(text, 'utf8'));
|
|
176
|
+
}
|
|
177
|
+
/** Sends a close frame with `code` and ends the connection. */
|
|
178
|
+
close(code = 1000) {
|
|
179
|
+
if (this.closed)
|
|
180
|
+
return;
|
|
181
|
+
const payload = Buffer.alloc(2);
|
|
182
|
+
payload.writeUInt16BE(code, 0);
|
|
183
|
+
this.frame(0x8, payload);
|
|
184
|
+
this.finish();
|
|
185
|
+
}
|
|
186
|
+
/** Ends the socket and calls the close handler once. */
|
|
187
|
+
finish() {
|
|
188
|
+
if (this.closed)
|
|
189
|
+
return;
|
|
190
|
+
this.closed = true;
|
|
191
|
+
this.buffer = Buffer.alloc(0);
|
|
192
|
+
this.fragments = [];
|
|
193
|
+
this.fragmentBytes = 0;
|
|
194
|
+
clearInterval(this.pinger);
|
|
195
|
+
try {
|
|
196
|
+
this.socket.end();
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// Already gone.
|
|
200
|
+
}
|
|
201
|
+
this.handlers.close?.();
|
|
202
|
+
}
|
|
203
|
+
}
|