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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// native node modules
|
| 2 |
+
import path from 'node:path';
|
| 3 |
+
import util from 'node:util';
|
| 4 |
+
import net from 'node:net';
|
| 5 |
+
import dns from 'node:dns';
|
| 6 |
+
import process from 'node:process';
|
| 7 |
+
|
| 8 |
+
import cors from 'cors';
|
| 9 |
+
import { csrfSync } from 'csrf-sync';
|
| 10 |
+
import express from 'express';
|
| 11 |
+
import compression from 'compression';
|
| 12 |
+
import cookieSession from 'cookie-session';
|
| 13 |
+
import multer from 'multer';
|
| 14 |
+
import responseTime from 'response-time';
|
| 15 |
+
import helmet from 'helmet';
|
| 16 |
+
import bodyParser from 'body-parser';
|
| 17 |
+
|
| 18 |
+
// local library imports
|
| 19 |
+
import './fetch-patch.js';
|
| 20 |
+
import { serverDirectory } from './server-directory.js';
|
| 21 |
+
|
| 22 |
+
import { serverEvents, EVENT_NAMES } from './server-events.js';
|
| 23 |
+
import { loadPlugins } from './plugin-loader.js';
|
| 24 |
+
import { router as usersInternalRouter } from './endpoints/users-internal.js'; //增
|
| 25 |
+
import {
|
| 26 |
+
initUserStorage,
|
| 27 |
+
getCookieSecret,
|
| 28 |
+
getCookieSessionName,
|
| 29 |
+
ensurePublicDirectoriesExist,
|
| 30 |
+
getUserDirectoriesList,
|
| 31 |
+
migrateSystemPrompts,
|
| 32 |
+
migrateUserData,
|
| 33 |
+
requireLoginMiddleware,
|
| 34 |
+
requireAdminMiddleware,//增
|
| 35 |
+
setUserDataMiddleware,
|
| 36 |
+
shouldRedirectToLogin,
|
| 37 |
+
cleanUploads,
|
| 38 |
+
getSessionCookieAge,
|
| 39 |
+
verifySecuritySettings,
|
| 40 |
+
loginPageMiddleware,
|
| 41 |
+
} from './users.js';
|
| 42 |
+
|
| 43 |
+
import getWebpackServeMiddleware from './middleware/webpack-serve.js';
|
| 44 |
+
import basicAuthMiddleware from './middleware/basicAuth.js';
|
| 45 |
+
import getWhitelistMiddleware from './middleware/whitelist.js';
|
| 46 |
+
import accessLoggerMiddleware, { getAccessLogPath, migrateAccessLog } from './middleware/accessLogWriter.js';
|
| 47 |
+
import multerMonkeyPatch from './middleware/multerMonkeyPatch.js';
|
| 48 |
+
import initRequestProxy from './request-proxy.js';
|
| 49 |
+
import cacheBuster from './middleware/cacheBuster.js';
|
| 50 |
+
import corsProxyMiddleware from './middleware/corsProxy.js';
|
| 51 |
+
import {
|
| 52 |
+
getVersion,
|
| 53 |
+
color,
|
| 54 |
+
removeColorFormatting,
|
| 55 |
+
getSeparator,
|
| 56 |
+
safeReadFileSync,
|
| 57 |
+
setupLogLevel,
|
| 58 |
+
setWindowTitle,
|
| 59 |
+
getConfigValue,
|
| 60 |
+
} from './util.js';
|
| 61 |
+
import { UPLOADS_DIRECTORY } from './constants.js';
|
| 62 |
+
import { ensureThumbnailCache } from './endpoints/thumbnails.js';
|
| 63 |
+
|
| 64 |
+
// Routers
|
| 65 |
+
import { router as usersPublicRouter } from './endpoints/users-public.js';
|
| 66 |
+
import { init as statsInit, onExit as statsOnExit } from './endpoints/stats.js';
|
| 67 |
+
import { checkForNewContent } from './endpoints/content-manager.js';
|
| 68 |
+
import { init as settingsInit } from './endpoints/settings.js';
|
| 69 |
+
import { redirectDeprecatedEndpoints, ServerStartup, setupPrivateEndpoints } from './server-startup.js';
|
| 70 |
+
import { diskCache } from './endpoints/characters.js';
|
| 71 |
+
import { migrateFlatSecrets } from './endpoints/secrets.js';
|
| 72 |
+
|
| 73 |
+
// Work around a node v20.0.0, v20.1.0, and v20.2.0 bug. The issue was fixed in v20.3.0.
|
| 74 |
+
// https://github.com/nodejs/node/issues/47822#issuecomment-1564708870
|
| 75 |
+
// Safe to remove once support for Node v20 is dropped.
|
| 76 |
+
if (process.versions && process.versions.node && process.versions.node.match(/20\.[0-2]\.0/)) {
|
| 77 |
+
// @ts-ignore
|
| 78 |
+
if (net.setDefaultAutoSelectFamily) net.setDefaultAutoSelectFamily(false);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// Unrestrict console logs display limit
|
| 82 |
+
util.inspect.defaultOptions.maxArrayLength = null;
|
| 83 |
+
util.inspect.defaultOptions.maxStringLength = null;
|
| 84 |
+
util.inspect.defaultOptions.depth = 4;
|
| 85 |
+
|
| 86 |
+
/** @type {import('./command-line.js').CommandLineArguments} */
|
| 87 |
+
const cliArgs = globalThis.COMMAND_LINE_ARGS;
|
| 88 |
+
|
| 89 |
+
if (!cliArgs.enableIPv6 && !cliArgs.enableIPv4) {
|
| 90 |
+
console.error('error: You can\'t disable all internet protocols: at least IPv6 or IPv4 must be enabled.');
|
| 91 |
+
process.exit(1);
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
const app = express();
|
| 95 |
+
app.use(helmet({
|
| 96 |
+
contentSecurityPolicy: false,
|
| 97 |
+
}));
|
| 98 |
+
app.use(compression());
|
| 99 |
+
app.use(responseTime());
|
| 100 |
+
|
| 101 |
+
app.use(bodyParser.json({ limit: '500mb' }));
|
| 102 |
+
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb' }));
|
| 103 |
+
|
| 104 |
+
// CORS Settings //
|
| 105 |
+
const CORS = cors({
|
| 106 |
+
origin: 'null',
|
| 107 |
+
methods: ['OPTIONS'],
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
app.use(CORS);
|
| 111 |
+
|
| 112 |
+
if (cliArgs.listen && cliArgs.basicAuthMode) {
|
| 113 |
+
app.use(basicAuthMiddleware);
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
if (cliArgs.whitelistMode) {
|
| 117 |
+
const whitelistMiddleware = await getWhitelistMiddleware();
|
| 118 |
+
app.use(whitelistMiddleware);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
if (cliArgs.listen) {
|
| 122 |
+
app.use(accessLoggerMiddleware());
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
if (cliArgs.enableCorsProxy) {
|
| 126 |
+
app.use('/proxy/:url(*)', corsProxyMiddleware);
|
| 127 |
+
} else {
|
| 128 |
+
app.use('/proxy/:url(*)', async (_, res) => {
|
| 129 |
+
const message = 'CORS proxy is disabled. Enable it in config.yaml or use the --corsProxy flag.';
|
| 130 |
+
console.log(message);
|
| 131 |
+
res.status(404).send(message);
|
| 132 |
+
});
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
app.use(cookieSession({
|
| 136 |
+
name: getCookieSessionName(),
|
| 137 |
+
sameSite: 'lax',
|
| 138 |
+
httpOnly: true,
|
| 139 |
+
maxAge: getSessionCookieAge(),
|
| 140 |
+
secret: getCookieSecret(globalThis.DATA_ROOT),
|
| 141 |
+
}));
|
| 142 |
+
|
| 143 |
+
app.use(setUserDataMiddleware);
|
| 144 |
+
// Internal endpoints (no auth required)
|
| 145 |
+
app.use(bodyParser.json());//增
|
| 146 |
+
app.use('/api/users-internal', usersInternalRouter);//增
|
| 147 |
+
|
| 148 |
+
// Admin panel access control
|
| 149 |
+
app.use('/admin/*', [requireLoginMiddleware, requireAdminMiddleware]);
|
| 150 |
+
// CSRF Protection //
|
| 151 |
+
if (!cliArgs.disableCsrf) {
|
| 152 |
+
const csrfSyncProtection = csrfSync({
|
| 153 |
+
getTokenFromState: (req) => {
|
| 154 |
+
if (!req.session) {
|
| 155 |
+
console.error('(CSRF error) getTokenFromState: Session object not initialized');
|
| 156 |
+
return;
|
| 157 |
+
}
|
| 158 |
+
return req.session.csrfToken;
|
| 159 |
+
},
|
| 160 |
+
getTokenFromRequest: (req) => {
|
| 161 |
+
return req.headers['x-csrf-token']?.toString();
|
| 162 |
+
},
|
| 163 |
+
storeTokenInState: (req, token) => {
|
| 164 |
+
if (!req.session) {
|
| 165 |
+
console.error('(CSRF error) storeTokenInState: Session object not initialized');
|
| 166 |
+
return;
|
| 167 |
+
}
|
| 168 |
+
req.session.csrfToken = token;
|
| 169 |
+
},
|
| 170 |
+
size: 32,
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
app.get('/csrf-token', (req, res) => {
|
| 174 |
+
res.json({
|
| 175 |
+
'token': csrfSyncProtection.generateToken(req),
|
| 176 |
+
});
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
// Customize the error message
|
| 180 |
+
csrfSyncProtection.invalidCsrfTokenError.message = color.red('Invalid CSRF token. Please refresh the page and try again.');
|
| 181 |
+
csrfSyncProtection.invalidCsrfTokenError.stack = undefined;
|
| 182 |
+
|
| 183 |
+
app.use(csrfSyncProtection.csrfSynchronisedProtection);
|
| 184 |
+
} else {
|
| 185 |
+
console.warn('\nCSRF protection is disabled. This will make your server vulnerable to CSRF attacks.\n');
|
| 186 |
+
app.get('/csrf-token', (req, res) => {
|
| 187 |
+
res.json({
|
| 188 |
+
'token': 'disabled',
|
| 189 |
+
});
|
| 190 |
+
});
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// Static files
|
| 194 |
+
// Host index page
|
| 195 |
+
app.get('/', cacheBuster.middleware, (request, response) => {
|
| 196 |
+
if (shouldRedirectToLogin(request)) {
|
| 197 |
+
const query = request.url.split('?')[1];
|
| 198 |
+
const redirectUrl = query ? `/login?${query}` : '/login';
|
| 199 |
+
return response.redirect(redirectUrl);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
return response.sendFile('index.html', { root: path.join(serverDirectory, 'public') });
|
| 203 |
+
});
|
| 204 |
+
|
| 205 |
+
// Callback endpoint for OAuth PKCE flows (e.g. OpenRouter)
|
| 206 |
+
app.get('/callback/:source?', (request, response) => {
|
| 207 |
+
const source = request.params.source;
|
| 208 |
+
const query = request.url.split('?')[1];
|
| 209 |
+
const searchParams = new URLSearchParams();
|
| 210 |
+
source && searchParams.set('source', source);
|
| 211 |
+
query && searchParams.set('query', query);
|
| 212 |
+
const path = `/?${searchParams.toString()}`;
|
| 213 |
+
return response.redirect(307, path);
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
// Host login page
|
| 217 |
+
app.get('/login', loginPageMiddleware);
|
| 218 |
+
|
| 219 |
+
// Host frontend assets
|
| 220 |
+
const webpackMiddleware = getWebpackServeMiddleware();
|
| 221 |
+
app.use(webpackMiddleware);
|
| 222 |
+
app.use(express.static(path.join(serverDirectory, 'public'), {}));
|
| 223 |
+
|
| 224 |
+
// Public API
|
| 225 |
+
app.use('/api/users', usersPublicRouter);
|
| 226 |
+
|
| 227 |
+
// Everything below this line requires authentication
|
| 228 |
+
app.use(requireLoginMiddleware);
|
| 229 |
+
app.post('/api/ping', (request, response) => {
|
| 230 |
+
if (request.query.extend && request.session) {
|
| 231 |
+
request.session.touch = Date.now();
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
response.sendStatus(204);
|
| 235 |
+
});
|
| 236 |
+
|
| 237 |
+
// File uploads
|
| 238 |
+
const uploadsPath = path.join(cliArgs.dataRoot, UPLOADS_DIRECTORY);
|
| 239 |
+
app.use(multer({ dest: uploadsPath, limits: { fieldSize: 500 * 1024 * 1024 } }).single('avatar'));
|
| 240 |
+
app.use(multerMonkeyPatch);
|
| 241 |
+
|
| 242 |
+
app.get('/version', async function (_, response) {
|
| 243 |
+
const data = await getVersion();
|
| 244 |
+
response.send(data);
|
| 245 |
+
});
|
| 246 |
+
|
| 247 |
+
redirectDeprecatedEndpoints(app);
|
| 248 |
+
setupPrivateEndpoints(app);
|
| 249 |
+
|
| 250 |
+
/**
|
| 251 |
+
* Tasks that need to be run before the server starts listening.
|
| 252 |
+
* @returns {Promise<void>}
|
| 253 |
+
*/
|
| 254 |
+
async function preSetupTasks() {
|
| 255 |
+
const version = await getVersion();
|
| 256 |
+
|
| 257 |
+
// Print formatted header
|
| 258 |
+
console.log();
|
| 259 |
+
console.log(`SillyTavern ${version.pkgVersion}`);
|
| 260 |
+
if (version.gitBranch && version.commitDate) {
|
| 261 |
+
const date = new Date(version.commitDate);
|
| 262 |
+
const localDate = date.toLocaleString('en-US', { timeZoneName: 'short' });
|
| 263 |
+
console.log(`Running '${version.gitBranch}' (${version.gitRevision}) - ${localDate}`);
|
| 264 |
+
if (!version.isLatest && ['staging', 'release'].includes(version.gitBranch)) {
|
| 265 |
+
console.log('INFO: Currently not on the latest commit.');
|
| 266 |
+
console.log(' Run \'git pull\' to update. If you have any merge conflicts, run \'git reset --hard\' and \'git pull\' to reset your branch.');
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
console.log();
|
| 270 |
+
|
| 271 |
+
const directories = await getUserDirectoriesList();
|
| 272 |
+
await checkForNewContent(directories);
|
| 273 |
+
await ensureThumbnailCache(directories);
|
| 274 |
+
await diskCache.verify(directories);
|
| 275 |
+
migrateFlatSecrets(directories);
|
| 276 |
+
cleanUploads();
|
| 277 |
+
migrateAccessLog();
|
| 278 |
+
|
| 279 |
+
await settingsInit();
|
| 280 |
+
await statsInit();
|
| 281 |
+
|
| 282 |
+
const pluginsDirectory = path.join(serverDirectory, 'plugins');
|
| 283 |
+
const cleanupPlugins = await loadPlugins(app, pluginsDirectory);
|
| 284 |
+
const consoleTitle = process.title;
|
| 285 |
+
|
| 286 |
+
let isExiting = false;
|
| 287 |
+
const exitProcess = async () => {
|
| 288 |
+
if (isExiting) return;
|
| 289 |
+
isExiting = true;
|
| 290 |
+
await statsOnExit();
|
| 291 |
+
if (typeof cleanupPlugins === 'function') {
|
| 292 |
+
await cleanupPlugins();
|
| 293 |
+
}
|
| 294 |
+
diskCache.dispose();
|
| 295 |
+
setWindowTitle(consoleTitle);
|
| 296 |
+
process.exit();
|
| 297 |
+
};
|
| 298 |
+
|
| 299 |
+
// Set up event listeners for a graceful shutdown
|
| 300 |
+
process.on('SIGINT', exitProcess);
|
| 301 |
+
process.on('SIGTERM', exitProcess);
|
| 302 |
+
process.on('uncaughtException', (err) => {
|
| 303 |
+
console.error('Uncaught exception:', err);
|
| 304 |
+
exitProcess();
|
| 305 |
+
});
|
| 306 |
+
|
| 307 |
+
// Add request proxy.
|
| 308 |
+
initRequestProxy({ enabled: cliArgs.requestProxyEnabled, url: cliArgs.requestProxyUrl, bypass: cliArgs.requestProxyBypass });
|
| 309 |
+
|
| 310 |
+
// Wait for frontend libs to compile
|
| 311 |
+
await webpackMiddleware.runWebpackCompiler();
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
/**
|
| 315 |
+
* Tasks that need to be run after the server starts listening.
|
| 316 |
+
* @param {import('./server-startup.js').ServerStartupResult} result The result of the server startup
|
| 317 |
+
* @returns {Promise<void>}
|
| 318 |
+
*/
|
| 319 |
+
async function postSetupTasks(result) {
|
| 320 |
+
const browserLaunchHostname = await cliArgs.getBrowserLaunchHostname(result);
|
| 321 |
+
const browserLaunchUrl = cliArgs.getBrowserLaunchUrl(browserLaunchHostname);
|
| 322 |
+
const browserLaunchApp = String(getConfigValue('browserLaunch.browser', 'default') ?? '');
|
| 323 |
+
|
| 324 |
+
if (cliArgs.browserLaunchEnabled) {
|
| 325 |
+
try {
|
| 326 |
+
// TODO: This should be converted to a regular import when support for Node 18 is dropped
|
| 327 |
+
const openModule = await import('open');
|
| 328 |
+
const { default: open, apps } = openModule;
|
| 329 |
+
|
| 330 |
+
function getBrowsers() {
|
| 331 |
+
const isAndroid = process.platform === 'android';
|
| 332 |
+
if (isAndroid) {
|
| 333 |
+
return {};
|
| 334 |
+
}
|
| 335 |
+
return {
|
| 336 |
+
'firefox': apps.firefox,
|
| 337 |
+
'chrome': apps.chrome,
|
| 338 |
+
'edge': apps.edge,
|
| 339 |
+
'brave': apps.brave,
|
| 340 |
+
};
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
const validBrowsers = getBrowsers();
|
| 344 |
+
const appName = validBrowsers[browserLaunchApp.trim().toLowerCase()];
|
| 345 |
+
const openOptions = appName ? { app: { name: appName } } : {};
|
| 346 |
+
|
| 347 |
+
console.log(`Launching in a browser: ${browserLaunchApp}...`);
|
| 348 |
+
await open(browserLaunchUrl.toString(), openOptions);
|
| 349 |
+
} catch (error) {
|
| 350 |
+
console.error('Failed to launch the browser. Open the URL manually.', error);
|
| 351 |
+
}
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
setWindowTitle('SillyTavern WebServer');
|
| 355 |
+
|
| 356 |
+
let logListen = 'SillyTavern is listening on';
|
| 357 |
+
|
| 358 |
+
if (result.useIPv6 && !result.v6Failed) {
|
| 359 |
+
logListen += color.green(
|
| 360 |
+
' IPv6: ' + cliArgs.getIPv6ListenUrl().host,
|
| 361 |
+
);
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
if (result.useIPv4 && !result.v4Failed) {
|
| 365 |
+
logListen += color.green(
|
| 366 |
+
' IPv4: ' + cliArgs.getIPv4ListenUrl().host,
|
| 367 |
+
);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
const goToLog = `Go to: ${color.blue(browserLaunchUrl)} to open SillyTavern`;
|
| 371 |
+
const plainGoToLog = removeColorFormatting(goToLog);
|
| 372 |
+
|
| 373 |
+
console.log(logListen);
|
| 374 |
+
if (cliArgs.listen) {
|
| 375 |
+
console.log();
|
| 376 |
+
console.log('To limit connections to internal localhost only ([::1] or 127.0.0.1), change the setting in config.yaml to "listen: false".');
|
| 377 |
+
console.log('Check the "access.log" file in the data directory to inspect incoming connections:', color.green(getAccessLogPath()));
|
| 378 |
+
}
|
| 379 |
+
console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
|
| 380 |
+
console.log(goToLog);
|
| 381 |
+
console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
|
| 382 |
+
|
| 383 |
+
setupLogLevel();
|
| 384 |
+
serverEvents.emit(EVENT_NAMES.SERVER_STARTED, { url: browserLaunchUrl });
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
/**
|
| 388 |
+
* Registers a not-found error response if a not-found error page exists. Should only be called after all other middlewares have been registered.
|
| 389 |
+
*/
|
| 390 |
+
function apply404Middleware() {
|
| 391 |
+
const notFoundWebpage = safeReadFileSync(path.join(serverDirectory, 'public/error/url-not-found.html')) ?? '';
|
| 392 |
+
app.use((req, res) => {
|
| 393 |
+
res.status(404).send(notFoundWebpage);
|
| 394 |
+
});
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
/**
|
| 398 |
+
* Sets the DNS resolution order based on the command line arguments.
|
| 399 |
+
*/
|
| 400 |
+
function setDnsResolutionOrder() {
|
| 401 |
+
try {
|
| 402 |
+
if (cliArgs.dnsPreferIPv6) {
|
| 403 |
+
dns.setDefaultResultOrder('ipv6first');
|
| 404 |
+
console.log('Preferring IPv6 for DNS resolution');
|
| 405 |
+
} else {
|
| 406 |
+
dns.setDefaultResultOrder('ipv4first');
|
| 407 |
+
console.log('Preferring IPv4 for DNS resolution');
|
| 408 |
+
}
|
| 409 |
+
} catch (error) {
|
| 410 |
+
console.warn('Failed to set DNS resolution order. Possibly unsupported in this Node version.');
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
// User storage module needs to be initialized before starting the server
|
| 415 |
+
initUserStorage(globalThis.DATA_ROOT)
|
| 416 |
+
.then(setDnsResolutionOrder)
|
| 417 |
+
.then(ensurePublicDirectoriesExist)
|
| 418 |
+
.then(migrateUserData)
|
| 419 |
+
.then(migrateSystemPrompts)
|
| 420 |
+
.then(verifySecuritySettings)
|
| 421 |
+
.then(preSetupTasks)
|
| 422 |
+
.then(apply404Middleware)
|
| 423 |
+
.then(() => new ServerStartup(app, cliArgs).start())
|
| 424 |
+
.then(postSetupTasks);
|