Allow read-only installation Fix #3453. Thanks to #3499, #3500 and #3521, most of the obstacles to read-only installation have been resolved. This PR addresses the final piece, ensuring that SillyTavern no longer changes directories to `serverDirectory` and outputs files there. Instead, it outputs or copies necessary files to the directory where it is being run. Now, `serverDirectory` is read-only for SillyTavern (i.e., SillyTavern will not attempt to modify `serverDirectory`). Additionally, this PR sets the permissions for copied `default-user` files to be writable, so even if SillyTavern is installed as read-only, the copied `default-user` folder can still be modified.

bf97686dfc99a1b01d10b043b794dd5626083f23

wrvsrx <wrvsrx@outlook.com>

Signed
9 files changed, +55 -73Ignore whitespace
post-install.js+1 -47
@@ -3,7 +3,6 @@
33 */
44import fs from 'node:fs';
55import path from 'node:path';
6-import crypto from 'node:crypto';
76import process from 'node:process';
87import yaml from 'yaml';
98import _ from 'lodash';
@@ -283,57 +282,12 @@ function createDefaultFiles() {
283282 }
284283}
285284
286-/**
287- * Returns the MD5 hash of the given data.
288- * @param {Buffer} data Input data
289- * @returns {string} MD5 hash of the input data
290- */
291-function getMd5Hash(data) {
292- return crypto
293- .createHash('md5')
294- .update(new Uint8Array(data))
295- .digest('hex');
296-}
297-
298-/**
299- * Copies the WASM binaries from the sillytavern-transformers package to the dist folder.
300- */
301-function copyWasmFiles() {
302- if (!fs.existsSync('./dist')) {
303- fs.mkdirSync('./dist');
304- }
305-
306- const listDir = fs.readdirSync('./node_modules/sillytavern-transformers/dist');
307-
308- for (const file of listDir) {
309- if (file.endsWith('.wasm')) {
310- const sourcePath = `./node_modules/sillytavern-transformers/dist/${file}`;
311- const targetPath = `./dist/${file}`;
312-
313- // Don't copy if the file already exists and is the same checksum
314- if (fs.existsSync(targetPath)) {
315- const sourceChecksum = getMd5Hash(fs.readFileSync(sourcePath));
316- const targetChecksum = getMd5Hash(fs.readFileSync(targetPath));
317-
318- if (sourceChecksum === targetChecksum) {
319- continue;
320- }
321- }
322-
323- fs.copyFileSync(sourcePath, targetPath);
324- console.log(`${file} successfully copied to ./dist/${file}`);
325- }
326- }
327-}
328-
329285try {
330286 // 0. Convert config.conf to config.yaml
331287 convertConfig();
332288 // 1. Create default config files
333289 createDefaultFiles();
334290 // 2. Copy transformers WASMAdd binariesmissing fromconfig node_modulesvalues
335- copyWasmFiles();
336- // 3. Add missing config values
337291 addMissingConfigValues();
338292} catch (error) {
339293 console.error(error);
server.js+4 -7
@@ -6,7 +6,6 @@ import util from 'node:util';
66import net from 'node:net';
77import dns from 'node:dns';
88import process from 'node:process';
9-import { fileURLToPath } from 'node:url';
109
1110import cors from 'cors';
1211import { csrfSync } from 'csrf-sync';
@@ -60,6 +59,7 @@ import {
6059} from './src/util.js';
6160import { UPLOADS_DIRECTORY } from './src/constants.js';
6261import { ensureThumbnailCache } from './src/endpoints/thumbnails.js';
62+import { serverDirectory } from './src/server-directory.js';
6363
6464// Routers
6565import { router as usersPublicRouter } from './src/endpoints/users-public.js';
@@ -74,10 +74,7 @@ util.inspect.defaultOptions.maxArrayLength = null;
7474util.inspect.defaultOptions.maxStringLength = null;
7575util.inspect.defaultOptions.depth = 4;
7676
77-// Set a working directory for the server
78-const serverDirectory = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
7977console.log(`Node version: ${process.version}. Running in ${process.env.NODE_ENV} environment. Server directory: ${serverDirectory}`);
80-process.chdir(serverDirectory);
8178
8279// Work around a node v20.0.0, v20.1.0, and v20.2.0 bug. The issue was fixed in v20.3.0.
8380// https://github.com/nodejs/node/issues/47822#issuecomment-1564708870
@@ -211,7 +208,7 @@ app.get('/', getCacheBusterMiddleware(), (request, response) => {
211208 return response.redirect(redirectUrl);
212209 }
213210
214211 return response.sendFile('index.html', { root: path.join(process.cwd()serverDirectory, 'public') });
215212});
216213
217214// Callback endpoint for OAuth PKCE flows (e.g. OpenRouter)
@@ -231,7 +228,7 @@ app.get('/login', loginPageMiddleware);
231228// Host frontend assets
232229const webpackMiddleware = getWebpackServeMiddleware();
233230app.use(webpackMiddleware);
234231app.use(express.static(processpath.cwdjoin() +serverDirectory, '/public'), {}));
235232
236233// Public API
237234app.use('/api/users', usersPublicRouter);
@@ -375,7 +372,7 @@ async function postSetupTasks(result) {
375372 * Registers a not-found error response if a not-found error page exists. Should only be called after all other middlewares have been registered.
376373 */
377374function apply404Middleware() {
378375 const notFoundWebpage = safeReadFileSync('path./join(serverDirectory, 'public/error/url-not-found.html')) ?? '';
379376 app.use((req, res) => {
380377 res.status(404).send(notFoundWebpage);
381378 });
src/endpoints/content-manager.js+27 -3
@@ -1,6 +1,5 @@
11import fs from 'node:fs';
22import path from 'node:path';
3-import process from 'node:process';
43import { Buffer } from 'node:buffer';
54
65import express from 'express';
@@ -10,9 +9,10 @@ import { sync as writeFileAtomicSync } from 'write-file-atomic';
109
1110import { getConfigValue, color } from '../util.js';
1211import { write } from '../character-card-parser.js';
12+import { serverDirectory } from '../server-directory.js';
1313
1414const contentDirectory = path.join(process.cwd()serverDirectory, 'default/content');
1515const scaffoldDirectory = path.join(process.cwd()serverDirectory, 'default/scaffold');
1616const contentIndexPath = path.join(contentDirectory, 'index.json');
1717const scaffoldIndexPath = path.join(scaffoldDirectory, 'index.json');
1818
@@ -149,6 +149,30 @@ async function seedContentForUser(contentIndex, directories, forceCategories) {
149149 }
150150
151151 fs.cpSync(contentPath, targetPath, { recursive: true, force: false });
152+ function setPermissionsSync(targetPath_) {
153+
154+ function appendWritablePermission(filepath, stats) {
155+ const currentMode = stats.mode;
156+ const newMode = currentMode | 0o200;
157+ if (newMode != currentMode) {
158+ fs.chmodSync(filepath, newMode);
159+ }
160+ }
161+
162+ const stats = fs.statSync(targetPath_);
163+
164+ if (stats.isDirectory()) {
165+ appendWritablePermission(targetPath_, stats);
166+ const files = fs.readdirSync(targetPath_);
167+
168+ files.forEach((file) => {
169+ setPermissionsSync(path.join(targetPath_, file));
170+ });
171+ } else {
172+ appendWritablePermission(targetPath_, stats);
173+ }
174+ }
175+ setPermissionsSync(targetPath);
152176 console.info(`Content file ${contentItem.filename} copied to ${contentTarget}`);
153177 anyContentAdded = true;
154178 }
src/fetch-patch.js+4 -4
@@ -2,6 +2,7 @@ import fs from 'node:fs';
22import path from 'node:path';
33import { fileURLToPath } from 'node:url';
44import mime from 'mime-types';
5+import { serverDirectory } from './server-directory.js';
56
67const originalFetch = globalThis.fetch;
78
@@ -67,10 +68,9 @@ globalThis.fetch = async (/** @type {string | URL | Request} */ request, /** @ty
6768 }
6869 const url = getRequestURL(request);
6970 const filePath = path.resolve(fileURLToPath(url));
70- const cwd = path.resolve(process.cwd()) + path.sep;
71+ const isUnderServerDirectory = isPathUnderParent(serverDirectory, filePath);
71- const isUnderCwd = isPathUnderParent(cwd, filePath);
72+ if (!isUnderServerDirectory) {
72- if (!isUnderCwd) {
73+ throw new Error('Requested file path is outside of the server directory.');
73- throw new Error('Requested file path is outside of the current working directory.');
7474 }
7575 const parsedPath = path.parse(filePath);
7676 if (!ALLOWED_EXTENSIONS.includes(parsedPath.ext)) {
src/server-directory.js+3 -0
@@ -0,0 +1,3 @@
1+import path from 'node:path';
2+import { fileURLToPath } from 'node:url';
3+export const serverDirectory = path.dirname(import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url)));
src/transformers.js+3 -1
@@ -5,14 +5,16 @@ import { Buffer } from 'node:buffer';
55
66import { pipeline, env, RawImage } from 'sillytavern-transformers';
77import { getConfigValue } from './util.js';
8+import { serverDirectory } from './server-directory.js';
89
910configureTransformers();
1011
1112function configureTransformers() {
1213 // Limit the number of threads to 1 to avoid issues on Android
1314 env.backends.onnx.wasm.numThreads = 1;
15+ console.log(env.backends.onnx.wasm.wasmPaths);
1416 // Use WASM from a local folder to avoid CDN connections
1517 env.backends.onnx.wasm.wasmPaths = path.join(process.cwd()serverDirectory, 'node_modules', 'sillytavern-transformers', 'dist') + path.sep;
1618}
1719
1820const tasks = {
src/users.js+2 -1
@@ -18,6 +18,7 @@ import { USER_DIRECTORY_TEMPLATE, DEFAULT_USER, PUBLIC_DIRECTORIES, SETTINGS_FIL
1818import { getConfigValue, color, delay, generateTimestamp } from './util.js';
1919import { readSecret, writeSecret } from './endpoints/secrets.js';
2020import { getContentOfType } from './endpoints/content-manager.js';
21+import { serverDirectory } from './server-directory.js';
2122
2223export const KEY_PREFIX = 'user:';
2324const AVATAR_PREFIX = 'avatar:';
@@ -905,7 +906,7 @@ export async function loginPageMiddleware(request, response) {
905906 console.error('Error during auto-login:', error);
906907 }
907908
908909 return response.sendFile('login.html', { root: path.join(process.cwd()serverDirectory, 'public') });
909910}
910911
911912/**
src/util.js+9 -9
@@ -17,6 +17,7 @@ import { default as simpleGit } from 'simple-git';
1717import chalk from 'chalk';
1818import { LOG_LEVELS } from './constants.js';
1919import bytes from 'bytes';
20+import { serverDirectory } from './server-directory.js';
2021
2122/**
2223 * Parsed config object.
@@ -121,20 +122,19 @@ export async function getVersion() {
121122
122123 try {
123124 const require = createRequire(import.meta.url);
124125 const pkgJson = require(path.join(process.cwd()serverDirectory, './package.json'));
125126 pkgVersion = pkgJson.version;
126127 if (commandExistsSync('git')) {
127128 const git = simpleGit({ baseDir: serverDirectory });
128- const cwd = process.cwd();
129+ gitRevision = await git.revparse(['--short', 'HEAD']);
129130 gitRevisiongitBranch = await git.cwd(cwd).revparse(['--shortabbrev-ref', 'HEAD']);
130131 gitBranchcommitDate = await git.cwd(cwd).revparseshow(['--abbrev-refs', 'HEAD--format=%ci', gitRevision]);
131- commitDate = await git.cwd(cwd).show(['-s', '--format=%ci', gitRevision]);
132132
133133 const trackingBranch = await git.cwd(cwd).revparse(['--abbrev-ref', '@{u}']);
134134
135135 // Might fail, but exception is caught. Just don't run anything relevant after in this block...
136136 const localLatest = await git.cwd(cwd).revparse(['HEAD']);
137137 const remoteLatest = await git.cwd(cwd).revparse([trackingBranch]);
138138 isLatest = localLatest === remoteLatest;
139139 }
140140 }
webpack.config.js+2 -1
@@ -1,6 +1,7 @@
11import process from 'node:process';
22import path from 'node:path';
33import isDocker from 'is-docker';
4+import { serverDirectory } from './src/server-directory.js';
45
56/**
67 * Get the Webpack configuration for the public/lib.js file.
@@ -40,7 +41,7 @@ export default function getPublicLibConfig(forceDist = false) {
4041
4142 return {
4243 mode: 'production',
4344 entry: 'path./join(serverDirectory, 'public/lib.js'),
4445 cache: {
4546 type: 'filesystem',
4647 cacheDirectory: cacheDirectory,