@insforge/instabox-sdk 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -32,14 +32,14 @@ The key is sent as the `X-API-Key` header.
32
32
 
33
33
  ### Scopes
34
34
 
35
- | Scope | Allows |
36
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
37
- | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault` |
38
- | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials` |
39
- | `machines:delete` | `kill` |
40
- | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
41
- | `images:write` | `createSnapshot` |
42
- | `images:delete` | `deleteSnapshot` |
35
+ | Scope | Allows |
36
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
37
+ | `machines:read` | `Sandbox.list`, `getInfo`, `isRunning`, `vault`, `ports.list` |
38
+ | `machines:write` | `create`, `connect` (resume), `pause`, `resume`, `stop`, `setAutoSuspend`, `setMetadata`, `disableVault`, `pushVault`, `commands`, `files`, `sshCredentials`, `ports.publish`, `ports.unpublish` |
39
+ | `machines:delete` | `kill` |
40
+ | `images:read` | Resolve private snapshot names, `listSnapshots`, `getSnapshot` |
41
+ | `images:write` | `createSnapshot` |
42
+ | `images:delete` | `deleteSnapshot` |
43
43
 
44
44
  `: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`).
45
45
 
@@ -372,6 +372,21 @@ async function onCancel(userId: string) {
372
372
 
373
373
  The desktop must be running when the link is opened: a link to a paused sandbox does not wake it, so `connect()` before you hand it out. An open viewer does not count as activity, so with the default idle pause a sandbox someone only watches still pauses after 30 idle minutes. Each open viewer counts toward your account's limit of open terminals and desktops (8 unless we raised it for you). Keep `vault: false` for sandboxes your users can use: anything running in one can read what the Vault writes.
374
374
 
375
+ ## Ports: a URL for a server in the sandbox
376
+
377
+ `sandbox.ports` gives a server listening in the sandbox an HTTPS URL, as `instabox port publish` does. WebSockets and streaming responses pass through.
378
+
379
+ ```ts
380
+ const { url } = await sandbox.ports.publish(3000) // https://3000-<id>.instabox.tech on the hosted service
381
+ const web = await sandbox.ports.publish(8080, { name: 'web', access: 'private' })
382
+ console.log(web.tokenUrl) // the URL with ?_token=ibp_..., the link to share
383
+ await sandbox.ports.publish(8080, { access: 'private', rotateToken: true }) // new token, the old one stops working
384
+ await sandbox.ports.list() // [{ port, name, protocol, url, access, createdAt }]
385
+ await sandbox.ports.unpublish(3000) // false if it was not published
386
+ ```
387
+
388
+ A port stays published until you unpublish it, and publishing it again keeps its URL. The URL answers while the sandbox runs. Ports run from 1024 to 65535, except the desktop's and Orca's control ports. A new port is public: anyone with the URL reaches it. A private port answers only requests that carry its token, as the link's `_token` parameter (the browser then keeps it in a cookie) or an `Authorization: Bearer` header. Only the publish that creates or rotates a token returns it. The domain is the server's, so use the returned `url` instead of building one. Publishing and unpublishing need `machines:write`, listing needs `machines:read`.
389
+
375
390
  ## Metrics and usage
376
391
 
377
392
  ```ts
@@ -422,6 +437,7 @@ Reads, and mutations (which always carry an `Idempotency-Key`), are retried up t
422
437
  - At most 32 requests per user run at once, across all your sandboxes. Commands, file reads, desktop, port-forward and vault-push calls share this limit. A `background: true` command counts only while it starts; each `wait()` holds one while it waits (it polls the job's log, up to 25 seconds per request). More throw `InstaboxQuotaError` (429, retryable).
423
438
  - A command started with `run` runs for at most 10 minutes; longer ones need `background: true`. A background command takes no `stdin`, and its stdout and stderr share one log.
424
439
  - A file moves at up to 5 GiB per `write` (the server's limit) in one request; the CLI's `instabox push` splits a file of 64 MiB or more into 4 parallel uploads, which the SDK does not do yet.
440
+ - Published ports serve at most 128 requests at once per account, across all its sandboxes. Open WebSockets and streams count until they close. A request over the limit waits up to 2 seconds for a slot, then gets `429`.
425
441
 
426
442
  ## Agent skill
427
443
 
@@ -449,4 +465,10 @@ git tag v0.4.0 && git push origin v0.4.0
449
465
  The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
450
466
  checks and publishes through npm trusted publishing (OIDC): no token is stored anywhere. Once, a maintainer
451
467
  adds the trusted publisher on npmjs.com (the package's Settings, Trusted Publisher, GitHub Actions: organization
452
- `InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment).
468
+ `InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment) with **Allow npm dist-tag** on.
469
+
470
+ The new version is published under the `staging` dist-tag. `latest` (`next` for a prerelease) moves to it only
471
+ once its tarball downloads and installs from a clean cache, which can take a few minutes after the publish
472
+ (`scripts/npm-promote-latest.sh`, at most 15 minutes). If it never installs in that time, or npm refuses the
473
+ dist-tag, `latest` stays on the previous version and the run fails; re-run it once npm serves the tarball and it
474
+ promotes the version without publishing it again. `npm view @insforge/instabox-sdk dist-tags` shows both tags.
package/dist/index.cjs CHANGED
@@ -47,6 +47,7 @@ __export(index_exports, {
47
47
  MAX_FILE_BYTES: () => MAX_FILE_BYTES,
48
48
  MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
49
49
  MAX_UPLOAD_BYTES: () => MAX_UPLOAD_BYTES,
50
+ Ports: () => Ports,
50
51
  Sandbox: () => Sandbox,
51
52
  isLimitCode: () => isLimitCode
52
53
  });
@@ -2495,6 +2496,69 @@ var HttpClient = class {
2495
2496
  }
2496
2497
  };
2497
2498
 
2499
+ // src/ports.ts
2500
+ var enc3 = encodeURIComponent;
2501
+ function checkPort(port) {
2502
+ if (!Number.isInteger(port)) {
2503
+ throw new InstaboxError(`port must be a whole number; got ${port}`, { code: "bad_request" });
2504
+ }
2505
+ return port;
2506
+ }
2507
+ function fromServer(p) {
2508
+ const out = {
2509
+ port: p.port,
2510
+ name: p.name,
2511
+ protocol: p.protocol,
2512
+ url: p.url,
2513
+ access: p.access,
2514
+ createdAt: new Date(p.createdAt)
2515
+ };
2516
+ if (p.token) {
2517
+ out.token = p.token;
2518
+ out.tokenUrl = p.tokenUrl;
2519
+ }
2520
+ return out;
2521
+ }
2522
+ var Ports = class {
2523
+ /** @internal */
2524
+ constructor(http, sandboxId) {
2525
+ this.http = http;
2526
+ this.sandboxId = sandboxId;
2527
+ }
2528
+ http;
2529
+ sandboxId;
2530
+ /**
2531
+ * Publishes `port` (1024-65535) until `unpublish()`; publishing it again keeps its URL. The URL answers
2532
+ * while the sandbox runs, WebSockets included. Requires machines:write.
2533
+ */
2534
+ async publish(port, opts = {}) {
2535
+ const body = { port: checkPort(port) };
2536
+ if (opts.name !== void 0) body.name = opts.name;
2537
+ if (opts.access !== void 0) body.access = opts.access;
2538
+ if (opts.rotateToken) body.rotateToken = true;
2539
+ const r = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/ports`, { body });
2540
+ return fromServer(r);
2541
+ }
2542
+ /** The sandbox's published ports. Tokens are not included. Requires machines:read. */
2543
+ async list() {
2544
+ const r = await this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/ports`);
2545
+ return r.ports.map(fromServer);
2546
+ }
2547
+ /**
2548
+ * Removes the port's URL and closes its open connections. Returns false if the port was not published.
2549
+ * Requires machines:write.
2550
+ */
2551
+ async unpublish(port) {
2552
+ try {
2553
+ await this.http.request("DELETE", `/v1/machines/${enc3(this.sandboxId)}/ports/${checkPort(port)}`);
2554
+ return true;
2555
+ } catch (err) {
2556
+ if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
2557
+ throw err;
2558
+ }
2559
+ }
2560
+ };
2561
+
2498
2562
  // src/sandbox.ts
2499
2563
  var DEFAULT_TEMPLATE = "agent-browser";
2500
2564
  var FALLBACK_TEMPLATE = "universal";
@@ -2540,7 +2604,7 @@ function toSeconds(ms, field) {
2540
2604
  return s;
2541
2605
  }
2542
2606
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
2543
- var enc3 = encodeURIComponent;
2607
+ var enc4 = encodeURIComponent;
2544
2608
  var Sandbox = class _Sandbox {
2545
2609
  constructor(http, machine, opts = {}) {
2546
2610
  this.http = http;
@@ -2550,6 +2614,7 @@ var Sandbox = class _Sandbox {
2550
2614
  this.files = new Files(this.commands, http, machine.id);
2551
2615
  this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
2552
2616
  this.desktop = new Desktop(http, machine.id, this.commands, this.files);
2617
+ this.ports = new Ports(http, machine.id);
2553
2618
  }
2554
2619
  http;
2555
2620
  /** The machine ID (`m_...`). */
@@ -2560,6 +2625,8 @@ var Sandbox = class _Sandbox {
2560
2625
  files;
2561
2626
  /** See and control the sandbox's graphical desktop (screenshots, mouse, keyboard, a link to watch it). */
2562
2627
  desktop;
2628
+ /** Publish a port at an HTTPS URL, list published ports, unpublish them. */
2629
+ ports;
2563
2630
  machine;
2564
2631
  static async create(a, b) {
2565
2632
  const opts = (typeof a === "string" ? b : a) ?? {};
@@ -2639,12 +2706,12 @@ var Sandbox = class _Sandbox {
2639
2706
  }
2640
2707
  /** Fetches a snapshot by ID. Requires images:read. */
2641
2708
  static async getSnapshot(snapshotId, opts = {}) {
2642
- return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
2709
+ return new HttpClient(opts).request("GET", `/v1/snapshots/${enc4(snapshotId)}`);
2643
2710
  }
2644
2711
  /** Deletes a snapshot. Returns false if absent. Requires images:delete. */
2645
2712
  static async deleteSnapshot(snapshotId, opts = {}) {
2646
2713
  try {
2647
- await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
2714
+ await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc4(snapshotId)}`);
2648
2715
  return true;
