@capybara-hq/plugin-sdk 0.1.0-rc.76 → 0.1.0-rc.77

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.
@@ -12,4 +12,6 @@ Contract: IdentitySource (`identity.ts`)
12
12
 
13
13
  Provide SSO login through an external provider. The kernel owns state, nonce and PKCE checks; identities are keyed `<plugin>:<tenant>`.
14
14
 
15
+ Declare `tenant` so the admin console can label and check trusted tenants; list tenants that must never be trusted in `neverTrusted` (`validateTenantId` applies the same rule). A super admin turns the source on, orders the login page and sets its trusted tenants in the admin console (the login section of the extension's page, or the `login-sources.*` Platform operations); there is no startup config for it.
16
+
15
17
  See `extensions` for the rules every extension follows.
package/dist/ctx.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Kysely } from "kysely";
2
- import type { DeviceServiceSpec, DeviceServiceStatus } from "./device-provider.js";
2
+ import type { DeviceServiceSpec, DeviceServiceStatus, ServiceBlockedHost } from "./device-provider.js";
3
3
  import type { DevicesCtx, DialInChannel } from "./dial-in.js";
4
4
  import type { ExtensionPointRef } from "./extension-point.js";
5
5
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
@@ -202,12 +202,17 @@ export interface DeviceAccessCtx {
202
202
  timeoutMs: number;
203
203
  }): Promise<Uint8Array>;
204
204
  /**
205
- * The service saw requests to `hosts` refused by the device's network allowlist during this
206
- * call: the kernel raises the network ask in the call's conversation once the handler returns
207
- * (and runs the call again once the person approves). Only an ask. `opts.url` is the page the
208
- * refusals came from, shown with the ask.
205
+ * The service saw requests to `hosts` refused by the device's network during this call, each
206
+ * with the layer that refused it (`sandboxProxyRefusalLayer` reads it from the device's
207
+ * proxy): once the handler returns, the kernel raises the network ask in the call's
208
+ * conversation for `device` hosts it can offer (and runs the call again once the person
209
+ * approves), and writes a note for the others (an `address` host: a private or local address,
210
+ * which no host grant reaches). Only an ask: a layer never widens access, and the kernel's own
211
+ * planning still applies (a host the device list cannot take is never asked about; an IP
212
+ * literal is always `address`). A host reported twice keeps its most restrictive layer.
213
+ * `opts.url` is the page the refusals came from, shown with the ask.
209
214
  */
