@capybara-hq/kernel 0.1.0-rc.84 → 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.
Files changed (157) hide show
  1. package/dist/admin/admin.module.js +5 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +10 -2
  4. package/dist/catalog/admin-catalog.controller.d.ts +2 -1
  5. package/dist/catalog/admin-catalog.controller.js +2 -1
  6. package/dist/catalog/catalog-content.d.ts +5 -15
  7. package/dist/catalog/catalog-content.js +5 -56
  8. package/dist/catalog/catalog-scope.service.d.ts +3 -3
  9. package/dist/catalog/catalog-scope.service.js +4 -3
  10. package/dist/catalog/catalog.module.d.ts +3 -1
  11. package/dist/catalog/catalog.module.js +14 -1
  12. package/dist/catalog/component-scope.service.d.ts +6 -1
  13. package/dist/catalog/component-scope.service.js +16 -2
  14. package/dist/catalog/job-ids.d.ts +29 -0
  15. package/dist/catalog/job-ids.js +29 -0
  16. package/dist/catalog/jobs.d.ts +12 -3
  17. package/dist/catalog/jobs.js +28 -7
  18. package/dist/catalog/marketplaces.service.d.ts +1 -1
  19. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  20. package/dist/catalog/org-catalog.controller.js +3 -29
  21. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  22. package/dist/catalog/org-catalog.schemas.js +9 -23
  23. package/dist/catalog/org-catalog.service.js +14 -23
  24. package/dist/catalog/plugin-import.d.ts +21 -0
  25. package/dist/catalog/plugin-import.js +33 -3
  26. package/dist/catalog/plugin-install.d.ts +69 -76
  27. package/dist/catalog/plugin-install.js +156 -234
  28. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  29. package/dist/catalog/plugin-upgrade.js +222 -43
  30. package/dist/catalog/scope-sync.d.ts +22 -20
  31. package/dist/catalog/scope-sync.js +57 -42
  32. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  33. package/dist/catalog/template-connector-ensure.js +285 -0
  34. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  35. package/dist/catalog/template-connector-jobs.js +54 -0
  36. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  37. package/dist/catalog/template-connector-reconcile.js +114 -0
  38. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  39. package/dist/catalog/template-connectors.processor.js +101 -0
  40. package/dist/channels/cards.d.ts +7 -3
  41. package/dist/channels/cards.js +9 -4
  42. package/dist/channels/phrases.d.ts +10 -0
  43. package/dist/channels/phrases.js +10 -0
  44. package/dist/config/docs.js +1 -1
  45. package/dist/config/schema.d.ts +3 -0
  46. package/dist/config/schema.js +18 -12
  47. package/dist/ctx/create-ctx.d.ts +10 -1
  48. package/dist/ctx/create-ctx.js +42 -2
  49. package/dist/db/kernel-schema.d.ts +2 -1
  50. package/dist/device-access/device-access.module.d.ts +7 -0
  51. package/dist/device-access/device-access.module.js +41 -0
  52. package/dist/device-access/device-access.service.d.ts +142 -0
  53. package/dist/device-access/device-access.service.js +464 -0
  54. package/dist/device-access/token.d.ts +6 -0
  55. package/dist/device-access/token.js +6 -0
  56. package/dist/device-access/viewer-routes.d.ts +45 -0
  57. package/dist/device-access/viewer-routes.js +81 -0
  58. package/dist/device-access/viewer.d.ts +244 -0
  59. package/dist/device-access/viewer.js +844 -0
  60. package/dist/dial-in/access.d.ts +19 -0
  61. package/dist/dial-in/access.js +23 -0
  62. package/dist/dial-in/gateway.d.ts +48 -6
  63. package/dist/dial-in/gateway.js +145 -10
  64. package/dist/dial-in/keys.d.ts +7 -0
  65. package/dist/dial-in/keys.js +7 -0
  66. package/dist/dial-in/routes.d.ts +11 -3
  67. package/dist/dial-in/routes.js +15 -4
  68. package/dist/dial-in/streams.d.ts +58 -0
  69. package/dist/dial-in/streams.js +283 -0
  70. package/dist/errors.d.ts +2 -0
  71. package/dist/errors.js +2 -0
  72. package/dist/extensions/host.d.ts +13 -1
  73. package/dist/extensions/host.js +20 -1
  74. package/dist/extensions/org-config.d.ts +6 -1
  75. package/dist/extensions/org-config.js +15 -2
  76. package/dist/extensions/permission-set.d.ts +15 -1
  77. package/dist/extensions/permission-set.js +13 -1
  78. package/dist/extensions/permission-view.d.ts +6 -4
  79. package/dist/extensions/permission-view.js +6 -1
  80. package/dist/git/gateway.js +3 -1
  81. package/dist/http/error.filter.js +2 -0
  82. package/dist/http/gateway-routes.d.ts +8 -4
  83. package/dist/http/gateway-routes.js +4 -3
  84. package/dist/infra/lock/lock.service.d.ts +5 -1
  85. package/dist/infra/lock/lock.service.js +10 -4
  86. package/dist/infra/outbox/registry.d.ts +28 -0
  87. package/dist/infra/outbox/registry.js +33 -0
  88. package/dist/infra/queue/queue-names.d.ts +1 -1
  89. package/dist/infra/queue/queue-names.js +2 -0
  90. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  91. package/dist/infra/throttler/named-throttlers.js +16 -0
  92. package/dist/kernel.module.js +3 -0
  93. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  94. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  95. package/dist/orgs/org-owner.d.ts +7 -0
  96. package/dist/orgs/org-owner.js +16 -0
  97. package/dist/platform/operation.d.ts +3 -4
  98. package/dist/platform/ops/connectors.ops.js +8 -1
  99. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  100. package/dist/platform/ops/org-plugins.ops.js +18 -235
  101. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  102. package/dist/platform/ops/plugins.ops.js +3 -31
  103. package/dist/roles/gateway-role.d.ts +13 -6
  104. package/dist/roles/gateway-role.js +27 -9
  105. package/dist/roles/gateway.module.d.ts +2 -1
  106. package/dist/roles/gateway.module.js +13 -3
  107. package/dist/roles/worker-role.d.ts +9 -4
  108. package/dist/roles/worker-role.js +18 -5
  109. package/dist/roles/worker.module.d.ts +1 -1
  110. package/dist/roles/worker.module.js +8 -1
  111. package/dist/sandbox/device-services.d.ts +62 -0
  112. package/dist/sandbox/device-services.js +183 -0
  113. package/dist/sandbox/leases.d.ts +18 -1
  114. package/dist/sandbox/leases.js +75 -1
  115. package/dist/sandbox/network-grants.js +5 -2
  116. package/dist/sandbox/sandbox.module.d.ts +2 -1
  117. package/dist/sandbox/sandbox.module.js +5 -2
  118. package/dist/sandbox/sandbox.service.d.ts +44 -1
  119. package/dist/sandbox/sandbox.service.js +142 -5
  120. package/dist/setup/setup-guides.service.d.ts +9 -1
  121. package/dist/setup/setup-guides.service.js +38 -8
  122. package/dist/tools/admin-connectors.d.ts +3 -2
  123. package/dist/tools/admin-connectors.js +5 -4
  124. package/dist/tools/approvals.service.d.ts +45 -20
  125. package/dist/tools/approvals.service.js +19 -9
  126. package/dist/tools/call-scope.d.ts +60 -0
  127. package/dist/tools/call-scope.js +23 -0
  128. package/dist/tools/connector-setup.d.ts +28 -0
  129. package/dist/tools/connector-setup.js +33 -0
  130. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  131. package/dist/tools/connector-tools-jobs.js +40 -0
  132. package/dist/tools/connector-tools.processor.d.ts +32 -0
  133. package/dist/tools/connector-tools.processor.js +97 -0
  134. package/dist/tools/connectors.controller.d.ts +1 -0
  135. package/dist/tools/connectors.schemas.d.ts +1 -0
  136. package/dist/tools/connectors.schemas.js +5 -0
  137. package/dist/tools/connectors.service.d.ts +138 -14
  138. package/dist/tools/connectors.service.js +410 -50
  139. package/dist/tools/credentials.d.ts +35 -0
  140. package/dist/tools/credentials.js +89 -1
  141. package/dist/tools/drift.d.ts +5 -0
  142. package/dist/tools/drift.js +21 -2
  143. package/dist/tools/editable-endpoint.d.ts +23 -0
  144. package/dist/tools/editable-endpoint.js +92 -0
  145. package/dist/tools/network-asks.d.ts +13 -0
  146. package/dist/tools/network-asks.js +26 -2
  147. package/dist/tools/oauth/flow.d.ts +1 -1
  148. package/dist/tools/oauth/flow.js +3 -2
  149. package/dist/tools/pipeline.d.ts +30 -1
  150. package/dist/tools/pipeline.js +299 -59
  151. package/dist/tools/questions.service.d.ts +24 -3
  152. package/dist/tools/questions.service.js +3 -1
  153. package/dist/tools/registry.d.ts +14 -2
  154. package/dist/tools/registry.js +27 -6
  155. package/dist/tools/tools.module.js +4 -0
  156. package/package.json +3 -3
  157. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -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 };
