@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.87

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.
Files changed (71) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/channels/cards.d.ts +7 -3
  4. package/dist/channels/cards.js +9 -4
  5. package/dist/channels/phrases.d.ts +10 -0
  6. package/dist/channels/phrases.js +10 -0
  7. package/dist/config/docs.js +1 -1
  8. package/dist/config/schema.d.ts +3 -0
  9. package/dist/config/schema.js +18 -12
  10. package/dist/ctx/create-ctx.d.ts +10 -1
  11. package/dist/ctx/create-ctx.js +42 -2
  12. package/dist/device-access/device-access.module.d.ts +7 -0
  13. package/dist/device-access/device-access.module.js +41 -0
  14. package/dist/device-access/device-access.service.d.ts +142 -0
  15. package/dist/device-access/device-access.service.js +464 -0
  16. package/dist/device-access/token.d.ts +6 -0
  17. package/dist/device-access/token.js +6 -0
  18. package/dist/device-access/viewer-routes.d.ts +45 -0
  19. package/dist/device-access/viewer-routes.js +81 -0
  20. package/dist/device-access/viewer.d.ts +244 -0
  21. package/dist/device-access/viewer.js +844 -0
  22. package/dist/dial-in/access.d.ts +19 -0
  23. package/dist/dial-in/access.js +23 -0
  24. package/dist/dial-in/gateway.d.ts +48 -6
  25. package/dist/dial-in/gateway.js +145 -10
  26. package/dist/dial-in/keys.d.ts +7 -0
  27. package/dist/dial-in/keys.js +7 -0
  28. package/dist/dial-in/routes.d.ts +11 -3
  29. package/dist/dial-in/routes.js +15 -4
  30. package/dist/dial-in/streams.d.ts +58 -0
  31. package/dist/dial-in/streams.js +283 -0
  32. package/dist/errors.d.ts +2 -0
  33. package/dist/errors.js +2 -0
  34. package/dist/extensions/host.d.ts +13 -1
  35. package/dist/extensions/host.js +20 -1
  36. package/dist/extensions/permission-set.d.ts +15 -1
  37. package/dist/extensions/permission-set.js +13 -1
  38. package/dist/extensions/permission-view.d.ts +6 -4
  39. package/dist/extensions/permission-view.js +6 -1
  40. package/dist/http/error.filter.js +2 -0
  41. package/dist/http/gateway-routes.d.ts +8 -4
  42. package/dist/http/gateway-routes.js +4 -3
  43. package/dist/infra/lock/lock.service.d.ts +5 -1
  44. package/dist/infra/lock/lock.service.js +10 -4
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/kernel.module.js +3 -0
  48. package/dist/roles/gateway-role.d.ts +13 -6
  49. package/dist/roles/gateway-role.js +27 -9
  50. package/dist/roles/gateway.module.d.ts +2 -1
  51. package/dist/roles/gateway.module.js +13 -3
  52. package/dist/sandbox/device-services.d.ts +62 -0
  53. package/dist/sandbox/device-services.js +183 -0
  54. package/dist/sandbox/leases.d.ts +18 -1
  55. package/dist/sandbox/leases.js +75 -1
  56. package/dist/sandbox/network-grants.js +5 -2
  57. package/dist/sandbox/sandbox.module.d.ts +2 -1
  58. package/dist/sandbox/sandbox.module.js +5 -2
  59. package/dist/sandbox/sandbox.service.d.ts +44 -1
  60. package/dist/sandbox/sandbox.service.js +142 -5
  61. package/dist/tools/approvals.service.d.ts +45 -20
  62. package/dist/tools/approvals.service.js +19 -9
  63. package/dist/tools/call-scope.d.ts +60 -0
  64. package/dist/tools/call-scope.js +23 -0
  65. package/dist/tools/network-asks.d.ts +13 -0
  66. package/dist/tools/network-asks.js +26 -2
  67. package/dist/tools/pipeline.d.ts +30 -1
  68. package/dist/tools/pipeline.js +285 -54
  69. package/dist/tools/questions.service.d.ts +24 -3
  70. package/dist/tools/questions.service.js +3 -1
  71. package/package.json +3 -3
