@rsdoctor/sdk 1.5.14 → 1.5.16

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/dist/index.cjs CHANGED
@@ -5695,6 +5695,19 @@ var __webpack_modules__ = {
5695
5695
  return this.dataLoader.loadAPI;
5696
5696
  }
5697
5697
  }
5698
+ let external_node_net_namespaceObject = require("node:net"), DEFAULT_ALLOWED_CORS_ORIGINS = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, LOCAL_HOSTNAMES = /^(?:localhost|[^:]+\.localhost)$/;
5699
+ function getHostnameFromHost(host) {
5700
+ if (host.startsWith('[')) {
5701
+ let endIndex = host.indexOf(']');
5702
+ return -1 === endIndex ? '' : host.slice(1, endIndex);
5703
+ }
5704
+ return host.split(':')[0];
5705
+ }
5706
+ function isAllowedRequestHost(host) {
5707
+ if ('string' != typeof host) return !1;
5708
+ let hostname = getHostnameFromHost(host).toLowerCase();
5709
+ return LOCAL_HOSTNAMES.test(hostname) || 0 !== (0, external_node_net_namespaceObject.isIP)(hostname);
5710
+ }
5698
5711
  class Socket {
5699
5712
  constructor(options){
5700
5713
  this.options = options, this.map = new Map(), this.loader = new SocketAPILoader({
@@ -5702,11 +5715,13 @@ var __webpack_modules__ = {
5702
5715
  });
5703
5716
  }
5704
5717
  bootstrap() {
5718
+ let { socketOptions } = this.options;
5705
5719
  this.io = new external_socket_io_namespaceObject.Server(this.options.server, {
5706
- cors: {
5707
- origin: '*'
5708
- },
5709
- ...this.options.socketOptions
5720
+ ...socketOptions,
5721
+ allowRequest: (req, callback)=>{
5722
+ var url, token;
5723
+ isAllowedRequestHost(req.headers.host || req.headers[':authority']) && (url = req.url, token = this.options.token, url && new URL(url, 'http://localhost').searchParams.get('token') === token) ? socketOptions?.allowRequest ? socketOptions.allowRequest(req, callback) : callback(null, !0) : callback(null, !1);
5724
+ }
5710
5725
  }), this.io.on('connection', (socket)=>{
5711
5726
  this.setupSocket(socket);
5712
5727
  });
@@ -6131,10 +6146,6 @@ var __webpack_modules__ = {
6131
6146
  plugin_ts_metadata("design:returntype", Promise)
6132
6147
  ], PluginAPI.prototype, "getPluginData", null);
6133
6148
  var external_os_ = __webpack_require__("os"), external_os_default = __webpack_require__.n(external_os_);
6134
- function getLocalIpAddress() {
6135
- for (let iface of Object.values(external_os_default().networkInterfaces()))for (let alias of iface)if ('IPv4' === alias.family && !alias.internal) return alias.address;
6136
- return '127.0.0.1';
6137
- }
6138
6149
  function project_ts_decorate(decorators, target, key, desc) {
6139
6150
  var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
6140
6151
  if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
@@ -6148,7 +6159,10 @@ var __webpack_modules__ = {
6148
6159
  async env() {
6149
6160
  let { server } = this.ctx;
6150
6161
  return {
6151
- ip: getLocalIpAddress(),
6162
+ ip: function() {
6163
+ for (let iface of Object.values(external_os_default().networkInterfaces()))for (let alias of iface)if ('IPv4' === alias.family && !alias.internal) return alias.address;
6164
+ return '127.0.0.1';
6165
+ }(),
6152
6166
  port: server.port
6153
6167
  };
6154
6168
  }
@@ -6273,10 +6287,10 @@ var __webpack_modules__ = {
6273
6287
  return logger_namespaceObject.logger.error('Failed to open Rsdoctor URL.'), logger_namespaceObject.logger.error(err), !1;
6274
6288
  }
6275
6289
  }
6276
- let server_require = (0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
6290
+ let external_crypto_namespaceObject = require("crypto"), server_require = (0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
6277
6291
  class RsdoctorServer {
6278
6292
  constructor(sdk, port = build_namespaceObject.Server.defaultPort, config){
6279
- this.sdk = sdk, this.disposed = !0, this.get = (route, cb)=>{
6293
+ this.sdk = sdk, this.disposed = !0, this._socketToken = (0, external_crypto_namespaceObject.randomBytes)(16).toString('hex'), this.get = (route, cb)=>{
6280
6294
  let { app } = this;
6281
6295
  return app.use(route, this.wrapNextHandleFunction('GET', cb)), app;
6282
6296
  }, this.post = (route, cb)=>{
@@ -6292,13 +6306,13 @@ var __webpack_modules__ = {
6292
6306
  sdk,
6293
6307
  server: this,
6294
6308
  apis: Object.values(apis_namespaceObject)
6295
- }), this._innerClientPath = config?.innerClientPath || '', this._printServerUrl = !!common_namespaceObject.Lodash.isUndefined(config?.printServerUrl) || config?.printServerUrl;
6309
+ }), this._innerClientPath = config?.innerClientPath || '', this._printServerUrl = !!common_namespaceObject.Lodash.isUndefined(config?.printServerUrl) || config?.printServerUrl, this._cors = config?.cors;
6296
6310
  }
6297
6311
  get app() {
6298
6312
  return this._server.app;
6299
6313
  }
6300
6314
  get host() {
6301
- return getLocalIpAddress();
6315
+ return build_namespaceObject.Server.defaultHost;
6302
6316
  }
6303
6317
  get origin() {
6304
6318
  return `http://${this.host}:${this.port}`;
@@ -6306,22 +6320,76 @@ var __webpack_modules__ = {
6306
6320
  get socketUrl() {
6307
6321
  return {
6308
6322
  port: this.port,
6309
- socketUrl: `ws://localhost:${this.port}`
6323
+ socketUrl: `ws://localhost:${this.port}?token=${this._socketToken}`,
6324
+ token: this._socketToken
6310
6325
  };
6311
6326
  }
6312
6327
  get innerClientPath() {
6313
6328
  return this._innerClientPath;
6314
6329
  }
6330
+ async createInnerServer() {
6331
+ let lastError, expectedPort = this.port;
6332
+ for(let retry = 0; retry < 10; retry++){
6333
+ let port = build_namespaceObject.Server.getPortSync(expectedPort, this.host);
6334
+ try {
6335
+ return {
6336
+ port,
6337
+ server: await build_namespaceObject.Server.createServer(port, this.host)
6338
+ };
6339
+ } catch (error) {
6340
+ if ('EADDRINUSE' !== error.code) throw error;
6341
+ lastError = error, expectedPort = port + 1;
6342
+ }
6343
+ }
6344
+ throw lastError;
6345
+ }
6346
+ resolveCorsOptions() {
6347
+ return !1 !== this._cors && (!0 === this._cors ? {} : void 0 === this._cors ? {
6348
+ origin: DEFAULT_ALLOWED_CORS_ORIGINS
6349
+ } : {
6350
+ ...this._cors,
6351
+ origin: void 0 === this._cors.origin ? DEFAULT_ALLOWED_CORS_ORIGINS : this._cors.origin
6352
+ });
6353
+ }
6315
6354
  async bootstrap() {
6316
6355
  if (!this.disposed) return;
6317
- let port = build_namespaceObject.Server.getPortSync(this.port);
6318
- this.port = port, this._server = await build_namespaceObject.Server.createServer(port), this._socket = new Socket({
6356
+ let { port, server } = await this.createInnerServer(), corsOptions = this.resolveCorsOptions();
6357
+ this.port = port, this._server = server, this._socket = new Socket({
6319
6358
  sdk: this.sdk,
6320
6359
  server: this._server.server,
6321
- port: this.port
6322
- }), await this._socket.bootstrap(), common_namespaceObject.GlobalConfig.writeMcpPort(this.port, this.sdk.name), logger_namespaceObject.logger.debug(`Successfully wrote mcp.json for ${logger_namespaceObject.chalk.cyan(this.sdk.name)} builder`), this.disposed = !1, this.app.use(cors_index_js_default()()), this.app.use(body_parser_default().json({
6360
+ port: this.port,
6361
+ token: this._socketToken,
6362
+ socketOptions: !1 === corsOptions ? void 0 : {
6363
+ cors: corsOptions
6364
+ }
6365
+ }), await this._socket.bootstrap(), common_namespaceObject.GlobalConfig.writeMcpPort(this.port, this.sdk.name), logger_namespaceObject.logger.debug(`Successfully wrote mcp.json for ${logger_namespaceObject.chalk.cyan(this.sdk.name)} builder`), this.disposed = !1, this.app.use((req, res, next)=>{
6366
+ if (!isAllowedRequestHost(req.headers.host || req.headers[':authority'])) {
6367
+ res.statusCode = 403, res.end();
6368
+ return;
6369
+ }
6370
+ next();
6371
+ }), !1 !== corsOptions && corsOptions.origin === DEFAULT_ALLOWED_CORS_ORIGINS && this.app.use((req, res, next)=>{
6372
+ let host = req.headers.host || req.headers[':authority'];
6373
+ if (!function(origin, host) {
6374
+ if (void 0 === origin) return !0;
6375
+ if ('string' != typeof origin || 'string' != typeof host || !(void 0 === origin || 'string' == typeof origin && DEFAULT_ALLOWED_CORS_ORIGINS.test(origin))) return !1;
6376
+ let originHostname = function(origin) {
6377
+ try {
6378
+ let hostname = new URL(origin).hostname.toLowerCase();
6379
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
6380
+ } catch {
6381
+ return '';
6382
+ }
6383
+ }(origin), hostHostname = getHostnameFromHost(host).toLowerCase();
6384
+ return !originHostname.endsWith('.localhost') || originHostname === hostHostname;
6385
+ }(req.headers.origin, host)) {
6386
+ res.statusCode = 403, res.end();
6387
+ return;
6388
+ }
6389
+ next();
6390
+ }), !1 !== corsOptions && this.app.use(cors_index_js_default()(corsOptions)), this.app.use(body_parser_default().json({
6323
6391
  limit: '500mb'
6324
- }));
6392
+ })), await this._router.setup();
6325
6393
  let clientHtmlPath = this._innerClientPath ? this._innerClientPath : server_require.resolve('@rsdoctor/client'), clientDistPath = external_path_default().resolve(clientHtmlPath, '..');
6326
6394
  this.app.use(function(dir, opts = {}) {
6327
6395
  dir = (0, external_node_path_.resolve)(dir || '.');
@@ -6414,7 +6482,7 @@ var __webpack_modules__ = {
6414
6482
  } catch (err) {
6415
6483
  res.writableEnded || (res.statusCode = 500, res.end(err.message));
6416
6484
  }
6417
- }), await this._router.setup(), process.once('exit', ()=>this.dispose()), process.once('SIGINT', ()=>this.dispose(0)), process.once('SIGTERM', ()=>this.dispose(0)), process.once('unhandledRejection', (reason)=>{
6485
+ }), process.once('exit', ()=>this.dispose()), process.once('SIGINT', ()=>this.dispose(0)), process.once('SIGTERM', ()=>this.dispose(0)), process.once('unhandledRejection', (reason)=>{
6418
6486
  console.error('Unhandled promise rejection:', reason), this.dispose(1);
6419
6487
  }), process.once('uncaughtException', (err, origin)=>{
6420
6488
  console.error('Uncaught exception:', err), origin && console.error('Exception origin:', origin), this.dispose(1);
@@ -6425,7 +6493,7 @@ var __webpack_modules__ = {
6425
6493
  if (req.method?.toUpperCase() === method) {
6426
6494
  try {
6427
6495
  let body = await cb(req, res, next);
6428
- if (res.setHeader('Access-Control-Allow-Origin', '*'), res.setHeader('Access-Control-Allow-Credentials', 'true'), res.statusCode = 200, Buffer.isBuffer(body)) {
6496
+ if (res.statusCode = 200, Buffer.isBuffer(body)) {
6429
6497
  res.setHeader('Content-Length', body.byteLength);
6430
6498
  let ps = new external_stream_.PassThrough();
6431
6499
  ps.write(body), ps.end(), ps.pipe(res);
@@ -6622,9 +6690,12 @@ var __webpack_modules__ = {
6622
6690
  constructor(options){
6623
6691
  super(options), this._summary = {
6624
6692
  costs: []
6625
- }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new graph_namespaceObject.ModuleGraph(), this._chunkGraph = new graph_namespaceObject.ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map(), this.server = options.config?.noServer ? new RsdoctorFakeServer(this, void 0) : new RsdoctorServer(this, options.port, {
6693
+ }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new graph_namespaceObject.ModuleGraph(), this._chunkGraph = new graph_namespaceObject.ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map();
6694
+ const serverConfig = options.config?.server, port = serverConfig?.port ?? options.port;
6695
+ this.server = options.config?.noServer ? new RsdoctorFakeServer(this, port) : new RsdoctorServer(this, port, {
6626
6696
  innerClientPath: options.config?.innerClientPath || '',
6627
- printServerUrl: options.config?.printLog?.serverUrls
6697
+ printServerUrl: options.config?.printLog?.serverUrls,
6698
+ cors: serverConfig?.cors
6628
6699
  }), this.type = common_namespaceObject.Lodash.isNumber(options.type) ? options.type : types_namespaceObject.SDK.ToDataType.Normal, this.extraConfig = options.config, this.root = findRoot() ?? '';
6629
6700
  }
6630
6701
  async bootstrap() {
@@ -6920,8 +6991,8 @@ var __webpack_modules__ = {
6920
6991
  }
6921
6992
  }
6922
6993
  class RsdoctorSlaveServer extends RsdoctorServer {
6923
- constructor(sdk, port = build_namespaceObject.Server.defaultPort){
6924
- super(sdk, port), this.sdk = sdk;
6994
+ constructor(sdk, port = build_namespaceObject.Server.defaultPort, config){
6995
+ super(sdk, port, config), this.sdk = sdk;
6925
6996
  }
6926
6997
  async openClientPage(...args) {
6927
6998
  return this.sdk.isMaster ? super.openClientPage(...args) : Promise.resolve();
@@ -6932,10 +7003,13 @@ var __webpack_modules__ = {
6932
7003
  constructor({ name, stage, controller, extraConfig, type }){
6933
7004
  super({
6934
7005
  name,
6935
- root: controller.root
7006
+ root: controller.root,
7007
+ config: extraConfig
6936
7008
  });
6937
- const lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : this.server.port;
6938
- this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.extraConfig = extraConfig, this.parent = controller, this.server = new RsdoctorSlaveServer(this, port), this.type = type, this.setName(name), this.clearSwitch();
7009
+ const lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : extraConfig?.server?.port ?? this.server.port;
7010
+ this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.extraConfig = extraConfig, this.parent = controller, this.server = new RsdoctorSlaveServer(this, port, {
7011
+ cors: extraConfig?.server?.cors
7012
+ }), this.type = type, this.setName(name), this.clearSwitch();
6939
7013
  }
6940
7014
  clearSwitch() {
6941
7015
  this.uploadPieces = new Promise((resolve)=>{
package/dist/index.js CHANGED
@@ -18,9 +18,11 @@ import cors from "../compiled/cors/index.js";
18
18
  import { PassThrough } from "stream";
19
19
  import { Server as external_socket_io_Server } from "socket.io";
20
20
  import { isDeepStrictEqual } from "util";
21
+ import { isIP } from "node:net";
21
22
  import os from "os";
22
23
  import { exec } from "node:child_process";
23
24
  import { promisify } from "node:util";
25
+ import { randomBytes } from "crypto";
24
26
  import { createHash, randomUUID } from "node:crypto";
25
27
  import node_process from "node:process";
26
28
  import { AsyncSeriesHook } from "tapable";
@@ -5714,6 +5716,19 @@ class SocketAPILoader {
5714
5716
  return this.dataLoader.loadAPI;
5715
5717
  }
5716
5718
  }
5719
+ let DEFAULT_ALLOWED_CORS_ORIGINS = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, LOCAL_HOSTNAMES = /^(?:localhost|[^:]+\.localhost)$/;
5720
+ function getHostnameFromHost(host) {
5721
+ if (host.startsWith('[')) {
5722
+ let endIndex = host.indexOf(']');
5723
+ return -1 === endIndex ? '' : host.slice(1, endIndex);
5724
+ }
5725
+ return host.split(':')[0];
5726
+ }
5727
+ function isAllowedRequestHost(host) {
5728
+ if ('string' != typeof host) return !1;
5729
+ let hostname = getHostnameFromHost(host).toLowerCase();
5730
+ return LOCAL_HOSTNAMES.test(hostname) || 0 !== isIP(hostname);
5731
+ }
5717
5732
  class Socket {
5718
5733
  constructor(options){
5719
5734
  this.options = options, this.map = new Map(), this.loader = new SocketAPILoader({
@@ -5721,11 +5736,13 @@ class Socket {
5721
5736
  });
5722
5737
  }
5723
5738
  bootstrap() {
5739
+ let { socketOptions } = this.options;
5724
5740
  this.io = new external_socket_io_Server(this.options.server, {
5725
- cors: {
5726
- origin: '*'
5727
- },
5728
- ...this.options.socketOptions
5741
+ ...socketOptions,
5742
+ allowRequest: (req, callback)=>{
5743
+ var url, token;
5744
+ isAllowedRequestHost(req.headers.host || req.headers[':authority']) && (url = req.url, token = this.options.token, url && new URL(url, 'http://localhost').searchParams.get('token') === token) ? socketOptions?.allowRequest ? socketOptions.allowRequest(req, callback) : callback(null, !0) : callback(null, !1);
5745
+ }
5729
5746
  }), this.io.on('connection', (socket)=>{
5730
5747
  this.setupSocket(socket);
5731
5748
  });
@@ -6138,10 +6155,6 @@ class PluginAPI extends BaseAPI {
6138
6155
  });
6139
6156
  }
6140
6157
  }
6141
- function getLocalIpAddress() {
6142
- for (let iface of Object.values(os.networkInterfaces()))for (let alias of iface)if ('IPv4' === alias.family && !alias.internal) return alias.address;
6143
- return '127.0.0.1';
6144
- }
6145
6158
  function project_ts_decorate(decorators, target, key, desc) {
6146
6159
  var d, c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
6147
6160
  if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
@@ -6166,7 +6179,10 @@ class ProjectAPI extends BaseAPI {
6166
6179
  async env() {
6167
6180
  let { server } = this.ctx;
6168
6181
  return {
6169
- ip: getLocalIpAddress(),
6182
+ ip: function() {
6183
+ for (let iface of Object.values(os.networkInterfaces()))for (let alias of iface)if ('IPv4' === alias.family && !alias.internal) return alias.address;
6184
+ return '127.0.0.1';
6185
+ }(),
6170
6186
  port: server.port
6171
6187
  };
6172
6188
  }
@@ -6296,7 +6312,7 @@ var body_parser_default = __webpack_require__.n(body_parser);
6296
6312
  let server_require = createRequire(import.meta.url);
6297
6313
  class RsdoctorServer {
6298
6314
  constructor(sdk, port = Server.defaultPort, config){
6299
- this.sdk = sdk, this.disposed = !0, this.get = (route, cb)=>{
6315
+ this.sdk = sdk, this.disposed = !0, this._socketToken = randomBytes(16).toString('hex'), this.get = (route, cb)=>{
6300
6316
  let { app } = this;
6301
6317
  return app.use(route, this.wrapNextHandleFunction('GET', cb)), app;
6302
6318
  }, this.post = (route, cb)=>{
@@ -6312,13 +6328,13 @@ class RsdoctorServer {
6312
6328
  sdk,
6313
6329
  server: this,
6314
6330
  apis: Object.values(apis_namespaceObject)
6315
- }), this._innerClientPath = config?.innerClientPath || '', this._printServerUrl = !!Lodash.isUndefined(config?.printServerUrl) || config?.printServerUrl;
6331
+ }), this._innerClientPath = config?.innerClientPath || '', this._printServerUrl = !!Lodash.isUndefined(config?.printServerUrl) || config?.printServerUrl, this._cors = config?.cors;
6316
6332
  }
6317
6333
  get app() {
6318
6334
  return this._server.app;
6319
6335
  }
6320
6336
  get host() {
6321
- return getLocalIpAddress();
6337
+ return Server.defaultHost;
6322
6338
  }
6323
6339
  get origin() {
6324
6340
  return `http://${this.host}:${this.port}`;
@@ -6326,22 +6342,76 @@ class RsdoctorServer {
6326
6342
  get socketUrl() {
6327
6343
  return {
6328
6344
  port: this.port,
6329
- socketUrl: `ws://localhost:${this.port}`
6345
+ socketUrl: `ws://localhost:${this.port}?token=${this._socketToken}`,
6346
+ token: this._socketToken
6330
6347
  };
6331
6348
  }
6332
6349
  get innerClientPath() {
6333
6350
  return this._innerClientPath;
6334
6351
  }
6352
+ async createInnerServer() {
6353
+ let lastError, expectedPort = this.port;
6354
+ for(let retry = 0; retry < 10; retry++){
6355
+ let port = Server.getPortSync(expectedPort, this.host);
6356
+ try {
6357
+ return {
6358
+ port,
6359
+ server: await Server.createServer(port, this.host)
6360
+ };
6361
+ } catch (error) {
6362
+ if ('EADDRINUSE' !== error.code) throw error;
6363
+ lastError = error, expectedPort = port + 1;
6364
+ }
6365
+ }
6366
+ throw lastError;
6367
+ }
6368
+ resolveCorsOptions() {
6369
+ return !1 !== this._cors && (!0 === this._cors ? {} : void 0 === this._cors ? {
6370
+ origin: DEFAULT_ALLOWED_CORS_ORIGINS
6371
+ } : {
6372
+ ...this._cors,
6373
+ origin: void 0 === this._cors.origin ? DEFAULT_ALLOWED_CORS_ORIGINS : this._cors.origin
6374
+ });
6375
+ }
6335
6376
  async bootstrap() {
6336
6377
  if (!this.disposed) return;
6337
- let port = Server.getPortSync(this.port);
6338
- this.port = port, this._server = await Server.createServer(port), this._socket = new Socket({
6378
+ let { port, server } = await this.createInnerServer(), corsOptions = this.resolveCorsOptions();
6379
+ this.port = port, this._server = server, this._socket = new Socket({
6339
6380
  sdk: this.sdk,
6340
6381
  server: this._server.server,
6341
- port: this.port
6342
- }), await this._socket.bootstrap(), GlobalConfig.writeMcpPort(this.port, this.sdk.name), logger.debug(`Successfully wrote mcp.json for ${chalk.cyan(this.sdk.name)} builder`), this.disposed = !1, this.app.use(cors()), this.app.use(body_parser_default().json({
6382
+ port: this.port,
6383
+ token: this._socketToken,
6384
+ socketOptions: !1 === corsOptions ? void 0 : {
6385
+ cors: corsOptions
6386
+ }
6387
+ }), await this._socket.bootstrap(), GlobalConfig.writeMcpPort(this.port, this.sdk.name), logger.debug(`Successfully wrote mcp.json for ${chalk.cyan(this.sdk.name)} builder`), this.disposed = !1, this.app.use((req, res, next)=>{
6388
+ if (!isAllowedRequestHost(req.headers.host || req.headers[':authority'])) {
6389
+ res.statusCode = 403, res.end();
6390
+ return;
6391
+ }
6392
+ next();
6393
+ }), !1 !== corsOptions && corsOptions.origin === DEFAULT_ALLOWED_CORS_ORIGINS && this.app.use((req, res, next)=>{
6394
+ let host = req.headers.host || req.headers[':authority'];
6395
+ if (!function(origin, host) {
6396
+ if (void 0 === origin) return !0;
6397
+ if ('string' != typeof origin || 'string' != typeof host || !(void 0 === origin || 'string' == typeof origin && DEFAULT_ALLOWED_CORS_ORIGINS.test(origin))) return !1;
6398
+ let originHostname = function(origin) {
6399
+ try {
6400
+ let hostname = new URL(origin).hostname.toLowerCase();
6401
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
6402
+ } catch {
6403
+ return '';
6404
+ }
6405
+ }(origin), hostHostname = getHostnameFromHost(host).toLowerCase();
6406
+ return !originHostname.endsWith('.localhost') || originHostname === hostHostname;
6407
+ }(req.headers.origin, host)) {
6408
+ res.statusCode = 403, res.end();
6409
+ return;
6410
+ }
6411
+ next();
6412
+ }), !1 !== corsOptions && this.app.use(cors(corsOptions)), this.app.use(body_parser_default().json({
6343
6413
  limit: '500mb'
6344
- }));
6414
+ })), await this._router.setup();
6345
6415
  let clientHtmlPath = this._innerClientPath ? this._innerClientPath : server_require.resolve('@rsdoctor/client'), clientDistPath = path_0.resolve(clientHtmlPath, '..');
6346
6416
  this.app.use(function(dir, opts = {}) {
6347
6417
  dir = external_node_path_resolve(dir || '.');
@@ -6433,7 +6503,7 @@ class RsdoctorServer {
6433
6503
  } catch (err) {
6434
6504
  res.writableEnded || (res.statusCode = 500, res.end(err.message));
6435
6505
  }
6436
- }), await this._router.setup(), process.once('exit', ()=>this.dispose()), process.once('SIGINT', ()=>this.dispose(0)), process.once('SIGTERM', ()=>this.dispose(0)), process.once('unhandledRejection', (reason)=>{
6506
+ }), process.once('exit', ()=>this.dispose()), process.once('SIGINT', ()=>this.dispose(0)), process.once('SIGTERM', ()=>this.dispose(0)), process.once('unhandledRejection', (reason)=>{
6437
6507
  console.error('Unhandled promise rejection:', reason), this.dispose(1);
6438
6508
  }), process.once('uncaughtException', (err, origin)=>{
6439
6509
  console.error('Uncaught exception:', err), origin && console.error('Exception origin:', origin), this.dispose(1);
@@ -6444,7 +6514,7 @@ class RsdoctorServer {
6444
6514
  if (req.method?.toUpperCase() === method) {
6445
6515
  try {
6446
6516
  let body = await cb(req, res, next);
6447
- if (res.setHeader('Access-Control-Allow-Origin', '*'), res.setHeader('Access-Control-Allow-Credentials', 'true'), res.statusCode = 200, Buffer.isBuffer(body)) {
6517
+ if (res.statusCode = 200, Buffer.isBuffer(body)) {
6448
6518
  res.setHeader('Content-Length', body.byteLength);
6449
6519
  let ps = new PassThrough();
6450
6520
  ps.write(body), ps.end(), ps.pipe(res);
@@ -6638,9 +6708,12 @@ class RsdoctorSDK extends SDKCore {
6638
6708
  constructor(options){
6639
6709
  super(options), this._summary = {
6640
6710
  costs: []
6641
- }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new ModuleGraph(), this._chunkGraph = new ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map(), this.server = options.config?.noServer ? new RsdoctorFakeServer(this, void 0) : new RsdoctorServer(this, options.port, {
6711
+ }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new ModuleGraph(), this._chunkGraph = new ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map();
6712
+ let serverConfig = options.config?.server, port = serverConfig?.port ?? options.port;
6713
+ this.server = options.config?.noServer ? new RsdoctorFakeServer(this, port) : new RsdoctorServer(this, port, {
6642
6714
  innerClientPath: options.config?.innerClientPath || '',
6643
- printServerUrl: options.config?.printLog?.serverUrls
6715
+ printServerUrl: options.config?.printLog?.serverUrls,
6716
+ cors: serverConfig?.cors
6644
6717
  }), this.type = Lodash.isNumber(options.type) ? options.type : SDK.ToDataType.Normal, this.extraConfig = options.config, this.root = findRoot() ?? '';
6645
6718
  }
6646
6719
  async bootstrap() {
@@ -6936,8 +7009,8 @@ class RsdoctorSDK extends SDKCore {
6936
7009
  }
6937
7010
  }
6938
7011
  class RsdoctorSlaveServer extends RsdoctorServer {
6939
- constructor(sdk, port = Server.defaultPort){
6940
- super(sdk, port), this.sdk = sdk;
7012
+ constructor(sdk, port = Server.defaultPort, config){
7013
+ super(sdk, port, config), this.sdk = sdk;
6941
7014
  }
6942
7015
  async openClientPage(...args) {
6943
7016
  return this.sdk.isMaster ? super.openClientPage(...args) : Promise.resolve();
@@ -6948,10 +7021,13 @@ class RsdoctorPrimarySDK extends RsdoctorSDK {
6948
7021
  constructor({ name, stage, controller, extraConfig, type }){
6949
7022
  super({
6950
7023
  name,
6951
- root: controller.root
7024
+ root: controller.root,
7025
+ config: extraConfig
6952
7026
  });
6953
- let lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : this.server.port;
6954
- this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.extraConfig = extraConfig, this.parent = controller, this.server = new RsdoctorSlaveServer(this, port), this.type = type, this.setName(name), this.clearSwitch();
7027
+ let lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : extraConfig?.server?.port ?? this.server.port;
7028
+ this.id = primary_id++, this.stage = 'number' == typeof stage ? stage : 1, this.extraConfig = extraConfig, this.parent = controller, this.server = new RsdoctorSlaveServer(this, port, {
7029
+ cors: extraConfig?.server?.cors
7030
+ }), this.type = type, this.setName(name), this.clearSwitch();
6955
7031
  }
6956
7032
  clearSwitch() {
6957
7033
  this.uploadPieces = new Promise((resolve)=>{
@@ -1,7 +1,7 @@
1
- import { RsdoctorServer } from '../server';
1
+ import { RsdoctorServer, type RsdoctorServerOptions } from '../server';
2
2
  import type { RsdoctorPrimarySDK } from './primary';
3
3
  export declare class RsdoctorSlaveServer extends RsdoctorServer {
4
4
  protected sdk: RsdoctorPrimarySDK;
5
- constructor(sdk: RsdoctorPrimarySDK, port?: number);
5
+ constructor(sdk: RsdoctorPrimarySDK, port?: number, config?: RsdoctorServerOptions);
6
6
  openClientPage(...args: unknown[]): Promise<void>;
7
7
  }
@@ -1,7 +1,7 @@
1
- import { RsdoctorServer } from '../server/index.js';
1
+ import { RsdoctorServer, type RsdoctorServerOptions } from '../server/index.js';
2
2
  import type { RsdoctorPrimarySDK } from './primary.js';
3
3
  export declare class RsdoctorSlaveServer extends RsdoctorServer {
4
4
  protected sdk: RsdoctorPrimarySDK;
5
- constructor(sdk: RsdoctorPrimarySDK, port?: number);
5
+ constructor(sdk: RsdoctorPrimarySDK, port?: number, config?: RsdoctorServerOptions);
6
6
  openClientPage(...args: unknown[]): Promise<void>;
7
7
  }
@@ -3,6 +3,12 @@ export * from './utils';
3
3
  export type ISocketType = {
4
4
  port: number;
5
5
  socketUrl: string;
6
+ token: string;
7
+ };
8
+ export type RsdoctorServerOptions = {
9
+ innerClientPath?: string;
10
+ printServerUrl?: boolean;
11
+ cors?: SDK.RsdoctorServerConfig['cors'];
6
12
  };
7
13
  export declare class RsdoctorServer implements SDK.RsdoctorServerInstance {
8
14
  protected sdk: SDK.RsdoctorBuilderSDKInstance;
@@ -13,15 +19,16 @@ export declare class RsdoctorServer implements SDK.RsdoctorServerInstance {
13
19
  private _router;
14
20
  private _innerClientPath;
15
21
  private _printServerUrl;
16
- constructor(sdk: SDK.RsdoctorBuilderSDKInstance, port?: number, config?: {
17
- innerClientPath?: string;
18
- printServerUrl?: boolean;
19
- });
22
+ private _cors;
23
+ private _socketToken;
24
+ constructor(sdk: SDK.RsdoctorBuilderSDKInstance, port?: number, config?: RsdoctorServerOptions);
20
25
  get app(): SDK.RsdoctorServerInstance['app'];
21
26
  get host(): string;
22
27
  get origin(): string;
23
28
  get socketUrl(): ISocketType;
24
29
  get innerClientPath(): string;
30
+ private createInnerServer;
31
+ private resolveCorsOptions;
25
32
  bootstrap(): Promise<void>;
26
33
  protected wrapNextHandleFunction(method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): Thirdparty.connect.NextHandleFunction;
27
34
  proxy(api: SDK.ServerAPI.API, method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): void;
@@ -3,6 +3,12 @@ export * from './utils.js';
3
3
  export type ISocketType = {
4
4
  port: number;
5
5
  socketUrl: string;
6
+ token: string;
7
+ };
8
+ export type RsdoctorServerOptions = {
9
+ innerClientPath?: string;
10
+ printServerUrl?: boolean;
11
+ cors?: SDK.RsdoctorServerConfig['cors'];
6
12
  };
7
13
  export declare class RsdoctorServer implements SDK.RsdoctorServerInstance {
8
14
  protected sdk: SDK.RsdoctorBuilderSDKInstance;
@@ -13,15 +19,16 @@ export declare class RsdoctorServer implements SDK.RsdoctorServerInstance {
13
19
  private _router;
14
20
  private _innerClientPath;
15
21
  private _printServerUrl;
16
- constructor(sdk: SDK.RsdoctorBuilderSDKInstance, port?: number, config?: {
17
- innerClientPath?: string;
18
- printServerUrl?: boolean;
19
- });
22
+ private _cors;
23
+ private _socketToken;
24
+ constructor(sdk: SDK.RsdoctorBuilderSDKInstance, port?: number, config?: RsdoctorServerOptions);
20
25
  get app(): SDK.RsdoctorServerInstance['app'];
21
26
  get host(): string;
22
27
  get origin(): string;
23
28
  get socketUrl(): ISocketType;
24
29
  get innerClientPath(): string;
30
+ private createInnerServer;
31
+ private resolveCorsOptions;
25
32
  bootstrap(): Promise<void>;
26
33
  protected wrapNextHandleFunction(method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): Thirdparty.connect.NextHandleFunction;
27
34
  proxy(api: SDK.ServerAPI.API, method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): void;
@@ -0,0 +1,4 @@
1
+ export declare const DEFAULT_ALLOWED_CORS_ORIGINS: RegExp;
2
+ export declare function isAllowedRequestOrigin(origin: string | string[] | undefined): boolean;
3
+ export declare function isAllowedRequestHost(host: string | string[] | undefined): boolean;
4
+ export declare function isAllowedCorsRequest(origin: string | string[] | undefined, host: string | string[] | undefined): boolean;
@@ -0,0 +1,4 @@
1
+ export declare const DEFAULT_ALLOWED_CORS_ORIGINS: RegExp;
2
+ export declare function isAllowedRequestOrigin(origin: string | string[] | undefined): boolean;
3
+ export declare function isAllowedRequestHost(host: string | string[] | undefined): boolean;
4
+ export declare function isAllowedCorsRequest(origin: string | string[] | undefined, host: string | string[] | undefined): boolean;
@@ -6,7 +6,8 @@ interface SocketOptions {
6
6
  sdk: SDK.RsdoctorBuilderSDKInstance;
7
7
  server: Server;
8
8
  port: number;
9
- socketOptions?: SocketServerOptions;
9
+ token: string;
10
+ socketOptions?: Partial<SocketServerOptions>;
10
11
  }
11
12
  export declare class Socket {
12
13
  protected options: SocketOptions;
@@ -6,7 +6,8 @@ interface SocketOptions {
6
6
  sdk: SDK.RsdoctorBuilderSDKInstance;
7
7
  server: Server;
8
8
  port: number;
9
- socketOptions?: SocketServerOptions;
9
+ token: string;
10
+ socketOptions?: Partial<SocketServerOptions>;
10
11
  }
11
12
  export declare class Socket {
12
13
  protected options: SocketOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsdoctor/sdk",
3
- "version": "1.5.14",
3
+ "version": "1.5.16",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/web-infra-dev/rsdoctor",
@@ -32,10 +32,10 @@
32
32
  "safer-buffer": "2.1.2",
33
33
  "socket.io": "4.8.1",
34
34
  "tapable": "2.3.3",
35
- "@rsdoctor/client": "1.5.14",
36
- "@rsdoctor/graph": "1.5.14",
37
- "@rsdoctor/types": "1.5.14",
38
- "@rsdoctor/utils": "1.5.14"
35
+ "@rsdoctor/graph": "1.5.16",
36
+ "@rsdoctor/types": "1.5.16",
37
+ "@rsdoctor/client": "1.5.16",
38
+ "@rsdoctor/utils": "1.5.16"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/body-parser": "1.19.6",