├── .dockerignore ├── .env.template ├── .github ├── CONTRIBUTING.md ├── FUNDING.yml └── workflows │ ├── build_and_push.yaml │ ├── coverage_and_lint.yml │ ├── deploy.yaml │ └── signoff.yaml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── config.template.toml ├── core ├── __init__.py ├── config.py ├── database.py ├── models.py ├── scanners.py ├── server.py └── utils.py ├── docker-compose.yaml ├── launcher.py ├── migration.sql ├── pyproject.toml ├── redis.conf ├── requirements.txt ├── schema.sql ├── types_ ├── config.py ├── github.py └── scanner.py ├── views ├── __init__.py ├── api.py ├── docs.py └── htmx.py └── web ├── docs.html ├── index.html ├── maint.html ├── password.html ├── paste.html └── static ├── images ├── favicon.ico ├── keyboard-light.svg ├── keyboard.svg ├── logo.svg └── vsc.svg ├── packages ├── highlight.min.js └── htmx.min.js ├── scripts ├── dragDrop.js ├── files.js ├── files.old.js ├── hidecopy.js ├── highlights.js ├── highlightsHTMX.js ├── initialTheme.js ├── lineHighlights.js ├── shortcuts.js ├── themes.js └── utils.js └── styles ├── global.css └── highlights.css /.dockerignore: -------------------------------------------------------------------------------- 1 | .git/ 2 | .github/ 3 | types_/ 4 | config.template.toml 5 | Dockerfile 6 | LICENSE 7 | migration.sql 8 | pyproject.toml 9 | README.md 10 | -------------------------------------------------------------------------------- /.env.template: -------------------------------------------------------------------------------- 1 | POSTGRES_USER=mystbin 2 | POSTGRES_PASSWORD=mystbin 3 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing to Mystbin! 2 | 3 | First off, thanks for taking the time to contribute. It makes the service substantially better. :+1: 4 | 5 | The following is a set of guidelines for contributing to the repository. These are guidelines, not hard rules. 6 | 7 | ## Good Bug Reports 8 | 9 | Please be aware of the following things when filing bug reports. 10 | 11 | 1. Don't open duplicate issues. Please search your issue to see if it has been asked already. Duplicate issues will be closed. 12 | 2. When filing a bug about exceptions or tracebacks, please include the *complete* traceback. Without the complete traceback the issue might be **unsolvable** and you will be asked to provide more information. 13 | 3. Make sure to provide enough information to make the issue workable. The issue template will generally walk you through the process, but they are enumerated here as well: 14 | - A **summary** of your bug report. This is generally a quick sentence or two to describe the issue in human terms. 15 | - Guidance on **how to reproduce the issue**. Ideally, this should have a paste ID that allows us to run and see the issue for ourselves to debug. **Please make sure any of your tokens are not displayed**. If you cannot provide a paste ID, then let us know what the steps were, how often it happens, etc. 16 | - Tell us **what you expected to happen**. That way we can meet that expectation. 17 | - Tell us **what actually happens**. What ends up happening in reality? It's not helpful to say "it fails" or "it doesn't work". Say *how* it failed, do you get an error? Does it hang? How are the expectations different from reality? 18 | - Tell us **information about your environment**. What web browser(s) does this occur on, etc? 19 | 20 | If the bug report is missing this information then it'll take us longer to fix the issue. We will probably ask for clarification, and barring that if no response was given then the issue will be closed. 21 | 22 | ## Submitting a Pull Request 23 | 24 | Submitting a pull request is fairly simple, just make sure it focuses on a single aspect and doesn't manage to have scope creep, and it's probably good to go. It would be incredibly lovely if the style is consistent to that found in the project. This project follows PEP-8 guidelines (mostly) with a column limit of 125. 25 | There are provided tool rules in `pyproject.toml` for `isort`, `black` and `pyright` when working on the backend side of things. 26 | There are rules provided for prettier when working on the frontend side of things. 27 | 28 | There are actions that run on new PRs and if those checks fail then the PR will not be accepted. 29 | 30 | NOTE: We do not provide `black` and `isort` in the requirements files for the backend. Feel free to install these yourself. 31 | 32 | ### Git Commit Guidelines 33 | 34 | - Use present tense (e.g. "Add feature" not "Added feature") 35 | - Limit all lines to 72 characters or fewer. 36 | - Reference issues or pull requests outside the first line. 37 | - Please use the shorthand `#123` and not the full URL. 38 | 39 | If you do not meet any of these guidelines, don't fret. Chances are they will be fixed upon rebasing but please do try to meet them to remove some workload. 40 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | 2 | github: [IAmTomahawkx, EvieePy, AbstractUmbra] 3 | ko_fi: AbstractUmbra 4 | -------------------------------------------------------------------------------- /.github/workflows/build_and_push.yaml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | # GitHub recommends pinning actions to a commit SHA. 7 | # To get a newer version, you will need to update the SHA. 8 | # You can also reference a tag or branch, but the action may change without warning. 9 | 10 | name: Create and publish a Docker image 11 | 12 | on: 13 | workflow_dispatch: 14 | push: 15 | branches: 16 | - main 17 | paths: 18 | - '**.html' 19 | - '**.css' 20 | - '**.js' 21 | - '**.py' 22 | - '**.toml' 23 | - '**.svg' 24 | 25 | concurrency: 26 | cancel-in-progress: true 27 | group: ci-${{ github.ref }} 28 | 29 | env: 30 | REGISTRY: ghcr.io 31 | IMAGE_NAME: ${{ github.repository }} 32 | 33 | jobs: 34 | build-and-push-image: 35 | runs-on: ubuntu-latest 36 | env: 37 | GIT_SHA: ${GITHUB_SHA::7} 38 | permissions: 39 | contents: read 40 | packages: write 41 | 42 | steps: 43 | - name: Checkout repository 44 | uses: actions/checkout@v4 45 | with: 46 | fetch-depth: 0 47 | 48 | - name: Set up QEMU 49 | uses: docker/setup-qemu-action@v3 50 | 51 | - name: Set up Docker Buildx 52 | uses: docker/setup-buildx-action@v3 53 | 54 | - name: Log in to the Container registry 55 | uses: docker/login-action@master 56 | with: 57 | registry: ${{ env.REGISTRY }} 58 | username: ${{ github.actor }} 59 | password: ${{ secrets.GITHUB_TOKEN }} 60 | 61 | - name: Extract metadata (tags, labels) for Docker 62 | id: meta 63 | uses: docker/metadata-action@master 64 | with: 65 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 66 | 67 | - name: Generate lowername image 68 | id: image-name 69 | run: | 70 | echo "IMAGE_NAME_LC=${IMAGE_NAME,,}" >> "${GITHUB_OUTPUT}" 71 | env: 72 | IMAGE_NAME: '${{ env.IMAGE_NAME }}' 73 | 74 | - name: Get short SHA 75 | id: slug 76 | run: echo "GIT_SHORT_SHA7=$(echo ${GITHUB_SHA} | cut -c1-7)" >> "$GITHUB_OUTPUT" 77 | 78 | - name: Build and push Docker image 79 | uses: docker/build-push-action@v5 80 | with: 81 | context: . 82 | push: true 83 | tags: | 84 | ${{ steps.meta.outputs.tags }} 85 | ghcr.io/${{ steps.image-name.outputs.IMAGE_NAME_LC }}:${{ steps.slug.outputs.GIT_SHORT_SHA7 }} 86 | ghcr.io/${{ steps.image-name.outputs.IMAGE_NAME_LC }}:latest 87 | labels: ${{ steps.meta.outputs.labels }} 88 | -------------------------------------------------------------------------------- /.github/workflows/coverage_and_lint.yml: -------------------------------------------------------------------------------- 1 | name: Type Coverage and Linting 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | types: [opened, reopened, synchronize] 11 | 12 | jobs: 13 | check: 14 | runs-on: ubuntu-latest 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | python-version: ["3.11", "3.x"] 19 | 20 | name: "Type Coverage and Linting @ ${{ matrix.python-version }}" 21 | steps: 22 | - name: "Checkout Repository" 23 | uses: actions/checkout@v3 24 | with: 25 | fetch-depth: 0 26 | 27 | - name: "Setup Python @ ${{ matrix.python-version }}" 28 | id: setup-python 29 | uses: actions/setup-python@v4 30 | with: 31 | python-version: "${{ matrix.python-version }}" 32 | cache: "pip" 33 | 34 | - name: "Install Python deps @ ${{ matrix.python-version }}" 35 | id: install-deps 36 | run: | 37 | pip install -Ur requirements.txt 38 | - name: "Run Pyright @ ${{ matrix.python-version }}" 39 | uses: jakebailey/pyright-action@v1 40 | with: 41 | no-comments: ${{ matrix.python-version != '3.x' }} 42 | warnings: false 43 | 44 | - name: Lint with Ruff 45 | if: ${{ always() && steps.install-deps.outcome == 'success' }} 46 | uses: chartboost/ruff-action@v1 47 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | workflow_run: 5 | workflows: ["Create and publish a Docker image"] 6 | branches: [main] 7 | types: 8 | - completed 9 | 10 | jobs: 11 | deploy: 12 | name: Deploy bot 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Remote deploy 16 | uses: appleboy/ssh-action@master 17 | with: 18 | host: ${{ secrets.SSH_HOST }} 19 | key: ${{ secrets.SSH_KEY }} 20 | port: ${{ secrets.SSH_PORT }} 21 | script: | 22 | cd ~/mystbin 23 | git reset --hard HEAD || true 24 | git pull origin main 25 | docker compose --profile redis pull 26 | docker compose --profile redis up --build -d mystbin 27 | username: ${{ secrets.SSH_USER }} 28 | -------------------------------------------------------------------------------- /.github/workflows/signoff.yaml: -------------------------------------------------------------------------------- 1 | name: validate-signoff 2 | on: 3 | pull_request: 4 | types: 5 | - opened 6 | - edited 7 | 8 | jobs: 9 | validate: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: PR Description Check 13 | uses: pythonistaguild/pr-description-check@v1.0 14 | with: 15 | content: "[x] I have read and agree to the [Developer Certificate of Origin]" 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | # Config Files... 163 | config.toml 164 | .config.toml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.12-slim 2 | 3 | LABEL org.opencontainers.image.source=https://github.com/pythonistaguild/mystbin 4 | LABEL org.opencontainers.image.description="Container for running MystB.in" 5 | LABEL org.opencontainers.image.licenses=GPLv3 6 | 7 | RUN mkdir -p /etc/apt/keyrings \ 8 | && apt update -y \ 9 | && apt-get install --no-install-recommends -y \ 10 | # deps for building python deps 11 | git \ 12 | build-essential \ 13 | libcurl4-gnutls-dev \ 14 | gnutls-dev \ 15 | libmagic-dev \ 16 | && rm -rf /var/lib/apt/lists/* 17 | 18 | # copy project requirement files here to ensure they will be cached. 19 | WORKDIR /app 20 | COPY requirements.txt ./ 21 | 22 | # install runtime deps 23 | RUN pip install -Ur requirements.txt 24 | 25 | COPY . /app/ 26 | ENTRYPOINT python -O launcher.py 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MystBin 2 | 3 | Easily share code and text. 4 | 5 | [Website](https://mystb.in) 6 | 7 | [API Documentation](https://mystb.in/api/documentation) 8 | 9 | [Install on VSCode](https://marketplace.visualstudio.com/items?itemName=PythonistaGuild.mystbin) 10 | 11 | 12 | ### Running without Docker 13 | **Requirements:** 14 | - Postgres 15 | 16 | **Setup:** 17 | - Clone 18 | - Copy `config.template.toml` into `config.toml` 19 | - Set Database connection DSN. 20 | - Optionally set URLs to a running Redis Instance. 21 | - ! If you haven't already: Create a Database in `postgres` (Default `mystbin`) 22 | - Install dependencies (Preferably to a `venv`): `pip install -Ur requirements.txt` 23 | - Optionally in `core/server.py` set `ignore_localhost=` to `False` in the RateLimit Middleware for testing. 24 | - Run: `python launcher.py` 25 | 26 | ### Running with Docker 27 | **Requirements** 28 | - Docker 29 | - Docker Compose 30 | 31 | **Setup:** 32 | - Clone 33 | - Copy `config.template.toml` into `config.toml` 34 | - The default config for database (and redis) should work Out of Box. 35 | - Optionally in `core/server.py` set `ignore_localhost=` to `False` in the RateLimit Middleware for testing. 36 | - Run `docker compose up -d` to start the services. 37 | - If you want to use redis for session/limit handling, run with the redis profile: `docker compose --profile redis up -d` 38 | - The redis container doesn't expose connections outside of the network, but for added security edit `redis.conf` and change the password. 39 | -------------------------------------------------------------------------------- /config.template.toml: -------------------------------------------------------------------------------- 1 | [SERVER] 2 | host = "localhost" 3 | port = 8181 4 | session_secret = "" # Run: import secrets; print(secrets.token_urlsafe(64)) 5 | maintenance = false 6 | 7 | [DATABASE] 8 | dsn = "postgres://mystbin:mystbin@database:5432/mystbin" 9 | 10 | [LIMITS] 11 | paste_get = { rate = 30, per = 60, priority = 1, bucket = "ip" } 12 | paste_get_day = { rate = 7200, per = 86400, priority = 2, bucket = "ip" } 13 | paste_post = { rate = 10, per = 60, priority = 1, bucket = "ip" } 14 | paste_post_day = { rate = 1440, per = 86400, priority = 2, bucket = "ip" } 15 | global_limit = { rate = 21600, per = 86400, priority = 1, bucket = "ip" } 16 | 17 | [PASTES] 18 | char_limit = 300_000 19 | file_limit = 5 20 | name_limit = 25 21 | 22 | [REDIS] # optional key 23 | limiter = "redis://redis:6379/0" # required if key present 24 | sessions = "redis://redis:6379/1" # required if key present 25 | 26 | [GITHUB] # optional key 27 | token = "..." # a github token capable of creating gists, non-optional if the above key is provided 28 | timeout = 10 # how long to wait between posting gists if there's an influx of tokens posted. Non-optional 29 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from .config import CONFIG as CONFIG 20 | from .database import Database as Database 21 | from .server import Application as Application 22 | -------------------------------------------------------------------------------- /core/config.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | from typing import TYPE_CHECKING 22 | 23 | import tomllib 24 | 25 | 26 | if TYPE_CHECKING: 27 | from types_.config import Config 28 | 29 | 30 | __all__ = ("CONFIG",) 31 | 32 | 33 | with open("config.toml", "rb") as fp: 34 | CONFIG: Config = tomllib.load(fp) # type: ignore 35 | -------------------------------------------------------------------------------- /core/database.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | import asyncio 22 | import datetime 23 | import logging 24 | from typing import TYPE_CHECKING, Any, Self 25 | 26 | import aiohttp 27 | import asyncpg 28 | 29 | from core import CONFIG 30 | 31 | from . import utils 32 | from .models import FileModel, PasteModel 33 | from .scanners import SecurityInfo, Services 34 | 35 | 36 | if TYPE_CHECKING: 37 | _Pool = asyncpg.Pool[asyncpg.Record] 38 | from types_.config import Github 39 | from types_.github import PostGist 40 | from types_.scanner import ScannerSecret 41 | else: 42 | _Pool = asyncpg.Pool 43 | 44 | 45 | LOGGER: logging.Logger = logging.getLogger(__name__) 46 | 47 | 48 | class Database: 49 | pool: _Pool 50 | 51 | def __init__(self, *, dsn: str, session: aiohttp.ClientSession | None = None, github_config: Github | None) -> None: 52 | self._dsn: str = dsn 53 | self.session: aiohttp.ClientSession | None = session 54 | self._handling_tokens = bool(self.session and github_config) 55 | 56 | if self._handling_tokens: 57 | LOGGER.info("Setup to handle Discord Tokens.") 58 | assert github_config # guarded by if here 59 | 60 | self._gist_token = github_config["token"] 61 | self._gist_timeout = github_config["timeout"] 62 | # tokens bucket for gist posting: {paste_id: token\ntoken} 63 | self.__tokens_bucket: dict[str, str] = {} 64 | self.__token_lock = asyncio.Lock() 65 | self.__token_task = asyncio.create_task(self._token_task()) 66 | 67 | async def __aenter__(self) -> Self: 68 | await self.connect() 69 | return self 70 | 71 | async def __aexit__(self, *_: Any) -> None: 72 | task: asyncio.Task[None] | None = getattr(self, "__token_task", None) 73 | if task: 74 | task.cancel() 75 | 76 | await self.close() 77 | 78 | async def _token_task(self) -> None: 79 | # won't run unless pre-reqs are met in __init__ 80 | while True: 81 | if self.__tokens_bucket: 82 | async with self.__token_lock: 83 | await self._post_gist_of_tokens() 84 | 85 | await asyncio.sleep(self._gist_timeout) 86 | 87 | def _handle_discord_tokens(self, tokens: list[str], paste_id: str) -> None: 88 | if not self._handling_tokens or not tokens: 89 | return 90 | 91 | LOGGER.info( 92 | "Discord bot token located and added to token bucket. Current bucket size is: %s", len(self.__tokens_bucket) 93 | ) 94 | 95 | self.__tokens_bucket[paste_id] = "\n".join(tokens) 96 | 97 | async def _post_gist_of_tokens(self) -> None: 98 | assert self.session # guarded in caller 99 | json_payload: PostGist = { 100 | "description": "MystBin found these Discord tokens in a public paste, and posted them here to invalidate them. If you intended to share these, please apply a password to the paste.", 101 | "files": {}, 102 | "public": True, 103 | } 104 | 105 | github_headers = { 106 | "Accept": "application/vnd.github+json", 107 | "Authorization": f"Bearer {self._gist_token}", 108 | "X-GitHub-Api-Version": "2022-11-28", 109 | } 110 | 111 | current_tokens = self.__tokens_bucket 112 | self.__tokens_bucket = {} 113 | 114 | for paste_id, tokens in current_tokens.items(): 115 | filename = str(datetime.datetime.now(datetime.UTC)) + "-tokens.txt" 116 | json_payload["files"][filename] = {"content": f"https://mystb.in/{paste_id}:\n{tokens}"} 117 | 118 | success = False 119 | 120 | try: 121 | async with self.session.post( 122 | "https://api.github.com/gists", headers=github_headers, json=json_payload 123 | ) as resp: 124 | success = resp.ok 125 | 126 | if not success: 127 | response_body = await resp.text() 128 | LOGGER.error( 129 | "Failed to create gist with token bucket with response status code %s and response body:\n\n%s", 130 | resp.status, 131 | response_body, 132 | ) 133 | except (aiohttp.ClientError, aiohttp.ClientOSError) as error: 134 | success = False 135 | LOGGER.error("Failed to handle gist creation due to a client or operating system error", exc_info=error) 136 | 137 | if success: 138 | LOGGER.info("Gist created and invalidated tokens from %s pastes.", len(current_tokens)) 139 | else: 140 | self.__tokens_bucket.update(current_tokens) 141 | 142 | async def connect(self) -> None: 143 | try: 144 | pool: asyncpg.Pool[asyncpg.Record] | None = await asyncpg.create_pool(dsn=self._dsn) 145 | except Exception as e: 146 | raise RuntimeError from e 147 | 148 | if not pool: 149 | raise RuntimeError("Failed to connect to the database... No additional information.") 150 | 151 | with open("schema.sql") as fp: 152 | await pool.execute(fp.read()) 153 | 154 | self.pool = pool 155 | LOGGER.info("Successfully connected to the database.") 156 | 157 | async def close(self) -> None: 158 | try: 159 | await asyncio.wait_for(self.pool.close(), timeout=10) 160 | except TimeoutError: 161 | LOGGER.warning("Failed to greacefully close the database connection...") 162 | else: 163 | LOGGER.info("Successfully closed the database connection.") 164 | 165 | async def fetch_paste(self, identifier: str, *, password: str | None) -> PasteModel | None: 166 | assert self.pool 167 | 168 | paste_query: str = """ 169 | UPDATE pastes SET views = views + 1 WHERE id = $1 170 | RETURNING *, 171 | CASE WHEN password IS NOT NULL THEN true 172 | ELSE false END AS has_password, 173 | CASE WHEN password = CRYPT($2, password) THEN true 174 | ELSE false END AS password_ok 175 | """ 176 | 177 | file_query: str = """ 178 | SELECT * FROM files WHERE parent_id = $1 179 | """ 180 | 181 | async with self.pool.acquire() as connection: 182 | record: asyncpg.Record | None = await connection.fetchrow(paste_query, identifier, password) 183 | 184 | if not record: 185 | return 186 | 187 | paste: PasteModel = PasteModel(record) 188 | if paste.expires and paste.expires <= datetime.datetime.now(tz=datetime.timezone.utc): 189 | await connection.execute("DELETE FROM pastes WHERE id = $1", identifier) 190 | return 191 | 192 | if paste.has_password and not paste.password_ok: 193 | return paste 194 | 195 | records: list[asyncpg.Record] = await connection.fetch(file_query, identifier) 196 | paste.files = [FileModel(d) for d in records] 197 | 198 | return paste 199 | 200 | async def create_paste(self, *, data: dict[str, Any]) -> PasteModel: 201 | assert self.pool 202 | 203 | paste_query: str = """ 204 | INSERT INTO pastes (id, expires, password, safety) 205 | VALUES ($1, $2, (SELECT crypt($3, gen_salt('bf')) WHERE $3 is not null), $4) 206 | RETURNING * 207 | """ 208 | 209 | file_query: str = """ 210 | INSERT INTO files (parent_id, content, filename, loc, annotation, warning_positions) 211 | VALUES ($1, $2, $3, $4, $5, $6) 212 | RETURNING * 213 | """ 214 | 215 | files: list[dict[str, Any]] = data["files"] 216 | expiry: str | None = data["expires"] 217 | password: str | None = data["password"] 218 | 219 | async with self.pool.acquire() as connection: 220 | while True: 221 | identifier: str = utils.generate_id() 222 | safety: str = utils.generate_safety_token() 223 | 224 | try: 225 | paster: asyncpg.Record | None = await connection.fetchrow( 226 | paste_query, 227 | identifier, 228 | expiry, 229 | password, 230 | safety, 231 | ) 232 | except asyncpg.exceptions.UniqueViolationError: 233 | continue 234 | else: 235 | break 236 | 237 | assert paster 238 | 239 | paste: PasteModel = PasteModel(paster) 240 | async with connection.transaction(): 241 | for index, file in enumerate(files, 1): 242 | name: str = (file.get("filename") or f"file_{index}")[-CONFIG["PASTES"]["name_limit"] :] 243 | name = "_".join(name.splitlines()) 244 | 245 | # Normalise newlines... 246 | content: str = file["content"].replace("\r\n", "\n").replace("\r", "\n") 247 | loc: int = file["content"].count("\n") + 1 248 | 249 | positions: list[int] = [] 250 | extra: str = "" 251 | 252 | secrets: list[ScannerSecret] = SecurityInfo.scan_file(content) 253 | for payload in secrets: 254 | service: Services = payload["service"] 255 | 256 | extra += f"{service.value}, " 257 | positions += [t[0] for t in payload["tokens"]] 258 | 259 | if not password and self._handling_tokens and service is Services.discord: 260 | self._handle_discord_tokens(tokens=[t[1] for t in payload["tokens"]], paste_id=paste.id) 261 | 262 | extra = extra.removesuffix(", ") 263 | annotation = f"Contains possibly sensitive data from: {extra}" if extra else "" 264 | 265 | row: asyncpg.Record | None = await connection.fetchrow( 266 | file_query, 267 | paste.id, 268 | content, 269 | name, 270 | loc, 271 | annotation, 272 | sorted(positions), 273 | ) 274 | 275 | if row: 276 | paste.files.append(FileModel(row)) 277 | 278 | return paste 279 | 280 | async def fetch_paste_security(self, *, token: str) -> PasteModel | None: 281 | query: str = """SELECT * FROM pastes WHERE safety = $1""" 282 | 283 | async with self.pool.acquire() as connection: 284 | record: asyncpg.Record | None = await connection.fetchrow(query, token) 285 | if not record: 286 | return 287 | 288 | paste: PasteModel = PasteModel(record=record) 289 | if paste.expires and paste.expires <= datetime.datetime.now(tz=datetime.timezone.utc): 290 | await connection.execute("DELETE FROM pastes WHERE id = $1", token) 291 | return 292 | 293 | return paste 294 | 295 | async def delete_paste_security(self, *, token: str) -> None: 296 | query: str = """DELETE FROM pastes WHERE safety = $1""" 297 | 298 | async with self.pool.acquire() as connection: 299 | await connection.execute(query, token) 300 | -------------------------------------------------------------------------------- /core/models.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | import datetime 20 | from collections.abc import Iterator, Mapping 21 | from typing import Any 22 | 23 | import asyncpg 24 | 25 | 26 | class BaseModel(Mapping[str, Any]): 27 | __slots__ = ("record",) 28 | 29 | def __init__(self, record: asyncpg.Record | dict[str, Any], /) -> None: 30 | self.record: dict[str, Any] = dict(record) 31 | 32 | def __getitem__(self, key: str) -> Any: 33 | return self.record[key] 34 | 35 | def __iter__(self) -> Iterator[str]: 36 | return iter(self.record) 37 | 38 | def __len__(self) -> int: 39 | return len(self.record) 40 | 41 | def serialize(self, *, exclude: list[str] = ["file_index"]) -> dict[str, Any]: 42 | new: dict[str, Any] = {} 43 | 44 | for key, value in self.record.items(): 45 | if key in exclude: 46 | continue 47 | 48 | if isinstance(value, datetime.datetime): 49 | new[key] = value.isoformat() 50 | else: 51 | new[key] = value 52 | 53 | if isinstance(self, PasteModel) and self.files: 54 | new["files"] = [f.serialize() for f in self.files] 55 | 56 | return new 57 | 58 | 59 | class FileModel(BaseModel): 60 | def __init__(self, record: asyncpg.Record | dict[str, Any]) -> None: 61 | super().__init__(record) 62 | 63 | self.parent_id: str = record["parent_id"] 64 | self.content: str = record["content"] 65 | self.filename: str = record["filename"] 66 | self.loc: int = record["loc"] 67 | self.charcount: int = record["charcount"] 68 | self.index: int = record["file_index"] 69 | self.annotation: str | None = record["annotation"] 70 | self.warning_positions: list[int] = record["warning_positions"] 71 | 72 | 73 | class PasteModel(BaseModel): 74 | def __init__(self, record: asyncpg.Record) -> None: 75 | super().__init__(record) 76 | 77 | self.id: str = record["id"] 78 | self.created_at: datetime.datetime = record["created_at"] 79 | self.expires: datetime.datetime | None = record["expires"] 80 | self.password: str | None = record["password"] 81 | self.views: int = record["views"] 82 | self.safety: str = record["safety"] 83 | self.has_password: bool | None = record.get("has_password", None) 84 | self.password_ok: bool | None = record.get("password_ok", None) 85 | self.files: list[FileModel] = [] 86 | -------------------------------------------------------------------------------- /core/scanners.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | import base64 22 | import binascii 23 | import enum 24 | import logging 25 | import re 26 | from typing import TYPE_CHECKING, ClassVar 27 | 28 | 29 | if TYPE_CHECKING: 30 | from types_.scanner import ScannerSecret 31 | 32 | 33 | logger: logging.Logger = logging.getLogger(__name__) 34 | 35 | 36 | class Services(enum.Enum): 37 | discord = "Discord" 38 | pypi = "PyPi" 39 | github = "GitHub" 40 | 41 | 42 | class BaseScanner: 43 | REGEX: ClassVar[re.Pattern[str]] 44 | SERVICE: ClassVar[Services] 45 | 46 | @classmethod 47 | def match(cls, content: str) -> ScannerSecret: 48 | matches: list[tuple[int, str]] = [(m.start(0), m.group(0)) for m in cls.REGEX.finditer(content)] 49 | 50 | payload: ScannerSecret = { 51 | "service": cls.SERVICE, 52 | "tokens": matches, 53 | } 54 | 55 | return payload 56 | 57 | 58 | class DiscordScanner(BaseScanner): 59 | REGEX = re.compile(r"[a-zA-Z0-9_-]{23,28}\.[a-zA-Z0-9_-]{6,7}\.[a-zA-Z0-9_-]{27,}") 60 | SERVICE = Services.discord 61 | 62 | @staticmethod 63 | def validate_discord_token(token: str) -> bool: 64 | try: 65 | # Just check if the first part validates as a user ID 66 | (user_id, _, _) = token.split(".") 67 | user_id = int(base64.b64decode(user_id + "=" * (len(user_id) % 4), validate=True)) 68 | except (ValueError, binascii.Error): 69 | return False 70 | else: 71 | return True 72 | 73 | @classmethod 74 | def match(cls, content: str) -> ScannerSecret: 75 | matches: list[tuple[int, str]] = [ 76 | (m.start(0), m.group(0)) for m in cls.REGEX.finditer(content) if cls.validate_discord_token(m.group(0)) 77 | ] 78 | 79 | payload: ScannerSecret = { 80 | "service": cls.SERVICE, 81 | "tokens": matches, 82 | } 83 | 84 | return payload 85 | 86 | 87 | class PyPiScanner(BaseScanner): 88 | REGEX = re.compile(r"pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{70,}") 89 | SERVICE = Services.pypi 90 | 91 | 92 | class GitHubScanner(BaseScanner): 93 | REGEX = re.compile(r"((ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36})") 94 | SERVICE = Services.github 95 | 96 | 97 | class SecurityInfo: 98 | __SERVICE_MAPPING: ClassVar[dict[Services, type[BaseScanner]]] = { 99 | Services.discord: DiscordScanner, 100 | Services.pypi: PyPiScanner, 101 | Services.github: GitHubScanner, 102 | } 103 | 104 | @classmethod 105 | def scan_file( 106 | cls, 107 | file: str, 108 | /, 109 | *, 110 | allowed: list[Services] | None = None, 111 | disallowed: list[Services] | None = None, 112 | ) -> list[ScannerSecret]: 113 | """Scan for tokens in a given files content. 114 | 115 | You may pass a list of allowed or disallowed Services. 116 | If both lists are empty (Default) all available services will be scanned. 117 | """ 118 | disallowed = disallowed or [] 119 | allowed = allowed or list(Services) 120 | 121 | services: list[Services] = [s for s in allowed if s not in disallowed] 122 | secrets: list[ScannerSecret] = [] 123 | 124 | for service in services: 125 | scanner: type[BaseScanner] | None = cls.__SERVICE_MAPPING.get(service, None) 126 | if not scanner: 127 | logging.warning("The provided service %r is not a supported or a valid service.", service) 128 | continue 129 | 130 | found: ScannerSecret = scanner.match(file) 131 | if found["tokens"]: 132 | secrets.append(found) 133 | 134 | return secrets 135 | -------------------------------------------------------------------------------- /core/server.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | import logging 20 | 21 | import aiohttp 22 | import starlette_plus 23 | from starlette.middleware import Middleware 24 | from starlette.routing import Mount, Route 25 | from starlette.schemas import SchemaGenerator 26 | from starlette.staticfiles import StaticFiles 27 | 28 | from core.database import Database 29 | from views import * 30 | 31 | from .config import CONFIG 32 | 33 | 34 | logger: logging.Logger = logging.getLogger(__name__) 35 | 36 | 37 | class Application(starlette_plus.Application): 38 | def __init__(self, *, database: Database, session: aiohttp.ClientSession | None = None) -> None: 39 | self.database: Database = database 40 | self.session: aiohttp.ClientSession | None = session 41 | self.schemas: SchemaGenerator | None = None 42 | 43 | views: list[starlette_plus.View] = [ 44 | HTMXView(self), 45 | APIView(self), 46 | DocsView(self), 47 | ] 48 | routes: list[Mount | Route] = [Mount("/static", app=StaticFiles(directory="web/static"), name="static")] 49 | 50 | if redis_key := CONFIG.get("REDIS"): 51 | limit_url = redis_key["limiter"] 52 | session_url = redis_key["sessions"] 53 | else: 54 | limit_url = None 55 | session_url = None 56 | 57 | limit_redis = starlette_plus.Redis(url=limit_url) 58 | sess_redis = starlette_plus.Redis(url=session_url) 59 | 60 | global_limits = [CONFIG["LIMITS"]["global_limit"]] 61 | middleware = [ 62 | Middleware( 63 | starlette_plus.middleware.RatelimitMiddleware, 64 | ignore_localhost=True, 65 | redis=limit_redis, 66 | global_limits=global_limits, 67 | ), 68 | Middleware( 69 | starlette_plus.middleware.SessionMiddleware, 70 | secret=CONFIG["SERVER"]["session_secret"], 71 | redis=sess_redis, 72 | max_age=86400, 73 | ), 74 | ] 75 | 76 | if CONFIG["SERVER"]["maintenance"]: 77 | # inject a catch all before any route... 78 | routes.append(Route("/", self.maint_mode, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])) 79 | routes.append( 80 | Route("/{path:path}", self.maint_mode, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) 81 | ) 82 | 83 | super().__init__(on_startup=[self.event_ready], views=views, routes=routes, middleware=middleware) 84 | 85 | @staticmethod 86 | async def maint_mode(request: starlette_plus.Request) -> starlette_plus.Response: 87 | return starlette_plus.FileResponse("web/maint.html") 88 | 89 | @starlette_plus.route("/docs") 90 | @starlette_plus.route("/documentation") 91 | async def documentation_redirect(self, request: starlette_plus.Request) -> starlette_plus.Response: 92 | return starlette_plus.RedirectResponse("/api/documentation") 93 | 94 | @starlette_plus.route("/documents", methods=["POST"]) 95 | @starlette_plus.route("/api/documents", methods=["POST"]) 96 | async def documents_redirect(self, request: starlette_plus.Request) -> starlette_plus.Response: 97 | # Compat redirect route... 98 | return starlette_plus.RedirectResponse("/api/paste", status_code=308) 99 | 100 | async def event_ready(self) -> None: 101 | self.schemas = SchemaGenerator( 102 | { 103 | "openapi": "3.1.0", 104 | "info": { 105 | "title": "MystBin API", 106 | "version": "4.0", 107 | "summary": "API Documentation", 108 | "description": "MystBin - Easily share code and text.", 109 | }, 110 | } 111 | ) 112 | logger.info("MystBin application has successfully started!") 113 | -------------------------------------------------------------------------------- /core/utils.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | import base64 22 | import binascii 23 | import datetime 24 | import json 25 | import re 26 | import secrets 27 | from typing import Any 28 | 29 | import starlette_plus 30 | 31 | from core import CONFIG 32 | 33 | 34 | TOKEN_REGEX = re.compile(r"[a-zA-Z0-9_-]{23,28}\.[a-zA-Z0-9_-]{6,7}\.[a-zA-Z0-9_-]{27,}") 35 | 36 | 37 | def generate_id() -> str: 38 | return secrets.token_hex(9) 39 | 40 | 41 | def generate_safety_token() -> str: 42 | return secrets.token_urlsafe(64) 43 | 44 | 45 | async def json_or_text(request: starlette_plus.Request) -> dict[str, Any] | str: 46 | text: str = str(await request.body()) 47 | 48 | try: 49 | data: dict[str, Any] = json.loads(text) 50 | except json.JSONDecodeError: 51 | return text 52 | 53 | return data 54 | 55 | 56 | def validate_paste(data: dict[str, Any]) -> starlette_plus.Response | None: 57 | limit: int = CONFIG["PASTES"]["char_limit"] 58 | file_limit: int = CONFIG["PASTES"]["file_limit"] 59 | 60 | try: 61 | files: list[dict[str, str | None]] = data["files"] 62 | except KeyError: 63 | return starlette_plus.JSONResponse({"error": 'Missing the "files" parameter.'}, status_code=400) 64 | 65 | if len(files) > file_limit: 66 | return starlette_plus.JSONResponse( 67 | {"error": f'Paste exceeds the file limit of "{file_limit}" files.'}, 68 | status_code=400, 69 | ) 70 | 71 | for index, file in enumerate(files): 72 | try: 73 | content: str | None = file["content"] 74 | except KeyError: 75 | return starlette_plus.JSONResponse( 76 | {"error": f'The file at index "{index}" is missing the content parameter.'}, 77 | status_code=400, 78 | ) 79 | 80 | if not content: 81 | return starlette_plus.JSONResponse( 82 | {"error": f'The file at index "{index}" has no content.'}, 83 | status_code=400, 84 | ) 85 | 86 | if len(content) > limit: 87 | return starlette_plus.JSONResponse( 88 | {"error": f'The file at index "{index}" exceeds content size limits of "{limit}" characters.'}, 89 | status_code=400, 90 | ) 91 | 92 | 93 | def validate_discord_token(token: str) -> bool: 94 | try: 95 | # Just check if the first part validates as a user ID 96 | (user_id, _, _) = token.split(".") 97 | user_id = int(base64.b64decode(user_id + "==", validate=True)) 98 | except (ValueError, binascii.Error): 99 | return False 100 | else: 101 | return True 102 | 103 | 104 | def pluralize(count: int, singular: str) -> str: 105 | return singular if count == 1 else singular + "s" 106 | 107 | 108 | def natural_time( 109 | td: datetime.timedelta, 110 | /, 111 | *, 112 | source: datetime.datetime | None = None, 113 | ) -> str: 114 | now = source or datetime.datetime.now(datetime.UTC) 115 | 116 | then = now - td 117 | future = then > now 118 | 119 | seconds = round(td.total_seconds()) 120 | 121 | if seconds < 60 and not future: 122 | return "now" 123 | 124 | ago = "{delta} from now" if future else "{delta} ago" 125 | 126 | years, seconds = divmod(seconds, 60 * 60 * 24 * 365) 127 | months, seconds = divmod(seconds, 60 * 60 * 24 * 30) 128 | weeks, seconds = divmod(seconds, 60 * 60 * 24 * 7) 129 | days, seconds = divmod(seconds, 60 * 60 * 24) 130 | hours, seconds = divmod(seconds, 60 * 60) 131 | minutes, seconds = divmod(seconds, 60) 132 | 133 | ret = "" 134 | 135 | if years: 136 | ret += f"{years} {pluralize(years, 'year')}" 137 | if months: 138 | ret += f", {months} {pluralize(months, 'month')}" 139 | elif months: 140 | ret += f"{months} {pluralize(months, 'month')}" 141 | elif weeks: 142 | ret += f"{weeks} {pluralize(weeks, 'week')}" 143 | if days: 144 | ret += f", {days} {pluralize(days, 'day')}" 145 | elif days: 146 | ret += f"{days} {pluralize(days, 'day')}" 147 | 148 | if hours and not years and not months and not weeks and not days: 149 | if ret: 150 | ret += ", " 151 | ret += f"{hours} {pluralize(hours, 'hour')}" 152 | if minutes and not years and not months and not weeks and not days and not hours: 153 | if ret: 154 | ret += ", " 155 | ret += f"{minutes} {pluralize(minutes, 'minute')}" 156 | 157 | formatted_ret = ", ".join(ret.split(", ")[:2]) 158 | 159 | return ago.format(delta=formatted_ret) 160 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | mystbin: 3 | image: ghcr.io/pythonistaguild/mystbin 4 | container_name: mystbin 5 | ports: 6 | - 8181:8181 7 | restart: unless-stopped 8 | depends_on: 9 | database: 10 | condition: service_healthy 11 | restart: true 12 | volumes: 13 | - ./config.toml:/app/config.toml:ro 14 | 15 | database: 16 | image: postgres:16 17 | container_name: mystbin-database 18 | restart: unless-stopped 19 | healthcheck: 20 | test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"] 21 | interval: 10s 22 | timeout: 5s 23 | retries: 5 24 | env_file: .env 25 | environment: 26 | - PG_DATA=/var/lib/postgresql/data 27 | - POSTGRES_DB=mystbin 28 | volumes: 29 | - mystbin_pg_data:/var/lib/postgresql/data 30 | 31 | redis: 32 | image: redis:latest 33 | container_name: mystbin-redis 34 | restart: unless-stopped 35 | profiles: 36 | - redis 37 | volumes: 38 | - "./redis.conf:/config/redis.conf:ro" 39 | command: ["redis-server", "/config/redis.conf"] 40 | 41 | volumes: 42 | mystbin_pg_data: 43 | -------------------------------------------------------------------------------- /launcher.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | import asyncio 20 | import logging 21 | 22 | import aiohttp 23 | import starlette_plus 24 | import uvicorn 25 | 26 | import core 27 | import core.config 28 | 29 | 30 | starlette_plus.setup_logging(level=logging.INFO) 31 | logger: logging.Logger = logging.getLogger(__name__) 32 | 33 | 34 | async def main() -> None: 35 | async with aiohttp.ClientSession() as session, core.Database( 36 | dsn=core.CONFIG["DATABASE"]["dsn"], session=session, github_config=core.CONFIG.get("GITHUB") 37 | ) as database: 38 | app: core.Application = core.Application(database=database) 39 | 40 | host: str = core.CONFIG["SERVER"]["host"] 41 | port: int = core.CONFIG["SERVER"]["port"] 42 | 43 | config: uvicorn.Config = uvicorn.Config( 44 | app=app, 45 | host=host, 46 | port=port, 47 | access_log=False, 48 | forwarded_allow_ips="*", 49 | ) 50 | server: uvicorn.Server = uvicorn.Server(config) 51 | 52 | await server.serve() 53 | 54 | 55 | try: 56 | asyncio.run(main()) 57 | except KeyboardInterrupt: 58 | logger.info("Closing the MystBin application due to KeyboardInterrupt.") 59 | -------------------------------------------------------------------------------- /migration.sql: -------------------------------------------------------------------------------- 1 | BEGIN; -- start transaction 2 | 3 | SAVEPOINT pastes; 4 | ALTER TABLE pastes DROP COLUMN IF EXISTS author_id CASCADE; -- no longer storing users 5 | ALTER TABLE pastes DROP COLUMN IF EXISTS last_edited CASCADE; -- no longer allowing edits 6 | ALTER TABLE pastes ALTER COLUMN password SET DEFAULT NULL; -- nullable password by default 7 | ALTER TABLE pastes DROP COLUMN IF EXISTS origin_ip CASCADE; -- no longer needed 8 | ALTER TABLE pastes ADD COLUMN IF NOT EXISTS safety TEXT UNIQUE; -- this is how we handle paste deletion. 9 | UPDATE pastes SET safety = gen_random_uuid(); -- Populate with junk data. 10 | ALTER TABLE pastes ALTER COLUMN safety SET NOT NULL; -- add not null constraint 11 | CREATE UNIQUE INDEX IF NOT EXISTS pastes_safety_idx ON pastes (safety); -- -- Index by safety keys for faster lookup to delete. 12 | 13 | SAVEPOINT files; 14 | ALTER TABLE files ALTER COLUMN filename SET NOT NULL; -- always require filename 15 | ALTER TABLE files DROP COLUMN IF EXISTS attachment; -- we don't have these anymore 16 | ALTER TABLE files ADD COLUMN IF NOT EXISTS annotation TEXT; 17 | ALTER TABLE files RENAME COLUMN index TO file_index; -- bad column name 18 | ALTER TABLE files ADD COLUMN IF NOT EXISTS warning_positions INTEGER[]; -- New line warning positions 19 | 20 | SAVEPOINT drops; 21 | DROP TABLE IF EXISTS bans CASCADE; -- no longer needed 22 | DROP TABLE IF EXISTS logs CASCADE; -- no longer needed 23 | DROP TABLE IF EXISTS bookmarks CASCADE; -- no longer needed 24 | DROP TABLE IF EXISTS users CASCADE; -- no longer needed 25 | 26 | COMMIT; 27 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.ruff] 2 | line-length = 120 3 | indent-width = 4 4 | exclude = ["venv", ".venv"] 5 | 6 | [tool.ruff.lint] 7 | select = [ 8 | "C4", 9 | "E", 10 | "F", 11 | "G", 12 | "I", 13 | "PTH", 14 | "RUF", 15 | "SIM", 16 | "TCH", 17 | "UP", 18 | "W", 19 | "PERF", 20 | "ANN", 21 | ] 22 | ignore = [ 23 | "F402", 24 | "F403", 25 | "F405", 26 | "PERF203", 27 | "RUF001", 28 | "RUF009", 29 | "SIM105", 30 | "UP034", 31 | "UP038", 32 | "ANN101", 33 | "ANN102", 34 | "ANN401", 35 | "UP031", 36 | "PTH123", 37 | "E203", 38 | "E501", 39 | ] 40 | 41 | [tool.ruff.lint.isort] 42 | split-on-trailing-comma = true 43 | combine-as-imports = true 44 | lines-after-imports = 2 45 | 46 | [tool.ruff.lint.flake8-annotations] 47 | allow-star-arg-any = true 48 | 49 | [tool.ruff.lint.flake8-quotes] 50 | inline-quotes = "double" 51 | 52 | [tool.ruff.format] 53 | quote-style = "double" 54 | indent-style = "space" 55 | skip-magic-trailing-comma = false 56 | line-ending = "auto" 57 | 58 | [tool.pyright] 59 | exclude = ["venv", ".venv"] 60 | useLibraryCodeForTypes = true 61 | typeCheckingMode = "strict" 62 | reportImportCycles = false 63 | reportPrivateUsage = false 64 | pythonVersion = "3.11" 65 | -------------------------------------------------------------------------------- /redis.conf: -------------------------------------------------------------------------------- 1 | port 6379 2 | tcp-backlog 511 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | starlette_plus @ git+https://github.com/PythonistaGuild/StarlettePlus.git@f21169a 2 | uvicorn==0.29.0 3 | asyncpg==0.29.0 4 | asyncpg-stubs==0.29.1 5 | bleach==6.1.0 6 | python-multipart==0.0.9 7 | aiohttp==3.10.5 8 | pyyaml==6.0.1 9 | -------------------------------------------------------------------------------- /schema.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION IF NOT EXISTS pgcrypto; 2 | 3 | CREATE TABLE IF NOT EXISTS pastes ( 4 | id TEXT PRIMARY KEY, 5 | created_at TIMESTAMP NOT NULL DEFAULT (NOW() AT TIME ZONE 'UTC'), 6 | expires TIMESTAMP WITH TIME ZONE, 7 | password TEXT DEFAULT NULL, 8 | views INTEGER DEFAULT 0, 9 | safety TEXT UNIQUE 10 | ); 11 | 12 | CREATE UNIQUE INDEX IF NOT EXISTS pastes_safety_idx ON pastes (safety); 13 | -- Index by safety keys for faster lookup to delete. 14 | 15 | CREATE TABLE IF NOT EXISTS files ( 16 | parent_id TEXT REFERENCES pastes(id) ON DELETE CASCADE, 17 | content TEXT NOT NULL, 18 | filename TEXT NOT NULL, 19 | loc INTEGER NOT NULL, 20 | charcount INTEGER GENERATED ALWAYS AS (LENGTH(content)) STORED, 21 | file_index SERIAL NOT NULL, 22 | annotation TEXT, 23 | warning_positions INTEGER[], 24 | PRIMARY KEY (parent_id, file_index) 25 | ); 26 | -------------------------------------------------------------------------------- /types_/config.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from typing import NotRequired, TypedDict 20 | 21 | import starlette_plus 22 | 23 | 24 | class Server(TypedDict): 25 | host: str 26 | port: int 27 | domain: str 28 | session_secret: str 29 | maintenance: bool 30 | 31 | 32 | class Database(TypedDict): 33 | dsn: str 34 | 35 | 36 | class Redis(TypedDict): 37 | limiter: str 38 | sessions: str 39 | 40 | 41 | class Limits(TypedDict): 42 | paste_get: starlette_plus.RateLimitData 43 | paste_get_day: starlette_plus.RateLimitData 44 | paste_post: starlette_plus.RateLimitData 45 | paste_post_day: starlette_plus.RateLimitData 46 | global_limit: starlette_plus.RateLimitData 47 | 48 | 49 | class Pastes(TypedDict): 50 | char_limit: int 51 | file_limit: int 52 | name_limit: int 53 | 54 | 55 | class Github(TypedDict): 56 | token: str 57 | timeout: float 58 | 59 | 60 | class Config(TypedDict): 61 | SERVER: Server 62 | DATABASE: Database 63 | REDIS: NotRequired[Redis] 64 | LIMITS: Limits 65 | PASTES: Pastes 66 | GITHUB: NotRequired[Github] 67 | -------------------------------------------------------------------------------- /types_/github.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from typing import TypedDict 20 | 21 | 22 | class GistContent(TypedDict): 23 | content: str 24 | 25 | 26 | class PostGist(TypedDict): 27 | description: str 28 | files: dict[str, GistContent] 29 | public: bool 30 | -------------------------------------------------------------------------------- /types_/scanner.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | from typing import TYPE_CHECKING, TypedDict 22 | 23 | 24 | if TYPE_CHECKING: 25 | from core.scanners import Services 26 | 27 | 28 | class ScannerSecret(TypedDict): 29 | service: Services 30 | tokens: list[tuple[int, str]] 31 | -------------------------------------------------------------------------------- /views/__init__.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from .api import APIView as APIView 20 | from .docs import DocsView as DocsView 21 | from .htmx import HTMXView as HTMXView 22 | -------------------------------------------------------------------------------- /views/api.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | import datetime 22 | import json 23 | from typing import TYPE_CHECKING, Any 24 | 25 | import asyncpg 26 | import starlette_plus 27 | 28 | from core import CONFIG 29 | from core.utils import validate_paste 30 | 31 | 32 | if TYPE_CHECKING: 33 | from core import Application 34 | 35 | 36 | class APIView(starlette_plus.View, prefix="api"): 37 | def __init__(self, app: Application) -> None: 38 | self.app: Application = app 39 | 40 | @starlette_plus.route("/paste/{id}", methods=["GET"]) 41 | @starlette_plus.route("/pastes/{id}", methods=["GET"], include_in_schema=False) 42 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get"]) 43 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get_day"]) 44 | async def paste_get(self, request: starlette_plus.Request) -> starlette_plus.Response: 45 | """Fetch a paste. 46 | 47 | --- 48 | summary: Fetch a paste. 49 | description: 50 | Fetches a paste with all relevant meta-data and files.\n\n 51 | 52 | Fetching pastes does not include the `password` or `safety` fields. You only receive the `safety` field 53 | directly after creating a paste. 54 | 55 | parameters: 56 | - in: path 57 | name: id 58 | schema: 59 | type: string 60 | required: true 61 | description: The paste ID. 62 | 63 | - in: header 64 | name: Authorization 65 | schema: 66 | type: string 67 | format: basic 68 | required: false 69 | description: The password for the paste; if one is required. 70 | 71 | responses: 72 | 200: 73 | description: The paste meta-data and files. 74 | content: 75 | application/json: 76 | schema: 77 | type: object 78 | properties: 79 | id: 80 | type: string 81 | example: abc123 82 | created_at: 83 | type: string 84 | example: 2024-01-01T00:00:00.000000+00:00 85 | expires: 86 | type: string 87 | views: 88 | type: integer 89 | example: 3 90 | has_password: 91 | type: boolean 92 | example: false 93 | files: 94 | type: array 95 | items: 96 | type: object 97 | properties: 98 | parent_id: 99 | type: string 100 | content: 101 | type: string 102 | filename: 103 | type: string 104 | loc: 105 | type: integer 106 | charcount: 107 | type: integer 108 | annotation: 109 | type: string 110 | 111 | 404: 112 | description: The paste does not exist or has been previously deleted. 113 | content: 114 | application/json: 115 | schema: 116 | type: object 117 | properties: 118 | error: 119 | type: string 120 | 121 | 401: 122 | description: You are not authorized to view this paste or you provided an incorrect password. 123 | content: 124 | application/json: 125 | schema: 126 | type: object 127 | properties: 128 | error: 129 | type: string 130 | example: Unauthorized. 131 | 132 | 429: 133 | description: You are requesting too fast. 134 | content: 135 | application/json: 136 | schema: 137 | type: object 138 | properties: 139 | error: 140 | type: string 141 | example: You are requesting too fast. 142 | """ 143 | password: str | None = request.headers.get("authorization", None) 144 | identifier: str = request.path_params["id"] 145 | 146 | paste = await self.app.database.fetch_paste(identifier, password=password) 147 | if not paste: 148 | return starlette_plus.JSONResponse( 149 | {"error": f'A paste with the id "{identifier}" could not be found or has expired.'}, status_code=404 150 | ) 151 | 152 | if paste.has_password and not paste.password_ok: 153 | return starlette_plus.JSONResponse({"error": "Unauthorized"}, status_code=401) 154 | 155 | to_return: dict[str, Any] = paste.serialize(exclude=["safety", "password", "password_ok"]) 156 | return starlette_plus.JSONResponse(to_return) 157 | 158 | @starlette_plus.route("/paste", methods=["POST"]) 159 | @starlette_plus.route("/pastes", methods=["POST"], include_in_schema=False) 160 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_post"]) 161 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_post_day"]) 162 | async def paste_post(self, request: starlette_plus.Request) -> starlette_plus.Response: 163 | """Create a paste. 164 | 165 | --- 166 | summary: Create a paste. 167 | description: 168 | Creates a paste with or without multiple files for view on the web or via the API. 169 | You can use this endpoint to POST valid `JSON` data or `plain-text` content.\n\n\n 170 | 171 | When using `plain-text`, only one file will be created, without a password or expiry.\n\n\n 172 | 173 | Max Character per file is `300_000`.\n\n 174 | 175 | Max file limit is `5`.\n\n 176 | 177 | If the paste is regarded as public, and contains Discord authorization tokens, 178 | then these will be invalidated upon paste creation.\n\n 179 | 180 | requestBody: 181 | description: The paste data. `password` and `expires` are optional. 182 | content: 183 | application/json: 184 | schema: 185 | type: object 186 | properties: 187 | files: 188 | type: array 189 | items: 190 | type: object 191 | properties: 192 | filename: 193 | type: string 194 | required: false 195 | content: 196 | type: string 197 | required: true 198 | example: 199 | - filename: thing.py 200 | content: print(\"Hello World!\") 201 | - content: Some text or code... 202 | password: 203 | required: false 204 | type: string 205 | example: null 206 | expires: 207 | required: false 208 | type: string 209 | example: null 210 | text/plain: 211 | schema: 212 | type: string 213 | 214 | responses: 215 | 200: 216 | description: The paste meta-data. 217 | content: 218 | application/json: 219 | schema: 220 | type: object 221 | properties: 222 | id: 223 | type: string 224 | example: abc123 225 | created_at: 226 | type: string 227 | example: 2024-01-01T00:00:00.000000+00:00 228 | expires: 229 | type: string 230 | example: 2024-01-01T00:00:00.000000+00:00 231 | safety: 232 | type: string 233 | 400: 234 | description: The paste data was invalid. 235 | content: 236 | application/json: 237 | schema: 238 | type: object 239 | properties: 240 | error: 241 | type: string 242 | example: The reason the paste was invalid. 243 | 429: 244 | description: You are requesting too fast. 245 | content: 246 | application/json: 247 | schema: 248 | type: object 249 | properties: 250 | error: 251 | type: string 252 | example: You are requesting too fast. 253 | """ 254 | content_type: str | None = request.headers.get("content-type", None) 255 | body: dict[str, Any] | str 256 | data: dict[str, Any] 257 | 258 | if content_type == "application/json": 259 | try: 260 | body = await request.json() 261 | except json.JSONDecodeError: 262 | return starlette_plus.JSONResponse({"error": "Invalid JSON provided."}, status_code=400) 263 | else: 264 | body = (await request.body()).decode(encoding="UTF-8") 265 | 266 | data = {"files": [{"content": body, "filename": None}]} if isinstance(body, str) else body 267 | 268 | if resp := validate_paste(data): 269 | return resp 270 | 271 | expiry_str: str | None = data.get("expires", None) 272 | 273 | try: 274 | expiry: datetime.datetime | None = datetime.datetime.fromisoformat(expiry_str) if expiry_str else None 275 | except Exception as e: 276 | return starlette_plus.JSONResponse({"error": f'Unable to parse "expiry" parameter: {e}'}, status_code=400) 277 | 278 | data["expires"] = expiry 279 | data["password"] = data.get("password") 280 | 281 | try: 282 | paste = await self.app.database.create_paste(data=data) 283 | except asyncpg.CharacterNotInRepertoireError: 284 | message: str = "File(s)/Filename(s) contain invalid characters or byte sequences." 285 | return starlette_plus.JSONResponse({"error": message}, status_code=400) 286 | 287 | to_return: dict[str, Any] = paste.serialize(exclude=["password", "password_ok"]) 288 | to_return.pop("files", None) 289 | 290 | return starlette_plus.JSONResponse(to_return, status_code=200) 291 | 292 | @starlette_plus.route("/security/info/{token}") 293 | async def security_info(self, request: starlette_plus.Request) -> starlette_plus.Response: 294 | token: str | None = request.path_params.get("token", None) 295 | if not token: 296 | return starlette_plus.JSONResponse({"error": "Unauthorized."}, status_code=401) 297 | 298 | paste = await self.app.database.fetch_paste_security(token=token) 299 | if not paste: 300 | return starlette_plus.JSONResponse( 301 | {"error": "A paste was not found with the provided token, or has expired or been deleted."}, 302 | status_code=404, 303 | ) 304 | 305 | delete: str = f"{request.url.scheme}://{request.url.hostname}/api/security/delete/{token}" 306 | info: str = f"{request.url.scheme}://{request.url.hostname}/api/security/info/{token}" 307 | data: dict[str, str] = { 308 | "token": paste.safety, 309 | "delete": delete, 310 | "info": info, 311 | "extra": "Visiting the delete URL will remove the paste instantly.", 312 | } 313 | 314 | return starlette_plus.JSONResponse(data, status_code=200) 315 | 316 | @starlette_plus.route("/security/delete/{token}", methods=["GET"]) 317 | async def security_delete(self, request: starlette_plus.Request) -> starlette_plus.Response: 318 | """Delete a paste. 319 | 320 | --- 321 | summary: Delete a paste. 322 | description: 323 | Deletes a paste with the associated safety token.\n\n 324 | 325 | This action is not reversible. 326 | 327 | parameters: 328 | - in: path 329 | name: token 330 | schema: 331 | type: string 332 | required: true 333 | description: The safety token received when creating the paste. 334 | 335 | 336 | responses: 337 | 200: 338 | description: The paste was successfully deleted. 339 | content: 340 | text/plain: 341 | schema: 342 | type: string 343 | 344 | 401: 345 | description: You are not authorized to delete this paste. 346 | content: 347 | application/json: 348 | schema: 349 | type: object 350 | properties: 351 | error: 352 | type: string 353 | example: Unauthorized. 354 | """ 355 | token: str | None = request.path_params.get("token", None) 356 | if not token: 357 | return starlette_plus.JSONResponse({"error": "Unauthorized."}, status_code=401) 358 | 359 | await self.app.database.delete_paste_security(token=token) 360 | return starlette_plus.Response("Ok", status_code=200) 361 | -------------------------------------------------------------------------------- /views/docs.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | from typing import TYPE_CHECKING 22 | 23 | import starlette_plus 24 | 25 | 26 | if TYPE_CHECKING: 27 | from core import Application 28 | 29 | 30 | class DocsView(starlette_plus.View, prefix="api"): 31 | def __init__(self, app: Application) -> None: 32 | self.app: Application = app 33 | 34 | @starlette_plus.route("/documentation") 35 | async def documentation(self, request: starlette_plus.Request) -> starlette_plus.Response: 36 | headers = {"Access-Control-Allow-Origin": "*"} 37 | return starlette_plus.FileResponse("web/docs.html", headers=headers) 38 | 39 | @starlette_plus.route("/docs") 40 | async def documentation_redirect(self, request: starlette_plus.Request) -> starlette_plus.Response: 41 | return starlette_plus.RedirectResponse("/api/documentation") 42 | 43 | @starlette_plus.route("/schema") 44 | async def openapi_schema(self, request: starlette_plus.Request) -> starlette_plus.Response: 45 | if not self.app.schemas: 46 | return starlette_plus.Response(status_code=503) 47 | 48 | return self.app.schemas.OpenAPIResponse(request=request) 49 | -------------------------------------------------------------------------------- /views/htmx.py: -------------------------------------------------------------------------------- 1 | """MystBin. Share code easily. 2 | 3 | Copyright (C) 2020-Current PythonistaGuild 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | 19 | from __future__ import annotations 20 | 21 | import asyncio 22 | import datetime 23 | import json 24 | from typing import TYPE_CHECKING, Any, cast 25 | from urllib.parse import unquote, urlsplit 26 | 27 | import asyncpg 28 | import bleach 29 | import starlette_plus 30 | 31 | from core import CONFIG 32 | from core.utils import natural_time, validate_paste 33 | 34 | 35 | if TYPE_CHECKING: 36 | from starlette.datastructures import FormData 37 | 38 | from core import Application 39 | 40 | 41 | with open("web/paste.html") as fp: 42 | PASTE_HTML: str = fp.read() 43 | 44 | 45 | class HTMXView(starlette_plus.View, prefix="htmx"): 46 | def __init__(self, app: Application) -> None: 47 | self.app: Application = app 48 | 49 | def highlight_code(self, *, files: list[dict[str, Any]]) -> str: 50 | html: str = "" 51 | 52 | for index, file in enumerate(files): 53 | filename = bleach.clean(file["filename"], attributes=[], tags=[]) 54 | filename = "_".join(filename.splitlines()) 55 | 56 | raw_url: str = f'/raw/{file["parent_id"]}' 57 | annotation: str = file["annotation"] or "" 58 | positions: list[int] = file.get("warning_positions", []) 59 | original: str = file["content"] 60 | 61 | parts: list[str] = annotation.split(":") 62 | annotation = parts.pop(0) 63 | 64 | extra: str = ( 65 | f"""{parts[0]}""" 66 | if parts 67 | else "" 68 | ) 69 | annotations: str = ( 70 | f'❌ {annotation}{": " + extra if extra else ""}' 71 | if annotation 72 | else "" 73 | ) 74 | 75 | position: int = 0 76 | next_pos: int | None = positions.pop(0) if positions else None 77 | 78 | numbers: list[str] = [] 79 | for n, line in enumerate(original.splitlines(), 1): 80 | length: int = len(line) 81 | 82 | if next_pos is not None and position <= next_pos <= position + length: 83 | numbers.append( 84 | f"""{n}""" 85 | ) 86 | 87 | try: 88 | next_pos = positions.pop(0) 89 | except IndexError: 90 | next_pos = None 91 | 92 | else: 93 | numbers.append( 94 | f"""{n}""" 95 | ) 96 | 97 | position += length + 1 98 | 99 | content = bleach.clean( 100 | original.replace("\n{"".join(numbers)}\n""" 107 | html += f""" 108 |
109 |
110 |
111 | {filename} 112 | Hide 113 | Copy 114 | Raw 115 |
116 |
117 | {annotations} 118 |
{lines}{content}
119 |
""" 120 | 121 | return html 122 | 123 | def check_discord(self, request: starlette_plus.Request) -> starlette_plus.Response | None: 124 | agent: str = request.headers.get("user-agent", "") 125 | if "discordbot" in agent.lower(): 126 | return starlette_plus.Response(status_code=204) 127 | 128 | @starlette_plus.route("/", prefix=False) 129 | async def home(self, request: starlette_plus.Request) -> starlette_plus.Response: 130 | if resp := self.check_discord(request=request): 131 | return resp 132 | 133 | return starlette_plus.FileResponse("web/index.html") 134 | 135 | @starlette_plus.route("/protected/{id}", prefix=False) 136 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get"]) 137 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get_day"]) 138 | async def protected_paste(self, request: starlette_plus.Request) -> starlette_plus.Response: 139 | return starlette_plus.FileResponse("web/password.html") 140 | 141 | @starlette_plus.route("/{id}", prefix=False) 142 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get"]) 143 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get_day"]) 144 | async def paste(self, request: starlette_plus.Request) -> starlette_plus.Response: 145 | if resp := self.check_discord(request=request): 146 | return resp 147 | 148 | identifier: str = request.path_params.get("id", "pass") 149 | htmx_url: str | None = request.headers.get("HX-Current-URL", None) 150 | 151 | if htmx_url and identifier == "pass": 152 | identifier = urlsplit(htmx_url).path.removeprefix("/protected/") 153 | 154 | not_found: str = """ 155 |
156 |

