@scrypted/server 0.146.2 → 0.148.0

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 (42) hide show
  1. package/dist/cluster/cluster-setup.js +16 -17
  2. package/dist/cluster/cluster-setup.js.map +1 -1
  3. package/dist/http-interfaces.js +16 -2
  4. package/dist/http-interfaces.js.map +1 -1
  5. package/dist/plugin/media.d.ts +5 -39
  6. package/dist/plugin/media.js +73 -109
  7. package/dist/plugin/media.js.map +1 -1
  8. package/dist/plugin/plugin-console.d.ts +2 -0
  9. package/dist/plugin/plugin-console.js +10 -0
  10. package/dist/plugin/plugin-console.js.map +1 -1
  11. package/dist/plugin/plugin-host.js +7 -3
  12. package/dist/plugin/plugin-host.js.map +1 -1
  13. package/dist/plugin/plugin-remote-worker.js.map +1 -1
  14. package/dist/plugin/plugin-remote.d.ts +15 -0
  15. package/dist/plugin/plugin-remote.js +36 -39
  16. package/dist/plugin/plugin-remote.js.map +1 -1
  17. package/dist/rpc-serializer.js +4 -0
  18. package/dist/rpc-serializer.js.map +1 -1
  19. package/dist/scrypted-cluster-main.js +20 -0
  20. package/dist/scrypted-cluster-main.js.map +1 -1
  21. package/dist/scrypted-server-main.js +31 -15
  22. package/dist/scrypted-server-main.js.map +1 -1
  23. package/dist/services/cluster-fork.js +3 -3
  24. package/dist/services/cluster-fork.js.map +1 -1
  25. package/dist/services/plugin.d.ts +1 -0
  26. package/dist/services/plugin.js +5 -0
  27. package/dist/services/plugin.js.map +1 -1
  28. package/package.json +1 -1
  29. package/python/cluster_setup.py +20 -20
  30. package/python/plugin_remote.py +0 -1
  31. package/src/cluster/cluster-setup.ts +16 -17
  32. package/src/http-interfaces.ts +16 -2
  33. package/src/plugin/media.ts +95 -120
  34. package/src/plugin/plugin-console.ts +11 -0
  35. package/src/plugin/plugin-host.ts +14 -4
  36. package/src/plugin/plugin-remote-worker.ts +1 -1
  37. package/src/plugin/plugin-remote.ts +43 -41
  38. package/src/rpc-serializer.ts +4 -0
  39. package/src/scrypted-cluster-main.ts +24 -0
  40. package/src/scrypted-server-main.ts +34 -16
  41. package/src/services/cluster-fork.ts +3 -3
  42. package/src/services/plugin.ts +6 -0
@@ -1,6 +1,5 @@
1
1
  import { BufferConverter, DeviceManager, FFmpegInput, MediaConverter, MediaManager, MediaObjectCreateOptions, MediaObject as MediaObjectInterface, MediaStreamUrl, ScryptedDevice, ScryptedInterface, ScryptedInterfaceProperty, ScryptedMimeTypes, ScryptedNativeId, SystemDeviceState, SystemManager } from "@scrypted/types";
2
2
  import fs from 'fs';
3
- import https from 'https';
4
3
  import mime from 'mime-types';
5
4
  import Graph from 'node-dijkstra';
6
5
  import path from 'path';
@@ -20,10 +19,6 @@ function mimeMatches(target: MimeType, candidate: MimeType) {
20
19
  return typeMatches(target.type, candidate.type) && typeMatches(target.subtype, candidate.subtype);
21
20
  }
22
21
 
