Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
632 lines (550 loc) · 23.5 KB
/
Copy pathserver.ts
File metadata and controls
632 lines (550 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import { inDevelopment, inProduction, ModuleRegistry } from '@n8n/backend-common';
import { EventService, PostHogClient } from '@n8n/backend-services';
import { AuthStrategyRegistry } from '@n8n/backend-services/auth';
import { SecurityConfig } from '@n8n/config';
import { EMBEDDED_SETTINGS_GLOBAL, HTML_NONCE_PLACEHOLDER, Time } from '@n8n/constants';
import type { APIRequest, AuthenticatedRequest } from '@n8n/db';
import { Container, Service } from '@n8n/di';
import { OperationalError } from '@n8n/errors';
import { withTimeout } from '@n8n/utils/promise/with-timeout';
import cookieParser from 'cookie-parser';
import express from 'express';
import { access as fsAccess, readFile } from 'fs/promises';
import helmet from 'helmet';
import escapeRegExp from 'lodash/escapeRegExp';
import { InstanceSettings } from 'n8n-core';
import { resolve } from 'path';
import { AbstractServer } from '@/abstract-server';
import { AuthService } from '@/auth/auth.service';
import { CLI_DIR, EDITOR_UI_DIST_DIR, EMBEDDED_SETTINGS_TIMEOUT_MS, inE2ETests } from '@/constants';
import { ControllerRegistry } from '@/controller.registry';
import { CredentialsOverwrites } from '@/credentials-overwrites';
import { MessageEventBus } from '@/eventbus/message-event-bus/message-event-bus';
import { LogStreamingEventRelay } from '@/events/relays/log-streaming.event-relay';
import type { ICredentialsOverwrite } from '@/interfaces';
import { LoadNodesAndCredentials } from '@/load-nodes-and-credentials';
import { handleMfaDisable, isMfaFeatureEnabled } from '@/mfa/helpers';
import { createContentSecurityPolicyMiddleware } from '@/middlewares/content-security-policy';
import { loadPublicApiVersions } from '@/public-api';
import { Push } from '@/push';
import * as ResponseHelper from '@/response-helper';
import { resolveContentSecurityPolicies } from '@/security/content-security-policy';
import type { FrontendService } from '@/services/frontend.service';
import { Telemetry } from '@/telemetry';
import * as requestPath from '@/utils/request-path';
import { setImmutableAssetHeaders } from '@/utils/static-asset-cache';
import '@/controllers/active-workflows.controller';
import '@/controllers/annotation-tags.controller.ee';
import '@/controllers/auth.controller';
import '@/controllers/binary-data.controller';
import '@/controllers/change-email.controller';
import '@/controllers/ai.controller';
import '@/controllers/ai-preference.controller';
import '@/controllers/ai-preference-settings.controller';
import '@/controllers/dynamic-node-parameters.controller';
import '@/controllers/invitation.controller';
import '@/controllers/me.controller';
import '@/controllers/node-types.controller';
import '@/controllers/oauth/oauth1-credential.controller';
import '@/controllers/oauth/oauth2-credential.controller';
import '@/controllers/orchestration.controller';
import '@/controllers/owner.controller';
import '@/controllers/password-reset.controller';
import '@/controllers/project.controller';
import '@/controllers/project-pool-settings.controller.ee';
import '@/controllers/role.controller';
import '@/controllers/tags.controller';
import '@/controllers/translation.controller';
import '@/controllers/folder.controller';
import '@/controllers/users.controller';
import '@/controllers/user-settings.controller';
import '@/controllers/workflow-statistics.controller';
import '@/controllers/api-keys.controller';
import '@/controllers/security-settings.controller';
import '@/controllers/public-api-rate-limit-settings.controller';
import '@/credentials/credentials.controller';
import '@/credentials/credential-options.controller';
import '@/events/events.controller';
import '@/executions/executions.controller';
import '@/node-execution/ephemeral-node-executor';
import '@/jwks/jwks.controller';
import '@/license/license.controller';
import '@/evaluation.ee/test-runs.controller.ee';
import '@/evaluation.ee/evaluation-config.controller';
import '@/evaluation.ee/evaluation-collections.controller.ee';
import '@/evaluation.ee/insights/eval-insights.controller.ee';
import '@/workflows/workflow-history/workflow-history.controller';
import '@/workflows/workflows.controller';
import '@/modules/workflow-index/workflow-dependency.controller';
import '@/webhooks/test-webhooks.controller';
import '@/webhooks/webhooks.controller';
import { ChatServer } from './chat/chat-server';
import { MfaService } from './mfa/mfa.service';
import { responsesApiFallback } from './modules/agents/integrations/platforms/webhook/responses-api';
import { BrowserUseServer } from './modules/instance-ai/browser/browser-use-server';
import { PubSubRegistry } from './scaling/pubsub/pubsub.registry';
import { ApiKeyAuthStrategy } from './services/api-key-auth.strategy';
import { SessionCookieAuthStrategy } from './services/session-cookie-auth.strategy';
/**
* JSON that is safe inside an inline `<script>`. `<`, `>` and `&` cannot close the
* script or start markup, and U+2028 and U+2029 cannot end a line in older parsers.
* `JSON.parse` and the JS parser map the escapes back to the original characters.
*/
const toScriptSafeJson = (value: unknown) =>
JSON.stringify(value).replace(
/[<>&\u2028\u2029]/g,
(char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`,
);
/** Inserts `markup` before `</head>`. Returns `html` unchanged when it has no `</head>`. */
const insertBeforeHeadEnd = (html: string, markup: string) => {
const headEnd = html.indexOf('</head>');
return headEnd !== -1 ? html.slice(0, headEnd) + markup + html.slice(headEnd) : html;
};
@Service()
export class Server extends AbstractServer {
private endpointPresetCredentials: string;
private presetCredentialsLoaded: boolean;
private frontendService?: FrontendService;
constructor(
private readonly loadNodesAndCredentials: LoadNodesAndCredentials,
private readonly postHogClient: PostHogClient,
private readonly eventService: EventService,
private readonly instanceSettings: InstanceSettings,
) {
super();
this.testWebhooksEnabled = true;
this.webhooksEnabled = !this.globalConfig.endpoints.disableProductionWebhooksOnMainProcess;
}
async start() {
if (!this.globalConfig.endpoints.disableUi) {
const { FrontendService } = await import('@/services/frontend.service.js');
this.frontendService = Container.get(FrontendService);
await import('@/controllers/module-settings.controller.js');
await import('@/controllers/third-party-licenses.controller.js');
}
this.presetCredentialsLoaded = false;
this.endpointPresetCredentials = this.globalConfig.credentials.overwrite.endpoint;
await super.start();
this.logger.debug(`Server ID: ${this.instanceSettings.hostId}`);
if (process.env.N8N_DEV_RELOAD === 'true') {
void this.loadNodesAndCredentials.setupHotReload();
}
this.markAsReady();
this.eventService.emit('server-started');
}
private async registerAdditionalControllers() {
if (!inProduction && this.instanceSettings.isMultiMain) {
await import('@/controllers/debug.controller.js');
}
if (inE2ETests) {
await import('@/controllers/e2e.controller.js');
}
if (process.env.N8N_DEV_RELOAD === 'true') {
await import('@/controllers/dev.controller.js');
}
if (isMfaFeatureEnabled()) {
await Container.get(MfaService).init();
await import('@/controllers/mfa.controller.js');
}
if (!this.globalConfig.endpoints.disableUi) {
await import('@/controllers/cta.controller.js');
}
if (!this.globalConfig.tags.disabled) {
await import('@/controllers/tags.controller.js');
}
if (this.globalConfig.diagnostics.enabled) {
await import('@/controllers/telemetry.controller.js');
await import('@/controllers/page-hide-telemetry.controller.js');
await import('@/controllers/posthog.controller.js');
}
// ----------------------------------------
// Variables
// ----------------------------------------
try {
await import('@/environments.ee/variables/variables.controller.ee.js');
} catch (error) {
this.logger.warn(`Variables initialization failed: ${(error as Error).message}`);
}
}
async configure(): Promise<void> {
if (this.globalConfig.endpoints.metrics.enable) {
const { PrometheusMetricsService } = await import('@/metrics/prometheus/index.js');
Container.get(PrometheusMetricsService).init(this.app);
}
const { frontendService } = this;
if (frontendService) {
const frontendSettings = await frontendService.getSettings();
await this.externalHooks.run('frontend.settings', [frontendSettings]);
if (this.globalConfig.deployment.type === 'cloud') {
Container.get(Telemetry).setUserCloudId(frontendSettings.n8nMetadata?.userId);
}
}
await this.postHogClient.init();
this.postHogClient.setupExpressSessionContext(this.app);
const publicApiEndpoint = this.globalConfig.publicApi.path;
// Register auth strategies in priority order. The registry evaluates them
// sequentially — the first strategy that does not abstain wins.
// API key auth is registered first so existing behavior is preserved.
// Session cookie auth is registered last: an explicit but wrong API
// key/bearer token fails fast rather than silently falling back to an
// ambient browser session cookie.
// Additional strategies (e.g. scoped JWT from the token-exchange module)
// can be appended later during their own module initialization.
const registry = Container.get(AuthStrategyRegistry);
registry.register(Container.get(ApiKeyAuthStrategy));
registry.register(Container.get(SessionCookieAuthStrategy));
// Parse cookies for easier access
this.app.use(cookieParser());
// Extract BrowserId from headers
this.app.use((req: APIRequest, _, next) => {
req.browserId = req.headers['browser-id'] as string;
next();
});
// Installed here on purpose, and the order is the mechanism: `AbstractServer` has
// already registered the webhook and form routes, so they never reach this
// middleware. Those pages serve HTML that a workflow author wrote, which the
// instance policy must not constrain - including when the `sandbox` policy is
// switched off with `N8N_INSECURE_DISABLE_*_SANDBOX`, where they carry no policy
// at all. Moving this line above `AbstractServer` would silently change that.
const securityConfig = Container.get(SecurityConfig);
this.app.use(
createContentSecurityPolicyMiddleware(
resolveContentSecurityPolicies(
securityConfig.contentSecurityPolicy,
securityConfig.contentSecurityPolicyReportOnly,
this.logger,
),
),
);
// ----------------------------------------
// Public API
// ----------------------------------------
const { apiRouters, apiLatestVersion } = await loadPublicApiVersions(publicApiEndpoint);
this.app.use(...apiRouters);
if (frontendService) {
(await frontendService.getSettings()).publicApi.latestVersion = apiLatestVersion;
}
const { restEndpoint, app } = this;
const push = Container.get(Push);
push.setupPushHandler(restEndpoint, app);
if (push.isBidirectional) {
const { CollaborationService } = await import('@/collaboration/collaboration.service.js');
const collaborationService = Container.get(CollaborationService);
collaborationService.init();
} else {
this.logger.warn(
'Collaboration features are disabled because push is configured unidirectional. Use N8N_PUSH_BACKEND=websocket environment variable to enable them.',
);
}
if (this.globalConfig.executions.mode === 'queue') {
const { ScalingService } = await import('@/scaling/scaling.service.js');
await Container.get(ScalingService).setupQueue();
}
await handleMfaDisable();
await this.registerAdditionalControllers();
// Reinitialize the PubSubRegistry
Container.get(PubSubRegistry).init();
// register all known controllers
Container.get(ControllerRegistry).activate(app);
// The agent webhook keeps the OpenAI error shape for unknown routes and unparsable bodies.
app.use(`/${this.globalConfig.endpoints.agentWebhook}`, ...responsesApiFallback);
// ----------------------------------------
// Options
// ----------------------------------------
// Returns all the available timezones
const tzDataFile = resolve(CLI_DIR, 'dist/timezones.json');
this.app.get(`/${this.restEndpoint}/options/timezones`, (_, res) =>
res.sendFile(tzDataFile, { dotfiles: 'allow' }),
);
this.configureSettingsRoute();
// ----------------------------------------
// EventBus Setup
// ----------------------------------------
// Before initialize(), which runs crash recovery.
Container.get(LogStreamingEventRelay).init();
const eventBus = Container.get(MessageEventBus);
await eventBus.initialize();
// ----------------------------------------
// Workflow Indexing Setup
// ----------------------------------------
await this.initializeWorkflowIndexing();
if (this.endpointPresetCredentials !== '') {
// POST endpoint to set preset credentials
const overwriteEndpointMiddleware =
Container.get(CredentialsOverwrites).getOverwriteEndpointMiddleware();
if (overwriteEndpointMiddleware) {
this.app.use(`/${this.endpointPresetCredentials}`, overwriteEndpointMiddleware);
}
const authenticationEnforced = overwriteEndpointMiddleware !== null;
this.app.post(
`/${this.endpointPresetCredentials}`,
async (req: express.Request, res: express.Response) => {
try {
// If authentication is enforced we can allow multiple overwrites
if (!this.presetCredentialsLoaded || authenticationEnforced) {
const body = req.body as ICredentialsOverwrite;
if (req.contentType !== 'application/json') {
ResponseHelper.sendErrorResponse(
res,
new Error(
'Body must be a valid JSON, make sure the content-type is application/json',
),
);
return;
}
await Container.get(CredentialsOverwrites).setData(body, true, true);
this.presetCredentialsLoaded = true;
// Send push event to notify frontend to refetch types
Container.get(Push).broadcast({ type: 'nodeDescriptionUpdated', data: {} });
ResponseHelper.sendSuccessResponse(res, { success: true }, true, 200);
} else {
ResponseHelper.sendErrorResponse(
res,
new Error('Preset credentials can be set once'),
);
}
} catch (error) {
this.logger.error('Error handling credentials overwrite', { error });
ResponseHelper.sendErrorResponse(
res,
new Error(
'An error occurred while handling credentials overwrite, please check the logs for more details',
),
);
}
},
);
}
const maxAge = Time.days.toMilliseconds;
const cacheOptions: { maxAge?: number; setHeaders?: typeof setImmutableAssetHeaders } =
inE2ETests || inDevelopment ? {} : { maxAge, setHeaders: setImmutableAssetHeaders };
const { staticCacheDir } = Container.get(InstanceSettings);
this.protectTypeFiles(staticCacheDir);
if (frontendService) {
const assetAuthMiddleware = Container.get(AuthService).createAssetAuthMiddleware();
const registerAuthenticatedRoutes = (paths: string[], handler: express.RequestHandler) => {
for (const assetPath of paths) {
this.app.get(assetPath, assetAuthMiddleware, handler);
}
};
const respondWithPrivateFile = (res: express.Response, filePath: string, assetMaxAge = 0) => {
const maxAgeSeconds = Math.floor(assetMaxAge * Time.milliseconds.toSeconds);
// `res.sendFile` writes its own `Cache-Control` only when the response carries none.
res.setHeader('Cache-Control', `private, max-age=${maxAgeSeconds}`);
return res.sendFile(filePath, { maxAge: assetMaxAge, dotfiles: 'allow' });
};
registerAuthenticatedRoutes(
[
'/icons/{@:scope/}:packageName/*path/*file.svg',
'/icons/{@:scope/}:packageName/*path/*file.png',
],
async (req, res) => {
// eslint-disable-next-line prefer-const
let { scope, packageName } = req.params;
if (scope) packageName = `@${scope}/${packageName}`;
const filePath = this.loadNodesAndCredentials.resolveIcon(packageName, req.originalUrl);
if (filePath) {
try {
await fsAccess(filePath);
return respondWithPrivateFile(res, filePath, maxAge);
} catch {}
}
res.sendStatus(404);
},
);
const serveSchemas: express.RequestHandler = async (req, res) => {
const { node, version, resource, operation } = req.params;
const filePath = this.loadNodesAndCredentials.resolveSchema({
node,
resource,
operation,
version,
});
if (filePath) {
try {
await fsAccess(filePath);
return respondWithPrivateFile(res, filePath, cacheOptions.maxAge);
} catch {}
}
res.sendStatus(404);
};
registerAuthenticatedRoutes(
['/schemas/:node/:version{/:resource}{/:operation}.json'],
serveSchemas,
);
const isTLSEnabled =
this.globalConfig.protocol === 'https' && !!(this.sslKey && this.sslCert);
const isPreviewMode = process.env.N8N_PREVIEW_MODE === 'true';
const crossOriginOpenerPolicy = Container.get(SecurityConfig).crossOriginOpenerPolicy;
// `createContentSecurityPolicyMiddleware` serves the CSP instead: helmet cannot
// inject a per-request nonce.
const securityHeadersMiddleware = helmet({
contentSecurityPolicy: false,
xFrameOptions:
isPreviewMode || inE2ETests || inDevelopment ? false : { action: 'sameorigin' },
dnsPrefetchControl: false,
// This is only relevant for Internet-explorer, which we do not support
ieNoOpen: false,
// This is already disabled in AbstractServer
xPoweredBy: false,
// Enable HSTS headers only when n8n handles TLS.
// if n8n is behind a reverse-proxy, then these headers needs to be configured there
strictTransportSecurity: isTLSEnabled
? {
maxAge: 180 * Time.days.toSeconds,
includeSubDomains: false,
preload: false,
}
: false,
crossOriginOpenerPolicy: {
policy: crossOriginOpenerPolicy,
},
});
// Route all UI urls to index.html to support history-api
const nonUIRoutes: readonly string[] = [
'favicon.ico',
'assets',
'static',
'types',
'\\.well-known',
this.endpointHealth,
'metrics',
'e2e',
this.restEndpoint,
this.endpointPresetCredentials,
// This path may contain `.`, which the route pattern must match literally.
escapeRegExp(this.globalConfig.endpoints.agentWebhook),
...this.globalConfig.endpoints.additionalNonUIRoutes.split(':'),
].filter((u) => !!u);
// Matched against the normalised path, so a non-UI asset requested in another
// case or spelling reaches the static handler rather than the editor page.
const nonUIRoutesRegex = new RegExp(`^/(${nonUIRoutes.join('|')})/?.*$`, 'i');
// `index.html` does not change while n8n runs. Read it once and keep it split
// around the nonce placeholders, so serving a request is only a join.
let indexHtmlParts: string[] | undefined;
const indexHtmlTemplate = async () => {
indexHtmlParts ??= (await readFile(resolve(staticCacheDir, 'index.html'), 'utf8')).split(
HTML_NONCE_PLACEHOLDER,
);
return indexHtmlParts;
};
// Public settings only: the page handler runs no auth middleware. If they cannot
// be built in time, the page is served without them and the editor fetches them
// instead. The time limit keeps a slow database from delaying the page.
const embeddedSettingsScript = async (nonce: string) => {
try {
const settings = await withTimeout(
frontendService.getPublicSettings(false),
EMBEDDED_SETTINGS_TIMEOUT_MS,
() => new OperationalError('Building the embedded settings timed out'),
);
return `<script nonce="${nonce}">window.${EMBEDDED_SETTINGS_GLOBAL} = ${toScriptSafeJson(settings)};</script>`;
} catch (error) {
this.logger.warn('Could not embed settings in the editor page', { error });
return undefined;
}
};
const historyApiHandler: express.RequestHandler = async (req, res, next) => {
const {
method,
headers: { accept },
} = req;
// A request with no `Accept` also gets the page. Only this handler fills in the
// nonce placeholders, so `express.static` would serve `index.html` with the
// placeholders intact, and no script on it could run under the CSP.
if (
method === 'GET' &&
(!accept || req.accepts('html') || accept.includes('*/*')) &&
!req.path.endsWith('.wasm') &&
!nonUIRoutesRegex.test(requestPath.normalize(req.path))
) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate');
let template: string[];
try {
template = await indexHtmlTemplate();
} catch (error) {
this.logger.error('Could not read index.html', { error });
res.sendStatus(500);
return;
}
// Only the placeholders the build wrote get the nonce. Markup that arrived
// any other way must not get one.
const nonce = res.locals.cspNonce;
const settingsScript = await embeddedSettingsScript(nonce);
securityHeadersMiddleware(req, res, () => {
const page = template.join(nonce);
res
.type('html')
.send(settingsScript ? insertBeforeHeadEnd(page, settingsScript) : page);
});
} else {
next();
}
};
this.app.use(
'/',
historyApiHandler,
express.static(staticCacheDir, cacheOptions),
express.static(EDITOR_UI_DIST_DIR, cacheOptions),
);
} else {
this.app.use('/', express.static(staticCacheDir, cacheOptions));
}
}
/** Authenticates every request that can reach a type file, whether or not the editor is served. */
private protectTypeFiles(staticCacheDir: string) {
const authMiddleware = Container.get(AuthService).createAuthMiddleware({
allowSkipMFA: true,
allowSkipPreviewAuth: true,
});
// Match exact urls. We always expect them in this form, and only a matched route
// path can skip AuthService's browser-id check, which the editor's fetch needs.
const typeFiles = ['/types/nodes.json', '/types/credentials.json', '/types/node-versions.json'];
typeFiles.forEach((typeFile) => {
this.app.get(typeFile, authMiddleware, async (_, res: express.Response) => {
res.setHeader('Cache-Control', 'no-cache, must-revalidate');
res.sendFile(typeFile.substring(1), { root: staticCacheDir });
});
});
// Deny any request that can reach /types/* that isn't caught above, rather than
// authenticating it: no client asks for those forms, and authenticating here would
// clear the session cookie of a signed-in caller, since this matches no route.
this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
if (requestPath.mayReachDirectory(req.path, 'types')) {
res.status(401).end();
return;
}
next();
});
}
private configureSettingsRoute() {
const { frontendService } = this;
const authService = Container.get(AuthService);
if (frontendService) {
// Returns the current settings for the UI
this.app.get(
`/${this.restEndpoint}/settings`,
authService.createAuthMiddleware({ allowSkipMFA: false, allowUnauthenticated: true }),
ResponseHelper.send(async (req: AuthenticatedRequest) => {
return req.user
? await frontendService.getSettings()
: await frontendService.getPublicSettings(!!req.authInfo?.mfaEnrollmentRequired);
}),
);
}
}
private async initializeWorkflowIndexing() {
const { WorkflowIndexService } = await import(
'@/modules/workflow-index/workflow-index.service.js'
);
Container.get(WorkflowIndexService).init();
}
protected setupPushServer(): void {
const { restEndpoint, server, app } = this;
Container.get(Push).setupPushServer(restEndpoint, server, app);
Container.get(ChatServer).setup(server, app);
if (Container.get(ModuleRegistry).isActive('instance-ai')) {
Container.get(BrowserUseServer).setup(server, app);
}
}
}