@nocobase/server 2.3.0-beta.2 → 2.3.0-beta.21

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.
@@ -34,7 +34,7 @@ const availableActions = {
34
34
  displayName: '{{t("Add new")}}',
35
35
  type: "new-data",
36
36
  onNewRecord: true,
37
- aliases: ["create", "firstOrCreate", "updateOrCreate"],
37
+ aliases: ["create"],
38
38
  allowConfigureFields: true
39
39
  },
40
40
  // import: {
@@ -53,6 +53,7 @@ export declare class AppSupervisor extends EventEmitter implements AsyncEmitter
53
53
  private appSsoIssuer?;
54
54
  appOptionsFactory: AppOptionsFactory;
55
55
  private environmentHeartbeatInterval;
56
+ private environmentHeartbeatTimeout;
56
57
  private environmentHeartbeatTimer;
57
58
  private constructor();
58
59
  private resolveDiscoveryAdapterName;
@@ -163,11 +164,13 @@ export declare class AppSupervisor extends EventEmitter implements AsyncEmitter
163
164
  proxyWeb(appName: string, req: IncomingMessage, res: ServerResponse): Promise<boolean>;
164
165
  proxyWs(req: IncomingMessage, socket: any, head: Buffer): Promise<boolean>;
165
166
  registerEnvironment(mainApp: Application): Promise<void>;
167
+ private getEnvironmentInfo;
166
168
  unregisterEnvironment(): Promise<void>;
167
169
  private normalizeEnvInfo;
168
170
  listEnvironments(): Promise<EnvironmentInfo[]>;
169
171
  getEnvironment(environmentName: string): Promise<EnvironmentInfo>;
170
- heartbeatEnvironment(): Promise<void>;
172
+ heartbeatEnvironment(mainApp: Application): Promise<void>;
173
+ private stopEnvironmentHeartbeat;
171
174
  dispatchCommand(command: ProcessCommand): Promise<void>;
172
175
  registerCommandHandler(mainApp: Application): void;
173
176
  sendSyncMessage(mainApp: Application, message: {
@@ -74,6 +74,7 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
74
74
  appSsoIssuer;
75
75
  appOptionsFactory = import_app_options_factory.appOptionsFactory;
76
76
  environmentHeartbeatInterval = 2 * 60 * 1e3;
77
+ environmentHeartbeatTimeout = 5 * 60 * 1e3;
77
78
  environmentHeartbeatTimer = null;
78
79
  constructor() {
79
80
  super();
@@ -282,13 +283,11 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
282
283
  }
283
284
  async reset() {
284
285
  var _a, _b, _c, _d;
286
+ this.stopEnvironmentHeartbeat();
285
287
  await this.processAdapter.removeAllApps();
286
288
  await ((_b = (_a = this.discoveryAdapter).dispose) == null ? void 0 : _b.call(_a));
287
289
  await ((_d = (_c = this.commandAdapter) == null ? void 0 : _c.dispose) == null ? void 0 : _d.call(_c));
288
290
  this.appManifests.clear();
289
- if (this.environmentHeartbeatTimer) {
290
- this.environmentHeartbeatTimer = null;
291
- }
292
291
  this.removeAllListeners();
293
292
  this.logger.close();
294
293
  }
@@ -389,6 +388,9 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
389
388
  if (!appOptions) {
390
389
  return;
391
390
  }
391
+ if (appModel.environments && !appModel.environments.includes(this.environmentName)) {
392
+ return;
393
+ }
392
394
  const newApp = this.registerApp({ appModel, mainApp: app2 });
393
395
  newApp.runCommand("start", "--quickstart");
394
396
  }
@@ -601,24 +603,25 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
601
603
  if (!this.environmentName || typeof this.discoveryAdapter.registerEnvironment !== "function") {
602
604
  return;
603
605
  }
604
- const registered = await this.discoveryAdapter.registerEnvironment({
606
+ const registered = await this.discoveryAdapter.registerEnvironment(this.getEnvironmentInfo(mainApp));
607
+ if (registered) {
608
+ this.heartbeatEnvironment(mainApp);
609
+ }
610
+ }
611
+ getEnvironmentInfo(mainApp) {
612
+ return {
605
613
  name: this.environmentName,
606
614
  url: this.environmentUrl || "",
607
615
  proxyUrl: this.environmentProxyUrl || this.environmentUrl || "",
608
616
  appVersion: mainApp.getPackageVersion(),
609
617
  lastHeartbeatAt: Date.now()
610
- });
611
- if (registered) {
612
- this.heartbeatEnvironment();
613
- }
618
+ };
614
619
  }
615
620
  async unregisterEnvironment() {
621
+ this.stopEnvironmentHeartbeat();
616
622
  if (this.environmentName && typeof this.discoveryAdapter.unregisterEnvironment === "function") {
617
623
  await this.discoveryAdapter.unregisterEnvironment();
618
624
  }
619
- if (this.environmentHeartbeatTimer) {
620
- this.environmentHeartbeatTimer = null;
621
- }
622
625
  }
623
626
  normalizeEnvInfo(environment) {
624
627
  if (typeof environment.available === "boolean") {
@@ -631,7 +634,7 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
631
634
  available: false
632
635
  };
633
636
  }
