@alineo-labs/opensandbox 0.2.0 → 0.3.1

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/dist/index.d.mts CHANGED
@@ -12,7 +12,7 @@ interface ImageSpec {
12
12
  uri: string;
13
13
  auth?: ImageAuth;
14
14
  }
15
- declare enum SandboxState {
15
+ export declare enum SandboxState {
16
16
  Pending = "Pending",
17
17
  Running = "Running",
18
18
  Pausing = "Pausing",
@@ -40,7 +40,15 @@ interface Sandbox {
40
40
  metadata?: Record<string, string>;
41
41
  platform?: unknown;
42
42
  }
43
- /** A single ordered rule in a `NetworkPolicy`. `target` is an FQDN or wildcard domain — no CIDR/IP targets yet. */
43
+ /**
44
+ * A single ordered rule in a `NetworkPolicy`. `target` is one of:
45
+ * - an FQDN (`"api.github.com"`) or wildcard domain (`"*.openai.com"`) — matched against the
46
+ * DNS query name;
47
+ * - a bare IPv4/IPv6 address (`"10.0.0.5"`) or CIDR block (`"10.0.0.0/8"`) — enforced at the
48
+ * nftables layer, so it only takes effect when the server runs `egress.mode = "dns+nft"`,
49
+ * and it gates raw-IP egress only. It does **not** authorize resolving a *domain* that
50
+ * happens to resolve into that range — use a domain rule for reach-by-name.
51
+ */
44
52
  interface NetworkRule {
45
53
  action: "allow" | "deny";
46
54
  target: string;
@@ -79,7 +87,7 @@ interface ListSandboxesOptions {
79
87
  limit?: number;
80
88
  offset?: number;
81
89
  }
82
- declare enum SnapshotState {
90
+ export declare enum SnapshotState {
83
91
  Pending = "Pending",
84
92
  Committing = "Committing",
85
93
  Pushing = "Pushing",
@@ -112,7 +120,7 @@ interface DiagnosticEvent {
112
120
  type: string;
113
121
  message: string;
114
122
  }
115
- declare enum SSEEventType {
123
+ export declare enum SSEEventType {
116
124
  Init = "init",
117
125
  Status = "status",
118
126
  Stdout = "stdout",
@@ -137,7 +145,7 @@ interface SSEEvent {
137
145
  execution_time?: number;
138
146
  timestamp: number;
139
147
  }
140
- declare enum CodeLanguage {
148
+ export declare enum CodeLanguage {
141
149
  Python = "python",
142
150
  JavaScript = "javascript",
143
151
  TypeScript = "typescript",
@@ -233,11 +241,15 @@ type PtyServerMessage = {
233
241
  };
234
242
  //#endregion
235
243
  //#region src/control.d.ts
236
- declare class OpenSandboxError extends Error {
244
+ export declare class OpenSandboxError extends Error {
237
245
  readonly status: number;
238
- constructor(message: string, status: number);
246
+ /** OpenSandbox's error code, e.g. `DOCKER::SANDBOX_NOT_FOUND`, when the response carried one. */
247
+ readonly code?: string | undefined;
248
+ constructor(message: string, status: number,
249
+ /** OpenSandbox's error code, e.g. `DOCKER::SANDBOX_NOT_FOUND`, when the response carried one. */
250
+ code?: string | undefined);
239
251
  }
240
- declare class ControlClient {
252
+ export declare class ControlClient {
241
253
  private baseUrl;
242
254
  private apiKey;
243
255
  private signal?;
@@ -265,8 +277,66 @@ declare class ControlClient {
265
277
  deleteSnapshot(id: string): Promise<void>;
266
278
  }
267
279
  //#endregion
280
+ //#region src/egress.d.ts
281
+ /** Thrown for a non-2xx response from the egress sidecar's policy API. */
282
+ export declare class EgressClientError extends Error {
283
+ readonly status: number;
284
+ constructor(message: string, status: number);
285
+ }
286
+ /** `GET /policy` response — the sidecar wraps the live policy in a status envelope. */
287
+ interface EgressPolicyStatus {
288
+ status?: string;
289
+ mode?: string;
290
+ enforcementMode?: string;
291
+ policy?: NetworkPolicy | null;
292
+ }
293
+ /**
294
+ * Talks directly to a sandbox's egress sidecar policy API (`PATCH`/`DELETE`/`GET /policy` on
295
+ * port `18080`), resolved the same way `VaultClient` resolves the Credential Vault — via
296
+ * `ControlClient.getEndpoint()`, against the sidecar's port instead of execd's `44772`.
297
+ *
298
+ * The policy API and the Credential Vault share one HTTP server and one auth check on the
299
+ * sidecar: an `alineo init` sidecar runs token-less, so the `getEndpoint()` headers are all
300
+ * that is needed. A hardened deployment that sets `OPENSANDBOX_EGRESS_TOKEN` would also need
301
+ * an `OPENSANDBOX-EGRESS-AUTH` header — not wired here yet.
302
+ *
303
+ * Wire shapes verified against `opensandbox-group/OpenSandbox`'s
304
+ * `components/egress/policy_server.go`:
305
+ * - `PATCH /policy` — body is a JSON **array** of `{ action, target }`; merge semantics
306
+ * (an incoming rule replaces a same-`target` rule, others untouched, `defaultAction` kept).
307
+ * - `DELETE /policy` — body is a JSON **array of target strings**; unmatched targets are
308
+ * silently ignored.
309
+ * - `GET /policy` — returns `{ status, mode, enforcementMode, policy }`.
310
+ *
311
+ * Egress policy is sidecar-local runtime state: it does not survive the sidecar restarting
312
+ * and is not restored by OpenSandbox's snapshot/checkpoint — `@alineo-labs/core` folds a
313
+ * `resume()`d sandbox's still-live changes back into its boot policy from the ledger. (A
314
+ * `fork()` does not carry them.)
315
+ */
316
+ export declare class EgressClient {
317
+ private readonly control;
318
+ private readonly useServerProxy?;
319
+ private static readonly PORT;
320
+ constructor(control: ControlClient, useServerProxy?: boolean | undefined);
321
+ private request;
322
+ /** Merge `rules` into the live policy — an incoming rule replaces any rule with the same `target`. */
323
+ patchRules(sandboxId: string, rules: NetworkRule[]): Promise<EgressPolicyStatus>;
324
+ /** Remove every rule whose `target` is in `targets`. Unknown targets are ignored. */
325
+ deleteRules(sandboxId: string, targets: string[]): Promise<EgressPolicyStatus>;
326
+ /** The live policy plus the sidecar's status envelope. */
327
+ getPolicy(sandboxId: string): Promise<EgressPolicyStatus>;
328
+ }
329
+ //#endregion
330
+ //#region src/egress-target.d.ts
331
+ /**
332
+ * Returns whether `target` is a plausible `NetworkRule.target`: an FQDN, a `*.`-prefixed
333
+ * wildcard domain, a bare IPv4/IPv6 address, or a CIDR block. Whitespace-only, URL-shaped
334
+ * (`http://…`), space-containing, or otherwise clearly-malformed strings return `false`.
335
+ */
336
+ export declare function isValidEgressTarget(target: string): boolean;
337
+ //#endregion
268
338
  //#region src/exec.d.ts
269
- declare class ExecClient {
339
+ export declare class ExecClient {
270
340
  private baseUrl;
271
341
  private accessToken;
272
342
  private signal?;
@@ -336,7 +406,7 @@ type PtyExitListener = (exitCode: number) => void;
336
406
  * callbacks, `write()`/`resize()`/`signal()` send input, `close()` tears
337
407
  * down the socket.
338
408
  */
339
- declare class PtyClient {
409
+ export declare class PtyClient {
340
410
  private readonly baseUrl;
341
411
  private readonly accessToken;
342
412
  private ws;
@@ -358,4 +428,4 @@ declare class PtyClient {
358
428
  close(): void;
359
429
  }
360
430
  //#endregion
361
- export { type CodeContext, CodeLanguage, type CommandStatus, ControlClient, type CreatePtyOptions, type CreatePtyResponse, type CreateSandboxOptions, type CreateSessionRequest, type CreateSessionResponse, type CredentialProxyConfig, type DiagnosticEvent, type DiagnosticLog, ExecClient, type ExecuteCodeOptions, type ExecuteCommandOptions, type FileInfo, type FileReplacement, type ImageAuth, type ImageSpec, type ListSandboxesOptions, type ListSnapshotsOptions, type Metrics, type NetworkPolicy, type NetworkRule, OpenSandboxError, PtyClient, type PtyClientMessage, type PtyExitListener, type PtyOutputListener, type PtyServerMessage, type Resources, type RunInSessionRequest, type SSEEvent, SSEEventType, type Sandbox, type SandboxEndpoint, SandboxState, type SandboxStatus, type Snapshot, SnapshotState };
431
+ export type { CodeContext, CommandStatus, CreatePtyOptions, CreatePtyResponse, CreateSandboxOptions, CreateSessionRequest, CreateSessionResponse, CredentialProxyConfig, DiagnosticEvent, DiagnosticLog, EgressPolicyStatus, ExecuteCodeOptions, ExecuteCommandOptions, FileInfo, FileReplacement, ImageAuth, ImageSpec, ListSandboxesOptions, ListSnapshotsOptions, Metrics, NetworkPolicy, NetworkRule, PtyClientMessage, PtyExitListener, PtyOutputListener, PtyServerMessage, Resources, RunInSessionRequest, SSEEvent, Sandbox, SandboxEndpoint, SandboxStatus, Snapshot };
package/dist/index.mjs CHANGED
@@ -9,12 +9,29 @@ function flattenSnapshot(raw) {
9
9
  }
10
10
  var OpenSandboxError = class extends Error {
11
11
  status;
12
- constructor(message, status) {
12
+ code;
13
+ constructor(message, status, code) {
13
14
  super(message);
14
15
  this.status = status;
16
+ this.code = code;
15
17
  this.name = "OpenSandboxError";
16
18
  }
17
19
  };
20
+ /**
21
+ * OpenSandbox answers an error with a JSON body, `{"code": "...", "message": "..."}`. Put the
22
+ * sentence in `message` (with the code after it), keep the code on `.code`, and fall back to the
23
+ * raw text when the body isn't that shape.
24
+ */
25
+ function errorFromBody(text, status) {
26
+ try {
27
+ const body = JSON.parse(text);
28
+ if (typeof body?.message === "string" && body.message) {
29
+ const code = typeof body.code === "string" && body.code ? body.code : void 0;
30
+ return new OpenSandboxError(code ? `${body.message} (${code})` : body.message, status, code);
31
+ }
32
+ } catch {}
33
+ return new OpenSandboxError(text || "OpenSandbox API error", status);
34
+ }
18
35
  var ControlClient = class ControlClient {
19
36
  baseUrl;
20
37
  apiKey;
@@ -42,7 +59,7 @@ var ControlClient = class ControlClient {
42
59
  ...body !== void 0 ? { body: JSON.stringify(body) } : {},
43
60
  signal: this.signal
44
61
  });
45
- if (!res.ok) throw new OpenSandboxError(await res.text().catch(() => "") || "OpenSandbox API error", res.status);
62
+ if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status);
46
63
  if (res.status === 204) return void 0;
47
64
  return res.json();
48
65
  }
@@ -101,6 +118,130 @@ var ControlClient = class ControlClient {
101
118
  }
102
119
  };
103
120
  //#endregion
121
+ //#region src/egress.ts
122
+ /** Thrown for a non-2xx response from the egress sidecar's policy API. */
123
+ var EgressClientError = class extends Error {
124
+ status;
125
+ constructor(message, status) {
126
+ super(message);
127
+ this.status = status;
128
+ this.name = "EgressClientError";
129
+ }
130
+ };
131
+ /**
132
+ * Talks directly to a sandbox's egress sidecar policy API (`PATCH`/`DELETE`/`GET /policy` on
133
+ * port `18080`), resolved the same way `VaultClient` resolves the Credential Vault — via
134
+ * `ControlClient.getEndpoint()`, against the sidecar's port instead of execd's `44772`.
135
+ *
136
+ * The policy API and the Credential Vault share one HTTP server and one auth check on the
137
+ * sidecar: an `alineo init` sidecar runs token-less, so the `getEndpoint()` headers are all
138
+ * that is needed. A hardened deployment that sets `OPENSANDBOX_EGRESS_TOKEN` would also need
139
+ * an `OPENSANDBOX-EGRESS-AUTH` header — not wired here yet.
140
+ *
141
+ * Wire shapes verified against `opensandbox-group/OpenSandbox`'s
142
+ * `components/egress/policy_server.go`:
143
+ * - `PATCH /policy` — body is a JSON **array** of `{ action, target }`; merge semantics
144
+ * (an incoming rule replaces a same-`target` rule, others untouched, `defaultAction` kept).
145
+ * - `DELETE /policy` — body is a JSON **array of target strings**; unmatched targets are
146
+ * silently ignored.
147
+ * - `GET /policy` — returns `{ status, mode, enforcementMode, policy }`.
148
+ *
149
+ * Egress policy is sidecar-local runtime state: it does not survive the sidecar restarting
150
+ * and is not restored by OpenSandbox's snapshot/checkpoint — `@alineo-labs/core` folds a
151
+ * `resume()`d sandbox's still-live changes back into its boot policy from the ledger. (A
152
+ * `fork()` does not carry them.)
153
+ */
154
+ var EgressClient = class EgressClient {
155
+ control;
156
+ useServerProxy;
157
+ static PORT = 18080;
158
+ constructor(control, useServerProxy) {
159
+ this.control = control;
160
+ this.useServerProxy = useServerProxy;
161
+ }
162
+ async request(sandboxId, method, body) {
163
+ const ep = await this.control.getEndpoint(sandboxId, EgressClient.PORT, this.useServerProxy);
164
+ const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
165
+ const init = {
166
+ method,
167
+ headers: {
168
+ ...ep.headers,
169
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
170
+ },
171
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
172
+ };
173
+ const delaysMs = [
174
+ 0,
175
+ 300,
176
+ 600,
177
+ 1200,
178
+ 2400
179
+ ];
180
+ let lastErr;
181
+ for (const delay of delaysMs) {
182
+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));
183
+ const res = await fetch(`${baseUrl}/policy`, init);
184
+ if (res.ok) {
185
+ if (res.status === 204) return void 0;
186
+ const text = await res.text();
187
+ return text ? JSON.parse(text) : void 0;
188
+ }
189
+ lastErr = new EgressClientError(await res.text().catch(() => "") || "egress policy API error", res.status);
190
+ if (res.status !== 500 && res.status !== 502 && res.status !== 412) throw lastErr;
191
+ }
192
+ throw lastErr ?? new EgressClientError("egress policy API error", 500);
193
+ }
194
+ /** Merge `rules` into the live policy — an incoming rule replaces any rule with the same `target`. */
195
+ patchRules(sandboxId, rules) {
196
+ return this.request(sandboxId, "PATCH", rules);
197
+ }
198
+ /** Remove every rule whose `target` is in `targets`. Unknown targets are ignored. */
199
+ deleteRules(sandboxId, targets) {
200
+ return this.request(sandboxId, "DELETE", targets);
201
+ }
202
+ /** The live policy plus the sidecar's status envelope. */
203
+ getPolicy(sandboxId) {
204
+ return this.request(sandboxId, "GET");
205
+ }
206
+ };
207
+ //#endregion
208
+ //#region src/egress-target.ts
209
+ const IPV4_OCTET = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
210
+ const ipv4Re = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`);
211
+ const ipv6Re = /^(?=.*:)[0-9a-fA-F:]*(?::(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3})?$/;
212
+ /** A single DNS label: alphanumeric plus internal hyphens, 1–63 chars. */
213
+ const LABEL = "(?!-)[A-Za-z0-9-]{1,63}(?<!-)";
214
+ const domainRe = new RegExp(`^(\\*\\.)?(${LABEL}\\.)*${LABEL}\\.?$`);
215
+ function isIpv6(s) {
216
+ return (s.includes("::") || (s.match(/:/g)?.length ?? 0) >= 2) && ipv6Re.test(s);
217
+ }
218
+ function isIpAddress(s) {
219
+ return ipv4Re.test(s) || isIpv6(s);
220
+ }
221
+ function isCidr(s) {
222
+ const slash = s.lastIndexOf("/");
223
+ if (slash === -1) return false;
224
+ const addr = s.slice(0, slash);
225
+ const bits = s.slice(slash + 1);
226
+ if (!/^\d{1,3}$/.test(bits)) return false;
227
+ const n = Number(bits);
228
+ if (ipv4Re.test(addr)) return n <= 32;
229
+ if (isIpv6(addr)) return n <= 128;
230
+ return false;
231
+ }
232
+ /**
233
+ * Returns whether `target` is a plausible `NetworkRule.target`: an FQDN, a `*.`-prefixed
234
+ * wildcard domain, a bare IPv4/IPv6 address, or a CIDR block. Whitespace-only, URL-shaped
235
+ * (`http://…`), space-containing, or otherwise clearly-malformed strings return `false`.
236
+ */
237
+ function isValidEgressTarget(target) {
238
+ const t = target.trim();
239
+ if (t === "" || /\s/.test(t) || t.includes("/") !== isCidr(t)) return false;
240
+ if (isIpAddress(t)) return true;
241
+ if (isCidr(t)) return true;
242
+ return domainRe.test(t);
243
+ }
244
+ //#endregion
104
245
  //#region src/types.ts
105
246
  let SandboxState = /* @__PURE__ */ function(SandboxState) {
106
247
  SandboxState["Pending"] = "Pending";
@@ -493,4 +634,4 @@ var PtyClient = class {
493
634
  }
494
635
  };
495
636
  //#endregion
496
- export { CodeLanguage, ControlClient, ExecClient, OpenSandboxError, PtyClient, SSEEventType, SandboxState, SnapshotState };
637
+ export { CodeLanguage, ControlClient, EgressClient, EgressClientError, ExecClient, OpenSandboxError, PtyClient, SSEEventType, SandboxState, SnapshotState, isValidEgressTarget };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alineo-labs/opensandbox",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,9 +30,9 @@
30
30
  "test:watch": "vitest"
31
31
  },
32
32
  "devDependencies": {
33
- "bun-types": "1.3.14",
34
- "tsdown": "0.22.3",
33
+ "bun-types": "1.4.2",
34
+ "tsdown": "0.23.0",
35
35
  "typescript": "6.0.3",
36
- "vitest": "4.1.9"
36
+ "vitest": "5.0.0"
37
37
  }
38
38
  }