@scrypted/server 0.148.6 → 0.148.7

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,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
@@ -311,7 +311,7 @@ export class RpcPeer {
311
311
  static activeRpcPeer: RpcPeer | undefined;
312
312
 
313
313
  static isRpcProxy(value: any) {
314
- return !!value?.[RpcPeer.PROPERTY_PROXY_ID];
314
+ return value?.[RpcPeer.PROPERTY_PROXY_PEER] instanceof RpcPeer;
315
315
  }
316
316
 
317
317
  static getDefaultTransportSafeArgumentTypes() {
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);
@@ -126,6 +131,13 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
126
131
  connection.close();
127
132
  return;
128
133
  }
134
+ if (clusterObject.id !== this.clusterId) {
135
+ connection.send({
136
+ error: 'invalid cluster id'
137
+ });
138
+ connection.close();
139
+ return;
140
+ }
129
141
 
130
142
  let address = clusterObject.address;
131
143
  if (isClusterAddress(address))
@@ -176,10 +188,9 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
176
188
  }
177
189
 
178
190
  checkUpgrade(req: express.Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: express.Response<any, Record<string, any>>, pluginData: HttpPluginData): void {
179
- // pluginData.pluginHost.io.
180
191
  const { sid } = req.query;
181
- const client = (pluginData.pluginHost.io as any).clients[sid as string];
182
- if (client) {
192
+ const clients = (pluginData.pluginHost.io as any).clients;
193
+ if (typeof sid === 'string' && Object.prototype.hasOwnProperty.call(clients, sid)) {
183
194
  res.locals.username = 'existing-io-session';
184
195
  }
185
196
  }
@@ -938,6 +949,12 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
938
949
  // catch kill
939
950
  process.on('SIGTERM', () => this.exit());
940
951
 
952
+ await this.clusterSetup.initializeCluster({
953
+ clusterId: this.clusterId,
954
+ clusterSecret: this.clusterSecret,
955
+ clusterWorkerId: this.serverClusterWorkerId,
956
+ });
957
+
941
958
  for await (const pluginDevice of this.datastore.getAll(PluginDevice)) {
942
959
  // this may happen due to race condition around deletion/update. investigate.
943
960
  if (!pluginDevice.state) {