23
- const httpsAgent = new https.Agent({
24
- rejectUnauthorized: false
25
- });
26
-
27
22
  type IdBufferConverter = BufferConverter & {
28
23
  id: string;
29
24
  name: string;
@@ -33,56 +28,69 @@ function getBuiltinId(n: number) {
33
28
  return 'builtin-' + n;
34
29
  }
35
30
 
36
- function getExtraId(n: number) {
37
- return 'extra-' + n;
38
- }
39
-
40
31
  export abstract class MediaManagerBase implements MediaManager {
41
32
  builtinConverters: IdBufferConverter[] = [];
42
- extraConverters: IdBufferConverter[] = [];
43
33
 
44
- constructor() {
45
- for (const h of ['http', 'https']) {
34
+ #getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } };
35
+ #getDeviceById: <T>(id: string) => T & ScryptedDevice;
36
+ #getPluginDeviceId: () => string;
37
+ #getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console;
38
+
39
+ constructor(
40
+ getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
41
+ getDeviceById: <T>(id: string) => T & ScryptedDevice,
42
+ getPluginDeviceId: () => string,
43
+ getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console,
44
+ privileged: boolean,
45
+ ) {
46
+ this.#getSystemState = getSystemState;
47
+ this.#getDeviceById = getDeviceById;
48
+ this.#getPluginDeviceId = getPluginDeviceId;
49
+ this.#getMixinConsole = getMixinConsole;
50
+
51
+ if (privileged) {
52
+ for (const h of ['http', 'https']) {
53
+ this.builtinConverters.push({
54
+ id: getBuiltinId(this.builtinConverters.length),
55
+ name: 'HTTP Converter',
56
+ fromMimeType: ScryptedMimeTypes.SchemePrefix + h,
57
+ toMimeType: ScryptedMimeTypes.MediaObject,
58
+ convert: async (data, fromMimeType, toMimeType) => {
59
+ const ab = await fetch(data.toString());
60
+ const mimeType = ab.headers.get('Content-type') || toMimeType;
61
+ const mo = this.createMediaObject(Buffer.from(await ab.arrayBuffer()), mimeType);
62
+ return mo;
63
+ }
64
+ });
65
+ }
66
+
46
67
  this.builtinConverters.push({
47
68
  id: getBuiltinId(this.builtinConverters.length),
48
- name: 'HTTP Converter',
49
- fromMimeType: ScryptedMimeTypes.SchemePrefix + h,
69
+ name: 'File Converter',
70
+ fromMimeType: ScryptedMimeTypes.SchemePrefix + 'file',
50
71
  toMimeType: ScryptedMimeTypes.MediaObject,
51
72
  convert: async (data, fromMimeType, toMimeType) => {
52
- const ab = await fetch(data.toString());
53
- const mimeType = ab.headers.get('Content-type') || toMimeType;
54
- const mo = this.createMediaObject(Buffer.from(await ab.arrayBuffer()), mimeType);
73
+ const url = data.toString();
74
+ const filename = url.substring('file:'.length);
75
+
76
+ if (toMimeType === ScryptedMimeTypes.FFmpegInput) {
77
+ const ffmpegInput: FFmpegInput = {
78
+ url,
79
+ inputArguments: [
80
+ '-i', filename,
81
+ ]
82
+ };
83
+ return this.createFFmpegMediaObject(ffmpegInput);
84
+ }
85
+
86
+ const ab = await fs.promises.readFile(filename);
87
+ const mt = mime.lookup(filename);
88
+ const mo = this.createMediaObject(ab, mt || 'application/octet-stream');
55
89
  return mo;
56
90
  }
57
91
  });
58
92
  }
59
93
 
60
- this.builtinConverters.push({
61
- id: getBuiltinId(this.builtinConverters.length),
62
- name: 'File Converter',
63
- fromMimeType: ScryptedMimeTypes.SchemePrefix + 'file',
64
- toMimeType: ScryptedMimeTypes.MediaObject,
65
- convert: async (data, fromMimeType, toMimeType) => {
66
- const url = data.toString();
67
- const filename = url.substring('file:'.length);
68
-
69
- if (toMimeType === ScryptedMimeTypes.FFmpegInput) {
70
- const ffmpegInput: FFmpegInput = {
71
- url,
72
- inputArguments: [
73
- '-i', filename,
74
- ]
75
- };
76
- return this.createFFmpegMediaObject(ffmpegInput);
77
- }
78
-
79
- const ab = await fs.promises.readFile(filename);
80
- const mt = mime.lookup(filename);
81
- const mo = this.createMediaObject(ab, mt || 'application/octet-stream');
82
- return mo;
83
- }
84
- });
85
-
86
94
  this.builtinConverters.push({
87
95
  id: getBuiltinId(this.builtinConverters.length),
88
96
  name: 'Url to FFmpegInput Converter',
@@ -150,15 +158,6 @@ export abstract class MediaManagerBase implements MediaManager {
150
158
  });
151
159
  }
152
160
 
153
- async addConverter(converter: IdBufferConverter): Promise<void> {
154
- converter.id = getExtraId(this.extraConverters.length);
155
- this.extraConverters.push(converter);
156
- }
157
-
158
- async clearConverters(): Promise<void> {
159
- this.extraConverters = [];
160
- }
161
-
162
161
  async convertMediaObjectToJSON<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
163
162
  const json = await this.convertMediaObjectToBuffer(mediaObject, toMimeType);
164
163
  // backcompat
@@ -167,11 +166,6 @@ export abstract class MediaManagerBase implements MediaManager {
167
166
  return json as T;
168
167
  }
169
168
 
170
- abstract getSystemState(): { [id: string]: { [property: string]: SystemDeviceState } };
171
- abstract getDeviceById<T>(id: string): T & ScryptedDevice;
172
- abstract getPluginDeviceId(): string;
173
- abstract getMixinConsole(mixinId: string, nativeId: ScryptedNativeId): Console;
174
-
175
169
  async getFFmpegPath(): Promise<string> {
176
170
  return getScryptedFFmpegPath();
177
171
  }
@@ -187,11 +181,11 @@ export abstract class MediaManagerBase implements MediaManager {
187
181
  return ret;
188
182
  }
189
183
 
190
- getConverters(): IdBufferConverter[] {
191
- const bufferConverters = Object.entries(this.getSystemState())
184
+ #getConverters(): IdBufferConverter[] {
185
+ const bufferConverters = Object.entries(this.#getSystemState())
192
186
  .filter(([id, state]) => state[ScryptedInterfaceProperty.interfaces]?.value?.includes(ScryptedInterface.BufferConverter))
193
187
  .map(([id]) => {
194
- const device = this.getDeviceById<BufferConverter>(id);
188
+ const device = this.#getDeviceById<BufferConverter>(id);
195
189
  return {
196
190
  id,
197
191
  name: device.name,
@@ -203,10 +197,10 @@ export abstract class MediaManagerBase implements MediaManager {
203
197
  } as IdBufferConverter;
204
198
  });
205
199
 
206
- const mediaConverters = Object.entries(this.getSystemState())
200
+ const mediaConverters = Object.entries(this.#getSystemState())
207
201
  .filter(([id, state]) => state[ScryptedInterfaceProperty.interfaces]?.value?.includes(ScryptedInterface.MediaConverter))
208
202
  .map(([id]) => {
209
- const device = this.getDeviceById<MediaConverter & BufferConverter>(id);
203
+ const device = this.#getDeviceById<MediaConverter & BufferConverter>(id);
210
204
 
211
205
  try {
212
206
  return (device.converters || []).map(([fromMimeType, toMimeType], index) => {
@@ -234,51 +228,47 @@ export abstract class MediaManagerBase implements MediaManager {
234
228
  // builtins should be after system converters. these should not be overriden by system,
235
229
  // as it could cause system instability with misconfiguration.
236
230
  converters.push(...this.builtinConverters);
237
-
238
- // extra converters are added last and do allow overriding builtins, as
239
- // the instability would be confined to a single plugin.
240
- converters.push(...this.extraConverters);
241
231
  return converters;
242
232
  }
243
233
 
244
- ensureMediaObjectRemote(mediaObject: string | MediaObjectInterface): MediaObjectRemote {
234
+ #ensureMediaObjectRemote(mediaObject: string | MediaObjectInterface): MediaObjectRemote {
245
235
  if (typeof mediaObject === 'string') {
246
236
  const mt = mime.lookup(mediaObject);
247
- return this.createMediaObjectRemote(mediaObject, mt || 'application/octet-stream');
237
+ return this.#createMediaObjectRemote(mediaObject, mt || 'application/octet-stream');
248
238
  }
249
239
  return mediaObject as MediaObjectRemote;
250
240
  }
251
241
 
252
242
  async convertMediaObject<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
253
- const converted = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
243
+ const converted = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
254
244
  return converted.data;
255
245
  }
256
246
 
257
247
  async convertMediaObjectToInsecureLocalUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
258
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
259
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
260
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.InsecureLocalUrl);
248
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
249
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
250
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.InsecureLocalUrl);
261
251
  return url.data.toString();
262
252
  }
263
253
 
264
254
  async convertMediaObjectToBuffer(mediaObject: MediaObjectInterface, toMimeType: string): Promise<Buffer> {
265
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
255
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
266
256
  return intermediate.data as Buffer;
267
257
  }
268
258
  async convertMediaObjectToLocalUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
269
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
270
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
271
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.LocalUrl);
259
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
260
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
261
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.LocalUrl);
272
262
  return url.data.toString();
273
263
  }
274
264
  async convertMediaObjectToUrl(mediaObject: string | MediaObjectInterface, toMimeType: string): Promise<string> {
275
- const intermediate = await this.convert(this.getConverters(), this.ensureMediaObjectRemote(mediaObject), toMimeType);
276
- const converted = this.createMediaObjectRemote(intermediate.data, intermediate.mimeType);
277
- const url = await this.convert(this.getConverters(), converted, ScryptedMimeTypes.Url);
265
+ const intermediate = await this.#convert(this.#getConverters(), this.#ensureMediaObjectRemote(mediaObject), toMimeType);
266
+ const converted = this.#createMediaObjectRemote(intermediate.data, intermediate.mimeType);
267
+ const url = await this.#convert(this.#getConverters(), converted, ScryptedMimeTypes.Url);
278
268
  return url.data.toString();
279
269
  }
280
270
 
281
- createMediaObjectRemote<T extends MediaObjectCreateOptions>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
271
+ #createMediaObjectRemote<T extends MediaObjectCreateOptions>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
282
272
  if (!mimeType)
283
273
  throw new Error('no mimeType provided');
284
274
  if (mimeType === ScryptedMimeTypes.MediaObject)
@@ -287,7 +277,7 @@ export abstract class MediaManagerBase implements MediaManager {
287
277
  if (data.constructor?.name === Object.name)
288
278
  data = Buffer.from(JSON.stringify(data));
289
279
 
290
- const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.getPluginDeviceId();
280
+ const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.#getPluginDeviceId();
291
281
  options ||= {} as T;
292
282
  options.sourceId = sourceId;
293
283
 
@@ -295,7 +285,7 @@ export abstract class MediaManagerBase implements MediaManager {
295
285
  }
296
286
 
297
287
  async createFFmpegMediaObject<T extends MediaObjectCreateOptions>(ffMpegInput: FFmpegInput, options?: T): Promise<MediaObjectInterface & T> {
298
- return this.createMediaObjectRemote(Buffer.from(JSON.stringify(ffMpegInput)), ScryptedMimeTypes.FFmpegInput, options);
288
+ return this.#createMediaObjectRemote(Buffer.from(JSON.stringify(ffMpegInput)), ScryptedMimeTypes.FFmpegInput, options);
299
289
  }
300
290
 
301
291
  async createMediaObjectFromUrl<T extends MediaObjectCreateOptions>(data: string, options?: T): Promise<MediaObjectInterface & T> {
@@ -303,14 +293,14 @@ export abstract class MediaManagerBase implements MediaManager {
303
293
  const scheme = url.protocol.slice(0, -1);
304
294
  const mimeType = ScryptedMimeTypes.SchemePrefix + scheme;
305
295
 
306
- return this.createMediaObjectRemote(data, mimeType, options);
296
+ return this.#createMediaObjectRemote(data, mimeType, options);
307
297
  }
308
298
 
309
299
  async createMediaObject<T extends MediaObjectCreateOptions>(data: any, mimeType: string, options?: T): Promise<MediaObjectInterface & T> {
310
- return this.createMediaObjectRemote(data, mimeType, options);
300
+ return this.#createMediaObjectRemote(data, mimeType, options);
311
301
  }
312
302
 
313
- async convert(converters: IdBufferConverter[], mediaObject: MediaObjectRemote, toMimeType: string): Promise<{ data: Buffer | string | any, mimeType: string }> {
303
+ async #convert(converters: IdBufferConverter[], mediaObject: MediaObjectRemote, toMimeType: string): Promise<{ data: Buffer | string | any, mimeType: string }> {
314
304
  // console.log('converting', mediaObject.mimeType, toMimeType);
315
305
  const mediaMime = new MimeType(mediaObject.mimeType);
316
306
  const outputMime = new MimeType(toMimeType);
@@ -324,8 +314,8 @@ export abstract class MediaManagerBase implements MediaManager {
324
314
 
325
315
  let sourceId = mediaObject?.sourceId;
326
316
  if (typeof sourceId !== 'string')
327
- sourceId = this.getPluginDeviceId();
328
- const console = this.getMixinConsole(sourceId, undefined);
317
+ sourceId = this.#getPluginDeviceId();
318
+ const console = this.#getMixinConsole(sourceId, undefined);
329
319
 
330
320
  const converterMap = new Map<string, IdBufferConverter>();
331
321
  for (const c of converters) {
@@ -472,42 +462,27 @@ export abstract class MediaManagerBase implements MediaManager {
472
462
  }
473
463
 
474
464
  export class MediaManagerImpl extends MediaManagerBase {
475
- constructor(public systemManager: SystemManager, public deviceManager: DeviceManager) {
476
- super();
477
- }
478
-
479
- getSystemState(): { [id: string]: { [property: string]: SystemDeviceState; }; } {
480
- return this.systemManager.getSystemState();
481
- }
482
-
483
- getDeviceById<T>(id: string): T {
484
- return this.systemManager.getDeviceById<T>(id);
485
- }
486
-
487
- getPluginDeviceId(): string {
488
- return this.deviceManager.getDeviceState().id;
489
- }
490
-
491
- getMixinConsole(mixinId: string, nativeId: string): Console {
492
- if (typeof mixinId !== 'string')
493
- return this.deviceManager.getDeviceConsole(nativeId);
494
- return this.deviceManager.getMixinConsole(mixinId, nativeId);
465
+ constructor(systemManager: SystemManager, deviceManager: DeviceManager) {
466
+ super(
467
+ () => systemManager.getSystemState(),
468
+ <T>(id: string) => systemManager.getDeviceById<T>(id),
469
+ () => deviceManager.getDeviceState().id,
470
+ (mixinId, nativeId) => {
471
+ if (typeof mixinId !== 'string')
472
+ return deviceManager.getDeviceConsole(nativeId);
473
+ return deviceManager.getMixinConsole(mixinId, nativeId);
474
+ },
475
+ true,
476
+ );
495
477
  }
496
478
  }
497
479
 
498
480
  export class MediaManagerHostImpl extends MediaManagerBase {
499
- constructor(public pluginDeviceId: string,
500
- public getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
501
- public console: Console,
502
- public getDeviceById: (id: string) => any) {
503
- super();
504
- }
505
-
506
- getPluginDeviceId(): string {
507
- return this.pluginDeviceId;
508
- }
509
-
510
- getMixinConsole(mixinId: string, nativeId: string): Console {
511
- return this.console;
481
+ constructor(pluginDeviceId: string,
482
+ getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
483
+ console: Console,
484
+ getDeviceById: (id: string) => any,
485
+ privileged: boolean) {
486
+ super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, privileged);
512
487
  }
513
488
  }
@@ -11,6 +11,7 @@ export interface ConsoleServer {
11
11
  writePort: number,
12
12
  destroy(): void;
13
13
  clear(nativeId: ScryptedNativeId): void;
14
+ read(nativeId: ScryptedNativeId): Buffer;
14
15
  }
15
16
 
16
17
  export interface StdPassThroughs {
@@ -305,12 +306,22 @@ export async function createConsoleServer(remoteStdout: Readable, remoteStderr:
305
306
 
306
307
  return {
307
308
  clear(nativeId: ScryptedNativeId) {
309
+ if (!nativeId)
310
+ nativeId = undefined;
308
311
  const pt = outputs.get(nativeId);
309
312
  if (pt) {
310
313
  pt.buffers = [];
311
314
  addHeader(pt);
312
315
  }
313
316
  },
317
+ read(nativeId: ScryptedNativeId) {
318
+ if (!nativeId)
319
+ nativeId = undefined;
320
+ const pt = outputs.get(nativeId);
321
+ if (!pt)
322
+ return Buffer.alloc(0);
323
+ return Buffer.concat(pt.buffers);
324
+ },
314
325
  destroy() {
315
326
  for (const socket of sockets) {
316
327
  socket.destroy();
@@ -23,7 +23,7 @@ import { ConsoleServer, createConsoleServer } from './plugin-console';
23
23
  import { PluginDebug } from './plugin-debug';
24
24
  import { PluginHostAPI } from './plugin-host-api';
25
25
  import { LazyRemote } from './plugin-lazy-remote';
26
- import { setupPluginRemote } from './plugin-remote';
26
+ import { getAccessControlSystemState, setupPluginRemote } from './plugin-remote';
27
27
  import { WebSocketConnection } from './plugin-remote-websocket';
28
28
  import { ensurePluginVolume, getScryptedVolume } from './plugin-volume';
29
29
  import { createClusterForkWorker } from './runtime/cluster-fork-worker';
@@ -210,7 +210,7 @@ export class PluginHost {
210
210
 
211
211
  const { runtime } = this.packageJson.scrypted;
212
212
  const mediaManager = runtime && runtime !== 'node'
213
- ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id))
213
+ ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true)
214
214
  : undefined;
215
215
 
216
216
  this.api = new PluginHostAPI(scrypted, this.pluginId, this, mediaManager!);
@@ -498,8 +498,18 @@ export class PluginHost {
498
498
  serializer.setupRpcPeer(rpcPeer);
499
499
 
500
500
  // wrap the host api with a connection specific api that can be torn down on disconnect
501
- const createMediaManager = await this.peer.getParam('createMediaManager');
502
- const api = new PluginAPIProxy(this.api, await createMediaManager());
501
+ const pluginDeviceId = this.scrypted.findPluginDevice(this.pluginId)!._id;
502
+ const getSystemState = accessControls
503
+ ? () => getAccessControlSystemState(accessControls, () => this.scrypted.stateManager.getSystemState())
504
+ : () => this.scrypted.stateManager.getSystemState();
505
+ const mediaManager = new MediaManagerHostImpl(
506
+ pluginDeviceId,
507
+ getSystemState,
508
+ console,
509
+ id => this.scrypted.getDevice(id),
510
+ !accessControls,
511
+ );
512
+ const api = new PluginAPIProxy(this.api, mediaManager);
503
513
  api.acl = accessControls;
504
514
  const kill = () => {
505
515
  serializer.onDisconnected();
@@ -77,7 +77,7 @@ export function startPluginRemote(mainFilename: string, pluginId: string, peerSe
77
77
  attachPluginRemote(peer, {
78
78
  createMediaManager: async (sm, dm) => {
79
79
  systemManager = sm;
80
- deviceManager = dm
80
+ deviceManager = dm;
81
81
  return new MediaManagerImpl(systemManager, dm);
82
82
  },
83
83
  onGetRemote: async (_api, _pluginId) => {
@@ -2,13 +2,48 @@ import { EventDetails, MediaManager, ScryptedInterface, ScryptedInterfacePropert
2
2
  import { RpcPeer, RPCResultError } from '../rpc';
3
3
  import { BufferSerializer } from '../rpc-buffer-serializer';
4
4
  import { AccessControls } from './acl';
5
+ import { ClusterManagerImpl } from './cluster';
5
6
  import { DeviceManagerImpl, StorageImpl } from './device';
6
7
  import { EndpointManagerImpl } from './endpoint';
7
8
  import { PluginAPI, PluginHostInfo, PluginRemote, PluginRemoteLoadZipOptions, PluginZipAPI } from './plugin-api';
8
9
  import { createWebSocketClass, WebSocketConnectCallbacks, WebSocketConnection, WebSocketMethods, WebSocketSerializer } from './plugin-remote-websocket';
9
10
  import { SystemManagerImpl } from './system';
10
- import { ClusterManagerImpl } from './cluster';
11
11
 
12
+ function getAccessControlDeviceState(accessControls: AccessControls | undefined, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }, id: string, state?: { [property: string]: SystemDeviceState }) {
13
+ state = state || getSystemState()[id];
14
+ if (accessControls && state) {
15
+ state = Object.assign({}, state);
16
+ for (const property of Object.keys(state)) {
17
+ if (accessControls.shouldRejectProperty(id, property))
18
+ delete state[property];
19
+ }
20
+ let interfaces: ScryptedInterface[] = state.interfaces?.value;
21
+ if (interfaces) {
22
+ interfaces = interfaces.filter(scryptedInterface => !accessControls.shouldRejectInterface(id, scryptedInterface));
23
+ state.interfaces = {
24
+ value: interfaces,
25
+ }
26
+ }
27
+ }
28
+ return state;
29
+ }
30
+
31
+
32
+ export function getAccessControlSystemState(accessControls: AccessControls | undefined, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }) {
33
+ let state = getSystemState();
34
+ if (accessControls) {
35
+ state = Object.assign({}, state);
36
+ for (const id of Object.keys(state)) {
37
+ if (accessControls.shouldRejectDevice(id)) {
38
+ delete state[id];
39
+ continue;
40
+ }
41
+ state[id] = getAccessControlDeviceState(accessControls, getSystemState, id, state[id]!)!;
42
+ }
43
+ }
44
+
45
+ return state;
46
+ }
12
47
 
13
48
  export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId: string, hostInfo: PluginHostInfo, getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } }): Promise<PluginRemote> {
14
49
  try {
@@ -23,42 +58,8 @@ export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId:
23
58
 
24
59
  const accessControls: AccessControls = peer.tags.acl;
25
60
 
26
- const getAccessControlDeviceState = (id: string, state?: { [property: string]: SystemDeviceState }) => {
27
- state = state || getSystemState()[id];
28
- if (accessControls && state) {
29
- state = Object.assign({}, state);
30
- for (const property of Object.keys(state)) {
31
- if (accessControls.shouldRejectProperty(id, property))
32
- delete state[property];
33
- }
34
- let interfaces: ScryptedInterface[] = state.interfaces?.value;
35
- if (interfaces) {
36
- interfaces = interfaces.filter(scryptedInterface => !accessControls.shouldRejectInterface(id, scryptedInterface));
37
- state.interfaces = {
38
- value: interfaces,
39
- }
40
- }
41
- }
42
- return state;
43
- }
44
61
 
45
- const getAccessControlSystemState = () => {
46
- let state = getSystemState();
47
- if (accessControls) {
48
- state = Object.assign({}, state);
49
- for (const id of Object.keys(state)) {
50
- if (accessControls.shouldRejectDevice(id)) {
51
- delete state[id];
52
- continue;
53
- }
54
- state[id] = getAccessControlDeviceState(id, state[id]!)!;
55
- }
56
- }
57
-
58
- return state;
59
- }
60
-
61
- await remote.setSystemState(getAccessControlSystemState());
62
+ await remote.setSystemState(getAccessControlSystemState(accessControls, getSystemState));
62
63
  api.listen((id, eventDetails, eventData) => {
63
64
  if (accessControls?.shouldRejectEvent(eventDetails.property === ScryptedInterfaceProperty.id ? eventData : id, eventDetails))
64
65
  return;
@@ -71,7 +72,7 @@ export async function setupPluginRemote(peer: RpcPeer, api: PluginAPI, pluginId:
71
72
  }
72
73
  else {
73
74
  // a change on anything else is a descriptor update
74
- remote.updateDeviceState(id, getAccessControlDeviceState(id)!);
75
+ remote.updateDeviceState(id, getAccessControlDeviceState(accessControls, getSystemState, id)!);
75
76
  }
76
77
  return;
77
78
  }
@@ -97,6 +98,11 @@ export interface WebSocketCustomHandler {
97
98
  }
98
99
 
99
100
  export interface PluginRemoteAttachOptions {
101
+ /**
102
+ * Injected by the host/plugin worker to create the media manager implementation.
103
+ * This keeps the media manager and its Node-only dependencies out of the web
104
+ * client bundle, where attachPluginRemote is also used.
105
+ */
100
106
  createMediaManager?: (systemManager: SystemManager, deviceManager: DeviceManagerImpl) => Promise<MediaManager>;
101
107
  getServicePort?: (name: string, ...args: any[]) => Promise<[number, string]>;
102
108
  getDeviceConsole?: (nativeId?: ScryptedNativeId) => Console;
@@ -144,11 +150,7 @@ export function attachPluginRemote(peer: RpcPeer, options?: PluginRemoteAttachOp
144
150
  const endpointManager = new EndpointManagerImpl();
145
151
  const clusterManager = new ClusterManagerImpl(undefined, api, undefined!);
146
152
  const hostMediaManager = await api.getMediaManager();
147
- if (!hostMediaManager) {
148
- peer.params['createMediaManager'] = async () => createMediaManager!(systemManager, deviceManager);
149
- }
150
153
  const mediaManager = hostMediaManager || await createMediaManager!(systemManager, deviceManager);
151
- peer.params['mediaManager'] = mediaManager;
152
154
 
153
155
  systemManager.api = api;
154
156
  deviceManager.api = api;
@@ -19,6 +19,10 @@ export function createDuplexRpcPeer(selfName: string, peerName: string, readable
19
19
  readable.on('data', data => serializer.onData(data));
20
20
  readable.on('close', serializer.onDisconnected);
21
21
  readable.on('error', serializer.onDisconnected);
22
+ rpcPeer.killedSafe.finally(() => {
23
+ readable.destroy();
24
+ writable.destroy();
25
+ });
22
26
  return rpcPeer;
23
27
  }
24
28
 
@@ -404,6 +404,30 @@ export function createClusterServer(mainFilename: string, scryptedRuntime: Scryp
404
404
  }
405
405
  }
406
406
  peer.params['connectForkWorker'] = connectForkWorker;
407
+
408
+ let lastCheck = Date.now();
409
+ let killed = false;
410
+
411
+ const healthInterval = setInterval(() => {
412
+ if (Date.now() - lastCheck > 60000)
413
+ peer.kill('Cluster liveness timeout.');
414
+ }, 15000);
415
+
416
+ peer.killedSafe.finally(() => {
417
+ killed = true;
418
+ clearInterval(healthInterval);
419
+ });
420
+
421
+ (async () => {
422
+ while (!killed) {
423
+ await sleep(15000);
424
+ if (killed)
425
+ return;
426
+ const info = await peer.getParam('info').catch(() => { });
427
+ if (info)
428
+ lastCheck = Date.now();
429
+ }
430
+ })();
407
431
  });
408
432
 
409
433
  return server;