@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.86
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/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.d.ts +7 -3
- package/dist/channels/cards.js +9 -4
- package/dist/channels/phrases.d.ts +10 -0
- package/dist/channels/phrases.js +10 -0
- package/dist/config/docs.js +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +18 -12
- package/dist/ctx/create-ctx.d.ts +10 -1
- package/dist/ctx/create-ctx.js +42 -2
- package/dist/device-access/device-access.module.d.ts +7 -0
- package/dist/device-access/device-access.module.js +41 -0
- package/dist/device-access/device-access.service.d.ts +142 -0
- package/dist/device-access/device-access.service.js +464 -0
- package/dist/device-access/token.d.ts +6 -0
- package/dist/device-access/token.js +6 -0
- package/dist/device-access/viewer-routes.d.ts +45 -0
- package/dist/device-access/viewer-routes.js +81 -0
- package/dist/device-access/viewer.d.ts +244 -0
- package/dist/device-access/viewer.js +844 -0
- package/dist/dial-in/access.d.ts +19 -0
- package/dist/dial-in/access.js +23 -0
- package/dist/dial-in/gateway.d.ts +48 -6
- package/dist/dial-in/gateway.js +145 -10
- package/dist/dial-in/keys.d.ts +7 -0
- package/dist/dial-in/keys.js +7 -0
- package/dist/dial-in/routes.d.ts +11 -3
- package/dist/dial-in/routes.js +15 -4
- package/dist/dial-in/streams.d.ts +58 -0
- package/dist/dial-in/streams.js +283 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/extensions/host.d.ts +13 -1
- package/dist/extensions/host.js +20 -1
- package/dist/extensions/permission-set.d.ts +15 -1
- package/dist/extensions/permission-set.js +13 -1
- package/dist/extensions/permission-view.d.ts +6 -4
- package/dist/extensions/permission-view.js +6 -1
- package/dist/http/error.filter.js +2 -0
- package/dist/http/gateway-routes.d.ts +8 -4
- package/dist/http/gateway-routes.js +4 -3
- package/dist/infra/lock/lock.service.d.ts +5 -1
- package/dist/infra/lock/lock.service.js +10 -4
- package/dist/infra/throttler/named-throttlers.d.ts +3 -0
- package/dist/infra/throttler/named-throttlers.js +16 -0
- package/dist/kernel.module.js +3 -0
- package/dist/roles/gateway-role.d.ts +13 -6
- package/dist/roles/gateway-role.js +27 -9
- package/dist/roles/gateway.module.d.ts +2 -1
- package/dist/roles/gateway.module.js +13 -3
- package/dist/sandbox/device-services.d.ts +62 -0
- package/dist/sandbox/device-services.js +183 -0
- package/dist/sandbox/leases.d.ts +18 -1
- package/dist/sandbox/leases.js +75 -1
- package/dist/sandbox/network-grants.js +5 -2
- package/dist/sandbox/sandbox.module.d.ts +2 -1
- package/dist/sandbox/sandbox.module.js +5 -2
- package/dist/sandbox/sandbox.service.d.ts +44 -1
- package/dist/sandbox/sandbox.service.js +142 -5
- package/dist/tools/approvals.service.d.ts +45 -20
- package/dist/tools/approvals.service.js +19 -9
- package/dist/tools/call-scope.d.ts +60 -0
- package/dist/tools/call-scope.js +23 -0
- package/dist/tools/network-asks.d.ts +13 -0
- package/dist/tools/network-asks.js +26 -2
- package/dist/tools/pipeline.d.ts +30 -1
- package/dist/tools/pipeline.js +285 -54
- package/dist/tools/questions.service.d.ts +24 -3
- package/dist/tools/questions.service.js +3 -1
- package/package.json +3 -3
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { DeviceAccessError, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
|
|
12
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
13
|
+
import { DeviceAccess } from "../devices/access.js";
|
|
14
|
+
import { ConversationDevices } from "../devices/conversation-devices.js";
|
|
15
|
+
import { DevicesService } from "../devices/devices.service.js";
|
|
16
|
+
import { ApiError } from "../errors.js";
|
|
17
|
+
import { isExtensionEnabled } from "../extensions/enabled.js";
|
|
18
|
+
import { ExtensionRegistry } from "../extensions/registry.js";
|
|
19
|
+
import { audit } from "../identity/audit.js";
|
|
20
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
21
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
22
|
+
import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
23
|
+
import { rootConversationOf } from "../runtime/subagents/child.js";
|
|
24
|
+
import { assertServiceSpec, DeviceServices } from "../sandbox/device-services.js";
|
|
25
|
+
import { DeviceProviders } from "../sandbox/providers.js";
|
|
26
|
+
import { CommandReviewService } from "../sandbox/review/review.service.js";
|
|
27
|
+
import { attachCallScope, callScopeOf } from "../tools/call-scope.js";
|
|
28
|
+
import { QuestionsService } from "../tools/questions.service.js";
|
|
29
|
+
/** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
|
|
30
|
+
export const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
|
|
31
|
+
/** A viewer ticket's key prefix (`capk:device-stream-ticket:<id>`, single use, GETDEL). */
|
|
32
|
+
export const DEVICE_STREAM_TICKET_PREFIX = "capk:device-stream-ticket:";
|
|
33
|
+
/** How long a viewer ticket lives, in seconds. */
|
|
34
|
+
export const DEVICE_STREAM_TICKET_TTL_SECONDS = 60;
|
|
35
|
+
/** Maps the device resolution's API errors to the extension's refusal codes. */
|
|
36
|
+
function refusal(e) {
|
|
37
|
+
if (!(e instanceof ApiError))
|
|
38
|
+
return e;
|
|
39
|
+
if (e.code === "device.not_found" || e.code === "sandbox.unavailable")
|
|
40
|
+
return new DeviceAccessError("no_device", e.message, { cause: e });
|
|
41
|
+
if (e.code === "device.unavailable")
|
|
42
|
+
return new DeviceAccessError("provider_unavailable", e.message, { cause: e });
|
|
43
|
+
return e;
|
|
44
|
+
}
|
|
45
|
+
/** How long the refresh of one service after an allowlist change may take. */
|
|
46
|
+
const REFRESH_TIMEOUT_MS = 30_000;
|
|
47
|
+
/**
|
|
48
|
+
* The launch as it runs: `env K=V … node <codeDir ?? stateDir>/<entry> <args…>` (no `env` without
|
|
49
|
+
* env): the entry runs from the service's code directory when the provider keeps code apart.
|
|
50
|
+
*/
|
|
51
|
+
function launchArgv(spec, status) {
|
|
52
|
+
const env = Object.entries(spec.env ?? {}).map(([k, v]) => `${k}=${v}`);
|
|
53
|
+
const dir = status.codeDir ?? status.stateDir;
|
|
54
|
+
const entry = `${dir.replace(/\/+$/, "")}/${spec.entry}`;
|
|
55
|
+
return [...(env.length > 0 ? ["env", ...env] : []), "node", entry, ...spec.args];
|
|
56
|
+
}
|
|
57
|
+
/** A POSIX shell word for the review's command text (bare when it needs no quoting). */
|
|
58
|
+
const shellWord = (s) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
59
|
+
/**
|
|
60
|
+
* `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
|
|
61
|
+
* device, limited to the conversation's owner on their own personal device and to the service
|
|
62
|
+
* names the extension's approved manifest declares. A service launch passes the command review
|
|
63
|
+
* (fail closed: only `allow` starts it), once per start; requests ride the provider's request
|
|
64
|
+
* path; refused hosts land in the call scope for the pipeline's network ask; viewer tickets are
|
|
65
|
+
* single-use Redis records; the allowlist write and the handoff answer go through the device page's
|
|
66
|
+
* and the questions' own services (their checks and audits apply).
|
|
67
|
+
*/
|
|
68
|
+
let DeviceAccessService = class DeviceAccessService {
|
|
69
|
+
kdb;
|
|
70
|
+
redis;
|
|
71
|
+
config;
|
|
72
|
+
services;
|
|
73
|
+
review;
|
|
74
|
+
devices;
|
|
75
|
+
access;
|
|
76
|
+
deviceWrites;
|
|
77
|
+
questions;
|
|
78
|
+
providers;
|
|
79
|
+
log;
|
|
80
|
+
registry;
|
|
81
|
+
constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry) {
|
|
82
|
+
this.kdb = kdb;
|
|
83
|
+
this.redis = redis;
|
|
84
|
+
this.config = config;
|
|
85
|
+
this.services = services;
|
|
86
|
+
this.review = review;
|
|
87
|
+
this.devices = devices;
|
|
88
|
+
this.access = access;
|
|
89
|
+
this.deviceWrites = deviceWrites;
|
|
90
|
+
this.questions = questions;
|
|
91
|
+
this.providers = providers;
|
|
92
|
+
this.log = log;
|
|
93
|
+
this.registry = registry;
|
|
94
|
+
}
|
|
95
|
+
get db() {
|
|
96
|
+
return this.kdb.db;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
|
|
100
|
+
* (never starts anything): a running service is kept with no review. A stopped one is
|
|
101
|
+
* launched only after the command review saw the command as it runs
|
|
102
|
+
* (`env K=V … node <codeDir ?? stateDir>/<entry> <args…>`, the state directory as its working
|
|
103
|
+
* directory) and allowed it; anything else refuses it (fail closed). The verdict is recorded
|
|
104
|
+
* on the call (the call scope) and a start is audited `device.service_started`.
|
|
105
|
+
*/
|
|
106
|
+
async ensureService(caller, call, spec) {
|
|
107
|
+
assertDeclared(caller, spec.name);
|
|
108
|
+
assertCallOwner(call);
|
|
109
|
+
assertServiceSpec(spec);
|
|
110
|
+
const scope = callScopeOf(call);
|
|
111
|
+
const facts = scope?.facts;
|
|
112
|
+
if (scope === null || facts === undefined)
|
|
113
|
+
throw new Error(`plugin ${caller.extension}: ctx.deviceAccess.ensureService needs the tool call context the kernel passed to the handler`);
|
|
114
|
+
const use = await this.callUse(call, facts.rootConversationId, scope);
|
|
115
|
+
const ensure = async (ifRunning) => {
|
|
116
|
+
try {
|
|
117
|
+
return await this.services.ensure(use, spec, call.signal, { ifRunning });
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
throw refusal(e);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
// race-free: the provider keeps a running service and never starts a stopped one here
|
|
124
|
+
const found = await ensure(true);
|
|
125
|
+
if (found.state === "running")
|
|
126
|
+
return found;
|
|
127
|
+
const reviewFacts = await this.devices.reviewFacts(call.orgId, facts.rootConversationId, call.conversationId);
|
|
128
|
+
if (reviewFacts === null || reviewFacts.deviceId !== use.deviceId)
|
|
129
|
+
throw new DeviceAccessError("no_device", "The conversation has no device to run in.");
|
|
130
|
+
const argv = launchArgv(spec, found);
|
|
131
|
+
const verdict = await this.review.review({
|
|
132
|
+
orgId: call.orgId,
|
|
133
|
+
conversationId: facts.rootConversationId,
|
|
134
|
+
runId: facts.runId,
|
|
135
|
+
accountId: call.accountId,
|
|
136
|
+
toolKey: "Bash",
|
|
137
|
+
input: { command: argv.map(shellWord).join(" ") },
|
|
138
|
+
mode: reviewFacts.mode,
|
|
139
|
+
// the command runs in the service's state directory
|
|
140
|
+
workspace: found.stateDir,
|
|
141
|
+
home: reviewFacts.home,
|
|
142
|
+
deviceHome: reviewFacts.deviceHome,
|
|
143
|
+
attended: !facts.unattended && call.accountId === reviewFacts.ownerAccountId,
|
|
144
|
+
step: facts.step,
|
|
145
|
+
callId: call.callId,
|
|
146
|
+
signal: call.signal,
|
|
147
|
+
agentId: call.agentId,
|
|
148
|
+
agentVersion: facts.agentVersion,
|
|
149
|
+
...(facts.conversationKind !== undefined && { conversationKind: facts.conversationKind }),
|
|
150
|
+
...(facts.parent !== undefined && {
|
|
151
|
+
parentRunId: facts.parent.runId,
|
|
152
|
+
...(facts.parent.budgetRunId !== undefined && { budgetRunId: facts.parent.budgetRunId }),
|
|
153
|
+
parent: {
|
|
154
|
+
conversationId: facts.parent.conversationId,
|
|
155
|
+
runId: facts.parent.runId,
|
|
156
|
+
callId: facts.parent.callId,
|
|
157
|
+
},
|
|
158
|
+
}),
|
|
159
|
+
});
|
|
160
|
+
const allowed = verdict.decision === "allow";
|
|
161
|
+
const record = {
|
|
162
|
+
decision: allowed ? "allow" : "deny",
|
|
163
|
+
by: verdict.by,
|
|
164
|
+
rule: verdict.rule,
|
|
165
|
+
reason: verdict.reason,
|
|
166
|
+
};
|
|
167
|
+
scope.review = record;
|
|
168
|
+
// fail closed: an ask has nobody to answer it here, and a deny is a deny
|
|
169
|
+
if (!allowed)
|
|
170
|
+
throw new ToolError(`The device service ${spec.name} was not started: the command review did not allow its launch (${verdict.reason}). Ask the user to check the device's settings.`);
|
|
171
|
+
// another call may have started it since the first look (that call audits its own start):
|
|
172
|
+
// found running now, this call started nothing and audits nothing
|
|
173
|
+
const raced = await ensure(true);
|
|
174
|
+
if (raced.state === "running")
|
|
175
|
+
return raced;
|
|
176
|
+
const started = await ensure(false);
|
|
177
|
+
// audited only when this ensure started it: the service was stopped (no startedAt) just
|
|
178
|
+
// before, and runs with a startedAt now
|
|
179
|
+
if (started.state !== "running" || started.startedAt === raced.startedAt)
|
|
180
|
+
return started;
|
|
181
|
+
await audit(this.db, {
|
|
182
|
+
actorAccountId: call.accountId,
|
|
183
|
+
orgId: call.orgId,
|
|
184
|
+
action: "device.service_started",
|
|
185
|
+
target: use.deviceId,
|
|
186
|
+
detail: {
|
|
187
|
+
extension: caller.extension,
|
|
188
|
+
service: spec.name,
|
|
189
|
+
deviceId: use.deviceId,
|
|
190
|
+
argv,
|
|
191
|
+
decision: record.decision,
|
|
192
|
+
rule: record.rule,
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
return started;
|
|
196
|
+
}
|
|
197
|
+
/** One request to the service's socket in the call's device. */
|
|
198
|
+
async request(caller, call, req) {
|
|
199
|
+
assertDeclared(caller, req.service);
|
|
200
|
+
assertCallOwner(call);
|
|
201
|
+
const scope = callScopeOf(call) ?? attachCallScope(call);
|
|
202
|
+
const root = scope.facts?.rootConversationId ?? (await this.rootOf(call.conversationId));
|
|
203
|
+
const use = await this.callUse(call, root, scope);
|
|
204
|
+
try {
|
|
205
|
+
return await this.services.request(use, req.service, req.body, req.timeoutMs, call.signal);
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
throw refusal(e);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Records refused hosts in the call scope (synchronous: the pipeline reads it once the handler
|
|
213
|
+
* returns) on the device this call's own `ctx.deviceAccess` calls resolved, if any.
|
|
214
|
+
*/
|
|
215
|
+
reportBlockedHosts(call, hosts, opts) {
|
|
216
|
+
assertCallOwner(call);
|
|
217
|
+
const scope = callScopeOf(call) ?? attachCallScope(call);
|
|
218
|
+
const valid = hosts.filter((h) => typeof h === "string" && h.length > 0);
|
|
219
|
+
if (valid.length === 0)
|
|
220
|
+
return;
|
|
221
|
+
const url = typeof opts?.url === "string" && opts.url.length > 0 ? opts.url : null;
|
|
222
|
+
if (scope.blocked === null) {
|
|
223
|
+
scope.blocked = { deviceId: scope.device, hosts: new Set(valid), url };
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
for (const h of valid)
|
|
227
|
+
scope.blocked.hosts.add(h);
|
|
228
|
+
if (url !== null)
|
|
229
|
+
scope.blocked.url = url;
|
|
230
|
+
}
|
|
231
|
+
/** A single-use viewer ticket for the service (the person's panel opens `url`). */
|
|
232
|
+
async streamTicket(caller, scope) {
|
|
233
|
+
const { url, expiresAt } = await this.mintTicket(scope, scope.service, caller);
|
|
234
|
+
return { url, expiresAt };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Mints a viewer ticket: `capk:device-stream-ticket:<id>` for
|
|
238
|
+
* {@link DEVICE_STREAM_TICKET_TTL_SECONDS} seconds, taken once ({@link takeTicket}). Refused
|
|
239
|
+
* unless the account owns the conversation and its personal device, and the device's provider
|
|
240
|
+
* can open streams.
|
|
241
|
+
*/
|
|
242
|
+
async mintTicket(scope, service, caller) {
|
|
243
|
+
assertDeclared(caller, service);
|
|
244
|
+
const d = await this.scopedDevice(caller, scope);
|
|
245
|
+
if (!this.providers.forDevice(d.provider)?.impl.openStream)
|
|
246
|
+
throw new DeviceAccessError("capability_missing", "This device's provider cannot open streams to device services; choose a device on a provider that supports them.");
|
|
247
|
+
const id = randomBytes(24).toString("base64url");
|
|
248
|
+
const record = {
|
|
249
|
+
orgId: d.orgId,
|
|
250
|
+
accountId: scope.accountId,
|
|
251
|
+
conversationId: d.conversationId,
|
|
252
|
+
deviceId: d.deviceId,
|
|
253
|
+
providerName: d.provider,
|
|
254
|
+
service,
|
|
255
|
+
extension: caller.extension,
|
|
256
|
+
};
|
|
257
|
+
await this.redis.set(`${DEVICE_STREAM_TICKET_PREFIX}${id}`, JSON.stringify(record), "EX", DEVICE_STREAM_TICKET_TTL_SECONDS);
|
|
258
|
+
const base = (this.config.get().http.publicUrl ?? "").replace(/\/+$/, "");
|
|
259
|
+
return {
|
|
260
|
+
id,
|
|
261
|
+
url: `${base}/device/stream?ticket=${id}`,
|
|
262
|
+
expiresAt: new Date(Date.now() + DEVICE_STREAM_TICKET_TTL_SECONDS * 1000).toISOString(),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/** Takes a viewer ticket (GETDEL: a second take finds nothing); null when unknown or used. */
|
|
266
|
+
async takeTicket(id) {
|
|
267
|
+
const raw = await this.redis.getdel(`${DEVICE_STREAM_TICKET_PREFIX}${id}`);
|
|
268
|
+
return raw === null ? null : JSON.parse(raw);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
|
|
272
|
+
* {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
|
|
273
|
+
* account, its device still the record's device on the record's provider and the account's
|
|
274
|
+
* own, the record's extension still enabled in the org and its approved manifest as loaded now
|
|
275
|
+
* (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
|
|
276
|
+
* False when any of that no longer holds; other failures (the database) are thrown.
|
|
277
|
+
*/
|
|
278
|
+
async ticketStands(t) {
|
|
279
|
+
return (await this.ticketCheck(t)) === "stands";
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* {@link ticketStands} with the reason when it does not: `provider_off` when the device's
|
|
283
|
+
* provider is no longer usable in the org (switched off, or no provider), `revoked` for
|
|
284
|
+
* everything else (the conversation, its owner or device, the extension or its declared
|
|
285
|
+
* services). An open viewer re-checks with it while it lives. Other failures are thrown.
|
|
286
|
+
*/
|
|
287
|
+
async ticketCheck(t) {
|
|
288
|
+
const declared = this.registry.current(t.extension)?.permissions.permissions.deviceAccess?.services ?? [];
|
|
289
|
+
if (!declared.includes(t.service))
|
|
290
|
+
return "revoked";
|
|
291
|
+
try {
|
|
292
|
+
const d = await this.scopedDevice({ extension: t.extension, services: [t.service] }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
|
|
293
|
+
return d.orgId === t.orgId && d.deviceId === t.deviceId && d.provider === t.providerName
|
|
294
|
+
? "stands"
|
|
295
|
+
: "revoked";
|
|
296
|
+
}
|
|
297
|
+
catch (e) {
|
|
298
|
+
if (e instanceof DeviceAccessError)
|
|
299
|
+
return e.code === "provider_unavailable" ? "provider_off" : "revoked";
|
|
300
|
+
throw e;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Adds hosts to the conversation's device allowlist through the device page's own write
|
|
305
|
+
* (ceilings, validation, the `device.network_changed` audit), owner only. Exact host names
|
|
306
|
+
* only, as an approved network ask grants: a wildcard is refused before anything is read.
|
|
307
|
+
*/
|
|
308
|
+
async addNetworkHosts(caller, scope) {
|
|
309
|
+
const wildcard = scope.hosts.find((h) => typeof h !== "string" || h.includes("*"));
|
|
310
|
+
if (wildcard !== undefined)
|
|
311
|
+
throw new TypeError(`${String(wildcard)} is not an exact host name: ctx.deviceAccess.addNetworkHosts takes exact host names only (no "*." wildcard), as an approved network ask grants.`);
|
|
312
|
+
const d = await this.scopedDevice(caller, scope);
|
|
313
|
+
await this.deviceWrites.addNetworkHostsIn(d.orgId, scope.accountId, d.deviceId, scope.hosts, "web");
|
|
314
|
+
// the extension's running services get the device's new limits (an ifRunning ensure: it
|
|
315
|
+
// never starts or resumes anything); the allowlist is written either way
|
|
316
|
+
const use = {
|
|
317
|
+
orgId: d.orgId,
|
|
318
|
+
deviceId: d.deviceId,
|
|
319
|
+
holderConversationId: d.conversationId,
|
|
320
|
+
actor: { accountId: scope.accountId, conversationId: d.conversationId },
|
|
321
|
+
};
|
|
322
|
+
for (const name of caller.services) {
|
|
323
|
+
try {
|
|
324
|
+
await this.services.refresh(use, name, AbortSignal.timeout(REFRESH_TIMEOUT_MS));
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
this.log.warn("device service not refreshed after an allowlist change", {
|
|
328
|
+
deviceId: d.deviceId,
|
|
329
|
+
service: name,
|
|
330
|
+
err,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
|
|
337
|
+
* the questions' own rules (only the run's starter answers, the form validates the answer); only
|
|
338
|
+
* a question one of this extension's tools raised.
|
|
339
|
+
*/
|
|
340
|
+
async answerHandoff(caller, scope) {
|
|
341
|
+
const d = await this.scopedDevice(caller, scope);
|
|
342
|
+
const q = await this.db
|
|
343
|
+
.selectFrom("questions")
|
|
344
|
+
.select(["id", "spec"])
|
|
345
|
+
.where("org_id", "=", d.orgId)
|
|
346
|
+
.where("conversation_id", "=", d.conversationId)
|
|
347
|
+
.where("call_id", "=", scope.callId)
|
|
348
|
+
.where("status", "=", "pending")
|
|
349
|
+
.orderBy("created_at", "desc")
|
|
350
|
+
.executeTakeFirst();
|
|
351
|
+
if (q === undefined)
|
|
352
|
+
throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} in this conversation`);
|
|
353
|
+
const key = q.spec?.toolKey;
|
|
354
|
+
const parsed = typeof key === "string" ? parseToolKey(key) : null;
|
|
355
|
+
if (parsed?.kind !== "extension" || parsed.plugin !== caller.extension)
|
|
356
|
+
throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} of ${caller.extension} in this conversation`);
|
|
357
|
+
await this.questions.answer(q.id, scope.accountId, { done: scope.done }, d.orgId);
|
|
358
|
+
}
|
|
359
|
+
/** The use of the call's device (bound now when the conversation has none yet, as tools do). */
|
|
360
|
+
async callUse(call, rootConversationId, scope) {
|
|
361
|
+
const conv = await this.db
|
|
362
|
+
.selectFrom("conversations")
|
|
363
|
+
.select("account_id")
|
|
364
|
+
.where("id", "=", rootConversationId)
|
|
365
|
+
.where("org_id", "=", call.orgId)
|
|
366
|
+
.where("deleted_at", "is", null)
|
|
367
|
+
.executeTakeFirst();
|
|
368
|
+
if (conv === undefined)
|
|
369
|
+
throw new DeviceAccessError("no_device", "The conversation has no device to run in.");
|
|
370
|
+
// the trigger account must own the conversation itself, not only by the call's word
|
|
371
|
+
if (conv.account_id !== call.accountId)
|
|
372
|
+
throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
|
|
373
|
+
let deviceId;
|
|
374
|
+
try {
|
|
375
|
+
deviceId = await this.devices.forTool(call.orgId, rootConversationId);
|
|
376
|
+
}
|
|
377
|
+
catch (e) {
|
|
378
|
+
throw refusal(e);
|
|
379
|
+
}
|
|
380
|
+
scope.device = deviceId;
|
|
381
|
+
return {
|
|
382
|
+
orgId: call.orgId,
|
|
383
|
+
deviceId,
|
|
384
|
+
holderConversationId: call.conversationId,
|
|
385
|
+
actor: { accountId: call.accountId, conversationId: call.conversationId },
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* The device of a scope-based call: the conversation live, the account its owner, the
|
|
390
|
+
* extension enabled in its org, its (root) conversation bound to a personal device the account
|
|
391
|
+
* may use now. Binds nothing.
|
|
392
|
+
*/
|
|
393
|
+
async scopedDevice(caller, scope) {
|
|
394
|
+
const conv = await this.db
|
|
395
|
+
.selectFrom("conversations")
|
|
396
|
+
.select(["org_id", "account_id"])
|
|
397
|
+
.where("id", "=", scope.conversationId)
|
|
398
|
+
.where("org_id", "=", scope.orgId)
|
|
399
|
+
.where("deleted_at", "is", null)
|
|
400
|
+
.executeTakeFirst();
|
|
401
|
+
// another org's conversation reads as missing (no probing across orgs)
|
|
402
|
+
if (conv === undefined)
|
|
403
|
+
throw new DeviceAccessError("no_device", "The conversation does not exist.");
|
|
404
|
+
if (conv.account_id !== scope.accountId)
|
|
405
|
+
throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
|
|
406
|
+
if (!(await isExtensionEnabled(this.db, conv.org_id, caller.extension)))
|
|
407
|
+
throw new DeviceAccessError("capability_missing", `The extension ${caller.extension} is not enabled in the conversation's organization.`);
|
|
408
|
+
const rootConversationId = await this.rootOf(scope.conversationId);
|
|
409
|
+
const root = await this.db
|
|
410
|
+
.selectFrom("conversations")
|
|
411
|
+
.select(["account_id", "device_id"])
|
|
412
|
+
.where("id", "=", rootConversationId)
|
|
413
|
+
.where("org_id", "=", conv.org_id)
|
|
414
|
+
.executeTakeFirst();
|
|
415
|
+
if (root === undefined || root.account_id !== scope.accountId)
|
|
416
|
+
throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
|
|
417
|
+
if (root.device_id === null)
|
|
418
|
+
throw new DeviceAccessError("no_device", "The conversation has no device yet.");
|
|
419
|
+
let usable;
|
|
420
|
+
try {
|
|
421
|
+
usable = await this.access.usable(conv.org_id, scope.accountId, root.device_id);
|
|
422
|
+
}
|
|
423
|
+
catch (e) {
|
|
424
|
+
// the device bound to the owner's conversation is not theirs to use: someone else's
|
|
425
|
+
if (e instanceof ApiError && e.code === "device.not_found")
|
|
426
|
+
throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT, { cause: e });
|
|
427
|
+
throw refusal(e);
|
|
428
|
+
}
|
|
429
|
+
return {
|
|
430
|
+
orgId: conv.org_id,
|
|
431
|
+
conversationId: scope.conversationId,
|
|
432
|
+
rootConversationId,
|
|
433
|
+
deviceId: usable.id,
|
|
434
|
+
provider: usable.provider,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
rootOf(conversationId) {
|
|
438
|
+
return rootConversationOf(this.db, conversationId);
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
DeviceAccessService = __decorate([
|
|
442
|
+
Injectable(),
|
|
443
|
+
__param(0, Inject(KernelDb)),
|
|
444
|
+
__param(1, Inject(REDIS)),
|
|
445
|
+
__param(2, Inject(KernelConfigService)),
|
|
446
|
+
__param(3, Inject(DeviceServices)),
|
|
447
|
+
__param(4, Inject(CommandReviewService)),
|
|
448
|
+
__param(5, Inject(ConversationDevices)),
|
|
449
|
+
__param(6, Inject(DeviceAccess)),
|
|
450
|
+
__param(7, Inject(DevicesService)),
|
|
451
|
+
__param(8, Inject(QuestionsService)),
|
|
452
|
+
__param(9, Inject(DeviceProviders)),
|
|
453
|
+
__param(10, Inject(KERNEL_LOGGER)),
|
|
454
|
+
__param(11, Inject(ExtensionRegistry))
|
|
455
|
+
], DeviceAccessService);
|
|
456
|
+
export { DeviceAccessService };
|
|
457
|
+
function assertDeclared(caller, service) {
|
|
458
|
+
if (!caller.services.includes(service))
|
|
459
|
+
throw new DeviceAccessError("service_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.services of ${caller.extension}.`);
|
|
460
|
+
}
|
|
461
|
+
function assertCallOwner(call) {
|
|
462
|
+
if (call.ownerAccountId === undefined || call.accountId !== call.ownerAccountId)
|
|
463
|
+
throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
|
|
464
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The token the extension host finds `DeviceAccessService` by at the time of use (`ModuleRef`):
|
|
3
|
+
* a symbol in a file of its own, so the host never imports the service's module graph (which
|
|
4
|
+
* imports the host back).
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEVICE_ACCESS_BACKEND: unique symbol;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The token the extension host finds `DeviceAccessService` by at the time of use (`ModuleRef`):
|
|
3
|
+
* a symbol in a file of its own, so the host never imports the service's module graph (which
|
|
4
|
+
* imports the host back).
|
|
5
|
+
*/
|
|
6
|
+
export const DEVICE_ACCESS_BACKEND = Symbol("DEVICE_ACCESS_BACKEND");
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { FastifyInstance } from "fastify";
|
|
2
|
+
import type { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
3
|
+
import { type DeviceStreamViewers } from "./viewer.js";
|
|
4
|
+
/** The viewer route the panel opens (browser use spec §6.2). */
|
|
5
|
+
export declare const DEVICE_STREAM_ROUTE = "/device/stream";
|
|
6
|
+
/** The replica-to-replica hop to the gateway replica holding a local device's machine. */
|
|
7
|
+
export declare const DEVICE_STREAM_HOP_ROUTE = "/internal/device-stream/:ticketId";
|
|
8
|
+
/** What the viewer routes need ({@link DeviceStreamViewers}). */
|
|
9
|
+
export interface DeviceStreamRoutesOptions {
|
|
10
|
+
viewers: Pick<DeviceStreamViewers, "serve" | "serveHop" | "verifyHop" | "claimHop">;
|
|
11
|
+
/**
|
|
12
|
+
* Counts each viewer upgrade per client address (`device-stream-ip`) before the upgrade; a
|
|
13
|
+
* valid ticket gives the attempt back. Absent when the client address is unknown
|
|
14
|
+
* ({@link viewerThrottleOn}): no limit then.
|
|
15
|
+
*/
|
|
16
|
+
throttler?: Pick<CredentialThrottler, "reserve" | "succeeded">;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Whether the viewer limit applies (ruling R23): only when `http.trustProxy` trusts some hop, so
|
|
20
|
+
* `req.ip` is the browser's address as the web tier forwards it. With nothing trusted, `req.ip` is
|
|
21
|
+
* the web tier itself for every browser, and one bucket for all would let one client lock every
|
|
22
|
+
* viewer out; the limit is defence in depth (a ticket is 192 random bits, used once), so it is
|
|
23
|
+
* skipped rather than shared.
|
|
24
|
+
*/
|
|
25
|
+
export declare function viewerThrottleOn(trustProxy: boolean | number | string | string[]): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Registers the viewer routes on `scope`, a Fastify scope where `@fastify/websocket` is
|
|
28
|
+
* registered (the gateway role's device scope, `dial-in/routes.ts`): raw routes outside Nest, so
|
|
29
|
+
* neither the API's `AuthGuard` nor its CSRF check applies; each route checks its own credential.
|
|
30
|
+
*
|
|
31
|
+
* - `GET /device/stream?ticket=`: the ticket is the only credential (cookies do not reach the
|
|
32
|
+
* gateway). With `opts.throttler` (a trusted proxy configured), each upgrade counts against
|
|
33
|
+
* `device-stream-ip`: 120 a minute per client address, `req.ip` under `http.trustProxy` (the
|
|
34
|
+
* web tier's upgrade proxy sets `X-Forwarded-For` for this path); 429 `rate_limited` before
|
|
35
|
+
* the upgrade; a valid ticket refunds it. Otherwise the upgrade is accepted and the socket
|
|
36
|
+
* closed with the viewer close codes (`VIEWER_CLOSE`), since a browser sees no HTTP status of
|
|
37
|
+
* a refused upgrade.
|
|
38
|
+
* - `GET /internal/device-stream/:ticketId`: another gateway replica's hop. Before the upgrade,
|
|
39
|
+
* and before anything else is read, the `X-Capybara-Hop` MAC and its issue time are checked
|
|
40
|
+
* (401 `device.stream_hop_refused` otherwise), then the hop is accepted once per ticket.
|
|
41
|
+
*
|
|
42
|
+
* The request log never carries the ticket: the access line drops the query and writes the hop
|
|
43
|
+
* path as `/internal/device-stream/:ticket` (`redactPath`).
|
|
44
|
+
*/
|
|
45
|
+
export declare function registerDeviceStreamRoutes(scope: FastifyInstance, opts: DeviceStreamRoutesOptions): Promise<void>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { ApiError, errorBody } from "../errors.js";
|
|
2
|
+
import { HOP_AT_HEADER, HOP_HEADER, TICKET_ID_RE } from "./viewer.js";
|
|
3
|
+
/** The viewer route the panel opens (browser use spec §6.2). */
|
|
4
|
+
export const DEVICE_STREAM_ROUTE = "/device/stream";
|
|
5
|
+
/** The replica-to-replica hop to the gateway replica holding a local device's machine. */
|
|
6
|
+
export const DEVICE_STREAM_HOP_ROUTE = "/internal/device-stream/:ticketId";
|
|
7
|
+
/**
|
|
8
|
+
* Whether the viewer limit applies (ruling R23): only when `http.trustProxy` trusts some hop, so
|
|
9
|
+
* `req.ip` is the browser's address as the web tier forwards it. With nothing trusted, `req.ip` is
|
|
10
|
+
* the web tier itself for every browser, and one bucket for all would let one client lock every
|
|
11
|
+
* viewer out; the limit is defence in depth (a ticket is 192 random bits, used once), so it is
|
|
12
|
+
* skipped rather than shared.
|
|
13
|
+
*/
|
|
14
|
+
export function viewerThrottleOn(trustProxy) {
|
|
15
|
+
if (trustProxy === false || trustProxy === 0 || trustProxy === "")
|
|
16
|
+
return false;
|
|
17
|
+
return !(Array.isArray(trustProxy) && trustProxy.length === 0);
|
|
18
|
+
}
|
|
19
|
+
/** The named throttler of the viewer route. */
|
|
20
|
+
const VIEWER_THROTTLER = ["device-stream-ip"];
|
|
21
|
+
const hopRefused = () => errorBody("device.stream_hop_refused", "This hop is not authenticated; it is refused.");
|
|
22
|
+
/**
|
|
23
|
+
* Registers the viewer routes on `scope`, a Fastify scope where `@fastify/websocket` is
|
|
24
|
+
* registered (the gateway role's device scope, `dial-in/routes.ts`): raw routes outside Nest, so
|
|
25
|
+
* neither the API's `AuthGuard` nor its CSRF check applies; each route checks its own credential.
|
|
26
|
+
*
|
|
27
|
+
* - `GET /device/stream?ticket=`: the ticket is the only credential (cookies do not reach the
|
|
28
|
+
* gateway). With `opts.throttler` (a trusted proxy configured), each upgrade counts against
|
|
29
|
+
* `device-stream-ip`: 120 a minute per client address, `req.ip` under `http.trustProxy` (the
|
|
30
|
+
* web tier's upgrade proxy sets `X-Forwarded-For` for this path); 429 `rate_limited` before
|
|
31
|
+
* the upgrade; a valid ticket refunds it. Otherwise the upgrade is accepted and the socket
|
|
32
|
+
* closed with the viewer close codes (`VIEWER_CLOSE`), since a browser sees no HTTP status of
|
|
33
|
+
* a refused upgrade.
|
|
34
|
+
* - `GET /internal/device-stream/:ticketId`: another gateway replica's hop. Before the upgrade,
|
|
35
|
+
* and before anything else is read, the `X-Capybara-Hop` MAC and its issue time are checked
|
|
36
|
+
* (401 `device.stream_hop_refused` otherwise), then the hop is accepted once per ticket.
|
|
37
|
+
*
|
|
38
|
+
* The request log never carries the ticket: the access line drops the query and writes the hop
|
|
39
|
+
* path as `/internal/device-stream/:ticket` (`redactPath`).
|
|
40
|
+
*/
|
|
41
|
+
export async function registerDeviceStreamRoutes(scope, opts) {
|
|
42
|
+
scope.get(DEVICE_STREAM_ROUTE, {
|
|
43
|
+
websocket: true,
|
|
44
|
+
preValidation: async (req, reply) => {
|
|
45
|
+
if (opts.throttler === undefined)
|
|
46
|
+
return;
|
|
47
|
+
try {
|
|
48
|
+
await opts.throttler.reserve(VIEWER_THROTTLER, req, reply);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
if (e instanceof ApiError && e.code === "rate_limited")
|
|
52
|
+
return reply.code(429).send(errorBody(e.code, e.message));
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
}, (socket, req) => {
|
|
57
|
+
const t = req.query?.ticket;
|
|
58
|
+
const throttler = opts.throttler;
|
|
59
|
+
void opts.viewers.serve(socket, typeof t === "string" ? t : "", throttler ? () => throttler.succeeded(VIEWER_THROTTLER, req) : undefined);
|
|
60
|
+
});
|
|
61
|
+
const verified = new WeakSet();
|
|
62
|
+
scope.get(DEVICE_STREAM_HOP_ROUTE, {
|
|
63
|
+
websocket: true,
|
|
64
|
+
preValidation: async (req, reply) => {
|
|
65
|
+
const ticketId = req.params.ticketId ?? "";
|
|
66
|
+
if (!opts.viewers.verifyHop(ticketId, req.headers[HOP_HEADER], req.headers[HOP_AT_HEADER]) ||
|
|
67
|
+
!TICKET_ID_RE.test(ticketId) ||
|
|
68
|
+
!(await opts.viewers.claimHop(ticketId))) {
|
|
69
|
+
return reply.code(401).send(hopRefused());
|
|
70
|
+
}
|
|
71
|
+
verified.add(req);
|
|
72
|
+
},
|
|
73
|
+
}, (socket, req) => {
|
|
74
|
+
if (!verified.has(req)) {
|
|
75
|
+
socket.close(4401, "invalid hop");
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const ticketId = req.params.ticketId;
|
|
79
|
+
void opts.viewers.serveHop(socket, ticketId, String(req.headers[HOP_AT_HEADER]));
|
|
80
|
+
});
|
|
81
|
+
}
|