634
- const available = Date.now() - lastHeartbeatAt <= this.environmentHeartbeatInterval;
637
+ const available = Date.now() - lastHeartbeatAt <= this.environmentHeartbeatTimeout;
635
638
  return {
636
639
  ...environment,
637
640
  available
@@ -654,17 +657,26 @@ const _AppSupervisor = class _AppSupervisor extends import_events.EventEmitter {
654
657
  }
655
658
  return this.normalizeEnvInfo(environment);
656
659
  }
657
- async heartbeatEnvironment() {
660
+ async heartbeatEnvironment(mainApp) {
658
661
  if (typeof this.discoveryAdapter.heartbeatEnvironment !== "function") {
659
662
  return;
660
663
  }
661
664
  if (this.environmentHeartbeatTimer) {
662
665
  return;
663
666
  }
664
- this.environmentHeartbeatTimer = setInterval(
665
- () => this.discoveryAdapter.heartbeatEnvironment(),
666
- this.environmentHeartbeatInterval
667
- );
667
+ this.environmentHeartbeatTimer = setInterval(async () => {
668
+ try {
669
+ await this.discoveryAdapter.heartbeatEnvironment(this.getEnvironmentInfo(mainApp));
670
+ } catch (error) {
671
+ this.logger.error(error instanceof Error ? error.message : String(error), { method: "heartbeatEnvironment" });
672
+ }
673
+ }, this.environmentHeartbeatInterval);
674
+ }
675
+ stopEnvironmentHeartbeat() {
676
+ if (this.environmentHeartbeatTimer) {
677
+ clearInterval(this.environmentHeartbeatTimer);
678
+ this.environmentHeartbeatTimer = null;
679
+ }
668
680
  }
669
681
  async dispatchCommand(command) {
670
682
  var _a;
@@ -50,7 +50,10 @@ const _MainOnlyAdapter = class _MainOnlyAdapter {
50
50
  return this.apps[appName];
51
51
  }
52
52
  async bootstrapApp(appName) {
53
- if (appName !== "main" || !this.apps[appName]) {
53
+ if (appName !== "main") {
54
+ return;
55
+ }
56
+ if (!this.apps[appName]) {
54
57
  this.setAppStatus(appName, "not_found");
55
58
  return;
56
59
  }
@@ -138,13 +141,16 @@ const _MainOnlyAdapter = class _MainOnlyAdapter {
138
141
  return this.removeApp("main");
139
142
  }
140
143
  setAppStatus(appName, status, options = {}) {
141
- if (this.status === status) {
144
+ if (appName !== "main" || this.status === status) {
142
145
  return;
143
146
  }
144
147
  this.status = status;
145
148
  this.supervisor.emit("appStatusChanged", { appName, status, options });
146
149
  }
147
150
  getAppStatus(appName, defaultStatus) {
151
+ if (appName !== "main") {
152
+ return "not_found";
153
+ }
148
154
  return this.status ?? defaultStatus ?? null;
149
155
  }
150
156
  hasAppError(appName) {
@@ -132,7 +132,7 @@ export interface AppDiscoveryAdapter {
132
132
  unregisterEnvironment?(): Promise<void>;
133
133
  listEnvironments?(): Promise<EnvironmentInfo[]>;
134
134
  getEnvironment?(environmentName: string): Promise<EnvironmentInfo | null>;
135
- heartbeatEnvironment?(): Promise<void>;
135
+ heartbeatEnvironment?(environment: EnvironmentInfo): Promise<void>;
136
136
  getBootstrapLock?(appName: string): Promise<BootstrapLock | null> | BootstrapLock | null;
137
137
  proxyWeb?(appName: string, req: IncomingMessage, res: ServerResponse): Promise<boolean>;
138
138
  proxyWs?(req: IncomingMessage, socket: any, head: Buffer): Promise<boolean>;
@@ -201,6 +201,14 @@ export declare class Application<StateT = DefaultState, ContextT = DefaultContex
201
201
  static addCommand(callback: (app: Application) => void): void;
202
202
  private _sqlLogger;
203
203
  get instanceId(): number;
204
+ /**
205
+ * Adopt a worker id handed out at runtime, after the allocator loses its lease and acquires a different one. Ids may
206
+ * only be minted under a worker id this process currently holds, so the generator is rebuilt to match.
207
+ *
208
+ * Returning early on an unchanged id is required rather than an optimisation: rebuilding restarts the sequence at 0,
209
+ * so doing it for the same worker id inside one second would re-issue ids this process has already handed out.
210
+ */
211
+ setInstanceId(instanceId: number): void;
204
212
  get sqlLogger(): Logger;
205
213
  protected _logger: SystemLogger;
206
214
  get logger(): SystemLogger;
@@ -154,6 +154,21 @@ const _Application = class _Application extends import_koa.default {
154
154
  get instanceId() {
155
155
  return this._instanceId;
156
156
  }
157
+ /**
158
+ * Adopt a worker id handed out at runtime, after the allocator loses its lease and acquires a different one. Ids may
159
+ * only be minted under a worker id this process currently holds, so the generator is rebuilt to match.
160
+ *
161
+ * Returning early on an unchanged id is required rather than an optimisation: rebuilding restarts the sequence at 0,
162
+ * so doing it for the same worker id inside one second would re-issue ids this process has already handed out.
163
+ */
164
+ setInstanceId(instanceId) {
165
+ if (this._instanceId === instanceId) {
166
+ return;
167
+ }
168
+ this._instanceId = instanceId;
169
+ this.snowflakeIdGenerator = new import_snowflake_id.Snowflake({ workerId: instanceId });
170
+ this.log.info(`adopt worker id: ${instanceId}`, { method: "setInstanceId" });
171
+ }
157
172
  get sqlLogger() {
158
173
  return this._sqlLogger;
159
174
  }
@@ -383,6 +398,7 @@ const _Application = class _Application extends import_koa.default {
383
398
  return this.cli._findCommand(name);
384
399
  }
385
400
  async disposeServices() {
401
+ await this.workerIdAllocator.release();
386
402
  if (this.redisConnectionManager) {
387
403
  await this.redisConnectionManager.close();
388
404
  }
@@ -395,7 +411,6 @@ const _Application = class _Application extends import_koa.default {
395
411
  if (this.telemetry.started) {
396
412
  await this.telemetry.shutdown();
397
413
  }
398
- await this.workerIdAllocator.release();
399
414
  }
400
415
  /**
401
416
  * @internal
@@ -452,7 +467,7 @@ const _Application = class _Application extends import_koa.default {
452
467
  if ((options == null ? void 0 : options.hooks) !== false) {
453
468
  await this.emitAsync("beforeLoad", this, options);
454
469
  }
455
- if (!this._instanceId) {
470
+ if (this._instanceId == null) {
456
471
  this._instanceId = await this.workerIdAllocator.getWorkerId();
457
472
  this.log.info(`allocate worker id: ${this._instanceId}`, { method: "load" });
458
473
  }
@@ -881,6 +896,7 @@ const _Application = class _Application extends import_koa.default {
881
896
  init() {
882
897
  const options = this.options;
883
898
  this._instanceId = options.instanceId;
899
+ this.snowflakeIdGenerator = void 0;
884
900
  this.initLogger(options.logger);
885
901
  this.reInitEvents();
886
902
  this.middleware = new import_utils.Toposort();
@@ -8,10 +8,14 @@
8
8
  */
9
9
  export declare class Environment {
10
10
  private vars;
11
- setVariable(key: string, value: string): void;
11
+ private secretKeys;
12
+ setVariable(key: string, value: string, options?: {
13
+ isSecret?: boolean;
14
+ }): void;
12
15
  removeVariable(key: string): void;
13
16
  getVariablesAndSecrets(): {};
14
17
  getVariables(): {};
18
+ getNonSecretVariables(): {};
15
19
  renderJsonTemplate(template: any, options?: {
16
20
  omit?: string[];
17
21
  }): any;
@@ -44,11 +44,18 @@ var import_utils = require("@nocobase/utils");
44
44
  var import_lodash = __toESM(require("lodash"));
45
45
  const _Environment = class _Environment {
46
46
  vars = {};
47
- setVariable(key, value) {
47
+ secretKeys = /* @__PURE__ */ new Set();
48
+ setVariable(key, value, options) {
48
49
  this.vars[key] = value;
50
+ if ((options == null ? void 0 : options.isSecret) === true) {
51
+ this.secretKeys.add(key);
52
+ } else if ((options == null ? void 0 : options.isSecret) === false) {
53
+ this.secretKeys.delete(key);
54
+ }
49
55
  }
50
56
  removeVariable(key) {
51
57
  delete this.vars[key];
58
+ this.secretKeys.delete(key);
52
59
  }
53
60
  getVariablesAndSecrets() {
54
61
  return this.vars;
@@ -56,6 +63,15 @@ const _Environment = class _Environment {
56
63
  getVariables() {
57
64
  return this.vars;
58
65
  }
66
+ getNonSecretVariables() {
67
+ const result = {};
68
+ for (const key of Object.keys(this.vars)) {
69
+ if (!this.secretKeys.has(key)) {
70
+ result[key] = this.vars[key];
71
+ }
72
+ }
73
+ return result;
74
+ }
59
75
  renderJsonTemplate(template, options) {
60
76
  if (options == null ? void 0 : options.omit) {
61
77
  const omitTemplate = import_lodash.default.omit(template, options.omit);
@@ -6,6 +6,11 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
+ /** Raised when a request resolves to an app name that could never name a real application. */
10
+ export declare class InvalidAppNameError extends Error {
11
+ readonly appName: unknown;
12
+ constructor(appName: unknown);
13
+ }
9
14
  interface AppError {
10
15
  status: number;
11
16
  message: any;
@@ -37,6 +37,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
  var errors_exports = {};
39
39
  __export(errors_exports, {
40
+ InvalidAppNameError: () => InvalidAppNameError,
40
41
  applyErrorWithArgs: () => applyErrorWithArgs,
41
42
  errors: () => errors,
42
43
  getErrorWithCode: () => getErrorWithCode
@@ -44,6 +45,15 @@ __export(errors_exports, {
44
45
  module.exports = __toCommonJS(errors_exports);
45
46
  var import_app_supervisor = require("../app-supervisor");
46
47
  var import_lodash = __toESM(require("lodash"));
48
+ const _InvalidAppNameError = class _InvalidAppNameError extends Error {
49
+ constructor(appName) {
50
+ super("invalid application name");
51
+ this.appName = appName;
52
+ this.name = "InvalidAppNameError";
53
+ }
54
+ };
55
+ __name(_InvalidAppNameError, "InvalidAppNameError");
56
+ let InvalidAppNameError = _InvalidAppNameError;
47
57
  function getMaintaining(app) {
48
58
  var _a;
49
59
  return (_a = app == null ? void 0 : app.getMaintaining) == null ? void 0 : _a.call(app);
@@ -54,6 +64,16 @@ function getAppName(app) {
54
64
  }
55
65
  __name(getAppName, "getAppName");
56
66
  const errors = {
67
+ INVALID_APP_NAME: {
68
+ status: 400,
69
+ message: "invalid application name",
70
+ maintaining: false
71
+ },
72
+ APP_ENVIRONMENT_UNAVAILABLE: {
73
+ status: 503,
74
+ message: /* @__PURE__ */ __name(({ appName }) => `deployment environment for application ${appName} is unavailable`, "message"),
75
+ maintaining: true
76
+ },
57
77
  APP_NOT_FOUND: {
58
78
  status: 404,
59
79
  message: /* @__PURE__ */ __name(({ appName }) => `application ${appName} not found`, "message"),
@@ -186,6 +206,7 @@ function applyErrorWithArgs(error, options) {
186
206
  __name(applyErrorWithArgs, "applyErrorWithArgs");
187
207
  // Annotate the CommonJS export names for ESM import in node:
188
208
  0 && (module.exports = {
209
+ InvalidAppNameError,
189
210
  applyErrorWithArgs,
190
211
  errors,
191
212
  getErrorWithCode
@@ -90,6 +90,7 @@ export declare class Gateway extends EventEmitter {
90
90
  requestHandler(req: IncomingMessage, res: ServerResponse): Promise<void>;
91
91
  getAppSelectorMiddlewares(): Toposort<AppSelectorMiddleware>;
92
92
  getRequestHandleAppName(req: IncomingMessage | IncomingRequest): Promise<string>;
93
+ private handleUpgrade;
93
94
  getCallback(): any;
94
95
  watch(): Promise<void>;
95
96
  run(options: RunOptions): Promise<void>;
@@ -66,13 +66,21 @@ var import_plugin_manager = require("../plugin-manager");
66
66
  var import_errors = require("./errors");
67
67
  var import_ipc_socket_client = require("./ipc-socket-client");
68
68
  var import_ipc_socket_server = require("./ipc-socket-server");
69
- var import_static_file_security = require("./static-file-security");
70
69
  var import_utils3 = require("./utils");
71
70
  var import_ws_server = require("./ws-server");
72
71
  var import_node_worker_threads = require("node:worker_threads");
73
72
  var import_node_process = __toESM(require("node:process"));
74
73
  var import_utils4 = require("./utils");
75
74
  const compress = (0, import_node_util.promisify)((0, import_compression.default)());
75
+ const APP_NAME_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
76
+ const MAX_APP_NAME_LENGTH = 255;
77
+ function isValidAppName(name) {
78
+ if (typeof name !== "string" || name.length > MAX_APP_NAME_LENGTH || !APP_NAME_PATTERN.test(name)) {
79
+ return false;
80
+ }
81
+ return !(name in Object.prototype);
82
+ }
83
+ __name(isValidAppName, "isValidAppName");
76
84
  function normalizeBasePath(path = "") {
77
85
  const normalized = path.replace(/\/+/g, "/").replace(/\/$/, "");
78
86
  return normalized || "/";
@@ -122,7 +130,17 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
122
130
  const internalUrl = req.url;
123
131
  req.url = this.getOriginalRequestUrl(req);
124
132
  try {
125
- return await supervisor.proxyWeb(appName, req, res);
133
+ const proxied = await supervisor.proxyWeb(appName, req, res);
134
+ const adapter = supervisor.getDiscoveryAdapter();
135
+ if (!proxied && import_node_process.default.env.APP_MODE === "supervisor" && typeof adapter.proxyWeb === "function") {
136
+ let code = "APP_ENVIRONMENT_UNAVAILABLE";
137
+ if (typeof adapter.getAppModel === "function" && !await supervisor.getAppModel(appName)) {
138
+ code = "APP_NOT_FOUND";
139
+ }
140
+ this.responseErrorWithCode(code, res, { appName });
141
+ return true;
142
+ }
143
+ return proxied;
126
144
  } finally {
127
145
  req.url = internalUrl;
128
146
  }
@@ -252,6 +270,9 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
252
270
  this.emit("appSelectorChanged");
253
271
  }
254
272
  getLogger(appName, res) {
273
+ if (!isValidAppName(appName)) {
274
+ throw new Error("Invalid app name");
275
+ }
255
276
  const reqId = (0, import_crypto.randomUUID)();
256
277
  res.setHeader("X-Request-Id", reqId);
257
278
  let logger = this.loggers.get(appName);
@@ -275,7 +296,9 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
275
296
  res.end(JSON.stringify({ error }));
276
297
  }
277
298
  responseErrorWithCode(code, res, options) {
278
- const log = this.getLogger(options.appName, res);
299
+ const appName = options == null ? void 0 : options.appName;
300
+ const loggerName = isValidAppName(appName) && import_app_supervisor.AppSupervisor.getInstance().hasApp(appName) ? appName : "main";
301
+ const log = this.getLogger(loggerName, res);
279
302
  const error = (0, import_errors.applyErrorWithArgs)((0, import_errors.getErrorWithCode)(code), options);
280
303
  log.error(error.message, {
281
304
  method: "responseErrorWithCode",
@@ -378,31 +401,14 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
378
401
  try {
379
402
  handleApp = await this.getRequestHandleAppName(req);
380
403
  } catch (error) {
404
+ if (error instanceof import_errors.InvalidAppNameError) {
405
+ this.responseErrorWithCode("INVALID_APP_NAME", res, {});
406
+ return;
407
+ }
381
408
  this.getLogger("main", res).error("Failed to get handle app name", { error });
382
409
  this.responseErrorWithCode("APP_INITIALIZING", res, { appName: handleApp });
383
410
  return;
384
411
  }
385
- if (pathname.startsWith(APP_PUBLIC_PATH + "storage/uploads/")) {
386
- if (handleApp !== "main") {
387
- const isProxy = await this.proxyRequestToSubApp(supervisor, handleApp, req, res);
388
- if (isProxy) {
389
- return;
390
- }
391
- }
392
- const headers = (0, import_static_file_security.getStorageUploadSecurityHeaders)(`${pathname}${search || ""}`);
393
- req.url = req.url.substring(APP_PUBLIC_PATH.length + "storage".length);
394
- await compress(req, res);
395
- return (0, import_serve_handler.default)(req, res, {
396
- public: (0, import_utils.resolveStorageRoot)(),
397
- directoryListing: false,
398
- headers: [
399
- {
400
- source: "**/*",
401
- headers: Object.entries(headers).map(([key, value]) => ({ key, value }))
402
- }
403
- ]
404
- });
405
- }
406
412
  if (pathname.startsWith(APP_PUBLIC_PATH + "dist/")) {
407
413
  if (handleApp !== "main") {
408
414
  const isProxy = await this.proxyRequestToSubApp(supervisor, handleApp, req, res);
@@ -439,7 +445,8 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
439
445
  });
440
446
  }
441
447
  const isFilesRequest = Boolean(getFileAccessRestPath(pathname, APP_PUBLIC_PATH));
442
- if (!pathname.startsWith(import_node_process.default.env.API_BASE_PATH) && !isFilesRequest) {
448
+ const isLegacyUploadRequest = pathname.startsWith(APP_PUBLIC_PATH + "storage/uploads/");
449
+ if (!pathname.startsWith(import_node_process.default.env.API_BASE_PATH) && !isFilesRequest && !isLegacyUploadRequest) {
443
450
  if (this.isV2Request(pathname)) {
444
451
  if (handleApp !== "main") {
445
452
  const isProxy = await this.proxyRequestToSubApp(supervisor, handleApp, req, res);
@@ -549,8 +556,32 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
549
556
  if (!ctx.resolvedAppName) {
550
557
  ctx.resolvedAppName = "main";
551
558
  }
559
+ if (!isValidAppName(ctx.resolvedAppName)) {
560
+ throw new import_errors.InvalidAppNameError(ctx.resolvedAppName);
561
+ }
552
562
  return ctx.resolvedAppName;
553
563
  }
564
+ async handleUpgrade(request, socket, head) {
565
+ const isProxy = await import_app_supervisor.AppSupervisor.getInstance().proxyWs(request, socket, head);
566
+ if (isProxy) {
567
+ return;
568
+ }
569
+ const appInstance = await import_app_supervisor.AppSupervisor.getInstance().getApp("main");
570
+ for (const handle of _Gateway.wsServers) {
571
+ const result = await handle(request, socket, head, appInstance);
572
+ if (result !== false) {
573
+ return;
574
+ }
575
+ }
576
+ const { pathname } = (0, import_url.parse)(request.url);
577
+ if (pathname === import_node_process.default.env.WS_PATH) {
578
+ this.wsServer.wss.handleUpgrade(request, socket, head, (ws) => {
579
+ this.wsServer.wss.emit("connection", ws, request);
580
+ });
581
+ } else {
582
+ socket.destroy();
583
+ }
584
+ }
554
585
  getCallback() {
555
586
  return this.requestHandler.bind(this);
556
587
  }
@@ -667,26 +698,11 @@ const _Gateway = class _Gateway extends import_events.EventEmitter {
667
698
  this.getCallback()(req, res);
668
699
  });
669
700
  this.wsServer = new import_ws_server.WSServer();
670
- this.server.on("upgrade", async (request, socket, head) => {
671
- const isProxy = await import_app_supervisor.AppSupervisor.getInstance().proxyWs(request, socket, head);
672
- if (isProxy) {
673
- return;
674
- }
675
- const appInstance = await import_app_supervisor.AppSupervisor.getInstance().getApp("main");
676
- for (const handle of _Gateway.wsServers) {
677
- const result = await handle(request, socket, head, appInstance);
678
- if (result !== false) {
679
- return;
680
- }
681
- }
682
- const { pathname } = (0, import_url.parse)(request.url);
683
- if (pathname === import_node_process.default.env.WS_PATH) {
684
- this.wsServer.wss.handleUpgrade(request, socket, head, (ws) => {
685
- this.wsServer.wss.emit("connection", ws, request);
686
- });
687
- } else {
701
+ this.server.on("upgrade", (request, socket, head) => {
702
+ this.handleUpgrade(request, socket, head).catch((error) => {
703
+ import_app_supervisor.AppSupervisor.getInstance().logger.error("Failed to handle websocket upgrade", { error });
688
704
  socket.destroy();
689
- }
705
+ });
690
706
  });
691
707
  this.server.listen(this.port, this.host, () => {
692
708
  console.log(`Gateway HTTP Server running at http://${this.host}:${this.port}/`);
@@ -74,6 +74,7 @@ function hasActiveContentExtension(pathname = "") {
74
74
  __name(hasActiveContentExtension, "hasActiveContentExtension");
75
75
  function getStorageUploadSecurityHeaders(pathname = "") {
76
76
  const headers = {
77
+ "Cache-Control": "private, no-store",
77
78
  "Content-Security-Policy": "sandbox",
78
79
  "X-Content-Type-Options": "nosniff"
79
80
  };
@@ -32,6 +32,11 @@ export declare class WSServer extends EventEmitter {
32
32
  addNewConnection(ws: WebSocketWithId, request: IncomingMessage): WebSocketClient;
33
33
  setClientTag(clientId: string, tagKey: string, tagValue: string): void;
34
34
  removeClientTag(clientId: string, tagKey: string): void;
35
+ /**
36
+ * Drop a connection whose url or headers resolve to an app name that can never exist. Closing beats tagging it with
37
+ * the raw value: the tag would end up as a map key and would bootstrap an app on every selector change.
38
+ */
39
+ private rejectInvalidAppName;
35
40
  setClientApp(client: WebSocketClient): Promise<void>;
36
41
  removeConnection(id: string): void;
37
42
  sendMessageToConnection(client: WebSocketClient, sendMessage: object): void;
@@ -80,10 +80,19 @@ const _WSServer = class _WSServer extends import_events.default {
80
80
  });
81
81
  import_gateway.Gateway.getInstance().on("appSelectorChanged", () => {
82
82
  this.loopThroughConnections(async (client) => {
83
- const handleAppName = await import_gateway.Gateway.getInstance().getRequestHandleAppName({
84
- url: client.url,
85
- headers: client.headers
86
- });
83
+ let handleAppName;
84
+ try {
85
+ handleAppName = await import_gateway.Gateway.getInstance().getRequestHandleAppName({
86
+ url: client.url,
87
+ headers: client.headers
88
+ });
89
+ } catch (error) {
90
+ if (!(error instanceof import_errors.InvalidAppNameError)) {
91
+ throw error;
92
+ }
93
+ this.rejectInvalidAppName(client);
94
+ return;
95
+ }
87
96
  for (const tag of client.tags) {
88
97
  if (tag.startsWith("app#")) {
89
98
  client.tags.delete(tag);
@@ -238,12 +247,29 @@ const _WSServer = class _WSServer extends import_events.default {
238
247
  }
239
248
  });
240
249
  }
250
+ /**
251
+ * Drop a connection whose url or headers resolve to an app name that can never exist. Closing beats tagging it with
252
+ * the raw value: the tag would end up as a map key and would bootstrap an app on every selector change.
253
+ */
254
+ rejectInvalidAppName(client) {
255
+ client.ws.close(1008, "INVALID_APP_NAME");
256
+ this.removeConnection(client.id);
257
+ }
241
258
  async setClientApp(client) {
242
259
  const req = {
243
260
  url: client.url,
244
261
  headers: client.headers
245
262
  };
246
- const handleAppName = await import_gateway.Gateway.getInstance().getRequestHandleAppName(req);
263
+ let handleAppName;
264
+ try {
265
+ handleAppName = await import_gateway.Gateway.getInstance().getRequestHandleAppName(req);
266
+ } catch (error) {
267
+ if (!(error instanceof import_errors.InvalidAppNameError)) {
268
+ throw error;
269
+ }
270
+ this.rejectInvalidAppName(client);
271
+ return;
272
+ }
247
273
  client.app = handleAppName;
248
274
  console.log(`client tags: app#${handleAppName}`);
249
275
  client.tags.add(`app#${handleAppName}`);
package/lib/helper.js CHANGED
@@ -57,10 +57,24 @@ var import_crypto = require("crypto");
57
57
  var import_fs = __toESM(require("fs"));
58
58
  var import_i18next = __toESM(require("i18next"));
59
59
  var import_koa_bodyparser = __toESM(require("koa-bodyparser"));
60
+ var import_koa_send = __toESM(require("koa-send"));
60
61
  var import_perf_hooks = require("perf_hooks");
61
62
  var import_data_wrapping = require("./middlewares/data-wrapping");
62
63
  var import_extract_client_ip = require("./middlewares/extract-client-ip");
64
+ var import_static_file_security = require("./gateway/static-file-security");
63
65
  var import_i18n = require("./middlewares/i18n");
66
+ function resolveAppPublicPath(value = "/") {
67
+ const normalized = String(value || "/").trim() || "/";
68
+ const withLeadingSlash = normalized.startsWith("/") ? normalized : `/${normalized}`;
69
+ return withLeadingSlash.endsWith("/") ? withLeadingSlash : `${withLeadingSlash}/`;
70
+ }
71
+ __name(resolveAppPublicPath, "resolveAppPublicPath");
72
+ function resolveApiBasePath(value = "/api") {
73
+ const normalized = String(value || "/api").trim() || "/api";
74
+ const withLeadingSlash = normalized.startsWith("/") ? normalized : `/${normalized}`;
75
+ return withLeadingSlash.replace(/\/+$/g, "") || "/";
76
+ }
77
+ __name(resolveApiBasePath, "resolveApiBasePath");
64
78
  function createI18n(options) {
65
79
  const instance = import_i18next.default.createInstance();
66
80
  instance.init({
@@ -138,7 +152,7 @@ function registerMiddlewares(app, options) {
138
152
  }
139
153
  app.use(/* @__PURE__ */ __name(async function getBearerToken(ctx, next) {
140
154
  ctx.getBearerToken = () => {
141
- var _a2;
155
+ var _a2, _b;
142
156
  const authorization = ctx.get("Authorization");
143
157
  if (authorization) {
144
158
  ctx.state.pendingAuthTokenSource = "authorization";
@@ -148,7 +162,7 @@ function registerMiddlewares(app, options) {
148
162
  ctx.state.pendingAuthTokenSource = "query";
149
163
  return ctx.query.token;
150
164
  }
151
- const canUseAuthCookie = Boolean((_a2 = ctx.state) == null ? void 0 : _a2.fileAccess) && ["GET", "HEAD"].includes(ctx.method);
165
+ const canUseAuthCookie = Boolean(((_a2 = ctx.state) == null ? void 0 : _a2.fileAccess) || ((_b = ctx.state) == null ? void 0 : _b.legacyFileAccess)) && ["GET", "HEAD"].includes(ctx.method);
152
166
  const cookieToken = canUseAuthCookie ? ctx.cookies.get((0, import_utils.getAuthCookieName)("authToken", app.name)) : void 0;
153
167
  ctx.state.pendingAuthTokenSource = cookieToken ? "cookie" : void 0;
154
168
  return cookieToken;
@@ -159,6 +173,47 @@ function registerMiddlewares(app, options) {
159
173
  if (options.dataWrapping !== false) {
160
174
  app.use((0, import_data_wrapping.dataWrapping)(), { tag: "dataWrapping", after: "cors" });
161
175
  }
176
+ app.use(
177
+ /* @__PURE__ */ __name(async function legacyFileAccess(ctx, next) {
178
+ const publicPath = resolveAppPublicPath(process.env.APP_PUBLIC_PATH);
179
+ const uploadsPrefix = `${publicPath}storage/uploads/`;
180
+ const authCheckPath = `${resolveApiBasePath(process.env.API_BASE_PATH)}/auth:checkLegacyFileAccess`;
181
+ const isUploadRequest = ctx.path.startsWith(uploadsPrefix);
182
+ const isAuthCheckRequest = ctx.path === authCheckPath || ctx.path === "/auth:checkLegacyFileAccess";
183
+ if (!isUploadRequest && !isAuthCheckRequest) {
184
+ return next();
185
+ }
186
+ if (!["GET", "HEAD"].includes(ctx.method)) {
187
+ return ctx.throw(405);
188
+ }
189
+ ctx.state.legacyFileAccess = true;
190
+ ctx.state.legacyLocalStoragePublicAccess = process.env.LEGACY_LOCAL_STORAGE_PUBLIC_ACCESS === "true";
191
+ if (ctx.state.legacyLocalStoragePublicAccess) {
192
+ ctx.skipAuthCheck = true;
193
+ }
194
+ if (isAuthCheckRequest) {
195
+ return next();
196
+ }
197
+ const originalPath = ctx.path;
198
+ ctx.path = authCheckPath;
199
+ try {
200
+ await next();
201
+ } finally {
202
+ ctx.path = originalPath;
203
+ }
204
+ const relativePath = `uploads/${originalPath.slice(uploadsPrefix.length)}`;
205
+ const headers = (0, import_static_file_security.getStorageUploadSecurityHeaders)(`${originalPath}${ctx.search || ""}`);
206
+ if (!headers["Content-Disposition"]) {
207
+ headers["Content-Disposition"] = "inline";
208
+ }
209
+ for (const [name, value] of Object.entries(headers)) {
210
+ ctx.set(name, value);
211
+ }
212
+ ctx.status = 200;
213
+ await (0, import_koa_send.default)(ctx, relativePath, { root: (0, import_utils.resolveStorageRoot)() });
214
+ }, "legacyFileAccess"),
215
+ { tag: "legacyFileAccess", before: "dataSource", after: "dataWrapping" }
216
+ );
162
217
  app.use(app.dataSourceManager.middleware(), { tag: "dataSource", after: "dataWrapping" });
163
218
  app.use((0, import_extract_client_ip.extractClientIp)(), { tag: "extractClientIp", before: "cors" });
164
219
  }
@@ -70,7 +70,7 @@ const deps = {
70
70
  "pg-hstore": "2.x",
71
71
  sqlite3: "5.x",
72
72
  supertest: "6.x",
73
- axios: "1.7.x",
73
+ axios: "1.20.x",
74
74
  "@emotion/css": "11.x",
75
75
  ahooks: "3.x",
76
76
  lodash: "4.x",
@@ -79,7 +79,7 @@ module.exports = __toCommonJS(utils_exports);
79
79
  var import_utils = require("@nocobase/utils");
80
80
  var import_plugin_symlink = require("@nocobase/utils/plugin-symlink");
81
81
  var import_axios = __toESM(require("axios"));
82
- var import_decompress = __toESM(require("decompress"));
82
+ var import_decompress = __toESM(require("@xhmikosr/decompress"));
83
83
  var import_fast_glob = __toESM(require("fast-glob"));
84
84
  var import_fs_extra = __toESM(require("fs-extra"));
85
85
  var import_ini = __toESM(require("ini"));
@@ -0,0 +1,9 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocobase/server",
3
- "version": "2.3.0-beta.2",
3
+ "version": "2.3.0-beta.21",
4
4
  "main": "lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "license": "Apache-2.0",
@@ -10,25 +10,25 @@
10
10
  "@koa/cors": "^5.0.0",
11
11
  "@koa/multer": "^3.1.0",
12
12
  "@koa/router": "^13.1.0",
13
- "@nocobase/acl": "2.3.0-beta.2",
14
- "@nocobase/actions": "2.3.0-beta.2",
15
- "@nocobase/ai": "2.3.0-beta.2",
16
- "@nocobase/auth": "2.3.0-beta.2",
17
- "@nocobase/cache": "2.3.0-beta.2",
18
- "@nocobase/data-source-manager": "2.3.0-beta.2",
19
- "@nocobase/database": "2.3.0-beta.2",
20
- "@nocobase/evaluators": "2.3.0-beta.2",
21
- "@nocobase/lock-manager": "2.3.0-beta.2",
22
- "@nocobase/logger": "2.3.0-beta.2",
23
- "@nocobase/resourcer": "2.3.0-beta.2",
24
- "@nocobase/sdk": "2.3.0-beta.2",
25
- "@nocobase/snowflake-id": "2.3.0-beta.2",
26
- "@nocobase/telemetry": "2.3.0-beta.2",
27
- "@nocobase/utils": "2.3.0-beta.2",
28
- "@types/decompress": "4.2.7",
13
+ "@nocobase/acl": "2.3.0-beta.21",
14
+ "@nocobase/actions": "2.3.0-beta.21",
15
+ "@nocobase/ai": "2.3.0-beta.21",
16
+ "@nocobase/auth": "2.3.0-beta.21",
17
+ "@nocobase/cache": "2.3.0-beta.21",
18
+ "@nocobase/data-source-manager": "2.3.0-beta.21",
19
+ "@nocobase/database": "2.3.0-beta.21",
20
+ "@nocobase/evaluators": "2.3.0-beta.21",
21
+ "@nocobase/lock-manager": "2.3.0-beta.21",
22
+ "@nocobase/logger": "2.3.0-beta.21",
23
+ "@nocobase/resourcer": "2.3.0-beta.21",
24
+ "@nocobase/sdk": "2.3.0-beta.21",
25
+ "@nocobase/snowflake-id": "2.3.0-beta.21",
26
+ "@nocobase/telemetry": "2.3.0-beta.21",
27
+ "@nocobase/utils": "2.3.0-beta.21",
29
28
  "@types/ini": "^1.3.31",
30
29
  "@types/koa-send": "^4.1.3",
31
30
  "@types/multer": "^1.4.12",
31
+ "@xhmikosr/decompress": "^11.1.4",
32
32
  "async-mutex": "^0.5.0",
33
33
  "axios": "^1.7.0",
34
34
  "chalk": "^4.1.1",
@@ -37,7 +37,6 @@
37
37
  "cron": "^2.4.4",
38
38
  "cronstrue": "^2.11.0",
39
39
  "dayjs": "^1.11.8",
40
- "decompress": "4.2.1",
41
40
  "find-package-json": "^1.2.0",
42
41
  "fs-extra": "^11.1.1",
43
42
  "i18next": "^22.4.9",
@@ -61,5 +60,5 @@
61
60
  "@types/serve-handler": "^6.1.1",
62
61
  "@types/ws": "^8.5.5"
63
62
  },
64
- "gitHead": "2e5b43a39d3f3e7cff58cb5e5a36a8c8e599dfb5"
63
+ "gitHead": "a2bdd27cc7bc8ced9ad395b3a7468fc1850eef4a"
65
64
  }