@@ -3,6 +3,7 @@ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
5
  import { KernelEvents } from "../infra/events/kernel-events.js";
6
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
6
7
  import { OrgLock } from "../orgs/org-lock.js";
7
8
  import { EffectiveConfigs } from "./effective-config.js";
8
9
  import { ExtensionHost } from "./host.js";
@@ -120,6 +121,8 @@ export declare class OrgExtensionConfigs {
120
121
  private readonly effective;
121
122
  /** Why an installed extension is not loaded (`status` / `reason` of the unavailable ones). */
122
123
  private readonly availability;
124
+ /** Owes the org's template connector ensure when an extension is switched on (ruling R27). */
125
+ private readonly outbox;
123
126
  constructor(kdb: KernelDb, txHost: TransactionHost, host: ExtensionHost,
124
127
  /** The org row lock (orgs/org-lock.ts): joins the transaction. */
125
128
  orgLock: OrgLock,
@@ -130,7 +133,9 @@ export declare class OrgExtensionConfigs {
130
133
  /** The effective deployment config of each org (spec A §6): read for `needsConfig`. */
131
134
  effective: EffectiveConfigs,
132
135
  /** Why an installed extension is not loaded (`status` / `reason` of the unavailable ones). */
133
- availability: ExtensionAvailability);
136
+ availability: ExtensionAvailability,
137
+ /** Owes the org's template connector ensure when an extension is switched on (ruling R27). */
138
+ outbox: Pick<OutboxService, "add">);
134
139
  /** The kernel-schema handle of the current transaction. */
135
140
  private get db();
136
141
  /** After a write committed: a disabled extension's channel connections drop at once. */
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
13
+ import { oweTemplateConnectors } from "../catalog/template-connector-jobs.js";
13
14
  import { ApiError } from "../errors.js";
14
15
  import { audit } from "../identity/audit.js";
15
16
  import { afterCommit } from "../infra/database/after-commit.js";
@@ -17,6 +18,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { KernelEvents } from "../infra/events/kernel-events.js";
21
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
20
22
  import { OrgLock } from "../orgs/org-lock.js";
21
23
  import { EffectiveConfigs } from "./effective-config.js";
22
24
  import { alwaysOnExtensions, enabledExtensionsQuery, requiredExtensions } from "./enabled.js";
@@ -61,6 +63,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
61
63
  events;
62
64
  effective;
63
65
  availability;
66
+ outbox;
64
67
  constructor(kdb, txHost, host,
65
68
  /** The org row lock (orgs/org-lock.ts): joins the transaction. */
66
69
  orgLock,
@@ -71,7 +74,9 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
71
74
  /** The effective deployment config of each org (spec A §6): read for `needsConfig`. */
72
75
  effective,
73
76
  /** Why an installed extension is not loaded (`status` / `reason` of the unavailable ones). */
74
- availability) {
77
+ availability,
78
+ /** Owes the org's template connector ensure when an extension is switched on (ruling R27). */
79
+ outbox) {
75
80
  this.kdb = kdb;
76
81
  this.txHost = txHost;
77
82
  this.host = host;
@@ -80,6 +85,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
80
85
  this.events = events;
81
86
  this.effective = effective;
82
87
  this.availability = availability;
88
+ this.outbox = outbox;
83
89
  }
84
90
  /** The kernel-schema handle of the current transaction. */
85
91
  get db() {
@@ -256,6 +262,12 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
256
262
  updated_at: new Date(),
257
263
  }))
