@scrypted/server 0.148.10 → 0.148.11

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/python/rpc.py CHANGED
@@ -173,6 +173,7 @@ class RpcPeer:
173
173
  self.remoteWeakProxies: Mapping[str, any] = {}
174
174
  self.nameDeserializerMap: Mapping[str, RpcSerializer] = {}
175
175
  self.onProxySerialization: Callable[[Any, str], tuple[str, Any]] = None
176
+ self.onProxyDeserialization: Callable[[Any], Any] = None
176
177
  self.killed = False
177
178
  self.tags = {}
178
179
 
@@ -469,6 +470,12 @@ class RpcPeer:
469
470
  __remote_proxy_oneway_methods,
470
471
  )
471
472
  setattr(proxy, "__proxy_finalizer_id", __remote_proxy_finalizer_id)
473
+
474
+ if self.onProxyDeserialization:
475
+ resolved = self.onProxyDeserialization(proxy)
476
+ if resolved:
477
+ return resolved
478
+
472
479
  return proxy
473
480
 
474
481
  if __local_proxy_id:
@@ -47,6 +47,18 @@ export function setupCluster(peer: RpcPeer) {
47
47
  // incoming connections: use the remote random/unique port
48
48
  // outgoing connections: use the local random/unique port
49
49
  const clusterPeers = new Map<string, Promise<RpcPeer>>();
50
+ const clusterPeersResolved = new Map<string, RpcPeer>();
51
+ function clusterPeersSet(key: string, peerPromise: Promise<RpcPeer>) {
52
+ clusterPeers.set(key, peerPromise);
53
+ peerPromise.then(peer => {
54
+ if (clusterPeers.get(key) === peerPromise)
55
+ clusterPeersResolved.set(key, peer);
56
+ }).catch(() => { });
57
+ }
58
+ function clusterPeersDelete(key: string) {
59
+ clusterPeers.delete(key);
60
+ clusterPeersResolved.delete(key);
61
+ }
50
62
 
51
63
  peer.killedSafe.finally(() => {
52
64
  for (const cp of clusterPeers.values()) {
@@ -68,6 +80,10 @@ export function setupCluster(peer: RpcPeer) {
68
80
  return ret;
69
81
  }
70
82
 
83
+ const isRpcProxy = async (o: any) => {
84
+ return RpcPeer.isRpcProxy(o);
85
+ };
86
+
71
87
  const connectClusterObject = async (o: ClusterObject) => {
72
88
  const sha256 = computeClusterObjectHash(o, clusterSecret);
73
89
  if (sha256 !== o.sha256)
@@ -88,7 +104,7 @@ export function setupCluster(peer: RpcPeer) {
88
104
 
89
105
  clusterPeerPromise = (async () => {
90
106
  const socket = net.connect(connectPort, address);
91
- socket.on('close', () => clusterPeers.delete(clusterPeerKey));
107
+ socket.on('close', () => clusterPeersDelete(clusterPeerKey));
92
108
 
93
109
  try {
94
110
  await once(socket, 'connect');
@@ -101,6 +117,7 @@ export function setupCluster(peer: RpcPeer) {
101
117
 
102
118
  const clusterPeer = createDuplexRpcPeer(peer.selfName, clusterPeerKey, socket, socket);
103
119
  clusterPeer.onProxySerialization = (value) => onProxySerialization(clusterPeer, value, clusterPeerKey);
120
+ clusterPeer.onProxyDeserialization = onProxyDeserialization;
104
121
  return clusterPeer;
105
122
  }
106
123
  catch (e) {
@@ -110,7 +127,7 @@ export function setupCluster(peer: RpcPeer) {
110
127
  }
111
128
  })();
112
129
 
113
- clusterPeers.set(clusterPeerKey, clusterPeerPromise);
130
+ clusterPeersSet(clusterPeerKey, clusterPeerPromise);
114
131
  return clusterPeerPromise;
115
132
  };
116
133
 
@@ -144,15 +161,17 @@ export function setupCluster(peer: RpcPeer) {
144
161
 
145
162
  const threadPeerKey = `thread:${tid}`;
146
163
  function peerCleanup() {
147
- clusterPeers.delete(threadPeerKey);
164
+ clusterPeersDelete(threadPeerKey);
148
165
  }
149
166
  peerPromise = tidDeferred.promise.then(port => {
150
167
  const threadPeer = NodeThreadWorker.createRpcPeer(peer.selfName, threadPeerKey, port);
151
168
  // set params from the primary peer, needed for get getRemote in cluster mode.
152
169
  Object.assign(threadPeer.params, peer.params);
153
170
  threadPeer.onProxySerialization = value => onProxySerialization(threadPeer, value, threadPeerKey);
171
+ threadPeer.onProxyDeserialization = onProxyDeserialization;
154
172
 
155
173
  threadPeer.params.connectRPCObject = connectClusterObject;
174
+ threadPeer.params.isRpcProxy = isRpcProxy;
156
175
 
157
176
  function cleanup(message: string) {
158
177
  peerCleanup();
@@ -165,7 +184,7 @@ export function setupCluster(peer: RpcPeer) {
165
184
  return threadPeer;
166
185
  });
167
186
  peerPromise.catch(() => peerCleanup());
168
- clusterPeers.set(threadPeerKey, peerPromise);
187
+ clusterPeersSet(threadPeerKey, peerPromise);
169
188
  tidPeers.set(tid, peerPromise);
170
189
 
171
190
  return peerPromise;
@@ -334,6 +353,40 @@ export function setupCluster(peer: RpcPeer) {
334
353
  properties,
335
354
  };
336
355
  }
356
+
357
+ const onProxyDeserialization = (proxy: any) => {
358
+ const o = getClusterObject(proxy);
359
+ if (!o)
360
+ return;
361
+ const sha256 = computeClusterObjectHash(o, clusterSecret);
362
+ if (sha256 !== o.sha256)
363
+ throw new Error('secret incorrect');
364
+ if (o.id !== clusterId)
365
+ throw new Error('invalid cluster id');
366
+ const sourceKey = o.sourceKey;
367
+ const sourcePeer = sourceKey
368
+ ? clusterPeersResolved.get(sourceKey)
369
+ : peer;
370
+ if (!sourcePeer)
371
+ return;
372
+ const ret = sourcePeer?.localProxyMap.get(o.proxyId);
373
+ if (!ret || RpcPeer.isRpcProxy(ret))
374
+ return;
375
+ return ret;
376
+ }
377
+
378
+ const registerClusterPeer = (clusterPeer: RpcPeer, key = `local:${RpcPeer.generateId()}`) => {
379
+ clusterPeer.onProxySerialization = value => onProxySerialization(clusterPeer, value, key);
380
+ clusterPeer.onProxyDeserialization = onProxyDeserialization;
381
+ const registered = Promise.resolve(clusterPeer);
382
+ clusterPeersSet(key, registered);
383
+ clusterPeer.killedSafe.finally(() => {
384
+ if (clusterPeers.get(key) === registered)
385
+ clusterPeersDelete(key);
386
+ });
387
+ return key;
388
+ }
389
+
337
390
  const initializeCluster: InitializeCluster = async (options: {
338
391
  clusterId: string;
339
392
  clusterSecret: string;
@@ -355,10 +408,12 @@ export function setupCluster(peer: RpcPeer) {
355
408
  // the listening peer sourceKey (client address/port) is used by the OTHER peer (the client)
356
409
  // to determine if it is already connected to THIS peer (the server).
357
410
  clusterPeer.onProxySerialization = (value) => onProxySerialization(clusterPeer, value, clusterPeerKey);
358
- clusterPeers.set(clusterPeerKey, Promise.resolve(clusterPeer));
411
+ clusterPeer.onProxyDeserialization = onProxyDeserialization;
412
+ clusterPeersSet(clusterPeerKey, Promise.resolve(clusterPeer));
359
413
  clusterPeer.params.connectRPCObject = connectClusterObject;
414
+ clusterPeer.params.isRpcProxy = isRpcProxy;
360
415
  client.on('close', () => {
361
- clusterPeers.delete(clusterPeerKey);
416
+ clusterPeersDelete(clusterPeerKey);
362
417
  clusterPeer.kill('cluster socket closed');
363
418
  clients.delete(client);
364
419
  });
@@ -368,6 +423,7 @@ export function setupCluster(peer: RpcPeer) {
368
423
  clusterPort = port;
369
424
 
370
425
  peer.onProxySerialization = value => onProxySerialization(peer, value, undefined!);
426
+ peer.onProxyDeserialization = onProxyDeserialization;
371
427
  delete peer.params.initializeCluster;
372
428
 
373
429
  peer.killedSafe.finally(() => clusterRpcServer.close());
@@ -389,6 +445,7 @@ export function setupCluster(peer: RpcPeer) {
389
445
  SCRYPTED_CLUSTER_ADDRESS,
390
446
  clusterPeers,
391
447
  onProxySerialization,
448
+ registerClusterPeer,
392
449
  connectClusterObject,
393
450
  ensureClusterPeer,
394
451
  mainThreadPort,
@@ -7,6 +7,8 @@ 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";
10
12
 
11
13
  function typeMatches(target: string, candidate: string): boolean {
12
14
  // candidate will accept anything
@@ -35,20 +37,25 @@ export abstract class MediaManagerBase implements MediaManager {
35
37
  #getDeviceById: <T>(id: string) => T & ScryptedDevice;
36
38
  #getPluginDeviceId: () => string;
37
39
  #getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console;
40
+ #trusted: boolean;
41
+ #connectRPCObject: (value: any) => Promise<any>;
38
42
 
39
43
  constructor(
40
44
  getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
41
45
  getDeviceById: <T>(id: string) => T & ScryptedDevice,
42
46
  getPluginDeviceId: () => string,
43
47
  getMixinConsole: (mixinId: string, nativeId: ScryptedNativeId) => Console,
44
- privileged: boolean,
48
+ trusted: boolean,
49
+ connectRPCObject: (value: any) => Promise<any>,
45
50
  ) {
46
51
  this.#getSystemState = getSystemState;
47
52
  this.#getDeviceById = getDeviceById;
48
53
  this.#getPluginDeviceId = getPluginDeviceId;
49
54
  this.#getMixinConsole = getMixinConsole;
55
+ this.#trusted = trusted;
56
+ this.#connectRPCObject = connectRPCObject;
50
57
 
51
- if (privileged) {
58
+ if (trusted) {
52
59
  for (const h of ['http', 'https']) {
53
60
  this.builtinConverters.push({
54
61
  id: getBuiltinId(this.builtinConverters.length),
@@ -158,6 +165,50 @@ export abstract class MediaManagerBase implements MediaManager {
158
165
  });
159
166
  }
160
167
 
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
+
161
212
  async convertMediaObjectToJSON<T>(mediaObject: MediaObjectInterface, toMimeType: string): Promise<T> {
162
213
  const json = await this.convertMediaObjectToBuffer(mediaObject, toMimeType);
163
214
  // backcompat
@@ -268,7 +319,7 @@ export abstract class MediaManagerBase implements MediaManager {
268
319
  return url.data.toString();
269
320
  }
270
321
 
271
- #createMediaObjectRemote<T extends MediaObjectCreateOptions>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
322
+ #createMediaObjectRemote<T extends MediaObjectCreateOptions & { trusted?: boolean }>(data: any | Buffer | Promise<string | Buffer>, mimeType: string, options?: T): MediaObjectRemote & T {
272
323
  if (!mimeType)
273
324
  throw new Error('no mimeType provided');
274
325
  if (mimeType === ScryptedMimeTypes.MediaObject)
@@ -280,8 +331,9 @@ export abstract class MediaManagerBase implements MediaManager {
280
331
  const sourceId = typeof options?.sourceId === 'string' ? options?.sourceId : this.#getPluginDeviceId();
281
332
  options ||= {} as T;
282
333
  options.sourceId = sourceId;
334
+ options.trusted = this.#trusted;
283
335
 
284
- return new MediaObject(mimeType, data, options) as MediaObject & T;
336
+ return new MediaObject(mimeType, data, this.#trusted, options) as MediaObject & T;
285
337
  }
286
338
 
287
339
  async createFFmpegMediaObject<T extends MediaObjectCreateOptions>(ffMpegInput: FFmpegInput, options?: T): Promise<MediaObjectInterface & T> {
@@ -462,7 +514,7 @@ export abstract class MediaManagerBase implements MediaManager {
462
514
  }
463
515
 
464
516
  export class MediaManagerImpl extends MediaManagerBase {
465
- constructor(systemManager: SystemManager, deviceManager: DeviceManager) {
517
+ constructor(systemManager: SystemManager, deviceManager: DeviceManager, connectRPCObject: (value: any) => Promise<any>) {
466
518
  super(
467
519
  () => systemManager.getSystemState(),
468
520
  <T>(id: string) => systemManager.getDeviceById<T>(id),
@@ -473,6 +525,7 @@ export class MediaManagerImpl extends MediaManagerBase {
473
525
  return deviceManager.getMixinConsole(mixinId, nativeId);
474
526
  },
475
527
  true,
528
+ connectRPCObject,
476
529
  );
477
530
  }
478
531
  }
@@ -482,7 +535,8 @@ export class MediaManagerHostImpl extends MediaManagerBase {
482
535
  getSystemState: () => { [id: string]: { [property: string]: SystemDeviceState } },
483
536
  console: Console,
484
537
  getDeviceById: (id: string) => any,
485
- privileged: boolean) {
486
- super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, privileged);
538
+ trusted: boolean,
539
+ connectRPCObject: (value: any) => Promise<any>) {
540
+ super(getSystemState, getDeviceById, () => pluginDeviceId, () => console, trusted, connectRPCObject);
487
541
  }
488
542
  }
@@ -5,14 +5,18 @@ 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, options?: MediaObjectCreateOptions) {
9
- this.__proxy_props = {}
8
+ constructor(public mimeType: string, public data: any, public trusted: boolean, options?: MediaObjectCreateOptions) {
9
+ this.__proxy_props = {
10
+ mimeType,
11
+ trusted,
12
+ };
10
13
  options ||= {};
11
- options.mimeType = mimeType;
12
14
  options!.convert ||= null!;
13
15
  options!.toMimeTypes ||= null!;
14
16
 
15
17
  for (const [key, value] of Object.entries(options)) {
18
+ if (key in this.__proxy_props || key === '__proxy_props')
19
+ continue;
16
20
  if (RpcPeer.isTransportSafe(value))
17
21
  this.__proxy_props[key] = value;
18
22
  (this as any)[key] = value;
@@ -6,7 +6,6 @@ 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';
10
9
  import { Plugin, PluginDevice } from '../db-types';
11
10
  import { IOServer, IOServerSocket } from '../io';
12
11
  import type { LogEntry, Logger } from '../logger';
@@ -210,7 +209,7 @@ export class PluginHost {
210
209
 
211
210
  const { runtime } = this.packageJson.scrypted;
212
211
  const mediaManager = runtime && runtime !== 'node'
213
- ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true)
212
+ ? new MediaManagerHostImpl(pluginDeviceId, () => scrypted.stateManager.getSystemState(), console, id => scrypted.getDevice(id), true, scrypted.clusterSetup.connectRPCObject)
214
213
  : undefined;
215
214
 
216
215
  this.api = new PluginHostAPI(scrypted, this.pluginId, this, mediaManager!);
@@ -374,6 +373,7 @@ export class PluginHost {
374
373
  reject(new Error('peer disconnected'));
375
374
  }
376
375
  });
376
+ this.scrypted.clusterSetup.registerClusterPeer(this.peer);
377
377
 
378
378
  peer = Promise.resolve(this.peer);
379
379
 
@@ -400,20 +400,12 @@ export class PluginHost {
400
400
  }
401
401
  });
402
402
 
403
- const clusterSetup = setupCluster(this.peer);
404
403
  const { runtimeWorker, forkPeer, clusterWorkerId } = createClusterForkWorker(
405
404
  runtimeWorkerOptions,
406
405
  scrypted,
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
- })(),
406
+ Promise.resolve(this.scrypted.clusterFork),
415
407
  async () => fs.promises.readFile(this.zipFile),
416
- clusterSetup.connectRPCObject);
408
+ this.scrypted.clusterSetup.connectRPCObject);
417
409
 
418
410
  forkPeer.then(peer => {
419
411
  const originalPeer = this.peer;
@@ -508,6 +500,7 @@ export class PluginHost {
508
500
  console,
509
501
  id => this.scrypted.getDevice(id),
510
502
  !accessControls,
503
+ this.scrypted.clusterSetup.connectRPCObject,
511
504
  );
512
505
  const api = new PluginAPIProxy(this.api, mediaManager);
513
506
  api.acl = accessControls;
@@ -45,6 +45,7 @@ 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);
48
49
  peer.params.ping = async (time: number) => {
49
50
  return time;
50
51
  };
@@ -78,7 +79,7 @@ export function startPluginRemote(mainFilename: string, pluginId: string, peerSe
78
79
  createMediaManager: async (sm, dm) => {
79
80
  systemManager = sm;
80
81
  deviceManager = dm;
81
- return new MediaManagerImpl(systemManager, dm);
82
+ return new MediaManagerImpl(systemManager, dm, connectRPCObject);
82
83
  },
83
84
  onGetRemote: async (_api, _pluginId) => {
84
85
  class PluginForkableAPI extends PluginAPIProxy {
package/src/rpc.ts CHANGED
@@ -298,6 +298,7 @@ export class RpcPeer {
298
298
  proxyId: string;
299
299
  properties: any;
300
300
  };
301
+ onProxyDeserialization?: (rpcProxy: any) => any;
301
302
  constructorSerializerMap = new Map<any, string>();
302
303
  transportSafeArgumentTypes = RpcPeer.getDefaultTransportSafeArgumentTypes();
303
304
  killed: Promise<string>;
@@ -562,6 +563,9 @@ export class RpcPeer {
562
563
  return deserializer.deserialize(proxy, deserializationContext);
563
564
  }
564
565
 
566
+ const onProxyDeserializationResolved = this.onProxyDeserialization?.(proxy);
567
+ if (onProxyDeserializationResolved)
568
+ return onProxyDeserializationResolved;
565
569
  return proxy;
566
570
  }
567
571
 
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 } from './cluster/cluster-setup';
18
+ import { isClusterAddress, setupCluster } 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,6 +47,7 @@ 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';
50
51
 
51
52
  interface DeviceProxyPair {
52
53
  handler: PluginDeviceProxyHandler;
@@ -85,6 +86,10 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
85
86
  })
86
87
  },
87
88
  });
89
+ runtimePeer = new RpcPeer('runtime', 'runtime', (message, reject, serializationContext) => {
90
+ console.warn('unexpected message to runtime peer', message);
91
+ });
92
+ clusterSetup = setupCluster(this.runtimePeer);
88
93
  pluginComponent = new PluginComponent(this);
89
94
  serviceControl = new ServiceControl();
90
95
  alerts = new Alerts(this);
@@ -944,6 +949,12 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
944
949
  // catch kill
945
950
  process.on('SIGTERM', () => this.exit());
946
951
 
952
+ await this.clusterSetup.initializeCluster({
953
+ clusterId: this.clusterId,
954
+ clusterSecret: this.clusterSecret,
955
+ clusterWorkerId: this.serverClusterWorkerId,
956
+ });
957
+
947
958
  for await (const pluginDevice of this.datastore.getAll(PluginDevice)) {
948
959
  // this may happen due to race condition around deletion/update. investigate.
949
960
  if (!pluginDevice.state) {