2649
2716
  } catch (err) {
2650
2717
  if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
@@ -2659,7 +2726,7 @@ var Sandbox = class _Sandbox {
2659
2726
  async createSnapshot(opts) {
2660
2727
  await this.settle();
2661
2728
  await this.untilSynced();
2662
- return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
2729
+ return this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/snapshots`, { body: opts });
2663
2730
  }
2664
2731
  /** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
2665
2732
  async getMetrics(opts = {}) {
@@ -2679,7 +2746,7 @@ var Sandbox = class _Sandbox {
2679
2746
  * pause off. The setting stays across pause and resume.
2680
2747
  */
2681
2748
  async setAutoSuspend(idleMs) {
2682
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2749
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2683
2750
  body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
2684
2751
  });
2685
2752
  }
@@ -2693,7 +2760,7 @@ var Sandbox = class _Sandbox {
2693
2760
  }
2694
2761
  /** Replaces the sandbox's metadata (`{}` clears it). */
2695
2762
  async setMetadata(metadata) {
2696
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2763
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2697
2764
  body: { metadata }
2698
2765
  });
2699
2766
  }
@@ -2703,21 +2770,21 @@ var Sandbox = class _Sandbox {
2703
2770
  * Throws `not_found` on a server without the Vault.
2704
2771
  */
2705
2772
  async vault() {
2706
- return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
2773
+ return this.http.request("GET", `/v1/machines/${enc4(this.sandboxId)}/vault`);
2707
2774
  }
2708
2775
  /**
2709
2776
  * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
2710
2777
  * and returns its record (`error` set when the guest refused it). Requires machines:write.
2711
2778
  */
2712
2779
  async pushVault() {
2713
- return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
2780
+ return this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/vault`);
2714
2781
  }
2715
2782
  /**
2716
2783
  * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
2717
2784
  * what the Vault wrote and nothing is written again. Requires machines:write.
2718
2785
  */
2719
2786
  async disableVault() {
2720
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
2787
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
2721
2788
  body: { vault: false }
2722
2789
  });