@@ -0,0 +1,283 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { DeviceOfflineError, DIAL_IN_STREAM_INITIAL_CREDIT, } from "@capybara-hq/plugin-sdk";
3
+ /**
4
+ * The `code` of the error a stream's `send` rejects with when a message does not fit one frame
5
+ * once base64-encoded (the viewer endpoint answers it with 1009).
6
+ */
7
+ export const DEVICE_STREAM_MESSAGE_TOO_BIG = "device.stream_message_too_big";
8
+ /** Whether a machine frame belongs to a stream (routed to {@link DialInStreams.onFrame}). */
9
+ export function isStreamFrame(frame) {
10
+ return (frame.type === "stream-opened" ||
11
+ frame.type === "stream-data" ||
12
+ frame.type === "stream-credit" ||
13
+ frame.type === "stream-close");
14
+ }
15
+ /** The reason every stream of a connection ends with when its socket closes. */
16
+ export const STREAM_OFFLINE_REASON = "device-offline";
17
+ /** Reasons and errors travel at most this many characters (the envelope's limit). */
18
+ const MAX_REASON = 500;
19
+ /** How long the machine has to answer `stream-open` ({@link DialInStreams.openStream}). */
20
+ export const STREAM_OPEN_TIMEOUT_MS = 15_000;
21
+ const clip = (text) => text.length > MAX_REASON ? text.slice(0, MAX_REASON) : text;
22
+ /** One stream of the table: its credit both ways, its queues and how it ends. */
23
+ class Stream {
24
+ id;
25
+ transport;
26
+ forget;
27
+ /** Messages the kernel may still send (granted by the machine). */
28
+ sendCredit = DIAL_IN_STREAM_INITIAL_CREDIT;
29
+ /** Messages the machine may still send (granted by the kernel). */
30
+ recvCredit = DIAL_IN_STREAM_INITIAL_CREDIT;
31
+ /** Sends waiting for credit, in call order (each frame text already checked to fit). */
32
+ waiting = [];
33
+ /** Messages received and not consumed yet (at most the credit the kernel granted). */
34
+ inbox = [];
35
+ /** A consumer waiting for the next message. */
36
+ reader;
37
+ endedWith;
38
+ resolveClosed;
39
+ closed;
40
+ messages;
41
+ constructor(id, transport, forget) {
42
+ this.id = id;
43
+ this.transport = transport;
44
+ this.forget = forget;
45
+ this.closed = new Promise((resolve) => {
46
+ this.resolveClosed = resolve;
47
+ });
48
+ const next = () => {
49
+ // one consumer: a second next() while one waits would lose a message
50
+ if (this.reader !== undefined)
51
+ return Promise.reject(new Error("A stream's messages are read by one consumer: await each next() in turn"));
52
+ const m = this.inbox.shift();
53
+ if (m !== undefined) {
54
+ this.consumed();
55
+ return Promise.resolve({ value: m, done: false });
56
+ }
57
+ if (this.endedWith !== undefined)
58
+ return Promise.resolve({ value: undefined, done: true });
59
+ return new Promise((resolve) => {
60
+ this.reader = resolve;
61
+ });
62
+ };
63
+ // a consumer that stops (break, a throw) closes the stream, like Node's stream iterators
64
+ const iterator = {
65
+ next,
66
+ return: async () => {
67
+ this.close("consumer stopped");
68
+ return { value: undefined, done: true };
69
+ },
70
+ throw: async (e) => {
71
+ this.close("consumer stopped");
72
+ throw e;
73
+ },
74
+ };
75
+ this.messages = { [Symbol.asyncIterator]: () => iterator };
76
+ }
77
+ send(message) {
78
+ if (!(message instanceof Uint8Array))
79
+ return Promise.reject(new TypeError("A stream message must be a Uint8Array"));
80
+ if (this.endedWith !== undefined)
81
+ return Promise.reject(new Error(`The stream is closed: ${this.endedWith}`));
82
+ const frame = {
83
+ type: "stream-data",
84
+ streamId: this.id,
85
+ data: Buffer.from(message.buffer, message.byteOffset, message.byteLength).toString("base64"),
86
+ };
87
+ const text = JSON.stringify(frame);
88
+ const cap = this.transport.maxFrameBytes();
89
+ // a message is never split: one that does not fit one frame is refused
90
+ if (Buffer.byteLength(text) > cap)
91
+ return Promise.reject(Object.assign(new Error(`A stream message of ${message.byteLength} bytes does not fit the connection's frame capacity of ${cap} bytes once base64-encoded; send smaller messages`), { code: DEVICE_STREAM_MESSAGE_TOO_BIG }));
92
+ return new Promise((resolve, reject) => {
93
+ this.waiting.push({ text, resolve, reject });
94
+ this.flush();
95
+ });
96
+ }
97
+ close(reason = "closed") {
98
+ if (this.endedWith !== undefined)
99
+ return;
100
+ const why = clip(String(reason));
101
+ this.transport.send(JSON.stringify({ type: "stream-close", streamId: this.id, reason: why }));
102
+ this.end(why);
103
+ }
104
+ /** A frame of this stream from the machine. */
105
+ onFrame(frame) {
106
+ if (this.endedWith !== undefined)
107
+ return;
108
+ if (frame.type === "stream-credit") {
109
+ this.sendCredit += frame.messages;
110
+ this.flush();
111
+ }
112
+ else if (frame.type === "stream-data") {
113
+ if (this.recvCredit <= 0) {
114
+ // the machine sent beyond the credit the kernel granted: the stream ends, the connection
115
+ // and its other streams go on
116
+ this.close("credit exceeded");
117
+ return;
118
+ }
119
+ this.recvCredit--;
120
+ const m = new Uint8Array(Buffer.from(frame.data, "base64"));
121
+ const reader = this.reader;
122
+ if (reader) {
123
+ this.reader = undefined;
124
+ this.consumed();
125
+ reader({ value: m, done: false });
126
+ }
127
+ else
128
+ this.inbox.push(m);
129
+ }
130
+ else if (frame.type === "stream-close") {
131
+ this.end(frame.reason);
132
+ }
133
+ }
134
+ /** The stream ended (either side, or the socket): waiting sends fail, the reader ends. */
135
+ end(reason) {
136
+ if (this.endedWith !== undefined)
137
+ return;
138
+ this.endedWith = reason;
139
+ this.forget(this.id);
140
+ for (const w of this.waiting.splice(0))
141
+ w.reject(new Error(`The stream is closed: ${reason}`));
142
+ const reader = this.reader;
143
+ this.reader = undefined;
144
+ reader?.({ value: undefined, done: true });
145
+ this.resolveClosed({ reason });
146
+ }
147
+ /** One message was handed to the consumer: the machine may send one more. */
148
+ consumed() {
149
+ if (this.endedWith !== undefined)
150
+ return;
151
+ this.recvCredit++;
152
+ this.transport.send(JSON.stringify({ type: "stream-credit", streamId: this.id, messages: 1 }));
153
+ }
154
+ flush() {
155
+ while (this.sendCredit > 0 && this.waiting.length > 0 && this.endedWith === undefined) {
156
+ const w = this.waiting.shift();
157
+ if (!this.transport.send(w.text)) {
158
+ w.reject(new Error(`The stream is closed: ${STREAM_OFFLINE_REASON}`));
159
+ continue;
160
+ }
161
+ this.sendCredit--;
162
+ w.resolve();
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * The streams of one machine connection on the gateway replica holding its socket (browser use
168
+ * spec §6.1): opened with `stream-open`, carried as `stream-data` frames straight over the socket
169
+ * (never through Redis or PG), each side sending only while it holds credit
170
+ * ({@link DIAL_IN_STREAM_INITIAL_CREDIT} at the open, one more per message the other side
171
+ * consumed). A data frame carries one whole message in base64; a message that does not fit the
172
+ * connection's frame capacity is refused, never split. The table is the connection's own state and
173
+ * lives exactly as long as the socket: its close ends every stream with
174
+ * {@link STREAM_OFFLINE_REASON}.
175
+ */
176
+ export class DialInStreams {
177
+ deviceId;
178
+ transport;
179
+ openTimeoutMs;
180
+ open = new Map();
181
+ /** Streams sent `stream-open` and not answered yet. */
182
+ opening = new Map();
183
+ ended = false;
184
+ constructor(deviceId, transport,
185
+ /** How long the machine has to answer an open ({@link STREAM_OPEN_TIMEOUT_MS}). */
186
+ openTimeoutMs = () => STREAM_OPEN_TIMEOUT_MS) {
187
+ this.deviceId = deviceId;
188
+ this.transport = transport;
189
+ this.openTimeoutMs = openTimeoutMs;
190
+ }
191
+ /**
192
+ * Opens a stream: sends `stream-open` with `body` and resolves once the machine answered
193
+ * `stream-opened` ok. A refusal rejects with the machine's error; `signal` bounds the opening
194
+ * only (an abort sends `stream-close` and rejects with the signal's reason), and so does the
195
+ * kernel's own deadline ({@link STREAM_OPEN_TIMEOUT_MS}: `stream-close` and a clear error); the
196
+ * socket's close rejects with `DeviceOfflineError`.
197
+ */
198
+ openStream(body, signal) {
199
+ if (this.ended)
200
+ return Promise.reject(new DeviceOfflineError(this.deviceId));
201
+ signal.throwIfAborted();
202
+ const streamId = randomUUID();
203
+ const text = JSON.stringify({
204
+ type: "stream-open",
205
+ streamId,
206
+ body,
207
+ });
208
+ const cap = this.transport.maxFrameBytes();
209
+ if (Buffer.byteLength(text) > cap)
210
+ return Promise.reject(new Error(`The stream-open frame does not fit the connection's frame capacity of ${cap} bytes; send a smaller target`));
211
+ const stream = new Stream(streamId, this.transport, (id) => this.open.delete(id));
212
+ return new Promise((resolve, reject) => {
213
+ let timer;
214
+ const settle = () => {
215
+ clearTimeout(timer);
216
+ signal.removeEventListener("abort", onAbort);
217
+ };
218
+ /** The open ends unanswered: the machine is told, the caller gets `error`. */
219
+ const giveUp = (reason, error) => {
220
+ if (!this.opening.delete(streamId))
221
+ return;
222
+ settle();
223
+ this.transport.send(JSON.stringify({ type: "stream-close", streamId, reason }));
224
+ stream.end(reason);
225
+ reject(error);
226
+ };
227
+ const onAbort = () => giveUp("aborted", signal.reason instanceof Error ? signal.reason : new Error("aborted"));
228
+ this.opening.set(streamId, {
229
+ stream,
230
+ resolve: (s) => {
231
+ settle();
232
+ resolve(s);
233
+ },
234
+ reject: (e) => {
235
+ settle();
236
+ reject(e);
237
+ },
238
+ });
239
+ signal.addEventListener("abort", onAbort, { once: true });
240
+ const timeoutMs = this.openTimeoutMs();
241
+ timer = setTimeout(() => giveUp("open timed out", new Error(`The machine did not answer the stream open within ${timeoutMs} ms; check that its program supports streams and retry`)), timeoutMs);
242
+ if (!this.transport.send(text)) {
243
+ this.opening.delete(streamId);
244
+ settle();
245
+ reject(new DeviceOfflineError(this.deviceId));
246
+ }
247
+ });
248
+ }
249
+ /** A stream frame from the machine; a frame of a stream that is not open is dropped. */
250
+ onFrame(frame) {
251
+ if (frame.type === "stream-opened") {
252
+ const pending = this.opening.get(frame.streamId);
253
+ if (pending === undefined)
254
+ return;
255
+ this.opening.delete(frame.streamId);
256
+ if (frame.ok) {
257
+ this.open.set(frame.streamId, pending.stream);
258
+ pending.resolve(pending.stream);
259
+ }
260
+ else {
261
+ pending.stream.end("refused");
262
+ pending.reject(new Error(`The machine refused the stream: ${frame.error ?? "no reason given"}`));
263
+ }
264
+ return;
265
+ }
266
+ // a frame racing the stream's close (or of a stream never opened here) has nothing to reach
267
+ this.open.get(frame.streamId)?.onFrame(frame);
268
+ }
269
+ /** The socket closed: every stream ends, every opening fails. */
270
+ closeAll() {
271
+ if (this.ended)
272
+ return;
273
+ this.ended = true;
274
+ for (const [id, p] of this.opening) {
275
+ this.opening.delete(id);
276
+ p.stream.end(STREAM_OFFLINE_REASON);
277
+ p.reject(new DeviceOfflineError(this.deviceId));
278
+ }
279
+ for (const s of [...this.open.values()])
280
+ s.end(STREAM_OFFLINE_REASON);
281
+ this.open.clear();
282
+ }
283
+ }
package/dist/errors.d.ts CHANGED
@@ -540,6 +540,8 @@ export declare const ERROR_CODES: {
540
540
  readonly "device_sign_in.unavailable": 503;
541
541
  /** The machine credential is unknown or revoked. */
542
542
  readonly "device.credential_invalid": 401;
543
+ /** A device stream hop from another gateway replica without a valid MAC (or replayed). */
544
+ readonly "device.stream_hop_refused": 401;
543
545
  /** The scheduled task is missing, deleted, in another org or not the caller's to see. */
544
546
  readonly "schedule.not_found": 404;
545
547
  /** Not a 5-field cron expression (no seconds field). */
package/dist/errors.js CHANGED
@@ -540,6 +540,8 @@ export const ERROR_CODES = {
540
540
  "device_sign_in.unavailable": 503,
541
541
  /** The machine credential is unknown or revoked. */
542
542
  "device.credential_invalid": 401,
543
+ /** A device stream hop from another gateway replica without a valid MAC (or replayed). */
544
+ "device.stream_hop_refused": 401,
543
545
  /** The scheduled task is missing, deleted, in another org or not the caller's to see. */
544
546
  "schedule.not_found": 404,
545
547
  /** Not a 5-field cron expression (no seconds field). */
@@ -3,9 +3,10 @@ import type { Redis } from "ioredis";
3
3
  import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
5
  import type { BusSubscriber } from "../ctx/bus.js";
6
- import { type Route } from "../ctx/create-ctx.js";
6
+ import { type DeviceAccessBackend, type Route } from "../ctx/create-ctx.js";
7
7
  import { type ExtensionNetSeams } from "../ctx/net.js";
8
8
  import type { Keyring } from "../ctx/secrets.js";
9
+ import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
9
10
  import { DialInAccess } from "../dial-in/access.js";
10
11
  import type { PluginRouteTable } from "../http/plugin-dispatch.js";
11
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -282,6 +283,17 @@ export declare class ExtensionHost {
282
283
  dialIn: DialInAccess,
283
284
  /** `ctx.devices`: the stored device reports, read again when a provider says they changed. */
284
285
  devices: DeviceReports,
286
+ /**
287
+ * Finds `DeviceAccessService` (`ctx.deviceAccess`, {@link DEVICE_ACCESS_BACKEND}) at the time
288
+ * of use: its module imports the sandbox, devices and tools modules, which import this one (a
289
+ * module cycle otherwise).
290
+ * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
291
+ */
292
+ modules?: {
293
+ get(token: typeof DEVICE_ACCESS_BACKEND, opts: {
294
+ strict: false;
295
+ }): DeviceAccessBackend;
296
+ },
285
297
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
286
298
  netSeams?: ExtensionNetSeams);
287
299
  /** The startup config's `extensionConfig` (file / Nacos merged with env). */
@@ -13,12 +13,14 @@ import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
14
14
  import { EXTENSION_POINT_CARDINALITY, parseExtensionPoint, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
+ import { ModuleRef } from "@nestjs/core";
16
17
  import { changedPaths, configFields, secretValues, unreachableSecrets } from "../config/fields.js";
17
18
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
18
19
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
19
20
  import { kernelDb } from "../db/kernel-schema.js";
20
21
  import { migrate } from "../db/migrator.js";
21
22
  import { createDb } from "../db/pool.js";
23
+ import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
22
24
  import { DialInAccess } from "../dial-in/access.js";
23
25
  import { waitWithin } from "../infra/close-within.js";
24
26
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -427,6 +429,13 @@ let ExtensionHost = class ExtensionHost {
427
429
  dialIn,
428
430
  /** `ctx.devices`: the stored device reports, read again when a provider says they changed. */
429
431
  devices,
432
+ /**
433
+ * Finds `DeviceAccessService` (`ctx.deviceAccess`, {@link DEVICE_ACCESS_BACKEND}) at the time
434
+ * of use: its module imports the sandbox, devices and tools modules, which import this one (a
435
+ * module cycle otherwise).
436
+ * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
437
+ */
438
+ modules,
430
439
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
431
440
  netSeams) {
432
441
  this.registry = registry;
@@ -463,6 +472,14 @@ let ExtensionHost = class ExtensionHost {
463
472
  net: { config, allowances, ...(netSeams !== undefined && { seams: netSeams }) },
464
473
  dialIn,
465
474
  devices,
475
+ deviceAccess: () => {
476
+ try {
477
+ return modules?.get(DEVICE_ACCESS_BACKEND, { strict: false });
478
+ }
479
+ catch {
480
+ return undefined;
481
+ }
482
+ },
466
483
  locks,
467
484
  runWorkers: c.roles.includes("worker"),
468
485
  log,
@@ -2415,6 +2432,8 @@ ExtensionHost = __decorate([
2415
2432
  __param(18, Inject(DialInAccess)),
2416
2433
  __param(19, Inject(DeviceReports)),
2417
2434
  __param(20, Optional()),
2418
- __param(20, Inject(EXTENSION_NET_SEAMS))
2435
+ __param(20, Inject(ModuleRef)),
2436
+ __param(21, Optional()),
2437
+ __param(21, Inject(EXTENSION_NET_SEAMS))
2419
2438
  ], ExtensionHost);
2420
2439
  export { ExtensionHost };
@@ -70,6 +70,14 @@ export interface PermissionSet {
70
70
  dialIn?: {
71
71
  protocol: string;
72
72
  };
73
+ /**
74
+ * The device services the extension runs in conversations' devices
75
+ * (`permissions.deviceAccess`, browser use spec §7): one blocking key per service. Absent when
76
+ * not declared (and in older snapshots).
77
+ */
78
+ deviceAccess?: {
79
+ services: string[];
80
+ };
73
81
  };
74
82
  /**
75
83
  * 安装记录包迁移警告的摘要(`warningsDigest`,Ruling P4);没有警告或不是安装记录时省略。
@@ -117,7 +125,7 @@ export declare function buildPermissionSet(input: {
117
125
  * `config.deployment.secret:apiKey`, `table:todos`, `permissions.tools:write`,
118
126
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
119
127
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
120
- * `permissions.dialin:capybara-device/6`.
128
+ * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`.
121
129
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
122
130
  */
123
131
  export declare function permissionKeys(set: PermissionSet): string[];
@@ -136,6 +144,12 @@ export declare const CLIENT_KEY = "permissions.client";
136
144
  * before the colon, as catalog permission keys require (`PERMISSION_KEY_RE`).
137
145
  */
138
146
  export declare const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
147
+ /**
148
+ * Key prefix of a device service (`permissions.deviceAccess.services`): sensitive and blocking, so
149
+ * an upgrade adding a service waits for approval. Lower-case letters and dots before the colon, as
150
+ * catalog permission keys require (`PERMISSION_KEY_RE`).
151
+ */
152
+ export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
139
153
  /** Key prefix of a client component (`ui.component:<id>`): sensitive and blocking. */
140
154
  export declare const UI_COMPONENT_KEY_PREFIX = "ui.component:";
141
155
  /** 渲染 schema 视图的权限键前缀:记入快照但不卡加载(见 {@link blockingKeys})。 */
@@ -117,6 +117,10 @@ export function buildPermissionSet(input) {
117
117
  : {}),
118
118
  // only when declared: sets (and snapshots) of plugins without a dial-in channel stay as they were
119
119
  ...(p.dialIn ? { dialIn: { protocol: p.dialIn.protocol } } : {}),
120
+ // only when declared, likewise
121
+ ...(p.deviceAccess
122
+ ? { deviceAccess: { services: sortedUnique(p.deviceAccess.services) } }
123
+ : {}),
120
124
  },
121
125
  ...(input.warningsDigest ? { warningsDigest: input.warningsDigest } : {}),
122
126
  };
@@ -126,7 +130,7 @@ export function buildPermissionSet(input) {
126
130
  * `config.deployment.secret:apiKey`, `table:todos`, `permissions.tools:write`,
127
131
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
128
132
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
129
- * `permissions.dialin:capybara-device/6`.
133
+ * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`.
130
134
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
131
135
  */
132
136
  export function permissionKeys(set) {
@@ -175,6 +179,8 @@ export function permissionKeys(set) {
175
179
  keys.push(`${SETUP_CHECK_KEY_PREFIX}${c}`);
176
180
  if (p.dialIn?.protocol)
177
181
  keys.push(`${DIAL_IN_KEY_PREFIX}${p.dialIn.protocol}`);
182
+ for (const svc of p.deviceAccess?.services ?? [])
183
+ keys.push(`${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
178
184
  if (s.warningsDigest)
179
185
  keys.push(`${WARNINGS_KEY_PREFIX}${s.warningsDigest}`);
180
186
  return sortedUnique(keys);
@@ -194,6 +200,12 @@ export const CLIENT_KEY = "permissions.client";
194
200
  * before the colon, as catalog permission keys require (`PERMISSION_KEY_RE`).
195
201
  */
196
202
  export const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
203
+ /**
204
+ * Key prefix of a device service (`permissions.deviceAccess.services`): sensitive and blocking, so
205
+ * an upgrade adding a service waits for approval. Lower-case letters and dots before the colon, as
206
+ * catalog permission keys require (`PERMISSION_KEY_RE`).
207
+ */
208
+ export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
197
209
  /** Key prefix of a client component (`ui.component:<id>`): sensitive and blocking. */
198
210
  export const UI_COMPONENT_KEY_PREFIX = "ui.component:";
199
211
  /** 渲染 schema 视图的权限键前缀:记入快照但不卡加载(见 {@link blockingKeys})。 */
@@ -13,9 +13,10 @@ import type { ExtensionSource } from "./sources.js";
13
13
  export declare function reviewHash(set: PermissionSet, warnings?: readonly PackageWarning[]): string;
14
14
  /** 权限清单展示用的一组:按类别分组,`sensitive` 标出需要管理员特别留意的类别。 */
15
15
  export interface PermissionGroup {
16
- category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client" | "dialIn";
16
+ category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client" | "dialIn" | "deviceAccess";
17
17
  /**
18
- * Sensitive category: secrets, public routes, tools, hooks, client components, client code; also
18
+ * Sensitive category: secrets, public routes, tools, hooks, client components, client code,
19
+ * device services; also
19
20
  * the "provides" group when it holds one of {@link SENSITIVE_EXTENSION_POINTS}, and the "UI" group
20
21
  * (views and embeds) when it holds an embedded app (embed: the extension's own page in an iframe).
21
22
  */
@@ -27,11 +28,12 @@ export interface PermissionGroup {
27
28
  /**
28
29
  * Sensitive reason codes (the UI translates them by code): secrets, public routes, embed routes,
29
30
  * tools, hooks, embedded apps, client code and client components (client extensions spec §5.4: code that runs with
30
- * full trust in members' browsers), and sensitive extension points
31
+ * full trust in members' browsers), device services (`device_access`: long-lived processes in
32
+ * conversations' devices), and sensitive extension points
31
33
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
32
34
  * `-` replaced by `_`).
33
35
  */
34
- export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "migration_warnings";
36
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "migration_warnings";
35
37
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
36
38
  export interface PermissionItem {
37
39
  value: string;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
3
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.js";
4
- import { CLIENT_KEY, DIAL_IN_KEY_PREFIX, permissionKeys, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
4
+ import { CLIENT_KEY, DEVICE_ACCESS_KEY_PREFIX, DIAL_IN_KEY_PREFIX, permissionKeys, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
5
5
  /**
6
6
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
7
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -49,6 +49,7 @@ const ALWAYS_SENSITIVE = new Set([
49
49
  "hooks",
50
50
  "components",
51
51
  "client",
52
+ "deviceAccess",
52
53
  ]);
53
54
  const CATEGORY_REASON = {
54
55
  secrets: "secrets",
@@ -58,6 +59,7 @@ const CATEGORY_REASON = {
58
59
  hooks: "hooks",
59
60
  components: "ui_component",
60
61
  client: "client_code",
62
+ deviceAccess: "device_access",
61
63
  };
62
64
  /**
63
65
  * Why an item in a category is sensitive (undefined when it is not; shared by the grouped list, the
@@ -106,6 +108,7 @@ function keyItem(key) {
106
108
  [UI_COMPONENT_KEY_PREFIX, "components", ""],
107
109
  ["ui.view:", "ui", "view:"],
108
110
  [DIAL_IN_KEY_PREFIX, "dialIn", ""],
111
+ [DEVICE_ACCESS_KEY_PREFIX, "deviceAccess", ""],
109
112
  ];
110
113
  for (const [prefix, category, itemPrefix] of table) {
111
114
  const rest = after(prefix);
@@ -183,6 +186,8 @@ export function permissionGroups(set) {
183
186
  { category: "client", items: p.client === true ? [CLIENT_ITEM] : [] },
184
187
  // machines that connect to the deployment for this provider's devices, speaking its protocol
185
188
  { category: "dialIn", items: p.dialIn ? [p.dialIn.protocol] : [] },
189
+ // long-lived services the extension runs in conversations' devices
190
+ { category: "deviceAccess", items: p.deviceAccess?.services ?? [] },
186
191
  ];
187
192
  return groups
188
193
  .filter((g) => g.items.length > 0)
@@ -44,6 +44,8 @@ export function redactPath(url) {
44
44
  // a share link's code (file sharing spec §3) opens the share while it is live
45
45
  .replace(/^\/api\/v1\/s\/[^/]+/, "/api/v1/s/:code")
46
46
  .replace(/^\/s\/[^/]+/, "/s/:code")
47
+ // a device stream hop names the viewer ticket (browser use spec §6.2)
48
+ .replace(/^\/internal\/device-stream\/[^/]+/, "/internal/device-stream/:ticket")
47
49
  .replace(/\/cap_[^/]*/g, "/:redacted"));
48
50
  }
49
51
  /**
@@ -7,13 +7,17 @@ export interface GatewayRoutes {
7
7
  webhooks: Pick<ChannelWebhooks, "handle">;
8
8
  /** `channels.webhookMaxBodyBytes`. */
9
9
  webhookMaxBodyBytes: number;
10
- /** The device connection route (`GET /device/connect`, environments spec §13.4). */
10
+ /**
11
+ * The device connection route (`GET /device/connect`, environments spec §13.4) and the device
12
+ * stream viewer routes (`GET /device/stream`, the replica hop; browser use spec §6.2).
13
+ */
11
14
  devices: DeviceRoutesOptions;
12
15
  }
13
16
  /**
14
17
  * Registers the gateway role's HTTP routes (`serveGateway = roles.includes("gateway")`): the
15
- * channel webhook and the device connection WebSocket. These are raw Fastify routes, not a Nest
16
- * module, so the API's global guard and CSRF check do not apply (P-4); each route does its own
17
- * verification (the channel plugin's signature check, the machine credential).
18
+ * channel webhook, the device connection WebSocket and the device stream viewer WebSockets. These
19
+ * are raw Fastify routes, not a Nest module, so the API's global guard and CSRF check do not apply
20
+ * (P-4); each route does its own verification (the channel plugin's signature check, the machine
21
+ * credential, the viewer ticket, the hop MAC).
18
22
  */
19
23
  export declare function registerGatewayRoutes(fastify: FastifyInstance, routes: GatewayRoutes, log: Pick<Logger, "error">): Promise<void>;
@@ -2,9 +2,10 @@ import { registerChannelWebhookRoute } from "../channels/webhook.controller.js";
2
2
  import { registerDeviceConnectRoute } from "../dial-in/routes.js";
3
3
  /**
4
4
  * Registers the gateway role's HTTP routes (`serveGateway = roles.includes("gateway")`): the
5
- * channel webhook and the device connection WebSocket. These are raw Fastify routes, not a Nest
6
- * module, so the API's global guard and CSRF check do not apply (P-4); each route does its own
7
- * verification (the channel plugin's signature check, the machine credential).
5
+ * channel webhook, the device connection WebSocket and the device stream viewer WebSockets. These
6
+ * are raw Fastify routes, not a Nest module, so the API's global guard and CSRF check do not apply
7
+ * (P-4); each route does its own verification (the channel plugin's signature check, the machine
8
+ * credential, the viewer ticket, the hop MAC).
8
9
  */
9
10
  export async function registerGatewayRoutes(fastify, routes, log) {
10
11
  await registerChannelWebhookRoute(fastify, {
@@ -116,11 +116,15 @@ export declare class LockService {
116
116
  * TTL/3; any successful renewal through the handle (the watchdog's or an explicit `renew()`)
117
117
  * moves it; when it passes without one, `lost` aborts, even with a renewal still in flight. So a
118
118
  * holder gives up one renewal period before the key can expire elsewhere. `release` stops
119
- * renewing and calls `ops.release` once.
119
+ * renewing and calls `ops.release` once. With `ops.quietYield`, a renewal answered `false` is a
120
+ * routine yield (the lease was taken back on purpose, e.g. a stream hold ending for a lifecycle
121
+ * change): it is logged at debug as `lease yielded`, not as a lost lock; a missed deadline is
122
+ * still a WARN.
120
123
  */
121
124
  keepAlive(label: string, ttlMs: number, ops: {
122
125
  renew(): Promise<boolean>;
123
126
  release(): Promise<void>;
127
+ quietYield?: boolean;
124
128
  }, acquiredAt?: number): LeaseHandle;
125
129
  /** {@link keepAlive}'s implementation, with {@link Watched.renewWith}. */
126
130
  private watchdog;
@@ -257,7 +257,10 @@ let LockService = class LockService {
257
257
  * TTL/3; any successful renewal through the handle (the watchdog's or an explicit `renew()`)
258
258
  * moves it; when it passes without one, `lost` aborts, even with a renewal still in flight. So a
259
259
  * holder gives up one renewal period before the key can expire elsewhere. `release` stops
260
- * renewing and calls `ops.release` once.
260
+ * renewing and calls `ops.release` once. With `ops.quietYield`, a renewal answered `false` is a
261
+ * routine yield (the lease was taken back on purpose, e.g. a stream hold ending for a lifecycle
262
+ * change): it is logged at debug as `lease yielded`, not as a lost lock; a missed deadline is
263
+ * still a WARN.
261
264
  */
262
265
  keepAlive(label, ttlMs, ops, acquiredAt = Date.now()) {
263
266
  return this.watchdog(label, ttlMs, ops, acquiredAt);
@@ -277,11 +280,14 @@ let LockService = class LockService {
277
280
  clearInterval(timer);
278
281
  clearTimeout(deadline);
279
282
  };
280
- const lose = (reason) => {
283
+ const lose = (reason, refused = false) => {
281
284
  // released or abandoned: the holder gave the lease up, so a late answer loses nothing
282
285
  if (released || stopped || lost.signal.aborted)
283
286
  return;
284
- this.log.warn(reason, { lockKey });
287
+ if (refused && ops.quietYield)
288
+ this.log.debug("lease yielded", { lockKey });
289
+ else
290
+ this.log.warn(reason, { lockKey });
285
291
  lost.abort(new Error(`lock lost: ${lockKey}`));
286
292
  stop();
287
293
  };
@@ -301,7 +307,7 @@ let LockService = class LockService {
301
307
  if (released || lost.signal.aborted)
302
308
  return false;
303
309
  if (!ok) {
304
- lose("lock lost: the key is gone or taken");
310
+ lose("lock lost: the key is gone or taken", true);
305
311
  return false;
306
312
  }
307
313
  if (sentAt > lastOkSentAt) {
@@ -40,6 +40,9 @@ export interface NamedThrottler {
40
40
  * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
41
41
  * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
42
42
  *
43
+ * `device-stream-ip` is not a Nest route limit either: the gateway's raw viewer route
44
+ * `GET /device/stream` reserves it before the upgrade (429 `rate_limited`).
45
+ *
43
46
  * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
44
47
  * methods on `public` extension routes (`PluginRouteAccess`).
45
48
  */