@scrypted/server 0.148.6 → 0.148.8

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/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@scrypted/server",
3
- "version": "0.148.6",
3
+ "version": "0.148.8",
4
4
  "description": "",
5
5
  "dependencies": {
6
6
  "@scrypted/ffmpeg-static": "^6.1.0-build3",
7
7
  "@scrypted/node-pty": "^1.0.25",
8
- "@scrypted/types": "^0.5.55",
8
+ "@scrypted/types": "^0.5.57",
9
9
  "adm-zip": "0.6.0",
10
10
  "body-parser": "^2.2.0",
11
11
  "cookie-parser": "^1.4.7",
@@ -55,6 +55,8 @@ class ClusterSetup:
55
55
  sha256 = self.computeClusterObjectHash(o)
56
56
  if sha256 != o["sha256"]:
57
57
  raise Exception("secret incorrect")
58
+ if o.get("id", None) != self.clusterId:
59
+ raise Exception("invalid cluster id")
58
60
  return await self.resolveObject(
59
61
  o.get("proxyId", None), o.get("sourceKey", None)
60
62
  )
@@ -119,6 +121,7 @@ class ClusterSetup:
119
121
  future.set_result(peer)
120
122
  self.clusterPeers[clusterPeerKey] = future
121
123
  peer.params["connectRPCObject"] = lambda o: self.connectClusterObject(o)
124
+ peer.params["isRpcProxy"] = lambda o: isinstance(o, rpc.RpcProxy)
122
125
  try:
123
126
  await peerReadLoop()
124
127
  except:
@@ -212,12 +215,12 @@ class ClusterSetup:
212
215
 
213
216
  clusterObject: ClusterObject = __cluster
214
217
 
215
- if clusterObject.get("id", None) != self.clusterId:
216
- return value
217
-
218
218
  if self.computeClusterObjectHash(clusterObject) != clusterObject.get("sha256", None):
219
219
  raise Exception("invalid cluster object signature")
220
220
 
221
+ if clusterObject.get("id", None) != self.clusterId:
222
+ raise Exception("invalid cluster id")
223
+
221
224
  address = clusterObject.get("address", None)
222
225
  port = clusterObject["port"]
223
226
  proxyId = clusterObject["proxyId"]
@@ -1150,6 +1150,7 @@ async def plugin_async_main(
1150
1150
  ):
1151
1151
  peer, readLoop = await rpc_reader.prepare_peer_readloop(loop, rpcTransport)
1152
1152
  peer.params["print"] = print
1153
+ peer.params["isRpcProxy"] = lambda o: isinstance(o, rpc.RpcProxy)
1153
1154
 
1154
1155
  clusterSetup = ClusterSetup(loop, peer)
1155
1156
  peer.params["initializeCluster"] = lambda options: clusterSetup.initializeCluster(
@@ -18,9 +18,9 @@ export function isClusterAddress(address: string) {
18
18
  return !address || address === process.env.SCRYPTED_CLUSTER_ADDRESS;
19
19
  }
20
20
 
21
- export function getClusterObject(clusterId: string, value: any): ClusterObject | undefined {
21
+ export function getClusterObject(value: any): ClusterObject | undefined {
22
22
  const clusterObject: ClusterObject = value?.__cluster;
23
- if (clusterObject?.id !== clusterId)
23
+ if (!clusterObject || typeof clusterObject !== 'object' || Array.isArray(clusterObject))
24
24
  return undefined;
25
25
  return clusterObject;
26
26
  }
@@ -67,11 +67,17 @@ export function setupCluster(peer: RpcPeer) {
67
67
  }
68
68
  return ret;
69
69
  }
70
+
71
+ const isRpcProxy = async (o: any) => {
72
+ return RpcPeer.isRpcProxy(o);
73
+ };
70
74
 
71
75
  const connectClusterObject = async (o: ClusterObject) => {
72
76
  const sha256 = computeClusterObjectHash(o, clusterSecret);
73
77
  if (sha256 !== o.sha256)
74
78
  throw new Error('secret incorrect');
79
+ if (o.id !== clusterId)
80
+ throw new Error('invalid cluster id');
75
81
  return resolveObject(o.proxyId, o.sourceKey);
76
82
  }
77
83
 
@@ -151,6 +157,7 @@ export function setupCluster(peer: RpcPeer) {
151
157
  threadPeer.onProxySerialization = value => onProxySerialization(threadPeer, value, threadPeerKey);
152
158
 
153
159
  threadPeer.params.connectRPCObject = connectClusterObject;
160
+ threadPeer.params.isRpcProxy = isRpcProxy;
154
161
 
155
162
  function cleanup(message: string) {
156
163
  peerCleanup();
@@ -255,12 +262,14 @@ export function setupCluster(peer: RpcPeer) {
255
262
  }
256
263
 
257
264
  const connectRPCObject = async (value: any) => {
258
- const clusterObject = getClusterObject(clusterId, value);
265
+ const clusterObject = getClusterObject(value);
259
266
  if (!clusterObject)
260
267
  return value;
261
268
  // invalidate cluster objects that do not have a valid signature for this cluster.
262
269
  if (computeClusterObjectHash(clusterObject, clusterSecret) !== clusterObject.sha256)
263
270
  throw new Error('invalid cluster object signature');
271
+ if (clusterObject.id !== clusterId)
272
+ throw new Error('invalid cluster id');
264
273
  const { address, port, proxyId } = clusterObject;
265
274
  // handle the case when trying to connect to an object is on this cluster node,
266
275
  // returning the actual object, rather than initiating a loopback connection.
@@ -330,6 +339,18 @@ export function setupCluster(peer: RpcPeer) {
330
339
  properties,
331
340
  };
332
341
  }
342
+
343
+ const registerClusterPeer = (clusterPeer: RpcPeer, key = `local:${RpcPeer.generateId()}`) => {
344
+ clusterPeer.onProxySerialization = value => onProxySerialization(clusterPeer, value, key);
345
+ const registered = Promise.resolve(clusterPeer);
346
+ clusterPeers.set(key, registered);
347
+ clusterPeer.killedSafe.finally(() => {
348
+ if (clusterPeers.get(key) === registered)
349
+ clusterPeers.delete(key);
350
+ });
351
+ return key;
352
+ }
353
+
333
354
  const initializeCluster: InitializeCluster = async (options: {
334
355
  clusterId: string;
335
356
  clusterSecret: string;
@@ -353,6 +374,7 @@ export function setupCluster(peer: RpcPeer) {
353
374
  clusterPeer.onProxySerialization = (value) => onProxySerialization(clusterPeer, value, clusterPeerKey);
354
375
  clusterPeers.set(clusterPeerKey, Promise.resolve(clusterPeer));
355
376
  clusterPeer.params.connectRPCObject = connectClusterObject;
377
+ clusterPeer.params.isRpcProxy = isRpcProxy;
356
378
  client.on('close', () => {
357
379
  clusterPeers.delete(clusterPeerKey);
358
380
  clusterPeer.kill('cluster socket closed');
@@ -385,6 +407,7 @@ export function setupCluster(peer: RpcPeer) {
385
407
  SCRYPTED_CLUSTER_ADDRESS,
386
408
  clusterPeers,
387
409
  onProxySerialization,
410
+ registerClusterPeer,
388
411
  connectClusterObject,
389
412
  ensureClusterPeer,
390
413
  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;
@@ -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,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;
@@ -66,8 +67,8 @@ export class ScryptedRuntime extends PluginHttp<HttpPluginData> {
66
67
  clusterSecret = process.env.SCRYPTED_CLUSTER_SECRET || crypto.randomBytes(16).toString('hex');
67
68
  clusterWorkers = new Map<string, RunningClusterWorker>();
68
69
  serverClusterWorkerId!: string;
69
- plugins: { [id: string]: PluginHost } = {};
70
- pluginDevices: { [id: string]: PluginDevice } = {};
70
+ plugins: { [id: string]: PluginHost } = Object.create(null);
71
+ pluginDevices: { [id: string]: PluginDevice } = Object.create(null);
71
72
  devices: { [id: string]: DeviceProxyPair } = {};
72
73
  stateManager = new ScryptedStateManager(this);
73
74
  logger = new Logger(this, '', 'Scrypted');
@@ -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) {
@@ -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
  }