210
- reportBlockedHosts(call: ToolCallContext, hosts: string[], opts?: {
215
+ reportBlockedHosts(call: ToolCallContext, hosts: ServiceBlockedHost[], opts?: {
211
216
  url?: string;
212
217
  }): void;
213
218
  /**
@@ -71,6 +71,26 @@ export interface SandboxActor {
71
71
  * points to a private or local address; never grantable), `unknown`.
72
72
  */
73
73
  export type NetworkBlockLayer = "device" | "org" | "address" | "unknown";
74
+ /**
75
+ * A host a device service saw refused, with the layer that refused it
76
+ * (`ctx.deviceAccess.reportBlockedHosts`). The service reports host names only (no port).
77
+ */
78
+ export interface ServiceBlockedHost {
79
+ host: string;
80
+ layer: NetworkBlockLayer;
81
+ }
82
+ /**
83
+ * The layer of a refusal by a device's sandbox proxy, read from the reason the proxy gives: the
84
+ * status phrase of its 403 answer to a CONNECT, or the reason in its violation line
85
+ * (`deny network-outbound <host>:<port> (<reason>)`).
86
+ *
87
+ * - `address`: the destination's address is closed (an IP literal in a closed class, or a name
88
+ * resolving to a private or local address: "address is …", "resolved to …"), or the host is
89
+ * malformed. No host grant reaches it, only a command run outside the sandbox.
90
+ * - `device`: the host is not on the operation's allowlist ("host is not on the allow list").
91
+ * - `unknown`: any other reason (a proxy that names none, a failed fake-IP lookup).
92
+ */
93
+ export declare function sandboxProxyRefusalLayer(reason: string): NetworkBlockLayer;
74
94
  /** A host a command was refused, as the provider reports it. */
75
95
  export interface NetworkBlockedHost {
76
96
  /** The host as the proxy saw it (IPv6 literals bracketed). */
@@ -329,6 +349,15 @@ export interface DeviceServiceStatus {
329
349
  * may send it to a machine instead of the files.
330
350
  */
331
351
  export declare function deviceServiceFilesDigest(files: Record<string, Uint8Array>): string;
352
+ /**
353
+ * A fixed input and its {@link deviceServiceFilesDigest}, for the tests of every implementation
354
+ * of the digest (the SDK's, capybara-device's, a provider's own): one that disagrees would restart
355
+ * every running service at every ensure.
356
+ */
357
+ export declare const DEVICE_SERVICE_FILES_DIGEST_VECTOR: {
358
+ readonly files: Readonly<Record<string, string>>;
359
+ readonly digest: string;
360
+ };
332
361
  /**
333
362
  * A message stream to a device service ({@link DeviceProvider.openStream},
334
363
  * `DialInChannel.openStream`): whole messages both ways, flow-controlled by credit.
@@ -24,6 +24,25 @@ export const DEFAULT_SANDBOX_ROOTS = Object.freeze({
24
24
  export function rootsOf(h) {
25
25
  return h.roots ?? DEFAULT_SANDBOX_ROOTS;
26
26
  }
27
+ /**
28
+ * The layer of a refusal by a device's sandbox proxy, read from the reason the proxy gives: the
29
+ * status phrase of its 403 answer to a CONNECT, or the reason in its violation line
30
+ * (`deny network-outbound <host>:<port> (<reason>)`).
31
+ *
32
+ * - `address`: the destination's address is closed (an IP literal in a closed class, or a name
33
+ * resolving to a private or local address: "address is …", "resolved to …"), or the host is
34
+ * malformed. No host grant reaches it, only a command run outside the sandbox.
35
+ * - `device`: the host is not on the operation's allowlist ("host is not on the allow list").
36
+ * - `unknown`: any other reason (a proxy that names none, a failed fake-IP lookup).
37
+ */
38
+ export function sandboxProxyRefusalLayer(reason) {
39
+ const r = reason.trim().toLowerCase();
40
+ if (r.startsWith("address is ") || r.startsWith("resolved to ") || r === "malformed host")
41
+ return "address";
42
+ if (r === "host is not on the allow list")
43
+ return "device";
44
+ return "unknown";
45
+ }
27
46
  /**
28
47
  * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
29
48
  * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
@@ -221,6 +240,33 @@ export function deviceServiceId(extension, name) {
221
240
  * may send it to a machine instead of the files.
222
241
  */
223
242
  export function deviceServiceFilesDigest(files) {
243
+ const cached = digests.get(files);
244
+ if (cached !== undefined)
245
+ return cached;
246
+ const digest = digestOf(files);
247
+ digests.set(files, digest);
248
+ return digest;
249
+ }
250
+ /**
251
+ * Digests already computed, by files object: a plugin passes the same `files` object on every
252
+ * call (its service files are read once), and a browser's are megabytes. Callers never mutate a
253
+ * spec's files after building it.
254
+ */
255
+ const digests = new WeakMap();
256
+ /**
257
+ * A fixed input and its {@link deviceServiceFilesDigest}, for the tests of every implementation
258
+ * of the digest (the SDK's, capybara-device's, a provider's own): one that disagrees would restart
259
+ * every running service at every ensure.
260
+ */
261
+ export const DEVICE_SERVICE_FILES_DIGEST_VECTOR = Object.freeze({
262
+ files: Object.freeze({
263
+ "main.js": "console.log(1)\n",
264
+ "lib/a.js": "export const a = 1;\n",
265
+ empty: "",
266
+ }),
267
+ digest: "sha256:7b3959ff2e10237b9f1a255bbecb5dacebd31422fe734b2867403e42913432a5",
268
+ });
269
+ function digestOf(files) {
224
270
  const h = createHash("sha256");
225
271
  for (const path of Object.keys(files).sort()) {
226
272
  const data = files[path];
@@ -26,6 +26,27 @@
26
26
  * never context. Providers and the device program pass the viewer context through like any
27
27
  * stream message.
28
28
  */
29
+ /**
30
+ * The request body the kernel sends a running service before restarting it on new files (an
31
+ * upgraded extension, {@link DeviceServiceRollCheck}). A service that answers
32
+ * `{"busy":true,"reason":"…"}` is kept running (a person is using it); the kernel asks again at a
33
+ * later ensure. Any other answer, an error or no answer within a few seconds lets the restart go
34
+ * ahead, so a service that does not know the check is restarted as before. Every service gets
35
+ * this body on its request connection, so a service must ignore a request body it does not know
36
+ * (answer an error, act on nothing), never treat an arbitrary body as a command.
37
+ */
38
+ export declare const DEVICE_SERVICE_ROLL_CHECK = "{\"capybara\":\"roll-check\"}";
39
+ /** A service's answer to {@link DEVICE_SERVICE_ROLL_CHECK}. */
40
+ export interface DeviceServiceRollCheck {
41
+ /** True while restarting now would lose something a person is doing (a takeover, a handoff). */
42
+ busy: boolean;
43
+ /** What keeps it busy, for the kernel's log. */
44
+ reason?: string;
45
+ }
46
+ /** Whether `body` is the kernel's {@link DEVICE_SERVICE_ROLL_CHECK} request. */
47
+ export declare function isRollCheck(body: Uint8Array | string): boolean;
48
+ /** Reads a service's answer to the roll check: busy only for `{"busy":true}` (never throws). */
49
+ export declare function parseRollCheck(body: Uint8Array | string): DeviceServiceRollCheck;
29
50
  /** Names the unix socket path the service listens on. */
30
51
  export declare const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
31
52
  /** Names the service's state directory (its own data, its write root; not where its code is). */
@@ -26,6 +26,43 @@
26
26
  * never context. Providers and the device program pass the viewer context through like any
27
27
  * stream message.
28
28
  */
29
+ /**
30
+ * The request body the kernel sends a running service before restarting it on new files (an
31
+ * upgraded extension, {@link DeviceServiceRollCheck}). A service that answers
32
+ * `{"busy":true,"reason":"…"}` is kept running (a person is using it); the kernel asks again at a
33
+ * later ensure. Any other answer, an error or no answer within a few seconds lets the restart go
34
+ * ahead, so a service that does not know the check is restarted as before. Every service gets
35
+ * this body on its request connection, so a service must ignore a request body it does not know
36
+ * (answer an error, act on nothing), never treat an arbitrary body as a command.
37
+ */
38
+ export const DEVICE_SERVICE_ROLL_CHECK = '{"capybara":"roll-check"}';
39
+ /** Whether `body` is the kernel's {@link DEVICE_SERVICE_ROLL_CHECK} request. */
40
+ export function isRollCheck(body) {
41
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
42
+ try {
43
+ const v = JSON.parse(text);
44
+ return (typeof v === "object" && v !== null && v.capybara === "roll-check");
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /** Reads a service's answer to the roll check: busy only for `{"busy":true}` (never throws). */
51
+ export function parseRollCheck(body) {
52
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
53
+ try {
54
+ const v = JSON.parse(text);
55
+ if (typeof v === "object" && v !== null && v.busy === true)
56
+ return {
57
+ busy: true,
58
+ ...(typeof v.reason === "string" && { reason: v.reason.slice(0, 200) }),
59
+ };
60
+ }
61
+ catch {
62
+ // not JSON: not busy
63
+ }
64
+ return { busy: false };
65
+ }
29
66
  /** Names the unix socket path the service listens on. */
30
67
  export const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
31
68
  /** Names the service's state directory (its own data, its write root; not where its code is). */
@@ -16,6 +16,32 @@ export interface ExternalIdentity {
16
16
  displayName: string;
17
17
  avatarUrl?: string;
18
18
  }
19
+ /** How an identity source describes its tenants to the admin console. */
20
+ export interface IdentitySourceTenant {
21
+ /** The field label in Chinese and English, e.g. the Slack workspace ID. */
22
+ label: {
23
+ zh: string;
24
+ en: string;
25
+ };
26
+ /** Where to find the tenant id. */
27
+ help?: {
28
+ zh: string;
29
+ en: string;
30
+ };
31
+ /** A regular expression (JavaScript syntax) a tenant id must match, e.g. `^T[A-Z0-9]+$`. */
32
+ pattern?: string;
33
+ /** An example tenant id shown as the placeholder. */
34
+ placeholder?: string;
35
+ /** Tenant ids that may never be trusted for email merge (Google: `consumer`). */
36
+ neverTrusted?: string[];
37
+ }
38
+ /**
39
+ * Checks a tenant id against a source's tenant declaration: `"empty"` for a blank id, `"pattern"`
40
+ * when it does not match the declared pattern (an invalid pattern counts as none),
41
+ * `"never_trusted"` when the source lists it in `neverTrusted`, else `"ok"`. The id is trimmed
42
+ * first. The kernel uses it before storing trusted tenants.
43
+ */
44
+ export declare function validateTenantId(decl: IdentitySourceTenant | undefined, id: string): "ok" | "pattern" | "never_trusted" | "empty";
19
45
  /**
20
46
  * Third-party login (`identity-source@1`). State, nonce and PKCE are all generated by the kernel
21
47
  * and kept server-side:
@@ -29,6 +55,12 @@ export interface IdentitySource {
29
55
  zh: string;
30
56
  en: string;
31
57
  };
58
+ /**
59
+ * What a tenant is on this platform, so the admin console can label and check the trusted
60
+ * tenants of this source (a tenant id is the `<tenant>` of the source key `<plugin>:<tenant>`).
61
+ * Without it the console shows a plain tenant id field.
62
+ */
63
+ tenant?: IdentitySourceTenant;
32
64
  authorizeUrl(args: {
33
65
  config: unknown;
34
66
  redirectUri: string;
package/dist/identity.js CHANGED
@@ -1,3 +1,28 @@
1
+ /**
2
+ * Checks a tenant id against a source's tenant declaration: `"empty"` for a blank id, `"pattern"`
3
+ * when it does not match the declared pattern (an invalid pattern counts as none),
4
+ * `"never_trusted"` when the source lists it in `neverTrusted`, else `"ok"`. The id is trimmed
5
+ * first. The kernel uses it before storing trusted tenants.
6
+ */
7
+ export function validateTenantId(decl, id) {
8
+ const value = id.trim();
9
+ if (value === "")
10
+ return "empty";
11
+ if (decl?.pattern) {
12
+ let re;
13
+ try {
14
+ re = new RegExp(decl.pattern);
15
+ }
16
+ catch {
17
+ re = undefined;
18
+ }
19
+ if (re && !re.test(value))
20
+ return "pattern";
21
+ }
22
+ if (decl?.neverTrusted?.includes(value))
23
+ return "never_trusted";
24
+ return "ok";
25
+ }
1
26
  /**
2
27
  * Thrown by an identity source's `callback` when it refuses the account on purpose (a hosted domain
3
28
  * or tenant the platform does not allow, a consumer account where only organization accounts are
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.76";
1
+ export declare const SDK_VERSION = "0.1.0-rc.77";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.76";
1
+ export const SDK_VERSION = "0.1.0-rc.77";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.76",
3
+ "version": "0.1.0-rc.77",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {