@rsdoctor/sdk 1.5.15 → 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
@@ -5675,7 +5675,9 @@ var __webpack_modules__ = {
5675
5675
  return enc && (headers['Content-Encoding'] = enc), isEtag && (headers.ETag = `W/"${stats.size}-${stats.mtime.getTime()}"`), headers;
5676
5676
  }
5677
5677
  let common_namespaceObject = require("@rsdoctor/utils/common"), external_assert_namespaceObject = require("assert");
5678
- var external_assert_default = __webpack_require__.n(external_assert_namespaceObject), body_parser = __webpack_require__("../../node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js"), body_parser_default = __webpack_require__.n(body_parser), external_stream_ = __webpack_require__("stream");
5678
+ var external_assert_default = __webpack_require__.n(external_assert_namespaceObject), body_parser = __webpack_require__("../../node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js"), body_parser_default = __webpack_require__.n(body_parser);
5679
+ let cors_index_js_namespaceObject = require("../compiled/cors/index.js");
5680
+ var cors_index_js_default = __webpack_require__.n(cors_index_js_namespaceObject), external_stream_ = __webpack_require__("stream");
5679
5681
  let external_socket_io_namespaceObject = require("socket.io");
5680
5682
  var external_util_ = __webpack_require__("util");
5681
5683
  class SocketAPILoader {
@@ -5693,6 +5695,19 @@ var __webpack_modules__ = {
5693
5695
  return this.dataLoader.loadAPI;
5694
5696
  }
5695
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
+ }
5696
5711
  class Socket {
5697
5712
  constructor(options){
5698
5713
  this.options = options, this.map = new Map(), this.loader = new SocketAPILoader({
@@ -5700,11 +5715,13 @@ var __webpack_modules__ = {
5700
5715
  });
5701
5716
  }
5702
5717
  bootstrap() {
5718
+ let { socketOptions } = this.options;
5703
5719
  this.io = new external_socket_io_namespaceObject.Server(this.options.server, {
5704
- cors: {
5705
- origin: '*'
5706
- },
5707
- ...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
+ }
5708
5725
  }), this.io.on('connection', (socket)=>{
5709
5726
  this.setupSocket(socket);
5710
5727
  });
@@ -6270,15 +6287,10 @@ var __webpack_modules__ = {
6270
6287
  return logger_namespaceObject.logger.error('Failed to open Rsdoctor URL.'), logger_namespaceObject.logger.error(err), !1;
6271
6288
  }
6272
6289
  }
6273
- let server_require = (0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__), LOCAL_HOSTNAMES = new Set([
6274
- 'localhost',
6275
- '127.0.0.1',
6276
- '[::1]',
6277
- '::1'
6278
- ]);
6290
+ let external_crypto_namespaceObject = require("crypto"), server_require = (0, external_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
6279
6291
  class RsdoctorServer {
6280
6292
  constructor(sdk, port = build_namespaceObject.Server.defaultPort, config){
6281
- 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)=>{
6282
6294
  let { app } = this;
6283
6295
  return app.use(route, this.wrapNextHandleFunction('GET', cb)), app;
6284
6296
  }, this.post = (route, cb)=>{
@@ -6294,7 +6306,7 @@ var __webpack_modules__ = {
6294
6306
  sdk,
6295
6307
  server: this,
6296
6308
  apis: Object.values(apis_namespaceObject)
6297
- }), 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;
6298
6310
  }
6299
6311
  get app() {
6300
6312
  return this._server.app;
@@ -6308,34 +6320,13 @@ var __webpack_modules__ = {
6308
6320
  get socketUrl() {
6309
6321
  return {
6310
6322
  port: this.port,
6311
- socketUrl: `ws://localhost:${this.port}`
6323
+ socketUrl: `ws://localhost:${this.port}?token=${this._socketToken}`,
6324
+ token: this._socketToken
6312
6325
  };
6313
6326
  }
6314
6327
  get innerClientPath() {
6315
6328
  return this._innerClientPath;
6316
6329
  }
6317
- isLocalOrigin(origin) {
6318
- try {
6319
- let url = new URL(origin);
6320
- return ('http:' === url.protocol || 'https:' === url.protocol) && LOCAL_HOSTNAMES.has(url.hostname);
6321
- } catch {
6322
- return !1;
6323
- }
6324
- }
6325
- setCorsHeaders(req, res) {
6326
- let origin = req.headers.origin;
6327
- return 'string' == typeof origin && !!this.isLocalOrigin(origin) && (res.setHeader('Access-Control-Allow-Origin', origin), res.setHeader('Vary', 'Origin'), res.setHeader('Access-Control-Allow-Headers', 'Content-Type'), res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), !0);
6328
- }
6329
- createSecurityMiddleware() {
6330
- return (req, res, next)=>{
6331
- let isCorsAllowed = this.setCorsHeaders(req, res);
6332
- if (req.method?.toUpperCase() === 'OPTIONS') {
6333
- res.statusCode = isCorsAllowed ? 204 : 403, res.end();
6334
- return;
6335
- }
6336
- next();
6337
- };
6338
- }
6339
6330
  async createInnerServer() {
6340
6331
  let lastError, expectedPort = this.port;
6341
6332
  for(let retry = 0; retry < 10; retry++){
@@ -6352,16 +6343,53 @@ var __webpack_modules__ = {
6352
6343
  }
6353
6344
  throw lastError;
6354
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
+ }
6355
6354
  async bootstrap() {
6356
6355
  if (!this.disposed) return;
6357
- let { port, server } = await this.createInnerServer();
6356
+ let { port, server } = await this.createInnerServer(), corsOptions = this.resolveCorsOptions();
6358
6357
  this.port = port, this._server = server, this._socket = new Socket({
6359
6358
  sdk: this.sdk,
6360
6359
  server: this._server.server,
6361
- port: this.port
6362
- }), 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(this.createSecurityMiddleware()), 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({
6363
6391
  limit: '500mb'
6364
- }));
6392
+ })), await this._router.setup();
6365
6393
  let clientHtmlPath = this._innerClientPath ? this._innerClientPath : server_require.resolve('@rsdoctor/client'), clientDistPath = external_path_default().resolve(clientHtmlPath, '..');
6366
6394
  this.app.use(function(dir, opts = {}) {
6367
6395
  dir = (0, external_node_path_.resolve)(dir || '.');
@@ -6454,7 +6482,7 @@ var __webpack_modules__ = {
6454
6482
  } catch (err) {
6455
6483
  res.writableEnded || (res.statusCode = 500, res.end(err.message));
6456
6484
  }
6457
- }), 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)=>{
6458
6486
  console.error('Unhandled promise rejection:', reason), this.dispose(1);
6459
6487
  }), process.once('uncaughtException', (err, origin)=>{
6460
6488
  console.error('Uncaught exception:', err), origin && console.error('Exception origin:', origin), this.dispose(1);
@@ -6662,9 +6690,12 @@ var __webpack_modules__ = {
6662
6690
  constructor(options){
6663
6691
  super(options), this._summary = {
6664
6692
  costs: []
6665
- }, 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, {
6666
6696
  innerClientPath: options.config?.innerClientPath || '',
6667
- printServerUrl: options.config?.printLog?.serverUrls
6697
+ printServerUrl: options.config?.printLog?.serverUrls,
6698
+ cors: serverConfig?.cors
6668
6699
  }), this.type = common_namespaceObject.Lodash.isNumber(options.type) ? options.type : types_namespaceObject.SDK.ToDataType.Normal, this.extraConfig = options.config, this.root = findRoot() ?? '';
6669
6700
  }
6670
6701
  async bootstrap() {
@@ -6960,8 +6991,8 @@ var __webpack_modules__ = {
6960
6991
  }
6961
6992
  }
6962
6993
  class RsdoctorSlaveServer extends RsdoctorServer {
6963
- constructor(sdk, port = build_namespaceObject.Server.defaultPort){
6964
- super(sdk, port), this.sdk = sdk;
6994
+ constructor(sdk, port = build_namespaceObject.Server.defaultPort, config){
6995
+ super(sdk, port, config), this.sdk = sdk;
6965
6996
  }
6966
6997
  async openClientPage(...args) {
6967
6998
  return this.sdk.isMaster ? super.openClientPage(...args) : Promise.resolve();
@@ -6972,10 +7003,13 @@ var __webpack_modules__ = {
6972
7003
  constructor({ name, stage, controller, extraConfig, type }){
6973
7004
  super({
6974
7005
  name,
6975
- root: controller.root
7006
+ root: controller.root,
7007
+ config: extraConfig
6976
7008
  });
6977
- const lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : this.server.port;
6978
- 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();
6979
7013
  }
6980
7014
  clearSwitch() {
6981
7015
  this.uploadPieces = new Promise((resolve)=>{
package/dist/index.js CHANGED
@@ -14,12 +14,15 @@ import node_path, { join, normalize, resolve as external_node_path_resolve, sep
14
14
  import fs, { readdirSync, statSync } from "fs";
15
15
  import { Algorithm, Bundle, Data, GlobalConfig, Lodash, decycle } from "@rsdoctor/utils/common";
16
16
  import assert from "assert";
17
+ import cors from "../compiled/cors/index.js";
17
18
  import { PassThrough } from "stream";
18
19
  import { Server as external_socket_io_Server } from "socket.io";
19
20
  import { isDeepStrictEqual } from "util";
21
+ import { isIP } from "node:net";
20
22
  import os from "os";
21
23
  import { exec } from "node:child_process";
22
24
  import { promisify } from "node:util";
25
+ import { randomBytes } from "crypto";
23
26
  import { createHash, randomUUID } from "node:crypto";
24
27
  import node_process from "node:process";
25
28
  import { AsyncSeriesHook } from "tapable";
@@ -5713,6 +5716,19 @@ class SocketAPILoader {
5713
5716
  return this.dataLoader.loadAPI;
5714
5717
  }
5715
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
+ }
5716
5732
  class Socket {
5717
5733
  constructor(options){
5718
5734
  this.options = options, this.map = new Map(), this.loader = new SocketAPILoader({
@@ -5720,11 +5736,13 @@ class Socket {
5720
5736
  });
5721
5737
  }
5722
5738
  bootstrap() {
5739
+ let { socketOptions } = this.options;
5723
5740
  this.io = new external_socket_io_Server(this.options.server, {
5724
- cors: {
5725
- origin: '*'
5726
- },
5727
- ...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
+ }
5728
5746
  }), this.io.on('connection', (socket)=>{
5729
5747
  this.setupSocket(socket);
5730
5748
  });
@@ -6291,15 +6309,10 @@ async function openBrowser(url, needEncodeURI = !0) {
6291
6309
  }
6292
6310
  let body_parser = __webpack_require__("../../node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js");
6293
6311
  var body_parser_default = __webpack_require__.n(body_parser);
6294
- let server_require = createRequire(import.meta.url), LOCAL_HOSTNAMES = new Set([
6295
- 'localhost',
6296
- '127.0.0.1',
6297
- '[::1]',
6298
- '::1'
6299
- ]);
6312
+ let server_require = createRequire(import.meta.url);
6300
6313
  class RsdoctorServer {
6301
6314
  constructor(sdk, port = Server.defaultPort, config){
6302
- 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)=>{
6303
6316
  let { app } = this;
6304
6317
  return app.use(route, this.wrapNextHandleFunction('GET', cb)), app;
6305
6318
  }, this.post = (route, cb)=>{
@@ -6315,7 +6328,7 @@ class RsdoctorServer {
6315
6328
  sdk,
6316
6329
  server: this,
6317
6330
  apis: Object.values(apis_namespaceObject)
6318
- }), 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;
6319
6332
  }
6320
6333
  get app() {
6321
6334
  return this._server.app;
@@ -6329,34 +6342,13 @@ class RsdoctorServer {
6329
6342
  get socketUrl() {
6330
6343
  return {
6331
6344
  port: this.port,
6332
- socketUrl: `ws://localhost:${this.port}`
6345
+ socketUrl: `ws://localhost:${this.port}?token=${this._socketToken}`,
6346
+ token: this._socketToken
6333
6347
  };
6334
6348
  }
6335
6349
  get innerClientPath() {
6336
6350
  return this._innerClientPath;
6337
6351
  }
6338
- isLocalOrigin(origin) {
6339
- try {
6340
- let url = new URL(origin);
6341
- return ('http:' === url.protocol || 'https:' === url.protocol) && LOCAL_HOSTNAMES.has(url.hostname);
6342
- } catch {
6343
- return !1;
6344
- }
6345
- }
6346
- setCorsHeaders(req, res) {
6347
- let origin = req.headers.origin;
6348
- return 'string' == typeof origin && !!this.isLocalOrigin(origin) && (res.setHeader('Access-Control-Allow-Origin', origin), res.setHeader('Vary', 'Origin'), res.setHeader('Access-Control-Allow-Headers', 'Content-Type'), res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), !0);
6349
- }
6350
- createSecurityMiddleware() {
6351
- return (req, res, next)=>{
6352
- let isCorsAllowed = this.setCorsHeaders(req, res);
6353
- if (req.method?.toUpperCase() === 'OPTIONS') {
6354
- res.statusCode = isCorsAllowed ? 204 : 403, res.end();
6355
- return;
6356
- }
6357
- next();
6358
- };
6359
- }
6360
6352
  async createInnerServer() {
6361
6353
  let lastError, expectedPort = this.port;
6362
6354
  for(let retry = 0; retry < 10; retry++){
@@ -6373,16 +6365,53 @@ class RsdoctorServer {
6373
6365
  }
6374
6366
  throw lastError;
6375
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
+ }
6376
6376
  async bootstrap() {
6377
6377
  if (!this.disposed) return;
6378
- let { port, server } = await this.createInnerServer();
6378
+ let { port, server } = await this.createInnerServer(), corsOptions = this.resolveCorsOptions();
6379
6379
  this.port = port, this._server = server, this._socket = new Socket({
6380
6380
  sdk: this.sdk,
6381
6381
  server: this._server.server,
6382
- port: this.port
6383
- }), 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(this.createSecurityMiddleware()), 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({
6384
6413
  limit: '500mb'
6385
- }));
6414
+ })), await this._router.setup();
6386
6415
  let clientHtmlPath = this._innerClientPath ? this._innerClientPath : server_require.resolve('@rsdoctor/client'), clientDistPath = path_0.resolve(clientHtmlPath, '..');
6387
6416
  this.app.use(function(dir, opts = {}) {
6388
6417
  dir = external_node_path_resolve(dir || '.');
@@ -6474,7 +6503,7 @@ class RsdoctorServer {
6474
6503
  } catch (err) {
6475
6504
  res.writableEnded || (res.statusCode = 500, res.end(err.message));
6476
6505
  }
6477
- }), 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)=>{
6478
6507
  console.error('Unhandled promise rejection:', reason), this.dispose(1);
6479
6508
  }), process.once('uncaughtException', (err, origin)=>{
6480
6509
  console.error('Uncaught exception:', err), origin && console.error('Exception origin:', origin), this.dispose(1);
@@ -6679,9 +6708,12 @@ class RsdoctorSDK extends SDKCore {
6679
6708
  constructor(options){
6680
6709
  super(options), this._summary = {
6681
6710
  costs: []
6682
- }, 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, {
6683
6714
  innerClientPath: options.config?.innerClientPath || '',
6684
- printServerUrl: options.config?.printLog?.serverUrls
6715
+ printServerUrl: options.config?.printLog?.serverUrls,
6716
+ cors: serverConfig?.cors
6685
6717
  }), this.type = Lodash.isNumber(options.type) ? options.type : SDK.ToDataType.Normal, this.extraConfig = options.config, this.root = findRoot() ?? '';
6686
6718
  }
6687
6719
  async bootstrap() {
@@ -6977,8 +7009,8 @@ class RsdoctorSDK extends SDKCore {
6977
7009
  }
6978
7010
  }
6979
7011
  class RsdoctorSlaveServer extends RsdoctorServer {
6980
- constructor(sdk, port = Server.defaultPort){
6981
- super(sdk, port), this.sdk = sdk;
7012
+ constructor(sdk, port = Server.defaultPort, config){
7013
+ super(sdk, port, config), this.sdk = sdk;
6982
7014
  }
6983
7015
  async openClientPage(...args) {
6984
7016
  return this.sdk.isMaster ? super.openClientPage(...args) : Promise.resolve();
@@ -6989,10 +7021,13 @@ class RsdoctorPrimarySDK extends RsdoctorSDK {
6989
7021
  constructor({ name, stage, controller, extraConfig, type }){
6990
7022
  super({
6991
7023
  name,
6992
- root: controller.root
7024
+ root: controller.root,
7025
+ config: extraConfig
6993
7026
  });
6994
- let lastSdk = controller.getLastSdk(), port = lastSdk ? lastSdk.server.port + 1 : this.server.port;
6995
- 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();
6996
7031
  }
6997
7032
  clearSwitch() {
6998
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,19 +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;
25
- private isLocalOrigin;
26
- private setCorsHeaders;
27
- private createSecurityMiddleware;
28
30
  private createInnerServer;
31
+ private resolveCorsOptions;
29
32
  bootstrap(): Promise<void>;
30
33
  protected wrapNextHandleFunction(method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): Thirdparty.connect.NextHandleFunction;
31
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,19 +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;
25
- private isLocalOrigin;
26
- private setCorsHeaders;
27
- private createSecurityMiddleware;
28
30
  private createInnerServer;
31
+ private resolveCorsOptions;
29
32
  bootstrap(): Promise<void>;
30
33
  protected wrapNextHandleFunction(method: 'GET' | 'POST', cb: (...args: Parameters<Thirdparty.connect.NextHandleFunction>) => Common.PlainObject | string): Thirdparty.connect.NextHandleFunction;
31
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.15",
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.15",
36
- "@rsdoctor/types": "1.5.15",
37
- "@rsdoctor/utils": "1.5.15",
38
- "@rsdoctor/graph": "1.5.15"
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",