2723
2790
  }
@@ -2764,7 +2831,7 @@ var Sandbox = class _Sandbox {
2764
2831
  }
2765
2832
  body.ttlSeconds = opts.ttlSeconds;
2766
2833
  }
2767
- const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
2834
+ const c = await this.http.request("POST", `/v1/machines/${enc4(this.sandboxId)}/connections`, { body });
2768
2835
  return {
2769
2836
  host: c.host,
2770
2837
  port: c.port,
@@ -2783,7 +2850,7 @@ var Sandbox = class _Sandbox {
2783
2850
  async settle(refresh = true) {
2784
2851
  if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
2785
2852
  if (this.machine.operationId) {
2786
- const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
2853
+ const op = await this.http.request("GET", `/v1/operations/${enc4(this.machine.operationId)}`);
2787
2854
  await this.http.waitForOperation(op).catch(() => {
2788
2855
  });
2789
2856
  this.machine = await getMachine(this.http, this.sandboxId);
@@ -2811,29 +2878,29 @@ var Sandbox = class _Sandbox {
2811
2878
  }
2812
2879
  }
2813
2880
  async mutate(method, action) {
2814
- const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
2881
+ const op = await this.http.request(method, `/v1/machines/${enc4(this.sandboxId)}/${action}`);
2815
2882
  await this.http.waitForOperation(op);
2816
2883
  this.machine = await getMachine(this.http, this.sandboxId);
2817
2884
  }
2818
2885
  };
2819
2886
  async function getMachine(http, id) {
2820
- return http.request("GET", `/v1/machines/${enc3(id)}`);
2887
+ return http.request("GET", `/v1/machines/${enc4(id)}`);
2821
2888
  }
2822
2889
  async function getMetrics(http, id, opts) {
2823
- const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
2890
+ const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2824
2891
  query: { since: opts.since?.toISOString() }
2825
2892
  });
2826
2893
  return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
2827
2894
  }
2828
2895
  async function getUsage(http, id, opts) {
2829
- const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
2896
+ const u = await http.request("GET", `/v1/machines/${enc4(id)}/usage`, {
2830
2897
  query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
2831
2898
  });
2832
2899
  return { ...u, from: new Date(u.from), to: new Date(u.to) };
2833
2900
  }
2834
2901
  async function killMachine(http, id) {
2835
2902
  try {
2836
- const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
2903
+ const op = await http.request("DELETE", `/v1/machines/${enc4(id)}`, {
2837
2904
  headers: { "X-Confirm-Delete": id }
2838
2905
  });
2839
2906
  await http.waitForOperation(op);