@insforge/instabox-sdk 0.2.2 → 0.4.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 +40 -20
- package/dist/index.cjs +280 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +94 -36
- package/dist/index.d.ts +94 -36
- package/dist/index.js +280 -47
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/skills/instabox/SKILL.md +13 -11
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @insforge/instabox-sdk
|
|
2
2
|
|
|
3
|
-
TypeScript SDK for [InstaBox](https://github.com/InsForge/instabox): create sandboxes on Firecracker dev machines, run commands in them, read and write files, pause and resume them,
|
|
3
|
+
TypeScript SDK for [InstaBox](https://github.com/InsForge/instabox): create sandboxes on Firecracker dev machines, run commands in them, read and write files, pause and resume them, save and restore snapshots and SSH in.
|
|
4
4
|
|
|
5
5
|
- Zero runtime dependencies. Uses the global `fetch` (Node 18+, Bun, Deno).
|
|
6
6
|
- ESM and CommonJS builds with type declarations.
|
|
@@ -30,14 +30,14 @@ The key is sent as the `X-API-Key` header.
|
|
|
30
30
|
|
|
31
31
|
### Scopes
|
|
32
32
|
|
|
33
|
-
| Scope | Allows
|
|
34
|
-
| ----------------- |
|
|
35
|
-
| `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault`
|
|
36
|
-
| `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `
|
|
37
|
-
| `machines:delete` | `kill`
|
|
38
|
-
| `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot`
|
|
39
|
-
| `images:write` | `createSnapshot`
|
|
40
|
-
| `images:delete` | `deleteSnapshot`
|
|
33
|
+
| Scope | Allows |
|
|
34
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
35
|
+
| `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
|
|
36
|
+
| `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setTimeout`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
|
|
37
|
+
| `machines:delete` | `kill` |
|
|
38
|
+
| `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
|
|
39
|
+
| `images:write` | `createSnapshot` |
|
|
40
|
+
| `images:delete` | `deleteSnapshot` |
|
|
41
41
|
|
|
42
42
|
`:write` and `:delete` imply `:read`. Creating from a template or a snapshot ID needs only machine scopes. Creating from a snapshot name also needs `images:read`. Snapshot permissions are named `images:*` by the current API. Add `images:write` and `images:delete` if your code saves and deletes snapshots. A call outside the key's scopes throws `InstaboxAuthError` (`403 insufficient_scope`).
|
|
43
43
|
|
|
@@ -149,14 +149,6 @@ A timeout is enforced by the server: at `endAt` it suspends the sandbox (`onTime
|
|
|
149
149
|
|
|
150
150
|
Idle pause: a new sandbox pauses after 30 idle minutes (no agent working, no terminal use, little CPU) and resumes on the next `commands.run`, file read or SSH sign-in, processes and memory intact. `autoSuspendMs: 0` makes a sandbox that stays on (a server that must keep answering), another value changes the idle time, `setAutoSuspend(ms)` changes it later and `getInfo().autoSuspendMs` shows it. Unlike a timeout the setting stays across pause and resume.
|
|
151
151
|
|
|
152
|
-
### Fork
|
|
153
|
-
|
|
154
|
-
```ts
|
|
155
|
-
const copy = await sandbox.fork({ name: 'copy' })
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
A fork copies the root disk and `/data`, including credentials kept under HOME. InstaBox forks only stopped machines, so `fork()` first stops a running or paused source (its processes end, `/data` is kept) and leaves it stopped; call `sandbox.resume()` to start it again. Pass `stopSource: false` to fail instead.
|
|
159
|
-
|
|
160
152
|
## Vault
|
|
161
153
|
|
|
162
154
|
The Vault holds the account's secrets on the control plane (API keys for model providers, a `.env`, a service-account file) and writes them into every sandbox of the account when it boots or resumes: `env` items become environment variables of every login shell (so of `commands.run` too), `file` items become files under the home directory. Items are managed by a person, on the dashboard's Vault page or with `instabox vault set`; an API key cannot read, create or change them.
|
|
@@ -165,11 +157,10 @@ What an API key can do is keep a sandbox out of it, which **a program creating s
|
|
|
165
157
|
|
|
166
158
|
```ts
|
|
167
159
|
const tenant = await Sandbox.create('universal', { vault: false }) // never gets the account's items
|
|
168
|
-
const copy = await sandbox.fork({ vault: false })
|
|
169
160
|
await sandbox.disableVault() // for good, in any state
|
|
170
161
|
```
|
|
171
162
|
|
|
172
|
-
`vault: false` is for good: such a sandbox
|
|
163
|
+
`vault: false` is for good: such a sandbox never gets items. On a sandbox that takes the Vault:
|
|
173
164
|
|
|
174
165
|
```ts
|
|
175
166
|
const v = await sandbox.vault() // { enabled, items: [{ name, kind, path? }], applied: { at, env, files, removed?, kept?, error? } | null }
|
|
@@ -198,6 +189,8 @@ try {
|
|
|
198
189
|
|
|
199
190
|
`deleteSnapshot` returns false if the snapshot is already absent. Snapshots do not save running processes; use pause/resume for memory preservation.
|
|
200
191
|
|
|
192
|
+
To copy a sandbox, save a snapshot and create from it, as above (InstaBox no longer has a fork call). The copy does not inherit the source's settings: `vault: false` and other `Sandbox.create` options apply to it as to any new sandbox, so a copy of a sandbox without the Vault needs `Sandbox.create(snapshot.id, { vault: false })`.
|
|
193
|
+
|
|
201
194
|
## SSH
|
|
202
195
|
|
|
203
196
|
```ts
|
|
@@ -216,6 +209,33 @@ console.log(`ssh -p ${ssh.port} ${ssh.username}@${ssh.host}`)
|
|
|
216
209
|
|
|
217
210
|
The sandbox must be running. Certificates last 1 hour by default; `ttlSeconds` takes 1 to 86 400 (24 hours), other values throw before the request. Pausing or stopping prevents connections while the sandbox is not running; an unexpired certificate can be used again after resume or start. Deleting the sandbox or revoking the API key that issued the certificate revokes access.
|
|
218
211
|
|
|
212
|
+
## Desktop: see it and control it
|
|
213
|
+
|
|
214
|
+
Sandboxes from the default `agent-browser` template have a desktop (Xfce and Chromium on display `:1`). `sandbox.desktop` starts it, gives an agent a mouse, a keyboard and screenshots, and makes a link people can watch it through.
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
await sandbox.desktop.start() // { installed, running, width: 1280, height: 800 }; a no-op when running
|
|
218
|
+
await sandbox.desktop.open('https://example.com')
|
|
219
|
+
const png = await sandbox.desktop.screenshot() // Uint8Array, PNG
|
|
220
|
+
|
|
221
|
+
await sandbox.desktop.click(640, 400) // { button: 'left' | 'right' | 'middle', double: true }
|
|
222
|
+
await sandbox.desktop.move(100, 200)
|
|
223
|
+
await sandbox.desktop.drag([100, 200], [300, 400])
|
|
224
|
+
await sandbox.desktop.scroll({ direction: 'down', amount: 3 })
|
|
225
|
+
await sandbox.desktop.type('Hello "world" ✓\n') // literal text, sent through stdin
|
|
226
|
+
await sandbox.desktop.press('Enter')
|
|
227
|
+
await sandbox.desktop.press(['ctrl', 'l']) // a chord
|
|
228
|
+
const { x, y } = await sandbox.desktop.cursorPosition()
|
|
229
|
+
|
|
230
|
+
// A page that shows the desktop full-screen: open it, or put it in an <iframe>.
|
|
231
|
+
const { url, expiresAt } = await sandbox.desktop.streamUrl({ viewOnly: true, ttlSeconds: 3600 })
|
|
232
|
+
await sandbox.desktop.revokeStreamUrls() // every link stops working; open viewers are disconnected
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`start({ width, height })` sizes the screen (800-2560 x 600-1600) of a desktop it starts; on other templates it installs the desktop first, about half a minute once. Coordinates are screen pixels from the top left. Keys take common names (`Enter`, `Esc`, `Tab`, `Backspace`, arrows, `F1`-`F24`, `ctrl`, `alt`, `shift`, `cmd`) or X keysym names. Input and screenshots run `xdotool` and `scrot` in the sandbox, so they need the `machines:exec` (or `machines:write`) scope; a failing one throws `CommandExitError`.
|
|
236
|
+
|
|
237
|
+
`streamUrl` needs no instabox account to open: anyone with the link can connect until `expiresAt` (60 s to 24 h, default 1 h). Expiry stops new connections; revoke ends open sessions: a viewer already watching stays until they leave or you call `revokeStreamUrls()`, which ends every link of the sandbox and disconnects its viewers within a few seconds. Revoke when someone's access should end, for example when a tenant's session or subscription ends. Links are view-only by default, enforced by the server; `viewOnly: false` lets the viewer use the mouse and keyboard. The sandbox and its desktop must be running when the link is opened.
|
|
238
|
+
|
|
219
239
|
## Errors
|
|
220
240
|
|
|
221
241
|
| Class | When |
|
|
@@ -256,7 +276,7 @@ INSTABOX_LIVE=1 INSTABOX_API_KEY=... npm run test:live # creates and deletes o
|
|
|
256
276
|
Bump `version` in `package.json` in a PR. After it merges, tag that commit and push the tag:
|
|
257
277
|
|
|
258
278
|
```bash
|
|
259
|
-
git tag v0.
|
|
279
|
+
git tag v0.3.0 && git push origin v0.3.0
|
|
260
280
|
```
|
|
261
281
|
|
|
262
282
|
The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
|
package/dist/index.cjs
CHANGED
|
@@ -24,6 +24,8 @@ __export(index_exports, {
|
|
|
24
24
|
Commands: () => Commands,
|
|
25
25
|
DEFAULT_API_URL: () => DEFAULT_API_URL,
|
|
26
26
|
DEFAULT_TEMPLATE: () => DEFAULT_TEMPLATE,
|
|
27
|
+
DESKTOP_DISPLAY: () => DESKTOP_DISPLAY,
|
|
28
|
+
Desktop: () => Desktop,
|
|
27
29
|
FALLBACK_TEMPLATE: () => FALLBACK_TEMPLATE,
|
|
28
30
|
Files: () => Files,
|
|
29
31
|
InstaboxAuthError: () => InstaboxAuthError,
|
|
@@ -211,6 +213,261 @@ var Commands = class {
|
|
|
211
213
|
}
|
|
212
214
|
};
|
|
213
215
|
|
|
216
|
+
// src/desktop.ts
|
|
217
|
+
var DESKTOP_DISPLAY = ":1";
|
|
218
|
+
var BUTTONS = { left: 1, middle: 2, right: 3 };
|
|
219
|
+
var WHEEL = { up: 4, down: 5, left: 6, right: 7 };
|
|
220
|
+
var KEYS = {
|
|
221
|
+
enter: "Return",
|
|
222
|
+
return: "Return",
|
|
223
|
+
esc: "Escape",
|
|
224
|
+
escape: "Escape",
|
|
225
|
+
tab: "Tab",
|
|
226
|
+
space: "space",
|
|
227
|
+
backspace: "BackSpace",
|
|
228
|
+
delete: "Delete",
|
|
229
|
+
del: "Delete",
|
|
230
|
+
insert: "Insert",
|
|
231
|
+
home: "Home",
|
|
232
|
+
end: "End",
|
|
233
|
+
pageup: "Prior",
|
|
234
|
+
pagedown: "Next",
|
|
235
|
+
up: "Up",
|
|
236
|
+
down: "Down",
|
|
237
|
+
left: "Left",
|
|
238
|
+
right: "Right",
|
|
239
|
+
ctrl: "ctrl",
|
|
240
|
+
control: "ctrl",
|
|
241
|
+
alt: "alt",
|
|
242
|
+
shift: "shift",
|
|
243
|
+
meta: "super",
|
|
244
|
+
cmd: "super",
|
|
245
|
+
command: "super",
|
|
246
|
+
super: "super",
|
|
247
|
+
win: "super",
|
|
248
|
+
"+": "plus"
|
|
249
|
+
};
|
|
250
|
+
var enc = encodeURIComponent;
|
|
251
|
+
function keysym(key) {
|
|
252
|
+
if (typeof key !== "string" || !key || /\s/.test(key)) {
|
|
253
|
+
throw new InstaboxError(`invalid key ${JSON.stringify(key)}`, { code: "bad_request" });
|
|
254
|
+
}
|
|
255
|
+
const lower = key.toLowerCase();
|
|
256
|
+
if (KEYS[lower]) return KEYS[lower];
|
|
257
|
+
if (/^f([1-9]|1[0-9]|2[0-4])$/.test(lower)) return lower.toUpperCase();
|
|
258
|
+
return key;
|
|
259
|
+
}
|
|
260
|
+
function coord(name, v) {
|
|
261
|
+
if (!Number.isInteger(v) || v < 0 || v > 16384) {
|
|
262
|
+
throw new InstaboxError(`${name} must be a whole number of pixels from 0; got ${v}`, { code: "bad_request" });
|
|
263
|
+
}
|
|
264
|
+
return v;
|
|
265
|
+
}
|
|
266
|
+
var SCREENSHOT_MAX_BYTES = 32 * 1024 * 1024;
|
|
267
|
+
var Desktop = class {
|
|
268
|
+
/** @internal */
|
|
269
|
+
constructor(http, sandboxId, commands, files) {
|
|
270
|
+
this.http = http;
|
|
271
|
+
this.sandboxId = sandboxId;
|
|
272
|
+
this.commands = commands;
|
|
273
|
+
this.files = files;
|
|
274
|
+
}
|
|
275
|
+
http;
|
|
276
|
+
sandboxId;
|
|
277
|
+
commands;
|
|
278
|
+
files;
|
|
279
|
+
/**
|
|
280
|
+
* Starts the desktop and resolves once it runs; a running desktop is left as it is (its size too).
|
|
281
|
+
* On a template without the desktop it is installed first (about half a minute, once). `width` and
|
|
282
|
+
* `height` size the screen: 800-2560 x 600-1600, default 1280 x 800.
|
|
283
|
+
*/
|
|
284
|
+
async start(opts = {}) {
|
|
285
|
+
const size = {};
|
|
286
|
+
for (const [k, lo, hi] of [
|
|
287
|
+
["width", 800, 2560],
|
|
288
|
+
["height", 600, 1600]
|
|
289
|
+
]) {
|
|
290
|
+
const v = opts[k];
|
|
291
|
+
if (v === void 0) continue;
|
|
292
|
+
if (!Number.isInteger(v) || v < lo || v > hi) {
|
|
293
|
+
throw new InstaboxError(`${k} must be a whole number from ${lo} to ${hi}; got ${v}`, { code: "bad_request" });
|
|
294
|
+
}
|
|
295
|
+
size[k] = v;
|
|
296
|
+
}
|
|
297
|
+
let s = await this.call({ action: "start", ...size });
|
|
298
|
+
if (!s.installed) {
|
|
299
|
+
if (!s.installing) s = await this.call({ action: "install" });
|
|
300
|
+
const deadline = Date.now() + this.http.operationTimeoutMs;
|
|
301
|
+
while (!s.installed) {
|
|
302
|
+
if (s.failed) {
|
|
303
|
+
throw new InstaboxError(
|
|
304
|
+
`the desktop could not be installed: ${s.log ?? "see /tmp/instabox-desktop-install.log"}`,
|
|
305
|
+
{
|
|
306
|
+
code: "desktop_install_failed"
|
|
307
|
+
}
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
if (Date.now() > deadline) {
|
|
311
|
+
throw new InstaboxTimeoutError(`the desktop was not installed within ${this.http.operationTimeoutMs} ms`, {
|
|
312
|
+
code: "operation_timeout"
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
await sleep(this.http.pollIntervalMs * 8);
|
|
316
|
+
s = await this.call({ action: "status" });
|
|
317
|
+
}
|
|
318
|
+
s = await this.call({ action: "start", ...size });
|
|
319
|
+
}
|
|
320
|
+
if (!s.running) throw new InstaboxError("the desktop did not start", { code: "desktop_not_running" });
|
|
321
|
+
return this.status();
|
|
322
|
+
}
|
|
323
|
+
/** Whether the desktop runs, and its screen size. */
|
|
324
|
+
async status() {
|
|
325
|
+
const s = await this.call({ action: "status" });
|
|
326
|
+
const out = { installed: s.installed, running: s.running };
|
|
327
|
+
if (s.running) {
|
|
328
|
+
const [w, h] = (await this.xdo("getdisplaygeometry")).stdout.trim().split(/\s+/).map(Number);
|
|
329
|
+
if (Number.isInteger(w) && Number.isInteger(h)) Object.assign(out, { width: w, height: h });
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
/** A PNG of the whole screen. */
|
|
334
|
+
async screenshot() {
|
|
335
|
+
const path = `/tmp/instabox-screenshot-${randomSuffix()}.png`;
|
|
336
|
+
const p = shellQuote(path);
|
|
337
|
+
try {
|
|
338
|
+
await this.run(
|
|
339
|
+
`if command -v scrot >/dev/null; then scrot -o ${p}; elif command -v import >/dev/null; then import -window root png:${p}; else echo 'no screenshot tool in the sandbox (scrot or ImageMagick import)' >&2; exit 127; fi`
|
|
340
|
+
);
|
|
341
|
+
return await this.files.read(path, { format: "bytes", maxBytes: SCREENSHOT_MAX_BYTES });
|
|
342
|
+
} finally {
|
|
343
|
+
await this.commands.exec(`rm -f ${p}`).catch(() => {
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** Clicks at (x, y): the left button by default; `double` clicks twice. */
|
|
348
|
+
async click(x, y, opts = {}) {
|
|
349
|
+
const button = BUTTONS[opts.button ?? "left"];
|
|
350
|
+
if (!button)
|
|
351
|
+
throw new InstaboxError(`button must be left, right or middle; got ${opts.button}`, { code: "bad_request" });
|
|
352
|
+
const repeat = opts.double ? " --repeat 2 --delay 80" : "";
|
|
353
|
+
await this.xdo(`mousemove ${coord("x", x)} ${coord("y", y)} click${repeat} ${button}`);
|
|
354
|
+
}
|
|
355
|
+
/** Moves the pointer to (x, y). */
|
|
356
|
+
async move(x, y) {
|
|
357
|
+
await this.xdo(`mousemove ${coord("x", x)} ${coord("y", y)}`);
|
|
358
|
+
}
|
|
359
|
+
/** Drags with the left button from `from` to `to`, each `[x, y]`. */
|
|
360
|
+
async drag(from, to) {
|
|
361
|
+
await this.xdo(
|
|
362
|
+
`mousemove ${coord("x", from[0])} ${coord("y", from[1])} mousedown 1 sleep 0.1 mousemove ${coord("x", to[0])} ${coord("y", to[1])} sleep 0.1 mouseup 1`
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
/** Scrolls the wheel at the pointer, `amount` notches (default 3). */
|
|
366
|
+
async scroll(opts) {
|
|
367
|
+
const wheel = WHEEL[opts.direction];
|
|
368
|
+
const n = opts.amount ?? 3;
|
|
369
|
+
if (!wheel)
|
|
370
|
+
throw new InstaboxError(`direction must be up, down, left or right; got ${opts.direction}`, {
|
|
371
|
+
code: "bad_request"
|
|
372
|
+
});
|
|
373
|
+
if (!Number.isInteger(n) || n < 1 || n > 100) {
|
|
374
|
+
throw new InstaboxError(`amount must be a whole number from 1 to 100; got ${n}`, { code: "bad_request" });
|
|
375
|
+
}
|
|
376
|
+
await this.xdo(`click --repeat ${n} --delay 30 ${wheel}`);
|
|
377
|
+
}
|
|
378
|
+
/** Types `text` as is (quotes, newlines and Unicode included) into the focused window. */
|
|
379
|
+
async type(text, opts = {}) {
|
|
380
|
+
if (typeof text !== "string") throw new InstaboxError("text must be a string", { code: "bad_request" });
|
|
381
|
+
if (!text) return;
|
|
382
|
+
const delay = opts.delayMs ?? 12;
|
|
383
|
+
if (!Number.isInteger(delay) || delay < 0 || delay > 1e3) {
|
|
384
|
+
throw new InstaboxError(`delayMs must be a whole number from 0 to 1000; got ${delay}`, { code: "bad_request" });
|
|
385
|
+
}
|
|
386
|
+
await this.xdo(`type --delay ${delay} --file -`, text);
|
|
387
|
+
}
|
|
388
|
+
/** Presses a key (`'Enter'`, `'a'`, `'F5'`) or a chord (`['ctrl', 'l']`). */
|
|
389
|
+
async press(keys) {
|
|
390
|
+
const list = Array.isArray(keys) ? keys : [keys];
|
|
391
|
+
if (!list.length) throw new InstaboxError("press needs a key", { code: "bad_request" });
|
|
392
|
+
await this.xdo(`key -- ${shellQuote(list.map(keysym).join("+"))}`);
|
|
393
|
+
}
|
|
394
|
+
/** Opens `url` (http or https) in the desktop's browser. */
|
|
395
|
+
async open(url) {
|
|
396
|
+
let u;
|
|
397
|
+
try {
|
|
398
|
+
u = new URL(url);
|
|
399
|
+
} catch {
|
|
400
|
+
throw new InstaboxError(`invalid URL: ${url}`, { code: "bad_request" });
|
|
401
|
+
}
|
|
402
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
403
|
+
throw new InstaboxError(`only http and https URLs open in the browser; got ${u.protocol}`, {
|
|
404
|
+
code: "bad_request"
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
await this.run(
|
|
408
|
+
`b=$(command -v chromium || command -v chromium-browser || command -v google-chrome) || { echo 'no browser in the sandbox' >&2; exit 127; }; setsid nohup "$b" --no-first-run --no-default-browser-check --password-store=basic ${shellQuote(u.href)} >/dev/null 2>&1 </dev/null &`
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
/** Where the pointer is. */
|
|
412
|
+
async cursorPosition() {
|
|
413
|
+
const out = (await this.xdo("getmouselocation --shell")).stdout;
|
|
414
|
+
const x = Number(/^X=(\d+)/m.exec(out)?.[1]);
|
|
415
|
+
const y = Number(/^Y=(\d+)/m.exec(out)?.[1]);
|
|
416
|
+
if (!Number.isInteger(x) || !Number.isInteger(y)) {
|
|
417
|
+
throw new InstaboxError("could not read the pointer position", { code: "invalid_response" });
|
|
418
|
+
}
|
|
419
|
+
return { x, y };
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* A link that shows the desktop full-screen in a browser, for people without an instabox account:
|
|
423
|
+
* open it or embed it in an iframe. View-only by default (the server drops the viewer's input).
|
|
424
|
+
* `ttlSeconds`: 60 to 86 400, default 3 600. The expiry stops new connections only; a viewer already
|
|
425
|
+
* watching stays until they leave or `revokeStreamUrls()` is called.
|
|
426
|
+
*/
|
|
427
|
+
async streamUrl(opts = {}) {
|
|
428
|
+
const body = { viewOnly: opts.viewOnly ?? true };
|
|
429
|
+
if (opts.ttlSeconds !== void 0) {
|
|
430
|
+
if (!Number.isInteger(opts.ttlSeconds) || opts.ttlSeconds < 60 || opts.ttlSeconds > 86400) {
|
|
431
|
+
throw new InstaboxError(`ttlSeconds must be a whole number from 60 to 86 400; got ${opts.ttlSeconds}`, {
|
|
432
|
+
code: "bad_request"
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
body.ttlSeconds = opts.ttlSeconds;
|
|
436
|
+
}
|
|
437
|
+
const r = await this.http.request(
|
|
438
|
+
"POST",
|
|
439
|
+
`/v1/machines/${enc(this.sandboxId)}/desktop/stream`,
|
|
440
|
+
{ body }
|
|
441
|
+
);
|
|
442
|
+
return { url: r.url, expiresAt: new Date(r.expiresAt) };
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Revokes every link `streamUrl()` made for this sandbox: they stop working and open viewers are
|
|
446
|
+
* disconnected within a few seconds. Links made afterwards work.
|
|
447
|
+
*/
|
|
448
|
+
async revokeStreamUrls() {
|
|
449
|
+
await this.http.request("DELETE", `/v1/machines/${enc(this.sandboxId)}/desktop/stream`);
|
|
450
|
+
}
|
|
451
|
+
call(body) {
|
|
452
|
+
return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/desktop`, {
|
|
453
|
+
body,
|
|
454
|
+
timeoutMs: 9e4
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
/** Runs `xdotool <args>` on the desktop's display. */
|
|
458
|
+
xdo(args, stdin) {
|
|
459
|
+
return this.run(`xdotool ${args}`, stdin);
|
|
460
|
+
}
|
|
461
|
+
async run(cmd, stdin) {
|
|
462
|
+
const r = await this.commands.exec(
|
|
463
|
+
`export DISPLAY=${DESKTOP_DISPLAY}; ${cmd}`,
|
|
464
|
+
stdin === void 0 ? {} : { stdin }
|
|
465
|
+
);
|
|
466
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
467
|
+
return r;
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
|
|
214
471
|
// src/files.ts
|
|
215
472
|
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
216
473
|
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
@@ -223,18 +480,19 @@ var Files = class {
|
|
|
223
480
|
commands;
|
|
224
481
|
async read(path, opts = {}) {
|
|
225
482
|
const p = arg(path);
|
|
483
|
+
const limit = opts.maxBytes ?? MAX_FILE_BYTES;
|
|
226
484
|
const r = await this.commands.exec(
|
|
227
|
-
`[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${
|
|
485
|
+
`[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${limit} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
|
|
228
486
|
);
|
|
229
487
|
if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: "not_found" });
|
|
230
488
|
if (r.exitCode === 4) {
|
|
231
|
-
throw new InstaboxError(`${path} is larger than the ${
|
|
489
|
+
throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
|
|
232
490
|
code: "file_too_large"
|
|
233
491
|
});
|
|
234
492
|
}
|
|
235
493
|
ensureComplete(r);
|
|
236
494
|
const size = Number(r.stdout.trim());
|
|
237
|
-
if (!Number.isSafeInteger(size) || size < 0 || size >
|
|
495
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > limit) {
|
|
238
496
|
throw new InstaboxError("invalid file size returned by exec", { code: "invalid_response" });
|
|
239
497
|
}
|
|
240
498
|
const bytes = new Uint8Array(size);
|
|
@@ -503,7 +761,7 @@ function toSeconds(ms, field = "timeoutMs") {
|
|
|
503
761
|
return s;
|
|
504
762
|
}
|
|
505
763
|
var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
506
|
-
var
|
|
764
|
+
var enc2 = encodeURIComponent;
|
|
507
765
|
var Sandbox = class _Sandbox {
|
|
508
766
|
constructor(http, machine, opts = {}) {
|
|
509
767
|
this.http = http;
|
|
@@ -511,6 +769,7 @@ var Sandbox = class _Sandbox {
|
|
|
511
769
|
this.machine = machine;
|
|
512
770
|
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
513
771
|
this.files = new Files(this.commands);
|
|
772
|
+
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
514
773
|
}
|
|
515
774
|
http;
|
|
516
775
|
/** The machine ID (`m_...`). */
|
|
@@ -519,6 +778,8 @@ var Sandbox = class _Sandbox {
|
|
|
519
778
|
commands;
|
|
520
779
|
/** Read and write files. Needs a instabox server with the exec endpoint. */
|
|
521
780
|
files;
|
|
781
|
+
/** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
|
|
782
|
+
desktop;
|
|
522
783
|
machine;
|
|
523
784
|
static async create(a, b) {
|
|
524
785
|
const opts = (typeof a === "string" ? b : a) ?? {};
|
|
@@ -579,12 +840,12 @@ var Sandbox = class _Sandbox {
|
|
|
579
840
|
}
|
|
580
841
|
/** Fetches a snapshot by ID. Requires images:read. */
|
|
581
842
|
static async getSnapshot(snapshotId, opts = {}) {
|
|
582
|
-
return new HttpClient(opts).request("GET", `/v1/snapshots/${
|
|
843
|
+
return new HttpClient(opts).request("GET", `/v1/snapshots/${enc2(snapshotId)}`);
|
|
583
844
|
}
|
|
584
845
|
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
585
846
|
static async deleteSnapshot(snapshotId, opts = {}) {
|
|
586
847
|
try {
|
|
587
|
-
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${
|
|
848
|
+
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc2(snapshotId)}`);
|
|
588
849
|
return true;
|
|
589
850
|
} catch (err) {
|
|
590
851
|
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
@@ -599,7 +860,7 @@ var Sandbox = class _Sandbox {
|
|
|
599
860
|
async createSnapshot(opts) {
|
|
600
861
|
await this.settle();
|
|
601
862
|
await this.untilSynced();
|
|
602
|
-
return this.http.request("POST", `/v1/machines/${
|
|
863
|
+
return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/snapshots`, { body: opts });
|
|
603
864
|
}
|
|
604
865
|
/** Fetches the current state of the sandbox. */
|
|
605
866
|
async getInfo() {
|
|
@@ -613,20 +874,20 @@ var Sandbox = class _Sandbox {
|
|
|
613
874
|
async setTimeout(timeoutMs, opts = {}) {
|
|
614
875
|
const body = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) };
|
|
615
876
|
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
616
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
877
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, { body });
|
|
617
878
|
}
|
|
618
879
|
/**
|
|
619
880
|
* Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
|
|
620
881
|
* pause off. Unlike a timeout the setting stays across pause and resume.
|
|
621
882
|
*/
|
|
622
883
|
async setAutoSuspend(idleMs) {
|
|
623
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
884
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
|
|
624
885
|
body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
|
|
625
886
|
});
|
|
626
887
|
}
|
|
627
888
|
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
628
889
|
async setMetadata(metadata) {
|
|
629
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
890
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
|
|
630
891
|
body: { metadata }
|
|
631
892
|
});
|
|
632
893
|
}
|
|
@@ -636,21 +897,21 @@ var Sandbox = class _Sandbox {
|
|
|
636
897
|
* Throws `not_found` on a server without the Vault.
|
|
637
898
|
*/
|
|
638
899
|
async vault() {
|
|
639
|
-
return this.http.request("GET", `/v1/machines/${
|
|
900
|
+
return this.http.request("GET", `/v1/machines/${enc2(this.sandboxId)}/vault`);
|
|
640
901
|
}
|
|
641
902
|
/**
|
|
642
903
|
* Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
|
|
643
904
|
* and returns its record (`error` set when the guest refused it). Requires machines:write.
|
|
644
905
|
*/
|
|
645
906
|
async pushVault() {
|
|
646
|
-
return this.http.request("POST", `/v1/machines/${
|
|
907
|
+
return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/vault`);
|
|
647
908
|
}
|
|
648
909
|
/**
|
|
649
910
|
* Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
|
|
650
911
|
* what the Vault wrote and nothing is written again. Requires machines:write.
|
|
651
912
|
*/
|
|
652
913
|
async disableVault() {
|
|
653
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${
|
|
914
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
|
|
654
915
|
body: { vault: false }
|
|
655
916
|
});
|
|
656
917
|
}
|
|
@@ -678,34 +939,6 @@ var Sandbox = class _Sandbox {
|
|
|
678
939
|
if (this.machine.state === "suspended") await this.mutate("POST", "start");
|
|
679
940
|
await this.mutate("POST", "stop");
|
|
680
941
|
}
|
|
681
|
-
/** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
|
|
682
|
-
async fork(opts = {}) {
|
|
683
|
-
if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
|
|
684
|
-
if (opts.autoSuspendMs !== void 0) toIdleSeconds(opts.autoSuspendMs);
|
|
685
|
-
await this.settle();
|
|
686
|
-
if (this.machine.state !== "stopped") {
|
|
687
|
-
if (opts.stopSource === false) {
|
|
688
|
-
throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {
|
|
689
|
-
code: "operation_conflict"
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
|
-
await this.stop();
|
|
693
|
-
}
|
|
694
|
-
await this.untilSynced();
|
|
695
|
-
const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
|
|
696
|
-
if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
|
|
697
|
-
if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
|
|
698
|
-
if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
|
|
699
|
-
if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
|
|
700
|
-
if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
|
|
701
|
-
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
702
|
-
if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
|
|
703
|
-
if (opts.metadata) body.metadata = opts.metadata;
|
|
704
|
-
if (opts.vault === false) body.vault = false;
|
|
705
|
-
const op = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/fork`, { body });
|
|
706
|
-
const done = await this.http.waitForOperation(op);
|
|
707
|
-
return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
|
|
708
|
-
}
|
|
709
942
|
/** Deletes the sandbox and its disks. Returns false if it was already gone. */
|
|
710
943
|
async kill() {
|
|
711
944
|
return killMachine(this.http, this.sandboxId);
|
|
@@ -725,7 +958,7 @@ var Sandbox = class _Sandbox {
|
|
|
725
958
|
}
|
|
726
959
|
body.ttlSeconds = opts.ttlSeconds;
|
|
727
960
|
}
|
|
728
|
-
const c = await this.http.request("POST", `/v1/machines/${
|
|
961
|
+
const c = await this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/connections`, { body });
|
|
729
962
|
return {
|
|
730
963
|
host: c.host,
|
|
731
964
|
port: c.port,
|
|
@@ -744,7 +977,7 @@ var Sandbox = class _Sandbox {
|
|
|
744
977
|
async settle(refresh = true) {
|
|
745
978
|
if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
|
|
746
979
|
if (this.machine.operationId) {
|
|
747
|
-
const op = await this.http.request("GET", `/v1/operations/${
|
|
980
|
+
const op = await this.http.request("GET", `/v1/operations/${enc2(this.machine.operationId)}`);
|
|
748
981
|
await this.http.waitForOperation(op).catch(() => {
|
|
749
982
|
});
|
|
750
983
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
@@ -752,7 +985,7 @@ var Sandbox = class _Sandbox {
|
|
|
752
985
|
}
|
|
753
986
|
/**
|
|
754
987
|
* Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns
|
|
755
|
-
* once the host has the snapshot and uploads it after, so a
|
|
988
|
+
* once the host has the snapshot and uploads it after, so a snapshot right after a stop
|
|
756
989
|
* was refused ("not uploaded to object storage"), which took long enough after a pause and resume
|
|
757
990
|
* to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.
|
|
758
991
|
*/
|
|
@@ -772,17 +1005,17 @@ var Sandbox = class _Sandbox {
|
|
|
772
1005
|
}
|
|
773
1006
|
}
|
|
774
1007
|
async mutate(method, action) {
|
|
775
|
-
const op = await this.http.request(method, `/v1/machines/${
|
|
1008
|
+
const op = await this.http.request(method, `/v1/machines/${enc2(this.sandboxId)}/${action}`);
|
|
776
1009
|
await this.http.waitForOperation(op);
|
|
777
1010
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
778
1011
|
}
|
|
779
1012
|
};
|
|
780
1013
|
async function getMachine(http, id) {
|
|
781
|
-
return http.request("GET", `/v1/machines/${
|
|
1014
|
+
return http.request("GET", `/v1/machines/${enc2(id)}`);
|
|
782
1015
|
}
|
|
783
1016
|
async function killMachine(http, id) {
|
|
784
1017
|
try {
|
|
785
|
-
const op = await http.request("DELETE", `/v1/machines/${
|
|
1018
|
+
const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`);
|
|
786
1019
|
await http.waitForOperation(op);
|
|
787
1020
|
return true;
|
|
788
1021
|
} catch (err) {
|