258
264
  .execute();
265
+ // Switched on: it may provide the connector kind of a template whose plugin is installed in
266
+ // the org without its connector; a worker creates the connectors it never had, once the
267
+ // extension is loaded there (ruling R27)
268
+ if (input.enabled === true && row?.enabled !== true) {
269
+ await oweTemplateConnectors(this.outbox, t, orgId);
270
+ }
259
271
  await audit(t, {
260
272
  actorAccountId,
261
273
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -491,7 +503,8 @@ OrgExtensionConfigs = __decorate([
491
503
  __param(4, Inject(ExtensionInstalls)),
492
504
  __param(5, Inject(KernelEvents)),
493
505
  __param(6, Inject(EffectiveConfigs)),
494
- __param(7, Inject(ExtensionAvailability))
506
+ __param(7, Inject(ExtensionAvailability)),
507
+ __param(8, Inject(OutboxService))
495
508
  ], OrgExtensionConfigs);
496
509
  export { OrgExtensionConfigs };
497
510
  /**
@@ -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)
@@ -153,6 +153,8 @@ const TOO_MANY = "too many git transfers are running in this organization; try a
153
153
  const BYTES_EXCEEDED = "this task reached its git transfer limit (tools.git.maxBytesPerRun).";
154
154
  const NOT_AN_ENDPOINT = "not a git smart-HTTP endpoint.";
155
155
  const reconnect = (host) => `${host} refused the connection's credential. Reconnect it under Settings → Connectors, then run the command again.`;
156
+ /** An org-owned input is missing (the connector is needs_config): not the member's to reconnect. */
157
+ const orgUnconfigured = (host) => `the connector that serves ${host} needs to be configured by an organization admin under Settings → Connectors before it can be used.`;
156
158
  const repoRefused = (repo) => `this task may not use the repository ${repo}.`;
157
159
  const upstreamFailed = (host, detail) => `the request to ${host} failed (${detail}).`;
158
160
  const BAD_PUSH = (why) => `the push could not be read (${why}).`;
@@ -621,7 +623,7 @@ let GitGateway = class GitGateway {
621
623
  catch (e) {
622
624
  if (e instanceof CredentialMissing) {
623
625
  pushResult("refused:credential");
624
- text(403, reconnect(target.host));
626
+ text(403, e.ownership === "org" ? orgUnconfigured(target.host) : reconnect(target.host));
625
627
  return;
626
628
  }
627
629
  if (e instanceof NetDeniedError) {
@@ -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
  /**