@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.
- package/bootstrap.json +5 -5
- 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,844 @@
|
|
|
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 { createHmac, timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { DeviceAccessError, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
|
|
12
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
13
|
+
import WebSocket, {} from "ws";
|
|
14
|
+
import { DialInGateway } from "../dial-in/gateway.js";
|
|
15
|
+
import { DialInHandlers } from "../dial-in/handlers.js";
|
|
16
|
+
import { DEVICE_STREAM_MESSAGE_TOO_BIG } from "../dial-in/streams.js";
|
|
17
|
+
import { audit } from "../identity/audit.js";
|
|
18
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
19
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
20
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
21
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
22
|
+
import { KERNEL_LOGGER, KEYRING } from "../infra/tokens.js";
|
|
23
|
+
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
24
|
+
import { DeviceAccessService } from "./device-access.service.js";
|
|
25
|
+
/**
|
|
26
|
+
* The close codes of a viewer socket (browser use spec §6.2). The panel reconnects with a new
|
|
27
|
+
* ticket after 1001 and 1012; 4401, 4404 and 4409 tell it why the view ended.
|
|
28
|
+
*/
|
|
29
|
+
export const VIEWER_CLOSE = {
|
|
30
|
+
normal: 1000,
|
|
31
|
+
/** The replica is shutting down: reconnect with a new ticket (another replica serves it). */
|
|
32
|
+
shutdown: 1001,
|
|
33
|
+
/**
|
|
34
|
+
* A viewer message over {@link VIEWER_MAX_MESSAGE_BYTES}, or one the device stream refused as
|
|
35
|
+
* too big for its frame capacity.
|
|
36
|
+
*/
|
|
37
|
+
tooBig: 1009,
|
|
38
|
+
/** The kernel failed (the database, a hop that could not connect). */
|
|
39
|
+
internal: 1011,
|
|
40
|
+
/**
|
|
41
|
+
* The device yielded the viewer to a lifecycle change that keeps its instance (a limits change,
|
|
42
|
+
* a rebuild in place): reconnect with a new ticket.
|
|
43
|
+
*/
|
|
44
|
+
restart: 1012,
|
|
45
|
+
/** A socket paused longer than {@link VIEWER_PAUSED_LIMIT_MS}: the peer took nothing. */
|
|
46
|
+
stalled: 1013,
|
|
47
|
+
/**
|
|
48
|
+
* No ticket, an unknown or used one, or its record no longer stands (owner, device,
|
|
49
|
+
* extension).
|
|
50
|
+
*/
|
|
51
|
+
badTicket: 4401,
|
|
52
|
+
/** The device, its running instance or the service is gone, or the provider cannot stream. */
|
|
53
|
+
gone: 4404,
|
|
54
|
+
/** The device's machine is not connected (`device-offline`). */
|
|
55
|
+
offline: 4409,
|
|
56
|
+
};
|
|
57
|
+
/** The header carrying the hop's MAC (hex HMAC-SHA256). */
|
|
58
|
+
export const HOP_HEADER = "x-capybara-hop";
|
|
59
|
+
/** The header carrying the hop's issue time (ms since the epoch), covered by the MAC. */
|
|
60
|
+
export const HOP_AT_HEADER = "x-capybara-hop-at";
|
|
61
|
+
/** How old (or how far ahead, clock skew) a hop's issue time may be. */
|
|
62
|
+
export const HOP_MAX_AGE_MS = 60_000;
|
|
63
|
+
/**
|
|
64
|
+
* The keyring purpose the hop key is derived for (HKDF-SHA256, info
|
|
65
|
+
* `capybara:device-stream-hop`).
|
|
66
|
+
*/
|
|
67
|
+
const HOP_KEY_INFO = "device-stream-hop";
|
|
68
|
+
/**
|
|
69
|
+
* A hop accepted once per ticket: `capk:device-stream-hop:<ticketId>` (a captured hop replays
|
|
70
|
+
* nothing).
|
|
71
|
+
*/
|
|
72
|
+
const HOP_SEEN_PREFIX = "capk:device-stream-hop:";
|
|
73
|
+
/** How long the holder waits for the hop's first message (the ticket record). */
|
|
74
|
+
export const HOP_FIRST_MESSAGE_MS = 10_000;
|
|
75
|
+
/** How long a hop has to connect to the holder. */
|
|
76
|
+
const HOP_CONNECT_MS = 10_000;
|
|
77
|
+
/** A ticket id as minted (`randomBytes(24)` in base64url) or any similar opaque id. */
|
|
78
|
+
export const TICKET_ID_RE = /^[A-Za-z0-9_-]{16,128}$/;
|
|
79
|
+
/**
|
|
80
|
+
* Outgoing backpressure: while a socket has more than this many bytes queued, the next message
|
|
81
|
+
* waits until its write is flushed (the pipe stops pulling from its source).
|
|
82
|
+
*/
|
|
83
|
+
const SEND_HIGH_WATER_BYTES = 1024 * 1024;
|
|
84
|
+
/**
|
|
85
|
+
* Incoming backpressure: a socket with this many bytes received and not yet forwarded is paused
|
|
86
|
+
* (`ws.pause()`, no more reads) until half of them are forwarded.
|
|
87
|
+
*/
|
|
88
|
+
export const RECEIVE_HIGH_WATER_BYTES = 2 * 1024 * 1024;
|
|
89
|
+
/**
|
|
90
|
+
* The largest message a viewer sends towards the service (input events are small). The shared
|
|
91
|
+
* WebSocket scope's `maxPayload` is the dial-in frame limit, so the viewer routes enforce this
|
|
92
|
+
* themselves: a larger message closes the socket with 1009.
|
|
93
|
+
*/
|
|
94
|
+
export const VIEWER_MAX_MESSAGE_BYTES = 256 * 1024;
|
|
95
|
+
/** How often viewer and hop sockets are pinged; two pings without a pong end the socket. */
|
|
96
|
+
export const VIEWER_PING_INTERVAL_MS = 20_000;
|
|
97
|
+
/**
|
|
98
|
+
* How long a socket may stay paused (its peer not taking what it sends) before it is closed
|
|
99
|
+
* with 1013: a paused socket reads nothing, so neither a pong nor a closed tab would be seen.
|
|
100
|
+
*/
|
|
101
|
+
export const VIEWER_PAUSED_LIMIT_MS = 30_000;
|
|
102
|
+
/**
|
|
103
|
+
* How often an open viewer checks its ticket's record again ({@link DeviceAccessService.ticketCheck}):
|
|
104
|
+
* an access that lapsed mid-view (the extension switched off, the service no longer declared, the
|
|
105
|
+
* conversation deleted or its owner changed, the provider switched off) ends the view within this
|
|
106
|
+
* time. A timer of the viewer's own socket, cleared with it.
|
|
107
|
+
*/
|
|
108
|
+
export const VIEWER_RECHECK_MS = 60_000;
|
|
109
|
+
/** A WebSocket close reason is at most 123 UTF-8 bytes. */
|
|
110
|
+
const closeReason = (text) => {
|
|
111
|
+
let out = text;
|
|
112
|
+
while (Buffer.byteLength(out) > 123)
|
|
113
|
+
out = out.slice(0, -1);
|
|
114
|
+
return out;
|
|
115
|
+
};
|
|
116
|
+
const toBytes = (data) => Array.isArray(data)
|
|
117
|
+
? Buffer.concat(data)
|
|
118
|
+
: data instanceof ArrayBuffer
|
|
119
|
+
? new Uint8Array(data)
|
|
120
|
+
: data;
|
|
121
|
+
const errMsg = (e) => (e instanceof Error ? e.message : String(e));
|
|
122
|
+
/**
|
|
123
|
+
* A WebSocket (the browser's, a hop in either direction) as a {@link PipeEnd}. Received messages
|
|
124
|
+
* are queued from the moment it is wrapped (nothing is lost while the other end opens); once
|
|
125
|
+
* {@link RECEIVE_HIGH_WATER_BYTES} are queued the socket's reads pause, and a socket paused
|
|
126
|
+
* longer than `pausedLimitMs` is closed (1013). A message over `maxMessageBytes` closes it (1009).
|
|
127
|
+
* The socket is pinged every `pingIntervalMs` (its own timer, cleared with the socket); two
|
|
128
|
+
* pings without a pong while it is reading terminate it, so a closed tab is noticed. A send waits
|
|
129
|
+
* for its flush while the socket's buffer is over {@link SEND_HIGH_WATER_BYTES}, and is dropped
|
|
130
|
+
* once the socket is no longer open (the pipe is ending).
|
|
131
|
+
*/
|
|
132
|
+
export class WsEnd {
|
|
133
|
+
ws;
|
|
134
|
+
opts;
|
|
135
|
+
queue = [];
|
|
136
|
+
queuedBytes = 0;
|
|
137
|
+
wake = null;
|
|
138
|
+
pausedAt = null;
|
|
139
|
+
missedPongs = 0;
|
|
140
|
+
ended = false;
|
|
141
|
+
timer;
|
|
142
|
+
overLimit = false;
|
|
143
|
+
closed;
|
|
144
|
+
messages;
|
|
145
|
+
constructor(ws, opts) {
|
|
146
|
+
this.ws = ws;
|
|
147
|
+
this.opts = opts;
|
|
148
|
+
ws.on("message", (data) => {
|
|
149
|
+
const m = toBytes(data);
|
|
150
|
+
if (opts.maxMessageBytes !== undefined && m.byteLength > opts.maxMessageBytes) {
|
|
151
|
+
this.overLimit = true;
|
|
152
|
+
this.close(1009, "message too big");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
this.queue.push(m);
|
|
156
|
+
this.queuedBytes += m.byteLength;
|
|
157
|
+
if (this.pausedAt === null && this.queuedBytes >= RECEIVE_HIGH_WATER_BYTES) {
|
|
158
|
+
this.pausedAt = Date.now();
|
|
159
|
+
ws.pause();
|
|
160
|
+
}
|
|
161
|
+
this.notify();
|
|
162
|
+
});
|
|
163
|
+
ws.on("pong", () => {
|
|
164
|
+
this.missedPongs = 0;
|
|
165
|
+
});
|
|
166
|
+
// an error is followed by close; without a listener it would be thrown. A message over the
|
|
167
|
+
// socket's own maxPayload is one (ws closes the socket with 1009)
|
|
168
|
+
ws.on("error", (err) => {
|
|
169
|
+
if (err.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")
|
|
170
|
+
this.overLimit = true;
|
|
171
|
+
});
|
|
172
|
+
this.closed = new Promise((resolve) => {
|
|
173
|
+
ws.once("close", (code, reason) => {
|
|
174
|
+
this.ended = true;
|
|
175
|
+
clearInterval(this.timer);
|
|
176
|
+
this.notify();
|
|
177
|
+
resolve({ code, reason: reason.toString("utf8") });
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
const watch = () => {
|
|
181
|
+
if (this.timer !== undefined || this.ended)
|
|
182
|
+
return;
|
|
183
|
+
this.timer = setInterval(() => this.tick(), opts.pingIntervalMs);
|
|
184
|
+
this.timer.unref();
|
|
185
|
+
};
|
|
186
|
+
if (ws.readyState === WebSocket.OPEN)
|
|
187
|
+
watch();
|
|
188
|
+
else
|
|
189
|
+
ws.once("open", watch);
|
|
190
|
+
this.messages = {
|
|
191
|
+
[Symbol.asyncIterator]: () => ({
|
|
192
|
+
next: () => this.next(),
|
|
193
|
+
}),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
get isOpen() {
|
|
197
|
+
return this.ws.readyState === WebSocket.OPEN;
|
|
198
|
+
}
|
|
199
|
+
/** Whether the socket ended because a received message was over its limit. */
|
|
200
|
+
get tooBig() {
|
|
201
|
+
return this.overLimit;
|
|
202
|
+
}
|
|
203
|
+
/** Whether the socket's reads are paused (a test seam). */
|
|
204
|
+
get paused() {
|
|
205
|
+
return this.pausedAt !== null;
|
|
206
|
+
}
|
|
207
|
+
/** The bytes received and not yet taken (a test seam). */
|
|
208
|
+
get pending() {
|
|
209
|
+
return this.queuedBytes;
|
|
210
|
+
}
|
|
211
|
+
tick() {
|
|
212
|
+
if (!this.isOpen)
|
|
213
|
+
return;
|
|
214
|
+
if (this.pausedAt !== null) {
|
|
215
|
+
// a paused socket reads no pong: it gets a bounded time instead
|
|
216
|
+
if (Date.now() - this.pausedAt >= this.opts.pausedLimitMs)
|
|
217
|
+
this.close(1013, "the peer is not taking messages");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (this.missedPongs >= 2) {
|
|
221
|
+
this.ws.terminate();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.missedPongs++;
|
|
225
|
+
this.ws.ping();
|
|
226
|
+
}
|
|
227
|
+
notify() {
|
|
228
|
+
const w = this.wake;
|
|
229
|
+
this.wake = null;
|
|
230
|
+
w?.();
|
|
231
|
+
}
|
|
232
|
+
/** The next received message; done once the socket closed and the queue is empty. */
|
|
233
|
+
async next() {
|
|
234
|
+
for (;;) {
|
|
235
|
+
const m = this.queue.shift();
|
|
236
|
+
if (m !== undefined) {
|
|
237
|
+
this.queuedBytes -= m.byteLength;
|
|
238
|
+
if (this.pausedAt !== null && this.queuedBytes <= RECEIVE_HIGH_WATER_BYTES / 2) {
|
|
239
|
+
this.pausedAt = null;
|
|
240
|
+
this.missedPongs = 0;
|
|
241
|
+
this.ws.resume();
|
|
242
|
+
}
|
|
243
|
+
return { value: m, done: false };
|
|
244
|
+
}
|
|
245
|
+
if (this.ended)
|
|
246
|
+
return { value: undefined, done: true };
|
|
247
|
+
await new Promise((resolve) => {
|
|
248
|
+
this.wake = resolve;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
send(m) {
|
|
253
|
+
if (!this.isOpen)
|
|
254
|
+
return Promise.resolve();
|
|
255
|
+
if (this.ws.bufferedAmount < SEND_HIGH_WATER_BYTES) {
|
|
256
|
+
this.ws.send(m, { binary: true });
|
|
257
|
+
return Promise.resolve();
|
|
258
|
+
}
|
|
259
|
+
return new Promise((resolve) => this.ws.send(m, { binary: true }, () => resolve()));
|
|
260
|
+
}
|
|
261
|
+
/** Closes the socket (a socket still connecting is dropped); a no-op once closing. */
|
|
262
|
+
close(code, reason) {
|
|
263
|
+
const s = this.ws.readyState;
|
|
264
|
+
if (s === WebSocket.CONNECTING)
|
|
265
|
+
this.ws.terminate();
|
|
266
|
+
else if (s === WebSocket.OPEN)
|
|
267
|
+
this.ws.close(code, closeReason(reason));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Forwards every message of `from` to `to`, in order, awaiting each send (backpressure).
|
|
272
|
+
* Resolves with the send error that stopped it, or `undefined` once `from` ended; the caller
|
|
273
|
+
* ends the whole pipe on a failure (a pipe never runs one way only).
|
|
274
|
+
*/
|
|
275
|
+
async function pump(from, to) {
|
|
276
|
+
try {
|
|
277
|
+
for await (const m of from)
|
|
278
|
+
await to.send(m);
|
|
279
|
+
return {};
|
|
280
|
+
}
|
|
281
|
+
catch (failed) {
|
|
282
|
+
return { failed: failed ?? new Error("send failed") };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Whether a refused send was a message too big for the stream's frames: the error carries
|
|
287
|
+
* {@link DEVICE_STREAM_MESSAGE_TOO_BIG} as its `code` (the dial-in stream's; a provider's stream
|
|
288
|
+
* may use the same code).
|
|
289
|
+
*/
|
|
290
|
+
const isTooBig = (e) => typeof e === "object" &&
|
|
291
|
+
e !== null &&
|
|
292
|
+
e.code === DEVICE_STREAM_MESSAGE_TOO_BIG;
|
|
293
|
+
/** Resolves once `s` aborts. */
|
|
294
|
+
const abortedOf = (s) => new Promise((resolve) => {
|
|
295
|
+
if (s.aborted)
|
|
296
|
+
resolve();
|
|
297
|
+
else
|
|
298
|
+
s.addEventListener("abort", () => resolve(), { once: true });
|
|
299
|
+
});
|
|
300
|
+
/**
|
|
301
|
+
* The hop keys: the one derived from the current master key first (it signs), then those of the
|
|
302
|
+
* previous master keys (they still verify, so replicas mid key rotation accept each other's hops).
|
|
303
|
+
*/
|
|
304
|
+
function hopKeys(keyring) {
|
|
305
|
+
const derived = keyring.deriveKey(HOP_KEY_INFO);
|
|
306
|
+
const out = [derived.current];
|
|
307
|
+
for (const id of keyring.toJSON().previousIds) {
|
|
308
|
+
const k = id === derived.currentId ? undefined : derived.byId(id);
|
|
309
|
+
if (k !== undefined)
|
|
310
|
+
out.push(k);
|
|
311
|
+
}
|
|
312
|
+
return out;
|
|
313
|
+
}
|
|
314
|
+
const macWith = (key, parts) => createHmac("sha256", key).update(parts.join("\n")).digest();
|
|
315
|
+
/** The hex MAC over `parts` under the current hop key. */
|
|
316
|
+
export function signHop(keyring, parts) {
|
|
317
|
+
return macWith(hopKeys(keyring)[0], parts).toString("hex");
|
|
318
|
+
}
|
|
319
|
+
/** Whether `mac` (64 hex) is the MAC over `parts` under any hop key (constant-time compare). */
|
|
320
|
+
export function verifyHopMac(keyring, parts, mac) {
|
|
321
|
+
if (typeof mac !== "string" || !/^[0-9a-f]{64}$/.test(mac))
|
|
322
|
+
return false;
|
|
323
|
+
const got = Buffer.from(mac, "hex");
|
|
324
|
+
let ok = false;
|
|
325
|
+
for (const key of hopKeys(keyring))
|
|
326
|
+
if (timingSafeEqual(got, macWith(key, parts)))
|
|
327
|
+
ok = true;
|
|
328
|
+
return ok;
|
|
329
|
+
}
|
|
330
|
+
/** The headers of a hop for `ticketId` issued at `at` (signed with the current key). */
|
|
331
|
+
export function hopHeaders(keyring, ticketId, at) {
|
|
332
|
+
return {
|
|
333
|
+
[HOP_HEADER]: signHop(keyring, ["hop", ticketId, String(at)]),
|
|
334
|
+
[HOP_AT_HEADER]: String(at),
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Whether a hop's headers are valid for `ticketId`: the MAC over the ticket id and the issue time
|
|
339
|
+
* under any hop key, issued at most {@link HOP_MAX_AGE_MS} away from `now`. Reads nothing else.
|
|
340
|
+
*/
|
|
341
|
+
export function verifyHopHeaders(keyring, ticketId, mac, at, now) {
|
|
342
|
+
if (typeof at !== "string" || !/^[0-9]{1,16}$/.test(at))
|
|
343
|
+
return false;
|
|
344
|
+
if (Math.abs(now - Number(at)) > HOP_MAX_AGE_MS)
|
|
345
|
+
return false;
|
|
346
|
+
return verifyHopMac(keyring, ["hop", ticketId, at], mac);
|
|
347
|
+
}
|
|
348
|
+
/** A ticket record taken from Redis, checked field by field; null for anything else. */
|
|
349
|
+
export function parseTicketRecord(raw) {
|
|
350
|
+
if (typeof raw !== "object" || raw === null)
|
|
351
|
+
return null;
|
|
352
|
+
const r = raw;
|
|
353
|
+
const keys = [
|
|
354
|
+
"orgId",
|
|
355
|
+
"accountId",
|
|
356
|
+
"conversationId",
|
|
357
|
+
"deviceId",
|
|
358
|
+
"providerName",
|
|
359
|
+
"service",
|
|
360
|
+
"extension",
|
|
361
|
+
];
|
|
362
|
+
for (const k of keys)
|
|
363
|
+
if (typeof r[k] !== "string" || r[k] === "")
|
|
364
|
+
return null;
|
|
365
|
+
return {
|
|
366
|
+
orgId: r.orgId,
|
|
367
|
+
accountId: r.accountId,
|
|
368
|
+
conversationId: r.conversationId,
|
|
369
|
+
deviceId: r.deviceId,
|
|
370
|
+
providerName: r.providerName,
|
|
371
|
+
service: r.service,
|
|
372
|
+
extension: r.extension,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* The viewer endpoint (browser use spec §6.2, served on the gateway role by `viewer-routes.ts`):
|
|
377
|
+
* `GET /device/stream?ticket=` takes the single-use viewer ticket
|
|
378
|
+
* (`DeviceAccessService.takeTicket`) and pipes the device service's stream to the browser, bytes
|
|
379
|
+
* unchanged both ways. Where the stream opens:
|
|
380
|
+
*
|
|
381
|
+
* - A device whose provider declares `permissions.dialIn` (a local device) streams only from the
|
|
382
|
+
* gateway replica holding its machine's socket. Any other replica hops once: a `ws` connection
|
|
383
|
+
* to `<holderAddress>/internal/device-stream/<ticketId>` carrying `X-Capybara-Hop` (hex
|
|
384
|
+
* HMAC-SHA256 under the key derived from the master key for `device-stream-hop`, over the
|
|
385
|
+
* ticket id and the issue time `X-Capybara-Hop-At`). The ticket is consumed here; the hop's
|
|
386
|
+
* first message is the record, MACed with the same key. The holder checks the MAC
|
|
387
|
+
* (constant time) and the issue time (at most {@link HOP_MAX_AGE_MS} away) before anything
|
|
388
|
+
* else, accepts each ticket's hop once (`capk:device-stream-hop:<ticketId>`), never takes a
|
|
389
|
+
* ticket, and opens locally.
|
|
390
|
+
* - Every other device opens on the replica the viewer reached (the provider's `openStream`).
|
|
391
|
+
*
|
|
392
|
+
* A local open checks the record again ({@link DeviceAccessService.ticketCheck}: 4401, or 4404
|
|
393
|
+
* when the device's provider is off in the org) and keeps checking it every
|
|
394
|
+
* {@link VIEWER_RECHECK_MS} while the viewer lives (a lapsed access closes it the same way), holds
|
|
395
|
+
* the device for the viewer's life ({@link SandboxService.holdForStream}: an open viewer counts as
|
|
396
|
+
* device use) and audits `browser.view` / `browser.view_closed`; frames are never audited and
|
|
397
|
+
* never pass through Redis or PG. Close codes: {@link VIEWER_CLOSE}. Everything settles when any
|
|
398
|
+
* side closes: the browser socket, the hop, the provider stream, the hold (a lifecycle change)
|
|
399
|
+
* or this replica's shutdown ({@link stop}: 1001). The sockets live in this process only (they
|
|
400
|
+
* cannot live anywhere else); what other replicas need is in Redis.
|
|
401
|
+
*
|
|
402
|
+
* Backpressure pauses, never drops, in both directions: service to browser, the next message
|
|
403
|
+
* waits while the browser socket has over 1 MiB queued (the provider stream's credit then holds
|
|
404
|
+
* the service back); browser to service, each message waits for `DeviceStream.send` (the
|
|
405
|
+
* service's credit), and a socket with 2 MiB received and not yet forwarded is paused until half
|
|
406
|
+
* is. A socket paused for 30 s is closed (1013), a socket that misses two pings is terminated, a
|
|
407
|
+
* viewer message over 256 KiB closes it (1009), and a send the stream refuses ends the whole pipe
|
|
408
|
+
* (1009 when the stream lives on: the message did not fit its frames; else 4404 / 4409). Every end
|
|
409
|
+
* releases the hold and audits the close.
|
|
410
|
+
*/
|
|
411
|
+
let DeviceStreamViewers = class DeviceStreamViewers {
|
|
412
|
+
access;
|
|
413
|
+
sandbox;
|
|
414
|
+
gateway;
|
|
415
|
+
handlers;
|
|
416
|
+
kdb;
|
|
417
|
+
locks;
|
|
418
|
+
keyring;
|
|
419
|
+
config;
|
|
420
|
+
log;
|
|
421
|
+
open = new Set();
|
|
422
|
+
stopping = false;
|
|
423
|
+
/** How long the holder waits for a hop's first message (a test seam). */
|
|
424
|
+
firstMessageMs = HOP_FIRST_MESSAGE_MS;
|
|
425
|
+
/** {@link VIEWER_PING_INTERVAL_MS} (a test seam). */
|
|
426
|
+
pingIntervalMs = VIEWER_PING_INTERVAL_MS;
|
|
427
|
+
/** {@link VIEWER_PAUSED_LIMIT_MS} (a test seam). */
|
|
428
|
+
pausedLimitMs = VIEWER_PAUSED_LIMIT_MS;
|
|
429
|
+
/** {@link VIEWER_RECHECK_MS} (a test seam). */
|
|
430
|
+
recheckMs = VIEWER_RECHECK_MS;
|
|
431
|
+
constructor(access, sandbox, gateway, handlers, kdb, locks, keyring, config, log) {
|
|
432
|
+
this.access = access;
|
|
433
|
+
this.sandbox = sandbox;
|
|
434
|
+
this.gateway = gateway;
|
|
435
|
+
this.handlers = handlers;
|
|
436
|
+
this.kdb = kdb;
|
|
437
|
+
this.locks = locks;
|
|
438
|
+
this.keyring = keyring;
|
|
439
|
+
this.config = config;
|
|
440
|
+
this.log = log;
|
|
441
|
+
}
|
|
442
|
+
/** {@link verifyHopHeaders} under this kernel's keys, now. */
|
|
443
|
+
verifyHop(ticketId, mac, at) {
|
|
444
|
+
return verifyHopHeaders(this.keyring, ticketId, mac, at, Date.now());
|
|
445
|
+
}
|
|
446
|
+
/** How a viewer or hop socket is watched (`maxMessageBytes` for sockets carrying input). */
|
|
447
|
+
socketOptions(maxMessageBytes) {
|
|
448
|
+
return {
|
|
449
|
+
pingIntervalMs: this.pingIntervalMs,
|
|
450
|
+
pausedLimitMs: this.pausedLimitMs,
|
|
451
|
+
...(maxMessageBytes !== undefined && { maxMessageBytes }),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
/** Accepts the hop of `ticketId` once (a replay of a captured hop is refused). */
|
|
455
|
+
async claimHop(ticketId) {
|
|
456
|
+
// a marker that is never released: it outlives the hop's age limit, then expires
|
|
457
|
+
return this.locks.lease(`${HOP_SEEN_PREFIX}${ticketId}`, "1", HOP_MAX_AGE_MS * 2);
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Serves a browser's viewer socket for the ticket `ticketId` until everything settled.
|
|
461
|
+
* `onTaken` runs once a valid ticket was taken (the route gives the attempt back to its
|
|
462
|
+
* per-address limit).
|
|
463
|
+
*/
|
|
464
|
+
serve(socket, ticketId, onTaken) {
|
|
465
|
+
return this.track(socket, (end) => this.serveViewer(end, ticketId, onTaken));
|
|
466
|
+
}
|
|
467
|
+
/** Serves a hop from another gateway replica (its headers were verified and claimed). */
|
|
468
|
+
serveHop(socket, ticketId, at) {
|
|
469
|
+
return this.track(socket, (end) => this.serveHopped(end, ticketId, at));
|
|
470
|
+
}
|
|
471
|
+
/** Closes every open viewer (1001: the panel reconnects elsewhere) and waits until settled. */
|
|
472
|
+
async stop() {
|
|
473
|
+
this.stopping = true;
|
|
474
|
+
const all = [...this.open];
|
|
475
|
+
for (const v of all)
|
|
476
|
+
v.end.close(VIEWER_CLOSE.shutdown, "shutting down");
|
|
477
|
+
await Promise.allSettled(all.map((v) => v.done));
|
|
478
|
+
}
|
|
479
|
+
/** How many viewers this replica serves (a test seam). */
|
|
480
|
+
count() {
|
|
481
|
+
return this.open.size;
|
|
482
|
+
}
|
|
483
|
+
track(socket, fn) {
|
|
484
|
+
// both carry the browser's messages towards the service (a hop's first message is small)
|
|
485
|
+
const end = new WsEnd(socket, this.socketOptions(VIEWER_MAX_MESSAGE_BYTES));
|
|
486
|
+
if (this.stopping) {
|
|
487
|
+
end.close(VIEWER_CLOSE.shutdown, "shutting down");
|
|
488
|
+
return Promise.resolve();
|
|
489
|
+
}
|
|
490
|
+
const entry = { end, done: Promise.resolve() };
|
|
491
|
+
entry.done = (async () => {
|
|
492
|
+
try {
|
|
493
|
+
await fn(end);
|
|
494
|
+
}
|
|
495
|
+
catch (err) {
|
|
496
|
+
this.log.warn("device stream viewer failed", { error: errMsg(err) });
|
|
497
|
+
end.close(VIEWER_CLOSE.internal, "internal error");
|
|
498
|
+
}
|
|
499
|
+
finally {
|
|
500
|
+
this.open.delete(entry);
|
|
501
|
+
}
|
|
502
|
+
})();
|
|
503
|
+
this.open.add(entry);
|
|
504
|
+
return entry.done;
|
|
505
|
+
}
|
|
506
|
+
async serveViewer(end, ticketId, onTaken) {
|
|
507
|
+
if (!TICKET_ID_RE.test(ticketId)) {
|
|
508
|
+
end.close(VIEWER_CLOSE.badTicket, "invalid ticket");
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const record = parseTicketRecord(await this.access.takeTicket(ticketId).catch(() => null));
|
|
512
|
+
if (record === null) {
|
|
513
|
+
end.close(VIEWER_CLOSE.badTicket, "invalid ticket");
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
await onTaken?.().catch((err) => this.log.warn("cannot refund a device stream viewer attempt", { error: errMsg(err) }));
|
|
517
|
+
if (!end.isOpen)
|
|
518
|
+
return;
|
|
519
|
+
// a long-lived socket outside any request's org guard: the record's org scopes every query
|
|
520
|
+
// of this viewer (Postgres RLS)
|
|
521
|
+
await withOrgScope(record.orgId, async () => {
|
|
522
|
+
const serving = await this.handlers.forDevice(record.deviceId);
|
|
523
|
+
if ("plugin" in serving && !this.gateway.holdsLocally(record.deviceId)) {
|
|
524
|
+
await this.hop(end, ticketId, record);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
await this.openLocal(end, record, ticketId);
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
async serveHopped(end, ticketId, at) {
|
|
531
|
+
// the first message is the record the first replica took with the ticket
|
|
532
|
+
let timer;
|
|
533
|
+
const first = await Promise.race([
|
|
534
|
+
end.next(),
|
|
535
|
+
new Promise((resolve) => {
|
|
536
|
+
timer = setTimeout(() => resolve(null), this.firstMessageMs);
|
|
537
|
+
timer.unref();
|
|
538
|
+
}),
|
|
539
|
+
]).finally(() => clearTimeout(timer));
|
|
540
|
+
const record = first === null || first.done ? null : this.openHopRecord(first.value, ticketId, at);
|
|
541
|
+
if (record === null) {
|
|
542
|
+
end.close(VIEWER_CLOSE.badTicket, "invalid hop");
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
await withOrgScope(record.orgId, () => this.openLocal(end, record, null));
|
|
546
|
+
}
|
|
547
|
+
/** The hop's first message `{ record, mac }` as the record, when its MAC is valid. */
|
|
548
|
+
openHopRecord(m, ticketId, at) {
|
|
549
|
+
let msg;
|
|
550
|
+
try {
|
|
551
|
+
msg = JSON.parse(Buffer.from(m).toString("utf8"));
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
const { record, mac } = (msg ?? {});
|
|
557
|
+
if (typeof record !== "string")
|
|
558
|
+
return null;
|
|
559
|
+
if (!verifyHopMac(this.keyring, ["record", ticketId, at, record], mac))
|
|
560
|
+
return null;
|
|
561
|
+
try {
|
|
562
|
+
return parseTicketRecord(JSON.parse(record));
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Hops to the gateway replica holding the device's machine and pipes the browser to it. The
|
|
570
|
+
* holder's close code reaches the browser (an unexpected one, or a hop that failed, is 1011);
|
|
571
|
+
* no holder is 4409.
|
|
572
|
+
*/
|
|
573
|
+
async hop(end, ticketId, record) {
|
|
574
|
+
const address = await this.gateway.holderAddress(record.deviceId);
|
|
575
|
+
if (address === null) {
|
|
576
|
+
end.close(VIEWER_CLOSE.offline, "device-offline");
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
if (!end.isOpen)
|
|
580
|
+
return;
|
|
581
|
+
const at = Date.now();
|
|
582
|
+
const url = `${address.replace(/^http/, "ws")}/internal/device-stream/${ticketId}`;
|
|
583
|
+
// the holder's messages are the service's: bounded by the dial-in frame limit
|
|
584
|
+
const up = new WsEnd(new WebSocket(url, {
|
|
585
|
+
headers: hopHeaders(this.keyring, ticketId, at),
|
|
586
|
+
handshakeTimeout: HOP_CONNECT_MS,
|
|
587
|
+
maxPayload: this.config.get().devices.dialIn.maxFrameBytes,
|
|
588
|
+
}), this.socketOptions());
|
|
589
|
+
const recordJson = JSON.stringify(record);
|
|
590
|
+
const opened = new Promise((resolve) => {
|
|
591
|
+
up.ws.once("open", () => {
|
|
592
|
+
up.ws.send(JSON.stringify({
|
|
593
|
+
record: recordJson,
|
|
594
|
+
mac: signHop(this.keyring, ["record", ticketId, String(at), recordJson]),
|
|
595
|
+
}));
|
|
596
|
+
resolve(true);
|
|
597
|
+
});
|
|
598
|
+
void up.closed.then(() => resolve(false));
|
|
599
|
+
});
|
|
600
|
+
const first = await Promise.race([
|
|
601
|
+
opened.then((ok) => (ok ? "open" : "up")),
|
|
602
|
+
end.closed.then(() => "viewer"),
|
|
603
|
+
]);
|
|
604
|
+
if (first === "open") {
|
|
605
|
+
// both directions only once the holder has the record
|
|
606
|
+
void pump(end.messages, up);
|
|
607
|
+
void pump(up.messages, end);
|
|
608
|
+
}
|
|
609
|
+
const settled = await Promise.race([
|
|
610
|
+
up.closed.then((c) => ({ side: "up", code: c.code, reason: c.reason })),
|
|
611
|
+
end.closed.then(() => ({ side: "viewer", code: 0, reason: "" })),
|
|
612
|
+
]);
|
|
613
|
+
if (settled.side === "viewer") {
|
|
614
|
+
up.close(VIEWER_CLOSE.normal, "viewer closed");
|
|
615
|
+
await up.closed;
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
const forwarded = new Set([
|
|
619
|
+
VIEWER_CLOSE.normal,
|
|
620
|
+
VIEWER_CLOSE.shutdown,
|
|
621
|
+
VIEWER_CLOSE.tooBig,
|
|
622
|
+
VIEWER_CLOSE.stalled,
|
|
623
|
+
VIEWER_CLOSE.restart,
|
|
624
|
+
VIEWER_CLOSE.badTicket,
|
|
625
|
+
VIEWER_CLOSE.gone,
|
|
626
|
+
VIEWER_CLOSE.offline,
|
|
627
|
+
]);
|
|
628
|
+
// a holder message over this socket's maxPayload (ws closes it 1009, or 1006 when it drops)
|
|
629
|
+
if (up.tooBig)
|
|
630
|
+
end.close(VIEWER_CLOSE.tooBig, "message too big");
|
|
631
|
+
else if (forwarded.has(settled.code))
|
|
632
|
+
end.close(settled.code, settled.reason);
|
|
633
|
+
else {
|
|
634
|
+
this.log.warn("device stream hop ended unexpectedly", {
|
|
635
|
+
deviceId: record.deviceId,
|
|
636
|
+
code: settled.code,
|
|
637
|
+
});
|
|
638
|
+
end.close(VIEWER_CLOSE.internal, "hop failed");
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Opens the service's stream on this replica and pipes it to `end` until any side closes.
|
|
643
|
+
* `ticketId` is set for a viewer that reached this replica directly (a machine that moved
|
|
644
|
+
* meanwhile is hopped to); null for a hop, which never hops again.
|
|
645
|
+
*/
|
|
646
|
+
async openLocal(end, record, ticketId) {
|
|
647
|
+
const first = await this.access.ticketCheck(record);
|
|
648
|
+
if (first !== "stands") {
|
|
649
|
+
if (first === "provider_off")
|
|
650
|
+
end.close(VIEWER_CLOSE.gone, "provider unavailable");
|
|
651
|
+
else
|
|
652
|
+
end.close(VIEWER_CLOSE.badTicket, "invalid ticket");
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const life = new AbortController();
|
|
656
|
+
void end.closed.then(() => life.abort());
|
|
657
|
+
let hold;
|
|
658
|
+
try {
|
|
659
|
+
hold = await this.sandbox.holdForStream(record.deviceId, record.orgId, life.signal);
|
|
660
|
+
}
|
|
661
|
+
catch (err) {
|
|
662
|
+
if (life.signal.aborted)
|
|
663
|
+
return;
|
|
664
|
+
if (err instanceof DeviceAccessError) {
|
|
665
|
+
end.close(VIEWER_CLOSE.gone, closeReason(err.message));
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
throw err;
|
|
669
|
+
}
|
|
670
|
+
let stream;
|
|
671
|
+
try {
|
|
672
|
+
stream = await hold.p.openStream(hold.h, { service: record.service }, hold.signal);
|
|
673
|
+
}
|
|
674
|
+
catch (err) {
|
|
675
|
+
await hold.release();
|
|
676
|
+
if (life.signal.aborted)
|
|
677
|
+
return;
|
|
678
|
+
if (isElsewhere(err) && ticketId !== null) {
|
|
679
|
+
await this.hop(end, ticketId, record);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (isDeviceOfflineError(err) || isElsewhere(err)) {
|
|
683
|
+
end.close(VIEWER_CLOSE.offline, "device-offline");
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
this.log.debug("device stream did not open", {
|
|
687
|
+
deviceId: record.deviceId,
|
|
688
|
+
service: record.service,
|
|
689
|
+
error: errMsg(err),
|
|
690
|
+
});
|
|
691
|
+
end.close(VIEWER_CLOSE.gone, "service unavailable");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const started = Date.now();
|
|
695
|
+
let viewed = false;
|
|
696
|
+
let closeCode = VIEWER_CLOSE.normal;
|
|
697
|
+
// the record is checked again while the viewer lives: a lapsed access ends the view
|
|
698
|
+
const lapsed = new AbortController();
|
|
699
|
+
const lapse = { why: null };
|
|
700
|
+
let checking = false;
|
|
701
|
+
const recheck = setInterval(() => {
|
|
702
|
+
if (checking || lapsed.signal.aborted)
|
|
703
|
+
return;
|
|
704
|
+
checking = true;
|
|
705
|
+
void this.access
|
|
706
|
+
.ticketCheck(record)
|
|
707
|
+
.then((r) => {
|
|
708
|
+
if (r === "stands")
|
|
709
|
+
return;
|
|
710
|
+
lapse.why =
|
|
711
|
+
r === "provider_off"
|
|
712
|
+
? { code: VIEWER_CLOSE.gone, reason: "provider unavailable" }
|
|
713
|
+
: { code: VIEWER_CLOSE.badTicket, reason: "access revoked" };
|
|
714
|
+
lapsed.abort();
|
|
715
|
+
}, (err) => {
|
|
716
|
+
// fail closed: access that cannot be checked is not kept
|
|
717
|
+
this.log.warn("cannot check a device stream viewer's access again", {
|
|
718
|
+
deviceId: record.deviceId,
|
|
719
|
+
error: errMsg(err),
|
|
720
|
+
});
|
|
721
|
+
lapse.why = { code: VIEWER_CLOSE.internal, reason: "internal error" };
|
|
722
|
+
lapsed.abort();
|
|
723
|
+
})
|
|
724
|
+
.finally(() => {
|
|
725
|
+
checking = false;
|
|
726
|
+
});
|
|
727
|
+
}, this.recheckMs);
|
|
728
|
+
recheck.unref();
|
|
729
|
+
try {
|
|
730
|
+
if (!end.isOpen) {
|
|
731
|
+
stream.close("viewer closed");
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
await audit(this.kdb.db, {
|
|
735
|
+
actorAccountId: record.accountId,
|
|
736
|
+
orgId: record.orgId,
|
|
737
|
+
action: "browser.view",
|
|
738
|
+
target: record.deviceId,
|
|
739
|
+
detail: {
|
|
740
|
+
deviceId: record.deviceId,
|
|
741
|
+
service: record.service,
|
|
742
|
+
extension: record.extension,
|
|
743
|
+
conversationId: record.conversationId,
|
|
744
|
+
},
|
|
745
|
+
});
|
|
746
|
+
viewed = true;
|
|
747
|
+
void pump(stream.messages, end);
|
|
748
|
+
const inbound = pump(end.messages, stream);
|
|
749
|
+
const settled = await Promise.race([
|
|
750
|
+
end.closed.then(() => ({ side: "viewer" })),
|
|
751
|
+
stream.closed.then((c) => ({ side: "stream", reason: c.reason })),
|
|
752
|
+
abortedOf(hold.signal).then(() => ({ side: "hold" })),
|
|
753
|
+
abortedOf(lapsed.signal).then(() => ({ side: "lapsed" })),
|
|
754
|
+
// the browser's messages end only with the socket: a failed send is the one news here
|
|
755
|
+
inbound.then((r) => ({ side: "send", failed: r.failed })),
|
|
756
|
+
]);
|
|
757
|
+
if (settled.side === "send" && settled.failed !== undefined && !life.signal.aborted) {
|
|
758
|
+
// any refused send ends the whole pipe: a message too big for the stream's frames is
|
|
759
|
+
// 1009; otherwise the stream's own close decides (closing it again keeps its reason)
|
|
760
|
+
if (isTooBig(settled.failed)) {
|
|
761
|
+
closeCode = VIEWER_CLOSE.tooBig;
|
|
762
|
+
stream.close("message too big");
|
|
763
|
+
end.close(closeCode, "message too big for the device stream");
|
|
764
|
+
}
|
|
765
|
+
else {
|
|
766
|
+
stream.close("send failed");
|
|
767
|
+
const { reason } = await stream.closed;
|
|
768
|
+
closeCode = reason === "device-offline" ? VIEWER_CLOSE.offline : VIEWER_CLOSE.gone;
|
|
769
|
+
end.close(closeCode, reason === "device-offline" ? "device-offline" : "stream closed");
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
else if (settled.side === "viewer" || settled.side === "send" || life.signal.aborted) {
|
|
773
|
+
stream.close("viewer closed");
|
|
774
|
+
closeCode = (await end.closed).code;
|
|
775
|
+
}
|
|
776
|
+
else if (settled.side === "lapsed") {
|
|
777
|
+
const why = lapse.why ?? { code: VIEWER_CLOSE.badTicket, reason: "access revoked" };
|
|
778
|
+
stream.close("viewer access revoked");
|
|
779
|
+
closeCode = why.code;
|
|
780
|
+
end.close(closeCode, why.reason);
|
|
781
|
+
}
|
|
782
|
+
else if (settled.side === "stream") {
|
|
783
|
+
closeCode = settled.reason === "device-offline" ? VIEWER_CLOSE.offline : VIEWER_CLOSE.gone;
|
|
784
|
+
end.close(closeCode, settled.reason === "device-offline" ? "device-offline" : "stream closed");
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
// the hold yielded to a lifecycle change: gone with the instance, else reconnect
|
|
788
|
+
stream.close("device lifecycle change");
|
|
789
|
+
closeCode = (await this.instanceRunning(record.deviceId, record.orgId))
|
|
790
|
+
? VIEWER_CLOSE.restart
|
|
791
|
+
: VIEWER_CLOSE.gone;
|
|
792
|
+
end.close(closeCode, "device lifecycle change");
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
finally {
|
|
796
|
+
clearInterval(recheck);
|
|
797
|
+
stream.close("viewer closed");
|
|
798
|
+
await hold.release();
|
|
799
|
+
if (viewed) {
|
|
800
|
+
await audit(this.kdb.db, {
|
|
801
|
+
actorAccountId: record.accountId,
|
|
802
|
+
orgId: record.orgId,
|
|
803
|
+
action: "browser.view_closed",
|
|
804
|
+
target: record.deviceId,
|
|
805
|
+
detail: {
|
|
806
|
+
deviceId: record.deviceId,
|
|
807
|
+
service: record.service,
|
|
808
|
+
durationMs: Date.now() - started,
|
|
809
|
+
code: closeCode,
|
|
810
|
+
},
|
|
811
|
+
}).catch((err) => this.log.warn("cannot audit a closed device stream viewer", {
|
|
812
|
+
deviceId: record.deviceId,
|
|
813
|
+
error: errMsg(err),
|
|
814
|
+
}));
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
async instanceRunning(deviceId, orgId) {
|
|
819
|
+
const row = await this.kdb.db
|
|
820
|
+
.selectFrom("device_instances")
|
|
821
|
+
.select("status")
|
|
822
|
+
.where("device_id", "=", deviceId)
|
|
823
|
+
.where("org_id", "=", orgId)
|
|
824
|
+
.executeTakeFirst()
|
|
825
|
+
.catch(() => undefined);
|
|
826
|
+
return row?.status === "running";
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
DeviceStreamViewers = __decorate([
|
|
830
|
+
Injectable(),
|
|
831
|
+
__param(0, Inject(DeviceAccessService)),
|
|
832
|
+
__param(1, Inject(SandboxService)),
|
|
833
|
+
__param(2, Inject(DialInGateway)),
|
|
834
|
+
__param(3, Inject(DialInHandlers)),
|
|
835
|
+
__param(4, Inject(KernelDb)),
|
|
836
|
+
__param(5, Inject(LockService)),
|
|
837
|
+
__param(6, Inject(KEYRING)),
|
|
838
|
+
__param(7, Inject(KernelConfigService)),
|
|
839
|
+
__param(8, Inject(KERNEL_LOGGER))
|
|
840
|
+
], DeviceStreamViewers);
|
|
841
|
+
export { DeviceStreamViewers };
|
|
842
|
+
const isElsewhere = (e) => typeof e === "object" &&
|
|
843
|
+
e !== null &&
|
|
844
|
+
e.code === "device.stream_elsewhere";
|