├── .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"""