@keska/sandbox 0.49.0 → 0.50.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/dist/index.d.ts CHANGED
@@ -5315,6 +5315,16 @@ declare class GuestHttp$1 {
5315
5315
  websocket(path?: string): Promise<WebSocket>;
5316
5316
  }
5317
5317
 
5318
+ /** Exchange a login JWT for one Matrix device. The homeserver follows the control plane. */
5319
+ /** One Matrix access token. It is one device for one person. */
5320
+ type MatrixToken = {
5321
+ accessToken: string;
5322
+ userId: string;
5323
+ deviceId: string;
5324
+ expiresAt: string;
5325
+ homeserver: string;
5326
+ };
5327
+
5318
5328
  type TimeoutOpts = {
5319
5329
  timeout?: number;
5320
5330
  signal?: AbortSignal;
@@ -6299,6 +6309,7 @@ declare class Agents {
6299
6309
  create(name: string, opts?: {
6300
6310
  template?: string;
6301
6311
  messaging?: boolean;
6312
+ user?: User | string;
6302
6313
  userId?: string;
6303
6314
  displayName?: string;
6304
6315
  timeout?: Timeout;
@@ -6360,6 +6371,13 @@ declare class User {
6360
6371
  newToken(opts?: {
6361
6372
  timeout?: Timeout;
6362
6373
  }): Promise<LoginToken>;
6374
+ /**
6375
+ * Matrix access token for this person.
6376
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
6377
+ */
6378
+ matrixToken(opts?: {
6379
+ deviceId?: string;
6380
+ }): Promise<MatrixToken>;
6363
6381
  /** Sign this person out of every device. */
6364
6382
  revoke(opts?: {
6365
6383
  timeout?: Timeout;
@@ -6431,6 +6449,13 @@ declare class Client {
6431
6449
  newToken(opts?: {
6432
6450
  timeout?: Timeout;
6433
6451
  }): Promise<LoginToken>;
6452
+ /**
6453
+ * Matrix access token for the API caller.
6454
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
6455
+ */
6456
+ matrixToken(opts?: {
6457
+ deviceId?: string;
6458
+ }): Promise<MatrixToken>;
6434
6459
  /** Close the connection. */
6435
6460
  close(): void;
6436
6461
  /** `using` calls this. */
@@ -6867,14 +6892,11 @@ declare class Sandbox {
6867
6892
  private exec;
6868
6893
  /** Run one shell string with `/bin/sh -c`. */
6869
6894
  sh(command: string, opts?: Parameters<Sandbox["run"]>[1]): Promise<ExecResult>;
6870
- /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
6895
+ /** Start a command and return its handle. The process runs until it exits. */
6871
6896
  start(argv: string[], opts?: {
6872
6897
  env?: Record<string, string>;
6873
6898
  cwd?: string;
6874
- timeout?: Timeout;
6875
6899
  name?: string;
6876
- keepAlive?: boolean;
6877
- endsSandbox?: boolean;
6878
6900
  }): Promise<ProcessHandle>;
6879
6901
  /** Copy this sandbox's writable layer into new sandboxes. */
6880
6902
  clone(opts?: {
@@ -7045,4 +7067,4 @@ type GuestResponse = GuestResponse$1;
7045
7067
 
7046
7068
  declare const publicExports: readonly ["Agent", "Template", "AuthenticationError", "CapacityError", "Client", "CommandFailedError", "CommandTimeoutError", "CommandTooLargeError", "ConflictError", "DirectoryNotEmptyError", "ExecutableNotFoundError", "FileExistsError", "FileTooLargeError", "GuestRuntimeDeadError", "ImageTimeoutError", "InvalidArgumentError", "InvalidPathError", "Mkdir", "UNLIMITED", "NameTakenError", "NotFoundError", "Page", "PathNotFoundError", "PageExhaustedError", "PermissionDeniedError", "PortNotOpenError", "ProcessHandle", "Profile", "ResourceInUseError", "ResourcePolicy", "SecurityPolicy", "ProcessNotFoundError", "ProcessWaitTimeoutError", "Remove", "Sandbox", "SandboxConflictError", "SandboxError", "SandboxNotFoundError", "SandboxNotReadyError", "SandboxSleepingError", "SandboxStateError", "LogStream", "SandboxStatus", "SandboxWaitTimeoutError", "SandboxTimeoutError", "TimeoutError", "UnavailableError", "Write", "mkdir", "publicExports", "remove", "write"];
7047
7069
 
7048
- export { Agent, AuthenticationError, CapacityError, Client, type ClientOptions, CommandFailedError, CommandTimeoutError, CommandTooLargeError, ConflictError, DirectoryNotEmptyError, type ExecBytesResult, type ExecResult, ExecutableNotFoundError, FileExistsError, type FileInfo, type FileList, FileTooLargeError, type GuestHttp, type GuestResponse, GuestRuntimeDeadError, type HTTPGrant, type Image, type ImageKind, ImageTimeoutError, InvalidArgumentError, InvalidPathError, type LogEntry, LogStream, Mkdir, NameTakenError, NotFoundError, Page, PageExhaustedError, PathNotFoundError, PermissionDeniedError, PortNotOpenError, type Process, ProcessHandle, ProcessNotFoundError, ProcessWaitTimeoutError, Profile, Remove, ResourceInUseError, ResourcePolicy, type Resources, Sandbox, SandboxConflictError, type SandboxCreateParams, SandboxError, type SandboxInfo, SandboxNotFoundError, SandboxNotReadyError, type SandboxRow, SandboxSleepingError, SandboxStateError, SandboxStatus, SandboxTimeoutError, SandboxWaitTimeoutError, type Secret, SecurityPolicy, type Snapshot, type StreamChunk, Template, TimeoutError, UNLIMITED, UnavailableError, type Volume, Write, mkdir, publicExports, remove, write };
7070
+ export { Agent, AuthenticationError, CapacityError, Client, type ClientOptions, CommandFailedError, CommandTimeoutError, CommandTooLargeError, ConflictError, DirectoryNotEmptyError, type ExecBytesResult, type ExecResult, ExecutableNotFoundError, FileExistsError, type FileInfo, type FileList, FileTooLargeError, type GuestHttp, type GuestResponse, GuestRuntimeDeadError, type HTTPGrant, type Image, type ImageKind, ImageTimeoutError, InvalidArgumentError, InvalidPathError, type LogEntry, LogStream, type MatrixToken, Mkdir, NameTakenError, NotFoundError, Page, PageExhaustedError, PathNotFoundError, PermissionDeniedError, PortNotOpenError, type Process, ProcessHandle, ProcessNotFoundError, ProcessWaitTimeoutError, Profile, Remove, ResourceInUseError, ResourcePolicy, type Resources, Sandbox, SandboxConflictError, type SandboxCreateParams, SandboxError, type SandboxInfo, SandboxNotFoundError, SandboxNotReadyError, type SandboxRow, SandboxSleepingError, SandboxStateError, SandboxStatus, SandboxTimeoutError, SandboxWaitTimeoutError, type Secret, SecurityPolicy, type Snapshot, type StreamChunk, Template, TimeoutError, UNLIMITED, UnavailableError, type Volume, Write, mkdir, publicExports, remove, write };
package/dist/index.js CHANGED
@@ -4122,6 +4122,73 @@ var Client = class {
4122
4122
  }
4123
4123
  };
4124
4124
 
4125
+ // src/matrixToken.ts
4126
+ var TOKEN_MS = 36e5;
4127
+ var HOMESERVERS = {
4128
+ "numenbox.keska.dev": "https://numen-matrix.keska.dev",
4129
+ "numenbox.keska.io": "https://numen-matrix.keska.io"
4130
+ };
4131
+ function matrixHomeserver(baseUrl) {
4132
+ let host = "";
4133
+ try {
4134
+ host = new URL(baseUrl).hostname;
4135
+ } catch {
4136
+ host = "";
4137
+ }
4138
+ const homeserver = HOMESERVERS[host];
4139
+ if (!homeserver) {
4140
+ throw new InvalidArgumentError(`no matrix homeserver for ${host || baseUrl}`, {
4141
+ code: "invalid_argument",
4142
+ reason: "HOMESERVER_UNKNOWN"
4143
+ });
4144
+ }
4145
+ return homeserver;
4146
+ }
4147
+ async function openMatrixToken(baseUrl, mint, opts, doFetch = fetch) {
4148
+ const homeserver = matrixHomeserver(baseUrl);
4149
+ const deviceId = opts?.deviceId || crypto.randomUUID();
4150
+ const jwt = await mint();
4151
+ const url = `${homeserver}/_matrix/client/v3/login`;
4152
+ let res;
4153
+ try {
4154
+ res = await doFetch(url, {
4155
+ method: "POST",
4156
+ headers: { "content-type": "application/json" },
4157
+ body: JSON.stringify({ type: "org.matrix.login.jwt", token: jwt, device_id: deviceId })
4158
+ });
4159
+ } catch (error) {
4160
+ throw new SandboxError(`matrix login ${error instanceof Error ? error.message : "failed"}`, {
4161
+ code: "unavailable",
4162
+ reason: "UNAVAILABLE"
4163
+ });
4164
+ }
4165
+ if (res.status === 401 || res.status === 403) {
4166
+ throw new AuthenticationError("matrix login refused", { code: "unauthenticated", reason: "UNAUTHENTICATED" });
4167
+ }
4168
+ if (!res.ok) throw new SandboxError(`matrix login ${res.status}`);
4169
+ const body = await res.json();
4170
+ if (!body.access_token || !body.user_id) {
4171
+ throw new AuthenticationError("matrix login returned no token", {
4172
+ code: "unauthenticated",
4173
+ reason: "UNAUTHENTICATED"
4174
+ });
4175
+ }
4176
+ if (body.device_id && body.device_id !== deviceId) {
4177
+ throw new AuthenticationError("matrix login changed the device", {
4178
+ code: "unauthenticated",
4179
+ reason: "UNAUTHENTICATED"
4180
+ });
4181
+ }
4182
+ const expiresInMs = body.expires_in_ms ?? TOKEN_MS;
4183
+ return {
4184
+ accessToken: body.access_token,
4185
+ userId: body.user_id,
4186
+ deviceId,
4187
+ expiresAt: new Date(Date.now() + expiresInMs).toISOString(),
4188
+ homeserver
4189
+ };
4190
+ }
4191
+
4125
4192
  // src/sandbox.ts
4126
4193
  import { createWriteStream as createWriteStream2, lstatSync } from "fs";
4127
4194
  import { rename as rename2, unlink as unlink2 } from "fs/promises";
@@ -5669,10 +5736,12 @@ var Agents2 = class {
5669
5736
  client;
5670
5737
  templates;
5671
5738
  create(name, opts) {
5739
+ const bound = opts?.user;
5740
+ const userId = typeof bound === "string" ? bound : bound instanceof User ? bound.id : opts?.userId;
5672
5741
  return this.client.wire.agents.create(name, {
5673
5742
  template: opts?.template,
5674
5743
  messaging: opts?.messaging,
5675
- userId: opts?.userId,
5744
+ userId,
5676
5745
  displayName: opts?.displayName,
5677
5746
  timeout: timeoutSeconds(opts?.timeout)
5678
5747
  }).then((info) => new Agent(this.client, info));
@@ -5795,6 +5864,13 @@ var User = class {
5795
5864
  () => this.client.wire.tokens.create(this.id, { timeout: timeoutSeconds(opts?.timeout) })
5796
5865
  );
5797
5866
  }
5867
+ /**
5868
+ * Matrix access token for this person.
5869
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
5870
+ */
5871
+ matrixToken(opts) {
5872
+ return openMatrixToken(this.client.wire.baseUrl, async () => (await this.newToken()).token, opts);
5873
+ }
5798
5874
  /** Sign this person out of every device. */
5799
5875
  revoke(opts) {
5800
5876
  return retry(
@@ -5909,6 +5985,13 @@ var Client2 = class {
5909
5985
  newToken(opts) {
5910
5986
  return retry(this, () => this.wire.newToken({ timeout: timeoutSeconds(opts?.timeout) }));
5911
5987
  }
5988
+ /**
5989
+ * Matrix access token for the API caller.
5990
+ * Omit `deviceId` to create a device. Pass it back to keep that device.
5991
+ */
5992
+ matrixToken(opts) {
5993
+ return openMatrixToken(this.wire.baseUrl, async () => (await this.newToken()).token, opts);
5994
+ }
5912
5995
  /** Close the connection. */
5913
5996
  close() {
5914
5997
  this.wire.close();
@@ -6647,15 +6730,12 @@ var Sandbox2 = class _Sandbox {
6647
6730
  sh(command, opts) {
6648
6731
  return this.run(["/bin/sh", "-c", command], opts);
6649
6732
  }
6650
- /** Start a command and return its handle. Omit `timeout` for no RPC deadline. */
6733
+ /** Start a command and return its handle. The process runs until it exits. */
6651
6734
  async start(argv, opts) {
6652
6735
  const inner = await this.inner.start(argv, {
6653
6736
  env: opts?.env,
6654
6737
  cwd: opts?.cwd,
6655
- timeout: timeoutSeconds(opts?.timeout, UNLIMITED),
6656
- serviceName: opts?.name,
6657
- holdsIdle: opts?.keepAlive,
6658
- endsSandbox: opts?.endsSandbox
6738
+ serviceName: opts?.name
6659
6739
  });
6660
6740
  return new ProcessHandle2(this, inner);
6661
6741
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keska/sandbox",
3
- "version": "0.49.0",
3
+ "version": "0.50.0",
4
4
  "description": "TypeScript client for the Numen sandbox API",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",