404 - This page or paste could not be found

157 | Return Home... 158 |
159 | """ 160 | 161 | password: str = unquote(request.query_params.get("pastePassword", "")) 162 | paste = await self.app.database.fetch_paste(identifier, password=password) 163 | 164 | if not paste: 165 | return starlette_plus.HTMLResponse(PASTE_HTML.format(__PASTES__=not_found)) 166 | 167 | if paste.has_password and not paste.password_ok: 168 | if not password: 169 | return starlette_plus.RedirectResponse(f"/protected/{identifier}") 170 | 171 | error_headers: dict[str, str] = {"HX-Retarget": "#errorResponse", "HX-Reswap": "outerHTML"} 172 | return starlette_plus.HTMLResponse( 173 | """Incorrect Password.""", 174 | headers=error_headers, 175 | ) 176 | 177 | data: dict[str, Any] = paste.serialize(exclude=["password", "password_ok"]) 178 | files: list[dict[str, Any]] = data["files"] 179 | created_delta: datetime.timedelta = datetime.datetime.now(tz=datetime.timezone.utc) - paste.created_at.replace( 180 | tzinfo=datetime.timezone.utc 181 | ) 182 | 183 | url: str = f"/{identifier}" 184 | raw_url: str = f"/raw/{identifier}" 185 | security_html: str = "" 186 | 187 | stored: list[str] = request.session.get("pastes", []) 188 | if identifier in stored: 189 | security_url: str = f"/api/security/info/{data['safety']}" 190 | 191 | security_html = f""" 192 |
193 | Security Info 194 |
""" 195 | 196 | html: str = f""" 197 |
198 |
199 | /{identifier} 200 | Created {natural_time(created_delta)}... 201 |
202 | {security_html} 203 |
204 | Raw 205 | 206 |
207 |
208 | """ 209 | 210 | html += await asyncio.to_thread(self.highlight_code, files=files) 211 | if htmx_url and password: 212 | return starlette_plus.HTMLResponse(html, headers={"HX-Replace-Url": f"{url}?pastePassword={password}"}) 213 | 214 | return starlette_plus.HTMLResponse(PASTE_HTML.format(__PASTES__=html), media_type="text/html") 215 | 216 | @starlette_plus.route("/raw/{id}", prefix=False) 217 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get"]) 218 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get_day"]) 219 | async def paste_raw(self, request: starlette_plus.Request) -> starlette_plus.Response: 220 | if resp := self.check_discord(request=request): 221 | return resp 222 | 223 | password: str | None = request.headers.get("authorization", None) 224 | identifier: str = request.path_params["id"] 225 | 226 | htmx_url: str | None = request.headers.get("HX-Current-URL", None) 227 | if identifier == "0" and htmx_url: 228 | identifier = htmx_url.removeprefix(f"{request.url.scheme}://{request.url.hostname}/") 229 | 230 | headers: dict[str, str] = {"HX-Redirect": f"/raw/{identifier}"} 231 | paste = await self.app.database.fetch_paste(identifier, password=password) 232 | 233 | if not paste: 234 | return starlette_plus.JSONResponse( 235 | {"error": f'A paste with the id "{identifier}" could not be found or has expired.'}, 236 | status_code=404, 237 | headers=headers, 238 | ) 239 | 240 | if paste.has_password and not paste.password_ok: 241 | return starlette_plus.JSONResponse( 242 | {"error": "Unauthorized. Raw pastes can not be viewed when protected by passwords."}, 243 | status_code=401, 244 | headers=headers, 245 | ) 246 | 247 | to_return: dict[str, Any] = paste.serialize(exclude=["safety", "password", "password_ok"]) 248 | text: str = "\n\n\n\n".join([f"# MystBin ! - {f['filename']}\n{f['content']}" for f in to_return["files"]]) 249 | 250 | return starlette_plus.PlainTextResponse(text, headers=headers) 251 | 252 | @starlette_plus.route("/raw/{id}/{page:int}", prefix=False) 253 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get"]) 254 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_get_day"]) 255 | async def paste_raw_page(self, request: starlette_plus.Request) -> starlette_plus.Response: 256 | if resp := self.check_discord(request=request): 257 | return resp 258 | 259 | password: str | None = request.headers.get("authorization", None) 260 | identifier: str = request.path_params["id"] 261 | page: int = max(request.path_params["page"], 1) 262 | 263 | paste = await self.app.database.fetch_paste(identifier, password=password) 264 | if not paste: 265 | return starlette_plus.JSONResponse( 266 | {"error": f'A paste with the id "{identifier}" could not be found or has expired.'}, 267 | status_code=404, 268 | ) 269 | 270 | if paste.has_password and not paste.password_ok: 271 | return starlette_plus.JSONResponse( 272 | {"error": "Unauthorized. Raw pastes can not be viewed when protected by passwords."}, 273 | status_code=401, 274 | ) 275 | 276 | to_return: dict[str, Any] = paste.serialize(exclude=["safety", "password", "password_ok"]) 277 | 278 | try: 279 | text: str = to_return["files"][page - 1]["content"] 280 | except IndexError: 281 | return starlette_plus.JSONResponse({"error": f"This file does not exist on paste: '{identifier}'"}) 282 | 283 | return starlette_plus.PlainTextResponse(text) 284 | 285 | @starlette_plus.route("/save", methods=["POST"]) 286 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_post"]) 287 | @starlette_plus.limit(**CONFIG["LIMITS"]["paste_post_day"]) 288 | async def htmx_save(self, request: starlette_plus.Request) -> starlette_plus.Response: 289 | if resp := self.check_discord(request=request): 290 | return resp 291 | 292 | form: FormData = await request.form() 293 | multi = form.multi_items() 294 | 295 | password: str = cast(str, multi.pop()[1]) 296 | names: list[str] = cast(list[str], [i[1] for i in multi if i[0] == "fileName"]) 297 | contents: list[str] = cast(list[str], [i[1] for i in multi if i[0] == "fileContent"]) 298 | 299 | error_headers: dict[str, str] = {"HX-Retarget": "#errorResponse"} 300 | 301 | if len(names) != len(contents): 302 | return starlette_plus.HTMLResponse( 303 | """400: Invalidated paste data.""", 304 | headers=error_headers, 305 | ) 306 | 307 | data: dict[str, Any] = {"files": []} 308 | for n in range(len(names)): 309 | if not contents[n]: 310 | continue 311 | 312 | inner: dict[str, str | None] = {} 313 | 314 | try: 315 | inner["filename"] = names[n].encode("UTF-8").decode("UTF-8") or None 316 | inner["content"] = contents[n].encode("UTF-8").decode("UTF-8") 317 | except Exception: 318 | return starlette_plus.HTMLResponse( 319 | """400: File/Filename contains invalid characters.""", 320 | headers=error_headers, 321 | ) 322 | data["files"].append(inner) 323 | 324 | if not data["files"]: 325 | return starlette_plus.HTMLResponse( 326 | """400: Missing files or data to paste.""", 327 | headers=error_headers, 328 | ) 329 | 330 | if resp := validate_paste(data): 331 | json_: dict[str, Any] = json.loads(resp.body) # type: ignore Can only be memoryview when specifically used. 332 | return starlette_plus.HTMLResponse( 333 | f"""{resp.status_code}: {json_["error"]}""", 334 | headers=error_headers, 335 | ) 336 | 337 | data["expires"] = None # TODO: Add this to Frontend... 338 | data["password"] = password or None 339 | 340 | try: 341 | paste = await self.app.database.create_paste(data=data) 342 | except asyncpg.CharacterNotInRepertoireError: 343 | return starlette_plus.HTMLResponse( 344 | """400: File/Filename contains invalid characters.""", 345 | headers=error_headers, 346 | ) 347 | 348 | to_return: dict[str, Any] = paste.serialize(exclude=["password", "password_ok"]) 349 | identifier: str = to_return["id"] 350 | 351 | url: str = f"/{identifier}" 352 | 353 | try: 354 | (request.session["pastes"].append(identifier)) 355 | except (KeyError, AttributeError): 356 | request.session["pastes"] = [identifier] 357 | else: 358 | request.session["pastes"] = request.session["pastes"][-5:] 359 | 360 | return starlette_plus.HTMLResponse("", headers={"HX-Redirect": url}) 361 | -------------------------------------------------------------------------------- /web/docs.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Mystbin - Documentation 5 | 6 | 9 | 10 | 11 | 14 | 15 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MystBin 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 35 | 36 | 37 | 40 | 41 | 42 | 43 | 44 | 45 |
46 | 47 | 48 | MystBin 49 | 50 |
51 | 54 | 57 | 58 | 59 |
60 |
61 | 62 |
64 |
65 |
68 |
69 | 71 | Delete File 72 |
73 | 75 |
76 | 77 |
80 |
81 | 83 | Delete File 84 |
85 | 87 |
88 |
89 | 90 |
91 |
92 |
93 | Save Paste 95 | 97 |
98 | 99 |
100 |
101 | 102 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /web/maint.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MystBin - Maintenance 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 29 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 39 | 40 | MystBin 41 | 42 |
43 | 46 | 49 | 50 | 51 |
52 |
53 | 54 |
55 |

We are currently undergoing maintenance, be back soon!

56 |
57 | 58 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /web/password.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MystBin 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 38 | 39 | 40 | 43 | 44 | 45 | 46 | 47 | 48 |
49 | 50 | 51 | MystBin 52 | 53 |
54 | 57 | 60 | 61 | 62 |
63 |
64 | 65 |
68 |
69 |
70 |

Password Protected!

71 | This paste has been password protected. Please enter the password below to continue. 72 | 74 | 75 | Submit 77 |
78 |
79 |
80 | 81 | 96 | 97 |
98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /web/paste.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MystBin 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 38 | 39 | 40 | 43 | 44 | 45 | 46 | 47 | 48 |
49 | 50 | 51 | MystBin 52 | 53 |
54 | 57 | 60 | 61 | 62 |
63 |
64 | 65 |
66 |
{__PASTES__}
67 |
68 | 69 | 84 | 85 |
86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /web/static/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonistaGuild/MystBin/d8b4375f497f103e49000972420447b2c7d49a6f/web/static/images/favicon.ico -------------------------------------------------------------------------------- /web/static/images/keyboard-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/static/images/keyboard.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/static/images/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/static/images/vsc.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /web/static/scripts/dragDrop.js: -------------------------------------------------------------------------------- 1 | let dragCounter = 0; 2 | 3 | function fileDragStart(event, target) { 4 | event.preventDefault(); 5 | event.stopPropagation(); 6 | 7 | target.classList.add("dragging"); 8 | let pasteAreas = pasteContainer.getElementsByClassName("pasteArea"); 9 | 10 | for (let area of pasteAreas) { 11 | if (area === target) { 12 | continue; 13 | } 14 | area.classList.remove("dragging"); 15 | } 16 | 17 | if (target.classList.contains("smallArea")) { 18 | target.classList.remove("smallArea"); 19 | } 20 | 21 | dragCounter++; 22 | } 23 | 24 | function fileDragOver(event, target) { 25 | event.preventDefault(); 26 | 27 | if (event.dataTransfer.items === 0) { return } 28 | 29 | let type = event.dataTransfer.items[0].type; 30 | if (!type) { return } 31 | 32 | if (!type.startsWith("text/") && !type.startsWith("application/")) { 33 | target.classList.add("prevented"); 34 | event.dataTransfer.dropEffect = "none"; 35 | } 36 | } 37 | 38 | function fileDragEnd(event, target) { 39 | event.preventDefault(); 40 | event.stopPropagation(); 41 | 42 | dragCounter--; 43 | if (dragCounter !== 0) { return } 44 | 45 | target.classList.remove("dragging"); 46 | target.classList.remove("prevented"); 47 | 48 | } 49 | 50 | async function fileDrop(event, target) { 51 | event.preventDefault(); 52 | event.stopPropagation(); 53 | 54 | dragCounter = 0; 55 | 56 | target.classList.remove("prevented"); 57 | target.classList.remove("dragging"); 58 | 59 | const file = event.dataTransfer.files[0]; 60 | const textArea = target.querySelector(".fileContent"); 61 | const fileName = target.querySelector(".pasteHeader > .filenameArea"); 62 | 63 | // Allow double the server limit incase of editing... 64 | if (file.size > 600000) { 65 | return; 66 | } 67 | 68 | if (!file.type) { } 69 | else if (!file.type.startsWith("text/") && !file.type.startsWith("application/")) { 70 | return; 71 | } 72 | 73 | let name = file.name; 74 | let content = await file.text(); 75 | fileName.value = name; 76 | textArea.value = content; 77 | 78 | addFile(); 79 | } -------------------------------------------------------------------------------- /web/static/scripts/files.js: -------------------------------------------------------------------------------- 1 | let pasteContainer = document.querySelector(".pasteContainer"); 2 | let count = 1; 3 | 4 | 5 | function addFile(number) { 6 | let canContinue = true; 7 | let pasteAreas = pasteContainer.getElementsByClassName("pasteArea"); 8 | let files = pasteContainer.querySelectorAll("[name='fileContent']"); 9 | 10 | for (let area of pasteAreas) { 11 | let file = area.querySelector("[name='fileContent']"); 12 | 13 | if (!file.value) { 14 | canContinue = false; 15 | 16 | if (file !== files[0]) { 17 | area.classList.add("smallArea"); 18 | } 19 | } 20 | 21 | else if (file.value) { 22 | area.classList.remove("smallArea"); 23 | } 24 | } 25 | 26 | if (!canContinue) { return } 27 | if (files.length === 5) { return } 28 | 29 | count += 1; 30 | 31 | const pasteHTML = ` 32 |
33 | 34 |
35 | 36 | Delete File 37 |
38 | 39 |
`; 40 | 41 | pasteContainer.insertAdjacentHTML("beforeend", pasteHTML); 42 | } 43 | 44 | function deleteFile(identifier) { 45 | let pasteAreas = pasteContainer.getElementsByClassName("pasteArea"); 46 | let files = pasteContainer.querySelectorAll("[name='fileContent']"); 47 | let area = document.getElementById(identifier); 48 | let file = area.querySelector("[name='fileContent']") 49 | 50 | if (pasteAreas.length == 2) { 51 | file.value = ""; 52 | 53 | if (file === files[1]) { 54 | area.classList.add("smallArea"); 55 | } 56 | return 57 | } 58 | 59 | if (files.length === 5 && file === files[4]) { 60 | file.value = ""; 61 | area.classList.add("smallArea"); 62 | return 63 | } 64 | 65 | area.remove(); 66 | let canContinue = true; 67 | let newAreas = pasteContainer.getElementsByClassName("pasteArea"); 68 | 69 | for (let newArea of newAreas) { 70 | let newFile = newArea.querySelector("[name='fileContent']"); 71 | 72 | if (!newFile.value) { 73 | canContinue = false; 74 | 75 | if (newFile !== files[0]) { 76 | newArea.classList.add("smallArea"); 77 | } 78 | } 79 | 80 | else if (newFile.value) { 81 | newArea.classList.remove("smallArea"); 82 | } 83 | } 84 | 85 | if (!canContinue) { return } 86 | 87 | const pasteHTML = ` 88 |
89 | 90 |
91 | 92 | Delete File 93 |
94 | 95 |
`; 96 | 97 | pasteContainer.insertAdjacentHTML("beforeend", pasteHTML); 98 | } 99 | -------------------------------------------------------------------------------- /web/static/scripts/files.old.js: -------------------------------------------------------------------------------- 1 | let pasteContainer = document.querySelector(".pasteContainer"); 2 | let addButton = document.querySelector(".addPaste"); 3 | let count = 0; 4 | 5 | addButton.addEventListener("click", (e) => { 6 | let files = pasteContainer.getElementsByClassName("pasteArea"); 7 | 8 | if (files.length >= 5) { 9 | return; 10 | } 11 | 12 | count += 1; 13 | 14 | const pasteHTML = `
15 |
16 | 17 | Delete File 18 |
19 | 20 |
`; 21 | 22 | pasteContainer.insertAdjacentHTML("beforeend", pasteHTML); 23 | 24 | files = pasteContainer.getElementsByClassName("pasteArea"); 25 | for (let file of files) { 26 | file.querySelector(".pasteHeader .deleteFile").classList.remove("disabled"); 27 | } 28 | 29 | if (files.length >= 5) { 30 | addButton.style.display = "none"; 31 | } 32 | }); 33 | 34 | function deleteFile(identifier) { 35 | let files = pasteContainer.getElementsByClassName("pasteArea"); 36 | 37 | if (files.length == 1) { 38 | return; 39 | } else { 40 | addButton.style.display = "flex"; 41 | } 42 | 43 | document.getElementById(identifier).remove(); 44 | 45 | files = pasteContainer.getElementsByClassName("pasteArea"); 46 | if (files.length == 1) { 47 | files[0] 48 | .querySelector(".pasteHeader .deleteFile") 49 | .classList.add("disabled"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /web/static/scripts/hidecopy.js: -------------------------------------------------------------------------------- 1 | function hideFile(button, index) { 2 | const pastec = document.getElementById(`__paste_c_${index}`); 3 | const pastea = document.getElementById(`__paste_a_${index}`); 4 | 5 | if (!pastec || !pastea) { 6 | return; 7 | } 8 | 9 | if (button.textContent == "Hide") { 10 | button.textContent = "Show"; 11 | pastec.style.display = "none"; 12 | pastea.style.flexGrow = "0"; 13 | } else { 14 | button.textContent = "Hide"; 15 | pastec.style.display = "flex"; 16 | pastea.style.flexGrow = "1"; 17 | } 18 | } 19 | 20 | async function copyFile(index) { 21 | let button = document.getElementById(`__paste_copy_${index}`); 22 | 23 | if (button.textContent != "Copy") { 24 | button.textContent = "✓"; 25 | return; 26 | } 27 | 28 | if (pasteStores.length == 0) { 29 | return 30 | } 31 | 32 | let content = pasteStores[index]; 33 | if (!content) { 34 | return; 35 | } 36 | 37 | await navigator.clipboard.writeText(content); 38 | button.textContent = "✓"; 39 | 40 | setTimeout(() => { 41 | button.textContent = "Copy"; 42 | }, 3500); 43 | } 44 | -------------------------------------------------------------------------------- /web/static/scripts/highlights.js: -------------------------------------------------------------------------------- 1 | let pasteStores = []; 2 | 3 | const HIGHLIGHT_AREAS = document.querySelectorAll(".pasteArea"); 4 | const LANGUAGES = hljs.listLanguages(); 5 | let DlCount = 0; 6 | 7 | for (let area of HIGHLIGHT_AREAS) { 8 | let code = area.querySelector("pre > code"); 9 | let name = area.querySelector(".pasteHeader > div > .filenameArea"); 10 | 11 | pasteStores.push(code.textContent); 12 | 13 | // Highlight Code Block and get Language Details... 14 | let nameLang = getLangByName(name.textContent); 15 | let highlightedLang; 16 | let details; 17 | 18 | if (!nameLang) { 19 | details = hljs.highlightAuto(code.textContent); 20 | highlightedLang = details.language || "plaintext"; 21 | } else { 22 | details = hljs.highlight(code.textContent, { "language": nameLang }) 23 | highlightedLang = nameLang.toLowerCase(); 24 | } 25 | 26 | code.innerHTML = details.value; 27 | 28 | let header = area.querySelector(".pasteHeader"); 29 | let langOpts = ""; 30 | 31 | for (let lang of LANGUAGES) { 32 | if (lang == highlightedLang) { 33 | continue 34 | } 35 | langOpts += `` 36 | } 37 | 38 | langOpts = `\n${langOpts}` 39 | let html = ` 40 |
41 | 43 | 44 | ${langOpts} 45 | 46 |
` 47 | 48 | header.insertAdjacentHTML("beforeend", html); 49 | DlCount++; 50 | } 51 | 52 | function changeLang(inp, area, index) { 53 | let chosen = inp.value; 54 | 55 | if (!chosen) { return } 56 | if (!LANGUAGES.includes(chosen)) { return } 57 | 58 | if (inp.placeholder === chosen) { return } 59 | 60 | let code = area.querySelector("pre > code"); 61 | let highlighted = hljs.highlight(pasteStores[index], { language: chosen }); 62 | code.innerHTML = highlighted.value; 63 | 64 | inp.placeholder = chosen; 65 | } -------------------------------------------------------------------------------- /web/static/scripts/highlightsHTMX.js: -------------------------------------------------------------------------------- 1 | let pasteStores = []; 2 | 3 | const LANGUAGES = hljs.listLanguages(); 4 | let DlCount = 0; 5 | 6 | 7 | document.addEventListener("htmx:afterRequest", function (evt) { 8 | if (evt.detail.xhr.status != 200) { 9 | return 10 | } 11 | 12 | if (evt.detail.target.id == "pastecontainer" || evt.detail.target.id == "content") { 13 | const HIGHLIGHT_AREAS = document.querySelectorAll(".pasteArea"); 14 | 15 | for (let area of HIGHLIGHT_AREAS) { 16 | let code = area.querySelector("pre > code"); 17 | let name = area.querySelector(".pasteHeader > div > .filenameArea"); 18 | pasteStores.push(code.textContent); 19 | 20 | // Highlight Code Block and get Language Details... 21 | let nameLang = getLangByName(name.textContent); 22 | let highlightedLang; 23 | let details; 24 | 25 | if (!nameLang) { 26 | details = hljs.highlightAuto(code.textContent); 27 | highlightedLang = details.language || "plaintext"; 28 | } else { 29 | details = hljs.highlight(code.textContent, { "language": nameLang }) 30 | highlightedLang = nameLang.toLowerCase(); 31 | } 32 | 33 | code.innerHTML = details.value; 34 | 35 | let header = area.querySelector(".pasteHeader"); 36 | let langOpts = ""; 37 | 38 | for (let lang of LANGUAGES) { 39 | if (lang == highlightedLang) { 40 | continue 41 | } 42 | langOpts += `` 43 | } 44 | 45 | langOpts = `\n${langOpts}` 46 | let html = ` 47 |
48 | 50 | 51 | ${langOpts} 52 | 53 |
` 54 | 55 | header.insertAdjacentHTML("beforeend", html); 56 | DlCount++; 57 | } 58 | } 59 | }); 60 | 61 | 62 | function changeLang(inp, area, index) { 63 | let chosen = inp.value; 64 | 65 | if (!chosen) { return } 66 | if (!LANGUAGES.includes(chosen)) { return } 67 | 68 | if (inp.placeholder === chosen) { return } 69 | 70 | let code = area.querySelector("pre > code"); 71 | let highlighted = hljs.highlight(pasteStores[index], { language: chosen }); 72 | code.innerHTML = highlighted.value; 73 | 74 | inp.placeholder = chosen; 75 | } -------------------------------------------------------------------------------- /web/static/scripts/initialTheme.js: -------------------------------------------------------------------------------- 1 | function calculateSettingAsThemeString({ 2 | localStorageTheme, 3 | systemSettingDark, 4 | }) { 5 | if (localStorageTheme !== null) { 6 | return localStorageTheme; 7 | } 8 | 9 | if (systemSettingDark.matches) { 10 | return "dark"; 11 | } 12 | 13 | return "light"; 14 | } 15 | 16 | function updateThemeOnHtmlEl({ theme }) { 17 | document.querySelector("html").setAttribute("data-theme", theme); 18 | } 19 | 20 | let localStorageTheme = localStorage.getItem("theme"); 21 | let systemSettingDark = window.matchMedia("(prefers-color-scheme: dark)"); 22 | 23 | let currentThemeSetting = calculateSettingAsThemeString({ 24 | localStorageTheme, 25 | systemSettingDark, 26 | }); 27 | 28 | updateThemeOnHtmlEl({ theme: currentThemeSetting }); -------------------------------------------------------------------------------- /web/static/scripts/lineHighlights.js: -------------------------------------------------------------------------------- 1 | let selections = {}; 2 | 3 | function parseLines() { 4 | let params = new URLSearchParams(document.location.search); 5 | let param = params.get("lines"); 6 | 7 | if (!param) { 8 | return 9 | } 10 | 11 | const regex = /F(\d+)-L(\d+)(?:-L(\d+))?/g; 12 | let match; 13 | while ((match = regex.exec(param)) !== null) { 14 | let file = parseInt(match[1]); 15 | let start = parseInt(match[2]); 16 | let end = match[3] ? parseInt(match[3]) : start; 17 | 18 | if (isNaN(file) || isNaN(start) || isNaN(end)) { 19 | continue; 20 | } 21 | 22 | highlightLine(null, file - 1, start); 23 | if (start !== end) { 24 | highlightLine(null, file - 1, end); 25 | } 26 | } 27 | } 28 | 29 | parseLines(); 30 | 31 | function removeSelected(lines) { 32 | lines.forEach(line => { 33 | let child = line.querySelector("td.lineSelected"); 34 | if (child) { 35 | line.removeChild(child); 36 | line.classList.remove("lineNumRowSelected"); 37 | } 38 | }); 39 | } 40 | 41 | function updateParams() { 42 | const url = new URL(window.location); 43 | let param = Object.entries(selections).map(([key, value]) => { 44 | let end = value.end !== value.start ? `-L${value.end}_` : ''; 45 | return `F${parseInt(key) + 1}-L${value.start}${end}`; 46 | }).join(''); 47 | 48 | url.searchParams.set("lines", param); 49 | url.searchParams.delete("pastePassword"); 50 | 51 | history.pushState(null, '', url); 52 | } 53 | 54 | function replaceSelected(lines, idIndex, index, start, end) { 55 | let newLines = lines.slice(start, end); 56 | removeSelected(newLines); 57 | 58 | let line = lines[index - 1]; 59 | line.insertAdjacentHTML("beforeend", ``); 60 | line.classList.add("lineNumRowSelected"); 61 | 62 | selections[idIndex] = { "start": index, "end": index }; 63 | updateParams(); 64 | } 65 | 66 | function addLines(lines, idIndex, start, end) { 67 | let newLines = lines.slice(start - 1, end); 68 | newLines.forEach(line => { 69 | if (!line.querySelector("td.lineSelected")) { 70 | line.insertAdjacentHTML("beforeend", ``); 71 | line.classList.add("lineNumRowSelected"); 72 | } 73 | }); 74 | 75 | selections[idIndex] = { "start": start, "end": end }; 76 | updateParams(); 77 | } 78 | 79 | function highlightLine(event, idI, selected) { 80 | let idIndex = parseInt(idI); 81 | let id = `__paste_c_${idIndex}`; 82 | let block = document.getElementById(id); 83 | 84 | if (!block) { 85 | return; 86 | } 87 | 88 | let lines = Array.from(block.querySelectorAll("tbody>tr")); 89 | let line = Math.min(parseInt(selected), lines.length); 90 | 91 | let current = selections[idIndex]; 92 | if (!current) { 93 | let selectedLine = lines[line - 1]; 94 | selectedLine.insertAdjacentHTML("beforeend", ``); 95 | selectedLine.classList.add("lineNumRowSelected"); 96 | 97 | selections[idIndex] = { "start": line, "end": line }; 98 | updateParams(); 99 | return; 100 | } 101 | 102 | let { start, end } = current; 103 | 104 | if (event && !event.shiftKey) { 105 | replaceSelected(lines, idIndex, line, start - 1, end); 106 | return; 107 | } 108 | 109 | if (!event || event.shiftKey) { 110 | if (line < start) { 111 | removeSelected(lines.slice(start, end)); 112 | addLines(lines, idIndex, line, start); 113 | } else if (line <= end) { 114 | replaceSelected(lines, idIndex, line, start - 1, end); 115 | } else { 116 | addLines(lines, idIndex, start, line); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /web/static/scripts/shortcuts.js: -------------------------------------------------------------------------------- 1 | window.addEventListener("keydown", (e) => { 2 | 3 | // Ctrl + s === Save Paste 4 | if (e.ctrlKey && e.key === "s") { 5 | e.preventDefault(); 6 | e.stopPropagation(); 7 | return; 8 | } 9 | 10 | // Ctrl + Shift + R === Raw Paste 11 | else if (e.ctrlKey && e.shiftKey && e.key === "R") { 12 | e.preventDefault(); 13 | e.stopPropagation(); 14 | return; 15 | } 16 | }); -------------------------------------------------------------------------------- /web/static/scripts/themes.js: -------------------------------------------------------------------------------- 1 | function updateButton({ checkboxEl, isDark }) { 2 | checkboxEl.checked = isDark ? true : false; 3 | } 4 | 5 | let checkbox = document.querySelector("#themeSwitch"); 6 | updateButton({ checkboxEl: checkbox, isDark: currentThemeSetting === "dark" }); 7 | 8 | checkbox.addEventListener("click", (event) => { 9 | const newTheme = currentThemeSetting === "dark" ? "light" : "dark"; 10 | 11 | localStorage.setItem("theme", newTheme); 12 | updateButton({ checkboxEl: checkbox, isDark: newTheme === "dark" }); 13 | updateThemeOnHtmlEl({ theme: newTheme }); 14 | 15 | currentThemeSetting = newTheme; 16 | }); 17 | -------------------------------------------------------------------------------- /web/static/scripts/utils.js: -------------------------------------------------------------------------------- 1 | function getLangByName(name) { 2 | splat = name.split("."); 3 | if (splat.length <= 1) { 4 | return null 5 | } 6 | 7 | ext = splat[splat.length - 1]; 8 | lang = hljs.getLanguage(ext); 9 | 10 | if (!lang) { 11 | return null 12 | } 13 | 14 | let lname = lang.name.replace(/\s+/g, '').toLowerCase(); 15 | let lastN = lname.split(",")[0]; 16 | return lastN; 17 | } -------------------------------------------------------------------------------- /web/static/styles/global.css: -------------------------------------------------------------------------------- 1 | [data-theme="light"] { 2 | --color-switch: rgba(31, 31, 65, 0.9); 3 | --color-accent: #9069a7; 4 | --color-error: #dd374d; 5 | --color-security: #004ac0; 6 | --color-warning: #004ac0; 7 | --color-background: #ffe5ee; 8 | --color-background--header: #fefefe; 9 | --color-background--pastes: #fff; 10 | --color-background--resizer: rgb(255, 255, 255, 0.9); 11 | --color-background--button: #eff2f7; 12 | --color-foreground: #2e2e33; 13 | --color-foreground--dim: rgb(46, 46, 51, 0.6); 14 | --color-foreground--border: rgb(46, 46, 51, 0.2); 15 | --color-annotation: rgb(185, 52, 69); 16 | --color-second-paste: #f6f8fa; 17 | --button--brightness: brightness(0.95); 18 | --button--brightness-hover: brightness(0.85); 19 | --button--brightness-active: brightness(0.95); 20 | --color-line-hover: rgb(237, 219, 85, 0.2); 21 | --color-line-selected: rgb(237, 219, 85, 0.2); 22 | 23 | .keyboardLight { 24 | display: none !important; 25 | } 26 | 27 | .deleteFile { 28 | background-color: var(--color-background); 29 | filter: brightness(0.99); 30 | } 31 | 32 | .deleteFile:hover { 33 | cursor: pointer; 34 | filter: brightness(0.97); 35 | } 36 | 37 | .deleteFile:active { 38 | filter: brightness(0.99); 39 | } 40 | 41 | .savePaste { 42 | background-color: var(--color-background); 43 | filter: brightness(0.99); 44 | } 45 | 46 | .savePaste:hover { 47 | cursor: pointer; 48 | filter: brightness(0.97); 49 | } 50 | 51 | .savePaste:active { 52 | filter: brightness(0.99); 53 | } 54 | } 55 | 56 | [data-theme="dark"] { 57 | --color-switch: rgb(246, 249, 255, 0.6); 58 | --color-accent: #c89ee0; 59 | --color-error: #dd374d; 60 | --color-security: #c8e09e; 61 | --color-warning: #feff99; 62 | --color-background: #15151c; 63 | --color-background--header: #1d1d26; 64 | --color-background--pastes: rgb(29, 29, 38, 0.9); 65 | --color-background--resizer: rgb(29, 29, 38, 0.9); 66 | --color-background--button: #1d1d26; 67 | --color-foreground: #c9c9d1; 68 | --color-foreground--dim: rgb(201, 201, 209, 0.6); 69 | --color-foreground--border: rgb(201, 201, 209, 0.2); 70 | --color-annotation: rgb(192, 99, 112, 0.8); 71 | --color-second-paste: rgba(127, 97, 175, 0.05); 72 | --button--brightness: brightness(1.2); 73 | --button--brightness-hover: brightness(1.1); 74 | --button--brightness-active: brightness(1.1); 75 | --color-line-hover: rgb(237, 219, 85, 0.1); 76 | --color-line-selected: rgb(237, 219, 85, 0.1); 77 | 78 | .keyboardDark { 79 | display: none !important; 80 | } 81 | } 82 | 83 | * { 84 | box-sizing: border-box; 85 | } 86 | 87 | html, 88 | body { 89 | padding: 0; 90 | margin: 0; 91 | scrollbar-color: var(--color-background) var(--color-background--header); 92 | scrollbar-width: auto; 93 | } 94 | 95 | body { 96 | background-color: var(--color-background); 97 | color: var(--color-foreground); 98 | font-family: "Lato", sans-serif; 99 | min-height: 100vh; 100 | display: flex; 101 | flex-direction: column; 102 | justify-content: space-between; 103 | } 104 | 105 | a { 106 | color: var(--color-accent); 107 | } 108 | 109 | .logo { 110 | height: 2.25rem; 111 | width: 2.25rem; 112 | } 113 | 114 | .header { 115 | display: flex; 116 | flex-direction: row; 117 | justify-content: space-between; 118 | align-items: center; 119 | padding: 0.25rem 2rem; 120 | background-color: var(--color-background--header); 121 | } 122 | 123 | .headerSection { 124 | display: flex; 125 | flex-direction: row; 126 | align-items: center; 127 | gap: 0.5rem; 128 | font-size: 1.3em; 129 | color: var(--color-accent); 130 | } 131 | 132 | .headerSection { 133 | text-decoration: none; 134 | } 135 | 136 | .headerRight { 137 | display: flex; 138 | gap: 1rem; 139 | align-items: center; 140 | } 141 | 142 | .keyboard { 143 | user-select: none; 144 | width: 2.75rem; 145 | padding-top: 0.19rem; 146 | height: auto; 147 | opacity: 0.6; 148 | } 149 | 150 | .keyboard:hover { 151 | cursor: help; 152 | } 153 | 154 | .footer { 155 | display: flex; 156 | flex-direction: row; 157 | justify-content: space-between; 158 | align-items: center; 159 | padding: 1rem 2rem; 160 | } 161 | 162 | .footerSection { 163 | align-items: center; 164 | display: flex; 165 | flex-direction: row; 166 | gap: 1rem; 167 | font-size: 0.8em; 168 | } 169 | 170 | .footerSection>a { 171 | display: flex; 172 | flex-direction: row; 173 | align-items: center; 174 | gap: 0.25rem; 175 | font-size: 0.9em; 176 | } 177 | 178 | .footerText { 179 | font-size: 0.9em; 180 | color: var(--color-foreground--dim); 181 | } 182 | 183 | .content { 184 | display: flex; 185 | flex-direction: column; 186 | flex-grow: 1; 187 | padding: 2rem; 188 | gap: 2rem; 189 | } 190 | 191 | .pasteArea { 192 | display: flex; 193 | flex-grow: 1; 194 | flex-shrink: 1; 195 | flex-direction: column; 196 | width: 100%; 197 | max-width: 100%; 198 | height: 100%; 199 | background-color: var(--color-background--pastes); 200 | border-radius: 0.25rem; 201 | border: 1px solid transparent; 202 | } 203 | 204 | .dragging { 205 | opacity: 0.5; 206 | border: 1px dashed var(--color-accent); 207 | position: relative; 208 | cursor: copy; 209 | background-color: var(--color-background--pastes); 210 | } 211 | 212 | .dragging::after { 213 | pointer-events: none; 214 | content: "Drop File to Paste..."; 215 | position: absolute; 216 | top: 50%; 217 | left: 50%; 218 | transform: translate(-50%, -50%); 219 | } 220 | 221 | .prevented { 222 | border: 1px dashed var(--color-error); 223 | cursor: no-drop; 224 | } 225 | 226 | .prevented::after { 227 | content: "File is not allowed..."; 228 | color: var(--color-error); 229 | font-weight: 700; 230 | font-size: larger; 231 | } 232 | 233 | .pasteHeader { 234 | background-color: var(--color-second-paste); 235 | border-radius: 0.25rem 0.2rem 0 0; 236 | display: flex; 237 | flex-direction: row; 238 | justify-content: space-between; 239 | align-items: center; 240 | padding: 0.5rem 1rem; 241 | width: 100%; 242 | } 243 | 244 | .pasteContainer { 245 | display: flex; 246 | flex-direction: column; 247 | gap: 1rem; 248 | flex-grow: 1; 249 | width: 100%; 250 | max-width: 100%; 251 | border-radius: 0.25rem; 252 | } 253 | 254 | input[type="password"] { 255 | background-color: var(--color-background--pastes) !important; 256 | color: var(--color-foreground) !important; 257 | } 258 | 259 | .filenameArea { 260 | resize: none; 261 | background-color: var(--color-background--pastes); 262 | color: var(--color-foreground); 263 | border-radius: 0.25rem; 264 | font-family: "JetBrains Mono", monospace; 265 | font-optical-sizing: auto; 266 | font-style: normal; 267 | font-size: smaller; 268 | outline: none; 269 | border: var(--color-foreground--border) 1px solid; 270 | padding: 0.25rem; 271 | white-space: pre; 272 | overflow-wrap: normal; 273 | overflow-x: hidden; 274 | } 275 | 276 | .filenameArea:focus { 277 | outline: var(--color-foreground--dim) 1px solid; 278 | } 279 | 280 | .pasteArea>textarea { 281 | display: flex; 282 | flex-grow: 1; 283 | resize: vertical; 284 | background-color: var(--color-background--pastes); 285 | color: var(--color-foreground); 286 | outline: none; 287 | border-radius: 0.25rem; 288 | font-family: "JetBrains Mono", monospace; 289 | font-optical-sizing: auto; 290 | font-style: normal; 291 | white-space: pre; 292 | overflow-wrap: normal; 293 | overflow-x: scroll; 294 | border: none; 295 | padding: 1rem; 296 | width: 100%; 297 | height: 100%; 298 | min-height: 32rem; 299 | } 300 | 301 | .smallArea { 302 | flex-grow: 0; 303 | height: 9rem; 304 | } 305 | 306 | .smallArea>textarea { 307 | min-height: 4rem; 308 | height: 4rem; 309 | } 310 | 311 | textarea::-webkit-resizer { 312 | background-color: var(--color-background--resizer); 313 | } 314 | 315 | textarea { 316 | scrollbar-color: var(--color-background) var(--color-background--header); 317 | scrollbar-width: auto; 318 | } 319 | 320 | .addPaste { 321 | display: flex; 322 | padding: 1rem; 323 | border-radius: 0 0 0.25rem 0.25rem; 324 | background-color: var(--color-background--header); 325 | color: var(--color-accent); 326 | justify-content: center; 327 | align-content: center; 328 | user-select: none; 329 | } 330 | 331 | .addPaste:hover { 332 | cursor: pointer; 333 | filter: var(--button--brightness-hover); 334 | } 335 | 336 | .addPaste:active { 337 | filter: var(--button--brightness-active); 338 | } 339 | 340 | .deleteFile { 341 | display: flex; 342 | padding: 0.5rem 1rem; 343 | border-radius: 0.25rem; 344 | background-color: var(--color-background--header); 345 | filter: brightness(0.8); 346 | color: var(--color-accent); 347 | justify-content: center; 348 | align-content: center; 349 | user-select: none; 350 | } 351 | 352 | .deleteFile:hover { 353 | cursor: pointer; 354 | filter: brightness(0.9); 355 | } 356 | 357 | .deleteFile:active { 358 | filter: brightness(0.8); 359 | } 360 | 361 | .disabled { 362 | cursor: unset; 363 | opacity: 0.6; 364 | filter: brightness(0.9); 365 | } 366 | 367 | .disabled:hover { 368 | cursor: unset; 369 | filter: brightness(0.9); 370 | } 371 | 372 | .disabled:active { 373 | filter: brightness(0.9); 374 | } 375 | 376 | .pasteOptions { 377 | display: flex; 378 | flex-direction: column; 379 | background-color: var(--color-background--header); 380 | border-radius: 0 0 0.25rem 0.25rem; 381 | } 382 | 383 | .pasteOptions>.hrLight { 384 | width: 98%; 385 | } 386 | 387 | .hrLight { 388 | border-top: none; 389 | border-left: none; 390 | border-right: none; 391 | outline: none; 392 | border-bottom: 1px solid var(--color-foreground--border); 393 | margin: 1rem 0; 394 | align-self: center; 395 | } 396 | 397 | .pasteOptionsSection { 398 | display: flex; 399 | flex-direction: row; 400 | align-items: center; 401 | gap: 2rem; 402 | padding: 0 1rem; 403 | width: 100%; 404 | } 405 | 406 | .savePaste { 407 | display: flex; 408 | padding: 0.75rem 4rem; 409 | border-radius: 0.25rem; 410 | background-color: var(--color-background--button); 411 | filter: var(--button--brightness); 412 | color: var(--color-accent); 413 | justify-content: center; 414 | align-content: center; 415 | user-select: none; 416 | } 417 | 418 | .savePaste:hover { 419 | cursor: pointer; 420 | filter: var(--button--brightness-hover); 421 | } 422 | 423 | .savePaste:active { 424 | filter: var(--button--brightness-active); 425 | } 426 | 427 | .fileContent { 428 | padding: 0.5rem; 429 | overflow-x: auto; 430 | position: relative; 431 | } 432 | 433 | .identifierHeader { 434 | display: flex; 435 | flex-direction: row; 436 | gap: 1rem; 437 | align-items: baseline; 438 | } 439 | 440 | .identifierHeaderLeft { 441 | display: flex; 442 | flex-direction: column; 443 | gap: 0.25rem; 444 | } 445 | 446 | .identifierHeaderLeft>a { 447 | font-weight: 600; 448 | text-decoration: none; 449 | } 450 | 451 | .identifierHeaderLeft>span { 452 | color: var(--color-foreground--dim); 453 | font-weight: 400; 454 | font-size: 0.7em; 455 | } 456 | 457 | .identifierHeaderSection { 458 | font-size: 0.9em; 459 | display: flex; 460 | flex-direction: row; 461 | gap: 0.5rem; 462 | } 463 | 464 | .linenos { 465 | font-family: "JetBrains Mono", monospace; 466 | } 467 | 468 | .pre { 469 | font-family: "JetBrains Mono", monospace; 470 | } 471 | 472 | .vsc { 473 | width: 14px; 474 | height: 14px; 475 | } 476 | 477 | .pasteButton { 478 | font-size: 0.8em; 479 | color: var(--color-accent); 480 | user-select: none; 481 | } 482 | 483 | .pasteButton:hover { 484 | cursor: pointer; 485 | filter: brightness(1.1); 486 | } 487 | 488 | #errorResponse { 489 | color: var(--color-error); 490 | padding: 1rem; 491 | } 492 | 493 | .protected { 494 | display: flex; 495 | flex-direction: column; 496 | gap: 1rem; 497 | } 498 | 499 | .protectedPassword { 500 | resize: none; 501 | background-color: var(--color-background--pastes); 502 | color: var(--color-foreground); 503 | border-radius: 0.25rem; 504 | font-family: "JetBrains Mono", monospace; 505 | font-optical-sizing: auto; 506 | font-style: normal; 507 | outline: none; 508 | border: var(--color-foreground--border) 1px solid; 509 | padding: 0.5rem; 510 | white-space: pre; 511 | overflow-wrap: normal; 512 | overflow-x: hidden; 513 | height: 3rem; 514 | } 515 | 516 | .protectedPassword:focus { 517 | outline: var(--color-foreground--dim) 1px solid; 518 | } 519 | 520 | .annotations { 521 | padding-bottom: 0.25rem; 522 | font-size: 0.9em; 523 | color: var(--color-annotation); 524 | padding-left: 1rem; 525 | background-color: var(--color-second-paste); 526 | } 527 | 528 | .security { 529 | color: var(--color-security); 530 | } 531 | 532 | .langSelectContainer { 533 | display: flex; 534 | align-items: center; 535 | } 536 | 537 | .langSelectContainer>label { 538 | background-color: var(--color-background--resizer); 539 | color: var(--color-foreground); 540 | padding: 0.25rem; 541 | border-radius: 0.25rem; 542 | border: 1px solid var(--color-foreground--border); 543 | outline: none; 544 | } 545 | 546 | .langSelectContainer>label>input { 547 | background-color: transparent; 548 | color: var(--color-foreground--dim); 549 | outline: none; 550 | border: none; 551 | padding: 0.25rem; 552 | } 553 | 554 | .langSelectContainer>label:hover { 555 | cursor: pointer; 556 | filter: brightness(1.1); 557 | } 558 | 559 | .langSelectContainer>label>input:hover { 560 | cursor: pointer; 561 | } 562 | 563 | .lineNums { 564 | display: block; 565 | border-collapse: collapse; 566 | border-spacing: 0; 567 | border: none; 568 | font-family: "JetBrains Mono", monospace; 569 | font-size: 0.75rem; 570 | line-height: 1.1rem; 571 | user-select: none; 572 | } 573 | 574 | .lineNumRow { 575 | padding: 0; 576 | padding-right: 16px !important; 577 | opacity: 0.7; 578 | } 579 | 580 | .lineNumRow:hover { 581 | cursor: pointer; 582 | background-color: var(--color-line-hover); 583 | } 584 | 585 | .lineNumRowSelected { 586 | background: var(--color-line-selected); 587 | } 588 | 589 | .lineSelected { 590 | background: var(--color-line-selected); 591 | position: absolute; 592 | width: 100%; 593 | z-index: 1; 594 | height: 1.1rem; 595 | } 596 | 597 | .lineWarn { 598 | background: var(--color-error); 599 | position: absolute; 600 | width: 100%; 601 | z-index: 1; 602 | height: 1.1rem; 603 | opacity: 0.4; 604 | } 605 | 606 | code { 607 | font-family: "JetBrains Mono", monospace; 608 | font-size: 0.75rem; 609 | line-height: 1.1rem; 610 | z-index: 2; 611 | } 612 | 613 | .annotationSecond { 614 | color: var(--color-warning); 615 | opacity: 0.9; 616 | padding-left: 0.125rem; 617 | font-weight: 400; 618 | } 619 | 620 | .annotationSecond:hover { 621 | cursor: help; 622 | } 623 | 624 | /* Theme Switch */ 625 | .themeSwitch { 626 | --size: 1.5rem; 627 | 628 | appearance: none; 629 | outline: none; 630 | cursor: pointer; 631 | 632 | width: var(--size); 633 | height: var(--size); 634 | box-shadow: inset calc(var(--size) * 0.33) calc(var(--size) * -0.25) 0; 635 | border-radius: 999px; 636 | color: var(--color-switch); 637 | 638 | transition: all 500ms; 639 | 640 | &:checked { 641 | --ray-size: calc(var(--size) * -0.4); 642 | --offset-orthogonal: calc(var(--size) * 0.65); 643 | --offset-diagonal: calc(var(--size) * 0.45); 644 | 645 | transform: scale(0.75); 646 | color: var(--color-switch); 647 | box-shadow: inset 0 0 0 var(--size), 648 | calc(var(--offset-orthogonal) * -1) 0 0 var(--ray-size), 649 | var(--offset-orthogonal) 0 0 var(--ray-size), 650 | 0 calc(var(--offset-orthogonal) * -1) 0 var(--ray-size), 651 | 0 var(--offset-orthogonal) 0 var(--ray-size), 652 | calc(var(--offset-diagonal) * -1) calc(var(--offset-diagonal) * -1) 0 var(--ray-size), 653 | var(--offset-diagonal) var(--offset-diagonal) 0 var(--ray-size), 654 | calc(var(--offset-diagonal) * -1) var(--offset-diagonal) 0 var(--ray-size), 655 | var(--offset-diagonal) calc(var(--offset-diagonal) * -1) 0 var(--ray-size); 656 | } 657 | } 658 | 659 | .notFound { 660 | display: flex; 661 | flex-direction: column; 662 | gap: 0.5rem; 663 | align-self: center; 664 | } 665 | 666 | .annotationSecond { 667 | position: relative; 668 | } 669 | 670 | .annotationSecond:after { 671 | position: absolute; 672 | content: attr(data-text); 673 | color: var(--color-foreground); 674 | background-color: var(--color-background); 675 | top: 50%; 676 | transform: translateY(-50%); 677 | left: 100%; 678 | width: max-content; 679 | border-radius: 0.25rem; 680 | margin-left: 0.5rem; 681 | padding: 0.5rem; 682 | display: none; 683 | /* hide by default */ 684 | opacity: 1; 685 | } 686 | 687 | .annotationSecond:hover:after { 688 | display: block; 689 | } 690 | 691 | .keyboardTool { 692 | position: relative; 693 | } 694 | 695 | .keyboardTool:after { 696 | position: absolute; 697 | content: attr(data-text); 698 | color: var(--color-foreground); 699 | background-color: var(--color-background); 700 | width: max-content; 701 | border-radius: 0.25rem; 702 | padding: 0.75rem; 703 | display: none; 704 | /* hide by default */ 705 | opacity: 1; 706 | right: 0; 707 | white-space: pre; 708 | z-index: 9; 709 | cursor: help; 710 | } 711 | 712 | .keyboardTool:hover:after { 713 | display: inline-block; 714 | } 715 | 716 | @media screen and (max-width: 600px) { 717 | .annotations { 718 | font-size: 0.8em; 719 | } 720 | 721 | .savePaste { 722 | padding: 0.75rem; 723 | font-size: 0.8em; 724 | } 725 | 726 | .deleteFile { 727 | padding: 0.5rem 1rem; 728 | font-size: 0.8em; 729 | } 730 | 731 | .deleteFile { 732 | padding: 1rem; 733 | font-size: 0.8em; 734 | } 735 | 736 | .footer { 737 | flex-direction: column; 738 | padding: 0 0 1rem 0; 739 | } 740 | 741 | .identifierHeaderSection { 742 | font-size: 0.8em; 743 | } 744 | 745 | .identifierHeader { 746 | gap: 1rem; 747 | } 748 | 749 | .filenameArea { 750 | font-size: 0.6em; 751 | } 752 | 753 | .content { 754 | padding: 1rem 0.5rem 1rem 0.5rem; 755 | } 756 | 757 | .header { 758 | padding: 1rem 0.5rem; 759 | } 760 | 761 | .pasteArea>textarea { 762 | font-size: 0.8em; 763 | } 764 | 765 | .langSelectContainer>label { 766 | max-width: 6rem; 767 | padding: 0; 768 | } 769 | 770 | .langSelectContainer>label>input { 771 | max-width: 6rem; 772 | font-size: 0.7em; 773 | } 774 | 775 | .pasteHeader { 776 | padding: 0.5rem; 777 | } 778 | } 779 | 780 | @media screen and (max-device-width: 480px){ 781 | body { 782 | -webkit-text-size-adjust: 100%; 783 | } 784 | 785 | code { 786 | -webkit-text-size-adjust: 100%; 787 | } 788 | } 789 | -------------------------------------------------------------------------------- /web/static/styles/highlights.css: -------------------------------------------------------------------------------- 1 | pre code.hljs { 2 | display: block; 3 | overflow-x: auto; 4 | padding: 1em; 5 | font-family: "JetBrains Mono", monospace; 6 | font-size: 0.8em; 7 | } 8 | 9 | code.hljs { 10 | padding: 3px 5px; 11 | font-family: "JetBrains Mono", monospace; 12 | } 13 | 14 | .hljs-ln td { 15 | padding-right: 16px!important; 16 | } 17 | 18 | .hljs-ln-n { 19 | opacity: 0.7; 20 | } 21 | 22 | [data-theme="light"] { 23 | .hljs { 24 | color: #383a42; 25 | } 26 | 27 | .hljs-comment, 28 | .hljs-quote { 29 | color: #a0a1a7; 30 | font-style: italic; 31 | } 32 | 33 | .hljs-doctag, 34 | .hljs-keyword, 35 | .hljs-formula { 36 | color: #a626a4; 37 | } 38 | 39 | .hljs-section, 40 | .hljs-name, 41 | .hljs-selector-tag, 42 | .hljs-deletion, 43 | .hljs-subst { 44 | color: #e45649; 45 | } 46 | 47 | .hljs-literal { 48 | color: #0184bb; 49 | } 50 | 51 | .hljs-string, 52 | .hljs-regexp, 53 | .hljs-addition, 54 | .hljs-attribute, 55 | .hljs-meta .hljs-string { 56 | color: #50a14f; 57 | } 58 | 59 | .hljs-attr, 60 | .hljs-variable, 61 | .hljs-template-variable, 62 | .hljs-type, 63 | .hljs-selector-class, 64 | .hljs-selector-attr, 65 | .hljs-selector-pseudo, 66 | .hljs-number { 67 | color: #986801; 68 | } 69 | 70 | .hljs-symbol, 71 | .hljs-bullet, 72 | .hljs-link, 73 | .hljs-meta, 74 | .hljs-selector-id, 75 | .hljs-title { 76 | color: #4078f2; 77 | } 78 | 79 | .hljs-built_in, 80 | .hljs-title.class_, 81 | .hljs-class .hljs-title { 82 | color: #c18401; 83 | } 84 | 85 | .hljs-emphasis { 86 | font-style: italic; 87 | } 88 | 89 | .hljs-strong { 90 | font-weight: bold; 91 | } 92 | 93 | .hljs-link { 94 | text-decoration: underline; 95 | } 96 | } 97 | 98 | [data-theme="dark"] { 99 | .hljs { 100 | color: #b5bdca; 101 | } 102 | 103 | .hljs-comment, 104 | .hljs-quote { 105 | color: #5c6370; 106 | font-style: italic; 107 | } 108 | 109 | .hljs-doctag, 110 | .hljs-keyword, 111 | .hljs-formula { 112 | color: #c678dd; 113 | } 114 | 115 | .hljs-section, 116 | .hljs-name, 117 | .hljs-selector-tag, 118 | .hljs-deletion, 119 | .hljs-subst { 120 | color: #f5c2e4; 121 | } 122 | 123 | .hljs-literal { 124 | color: #f3a472; 125 | } 126 | 127 | .hljs-string, 128 | .hljs-regexp, 129 | .hljs-addition, 130 | .hljs-attribute, 131 | .hljs-meta .hljs-string { 132 | color: #8ca878; 133 | } 134 | 135 | .hljs-attr, 136 | .hljs-variable, 137 | .hljs-template-variable, 138 | .hljs-type, 139 | .hljs-selector-class, 140 | .hljs-selector-attr, 141 | .hljs-selector-pseudo, 142 | .hljs-number { 143 | color: #d19a66; 144 | } 145 | 146 | .hljs-meta { 147 | color: #ebb371; 148 | } 149 | 150 | .hljs-symbol, 151 | .hljs-bullet, 152 | .hljs-link, 153 | .hljs-selector-id, 154 | .hljs-title { 155 | color: #61aeee; 156 | } 157 | 158 | .hljs-built_in { 159 | color: #6cb4ed; 160 | } 161 | 162 | .hljs-title.class_, 163 | .hljs-class .hljs-title { 164 | color: #6cb4ed; 165 | } 166 | 167 | .hljs-emphasis { 168 | font-style: italic; 169 | } 170 | 171 | .hljs-strong { 172 | font-weight: bold; 173 | } 174 | 175 | .hljs-link { 176 | text-decoration: underline; 177 | } 178 | 179 | .hljs-params { 180 | color: #b5bdca; 181 | } 182 | } 183 | 184 | @media screen and (max-width: 600px) { 185 | pre code.hljs { 186 | font-size: 0.7em; 187 | } 188 | } --------------------------------------------------------------------------------