Nocigar commited on
Commit
78a92e4
1 Parent(s): 40569f1

Upload 26 files

Browse files
Files changed (26) hide show
  1. .dockerignore +14 -0
  2. .editorconfig +14 -0
  3. .eslintrc.js +92 -0
  4. .gitignore +51 -0
  5. .nomedia +0 -0
  6. .npmignore +13 -0
  7. .replit +81 -0
  8. CONTRIBUTING.md +41 -0
  9. Dockerfile +45 -0
  10. LICENSE +661 -0
  11. Remote-Link.cmd +18 -0
  12. SECURITY.md +25 -0
  13. Start.bat +7 -0
  14. Update-Instructions.txt +75 -0
  15. UpdateAndStart.bat +18 -0
  16. UpdateForkAndStart.bat +103 -0
  17. index.d.ts +25 -0
  18. jsconfig.json +25 -0
  19. package-lock.json +0 -0
  20. package.json +97 -0
  21. plugins.js +75 -0
  22. post-install.js +181 -0
  23. recover.js +62 -0
  24. replit.nix +8 -0
  25. server.js +910 -0
  26. start.sh +32 -0
.dockerignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ .vscode
4
+ node_modules
5
+ npm-debug.log
6
+ readme*
7
+ Start.bat
8
+ /dist
9
+ /backups
10
+ cloudflared.exe
11
+ access.log
12
+ /data
13
+ /cache
14
+ .DS_Store
.editorconfig ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ end_of_line = lf
5
+ insert_final_newline = true
6
+ trim_trailing_whitespace = true
7
+
8
+ [*.{js, conf, json, css, less, html}]
9
+ charset = utf-8
10
+ indent_style = space
11
+ indent_size = 4
12
+
13
+ [*.md]
14
+ trim_trailing_whitespace = false
.eslintrc.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ ],
6
+ env: {
7
+ es6: true,
8
+ },
9
+ parserOptions: {
10
+ ecmaVersion: 'latest',
11
+ },
12
+ overrides: [
13
+ {
14
+ // Server-side files (plus this configuration file)
15
+ files: ['src/**/*.js', './*.js', 'plugins/**/*.js'],
16
+ env: {
17
+ node: true,
18
+ },
19
+ },
20
+ {
21
+ files: ['src/**/*.mjs'],
22
+ parserOptions: {
23
+ sourceType: 'module',
24
+ },
25
+ env: {
26
+ node: true,
27
+ },
28
+ },
29
+ {
30
+ // Browser-side files
31
+ files: ['public/**/*.js'],
32
+ env: {
33
+ browser: true,
34
+ jquery: true,
35
+ },
36
+ parserOptions: {
37
+ sourceType: 'module',
38
+ },
39
+ // These scripts are loaded in HTML; tell ESLint not to complain about them being undefined
40
+ globals: {
41
+ DOMPurify: 'readonly',
42
+ droll: 'readonly',
43
+ Fuse: 'readonly',
44
+ Handlebars: 'readonly',
45
+ hljs: 'readonly',
46
+ localforage: 'readonly',
47
+ moment: 'readonly',
48
+ pdfjsLib: 'readonly',
49
+ Popper: 'readonly',
50
+ showdown: 'readonly',
51
+ showdownKatex: 'readonly',
52
+ SVGInject: 'readonly',
53
+ toastr: 'readonly',
54
+ Readability: 'readonly',
55
+ isProbablyReaderable: 'readonly',
56
+ ePub: 'readonly',
57
+ diff_match_patch: 'readonly',
58
+ SillyTavern: 'readonly',
59
+ },
60
+ },
61
+ ],
62
+ // There are various vendored libraries that shouldn't be linted
63
+ ignorePatterns: [
64
+ 'public/lib/**/*',
65
+ '*.min.js',
66
+ 'src/ai_horde/**/*',
67
+ 'plugins/**/*',
68
+ 'data/**/*',
69
+ 'backups/**/*',
70
+ 'node_modules/**/*',
71
+ ],
72
+ rules: {
73
+ 'no-unused-vars': ['error', { args: 'none' }],
74
+ 'no-control-regex': 'off',
75
+ 'no-constant-condition': ['error', { checkLoops: false }],
76
+ 'require-yield': 'off',
77
+ 'quotes': ['error', 'single'],
78
+ 'semi': ['error', 'always'],
79
+ 'indent': ['error', 4, { SwitchCase: 1, FunctionDeclaration: { parameters: 'first' } }],
80
+ 'comma-dangle': ['error', 'always-multiline'],
81
+ 'eol-last': ['error', 'always'],
82
+ 'no-trailing-spaces': 'error',
83
+ 'object-curly-spacing': ['error', 'always'],
84
+ 'space-infix-ops': 'error',
85
+ 'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
86
+ 'no-cond-assign': 'error',
87
+
88
+ // These rules should eventually be enabled.
89
+ 'no-async-promise-executor': 'off',
90
+ 'no-inner-declarations': 'off',
91
+ },
92
+ };
.gitignore ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ public/chats/
3
+ public/characters/
4
+ public/User Avatars/
5
+ public/backgrounds/
6
+ public/groups/
7
+ public/group chats/
8
+ public/worlds/
9
+ public/user/
10
+ public/css/bg_load.css
11
+ public/themes/
12
+ public/OpenAI Settings/
13
+ public/KoboldAI Settings/
14
+ public/NovelAI Settings/
15
+ public/TextGen Settings/
16
+ public/instruct/
17
+ public/context/
18
+ public/scripts/extensions/third-party/
19
+ public/stats.json
20
+ /uploads/
21
+ *.jsonl
22
+ /config.conf
23
+ /config.yaml
24
+ /config.conf.bak
25
+ /docker/config
26
+ /docker/user
27
+ /docker/extensions
28
+ /docker/data
29
+ .DS_Store
30
+ public/settings.json
31
+ /thumbnails
32
+ whitelist.txt
33
+ .vscode/**
34
+ !.vscode/extensions.json
35
+ .idea/
36
+ secrets.json
37
+ /dist
38
+ /backups/
39
+ public/movingUI/
40
+ public/QuickReplies/
41
+ content.log
42
+ cloudflared.exe
43
+ public/assets/
44
+ access.log
45
+ /vectors/
46
+ /cache/
47
+ public/css/user.css
48
+ /plugins/
49
+ /data
50
+ /default/scaffold
51
+ public/scripts/extensions/third-party
.nomedia ADDED
File without changes
.npmignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ /uploads/
3
+ .DS_Store
4
+ /thumbnails
5
+ secrets.json
6
+ /dist
7
+ /backups/
8
+ /data
9
+ /cache
10
+ access.log
11
+ .github
12
+ .vscode
13
+ .git
.replit ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ hidden = [".config", "package-lock.json"]
3
+ run = "chmod 755 ./start.sh && ./start.sh"
4
+ entrypoint = "server.js"
5
+
6
+ [[hints]]
7
+ regex = "Error \\[ERR_REQUIRE_ESM\\]"
8
+ message = "We see that you are using require(...) inside your code. We currently do not support this syntax. Please use 'import' instead when using external modules. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)"
9
+
10
+ [nix]
11
+ channel = "stable-22_11"
12
+
13
+ [env]
14
+ XDG_CONFIG_HOME = "/home/runner/$REPL_SLUG/.config"
15
+ PATH = "/home/runner/$REPL_SLUG/.config/npm/node_global/bin:/home/runner/$REPL_SLUG/node_modules/.bin"
16
+ npm_config_prefix = "/home/runner/$REPL_SLUG/.config/npm/node_global"
17
+
18
+ [gitHubImport]
19
+ requiredFiles = [".replit", "replit.nix", ".config", "package.json", "package-lock.json"]
20
+
21
+ [packager]
22
+ language = "nodejs"
23
+
24
+ [packager.features]
25
+ packageSearch = true
26
+ guessImports = true
27
+ enabledForHosting = false
28
+
29
+ [unitTest]
30
+ language = "nodejs"
31
+
32
+ [debugger]
33
+ support = true
34
+
35
+ [debugger.interactive]
36
+ transport = "localhost:0"
37
+ startCommand = [ "dap-node" ]
38
+
39
+ [debugger.interactive.initializeMessage]
40
+ command = "initialize"
41
+ type = "request"
42
+
43
+ [debugger.interactive.initializeMessage.arguments]
44
+ clientID = "replit"
45
+ clientName = "replit.com"
46
+ columnsStartAt1 = true
47
+ linesStartAt1 = true
48
+ locale = "en-us"
49
+ pathFormat = "path"
50
+ supportsInvalidatedEvent = true
51
+ supportsProgressReporting = true
52
+ supportsRunInTerminalRequest = true
53
+ supportsVariablePaging = true
54
+ supportsVariableType = true
55
+
56
+ [debugger.interactive.launchMessage]
57
+ command = "launch"
58
+ type = "request"
59
+
60
+ [debugger.interactive.launchMessage.arguments]
61
+ args = []
62
+ console = "externalTerminal"
63
+ cwd = "."
64
+ environment = []
65
+ pauseForSourceMap = false
66
+ program = "./server.js"
67
+ request = "launch"
68
+ sourceMaps = true
69
+ stopOnEntry = false
70
+ type = "pwa-node"
71
+
72
+ [languages]
73
+
74
+ [languages.javascript]
75
+ pattern = "**/{*.js,*.jsx,*.ts,*.tsx,*.json}"
76
+
77
+ [languages.javascript.languageServer]
78
+ start = "typescript-language-server --stdio"
79
+
80
+ [deployment]
81
+ run = ["sh", "-c", "./start.sh"]
CONTRIBUTING.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to contribute to SillyTavern
2
+
3
+ ## Setting up the dev environment
4
+
5
+ 1. Required software: git and node.
6
+ 2. Recommended editor: Visual Studio Code.
7
+ 3. You can also use GitHub Codespaces which sets up everything for you.
8
+
9
+ ## Getting the code ready
10
+
11
+ 1. Register a GitHub account.
12
+ 2. Fork this repository under your account.
13
+ 3. Clone the fork onto your machine.
14
+ 4. Open the cloned repository in the code editor.
15
+ 5. Create a git branch (recommended).
16
+ 6. Make your changes and test them locally.
17
+ 7. Commit the changes and push the branch to the remote repo.
18
+ 8. Go to GitHub, and open a pull request, targeting the upstream branch.
19
+
20
+ ## Contribution guidelines
21
+
22
+ 1. Our standards are pretty low, but make sure the code is not too ugly:
23
+ - Run VS Code's autoformat when you're done.
24
+ - Check with ESLint by running `npm run lint`, then fix the errors.
25
+ - Use common sense and follow existing naming conventions.
26
+ 2. Create pull requests for the staging branch, 99% of contributions should go there. That way people could test your code before the next stable release.
27
+ 3. You can still send a pull request for release in the following scenarios:
28
+ - Updating README.
29
+ - Updating GitHub Actions.
30
+ - Hotfixing a critical bug.
31
+ 4. Project maintainers will test and can change your code before merging.
32
+ 5. Write at least somewhat meaningful PR descriptions. There's no "right" way to do it, but the following may help with outlining a general structure:
33
+ - What is the reason for a change?
34
+ - What did you do to achieve this?
35
+ - How would a reviewer test the change?
36
+ 6. Mind the license. Your contributions will be licensed under the GNU Affero General Public License. If you don't know what that implies, consult your lawyer.
37
+
38
+ ## Further reading
39
+
40
+ 1. [How to write UI extensions](https://docs.sillytavern.app/for-contributors/writing-extensions/)
41
+ 2. [How to write server plugins](https://docs.sillytavern.app/for-contributors/server-plugins)
Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:lts-alpine3.18
2
+
3
+ # Arguments
4
+ ARG APP_HOME=/home/node/app
5
+
6
+ # Install system dependencies
7
+ RUN apk add gcompat tini git
8
+
9
+ # Ensure proper handling of kernel signals
10
+ ENTRYPOINT [ "tini", "--" ]
11
+
12
+ # Create app directory
13
+ WORKDIR ${APP_HOME}
14
+
15
+ # Set NODE_ENV to production
16
+ ENV NODE_ENV=production
17
+
18
+ # Install app dependencies
19
+ COPY package*.json post-install.js ./
20
+ RUN \
21
+ echo "*** Install npm packages ***" && \
22
+ npm i --no-audit --no-fund --quiet --omit=dev && npm cache clean --force
23
+
24
+ # Bundle app source
25
+ COPY . ./
26
+
27
+ # Copy default chats, characters and user avatars to <folder>.default folder
28
+ RUN \
29
+ rm -f "config.yaml" || true && \
30
+ ln -s "./config/config.yaml" "config.yaml" || true && \
31
+ mkdir "config" || true
32
+
33
+ # Cleanup unnecessary files
34
+ RUN \
35
+ echo "*** Cleanup ***" && \
36
+ mv "./docker/docker-entrypoint.sh" "./" && \
37
+ rm -rf "./docker" && \
38
+ echo "*** Make docker-entrypoint.sh executable ***" && \
39
+ chmod +x "./docker-entrypoint.sh" && \
40
+ echo "*** Convert line endings to Unix format ***" && \
41
+ dos2unix "./docker-entrypoint.sh"
42
+
43
+ EXPOSE 8000
44
+
45
+ CMD [ "./docker-entrypoint.sh" ]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
Remote-Link.cmd ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo ========================================================================================================================
3
+ echo WARNING: Cloudflare Tunnel!
4
+ echo ========================================================================================================================
5
+ echo This script downloads and runs the latest cloudflared.exe from Cloudflare to set up an HTTPS tunnel to your SillyTavern!
6
+ echo Using the randomly generated temporary tunnel URL, anyone can access your SillyTavern over the Internet while the tunnel
7
+ echo is active. Keep the URL safe and secure your SillyTavern installation by setting a username and password in config.yaml!
8
+ echo.
9
+ echo See https://docs.sillytavern.app/usage/remoteconnections/ for more details about how to secure your SillyTavern install.
10
+ echo.
11
+ echo By continuing you confirm that you're aware of the potential dangers of having a tunnel open and take all responsibility
12
+ echo to properly use and secure it!
13
+ echo.
14
+ echo To abort, press Ctrl+C or close this window now!
15
+ echo.
16
+ pause
17
+ if not exist cloudflared.exe curl -Lo cloudflared.exe https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe
18
+ cloudflared.exe tunnel --url localhost:8000
SECURITY.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ We take the security of this project seriously. If you discover any security vulnerabilities or have concerns regarding the security of this repository, please reach out to us immediately. We appreciate your efforts in responsibly disclosing the issue and will make every effort to address it promptly.
4
+
5
+ ## Reporting a Vulnerability
6
+
7
+ To report a security vulnerability, please follow these steps:
8
+
9
+ 1. Go to the **Security** tab of this repository on GitHub.
10
+ 2. Click on **"Report a vulnerability"**.
11
+ 3. Provide a clear description of the vulnerability and its potential impact. Be as detailed as possible.
12
+ 4. If applicable, include steps or a PoC (Proof of Concept) to reproduce the vulnerability.
13
+ 5. Submit the report.
14
+
15
+ Once we receive the private report notification, we will promptly investigate and assess the reported vulnerability.
16
+
17
+ Please do not disclose any potential vulnerabilities in public repositories, issue trackers, or forums until we have had a chance to review and address the issue.
18
+
19
+ ## Scope
20
+
21
+ This security policy applies to all the code and files within this repository and its dependencies actively maintained by us. If you encounter a security issue in a dependency that is not directly maintained by us, please follow responsible disclosure practices and report it to the respective project.
22
+
23
+ While we strive to ensure the security of this project, please note that there may be limitations on resources, response times, and mitigations.
24
+
25
+ Thank you for your help in making this project more secure.
Start.bat ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ pushd %~dp0
3
+ set NODE_ENV=production
4
+ call npm install --no-audit --no-fund --quiet --omit=dev
5
+ node server.js %*
6
+ pause
7
+ popd
Update-Instructions.txt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ How to Update SillyTavern
2
+
3
+ The most recent version can be found here: https://docs.sillytavern.app/usage/update/
4
+
5
+ This is not an installation guide. If you need installation instructions, look here:
6
+ https://docs.sillytavern.app/installation/windows/
7
+
8
+ This guide assumes you have already installed SillyTavern once, and know how to run it on your OS.
9
+
10
+ Linux/Termux:
11
+
12
+ You definitely installed via git, so just 'git pull' inside the SillyTavern directory.
13
+
14
+ Windows/MacOS:
15
+
16
+ Method 1 - GIT
17
+
18
+ We always recommend users install using 'git'. Here's why:
19
+
20
+ When you have installed via `git clone`, all you have to do to update is type `git pull` in a command line in the ST folder.
21
+ You can also try running the 'UpdateAndStart.bat' file, which will almost do the same thing. (Windows only)
22
+ Alternatively, if the command prompt gives you problems (and you have GitHub Desktop installed), you can use the 'Repository' menu and select 'Pull'.
23
+ The updates are applied automatically and safely.
24
+
25
+ If you are a developer and use a fork of ST or switch branches regularly, you can use the 'UpdateForkAndStart.bat', which works similarly to 'UpdateAndStart.bat',
26
+ but automatically pulls changes into your fork and handles switched branches gracefully by asking if you want to switch back.
27
+
28
+ Method 2 - ZIP
29
+
30
+ If you insist on installing via a zip, here is the tedious process for doing the update:
31
+
32
+ 1. Download the new release zip.
33
+ 2. Unzip it into a folder OUTSIDE of your current ST installation.
34
+ 3. Do the usual setup procedure for your OS to install the NodeJS requirements.
35
+
36
+ 4a. Updating 1.12.0 and above
37
+
38
+ Copy the user data directory from your data root into the data root of the new install.
39
+
40
+ By default: /data/default-user
41
+
42
+ 4a. Migrating from <1.12.0 to >=1.20.0
43
+ Copy the following files/folders as necessary(*) from your old ST installation:
44
+
45
+ - Assets
46
+ - Backgrounds
47
+ - Characters
48
+ - Chats
49
+ - Context
50
+ - Groups
51
+ - Group chats
52
+ - Instruct
53
+ - movingUI
54
+ - KoboldAI Settings
55
+ - NovelAI Settings
56
+ - OpenAI Settings (Chat Completion API)
57
+ - TextGen Settings (Text Completion API)
58
+ - QuickReplies
59
+ - Themes
60
+ - User Avatars
61
+ - Worlds
62
+ - User
63
+ - settings.json
64
+ - secrets.json <---- This one is in the base folder, not /public/
65
+
66
+ (*) 'As necessary' = "If you made any custom content related to those folders".
67
+ None of the folders are mandatory, so only copy what you need.
68
+
69
+ **NB: DO NOT COPY THE ENTIRE /PUBLIC/ FOLDER.**
70
+ Doing so could break the new install and prevent new features from being present.
71
+ Paste those items into the /data/default-user folder of the new install.
72
+
73
+ 5. Start SillyTavern once again with the method appropriate to your OS, and pray you got it right.
74
+
75
+ 6. If everything shows up, you can safely delete the old ST folder.
UpdateAndStart.bat ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ pushd %~dp0
3
+ git --version > nul 2>&1
4
+ if %errorlevel% neq 0 (
5
+ echo Git is not installed on this system. Skipping update.
6
+ echo If you installed with a zip file, you will need to download the new zip and install it manually.
7
+ ) else (
8
+ call git pull --rebase --autostash
9
+ if %errorlevel% neq 0 (
10
+ REM incase there is still something wrong
11
+ echo There were errors while updating. Please download the latest version manually.
12
+ )
13
+ )
14
+ set NODE_ENV=production
15
+ call npm install --no-audit --no-fund --quiet --omit=dev
16
+ node server.js %*
17
+ pause
18
+ popd
UpdateForkAndStart.bat ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ @setlocal enabledelayedexpansion
3
+ pushd %~dp0
4
+
5
+ echo Checking Git installation
6
+ git --version > nul 2>&1
7
+ if %errorlevel% neq 0 (
8
+ echo Git is not installed on this system. Skipping update.
9
+ echo If you installed with a zip file, you will need to download the new zip and install it manually.
10
+ goto end
11
+ )
12
+
13
+ REM Checking current branch
14
+ FOR /F "tokens=*" %%i IN ('git rev-parse --abbrev-ref HEAD') DO SET CURRENT_BRANCH=%%i
15
+ echo Current branch: %CURRENT_BRANCH%
16
+
17
+ REM Checking for automatic branch switching configuration
18
+ set AUTO_SWITCH=
19
+ FOR /F "tokens=*" %%j IN ('git config --local script.autoSwitch') DO SET AUTO_SWITCH=%%j
20
+
21
+ SET TARGET_BRANCH=%CURRENT_BRANCH%
22
+
23
+ if NOT "!AUTO_SWITCH!"=="" (
24
+ if "!AUTO_SWITCH!"=="s" (
25
+ goto autoswitch-staging
26
+ )
27
+ if "!AUTO_SWITCH!"=="r" (
28
+ goto autoswitch-release
29
+ )
30
+
31
+ if "!AUTO_SWITCH!"=="staging" (
32
+ :autoswitch-staging
33
+ echo Auto-switching to staging branch
34
+ git checkout staging
35
+ SET TARGET_BRANCH=staging
36
+ goto update
37
+ )
38
+ if "!AUTO_SWITCH!"=="release" (
39
+ :autoswitch-release
40
+ echo Auto-switching to release branch
41
+ git checkout release
42
+ SET TARGET_BRANCH=release
43
+ goto update
44
+ )
45
+
46
+ echo Auto-switching defined to stay on current branch
47
+ goto update
48
+ )
49
+
50
+ if "!CURRENT_BRANCH!"=="staging" (
51
+ echo Staying on the current branch
52
+ goto update
53
+ )
54
+ if "!CURRENT_BRANCH!"=="release" (
55
+ echo Staying on the current branch
56
+ goto update
57
+ )
58
+
59
+ echo You are not on 'staging' or 'release'. You are on '!CURRENT_BRANCH!'.
60
+ set /p "CHOICE=Do you want to switch to 'staging' (s), 'release' (r), or stay (any other key)? "
61
+ if /i "!CHOICE!"=="s" (
62
+ echo Switching to staging branch
63
+ git checkout staging
64
+ SET TARGET_BRANCH=staging
65
+ goto update
66
+ )
67
+ if /i "!CHOICE!"=="r" (
68
+ echo Switching to release branch
69
+ git checkout release
70
+ SET TARGET_BRANCH=release
71
+ goto update
72
+ )
73
+
74
+ echo Staying on the current branch
75
+
76
+ :update
77
+ REM Checking for 'upstream' remote
78
+ git remote | findstr "upstream" > nul
79
+ if %errorlevel% equ 0 (
80
+ echo Updating and rebasing against 'upstream'
81
+ git fetch upstream
82
+ git rebase upstream/%TARGET_BRANCH% --autostash
83
+ goto install
84
+ )
85
+
86
+ echo Updating and rebasing against 'origin'
87
+ git pull --rebase --autostash origin %TARGET_BRANCH%
88
+
89
+
90
+ :install
91
+ if %errorlevel% neq 0 (
92
+ echo There were errors while updating. Please check manually.
93
+ goto end
94
+ )
95
+
96
+ echo Installing npm packages and starting server
97
+ set NODE_ENV=production
98
+ call npm install --no-audit --no-fund --quiet --omit=dev
99
+ node server.js %*
100
+
101
+ :end
102
+ pause
103
+ popd
index.d.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { UserDirectoryList, User } from "./src/users";
2
+
3
+ declare global {
4
+ namespace Express {
5
+ export interface Request {
6
+ user: {
7
+ profile: User;
8
+ directories: UserDirectoryList;
9
+ };
10
+ }
11
+ }
12
+
13
+ /**
14
+ * The root directory for user data.
15
+ */
16
+ var DATA_ROOT: string;
17
+ }
18
+
19
+ declare module 'express-session' {
20
+ export interface SessionData {
21
+ handle: string;
22
+ touch: number;
23
+ // other properties...
24
+ }
25
+ }
jsconfig.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "module": "ESNext",
4
+ "target": "ESNext",
5
+ "moduleResolution": "node",
6
+ "strictNullChecks": true,
7
+ "strictFunctionTypes": true,
8
+ "checkJs": true,
9
+ "allowUmdGlobalAccess": true,
10
+ "allowSyntheticDefaultImports": true,
11
+ "resolveJsonModule": true
12
+ },
13
+ "exclude": [
14
+ "node_modules",
15
+ "**/node_modules/*",
16
+ "public/lib",
17
+ "backups/*",
18
+ "data/*",
19
+ "**/dist/*",
20
+ "dist/*",
21
+ "cache/*",
22
+ "src/tokenizers/*",
23
+ "docker/*",
24
+ ]
25
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependencies": {
3
+ "@agnai/sentencepiece-js": "^1.1.1",
4
+ "@agnai/web-tokenizers": "^0.1.3",
5
+ "@zeldafan0225/ai_horde": "^5.1.0",
6
+ "archiver": "^7.0.1",
7
+ "bing-translate-api": "^2.9.1",
8
+ "body-parser": "^1.20.2",
9
+ "command-exists": "^1.2.9",
10
+ "compression": "^1",
11
+ "cookie-parser": "^1.4.6",
12
+ "cookie-session": "^2.1.0",
13
+ "cors": "^2.8.5",
14
+ "csrf-csrf": "^2.2.3",
15
+ "express": "^4.19.2",
16
+ "form-data": "^4.0.0",
17
+ "google-translate-api-browser": "^3.0.1",
18
+ "he": "^1.2.0",
19
+ "helmet": "^7.1.0",
20
+ "iconv-lite": "^0.6.3",
21
+ "ip-matching": "^2.1.2",
22
+ "ipaddr.js": "^2.0.1",
23
+ "jimp": "^0.22.10",
24
+ "lodash": "^4.17.21",
25
+ "mime-types": "^2.1.35",
26
+ "multer": "^1.4.5-lts.1",
27
+ "node-fetch": "^2.6.11",
28
+ "node-persist": "^4.0.1",
29
+ "open": "^8.4.2",
30
+ "png-chunk-text": "^1.0.0",
31
+ "png-chunks-encode": "^1.0.0",
32
+ "png-chunks-extract": "^1.0.0",
33
+ "rate-limiter-flexible": "^5.0.0",
34
+ "response-time": "^2.3.2",
35
+ "sanitize-filename": "^1.6.3",
36
+ "sillytavern-transformers": "2.14.6",
37
+ "simple-git": "^3.19.1",
38
+ "tiktoken": "^1.0.15",
39
+ "vectra": "^0.2.2",
40
+ "wavefile": "^11.0.0",
41
+ "write-file-atomic": "^5.0.1",
42
+ "ws": "^8.17.1",
43
+ "yaml": "^2.3.4",
44
+ "yargs": "^17.7.1",
45
+ "yauzl": "^2.10.0"
46
+ },
47
+ "engines": {
48
+ "node": ">= 18"
49
+ },
50
+ "overrides": {
51
+ "parse-bmfont-xml": {
52
+ "xml2js": "^0.5.0"
53
+ },
54
+ "vectra": {
55
+ "openai": "^4.17.0"
56
+ },
57
+ "load-bmfont": {
58
+ "phin": "^3.7.1"
59
+ },
60
+ "axios": {
61
+ "follow-redirects": "^1.15.4"
62
+ },
63
+ "node-fetch": {
64
+ "whatwg-url": "^14.0.0"
65
+ }
66
+ },
67
+ "name": "sillytavern",
68
+ "type": "commonjs",
69
+ "license": "AGPL-3.0",
70
+ "repository": {
71
+ "type": "git",
72
+ "url": "https://github.com/SillyTavern/SillyTavern.git"
73
+ },
74
+ "version": "1.12.5",
75
+ "scripts": {
76
+ "start": "node server.js",
77
+ "start:no-csrf": "node server.js --disableCsrf",
78
+ "postinstall": "node post-install.js",
79
+ "lint": "eslint \"src/**/*.js\" \"public/**/*.js\" ./*.js",
80
+ "lint:fix": "eslint \"src/**/*.js\" \"public/**/*.js\" ./*.js --fix",
81
+ "plugins:update": "node plugins update",
82
+ "plugins:install": "node plugins install"
83
+ },
84
+ "bin": {
85
+ "sillytavern": "./server.js"
86
+ },
87
+ "rules": {
88
+ "no-path-concat": "off",
89
+ "no-var": "off"
90
+ },
91
+ "main": "server.js",
92
+ "devDependencies": {
93
+ "@types/jquery": "^3.5.29",
94
+ "eslint": "^8.57.0",
95
+ "jquery": "^3.6.4"
96
+ }
97
+ }
plugins.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Plugin manager script.
2
+ // Usage: node plugins.js update
3
+ // More operations coming soon.
4
+ const { default: git } = require('simple-git');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { color } = require('./src/util');
8
+
9
+ const pluginsPath = './plugins';
10
+
11
+ const command = process.argv[2];
12
+
13
+ if (command === 'update') {
14
+ console.log(color.magenta('Updating all plugins'));
15
+ updatePlugins();
16
+ }
17
+
18
+ if (command === 'install') {
19
+ const pluginName = process.argv[3];
20
+ console.log('Installing a new plugin', color.green(pluginName));
21
+ installPlugin(pluginName);
22
+ }
23
+
24
+ async function updatePlugins() {
25
+ const directories = fs.readdirSync(pluginsPath)
26
+ .filter(file => !file.startsWith('.'))
27
+ .filter(file => fs.statSync(path.join(pluginsPath, file)).isDirectory());
28
+
29
+ console.log(`Found ${color.cyan(directories.length)} directories in ./plugins`);
30
+
31
+ for (const directory of directories) {
32
+ try {
33
+ console.log(`Updating plugin ${color.green(directory)}...`);
34
+ const pluginPath = path.join(pluginsPath, directory);
35
+ const pluginRepo = git(pluginPath);
36
+ await pluginRepo.fetch();
37
+ const commitHash = await pluginRepo.revparse(['HEAD']);
38
+ const trackingBranch = await pluginRepo.revparse(['--abbrev-ref', '@{u}']);
39
+ const log = await pluginRepo.log({
40
+ from: commitHash,
41
+ to: trackingBranch,
42
+ });
43
+
44
+ if (log.total === 0) {
45
+ console.log(`Plugin ${color.blue(directory)} is already up to date`);
46
+ continue;
47
+ }
48
+
49
+ await pluginRepo.pull();
50
+ const latestCommit = await pluginRepo.revparse(['HEAD']);
51
+ console.log(`Plugin ${color.green(directory)} updated to commit ${color.cyan(latestCommit)}`);
52
+ } catch (error) {
53
+ console.error(color.red(`Failed to update plugin ${directory}: ${error.message}`));
54
+ }
55
+ }
56
+
57
+ console.log(color.magenta('All plugins updated!'));
58
+
59
+ }
60
+
61
+ async function installPlugin(pluginName) {
62
+ try {
63
+ const pluginPath = path.join(pluginsPath, path.basename(pluginName, '.git'));
64
+
65
+ if (fs.existsSync(pluginPath)) {
66
+ return console.log(color.yellow(`Directory already exists at ${pluginPath}`));
67
+ }
68
+
69
+ await git().clone(pluginName, pluginPath, { '--depth': 1 });
70
+ console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);
71
+ }
72
+ catch (error) {
73
+ console.error(color.red(`Failed to install plugin ${pluginName}`), error);
74
+ }
75
+ }
post-install.js ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Scripts to be done before starting the server for the first time.
3
+ */
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const yaml = require('yaml');
8
+ const _ = require('lodash');
9
+
10
+ /**
11
+ * Colorizes console output.
12
+ */
13
+ const color = {
14
+ byNum: (mess, fgNum) => {
15
+ mess = mess || '';
16
+ fgNum = fgNum === undefined ? 31 : fgNum;
17
+ return '\u001b[' + fgNum + 'm' + mess + '\u001b[39m';
18
+ },
19
+ black: (mess) => color.byNum(mess, 30),
20
+ red: (mess) => color.byNum(mess, 31),
21
+ green: (mess) => color.byNum(mess, 32),
22
+ yellow: (mess) => color.byNum(mess, 33),
23
+ blue: (mess) => color.byNum(mess, 34),
24
+ magenta: (mess) => color.byNum(mess, 35),
25
+ cyan: (mess) => color.byNum(mess, 36),
26
+ white: (mess) => color.byNum(mess, 37),
27
+ };
28
+
29
+ /**
30
+ * Gets all keys from an object recursively.
31
+ * @param {object} obj Object to get all keys from
32
+ * @param {string} prefix Prefix to prepend to all keys
33
+ * @returns {string[]} Array of all keys in the object
34
+ */
35
+ function getAllKeys(obj, prefix = '') {
36
+ if (typeof obj !== 'object' || Array.isArray(obj)) {
37
+ return [];
38
+ }
39
+
40
+ return _.flatMap(Object.keys(obj), key => {
41
+ const newPrefix = prefix ? `${prefix}.${key}` : key;
42
+ if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
43
+ return getAllKeys(obj[key], newPrefix);
44
+ } else {
45
+ return [newPrefix];
46
+ }
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Converts the old config.conf file to the new config.yaml format.
52
+ */
53
+ function convertConfig() {
54
+ if (fs.existsSync('./config.conf')) {
55
+ if (fs.existsSync('./config.yaml')) {
56
+ console.log(color.yellow('Both config.conf and config.yaml exist. Please delete config.conf manually.'));
57
+ return;
58
+ }
59
+
60
+ try {
61
+ console.log(color.blue('Converting config.conf to config.yaml. Your old config.conf will be renamed to config.conf.bak'));
62
+ const config = require(path.join(process.cwd(), './config.conf'));
63
+ fs.copyFileSync('./config.conf', './config.conf.bak');
64
+ fs.rmSync('./config.conf');
65
+ fs.writeFileSync('./config.yaml', yaml.stringify(config));
66
+ console.log(color.green('Conversion successful. Please check your config.yaml and fix it if necessary.'));
67
+ } catch (error) {
68
+ console.error(color.red('FATAL: Config conversion failed. Please check your config.conf file and try again.'));
69
+ return;
70
+ }
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Compares the current config.yaml with the default config.yaml and adds any missing values.
76
+ */
77
+ function addMissingConfigValues() {
78
+ try {
79
+ const defaultConfig = yaml.parse(fs.readFileSync(path.join(process.cwd(), './default/config.yaml'), 'utf8'));
80
+ let config = yaml.parse(fs.readFileSync(path.join(process.cwd(), './config.yaml'), 'utf8'));
81
+
82
+ // Get all keys from the original config
83
+ const originalKeys = getAllKeys(config);
84
+
85
+ // Use lodash's defaultsDeep function to recursively apply default properties
86
+ config = _.defaultsDeep(config, defaultConfig);
87
+
88
+ // Get all keys from the updated config
89
+ const updatedKeys = getAllKeys(config);
90
+
91
+ // Find the keys that were added
92
+ const addedKeys = _.difference(updatedKeys, originalKeys);
93
+
94
+ if (addedKeys.length === 0) {
95
+ return;
96
+ }
97
+
98
+ console.log('Adding missing config values to config.yaml:', addedKeys);
99
+ fs.writeFileSync('./config.yaml', yaml.stringify(config));
100
+ } catch (error) {
101
+ console.error(color.red('FATAL: Could not add missing config values to config.yaml'), error);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Creates the default config files if they don't exist yet.
107
+ */
108
+ function createDefaultFiles() {
109
+ const files = {
110
+ config: './config.yaml',
111
+ user: './public/css/user.css',
112
+ };
113
+
114
+ for (const file of Object.values(files)) {
115
+ try {
116
+ if (!fs.existsSync(file)) {
117
+ const defaultFilePath = path.join('./default', path.parse(file).base);
118
+ fs.copyFileSync(defaultFilePath, file);
119
+ console.log(color.green(`Created default file: ${file}`));
120
+ }
121
+ } catch (error) {
122
+ console.error(color.red(`FATAL: Could not write default file: ${file}`), error);
123
+ }
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Returns the MD5 hash of the given data.
129
+ * @param {Buffer} data Input data
130
+ * @returns {string} MD5 hash of the input data
131
+ */
132
+ function getMd5Hash(data) {
133
+ return crypto
134
+ .createHash('md5')
135
+ .update(data)
136
+ .digest('hex');
137
+ }
138
+
139
+ /**
140
+ * Copies the WASM binaries from the sillytavern-transformers package to the dist folder.
141
+ */
142
+ function copyWasmFiles() {
143
+ if (!fs.existsSync('./dist')) {
144
+ fs.mkdirSync('./dist');
145
+ }
146
+
147
+ const listDir = fs.readdirSync('./node_modules/sillytavern-transformers/dist');
148
+
149
+ for (const file of listDir) {
150
+ if (file.endsWith('.wasm')) {
151
+ const sourcePath = `./node_modules/sillytavern-transformers/dist/${file}`;
152
+ const targetPath = `./dist/${file}`;
153
+
154
+ // Don't copy if the file already exists and is the same checksum
155
+ if (fs.existsSync(targetPath)) {
156
+ const sourceChecksum = getMd5Hash(fs.readFileSync(sourcePath));
157
+ const targetChecksum = getMd5Hash(fs.readFileSync(targetPath));
158
+
159
+ if (sourceChecksum === targetChecksum) {
160
+ continue;
161
+ }
162
+ }
163
+
164
+ fs.copyFileSync(sourcePath, targetPath);
165
+ console.log(`${file} successfully copied to ./dist/${file}`);
166
+ }
167
+ }
168
+ }
169
+
170
+ try {
171
+ // 0. Convert config.conf to config.yaml
172
+ convertConfig();
173
+ // 1. Create default config files
174
+ createDefaultFiles();
175
+ // 2. Copy transformers WASM binaries from node_modules
176
+ copyWasmFiles();
177
+ // 3. Add missing config values
178
+ addMissingConfigValues();
179
+ } catch (error) {
180
+ console.error(error);
181
+ }
recover.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const yaml = require('yaml');
2
+ const fs = require('fs');
3
+ const storage = require('node-persist');
4
+ const users = require('./src/users');
5
+
6
+ const userAccount = process.argv[2];
7
+ const userPassword = process.argv[3];
8
+
9
+ if (!userAccount) {
10
+ console.error('A tool for recovering lost SillyTavern accounts. Uses a "dataRoot" setting from config.yaml file.');
11
+ console.error('Usage: node recover.js [account] (password)');
12
+ console.error('Example: node recover.js admin password');
13
+ process.exit(1);
14
+ }
15
+
16
+ async function initStorage() {
17
+ const config = yaml.parse(fs.readFileSync('config.yaml', 'utf8'));
18
+ const dataRoot = config.dataRoot;
19
+
20
+ if (!dataRoot) {
21
+ console.error('No "dataRoot" setting found in config.yaml file.');
22
+ process.exit(1);
23
+ }
24
+
25
+ await users.initUserStorage(dataRoot);
26
+ }
27
+
28
+ async function main() {
29
+ await initStorage();
30
+
31
+ /**
32
+ * @type {import('./src/users').User}
33
+ */
34
+ const user = await storage.get(users.toKey(userAccount));
35
+
36
+ if (!user) {
37
+ console.error(`User "${userAccount}" not found.`);
38
+ process.exit(1);
39
+ }
40
+
41
+ if (!user.enabled) {
42
+ console.log('User is disabled. Enabling...');
43
+ user.enabled = true;
44
+ }
45
+
46
+ if (userPassword) {
47
+ console.log('Setting new password...');
48
+ const salt = users.getPasswordSalt();
49
+ const passwordHash = users.getPasswordHash(userPassword, salt);
50
+ user.password = passwordHash;
51
+ user.salt = salt;
52
+ } else {
53
+ console.log('Setting an empty password...');
54
+ user.password = '';
55
+ user.salt = '';
56
+ }
57
+
58
+ await storage.setItem(users.toKey(userAccount), user);
59
+ console.log('User recovered. A program will exit now.');
60
+ }
61
+
62
+ main();
replit.nix ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ { pkgs }: {
2
+ deps = [
3
+ pkgs.nodejs-18_x
4
+ pkgs.nodePackages.typescript-language-server
5
+ pkgs.yarn
6
+ pkgs.replitPackages.jest
7
+ ];
8
+ }
server.js ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ // native node modules
4
+ const fs = require('fs');
5
+ const http = require('http');
6
+ const https = require('https');
7
+ const path = require('path');
8
+ const util = require('util');
9
+
10
+ // cli/fs related library imports
11
+ const open = require('open');
12
+ const yargs = require('yargs/yargs');
13
+ const { hideBin } = require('yargs/helpers');
14
+
15
+ // express/server related library imports
16
+ const cors = require('cors');
17
+ const doubleCsrf = require('csrf-csrf').doubleCsrf;
18
+ const express = require('express');
19
+ const compression = require('compression');
20
+ const cookieParser = require('cookie-parser');
21
+ const cookieSession = require('cookie-session');
22
+ const multer = require('multer');
23
+ const responseTime = require('response-time');
24
+ const helmet = require('helmet').default;
25
+
26
+ // net related library imports
27
+ const net = require('net');
28
+ const dns = require('dns');
29
+ const fetch = require('node-fetch').default;
30
+
31
+ // Unrestrict console logs display limit
32
+ util.inspect.defaultOptions.maxArrayLength = null;
33
+ util.inspect.defaultOptions.maxStringLength = null;
34
+ util.inspect.defaultOptions.depth = 4;
35
+
36
+ // local library imports
37
+ const userModule = require('./src/users');
38
+ const basicAuthMiddleware = require('./src/middleware/basicAuth');
39
+ const whitelistMiddleware = require('./src/middleware/whitelist');
40
+ const contentManager = require('./src/endpoints/content-manager');
41
+ const {
42
+ getVersion,
43
+ getConfigValue,
44
+ color,
45
+ forwardFetchResponse,
46
+ removeColorFormatting,
47
+ getSeparator,
48
+ } = require('./src/util');
49
+ const { ensureThumbnailCache } = require('./src/endpoints/thumbnails');
50
+
51
+ // Work around a node v20.0.0, v20.1.0, and v20.2.0 bug. The issue was fixed in v20.3.0.
52
+ // https://github.com/nodejs/node/issues/47822#issuecomment-1564708870
53
+ // Safe to remove once support for Node v20 is dropped.
54
+ if (process.versions && process.versions.node && process.versions.node.match(/20\.[0-2]\.0/)) {
55
+ // @ts-ignore
56
+ if (net.setDefaultAutoSelectFamily) net.setDefaultAutoSelectFamily(false);
57
+ }
58
+
59
+ const DEFAULT_PORT = 8000;
60
+ const DEFAULT_AUTORUN = false;
61
+ const DEFAULT_LISTEN = false;
62
+ const DEFAULT_CORS_PROXY = false;
63
+ const DEFAULT_WHITELIST = true;
64
+ const DEFAULT_ACCOUNTS = false;
65
+ const DEFAULT_CSRF_DISABLED = false;
66
+ const DEFAULT_BASIC_AUTH = false;
67
+
68
+ const DEFAULT_ENABLE_IPV6 = false;
69
+ const DEFAULT_ENABLE_IPV4 = true;
70
+
71
+ const DEFAULT_PREFER_IPV6 = false;
72
+
73
+ const DEFAULT_AVOID_LOCALHOST = false;
74
+
75
+ const DEFAULT_AUTORUN_HOSTNAME = 'auto';
76
+ const DEFAULT_AUTORUN_PORT = -1;
77
+
78
+ const cliArguments = yargs(hideBin(process.argv))
79
+ .usage('Usage: <your-start-script> <command> [options]')
80
+ .option('enableIPv6', {
81
+ type: 'boolean',
82
+ default: null,
83
+ describe: `Enables IPv6.\n[config default: ${DEFAULT_ENABLE_IPV6}]`,
84
+ }).option('enableIPv4', {
85
+ type: 'boolean',
86
+ default: null,
87
+ describe: `Enables IPv4.\n[config default: ${DEFAULT_ENABLE_IPV4}]`,
88
+ }).option('port', {
89
+ type: 'number',
90
+ default: null,
91
+ describe: `Sets the port under which SillyTavern will run.\nIf not provided falls back to yaml config 'port'.\n[config default: ${DEFAULT_PORT}]`,
92
+ }).option('dnsPreferIPv6', {
93
+ type: 'boolean',
94
+ default: null,
95
+ describe: `Prefers IPv6 for dns\nyou should probably have the enabled if you're on an IPv6 only network\nIf not provided falls back to yaml config 'preferIPv6'.\n[config default: ${DEFAULT_PREFER_IPV6}]`,
96
+ }).option('autorun', {
97
+ type: 'boolean',
98
+ default: null,
99
+ describe: `Automatically launch SillyTavern in the browser.\nAutorun is automatically disabled if --ssl is set to true.\nIf not provided falls back to yaml config 'autorun'.\n[config default: ${DEFAULT_AUTORUN}]`,
100
+ }).option('autorunHostname', {
101
+ type: 'string',
102
+ default: null,
103
+ describe: 'the autorun hostname, probably best left on \'auto\'.\nuse values like \'localhost\', \'st.example.com\'',
104
+ }).option('autorunPortOverride', {
105
+ type: 'string',
106
+ default: null,
107
+ describe: 'Overrides the port for autorun with open your browser with this port and ignore what port the server is running on. -1 is use server port',
108
+ }).option('listen', {
109
+ type: 'boolean',
110
+ default: null,
111
+ describe: `SillyTavern is listening on all network interfaces (Wi-Fi, LAN, localhost). If false, will limit it only to internal localhost (127.0.0.1).\nIf not provided falls back to yaml config 'listen'.\n[config default: ${DEFAULT_LISTEN}]`,
112
+ }).option('corsProxy', {
113
+ type: 'boolean',
114
+ default: null,
115
+ describe: `Enables CORS proxy\nIf not provided falls back to yaml config 'enableCorsProxy'.\n[config default: ${DEFAULT_CORS_PROXY}]`,
116
+ }).option('disableCsrf', {
117
+ type: 'boolean',
118
+ default: null,
119
+ describe: 'Disables CSRF protection',
120
+ }).option('ssl', {
121
+ type: 'boolean',
122
+ default: false,
123
+ describe: 'Enables SSL',
124
+ }).option('certPath', {
125
+ type: 'string',
126
+ default: 'certs/cert.pem',
127
+ describe: 'Path to your certificate file.',
128
+ }).option('keyPath', {
129
+ type: 'string',
130
+ default: 'certs/privkey.pem',
131
+ describe: 'Path to your private key file.',
132
+ }).option('whitelist', {
133
+ type: 'boolean',
134
+ default: null,
135
+ describe: 'Enables whitelist mode',
136
+ }).option('dataRoot', {
137
+ type: 'string',
138
+ default: null,
139
+ describe: 'Root directory for data storage',
140
+ }).option('avoidLocalhost', {
141
+ type: 'boolean',
142
+ default: null,
143
+ describe: 'Avoids using \'localhost\' for autorun in auto mode.\nuse if you don\'t have \'localhost\' in your hosts file',
144
+ }).option('basicAuthMode', {
145
+ type: 'boolean',
146
+ default: null,
147
+ describe: 'Enables basic authentication',
148
+ }).parseSync();
149
+
150
+ // change all relative paths
151
+ console.log(`Node version: ${process.version}. Running in ${process.env.NODE_ENV} environment.`);
152
+ const serverDirectory = __dirname;
153
+ process.chdir(serverDirectory);
154
+
155
+ const app = express();
156
+ app.use(helmet({
157
+ contentSecurityPolicy: false,
158
+ }));
159
+ app.use(compression());
160
+ app.use(responseTime());
161
+
162
+ const server_port = cliArguments.port ?? process.env.SILLY_TAVERN_PORT ?? getConfigValue('port', DEFAULT_PORT);
163
+ const autorun = (cliArguments.autorun ?? getConfigValue('autorun', DEFAULT_AUTORUN)) && !cliArguments.ssl;
164
+ const listen = cliArguments.listen ?? getConfigValue('listen', DEFAULT_LISTEN);
165
+ const enableCorsProxy = cliArguments.corsProxy ?? getConfigValue('enableCorsProxy', DEFAULT_CORS_PROXY);
166
+ const enableWhitelist = cliArguments.whitelist ?? getConfigValue('whitelistMode', DEFAULT_WHITELIST);
167
+ const dataRoot = cliArguments.dataRoot ?? getConfigValue('dataRoot', './data');
168
+ const disableCsrf = cliArguments.disableCsrf ?? getConfigValue('disableCsrfProtection', DEFAULT_CSRF_DISABLED);
169
+ const basicAuthMode = cliArguments.basicAuthMode ?? getConfigValue('basicAuthMode', DEFAULT_BASIC_AUTH);
170
+ const enableAccounts = getConfigValue('enableUserAccounts', DEFAULT_ACCOUNTS);
171
+
172
+ const uploadsPath = path.join(dataRoot, require('./src/constants').UPLOADS_DIRECTORY);
173
+
174
+ const enableIPv6 = cliArguments.enableIPv6 ?? getConfigValue('protocol.ipv6', DEFAULT_ENABLE_IPV6);
175
+ const enableIPv4 = cliArguments.enableIPv4 ?? getConfigValue('protocol.ipv4', DEFAULT_ENABLE_IPV4);
176
+
177
+ const autorunHostname = cliArguments.autorunHostname ?? getConfigValue('autorunHostname', DEFAULT_AUTORUN_HOSTNAME);
178
+ const autorunPortOverride = cliArguments.autorunPortOverride ?? getConfigValue('autorunPortOverride', DEFAULT_AUTORUN_PORT);
179
+
180
+ const dnsPreferIPv6 = cliArguments.dnsPreferIPv6 ?? getConfigValue('dnsPreferIPv6', DEFAULT_PREFER_IPV6);
181
+
182
+ const avoidLocalhost = cliArguments.avoidLocalhost ?? getConfigValue('avoidLocalhost', DEFAULT_AVOID_LOCALHOST);
183
+
184
+ if (dnsPreferIPv6) {
185
+ // Set default DNS resolution order to IPv6 first
186
+ dns.setDefaultResultOrder('ipv6first');
187
+ console.log('Preferring IPv6 for DNS resolution');
188
+ } else {
189
+ // Set default DNS resolution order to IPv4 first
190
+ dns.setDefaultResultOrder('ipv4first');
191
+ console.log('Preferring IPv4 for DNS resolution');
192
+ }
193
+
194
+ if (!enableIPv6 && !enableIPv4) {
195
+ console.error('error: You can\'t disable all internet protocols: at least IPv6 or IPv4 must be enabled.');
196
+ process.exit(1);
197
+ }
198
+
199
+ // CORS Settings //
200
+ const CORS = cors({
201
+ origin: 'null',
202
+ methods: ['OPTIONS'],
203
+ });
204
+
205
+ app.use(CORS);
206
+
207
+ if (listen && basicAuthMode) app.use(basicAuthMiddleware);
208
+
209
+ app.use(whitelistMiddleware(enableWhitelist, listen));
210
+
211
+ if (enableCorsProxy) {
212
+ const bodyParser = require('body-parser');
213
+ app.use(bodyParser.json({
214
+ limit: '200mb',
215
+ }));
216
+ console.log('Enabling CORS proxy');
217
+
218
+ app.use('/proxy/:url(*)', async (req, res) => {
219
+ const url = req.params.url; // get the url from the request path
220
+
221
+ // Disallow circular requests
222
+ const serverUrl = req.protocol + '://' + req.get('host');
223
+ if (url.startsWith(serverUrl)) {
224
+ return res.status(400).send('Circular requests are not allowed');
225
+ }
226
+
227
+ try {
228
+ const headers = JSON.parse(JSON.stringify(req.headers));
229
+ const headersToRemove = [
230
+ 'x-csrf-token', 'host', 'referer', 'origin', 'cookie',
231
+ 'x-forwarded-for', 'x-forwarded-protocol', 'x-forwarded-proto',
232
+ 'x-forwarded-host', 'x-real-ip', 'sec-fetch-mode',
233
+ 'sec-fetch-site', 'sec-fetch-dest',
234
+ ];
235
+
236
+ headersToRemove.forEach(header => delete headers[header]);
237
+
238
+ const bodyMethods = ['POST', 'PUT', 'PATCH'];
239
+
240
+ const response = await fetch(url, {
241
+ method: req.method,
242
+ headers: headers,
243
+ body: bodyMethods.includes(req.method) ? JSON.stringify(req.body) : undefined,
244
+ });
245
+
246
+ // Copy over relevant response params to the proxy response
247
+ forwardFetchResponse(response, res);
248
+
249
+ } catch (error) {
250
+ res.status(500).send('Error occurred while trying to proxy to: ' + url + ' ' + error);
251
+ }
252
+ });
253
+ } else {
254
+ app.use('/proxy/:url(*)', async (_, res) => {
255
+ const message = 'CORS proxy is disabled. Enable it in config.yaml or use the --corsProxy flag.';
256
+ console.log(message);
257
+ res.status(404).send(message);
258
+ });
259
+ }
260
+
261
+ function getSessionCookieAge() {
262
+ // Defaults to 24 hours in seconds if not set
263
+ const configValue = getConfigValue('sessionTimeout', 24 * 60 * 60);
264
+
265
+ // Convert to milliseconds
266
+ if (configValue > 0) {
267
+ return configValue * 1000;
268
+ }
269
+
270
+ // "No expiration" is just 400 days as per RFC 6265
271
+ if (configValue < 0) {
272
+ return 400 * 24 * 60 * 60 * 1000;
273
+ }
274
+
275
+ // 0 means session cookie is deleted when the browser session ends
276
+ // (depends on the implementation of the browser)
277
+ return undefined;
278
+ }
279
+
280
+ app.use(cookieSession({
281
+ name: userModule.getCookieSessionName(),
282
+ sameSite: 'strict',
283
+ httpOnly: true,
284
+ maxAge: getSessionCookieAge(),
285
+ secret: userModule.getCookieSecret(),
286
+ }));
287
+
288
+ app.use(userModule.setUserDataMiddleware);
289
+
290
+ // CSRF Protection //
291
+ if (!disableCsrf) {
292
+ const COOKIES_SECRET = userModule.getCookieSecret();
293
+
294
+ const { generateToken, doubleCsrfProtection } = doubleCsrf({
295
+ getSecret: userModule.getCsrfSecret,
296
+ cookieName: 'X-CSRF-Token',
297
+ cookieOptions: {
298
+ httpOnly: true,
299
+ sameSite: 'strict',
300
+ secure: false,
301
+ },
302
+ size: 64,
303
+ getTokenFromRequest: (req) => req.headers['x-csrf-token'],
304
+ });
305
+
306
+ app.get('/csrf-token', (req, res) => {
307
+ res.json({
308
+ 'token': generateToken(res, req),
309
+ });
310
+ });
311
+
312
+ app.use(cookieParser(COOKIES_SECRET));
313
+ app.use(doubleCsrfProtection);
314
+ } else {
315
+ console.warn('\nCSRF protection is disabled. This will make your server vulnerable to CSRF attacks.\n');
316
+ app.get('/csrf-token', (req, res) => {
317
+ res.json({
318
+ 'token': 'disabled',
319
+ });
320
+ });
321
+ }
322
+
323
+ // Static files
324
+ // Host index page
325
+ app.get('/', (request, response) => {
326
+ if (userModule.shouldRedirectToLogin(request)) {
327
+ const query = request.url.split('?')[1];
328
+ const redirectUrl = query ? `/login?${query}` : '/login';
329
+ return response.redirect(redirectUrl);
330
+ }
331
+
332
+ return response.sendFile('index.html', { root: path.join(process.cwd(), 'public') });
333
+ });
334
+
335
+ // Host login page
336
+ app.get('/login', async (request, response) => {
337
+ if (!enableAccounts) {
338
+ console.log('User accounts are disabled. Redirecting to index page.');
339
+ return response.redirect('/');
340
+ }
341
+
342
+ try {
343
+ const autoLogin = await userModule.tryAutoLogin(request);
344
+
345
+ if (autoLogin) {
346
+ return response.redirect('/');
347
+ }
348
+ } catch (error) {
349
+ console.error('Error during auto-login:', error);
350
+ }
351
+
352
+ return response.sendFile('login.html', { root: path.join(process.cwd(), 'public') });
353
+ });
354
+
355
+ // Host frontend assets
356
+ app.use(express.static(process.cwd() + '/public', {}));
357
+
358
+ // Public API
359
+ app.use('/api/users', require('./src/endpoints/users-public').router);
360
+
361
+ // Everything below this line requires authentication
362
+ app.use(userModule.requireLoginMiddleware);
363
+ app.get('/api/ping', (_, response) => response.sendStatus(204));
364
+
365
+ // File uploads
366
+ app.use(multer({ dest: uploadsPath, limits: { fieldSize: 10 * 1024 * 1024 } }).single('avatar'));
367
+ app.use(require('./src/middleware/multerMonkeyPatch'));
368
+
369
+ // User data mount
370
+ app.use('/', userModule.router);
371
+ // Private endpoints
372
+ app.use('/api/users', require('./src/endpoints/users-private').router);
373
+ // Admin endpoints
374
+ app.use('/api/users', require('./src/endpoints/users-admin').router);
375
+
376
+ app.get('/version', async function (_, response) {
377
+ const data = await getVersion();
378
+ response.send(data);
379
+ });
380
+
381
+ function cleanUploads() {
382
+ try {
383
+ if (fs.existsSync(uploadsPath)) {
384
+ const uploads = fs.readdirSync(uploadsPath);
385
+
386
+ if (!uploads.length) {
387
+ return;
388
+ }
389
+
390
+ console.debug(`Cleaning uploads folder (${uploads.length} files)`);
391
+ uploads.forEach(file => {
392
+ const pathToFile = path.join(uploadsPath, file);
393
+ fs.unlinkSync(pathToFile);
394
+ });
395
+ }
396
+ } catch (err) {
397
+ console.error(err);
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Redirect a deprecated API endpoint URL to its replacement. Because fetch, form submissions, and $.ajax follow
403
+ * redirects, this is transparent to client-side code.
404
+ * @param {string} src The URL to redirect from.
405
+ * @param {string} destination The URL to redirect to.
406
+ */
407
+ function redirect(src, destination) {
408
+ app.use(src, (req, res) => {
409
+ console.warn(`API endpoint ${src} is deprecated; use ${destination} instead`);
410
+ // HTTP 301 causes the request to become a GET. 308 preserves the request method.
411
+ res.redirect(308, destination);
412
+ });
413
+ }
414
+
415
+ // Redirect deprecated character API endpoints
416
+ redirect('/createcharacter', '/api/characters/create');
417
+ redirect('/renamecharacter', '/api/characters/rename');
418
+ redirect('/editcharacter', '/api/characters/edit');
419
+ redirect('/editcharacterattribute', '/api/characters/edit-attribute');
420
+ redirect('/v2/editcharacterattribute', '/api/characters/merge-attributes');
421
+ redirect('/deletecharacter', '/api/characters/delete');
422
+ redirect('/getcharacters', '/api/characters/all');
423
+ redirect('/getonecharacter', '/api/characters/get');
424
+ redirect('/getallchatsofcharacter', '/api/characters/chats');
425
+ redirect('/importcharacter', '/api/characters/import');
426
+ redirect('/dupecharacter', '/api/characters/duplicate');
427
+ redirect('/exportcharacter', '/api/characters/export');
428
+
429
+ // Redirect deprecated chat API endpoints
430
+ redirect('/savechat', '/api/chats/save');
431
+ redirect('/getchat', '/api/chats/get');
432
+ redirect('/renamechat', '/api/chats/rename');
433
+ redirect('/delchat', '/api/chats/delete');
434
+ redirect('/exportchat', '/api/chats/export');
435
+ redirect('/importgroupchat', '/api/chats/group/import');
436
+ redirect('/importchat', '/api/chats/import');
437
+ redirect('/getgroupchat', '/api/chats/group/get');
438
+ redirect('/deletegroupchat', '/api/chats/group/delete');
439
+ redirect('/savegroupchat', '/api/chats/group/save');
440
+
441
+ // Redirect deprecated group API endpoints
442
+ redirect('/getgroups', '/api/groups/all');
443
+ redirect('/creategroup', '/api/groups/create');
444
+ redirect('/editgroup', '/api/groups/edit');
445
+ redirect('/deletegroup', '/api/groups/delete');
446
+
447
+ // Redirect deprecated worldinfo API endpoints
448
+ redirect('/getworldinfo', '/api/worldinfo/get');
449
+ redirect('/deleteworldinfo', '/api/worldinfo/delete');
450
+ redirect('/importworldinfo', '/api/worldinfo/import');
451
+ redirect('/editworldinfo', '/api/worldinfo/edit');
452
+
453
+ // Redirect deprecated stats API endpoints
454
+ redirect('/getstats', '/api/stats/get');
455
+ redirect('/recreatestats', '/api/stats/recreate');
456
+ redirect('/updatestats', '/api/stats/update');
457
+
458
+ // Redirect deprecated backgrounds API endpoints
459
+ redirect('/getbackgrounds', '/api/backgrounds/all');
460
+ redirect('/delbackground', '/api/backgrounds/delete');
461
+ redirect('/renamebackground', '/api/backgrounds/rename');
462
+ redirect('/downloadbackground', '/api/backgrounds/upload'); // yes, the downloadbackground endpoint actually uploads one
463
+
464
+ // Redirect deprecated theme API endpoints
465
+ redirect('/savetheme', '/api/themes/save');
466
+
467
+ // Redirect deprecated avatar API endpoints
468
+ redirect('/getuseravatars', '/api/avatars/get');
469
+ redirect('/deleteuseravatar', '/api/avatars/delete');
470
+ redirect('/uploaduseravatar', '/api/avatars/upload');
471
+
472
+ // Redirect deprecated quick reply endpoints
473
+ redirect('/deletequickreply', '/api/quick-replies/delete');
474
+ redirect('/savequickreply', '/api/quick-replies/save');
475
+
476
+ // Redirect deprecated image endpoints
477
+ redirect('/uploadimage', '/api/images/upload');
478
+ redirect('/listimgfiles/:folder', '/api/images/list/:folder');
479
+ redirect('/api/content/import', '/api/content/importURL');
480
+
481
+ // Redirect deprecated moving UI endpoints
482
+ redirect('/savemovingui', '/api/moving-ui/save');
483
+
484
+ // Redirect Serp endpoints
485
+ redirect('/api/serpapi/search', '/api/search/serpapi');
486
+ redirect('/api/serpapi/visit', '/api/search/visit');
487
+ redirect('/api/serpapi/transcript', '/api/search/transcript');
488
+
489
+ // Moving UI
490
+ app.use('/api/moving-ui', require('./src/endpoints/moving-ui').router);
491
+
492
+ // Image management
493
+ app.use('/api/images', require('./src/endpoints/images').router);
494
+
495
+ // Quick reply management
496
+ app.use('/api/quick-replies', require('./src/endpoints/quick-replies').router);
497
+
498
+ // Avatar management
499
+ app.use('/api/avatars', require('./src/endpoints/avatars').router);
500
+
501
+ // Theme management
502
+ app.use('/api/themes', require('./src/endpoints/themes').router);
503
+
504
+ // OpenAI API
505
+ app.use('/api/openai', require('./src/endpoints/openai').router);
506
+
507
+ //Google API
508
+ app.use('/api/google', require('./src/endpoints/google').router);
509
+
510
+ //Anthropic API
511
+ app.use('/api/anthropic', require('./src/endpoints/anthropic').router);
512
+
513
+ // Tokenizers
514
+ app.use('/api/tokenizers', require('./src/endpoints/tokenizers').router);
515
+
516
+ // Preset management
517
+ app.use('/api/presets', require('./src/endpoints/presets').router);
518
+
519
+ // Secrets managemenet
520
+ app.use('/api/secrets', require('./src/endpoints/secrets').router);
521
+
522
+ // Thumbnail generation. These URLs are saved in chat, so this route cannot be renamed!
523
+ app.use('/thumbnail', require('./src/endpoints/thumbnails').router);
524
+
525
+ // NovelAI generation
526
+ app.use('/api/novelai', require('./src/endpoints/novelai').router);
527
+
528
+ // Third-party extensions
529
+ app.use('/api/extensions', require('./src/endpoints/extensions').router);
530
+
531
+ // Asset management
532
+ app.use('/api/assets', require('./src/endpoints/assets').router);
533
+
534
+ // File management
535
+ app.use('/api/files', require('./src/endpoints/files').router);
536
+
537
+ // Character management
538
+ app.use('/api/characters', require('./src/endpoints/characters').router);
539
+
540
+ // Chat management
541
+ app.use('/api/chats', require('./src/endpoints/chats').router);
542
+
543
+ // Group management
544
+ app.use('/api/groups', require('./src/endpoints/groups').router);
545
+
546
+ // World info management
547
+ app.use('/api/worldinfo', require('./src/endpoints/worldinfo').router);
548
+
549
+ // Stats calculation
550
+ const statsEndpoint = require('./src/endpoints/stats');
551
+ app.use('/api/stats', statsEndpoint.router);
552
+
553
+ // Background management
554
+ app.use('/api/backgrounds', require('./src/endpoints/backgrounds').router);
555
+
556
+ // Character sprite management
557
+ app.use('/api/sprites', require('./src/endpoints/sprites').router);
558
+
559
+ // Custom content management
560
+ app.use('/api/content', require('./src/endpoints/content-manager').router);
561
+
562
+ // Settings load/store
563
+ const settingsEndpoint = require('./src/endpoints/settings');
564
+ app.use('/api/settings', settingsEndpoint.router);
565
+
566
+ // Stable Diffusion generation
567
+ app.use('/api/sd', require('./src/endpoints/stable-diffusion').router);
568
+
569
+ // LLM and SD Horde generation
570
+ app.use('/api/horde', require('./src/endpoints/horde').router);
571
+
572
+ // Vector storage DB
573
+ app.use('/api/vector', require('./src/endpoints/vectors').router);
574
+
575
+ // Chat translation
576
+ app.use('/api/translate', require('./src/endpoints/translate').router);
577
+
578
+ // Emotion classification
579
+ app.use('/api/extra/classify', require('./src/endpoints/classify').router);
580
+
581
+ // Image captioning
582
+ app.use('/api/extra/caption', require('./src/endpoints/caption').router);
583
+
584
+ // Web search and scraping
585
+ app.use('/api/search', require('./src/endpoints/search').router);
586
+
587
+ // The different text generation APIs
588
+
589
+ // Ooba/OpenAI text completions
590
+ app.use('/api/backends/text-completions', require('./src/endpoints/backends/text-completions').router);
591
+
592
+ // KoboldAI
593
+ app.use('/api/backends/kobold', require('./src/endpoints/backends/kobold').router);
594
+
595
+ // OpenAI chat completions
596
+ app.use('/api/backends/chat-completions', require('./src/endpoints/backends/chat-completions').router);
597
+
598
+ // Scale (alt method)
599
+ app.use('/api/backends/scale-alt', require('./src/endpoints/backends/scale-alt').router);
600
+
601
+ // Speech (text-to-speech and speech-to-text)
602
+ app.use('/api/speech', require('./src/endpoints/speech').router);
603
+
604
+ // Azure TTS
605
+ app.use('/api/azure', require('./src/endpoints/azure').router);
606
+
607
+ const tavernUrlV6 = new URL(
608
+ (cliArguments.ssl ? 'https://' : 'http://') +
609
+ (listen ? '[::]' : '[::1]') +
610
+ (':' + server_port),
611
+ );
612
+
613
+ const tavernUrl = new URL(
614
+ (cliArguments.ssl ? 'https://' : 'http://') +
615
+ (listen ? '0.0.0.0' : '127.0.0.1') +
616
+ (':' + server_port),
617
+ );
618
+
619
+ /**
620
+ * Tasks that need to be run before the server starts listening.
621
+ */
622
+ const preSetupTasks = async function () {
623
+ const version = await getVersion();
624
+
625
+ // Print formatted header
626
+ console.log();
627
+ console.log(`SillyTavern ${version.pkgVersion}`);
628
+ console.log(version.gitBranch ? `Running '${version.gitBranch}' (${version.gitRevision}) - ${version.commitDate}` : '');
629
+ if (version.gitBranch && !version.isLatest && ['staging', 'release'].includes(version.gitBranch)) {
630
+ console.log('INFO: Currently not on the latest commit.');
631
+ console.log(' Run \'git pull\' to update. If you have any merge conflicts, run \'git reset --hard\' and \'git pull\' to reset your branch.');
632
+ }
633
+ console.log();
634
+
635
+ const directories = await userModule.getUserDirectoriesList();
636
+ await contentManager.checkForNewContent(directories);
637
+ await ensureThumbnailCache();
638
+ cleanUploads();
639
+
640
+ await settingsEndpoint.init();
641
+ await statsEndpoint.init();
642
+
643
+ const cleanupPlugins = await loadPlugins();
644
+ const consoleTitle = process.title;
645
+
646
+ let isExiting = false;
647
+ const exitProcess = async () => {
648
+ if (isExiting) return;
649
+ isExiting = true;
650
+ statsEndpoint.onExit();
651
+ if (typeof cleanupPlugins === 'function') {
652
+ await cleanupPlugins();
653
+ }
654
+ setWindowTitle(consoleTitle);
655
+ process.exit();
656
+ };
657
+
658
+ // Set up event listeners for a graceful shutdown
659
+ process.on('SIGINT', exitProcess);
660
+ process.on('SIGTERM', exitProcess);
661
+ process.on('uncaughtException', (err) => {
662
+ console.error('Uncaught exception:', err);
663
+ exitProcess();
664
+ });
665
+ };
666
+
667
+ /**
668
+ * Gets the hostname to use for autorun in the browser.
669
+ * @returns {string} The hostname to use for autorun
670
+ */
671
+ function getAutorunHostname() {
672
+ if (autorunHostname === 'auto') {
673
+ if (enableIPv6 && enableIPv4) {
674
+ if (avoidLocalhost) return '[::1]';
675
+ return 'localhost';
676
+ }
677
+
678
+ if (enableIPv6) {
679
+ return '[::1]';
680
+ }
681
+
682
+ if (enableIPv4) {
683
+ return '127.0.0.1';
684
+ }
685
+ }
686
+
687
+ return autorunHostname;
688
+ }
689
+
690
+ /**
691
+ * Tasks that need to be run after the server starts listening.
692
+ * @param {boolean} v6Failed If the server failed to start on IPv6
693
+ * @param {boolean} v4Failed If the server failed to start on IPv4
694
+ */
695
+ const postSetupTasks = async function (v6Failed, v4Failed) {
696
+ const autorunUrl = new URL(
697
+ (cliArguments.ssl ? 'https://' : 'http://') +
698
+ (getAutorunHostname()) +
699
+ (':') +
700
+ ((autorunPortOverride >= 0) ? autorunPortOverride : server_port),
701
+ );
702
+
703
+ console.log('Launching...');
704
+
705
+ if (autorun) open(autorunUrl.toString());
706
+
707
+ setWindowTitle('SillyTavern WebServer');
708
+
709
+ let logListen = 'SillyTavern is listening on';
710
+
711
+ if (enableIPv6 && !v6Failed) {
712
+ logListen += color.green(' IPv6: ' + tavernUrlV6.host);
713
+ }
714
+
715
+ if (enableIPv4 && !v4Failed) {
716
+ logListen += color.green(' IPv4: ' + tavernUrl.host);
717
+ }
718
+
719
+ const goToLog = 'Go to: ' + color.blue(autorunUrl) + ' to open SillyTavern';
720
+ const plainGoToLog = removeColorFormatting(goToLog);
721
+
722
+ console.log(logListen);
723
+ console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
724
+ console.log(goToLog);
725
+ console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
726
+
727
+ if (listen) {
728
+ console.log('[::] or 0.0.0.0 means SillyTavern is listening on all network interfaces (Wi-Fi, LAN, localhost). If you want to limit it only to internal localhost ([::1] or 127.0.0.1), change the setting in config.yaml to "listen: false". Check "access.log" file in the SillyTavern directory if you want to inspect incoming connections.\n');
729
+ }
730
+
731
+ if (basicAuthMode) {
732
+ const basicAuthUser = getConfigValue('basicAuthUser', {});
733
+ if (!basicAuthUser?.username || !basicAuthUser?.password) {
734
+ console.warn(color.yellow('Basic Authentication is enabled, but username or password is not set or empty!'));
735
+ }
736
+ }
737
+ };
738
+
739
+ /**
740
+ * Loads server plugins from a directory.
741
+ * @returns {Promise<Function>} Function to be run on server exit
742
+ */
743
+ async function loadPlugins() {
744
+ try {
745
+ const pluginDirectory = path.join(serverDirectory, 'plugins');
746
+ const loader = require('./src/plugin-loader');
747
+ const cleanupPlugins = await loader.loadPlugins(app, pluginDirectory);
748
+ return cleanupPlugins;
749
+ } catch {
750
+ console.log('Plugin loading failed.');
751
+ return () => { };
752
+ }
753
+ }
754
+
755
+ /**
756
+ * Set the title of the terminal window
757
+ * @param {string} title Desired title for the window
758
+ */
759
+ function setWindowTitle(title) {
760
+ if (process.platform === 'win32') {
761
+ process.title = title;
762
+ }
763
+ else {
764
+ process.stdout.write(`\x1b]2;${title}\x1b\x5c`);
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Prints an error message and exits the process if necessary
770
+ * @param {string} message The error message to print
771
+ * @returns {void}
772
+ */
773
+ function logSecurityAlert(message) {
774
+ if (basicAuthMode || enableWhitelist) return; // safe!
775
+ console.error(color.red(message));
776
+ if (getConfigValue('securityOverride', false)) {
777
+ console.warn(color.red('Security has been overridden. If it\'s not a trusted network, change the settings.'));
778
+ return;
779
+ }
780
+ process.exit(1);
781
+ }
782
+
783
+ /**
784
+ * Handles the case where the server failed to start on one or both protocols.
785
+ * @param {boolean} v6Failed If the server failed to start on IPv6
786
+ * @param {boolean} v4Failed If the server failed to start on IPv4
787
+ */
788
+ function handleServerListenFail(v6Failed, v4Failed) {
789
+ if (v6Failed && !enableIPv4) {
790
+ console.error(color.red('fatal error: Failed to start server on IPv6 and IPv4 disabled'));
791
+ process.exit(1);
792
+ }
793
+
794
+ if (v4Failed && !enableIPv6) {
795
+ console.error(color.red('fatal error: Failed to start server on IPv4 and IPv6 disabled'));
796
+ process.exit(1);
797
+ }
798
+
799
+ if (v6Failed && v4Failed) {
800
+ console.error(color.red('fatal error: Failed to start server on both IPv6 and IPv4'));
801
+ process.exit(1);
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Creates an HTTPS server.
807
+ * @param {URL} url The URL to listen on
808
+ * @returns {Promise<void>} A promise that resolves when the server is listening
809
+ * @throws {Error} If the server fails to start
810
+ */
811
+ function createHttpsServer(url) {
812
+ return new Promise((resolve, reject) => {
813
+ const server = https.createServer(
814
+ {
815
+ cert: fs.readFileSync(cliArguments.certPath),
816
+ key: fs.readFileSync(cliArguments.keyPath),
817
+ }, app);
818
+ server.on('error', reject);
819
+ server.on('listening', resolve);
820
+ server.listen(url.port || 443, url.hostname);
821
+ });
822
+ }
823
+
824
+ /**
825
+ * Creates an HTTP server.
826
+ * @param {URL} url The URL to listen on
827
+ * @returns {Promise<void>} A promise that resolves when the server is listening
828
+ * @throws {Error} If the server fails to start
829
+ */
830
+ function createHttpServer(url) {
831
+ return new Promise((resolve, reject) => {
832
+ const server = http.createServer(app);
833
+ server.on('error', reject);
834
+ server.on('listening', resolve);
835
+ server.listen(url.port || 80, url.hostname);
836
+ });
837
+ }
838
+
839
+ async function startHTTPorHTTPS() {
840
+ let v6Failed = false;
841
+ let v4Failed = false;
842
+
843
+ const createFunc = cliArguments.ssl ? createHttpsServer : createHttpServer;
844
+
845
+ if (enableIPv6) {
846
+ try {
847
+ await createFunc(tavernUrlV6);
848
+ } catch (error) {
849
+ console.error('non-fatal error: failed to start server on IPv6');
850
+ console.error(error);
851
+
852
+ v6Failed = true;
853
+ }
854
+ }
855
+
856
+ if (enableIPv4) {
857
+ try {
858
+ await createFunc(tavernUrl);
859
+ } catch (error) {
860
+ console.error('non-fatal error: failed to start server on IPv4');
861
+ console.error(error);
862
+
863
+ v4Failed = true;
864
+ }
865
+ }
866
+
867
+ return [v6Failed, v4Failed];
868
+ }
869
+
870
+ async function startServer() {
871
+ const [v6Failed, v4Failed] = await startHTTPorHTTPS();
872
+
873
+ handleServerListenFail(v6Failed, v4Failed);
874
+ postSetupTasks(v6Failed, v4Failed);
875
+ }
876
+
877
+ async function verifySecuritySettings() {
878
+ // Skip all security checks as listen is set to false
879
+ if (!listen) {
880
+ return;
881
+ }
882
+
883
+ if (!enableAccounts) {
884
+ logSecurityAlert('Your SillyTavern is currently insecurely open to the public. Enable whitelisting, basic authentication or user accounts.');
885
+ }
886
+
887
+ const users = await userModule.getAllEnabledUsers();
888
+ const unprotectedUsers = users.filter(x => !x.password);
889
+ const unprotectedAdminUsers = unprotectedUsers.filter(x => x.admin);
890
+
891
+ if (unprotectedUsers.length > 0) {
892
+ console.warn(color.blue('A friendly reminder that the following users are not password protected:'));
893
+ unprotectedUsers.map(x => `${color.yellow(x.handle)} ${color.red(x.admin ? '(admin)' : '')}`).forEach(x => console.warn(x));
894
+ console.log();
895
+ console.warn(`Consider setting a password in the admin panel or by using the ${color.blue('recover.js')} script.`);
896
+ console.log();
897
+
898
+ if (unprotectedAdminUsers.length > 0) {
899
+ logSecurityAlert('If you are not using basic authentication or whitelisting, you should set a password for all admin users.');
900
+ }
901
+ }
902
+ }
903
+
904
+ // User storage module needs to be initialized before starting the server
905
+ userModule.initUserStorage(dataRoot)
906
+ .then(userModule.ensurePublicDirectoriesExist)
907
+ .then(userModule.migrateUserData)
908
+ .then(verifySecuritySettings)
909
+ .then(preSetupTasks)
910
+ .finally(startServer);
start.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # Make sure pwd is the directory of the script
4
+ cd "$(dirname "$0")"
5
+
6
+ if ! command -v npm &> /dev/null
7
+ then
8
+ read -p "npm is not installed. Do you want to install nodejs and npm? (y/n)" choice
9
+ case "$choice" in
10
+ y|Y )
11
+ echo "Installing nvm..."
12
+ export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
13
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
14
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
15
+ source ~/.bashrc
16
+ nvm install --lts
17
+ nvm use --lts;;
18
+ n|N )
19
+ echo "Nodejs and npm will not be installed."
20
+ exit;;
21
+ * )
22
+ echo "Invalid option. Nodejs and npm will not be installed."
23
+ exit;;
24
+ esac
25
+ fi
26
+
27
+ echo "Installing Node Modules..."
28
+ export NODE_ENV=production
29
+ npm i --no-audit --no-fund --quiet --omit=dev
30
+
31
+ echo "Entering SillyTavern..."
32
+ node "server.js" "$@"