@scrypted/server 0.148.7 → 0.148.9

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.
@@ -7,8 +7,6 @@ import MimeType from 'whatwg-mimetype';
7
7
  import { getScryptedFFmpegPath } from './ffmpeg-path';
8
8
  import { MediaObject } from "./mediaobject";
9
9
  import { MediaObjectRemote } from "./plugin-api";
10
- import { RpcPeer } from "../rpc";
11
- import { getClusterObject } from "../cluster/cluster-setup";
12
10
 
13
11
  function typeMatches(target: string, candidate: string): boolean {
14
12
  // candidate will accept anything
@@ -37,25 +35,20 @@ export abstract class MediaManagerBase implements MediaManager {
37
35
  #getDeviceById: <T>(id: string) => T & ScryptedDevice;
38
36
  #getPluginDeviceId: () => string;
39
37
  #getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console;
40
- #trusted: boolean;
41
- #connectRPCObject: (value: any) => Promise<any>;
42
38
 
43
39
  constructor(
44
40
  getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
45
41
  getDeviceById: <T>(id: string) => T & ScryptedDevice,
46
42
  getPluginDeviceId: () => string,
47
43
  getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console,
48
- trusted: boolean,
49
- connectRPCObject: (value: any) => Promise<any>,
44
+ privileged: boolean,
50
45
  ) {
51
46
  this.#getSystemState = getSystemState;
52
47
  this.#getDeviceById = getDeviceById;
53
48
  this.#getPluginDeviceId = getPluginDeviceId;
54
49
  this.#getMixinConsole = getMixinConsole;
55
- this.#trusted = trusted;
56
- this.#connectRPCObject = connectRPCObject;
57
50
 
58
- if (trusted) {
51
+ if (privileged) {
59
52
  for (const h of ['http', 'https']) {
60
53
  this.builtinConverters.push({
61
54
  id: getBuiltinId(this.builtinConverters.length),
@@ -165,50 +158,6 @@ export abstract class MediaManagerBase implements MediaManager {
165
158
  });
166
159
  }
167
160
 
168
- async ensureTrusted(mediaObject: MediaObject): Promise<MediaObject> {
169
- if (!mediaObject)
170
- throw new Error('Invalid MediaObject.');
171
-
172
- if (mediaObject.trusted !== true) {
173
- throw new Error('Untrusted MediaObject.');
174
- }
175
-
176
- if (mediaObject instanceof MediaObject) {
177
- return mediaObject;
178
- }
179
-
180
- // invalid input.
181
- if (!RpcPeer.isRpcProxy(mediaObject))
182
- throw new Error('Invalid MediaObject.');
183
-
184
- // connect and validate
185
- const clusterObject = getClusterObject(mediaObject);
186
- if (!clusterObject)
187
- throw new Error('Untrusted MediaObject.');
188
-
189
- const remoteMediaObject = await this.#connectRPCObject(mediaObject);
190
- const peer: RpcPeer | undefined = remoteMediaObject?.[RpcPeer.PROPERTY_PROXY_PEER];
191
- if (!peer) {
192
- throw new Error('Invalid MediaObject.');
193
- }
194
-
195
- const isRpcProxyMethod: (obj: any) => Promise<boolean> = await peer.getParam('isRpcProxy');
196
- if (!isRpcProxyMethod) {
197
- throw new Error('Invalid MediaObject.');
198
- }
199
-
200
- const isRpcProxy = await isRpcProxyMethod(remoteMediaObject);
201
- if (isRpcProxy === true) {
202
- throw new Error('Untrusted MediaObject.');
203
- }
204
- if (isRpcProxy !== false) {
205
- throw new Error('Invalid MediaObject.');
206
- }
207
- if (remoteMediaObject.trusted !== true)
208
- throw new Error('Untrusted MediaObject.');
209
- return remoteMediaObject;
210
- }
211
-
212
161
  async convertMediaObjectToJSON<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
213
162
  const json = await this.convertMediaObjectToBuffer(mediaObject, toMimeType);
214
163
  // backcompat
@@ -319,7 +268,7 @@ export abstract class MediaManagerBase implements MediaManager {
319
268
  return url.data.toString();
320
269
  }
321
270
 
322
- #createMediaObjectRemote<T extends MediaObjectCreateOptions & { trusted?: boolean }>(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 {
323
272
  if (!mimeType)
324
273
  throw new Error('no mimeType provided');
325
274
  if (mimeType === ScryptedMimeTypes.MediaObject)
@@ -331,9 +280,8 @@ export abstract class MediaManagerBase implements MediaManager {
331
280
  const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.#getPluginDeviceId();
332
281
  options ||= {} as T;
333
282
  options.sourceId = sourceId;
334
- options.trusted = this.#trusted;
335
283
 
336
- return new MediaObject(mimeType, data, this.#trusted, options) as MediaObject & T;
284
+ return new MediaObject(mimeType, data, options) as MediaObject & T;
337
285
  }
338
286
 
339
287
  async createFFmpegMediaObject<T extends MediaObjectCreateOptions>(ffMpegInput: FFmpegInput, options?: T): Promise<MediaObjectInterface & T> {
@@ -514,7 +462,7 @@ export abstract class MediaManagerBase implements MediaManager {
514
462
  }
515
463
 
516
464
  export class MediaManagerImpl extends MediaManagerBase {
517
- constructor(systemManager: SystemManager, deviceManager: DeviceManager, connectRPCObject: (value: any) => Promise<any>) {
465
+ constructor(systemManager: SystemManager, deviceManager: DeviceManager) {
518
466
  super(
519
467
  () => systemManager.getSystemState(),
520
468
  <T>(id: string) => systemManager.getDeviceById<T>(id),
@@ -525,7 +473,6 @@ export class MediaManagerImpl extends MediaManagerBase {
525
473
  return deviceManager.getMixinConsole(mixinId, nativeId);
526
474
  },
527
475
  true,
528
- connectRPCObject,
529
476
  );
530
477
  }
531
478
  }
@@ -535,8 +482,7 @@ export class MediaManagerHostImpl extends MediaManagerBase {
535
482
  getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
536
483
  console: Console,
537
484
  getDeviceById: (id: string) => any,
538
- trusted: boolean,
539
- connectRPCObject: (value: any) => Promise<any>) {
540
- super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, trusted, connectRPCObject);
485
+ privileged: boolean) {
486
+ super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, privileged);
541
487
  }
542
488
  }
@@ -5,18 +5,14 @@ import { MediaObjectRemote } from "./plugin-api";
5
5
  export class MediaObject implements MediaObjectRemote {
6
6
  __proxy_props: any;
7
7
 
8
- constructor(public mimeType: string, public data: any, public trusted: boolean, options?: MediaObjectCreateOptions) {
9
- this.__proxy_props = {
10
- mimeType,
11
- trusted,
12
- };
8
+ constructor(public mimeType: string, public data: any, options?: MediaObjectCreateOptions) {
9
+ this.__proxy_props = {}
13
10
  options ||= {};
11
+ options.mimeType = mimeType;
14
12
  options!.convert ||= null!;
15
13
  options!.toMimeTypes ||= null!;
16
14
 
17
15
  for (const [key, value] of Object.entries(options)) {
18
- if (key in this.__proxy_props || key === '__proxy_props')
19
- continue;
20
16
  if (RpcPeer.isTransportSafe(value))
21
17
  this.__proxy_props[key] = value;
22
18
  (this as any)[key] = value;
@@ -6,6 +6,7 @@ import os from 'os';
6
6
  import { PassThrough } from 'stream';
7
7
  import WebSocket from 'ws';
8
8
  import { utilizesClusterForkWorker } from '../cluster/cluster-labels';
9
+ import { setupCluster } from '../cluster/cluster-setup';
9
10
  import { Plugin, PluginDevice } from '../db-types';
10
11
  import { IOServer, IOServerSocket } from '../io';
11
12
  import type { LogEntry, Logger } from '../logger';
@@ -209,7 +210,7 @@ export class PluginHost {
209
210
 
210
211
  const { runtime } = this.packageJson.scrypted;
211
212
  const mediaManager = runtime && runtime !== 'node'
212
- ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true, scrypted.clusterSetup.connectRPCObject)
213
+ ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true)
213
214
  : undefined;
214
215
 
215
216
  this.api = new PluginHostAPI(scrypted, this.pluginId, this, mediaManager!);
@@ -373,7 +374,6 @@ export class PluginHost {
373
374
  reject(new Error('peer disconnected'));
374
375
  }
375
376
  });
376
- this.scrypted.clusterSetup.registerClusterPeer(this.peer);
377
377
 
378
378
  peer = Promise.resolve(this.peer);
379
379
 
@@ -400,12 +400,20 @@ export class PluginHost {
400
400
  }
401
401
  });
402
402
 
403
+ const clusterSetup = setupCluster(this.peer);
403
404
  const { runtimeWorker, forkPeer, clusterWorkerId } = createClusterForkWorker(
404
405
  runtimeWorkerOptions,
405
406
  scrypted,
406
- Promise.resolve(this.scrypted.clusterFork),
407
+ (async () => {
408
+ await clusterSetup.initializeCluster({
409
+ clusterId: this.scrypted.clusterId,
410
+ clusterSecret: this.scrypted.clusterSecret,
411
+ clusterWorkerId: this.scrypted.serverClusterWorkerId,
412
+ });
413
+ return this.scrypted.clusterFork;
414
+ })(),
407
415
  async () => fs.promises.readFile(this.zipFile),
408
- this.scrypted.clusterSetup.connectRPCObject);
416
+ clusterSetup.connectRPCObject);
409
417
 
410
418
  forkPeer.then(peer => {
411
419
  const originalPeer = this.peer;
@@ -500,7 +508,6 @@ export class PluginHost {
500
508
  console,
501
509
  id => this.scrypted.getDevice(id),
502
510
  !accessControls,
503
- this.scrypted.clusterSetup.connectRPCObject,
504
511
  );
505
512
  const api = new PluginAPIProxy(this.api, mediaManager);
506
513
  api.acl = accessControls;
@@ -17,22 +17,22 @@ export abstract class PluginHttp<T> {
17
17
 
18
18
  addMiddleware() {
19
19
  this.app.all(['/endpoint/@:owner/:pkg/public/engine.io/*ignored', '/endpoint/:pkg/public/engine.io/*ignored'], (req, res) => {
20
- this.endpointHandler(req, res, true, true, this.handleEngineIOEndpoint.bind(this))
20
+ return this.endpointHandler(req, res, true, true, this.handleEngineIOEndpoint.bind(this));
21
21
  });
22
22
 
23
23
  this.app.all(['/endpoint/@:owner/:pkg/engine.io/*ignored', '/endpoint/@:owner/:pkg/engine.io/*ignored'], (req, res) => {
24
- this.endpointHandler(req, res, false, true, this.handleEngineIOEndpoint.bind(this))
24
+ return this.endpointHandler(req, res, false, true, this.handleEngineIOEndpoint.bind(this));
25
25
  });
26
26
 
27
27
  // stringify all http endpoints
28
28
  this.app.all(['/endpoint/@:owner/:pkg/public', '/endpoint/@:owner/:pkg/public/*ignored', '/endpoint/:pkg', '/endpoint/:pkg/*ignored'], bodyParser.text() as any);
29
29
 
30
30
  this.app.all(['/endpoint/@:owner/:pkg/public', '/endpoint/@:owner/:pkg/public/*ignored', '/endpoint/:pkg/public', '/endpoint/:pkg/public/*ignored'], (req, res) => {
31
- this.endpointHandler(req, res, true, false, this.handleRequestEndpoint.bind(this))
31
+ return this.endpointHandler(req, res, true, false, this.handleRequestEndpoint.bind(this));
32
32
  });
33
33
 
34
34
  this.app.all(['/endpoint/@:owner/:pkg', '/endpoint/@:owner/:pkg/*ignored', '/endpoint/:pkg', '/endpoint/:pkg/*ignored'], (req, res) => {
35
- this.endpointHandler(req, res, false, false, this.handleRequestEndpoint.bind(this))
35
+ return this.endpointHandler(req, res, false, false, this.handleRequestEndpoint.bind(this));
36
36
  });
37
37
  }
38
38
 
@@ -45,7 +45,6 @@ export function startPluginRemote(mainFilename: string, pluginId: string, peerSe
45
45
  const { initializeCluster, connectRPCObject, mainThreadBrokerRegister, mainThreadPort } = clusterPeerSetup;
46
46
 
47
47
  peer.params.initializeCluster = initializeCluster;
48
- peer.params.isRpcProxy = (value: any) => RpcPeer.isRpcProxy(value);
49
48
  peer.params.ping = async (time: number) => {
50
49
  return time;
51
50
  };
@@ -79,7 +78,7 @@ export function startPluginRemote(mainFilename: string, pluginId: string, peerSe
79
78
  createMediaManager: async (sm, dm) => {
80
79
  systemManager = sm;
81
80
  deviceManager = dm;
82
- return new MediaManagerImpl(systemManager, dm, connectRPCObject);
81
+ return new MediaManagerImpl(systemManager, dm);
83
82
  },
84
83
  onGetRemote: async (_api, _pluginId) => {
85
84
  class PluginForkableAPI extends PluginAPIProxy {
package/src/runtime.ts CHANGED
@@ -15,7 +15,7 @@ import { Parser as TarParser } from 'tar';
15
15
  import { URL } from "url";
16
16
  import WebSocket, { Server as WebSocketServer } from "ws";
17
17
  import { computeClusterObjectHash } from './cluster/cluster-hash';
18
- import { isClusterAddress, setupCluster } from './cluster/cluster-setup';
18
+ import { isClusterAddress } from './cluster/cluster-setup';
19
19
  import { ClusterObject } from './cluster/connect-rpc-object';
20
20
  import { Plugin, PluginDevice, ScryptedAlert, ScryptedUser } from './db-types';
21
21
  import { httpFetch } from './fetch/http-fetch';
@@ -47,7 +47,6 @@ import { getNpmPackageInfo, PluginComponent } from './services/plugin';
47
47
  import { ServiceControl } from './services/service-control';
48
48
  import { UsersService } from './services/users';
49
49
  import { getState, ScryptedStateManager, setState } from './state';
50
- import { RpcPeer } from './rpc';
51
50
 
52
51
  interface DeviceProxyPair {
53
52
  handler: PluginDeviceProxyHandler;
@@ -67,8 +66,8 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
67
66
  clusterSecret = process.env.SCRYPTED_CLUSTER_SECRET || crypto.randomBytes(16).toString('hex');
68
67
  clusterWorkers = new Map<string, RunningClusterWorker>();
69
68
  serverClusterWorkerId!: string;
70
- plugins: { [id: string]: PluginHost } = {};
71
- pluginDevices: { [id: string]: PluginDevice } = {};
69
+ plugins: { [id: string]: PluginHost } = Object.create(null);
70
+ pluginDevices: { [id: string]: PluginDevice } = Object.create(null);
72
71
  devices: { [id: string]: DeviceProxyPair } = {};
73
72
  stateManager = new ScryptedStateManager(this);
74
73
  logger = new Logger(this, '', 'Scrypted');
@@ -86,10 +85,6 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
86
85
  })
87
86
  },
88
87
  });
89
- runtimePeer = new RpcPeer('runtime', 'runtime', (message, reject, serializationContext) => {
90
- console.warn('unexpected message to runtime peer', message);
91
- });
92
- clusterSetup = setupCluster(this.runtimePeer);
93
88
  pluginComponent = new PluginComponent(this);
94
89
  serviceControl = new ServiceControl();
95
90
  alerts = new Alerts(this);
@@ -949,12 +944,6 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
949
944
  // catch kill
950
945
  process.on('SIGTERM', () => this.exit());
951
946
 
952
- await this.clusterSetup.initializeCluster({
953
- clusterId: this.clusterId,
954
- clusterSecret: this.clusterSecret,
955
- clusterWorkerId: this.serverClusterWorkerId,
956
- });
957
-
958
947
  for await (const pluginDevice of this.datastore.getAll(PluginDevice)) {
959
948
  // this may happen due to race condition around deletion/update. investigate.
960
949
  if (!pluginDevice.state) {
@@ -806,7 +806,15 @@ async function start(mainFilename: string, options?: {
806
806
  (app as any).handle(req, {
807
807
  socket,
808
808
  upgradeHead
809
- })
809
+ }, (err?: unknown) => {
810
+ // Express's default final handler requires a real ServerResponse.
811
+ if (err)
812
+ console.error('upgrade routing error', err);
813
+ if (socket.writable && !socket.writableEnded) {
814
+ const status = err ? '500 Internal Server Error' : '404 Not Found';
815
+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
816
+ }
817
+ });
810
818
  });
811
819
  return server;
812
820
  }