Compare commits

..

45 Commits

Author SHA1 Message Date
Colbster937
1cd60a4dba update bstats for platform types 2026-01-24 21:47:30 -06:00
Colbster937
ebcae682aa . 2026-01-21 19:32:30 -06:00
Colbster937
f22e800439 share plugin commit in http api 2026-01-21 10:43:47 -06:00
Colbster937
f0274ff4d4 only unregister routes fi enabled 2026-01-21 10:21:05 -06:00
Colbster937
12f9d669b4 make it register an eaglerxserver route 2026-01-20 22:03:34 -06:00
Colbster937
c43de8a1c9 accept eula 2026-01-19 15:40:40 -06:00
Colbster937
d8fa2b10c1 fix auto update invalid jar err 2026-01-17 10:38:56 -06:00
Colbster937
89311ee6de eagler 2026-01-16 18:06:31 -06:00
Colbster937
14ffd4eb08 relocate deps 2026-01-16 16:09:04 -06:00
Colbster937
50fdbb0c28 add http blacklist sharing 2026-01-14 16:44:44 -06:00
Colbster937
bb71befe78 update readme 2026-01-14 14:55:22 -06:00
Colbster937
49f4e249e5 bump version 2026-01-14 14:54:56 -06:00
Colbster937
5491efa79a management cmds 2026-01-14 14:54:30 -06:00
Colbster937
5e29f7f74a add manual update command 2026-01-13 20:32:08 -06:00
Colbster937
ffdbcfa3b4 fix version sorting 2026-01-12 16:27:50 -06:00
Colbster937
58123dddd7 eagler 2026-01-12 16:20:41 -06:00
Colbster937
91adbd5526 use commit sha in snapshot file names 2026-01-12 13:35:21 -06:00
Colbster937
2b1ccd018d auto update plugin 2026-01-12 12:34:17 -06:00
Colbster937
8f1fd3f1f4 allow disabling ips in webhook 2026-01-11 00:23:02 -06:00
Colbster937
50e2a954cd suppress warnings 2026-01-11 00:20:15 -06:00
Colbster937
a6fb5e379c remove build files 2026-01-11 00:02:54 -06:00
Colbster937
2699ceaeff fix ipv6 bug 2026-01-11 00:02:23 -06:00
Colbster937
9985223d22 sort imports 2026-01-10 13:06:24 -06:00
Colbster937
b6df47ee2e fix 2026-01-10 12:56:20 -06:00
Colbster937
9caec20ef0 add modrinth release 2026-01-10 12:52:04 -06:00
Colbster937
34226ec549 fix update checker's snapshot versions 2026-01-09 20:20:35 -06:00
Colbster937
1aa22606b2 add discord webhook support 2026-01-09 19:49:51 -06:00
Colbster937
a483b6ccc5 only run action when src is modified 2026-01-09 18:13:50 -06:00
Colbster937
a78fa33de8 fix README 2026-01-09 18:11:51 -06:00
Colbster937
92a7f746c1 fix README 2026-01-09 18:09:09 -06:00
Colbster937
430653a4ab 2.0 2026-01-09 18:07:40 -06:00
Colbster937
eab1eb27e7 fix 2026-01-02 19:51:06 -06:00
Colbster937
0b6e9e1b83 rm .vscode 2026-01-02 19:45:23 -06:00
Colbster937
07fa4bc21c switch to kotlin dsl & fix build on gradle 9 2026-01-02 19:44:41 -06:00
Colbster937
b10882c65f Update build.gradle 2026-01-02 19:37:46 -06:00
Colbster937
ee4b14bf30 Merge pull request #2 from Cirsius/main
bug fixes by @cirsius
2026-01-02 19:37:27 -06:00
Cirsius
c913d9d34e make work with eaglermotd 2026-01-02 19:12:21 -06:00
Cirsius
bfed49407f fix bug w ipv6 2026-01-02 17:42:22 -06:00
Colbster937
d4541c9de4 udpate 2025-08-08 10:40:19 -05:00
Colbster937
58e9819c3a fix webhook with ipv6 2025-07-09 17:15:32 -05:00
Colbster937
6e1d5d132c add ip blacklisting & blacklist cmd 2025-06-13 13:21:32 -04:00
Colbster937
1a22788630 change back number of lines before eagler face :> 2025-05-21 18:16:02 -05:00
Colbster937
cf0481fb58 Merge pull request #1 from Atticuss26/main
Update config.yml to add a hacked client site
2025-05-21 18:15:02 -05:00
Colbster937
f8ea6d5bfd Add more hacked clients 2025-05-21 18:14:47 -05:00
Atticuss26
8d5e5d688b Update config.yml to add a hacked client site 2025-05-21 16:04:58 -07:00
54 changed files with 3748 additions and 922 deletions

View File

@@ -1,76 +0,0 @@
name: Build Plugin
on:
push:
workflow_dispatch:
permissions:
contents: write
jobs:
build:
if: ${{ github.ref == 'refs/heads/main' }}
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
- name: Build Jar
run: |
gradle wrapper
./gradlew shadowJar
- name: Publish Jar
uses: actions/upload-artifact@v4
with:
name: OriginBlacklist
path: build/libs/OriginBlacklist.jar
- name: Extract Version
id: version
run: |
VERSION=$(grep "^version" build.gradle | head -n 1 | cut -d\' -f2)
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Remove Existing Release
run: |
gh release delete v${{ steps.version.outputs.version }} -y || true
git push origin :refs/tags/v${{ steps.version.outputs.version }} || true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Create Release
id: create_release
uses: softprops/action-gh-release@v1
with:
tag_name: v${{ steps.version.outputs.version }}
name: ${{ steps.version.outputs.version }}
draft: false
prerelease: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./build/libs/OriginBlacklist.jar
asset_name: OriginBlacklist_${{ steps.version.outputs.version }}.jar
asset_content_type: application/java-archive
- uses: eregon/publish-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
release_id: ${{ steps.create_release.outputs.id }}

98
.github/workflows/gradle.yml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: Build Plugin
on:
workflow_dispatch:
push:
branches: [ main ]
paths: [ src/**, build.gradle.kts, settings.gradle.kts ]
permissions:
contents: write
actions: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 21
- uses: gradle/actions/setup-gradle@v4
- run: |
gradle wrapper
chmod +x ./gradlew
./gradlew shadowJar
- id: vars
run: |
echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
./gradlew -q printVars | sed 's/ = /=/g' >> "$GITHUB_OUTPUT"
- id: ghck
run: |
CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"https://api.github.com/repos/${{ github.repository }}/releases/tags/v${{ steps.vars.outputs.VERS }}")
if [ "$CODE" = "200" ]; then
echo "EXISTS=true" >> "$GITHUB_OUTPUT"
else
echo "EXISTS=false" >> "$GITHUB_OUTPUT"
fi
- id: mrck
run: |
echo "TOKEN=$([ -n "${{ secrets.MODRINTH_TOKEN }}" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- id: dist
run: |
echo "TAG_NAME=${{ format('v{0}{1}', steps.vars.outputs.VERS, steps.ghck.outputs.EXISTS == 'true' && format('+{0}', steps.vars.outputs.COMMIT_HASH) || '') }}" >> "$GITHUB_OUTPUT"
echo "REL_NAME=${{ format('{0}{1}', steps.ghck.outputs.EXISTS == 'true' && 'Snapshot ' || 'v', steps.ghck.outputs.EXISTS == 'true' && steps.vars.outputs.COMMIT_HASH || steps.vars.outputs.VERS) }}" >> "$GITHUB_OUTPUT"
echo "ART_NAME=${{ format('{0}{1}.jar', steps.vars.outputs.AFCT, steps.ghck.outputs.EXISTS == 'true' && format('+{0}', steps.vars.outputs.COMMIT_HASH) || '') }}" >> "$GITHUB_OUTPUT"
- run: |
mkdir -p dist
cp "./build/libs/${{ steps.vars.outputs.AFCT }}.jar" ./dist/${{ steps.dist.outputs.ART_NAME }}
- uses: actions/upload-artifact@v4
with:
path: dist/${{ steps.dist.outputs.ART_NAME }}
name: ${{ steps.dist.outputs.ART_NAME }}
- if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.dist.outputs.TAG_NAME }}
name: ${{ steps.dist.outputs.REL_NAME }}
files: dist/${{ steps.dist.outputs.ART_NAME }}
prerelease: ${{ steps.ghck.outputs.EXISTS == 'true' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- if: github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.mrck.outputs.TOKEN == 'true'
uses: cloudnode-pro/modrinth-publish@v2
with:
token: ${{ secrets.MODRINTH_TOKEN }}
project: WfBtRGYI
version: ${{ steps.dist.outputs.TAG_NAME }}
loaders: '["bukkit", "bungeecord", "paper", "purpur", "spigot", "velocity", "waterfall"]'
game-versions: '["1.8.x", "1.9.x", "1.10.x", "1.11.x", "1.12.x", "1.13.x", "1.14.x", "1.15.x", "1.16.x", "1.17.x", "1.18.x", "1.19.x", "1.20.x", "1.21.x"]'
files: dist/${{ steps.dist.outputs.ART_NAME }}
primary-file: ${{ steps.dist.outputs.ART_NAME }}
name: ${{ steps.dist.outputs.REL_NAME }}
channel: ${{ steps.ghck.outputs.EXISTS == 'true' && 'beta' || 'release' }}
dependencies: |-
[{
"project_id": "Gtsn3SWv",
"dependency_type": "required"
}]

19
.gitignore vendored
View File

@@ -1,9 +1,10 @@
**/.DS_Store /.gradle/
.idea /.vscode/
.gradle /gradle/**
gradle /build/
build /bin/
run /run/
bin /gradlew
gradlew /gradlew.bat
gradlew.bat !/gradle/wrapper/
!/gradle/wrapper/*.properties

661
LICENSE.md Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -1,32 +1,36 @@
# OriginBlacklist <div align="center">
<h1>OriginBlacklist<br><img src="https://github.com/WebMCDevelopment/originblacklist/actions/workflows/gradle.yml/badge.svg"></h1>
<b><a>An eaglercraft client blacklisting plugin</a></b>
</div>
basically just a reimplementation of originblacklist but for eaglerxserver <h2>Features</h2>
> [!WARNING] - [x] Origin based blacklisting
> **Velocity is the main platform I'm developing this for, bungee & bukkit will still work but will probably have some bugs and will receive less support!** - [x] Client brand based blacklisting
- [x] Username based blacklisting
- [x] IP based blacklisting
- [x] Kick message customization
- [x] Blacklist MOTD customization
- [x] MiniMessage and legacy formattings supported
- [x] Plugin update checker
- [x] Send blacklist logs to a webhook
- [x] Ingame blacklist management commands
- [x] Blacklist sharing via EaglerXServer routes
- [x] Reverse blacklist (whitelist)
- [ ] Subscribe to an auto-updating blacklist
### Features <h2>Changes from v1</h2>
- [x] Origin Blacklisting
- [x] Brand Blacklisting
- [x] Username blacklisting
- [x] Custom kick message
- [x] Custom blacklist MOTD
- [x] MiniMessage formatting for messages
- [x] Velocity, *Bungee, and *Bukkit support
<br>_<sub><span style="color:gray">Bungee and Bukkit are should work, but have bugs.</span></sub>_
- [x] Send blacklists to a discord webhook
- [ ] Blacklist subscription URLs
- [ ] Simple blacklist command
- [ ] Blacklist -> Whitelist
- [ ] IP blacklisting
- [ ] Update system
### Download - [x] Modular multi-platform support
**[https://github.com/colbster937/originblacklist/releases/latest/](https://github.com/colbster937/originblacklist/releases/latest/)** - [x] JSON5 based configuration
### Building <h2>Download</h2>
``` The latest release can be found at <b><a href="https://github.com/WebMCDevelopment/originblacklist/releases/latest/">https://github.com/WebMCDevelopment/originblacklist/releases/latest/</a></b>
$ git clone https://github.com/colbster937/originblacklist.git
<h2>Building</h2>
```sh
$ git clone https://github.com/WebMCDevelopment/originblacklist
$ cd originblacklist $ cd originblacklist
$ gradle wrapper $ gradle wrapper
$ ./gradlew shadowJar $ ./gradlew shadowJar

View File

@@ -1,84 +0,0 @@
plugins {
id 'java'
id 'eclipse'
id 'org.jetbrains.gradle.plugin.idea-ext' version '1.1.8'
id 'com.github.johnrengelman.shadow' version '8.1.1'
id("xyz.jpenilla.run-velocity") version "2.3.1"
}
group = 'dev.colbster937'
version = '1.0.6'
description = 'A reimplementation of OriginBlacklist for EaglerXServer'
def targetJavaVersion = 17
repositories {
mavenCentral()
maven {
name = "papermc-repo"
url = "https://repo.papermc.io/repository/maven-public/"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/groups/public/"
}
maven {
name = "spigotmc-repo"
url = "https://hub.spigotmc.org/nexus/content/repositories/public/"
}
maven {
name = "md_5"
url = "https://repo.md-5.net/content/repositories/releases/"
}
maven {
name = "aikar"
url = "https://repo.aikar.co/nexus/content/groups/aikar/"
}
maven {
name = "lax1dude"
url = "https://repo.lax1dude.net/repository/releases/"
}
}
dependencies {
compileOnly("com.velocitypowered:velocity-api:3.3.0-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.3.0-SNAPSHOT")
compileOnly("org.bukkit:bukkit:1.8-R0.1-SNAPSHOT")
compileOnly("net.md-5:bungeecord-api:1.8-SNAPSHOT")
compileOnly("net.lax1dude.eaglercraft.backend:api-velocity:1.0.0")
compileOnly("net.lax1dude.eaglercraft.backend:api-bungee:1.0.0")
compileOnly("net.lax1dude.eaglercraft.backend:api-bukkit:1.0.0")
implementation("org.yaml:snakeyaml:2.2")
implementation("net.kyori:adventure-text-serializer-legacy:4.20.0")
implementation("net.kyori:adventure-text-minimessage:4.20.0")
}
tasks {
runVelocity {
velocityVersion("3.3.0-SNAPSHOT")
}
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
processResources {
filesMatching(['plugin.yml', 'bungee.yml', 'velocity-plugin.json', 'Base.java']) {
expand(
version: project.version,
description: project.description
)
}
}
shadowJar {
relocate 'org.yaml.snakeyaml', 'dev.colbster937.shaded.snakeyaml'
archiveVersion.set('')
archiveClassifier.set('')
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.release.set(targetJavaVersion)
}

209
build.gradle.kts Normal file
View File

@@ -0,0 +1,209 @@
import groovy.lang.Closure
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import com.palantir.gradle.gitversion.VersionDetails
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.language.jvm.tasks.ProcessResources
import xyz.jpenilla.runpaper.task.RunServer
import xyz.jpenilla.runwaterfall.task.RunWaterfall
import xyz.jpenilla.runvelocity.task.RunVelocity
val PLUGIN_NAME = "OriginBlacklist"
val PLUGIN_IDEN = "originblacklist"
val PLUGIN_DOMN = "xyz.webmc.$PLUGIN_IDEN"
val PLUGIN_DESC = "An eaglercraft client blacklist plugin."
val PLUGIN_VERS = "2.0.7"
val PLUGIN_SITE = "https://github.com/WebMCDevelopment/$PLUGIN_IDEN"
val PLUGIN_DEPA = listOf("EaglercraftXServer")
val PLUGIN_DEPB = listOf("EaglercraftXServer")
val PLUGIN_DEPC = listOf("eaglerxserver")
val PLUGIN_SDPA = listOf("PlaceholderAPI")
val PLUGIN_SDPB = listOf("PAPIProxyBridge")
val PLUGIN_SDPC = listOf("papiproxybridge")
val PLUGIN_PROV = emptyList<String>()
val PLUGIN_ATHR = listOf("Colbster937")
val PLUGIN_CTBR = emptyList<String>()
val PLUGIN_DEPA_J = getBukkitBungeeDeps(PLUGIN_DEPA)
val PLUGIN_DEPB_J = getBukkitBungeeDeps(PLUGIN_DEPB)
val PLUGIN_DEPC_J = getVelocityDeps(PLUGIN_DEPC, PLUGIN_SDPC)
val PLUGIN_SDPA_J = getBukkitBungeeDeps(PLUGIN_SDPA)
val PLUGIN_SDPB_J = getBukkitBungeeDeps(PLUGIN_SDPB)
val PLUGIN_PROV_J = getBukkitBungeeDeps(PLUGIN_PROV)
val PLUGIN_ATHR_J = getBukkitBungeeDeps(PLUGIN_ATHR)
val PLUGIN_CTBR_J = getBukkitBungeeDeps(PLUGIN_CTBR)
val EAGXS_VER = "1.0.8"
plugins {
id("java")
id("com.gradleup.shadow") version "9.3.1"
id("com.palantir.git-version") version "4.2.0"
id("xyz.jpenilla.run-paper") version "3.0.2"
id("xyz.jpenilla.run-waterfall") version "3.0.2"
id("xyz.jpenilla.run-velocity") version "3.0.2"
}
@Suppress("UNCHECKED_CAST")
val GIT_INFO = (extra["versionDetails"] as Closure<VersionDetails>)()
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://oss.sonatype.org/content/groups/public/")
maven("https://hub.spigotmc.org/nexus/content/repositories/public/")
maven("https://repo.md-5.net/content/repositories/releases/")
maven("https://repo.aikar.co/nexus/content/groups/aikar/")
maven("https://repo.lax1dude.net/repository/releases/")
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/")
maven("https://repo.william278.net/releases/")
}
dependencies {
compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT")
compileOnly("org.bukkit:bukkit:1.8-R0.1-SNAPSHOT")
compileOnly("net.md-5:bungeecord-api:1.21-R0.5-SNAPSHOT")
compileOnly("net.lax1dude.eaglercraft.backend:api-velocity:1.0.0")
compileOnly("net.lax1dude.eaglercraft.backend:api-bungee:1.0.0")
compileOnly("net.lax1dude.eaglercraft.backend:api-bukkit:1.0.0")
compileOnly("me.clip:placeholderapi:2.11.7")
compileOnly("net.william278:papiproxybridge:1.8.4")
implementation("org.semver4j:semver4j:6.0.0")
implementation("de.marhali:json5-java:3.0.0")
implementation("net.kyori:adventure-text-minimessage:4.26.1")
implementation("net.kyori:adventure-text-serializer-legacy:4.26.1")
implementation("com.github.seancfoley:ipaddress:5.5.1")
implementation("org.bstats:bstats-bukkit:3.1.0")
implementation("org.bstats:bstats-bungeecord:3.1.0")
implementation("org.bstats:bstats-velocity:3.1.0")
}
sourceSets {
named("main") {
java.srcDir("./src/main/java")
resources.srcDir("./src/main/resources")
}
}
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
}
val BUILD_PROPS = mapOf(
"plugin_name" to PLUGIN_NAME,
"plugin_iden" to PLUGIN_IDEN,
"plugin_desc" to PLUGIN_DESC,
"plugin_vers" to PLUGIN_VERS,
"plugin_site" to PLUGIN_SITE,
"plugin_depa" to PLUGIN_DEPA_J,
"plugin_depb" to PLUGIN_DEPB_J,
"plugin_depc" to PLUGIN_DEPC_J,
"plugin_sdpa" to PLUGIN_SDPA_J,
"plugin_sdpb" to PLUGIN_SDPB_J,
"plugin_prov" to PLUGIN_PROV_J,
"plugin_athr" to PLUGIN_ATHR_J,
"plugin_ctbr" to PLUGIN_CTBR_J,
"git_cm_hash" to GIT_INFO.gitHashFull,
)
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(17)
}
tasks.withType<ProcessResources>().configureEach {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
outputs.upToDateWhen { false }
doFirst {
filesMatching(listOf("plugin.yml", "bungee.yml", "velocity-plugin.json")) {
expand(BUILD_PROPS)
}
}
doLast {
val file = destinationDir.resolve("build.properties")
file.parentFile.mkdirs()
file.writeText(
BUILD_PROPS.entries.joinToString("\n") { (k, v) ->
"$k = $v"
}
)
}
inputs.files(tasks.named<JavaCompile>("compileJava").map { it.outputs.files })
}
tasks.withType<Jar>().configureEach {
if (this !is ShadowJar) enabled = false
}
tasks.withType<ShadowJar>().configureEach {
doFirst {
delete(layout.buildDirectory.dir("libs"))
mkdir(layout.buildDirectory.dir("libs"))
}
relocate("inet.ipaddr", "$PLUGIN_DOMN.shaded.ipaddress")
relocate("de.marhali.json5", "$PLUGIN_DOMN.shaded.json5")
relocate("org.bstats", "$PLUGIN_DOMN.shaded.bstats")
relocate("org.semver4j.semver4j", "$PLUGIN_DOMN.shaded.semver4j")
// relocate("net.kyori.adventure", "$PLUGIN_DOMN.shaded.adventure")
archiveFileName.set("$PLUGIN_NAME-$PLUGIN_VERS.jar")
}
tasks.named("build") {
dependsOn(tasks.named("shadowJar"))
}
tasks.register("printVars") {
group = "help"
doLast {
println("VERS = " + PLUGIN_VERS)
println("AFCT = " + tasks.named("shadowJar").get().outputs.files.singleFile.name.removeSuffix(".jar"))
}
}
tasks.withType<RunServer>().configureEach {
minecraftVersion("1.12.2")
runDirectory.set(layout.projectDirectory.dir("run/paper"))
jvmArgs("-Dcom.mojang.eula.agree=true")
downloadPlugins {
github("lax1dude", "eaglerxserver", "v" + EAGXS_VER, "EaglerXServer.jar")
modrinth("placeholderapi", "2.11.7")
}
}
tasks.withType<RunWaterfall>().configureEach {
waterfallVersion("1.21")
runDirectory.set(layout.projectDirectory.dir("run/waterfall"))
downloadPlugins {
github("lax1dude", "eaglerxserver", "v" + EAGXS_VER, "EaglerXServer.jar")
}
}
tasks.withType<RunVelocity>().configureEach {
velocityVersion("3.4.0-SNAPSHOT")
runDirectory.set(layout.projectDirectory.dir("run/velocity"))
downloadPlugins {
github("lax1dude", "eaglerxserver", "v" + EAGXS_VER, "EaglerXServer.jar")
modrinth("miniplaceholders", "3.1.0")
}
}
fun getBukkitBungeeDeps(list: List<String>): String {
return list.joinToString(
prefix = "[",
postfix = "]"
) { "\"$it\"" }
}
fun getVelocityDeps(a: List<String>, b: List<String>): String {
val c = a.joinToString(", ") { "{\"id\":\"$it\",\"optional\":false}" }
val d = b.joinToString(", ") { "{\"id\":\"$it\",\"optional\":true}" }
return "[" + listOf(c, d).filter { it.isNotEmpty() }.joinToString(",") + "]"
}

View File

@@ -0,0 +1,3 @@
org.gradle.jvmargs = -Xmx1G
org.gradle.parallel = true
org.gradle.problems.report = false

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

BIN
img/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
img/icon2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

View File

@@ -1 +0,0 @@
rootProject.name = 'OriginBlacklist'

View File

@@ -1,254 +0,0 @@
package dev.colbster937.originblacklist.base;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.lax1dude.eaglercraft.backend.server.api.*;
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftMOTDEvent;
import net.lax1dude.eaglercraft.backend.server.api.query.IMOTDConnection;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class Base {
private static LoggerAdapter adapter;
private static IEaglerXServerAPI api;
private static ConfigManager config;
public static void setLogger(LoggerAdapter log) {
adapter = log;
}
public static void setApi(IEaglerXServerAPI api1) {
api = api1;
}
public static String apiVer = "1.0.2";
public static boolean checkVer(String v1, String v2) {
String[] c = v1.split("\\.");
String[] r = v2.split("\\.");
for (int i = 0; i < Math.max(c.length, r.length); i++) {
int c1 = i < c.length ? Integer.parseInt(c[i]) : 0;
int r1 = i < r.length ? Integer.parseInt(r[i]) : 0;
if (c1 < r1)
return false;
if (c1 > r1)
return true;
}
return true;
}
public static LoggerAdapter getLogger() {
if (adapter == null)
throw new IllegalStateException("Logger not initialized!");
return adapter;
}
public interface LoggerAdapter {
void info(String msg);
void warn(String msg);
void error(String msg);
}
public static void handleConnection(IEaglercraftLoginEvent e) {
IEaglerLoginConnection conn = e.getLoginConnection();
String origin = conn.getWebSocketHeader(EnumWebSocketHeader.HEADER_ORIGIN);
String brand = conn.getEaglerBrandString();
String name = conn.getUsername();
if (origin != null && !origin.equals("null")) {
for (String origin1 : config.blacklist.origins) {
if (matches(origin, origin1)) {
setKick(e, formatKickMessage("origin", "website", origin, conn.getWebSocketHost()));
webhook(conn, origin, brand, "origin");
return;
}
}
}
if (brand != null && !brand.equals("null")) {
for (String brand1 : config.blacklist.brands) {
if (matches(brand, brand1)) {
setKick(e, formatKickMessage("brand", "client", brand, conn.getWebSocketHost()));
webhook(conn, origin, brand, "brand");
return;
}
}
}
if (name != null && !name.equals("null")) {
for (String name1 : config.blacklist.players) {
if (matches(name, name1) || (name.length() > 16 || name.length() < 3)) {
setKick(e, formatKickMessage("player", "username", name, conn.getWebSocketHost()));
webhook(conn, origin, name, "player");
return;
}
}
}
}
public static void setKick(IEaglercraftLoginEvent e, Component msg) {
try {
getLogger().info("Kicked " + e.getProfileUsername());
e.setKickMessage(msg);
} catch (Throwable ignored) {
String msg1 = LegacyComponentSerializer.legacySection().serialize(msg);
e.setKickMessage(msg1);
}
}
public static void handleMOTD(IEaglercraftMOTDEvent e) {
if (config.messages.motd.enabled) {
IMOTDConnection conn = e.getMOTDConnection();
String origin = conn.getWebSocketHeader(EnumWebSocketHeader.HEADER_ORIGIN);
List<String> m = List.of(config.messages.motd.text.split("\n")).stream()
.map(line -> line
.replaceAll("%blocktype%", "origin")
.replaceAll("%easyblocktype%", "website")
.replaceAll("%blocked%", origin)
.replaceAll("%host%", conn.getWebSocketHost()))
.map(line -> LegacyComponentSerializer.legacySection().serialize(
MiniMessage.miniMessage().deserialize(line)))
.collect(Collectors.toList());
if (origin != null && !origin.equals("null")) {
for (String origin1 : config.blacklist.origins) {
if (matches(origin, origin1)) {
setMOTD(conn, m);
return;
}
}
} else if (origin != null && !origin.equals("null")) {
setMOTD(conn, m);
}
}
}
public static void setMOTD(IMOTDConnection conn, List<String> m) {
conn.setServerMOTD(m);
conn.setPlayerTotal(0);
conn.setPlayerMax(0);
conn.setPlayerList(List.of());
if (config.messages.motd.icon != null && !config.messages.motd.icon.isEmpty()) {
try {
BufferedImage img = ImageIO.read(new File(config.messages.motd.icon));
if (img.getWidth() != 64 || img.getHeight() != 64) {
getLogger().warn("Icon must be 64x64");
return;
}
byte[] bytes = new byte[64 * 64 * 4];
for (int y = 0; y < 64; y++) {
for (int x = 0; x < 64; x++) {
int pixel = img.getRGB(x, y);
int i = (y * 64 + x) * 4;
bytes[i] = (byte) ((pixel >> 16) & 0xFF);
bytes[i + 1] = (byte) ((pixel >> 8) & 0xFF);
bytes[i + 2] = (byte) (pixel & 0xFF);
bytes[i + 3] = (byte) ((pixel >> 24) & 0xFF);
}
}
conn.setServerIcon(bytes);
} catch (IOException ex) {
getLogger().error(ex.toString());
}
}
}
public static boolean matches(String text1, String text2) {
return text1.toLowerCase().matches(text2.replace(".", "\\.").replaceAll("\\*", ".*").toLowerCase());
}
public static Component formatKickMessage(String type, String easytype, String value, String host) {
String help = "";
if (type != "player") {
help = config.messages.help.generic;
} else {
help = config.messages.help.player;
}
return MiniMessage.miniMessage().deserialize(
config.messages.kick
.replaceAll("%help%", help)
.replaceAll("%blocktype%", type)
.replaceAll("%easyblocktype%", easytype)
.replaceAll("%blocked%", value)
.replaceAll("%host%", host));
}
public static void webhook(IEaglerLoginConnection plr, String origin, String brand, String type) {
String webhook = config.discord.webhook;
if (webhook == null || webhook.isBlank())
return;
CompletableFuture.runAsync(() -> {
String addr = (plr.getPlayerAddress() != null ? plr.getPlayerAddress().toString().substring(1) : "undefined:undefined").split(":")[0];
int protocol = !plr.isEaglerXRewindPlayer() ? plr.getMinecraftProtocol() : plr.getRewindProtocolVersion();
String host = plr.getWebSocketHost();
String userAgent = plr.getWebSocketHeader(EnumWebSocketHeader.HEADER_USER_AGENT);
Boolean rewind = plr.isEaglerXRewindPlayer();
if (userAgent == null || userAgent.isEmpty())
userAgent = "undefined";
String payload = String.format(
"""
{
"content": "Blocked a blacklisted %s from joining",
"embeds": [
{
"title": "Player Information",
"description": "🎮 **Name:** %s\\n🏠 **IP:** %s\\n🌄 **PVN:** %s\\n🌐 **Origin:** %s\\n🔋 **Brand:** %s\\n🪑 **Host:** %s\\n🧊 **User Agent:** %s\\n⏪ **Rewind:** %s"
}
]
}
""",
type, plr.getUsername(), addr, protocol, origin, brand, plr.isWebSocketSecure() ? "wss://" : "ws://" + host, userAgent, rewind ? "Yes" : "No");
try {
HttpURLConnection conn = (HttpURLConnection) new URL(webhook).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
try (OutputStream os = conn.getOutputStream()) {
os.write(payload.getBytes());
}
conn.getInputStream().close();
} catch (Exception e) {
getLogger().warn("Failed to send webhook: " + e);
}
});
}
public static void init() {
File motdIcon = new File(config.messages.motd.icon);
if (!motdIcon.exists()) {
try (InputStream in = ConfigManager.class.getResourceAsStream("/server-blocked.png")) {
if (in != null) {
Files.copy(in, motdIcon.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
getLogger().warn(e.toString());
}
}
}
public static void reloadConfig() {
config = ConfigManager.loadConfig(adapter);
}
}

View File

@@ -1,39 +0,0 @@
package dev.colbster937.originblacklist.base;
public class Command {
public interface CommandContext {
String getName();
void reply(String message);
boolean hasPermission(String permission);
String[] getArgs();
}
public static void usage(CommandContext ctx) {
ctx.reply("<aqua>Commands:</aqua>");
ctx.reply("<gray> - /originblacklist reload</gray>");
}
public static void handle(CommandContext ctx) {
String[] args = ctx.getArgs();
if (!ctx.hasPermission("originblacklist.reload")) {
ctx.reply("<red>You do not have permission to use this command.</red>");
return;
} else if (args.length == 0) {
usage(ctx);
return;
}
String sub = args[0].toLowerCase();
switch (sub) {
case "reload" -> {
Base.reloadConfig();
ctx.reply("<green>Reloaded.</green>");
}
default -> usage(ctx);
}
}
}

View File

@@ -1,95 +0,0 @@
package dev.colbster937.originblacklist.base;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.DumperOptions;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
public class ConfigManager {
public Messages messages = new Messages();
public List<String> subscriptions = List.of();
public Blacklist blacklist = new Blacklist();
public Discord discord = new Discord();
public static ConfigManager loadConfig(Base.LoggerAdapter logger) {
File f = new File("plugins/originblacklist/config.yml");
try {
if (!f.exists()) {
f.getParentFile().mkdirs();
try (InputStream in = ConfigManager.class.getResourceAsStream("/config.yml")) {
if (in != null) Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
Yaml y = new Yaml(new Constructor(ConfigManager.class, new LoaderOptions()));
ConfigManager l;
try (InputStream in = new FileInputStream(f)) { l = y.load(in); }
if (l == null) l = new ConfigManager();
Yaml raw = new Yaml();
Map<String, Object> u = raw.load(new FileInputStream(f));
Map<String, Object> d = raw.load(ConfigManager.class.getResourceAsStream("/config.yml"));
if (mergeConfig(u, d)) saveConfig(u, f);
return l;
} catch (IOException e) {
return new ConfigManager();
}
}
@SuppressWarnings("unchecked")
private static boolean mergeConfig(Map<String, Object> u, Map<String, Object> d) {
boolean c = false;
for (String k : d.keySet()) {
if (!u.containsKey(k)) {
u.put(k, d.get(k));
c = true;
} else if (u.get(k) instanceof Map && d.get(k) instanceof Map)
c |= mergeConfig((Map<String, Object>) u.get(k), (Map<String, Object>) d.get(k));
}
return c;
}
private static void saveConfig(Map<String, Object> m, File f) throws IOException {
DumperOptions o = new DumperOptions();
o.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
o.setPrettyFlow(true);
new Yaml(o).dump(m, new FileWriter(f));
}
public static class Blacklist {
public List<String> origins;
public List<String> brands;
public List<String> players;
public boolean missing_origin;
public String blacklist_redirect;
}
public static class Discord {
public String webhook;
}
public static class Messages {
public String kick;
public MOTD motd;
public Help help;
}
public static class MOTD {
public boolean enabled;
public String text;
public String icon;
}
public static class Help {
public String generic;
public String player;
}
}

View File

@@ -1,24 +0,0 @@
package dev.colbster937.originblacklist.bukkit;
import dev.colbster937.originblacklist.base.Command;
import dev.colbster937.originblacklist.base.Command.CommandContext;
import org.bukkit.command.CommandSender;
import org.bukkit.command.CommandExecutor;
public class CommandBukkit implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) {
Command.handle(new CommandContext() {
public String getName() { return sender.getName(); }
public void reply(String msg) { sender.sendMessage(msg); }
public boolean hasPermission(String permission) {
return sender.hasPermission(permission);
}
public String[] getArgs() {
return args;
}
});
return true;
}
}

View File

@@ -1,53 +0,0 @@
package dev.colbster937.originblacklist.bukkit;
import dev.colbster937.originblacklist.base.Base;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.event.EaglercraftMOTDEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.Plugin;
public class OriginBlacklistBukkit extends JavaPlugin implements Listener {
@Override
public void onEnable() {
Plugin plugin = getServer().getPluginManager().getPlugin("EaglercraftXServer");
if (plugin != null) {
String version = plugin.getDescription().getVersion();
if (!Base.checkVer(version, Base.apiVer)) {
getLogger().severe("EaglerXServer " + Base.apiVer + " is required!");
throw new RuntimeException("Incompatible API version");
}
} else {
throw new RuntimeException("Missing EaglerXServer");
}
Base.setLogger(new Base.LoggerAdapter() {
@Override public void info(String msg) { getLogger().info(msg); }
@Override public void warn(String msg) { getLogger().warning(msg); }
@Override public void error(String msg) { getLogger().severe(msg); }
});
Base.setApi(EaglerXServerAPI.instance());
Base.reloadConfig();
Base.init();
getCommand("originblacklist").setExecutor(new CommandBukkit());
getServer().getPluginManager().registerEvents(this, this);
getLogger().info("Loaded Bukkit plugin");
}
@EventHandler
public void onLogin(EaglercraftLoginEvent event) {
Base.handleConnection(event);
}
@EventHandler
public void onMOTD(EaglercraftMOTDEvent event) {
Base.handleMOTD(event);
}
}

View File

@@ -1,26 +0,0 @@
package dev.colbster937.originblacklist.bungee;
import dev.colbster937.originblacklist.base.Command;
import dev.colbster937.originblacklist.base.Command.CommandContext;
import net.md_5.bungee.api.CommandSender;
public class CommandBungee extends net.md_5.bungee.api.plugin.Command {
public CommandBungee() {
super("originblacklist", "originblacklist.use");
}
@Override
public void execute(CommandSender sender, String[] args) {
Command.handle(new CommandContext() {
public String getName() { return sender.getName(); }
public void reply(String msg) { sender.sendMessage(msg); }
public boolean hasPermission(String permission) {
return sender.hasPermission(permission);
}
public String[] getArgs() {
return args;
}
});
}
}

View File

@@ -1,52 +0,0 @@
package dev.colbster937.originblacklist.bungee;
import dev.colbster937.originblacklist.base.Base;
import net.lax1dude.eaglercraft.backend.server.api.bungee.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bungee.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.bungee.event.EaglercraftMOTDEvent;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
public class OriginBlacklistBungee extends Plugin implements Listener {
@Override
public void onEnable() {
Plugin plugin = getProxy().getPluginManager().getPlugin("EaglercraftXServer");
if (plugin != null) {
String version = plugin.getDescription().getVersion();
if (!Base.checkVer(version, Base.apiVer)) {
getLogger().severe("EaglerXServer " + Base.apiVer + " is required!");
throw new RuntimeException("Incompatible API version");
}
} else {
throw new RuntimeException("Missing EaglerXServer");
}
Base.setLogger(new Base.LoggerAdapter() {
@Override public void info(String msg) { getLogger().info(msg); }
@Override public void warn(String msg) { getLogger().warning(msg); }
@Override public void error(String msg) { getLogger().severe(msg); }
});
Base.setApi(EaglerXServerAPI.instance());
Base.reloadConfig();
Base.init();
getProxy().getPluginManager().registerCommand(this, new CommandBungee());
getProxy().getPluginManager().registerListener(this, this);
getLogger().info("Loaded Bungee plugin");
}
@EventHandler
public void onLogin(EaglercraftLoginEvent event) {
Base.handleConnection(event);
}
@EventHandler
public void onMOTD(EaglercraftMOTDEvent event) {
Base.handleMOTD(event);
}
}

View File

@@ -1,34 +0,0 @@
package dev.colbster937.originblacklist.velocity;
import com.velocitypowered.api.command.SimpleCommand;
import dev.colbster937.originblacklist.base.Command.CommandContext;
import net.kyori.adventure.text.minimessage.MiniMessage;
import com.velocitypowered.api.command.CommandSource;
public class CommandVelocity implements SimpleCommand {
@Override
public void execute(Invocation invocation) {
CommandSource source = invocation.source();
dev.colbster937.originblacklist.base.Command.handle(new CommandContext() {
@Override
public String getName() {
return source.toString();
}
@Override
public void reply(String msg) {
source.sendMessage(MiniMessage.miniMessage().deserialize(msg));
}
@Override
public boolean hasPermission(String permission) {
return source.hasPermission(permission);
}
public String[] getArgs() {
return invocation.arguments();
}
});
}
}

View File

@@ -1,55 +0,0 @@
package dev.colbster937.originblacklist.velocity;
import com.google.inject.Inject;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.proxy.ProxyServer;
import dev.colbster937.originblacklist.base.Base;
import net.lax1dude.eaglercraft.backend.server.api.velocity.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.velocity.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.velocity.event.EaglercraftMOTDEvent;
import org.slf4j.Logger;
public class OriginBlacklistVelocity {
private final ProxyServer proxy;
private final Base.LoggerAdapter logger;
@Inject
public OriginBlacklistVelocity(ProxyServer proxy1, Logger logger1) {
this.proxy = proxy1;
this.logger = new Base.LoggerAdapter() {
@Override public void info(String msg) { logger1.info(msg); }
@Override public void warn(String msg) { logger1.warn(msg); }
@Override public void error(String msg) { logger1.error(msg); }
};
Base.setLogger(this.logger);
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
proxy.getPluginManager().getPlugin("eaglerxserver").ifPresentOrElse(plugin -> {
if (!Base.checkVer(plugin.getDescription().getVersion().orElse("1.0.0"), Base.apiVer)) {
logger.error("EaglerXServer " + Base.apiVer + " is required!");
throw new RuntimeException("Incompatible api version");
}
}, () -> {
throw new RuntimeException("Missing EaglerXServer");
});
Base.setApi(EaglerXServerAPI.instance());
Base.reloadConfig();
Base.init();
proxy.getCommandManager().register("originblacklist", new CommandVelocity());
logger.info("Loaded Velocity plugin");
}
@Subscribe
public void onLogin(EaglercraftLoginEvent event) {
Base.handleConnection(event);
}
@Subscribe
public void onMOTD(EaglercraftMOTDEvent event) {
Base.handleMOTD(event);
}
}

View File

@@ -0,0 +1,511 @@
package xyz.webmc.originblacklist.base;
import xyz.webmc.originblacklist.base.config.OriginBlacklistConfig;
import xyz.webmc.originblacklist.base.enums.EnumBlacklistType;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.enums.EnumLogLevel;
import xyz.webmc.originblacklist.base.events.OriginBlacklistLoginEvent;
import xyz.webmc.originblacklist.base.events.OriginBlacklistMOTDEvent;
import xyz.webmc.originblacklist.base.http.OriginBlacklistRequestHandler;
import xyz.webmc.originblacklist.base.util.BuildInfo;
import xyz.webmc.originblacklist.base.util.IOriginBlacklistPlugin;
import xyz.webmc.originblacklist.base.util.OPlayer;
import xyz.webmc.originblacklist.base.util.UpdateChecker;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;
import de.marhali.json5.Json5;
import de.marhali.json5.Json5Array;
import de.marhali.json5.Json5Element;
import de.marhali.json5.Json5Object;
import inet.ipaddr.AddressStringException;
import inet.ipaddr.IPAddressString;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.query.IMOTDConnection;
import org.semver4j.Semver;
@SuppressWarnings({ "rawtypes" })
public final class OriginBlacklist {
private static final String COMMIT_L = BuildInfo.get("git_cm_hash");
private static final String COMMIT_S = COMMIT_L.substring(0, 8);
public static final Semver REQUIRED_API_VER = new Semver("1.0.2");
public static final String GENERIC_STR = "GENERIC";
public static final String UNKNOWN_STR = "UNKNOWN";
public static final String CENSORED_STR = "CENSORED";
public static final String PLUGIN_REPO = "WebMCDevelopment/originblacklist";
private final IOriginBlacklistPlugin plugin;
private final OriginBlacklistConfig config;
private final Json5 json5;
private String updateURL;
private Path jarFile;
public OriginBlacklist(final IOriginBlacklistPlugin plugin) {
this.plugin = plugin;
this.config = new OriginBlacklistConfig(this);
this.json5 = Json5.builder(builder -> builder.prettyPrinting().indentFactor(0).build());
}
public final void init() {
this.jarFile = this.plugin.getPluginJarPath();
this.plugin.scheduleRepeat(() -> {
this.checkForUpdates();
}, this.config.getInteger("update_checker.check_timer"), TimeUnit.SECONDS);
if (this.isBlacklistAPIEnabled()) {
OriginBlacklistRequestHandler.register(this);
}
this.plugin.log(EnumLogLevel.INFO, "Initialized Plugin");
this.plugin.log(EnumLogLevel.DEBUG, "Commit " + COMMIT_L);
}
public final void shutdown() {
this.plugin.log(EnumLogLevel.INFO, "Shutting down...");
if (this.isBlacklistAPIEnabled()) {
OriginBlacklistRequestHandler.unRegister(this);
}
this.plugin.shutdown();
}
public final void handleReload() {
try {
if (this.isBlacklistAPIEnabled()) {
OriginBlacklistRequestHandler.register(this);
} else {
OriginBlacklistRequestHandler.unRegister(this);
}
} catch (final Throwable t) {
}
}
public final void handleLogin(final OriginBlacklistLoginEvent event) {
final OPlayer player = event.getPlayer();
final EnumBlacklistType blacklisted = this.testBlacklist(player);
if (blacklisted != EnumBlacklistType.NONE) {
final String blacklisted_value;
if (blacklisted == EnumBlacklistType.ORIGIN) {
blacklisted_value = player.getOrigin();
} else if (blacklisted == EnumBlacklistType.BRAND) {
blacklisted_value = player.getBrand();
} else if (blacklisted == EnumBlacklistType.NAME) {
blacklisted_value = player.getName();
} else if (blacklisted == EnumBlacklistType.ADDR) {
blacklisted_value = player.getAddr();
} else {
blacklisted_value = UNKNOWN_STR;
}
this.plugin.kickPlayer(this.getBlacklistedComponent("kick", blacklisted.getArrayString(),
blacklisted.getAltString(), blacklisted.getString(), "not allowed", "not allowed on the server",
blacklisted_value, blacklisted.getActionString()), event);
this.sendWebhooks(event, blacklisted);
final String name = player.getName();
if (isNonNull(name)) {
this.plugin.log(EnumLogLevel.INFO, "Prevented blacklisted player " + name + " from joining.");
this.updateLogFile(event, blacklisted);
}
}
}
public final void handleMOTD(final OriginBlacklistMOTDEvent event) {
final OPlayer player = event.getPlayer();
final EnumBlacklistType blacklisted = this.testBlacklist(player);
if (blacklisted != EnumBlacklistType.NONE) {
final String blacklisted_value;
if (blacklisted == EnumBlacklistType.ORIGIN) {
blacklisted_value = player.getOrigin();
} else if (blacklisted == EnumBlacklistType.ADDR) {
blacklisted_value = player.getAddr();
} else {
blacklisted_value = UNKNOWN_STR;
}
this.plugin.setMOTD(this.getBlacklistedComponent("motd", blacklisted.getArrayString(), blacklisted.getAltString(),
blacklisted.getString(), "blacklisted", "blacklisted from the server", blacklisted_value,
blacklisted.getActionString()), event);
}
}
public final boolean isDebugEnabled() {
return this.config.getBoolean("debug");
}
public final boolean isMetricsEnabled() {
return this.config.getBoolean("bStats");
}
public final boolean isLogFileEnabled() {
return this.config.getBoolean("logFile");
}
public final boolean isBlacklistAPIEnabled() {
return this.config.getBoolean("blacklist_http_api");
}
public final OriginBlacklistConfig getConfig() {
return this.config;
}
public final void setEaglerMOTD(final Component comp, final OriginBlacklistMOTDEvent event) {
final IMOTDConnection conn = event.getEaglerEvent().getMOTDConnection();
final List<String> lst = new ArrayList<>();
for (String ln : getComponentString(comp).split("\n")) {
lst.add(ln);
}
conn.setServerMOTD(lst);
conn.setPlayerTotal(0);
conn.setPlayerUnlimited();
conn.setPlayerList(List.of());
conn.setServerIcon(this.config.getIconBytes());
conn.sendToUser();
conn.disconnect();
}
public final void checkForUpdates(final Runnable action1, final Runnable action2) {
if (this.config.getBoolean("update_checker.enabled")) {
this.plugin.runAsync(() -> {
this.updateURL = UpdateChecker.checkForUpdates(PLUGIN_REPO, this.plugin.getPluginVersion(),
this.config.getBoolean("update_checker.allow_snapshots"));
if (isNonNull((this.updateURL))) {
action1.run();
return;
}
action2.run();
});
} else {
action2.run();
}
}
public final void updatePlugin(final Runnable action1, final Runnable action2) {
try {
final URL url = new URL(this.updateURL);
final Path jar = this.jarFile;
final Path bak = jar.resolveSibling(jar.getFileName().toString() + ".bak");
final Path upd = jar
.resolveSibling(Paths.get(URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8)).getFileName());
try {
Files.copy(jar, bak, StandardCopyOption.REPLACE_EXISTING);
} catch (final Throwable t) {
t.printStackTrace();
}
try {
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setRequestProperty("User-Agent", OriginBlacklist.getUserAgent());
conn.connect();
try (final InputStream in = conn.getInputStream()) {
Files.copy(in, upd, StandardCopyOption.REPLACE_EXISTING);
} finally {
conn.disconnect();
}
Files.delete(jar);
Files.delete(bak);
this.jarFile = upd;
action1.run();
return;
} catch (final Throwable t) {
t.printStackTrace();
Files.move(bak, jar, StandardCopyOption.REPLACE_EXISTING);
}
} catch (final Throwable t) {
t.printStackTrace();
}
action2.run();
}
public final void updatePlugin() {
this.updatePlugin(() -> {
}, () -> {
});
}
public final EnumBlacklistType testBlacklist(final OPlayer player) {
final String name = player.getName();
final String addr = player.getAddr();
final String origin = player.getOrigin();
final String brand = player.getBrand();
final boolean whitelist = this.config.getBoolean("blacklist_to_whitelist");
EnumBlacklistType type = EnumBlacklistType.NONE;
if (isNonNull(origin)) {
if (whitelist && !type.isBlacklisted())
type = EnumBlacklistType.ORIGIN;
for (final Json5Element element : this.config.getArray("blacklist.origins").getAsJson5Array()) {
if (origin.matches(element.getAsString())) {
if (whitelist)
type = EnumBlacklistType.NONE;
else if (!type.isBlacklisted())
type = EnumBlacklistType.ORIGIN;
break;
}
}
} else if (this.config.getBoolean("block_undefined_origin")) {
return whitelist ? EnumBlacklistType.NONE : EnumBlacklistType.ORIGIN;
}
if (isNonNull(brand)) {
if (whitelist && !type.isBlacklisted())
type = EnumBlacklistType.BRAND;
for (final Json5Element element : this.config.getArray("blacklist.brands")) {
if (brand.matches(element.getAsString())) {
if (whitelist)
type = EnumBlacklistType.NONE;
else if (!type.isBlacklisted())
type = EnumBlacklistType.BRAND;
break;
}
}
}
if (isNonNull(name)) {
if (whitelist && !type.isBlacklisted())
type = EnumBlacklistType.NAME;
for (final Json5Element element : this.config.getArray("blacklist.player_names")) {
if (name.matches(element.getAsString())) {
if (whitelist)
type = EnumBlacklistType.NONE;
else if (!type.isBlacklisted())
type = EnumBlacklistType.NAME;
break;
}
}
}
if (isNonNull(addr)) {
if (whitelist && !type.isBlacklisted())
type = EnumBlacklistType.ADDR;
for (final Json5Element element : this.config.getArray("blacklist.ip_addresses")) {
try {
if ((new IPAddressString(element.getAsString()).toAddress())
.contains((new IPAddressString(addr)).toAddress())) {
if (whitelist)
type = EnumBlacklistType.NONE;
else if (!type.isBlacklisted())
type = EnumBlacklistType.ADDR;
break;
}
} catch (final AddressStringException exception) {
if (this.isDebugEnabled())
exception.printStackTrace();
}
}
}
return type;
}
public final String getBlacklistShare() {
try {
final Json5Object obj = new Json5Object();
obj.addProperty("plugin_version", this.plugin.getPluginVersion().getVersion());
obj.addProperty("git_commit", COMMIT_L);
obj.addProperty("blacklist_to_whitelist", this.config.getBoolean("blacklist_to_whitelist"));
obj.addProperty("block_undefined_origin", this.config.getBoolean("block_undefined_origin"));
final Json5Object bObj = new Json5Object();
final String[] types = new String[] { "origins", "brands", "player_names", "ip_addresses" };
for (final String type : types) {
bObj.add(type, this.config.getArray("blacklist." + type));
}
obj.add("blacklist", bObj);
return this.json5.serialize(obj);
} catch (final Throwable t) {
return null;
}
}
public final String getDataDir() {
return "plugins/" + plugin.getPluginId();
}
public final IEaglerXServerAPI getEaglerAPI() {
return this.plugin.getEaglerAPI();
}
private final Component getBlacklistedComponent(final String type, final String id, final String blockType,
final String blockTypeAlt, final String notAllowed, final String notAllowedAlt, final String blockValue,
final String action) {
final Json5Array arr = this.config.getArray("messages." + type);
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.size(); i++) {
if (i > 0)
sb.append("\n");
sb.append(arr.get(i).getAsString());
}
final String str = sb.toString()
.replaceAll("%action%", this.config.getString("messages.actions." + action))
.replaceAll("%block_type%", blockType)
.replaceAll("%block_type%", blockType)
.replaceAll("%not_allowed%", notAllowed)
.replaceAll("%not_allowed_alt%", notAllowedAlt)
.replaceAll("%blocked_value%", blockValue);
return MiniMessage.miniMessage().deserialize(str);
}
private final void sendWebhooks(final OriginBlacklistLoginEvent event, final EnumBlacklistType type) {
if (this.config.getBoolean("discord.enabled")) {
final OPlayer player = event.getPlayer();
final EnumConnectionType connType = event.getConnectionType();
/* final String userAgent;
if (connType == EnumConnectionType.EAGLER) {
final IEaglerLoginConnection loginConn = event.getEaglerEvent().getLoginConnection();
userAgent = loginConn.getWebSocketHeader(EnumWebSocketHeader.HEADER_USER_AGENT);
} else {
userAgent = UNKNOWN_STR;
} */
final byte[] payload = String.format(
"""
{
"content": "Blocked a blacklisted %s from joining",
"embeds": [
{
"title": "-------- Player Information --------",
"description": "**→ Name:** %s\\n**→ Origin:** %s\\n**→ Brand:** %s\\n**→ IP Address:** %s\\n**→ Protocol Version:** %s\\n**→ Host:** %s\\n**→ Rewind:** %s\\n**→ Player Type:** %s",
"color": 15801922,
"fields": [],
"footer": {
"text": "%s v%s",
"icon_url": "https://raw.githubusercontent.com/%s/refs/heads/main/img/icon.png"
}
}
],
"components": [
{
"type": 1,
"components": [
{
"type": 2,
"style": 5,
"label": "Get the Plugin",
"url": "https://github.com/%s",
"emoji": {
"name": "🌐"
}
}
]
}
]
}
""",
type.getAltString(),
player.getName().replaceAll("_", "\\_"),
player.getOrigin(),
player.getBrand(),
this.config.getBoolean("discord.send_ips") ? player.getAddr() : CENSORED_STR,
player.getPVN(),
player.getVHost(),
// userAgent,
player.isRewind() ? "YES" : "NO",
connType.toString(),
BuildInfo.get("plugin_name"),
this.plugin.getPluginVersion() + "" + COMMIT_S,
PLUGIN_REPO,
PLUGIN_REPO).getBytes();
final Json5Array arr = this.config.get("discord.webhook_urls").getAsJson5Array();
for (final Json5Element element : arr) {
this.plugin.runAsync(() -> {
try {
final URL url = new URL(element.getAsString());
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
final OutputStream os = conn.getOutputStream();
os.write(payload);
os.close();
final int code = conn.getResponseCode();
if (code < 200 || code >= 300) {
this.plugin.log(EnumLogLevel.WARN, "Webhook failed (HTTP " + code + ")");
}
conn.disconnect();
} catch (final Throwable t) {
t.printStackTrace();
}
});
}
}
}
private final void checkForUpdates() {
this.checkForUpdates(() -> {
if (!this.config.getBoolean("update_checker.auto_update")) {
this.plugin.log(EnumLogLevel.INFO, "An update is available! Download it at " + this.updateURL);
} else {
this.updatePlugin();
}
}, () -> {
});
}
private final void updateLogFile(final OriginBlacklistLoginEvent event, final EnumBlacklistType type) {
if (this.isLogFileEnabled()) {
final OPlayer player = event.getPlayer();
final String txt = Instant.now() + " - [player=" + player.getName() + "," + "blacklist_reason=" + type.toString() + "]";
final Path dir = Paths.get(this.getDataDir());
try {
Files.createDirectories(dir);
Files.writeString(
dir.resolve("blacklist.log"),
txt + "\n",
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.APPEND
);
} catch (final Throwable t) {
t.printStackTrace();
}
}
}
public static final String getComponentString(final Component comp) {
return LegacyComponentSerializer.legacySection().serialize(comp);
}
public static final String getLegacyFromMiniMessage(final String str) {
return getComponentString(MiniMessage.miniMessage().deserialize(str));
}
public static final String getPNGBase64FromBytes(final byte[] bytes) {
return "data:image/png;base64," + Base64.getEncoder().encodeToString(bytes);
}
public static final String getUserAgent() {
return BuildInfo.get("plugin_name") + "/" + BuildInfo.get("plugin_vers") + "+" + BuildInfo.get("git_cm_hash");
}
public static final boolean isNonNull(final String str) {
return str != null && !str.isEmpty() && !str.isBlank() && !str.equals("null");
}
public static final class BSTATS {
public static final int VELOCITY = 29033;
public static final int BUNGEE = 29034;
public static final int BUKKIT = 29035;
}
}

View File

@@ -0,0 +1,15 @@
package xyz.webmc.originblacklist.base.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
public interface CommandContext {
public OriginBlacklist getPlugin();
public String getPlayerName();
public void reply(final String message);
public boolean hasPermission(final String permission);
public String[] getArgs();
}

View File

@@ -0,0 +1,13 @@
package xyz.webmc.originblacklist.base.command;
import java.util.List;
public interface ICommand {
public static final String NO_PERMISSION = "<red>You don't have permission to use this command.</red>";
public boolean execute(final CommandContext ctx);
public List<String> suggest(final CommandContext ctx);
public void usage(final CommandContext ctx);
}

View File

@@ -0,0 +1,162 @@
package xyz.webmc.originblacklist.base.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.config.OriginBlacklistConfig;
import xyz.webmc.originblacklist.base.enums.EnumBlacklistType;
import xyz.webmc.originblacklist.base.util.OPlayer;
import java.util.List;
import de.marhali.json5.Json5Array;
import de.marhali.json5.Json5Element;
import de.marhali.json5.Json5Primitive;
public class OriginBlacklistCommand implements ICommand {
private final OriginBlacklist plugin;
public OriginBlacklistCommand(OriginBlacklist plugin) {
this.plugin = plugin;
}
@Override
public boolean execute(final CommandContext ctx) {
final String[] args = ctx.getArgs();
if (ctx.hasPermission("originblacklist.command")) {
if (args.length > 0) {
final OriginBlacklistConfig config = this.plugin.getConfig();
final String command = args[0];
final String argA = args.length > 1 ? args[1] : null;
;
final String argB = args.length > 2 ? args[2] : null;
final boolean add = "add".equalsIgnoreCase(command);
final boolean remove = "remove".equalsIgnoreCase(command);
if ("reload".equalsIgnoreCase(command)) {
if (ctx.hasPermission("originblacklist.command.reload")) {
config.reloadConfig();
this.plugin.handleReload();
ctx.reply("<green>Configuration Reloaded</green>");
} else {
ctx.reply(NO_PERMISSION);
}
} else if ("update".equalsIgnoreCase(command)) {
if (ctx.hasPermission("originblacklist.command.update")) {
ctx.reply("<aqua>Checking for updates...</aqua>");
this.plugin.checkForUpdates(() -> {
ctx.reply("<yellow>Updating plugin...</yellow>");
this.plugin.updatePlugin(() -> {
ctx.reply("<green>Successfully updated plugin.</green>");
}, () -> {
ctx.reply("<red>Failed to update plugin.</red>");
});
}, () -> {
ctx.reply("<green>Plugin is up to date.</green>");
});
} else {
ctx.reply(NO_PERMISSION);
}
} else if ((add || remove) && OriginBlacklist.isNonNull(argB)) {
if ((add && ctx.hasPermission("originblacklist.command.add"))
|| (remove && ctx.hasPermission("originblacklist.command.add"))) {
final String arrName;
if ("origin".equalsIgnoreCase(argA)) {
arrName = "origins";
} else if ("brand".equalsIgnoreCase(argA)) {
arrName = "brands";
} else if ("name".equalsIgnoreCase(argA)) {
arrName = "player_names";
} else if ("ip".equalsIgnoreCase(argA)) {
arrName = "ip_addresses";
} else {
arrName = null;
}
if (OriginBlacklist.isNonNull(arrName)) {
final String arrPath = "blacklist." + arrName;
final Json5Array arr = config.getArray(arrPath);
if (add) {
if (!arr.contains(Json5Primitive.fromString(argB))) {
arr.add(argB);
config.set(arrPath, arr);
ctx.reply("<green>Added " + argB + " to the " + argA + " blacklist</green>");
} else {
ctx.reply("<red>" + argB + " is already on the " + argA + " blacklist</red>");
}
} else if (remove) {
if (arr.contains(Json5Primitive.fromString(argB))) {
arr.remove(Json5Primitive.fromString(argB));
config.set(arrPath, arr);
ctx.reply("<green>Removed " + argB + " from the " + argA + " blacklist</green>");
} else {
ctx.reply("<red>" + argB + " not on the " + argA + " blacklist</red>");
}
}
} else {
this.usage(ctx);
}
} else {
ctx.reply(NO_PERMISSION);
}
} else if ("test".equalsIgnoreCase(command) && OriginBlacklist.isNonNull(argA)) {
if (ctx.hasPermission("originblacklist.command.test")) {
if (this.isBlacklisted(argA)) {
ctx.reply("<green>" + argA + " is on the blacklist.</green>");
} else {
ctx.reply("<red>" + argA + " is not on the blacklist.</red>");
}
} else {
ctx.reply(NO_PERMISSION);
}
} else if ("list".equalsIgnoreCase(command)) {
if (ctx.hasPermission("originblacklist.command.list")) {
ctx.reply("<aqua>Blacklist:</aqua>");
ctx.reply("<gold> - Origins:</gold>");
for (final Json5Element element : config.getArray("blacklist.origins")) {
ctx.reply("<gray> - " + element.getAsString() + "</gray>");
}
ctx.reply("<gold> - Brands:</gold>");
for (final Json5Element element : config.getArray("blacklist.brands")) {
ctx.reply("<gray> - " + element.getAsString() + "</gray>");
}
ctx.reply("<gold> - Players:</gold>");
for (final Json5Element element : config.getArray("blacklist.player_names")) {
ctx.reply("<gray> - " + element.getAsString() + "</gray>");
}
ctx.reply("<gold> - IPs:</gold>");
for (final Json5Element element : config.getArray("blacklist.ip_addresses")) {
ctx.reply("<gray> - " + element.getAsString() + "</gray>");
}
} else {
ctx.reply(NO_PERMISSION);
}
} else {
this.usage(ctx);
}
} else {
this.usage(ctx);
}
} else {
ctx.reply("");
}
return true;
}
@Override
public final List<String> suggest(final CommandContext ctx) {
return List.of();
}
@Override
public final void usage(CommandContext ctx) {
ctx.reply("<aqua>Commands:</aqua>");
ctx.reply("<gray> - /originblacklist reload</gray>");
ctx.reply("<gray> - /originblacklist update</gray>");
ctx.reply("<gray> - /originblacklist add <origin/brand/name/ip> <arg></gray>");
ctx.reply("<gray> - /originblacklist remove <origin/brand/name/ip> <arg></gray>");
ctx.reply("<gray> - /originblacklist test <arg></gray>");
ctx.reply("<gray> - /originblacklist list</gray>");
}
private final boolean isBlacklisted(final String str) {
final OPlayer player = new OPlayer(null, str, null, str, str, null, -1);
return this.plugin.testBlacklist(player) != EnumBlacklistType.NONE;
}
}

View File

@@ -0,0 +1,497 @@
package xyz.webmc.originblacklist.base.config;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import de.marhali.json5.Json5;
import de.marhali.json5.Json5Array;
import de.marhali.json5.Json5Element;
import de.marhali.json5.Json5Object;
import de.marhali.json5.Json5Primitive;
public final class OriginBlacklistConfig {
private static final Json5Object DEFAULT_CONFIG = getDefaultConfig();
private final Json5 json5;
private final File file;
private final Path filePath;
private final File iconFile;
private final Path iconPath;
private Json5Object config;
private byte[] icon;
private String icon64;
public OriginBlacklistConfig(final OriginBlacklist plugin) {
this.json5 = Json5.builder(builder -> builder
.quoteless()
.quoteSingle()
.parseComments()
.writeComments()
.prettyPrinting()
.build());
this.file = new File(plugin.getDataDir() + "/config.json5");
this.filePath = file.toPath();
this.iconFile = new File(plugin.getDataDir() + "/blacklisted.png");
this.iconPath = iconFile.toPath();
this.loadConfig();
}
private final void loadConfig() {
try {
this.reloadConfigUnsafe();
this.reloadIconImage();
} catch (final IOException exception) {
throw new RuntimeException("Failed to load config.", exception);
}
}
public final void reloadConfig() {
try {
this.reloadConfigUnsafe();
this.reloadIconImage();
} catch (final IOException exception) {
exception.printStackTrace();
}
}
private final void reloadConfigUnsafe() throws IOException {
if (this.file.exists()) {
String text = Files.readString(this.file.toPath(), StandardCharsets.UTF_8);
Json5Element parsed = this.json5.parse(text);
if (parsed instanceof Json5Object) {
this.config = (Json5Object) parsed;
merge(this.config, DEFAULT_CONFIG);
} else {
throw new IOException("Config must be an object!");
}
} else {
this.config = DEFAULT_CONFIG;
}
this.saveConfig();
}
private final void reloadIconImage() {
try {
if (!this.iconFile.exists()) {
this.iconFile.getParentFile().mkdirs();
final InputStream in = OriginBlacklist.class.getResourceAsStream("/blacklisted.png");
Files.copy(in, iconPath, StandardCopyOption.REPLACE_EXISTING);
in.close();
}
final BufferedImage img = ImageIO.read(iconFile);
if (img.getWidth() == 64 && img.getHeight() == 64) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
this.icon64 = OriginBlacklist.getPNGBase64FromBytes(baos.toByteArray());
final byte[] bytes = new byte[64 * 64 * 4];
for (int y = 0; y < 64; y++) {
for (int x = 0; x < 64; x++) {
int pixel = img.getRGB(x, y);
int i = (y * 64 + x) * 4;
bytes[i] = (byte) ((pixel >> 16) & 0xFF);
bytes[i + 1] = (byte) ((pixel >> 8) & 0xFF);
bytes[i + 2] = (byte) (pixel & 0xFF);
bytes[i + 3] = (byte) ((pixel >> 24) & 0xFF);
}
this.icon = bytes;
}
} else {
throw new IOException("Icon must be 64x64!");
}
} catch (final IOException exception) {
exception.printStackTrace();
}
}
public final void saveConfig() {
try {
this.file.getParentFile().mkdirs();
Files.write(this.filePath, this.json5.serialize(this.config).getBytes(StandardCharsets.UTF_8));
} catch (final IOException exception) {
exception.printStackTrace();
}
}
public final Json5Element get(final String key) {
Json5Element element = null;
if (this.config != null && OriginBlacklist.isNonNull(key)) {
element = this.config;
final String[] parts = splitPath(key);
for (final String part : parts) {
if (element instanceof Json5Object) {
final Json5Object obj = (Json5Object) element;
if (obj.has(part)) {
element = obj.get(part);
} else {
element = null;
}
} else {
element = null;
}
if (element == null) {
break;
}
}
}
return element;
}
public final boolean set(final String key, final Json5Element value) {
boolean ret = false;
if (this.config != null && value != null) {
final String[] parts = splitPath(key);
if (parts.length > 0) {
Json5Object obj = this.config;
for (int i = 0; i < parts.length - 1; i++) {
final String part = parts[i];
final Json5Element cur = obj.has(part) ? obj.get(part) : null;
if (cur instanceof Json5Object next) {
obj = next;
} else {
final Json5Object next = new Json5Object();
obj.add(part, next);
obj = next;
}
}
obj.add(parts[parts.length - 1], value.deepCopy());
this.saveConfig();
ret = true;
}
}
return ret;
}
public final boolean remove(final String key) {
boolean ret = false;
if (this.config != null) {
final String[] parts = splitPath(key);
if (parts.length > 0) {
Json5Object obj = this.config;
Json5Element element = obj;
for (int i = 0; i < parts.length - 1; i++) {
if (element instanceof Json5Object cur && cur.has(parts[i])) {
element = cur.get(parts[i]);
if (element instanceof Json5Object) {
obj = (Json5Object) element;
} else {
element = null;
}
} else {
element = null;
}
if (element == null) {
break;
}
}
if (element != null && obj.has(parts[parts.length - 1])) {
obj.remove(parts[parts.length - 1]);
this.saveConfig();
ret = true;
}
}
}
return ret;
}
public final String getString(final String key) {
return this.get(key).getAsString();
}
public final boolean getBoolean(final String key) {
return this.get(key).getAsBoolean();
}
public final int getInteger(final String key) {
return this.get(key).getAsInt();
}
public final Json5Array getArray(final String key) {
return this.get(key).getAsJson5Array();
}
public final Json5Object getObject(final String key) {
return this.get(key).getAsJson5Object();
}
public final byte[] getIconBytes() {
return this.icon;
}
public final String getIconBase64URI() {
return this.icon64;
}
private static final Json5Object getDefaultConfig() {
final Json5Object obj = new Json5Object();
addJSONObj(obj, "debug", Json5Primitive.fromBoolean(false), null);
final Json5Object mObj = new Json5Object();
final Json5Array kick = new Json5Array();
kick.add("<red>This %block_type% is %not_allowed_alt%!</red>");
kick.add("<dark_gray>»</dark_gray> <gray>%blocked_value%</gray> <dark_gray>«</dark_gray>");
kick.add("");
kick.add("%action%");
kick.add("");
kick.add("<aqua>Think this is a mistake? Join our discord:</aqua>");
kick.add("<blue>discord.gg/changethisintheconfig</blue>");
addJSONObj(mObj, "kick", kick, null);
final Json5Array motd = new Json5Array();
motd.add("<red>This %block_type% is %not_allowed%!</red>");
motd.add("<dark_gray>»</dark_gray> <gray>%blocked_value%</gray>");
addJSONObj(mObj, "motd", motd, null);
final Json5Object actions = new Json5Object();
actions.add("generic", Json5Primitive.fromString("<gold>Please switch to a different %block_type%.</gold>"));
actions.add("player_name", Json5Primitive.fromString("<gold>Please change your %block_type%.</gold>"));
actions.add("ip_address", Json5Primitive.fromString("<gold>Please contact staff for assistance.</gold>"));
addJSONObj(mObj, "actions", actions, null);
addJSONObj(obj, "messages", mObj, null);
final Json5Object bObj = new Json5Object();
final Json5Array origins = new Json5Array();
origins.add(".*eaglerhackedclients\\.vercel\\.app.*");
origins.add(".*eaglerhacks\\.github\\.io.*");
origins.add(".*mcproject\\.vercel\\.app.*");
origins.add(".*wurst-b2\\.vercel\\.app.*");
origins.add(".*flqmedev\\.github\\.io.*");
origins.add(".*wurst2\\.vercel\\.app.*");
origins.add(".*dhyeybg7\\.vercel\\.app.*");
origins.add(".*uec\\.vercel\\.app.*");
origins.add(".*valux-game\\.github\\.io.*");
origins.add(".*project516\\.dev.*");
addJSONObj(bObj, "origins", origins, null);
final Json5Array brands = new Json5Array();
brands.add(".*dragonx.*");
brands.add(".*piclient.*");
brands.add(".*justin.*");
brands.add(".*wurstx.*");
brands.add(".*moonlight.*");
addJSONObj(bObj, "brands", brands, null);
final Json5Array players = new Json5Array();
players.add("Admin");
addJSONObj(bObj, "player_names", players, null);
final Json5Array ips = new Json5Array();
ips.add("192.0.2.0/24");
addJSONObj(bObj, "ip_addresses", ips, null);
addJSONObj(obj, "blacklist", bObj, null);
final Json5Object dObj = new Json5Object();
addJSONObj(dObj, "enabled", Json5Primitive.fromBoolean(false), null);
addJSONObj(dObj, "webhook_urls", new Json5Array(), null);
addJSONObj(dObj, "send_ips", Json5Primitive.fromBoolean(true), null);
addJSONObj(obj, "discord", dObj, null);
final Json5Object uObj = new Json5Object();
addJSONObj(uObj, "enabled", Json5Primitive.fromBoolean(true), null);
addJSONObj(uObj, "allow_snapshots", Json5Primitive.fromBoolean(false), null);
addJSONObj(uObj, "check_timer", Json5Primitive.fromNumber(3600), null);
addJSONObj(uObj, "auto_update", Json5Primitive.fromBoolean(true), null);
addJSONObj(obj, "update_checker", uObj, null);
addJSONObj(obj, "blacklist_http_api", Json5Primitive.fromBoolean(false), null);
addJSONObj(obj, "blacklist_to_whitelist", Json5Primitive.fromBoolean(false), null);
addJSONObj(obj, "block_undefined_origin", Json5Primitive.fromBoolean(false), null);
addJSONObj(obj, "bStats", Json5Primitive.fromBoolean(true), null);
addJSONObj(obj, "logFile", Json5Primitive.fromBoolean(true), null);
addJSONObj(obj, "config_version", Json5Primitive.fromNumber(1), "DO NOT CHANGE");
return obj;
}
private static final boolean merge(final Json5Object aObj, final Json5Object bObj) {
final Json5Object ret = new Json5Object();
boolean changed = false;
for (final String key : bObj.keySet()) {
final Json5Element dv = bObj.get(key);
if (aObj.has(key)) {
final Json5Element v = aObj.get(key);
if (dv instanceof Json5Object) {
if (v instanceof Json5Object) {
final boolean c = merge((Json5Object) v, (Json5Object) dv);
ret.add(key, (Json5Object) v);
if (c) {
changed = true;
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else if (dv instanceof Json5Array) {
if (v instanceof Json5Array) {
final Json5Array vArr = (Json5Array) v;
final Json5Array dArr = (Json5Array) dv;
if (dArr.size() == 0) {
ret.add(key, vArr.deepCopy());
} else {
final Json5Element d0 = dArr.get(0);
if (d0 instanceof Json5Primitive && ((Json5Primitive) d0).isString()) {
final Json5Array out = new Json5Array();
for (final Json5Element e : vArr) {
if (e instanceof Json5Primitive && ((Json5Primitive) e).isString()) {
out.add(e.deepCopy());
}
}
if (out.size() > 0) {
if (out.size() != vArr.size()) {
changed = true;
}
ret.add(key, out);
} else {
ret.add(key, dArr.deepCopy());
changed = true;
}
} else {
boolean a = true;
for (final Json5Element e : vArr) {
if (e == null) {
a = false;
} else if (d0 instanceof Json5Object) {
if (!(e instanceof Json5Object)) {
a = false;
}
} else if (d0 instanceof Json5Array) {
if (!(e instanceof Json5Array)) {
a = false;
}
} else if (d0 instanceof Json5Primitive && e instanceof Json5Primitive) {
final Json5Primitive bp = (Json5Primitive) d0;
final Json5Primitive ap = (Json5Primitive) e;
if (bp.isBoolean()) {
if (!ap.isBoolean()) {
a = false;
}
} else if (bp.isNumber()) {
if (!ap.isNumber()) {
a = false;
}
} else if (bp.isString()) {
if (!ap.isString()) {
a = false;
}
}
} else {
a = false;
}
if (!a) {
break;
}
}
if (a) {
ret.add(key, vArr.deepCopy());
} else {
ret.add(key, dArr.deepCopy());
changed = true;
}
}
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else if (dv instanceof Json5Primitive) {
if (v instanceof Json5Primitive) {
final Json5Primitive dp = (Json5Primitive) dv;
final Json5Primitive vp = (Json5Primitive) v;
if (dp.isBoolean()) {
if (vp.isBoolean()) {
ret.add(key, vp.deepCopy());
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else if (dp.isNumber()) {
if (vp.isNumber()) {
ret.add(key, vp.deepCopy());
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else if (dp.isString()) {
if (vp.isString()) {
ret.add(key, vp.deepCopy());
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
} else {
ret.add(key, dv.deepCopy());
changed = true;
}
}
for (final String key : aObj.keySet()) {
if (!bObj.has(key)) {
ret.add(key, aObj.get(key).deepCopy());
}
}
for (final String key : aObj.keySet()) {
if (!bObj.has(key)) {
ret.add(key, aObj.get(key).deepCopy());
}
}
for (final String k : new ArrayList<>(aObj.keySet())) {
aObj.remove(k);
}
for (final String k : ret.keySet()) {
aObj.add(k, ret.get(k));
}
for (final String key : ret.keySet()) {
aObj.add(key, ret.get(key));
}
return changed;
}
private static final void addJSONObj(final Json5Object obj, final String key, final Json5Element value,
final String comment) {
if (OriginBlacklist.isNonNull(comment)) {
value.setComment(comment);
}
obj.add(key, value);
}
private static final String[] splitPath(final String key) {
final String[] ret;
if (OriginBlacklist.isNonNull(key)) {
ret = key.split("\\.");
} else {
ret = new String[0];
}
return ret;
}
}

View File

@@ -0,0 +1,43 @@
package xyz.webmc.originblacklist.base.enums;
import xyz.webmc.originblacklist.base.OriginBlacklist;
public enum EnumBlacklistType {
ORIGIN("origin", "website", "origins", null),
BRAND("brand", "client", "brands", null),
NAME("name", "username", "player_names", "player_name"),
ADDR("addr", "ip address", "ip_addresses", "ip_address"),
NONE(null, null, null, null);
private final String str;
private final String alt;
private final String arr;
private final String act;
private EnumBlacklistType(final String str, final String alt, final String arr, final String act) {
this.str = str;
this.alt = alt;
this.arr = arr;
this.act = OriginBlacklist.isNonNull(act) ? act : OriginBlacklist.GENERIC_STR.toLowerCase();
}
public final String getString() {
return this.str;
}
public final String getAltString() {
return this.alt;
}
public final String getArrayString() {
return this.arr;
}
public final String getActionString() {
return this.act;
}
public final boolean isBlacklisted() {
return this != NONE;
}
}

View File

@@ -0,0 +1,6 @@
package xyz.webmc.originblacklist.base.enums;
public enum EnumConnectionType {
JAVA,
EAGLER
}

View File

@@ -0,0 +1,8 @@
package xyz.webmc.originblacklist.base.enums;
public enum EnumLogLevel {
INFO,
WARN,
ERROR,
DEBUG
}

View File

@@ -0,0 +1,37 @@
package xyz.webmc.originblacklist.base.events;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.util.OPlayer;
import net.lax1dude.eaglercraft.backend.server.api.event.IBaseServerEvent;
@SuppressWarnings({ "rawtypes" })
public abstract class OriginBlacklistEvent {
private final EnumConnectionType connectionType;
private final IBaseServerEvent eaglerEvent;
private final Object javaEvent;
private final OPlayer player;
protected OriginBlacklistEvent(final IBaseServerEvent eaglerEvent, final Object javaEvent, final EnumConnectionType connectionType, final OPlayer player) {
this.eaglerEvent = eaglerEvent;
this.javaEvent = javaEvent;
this.connectionType = connectionType;
this.player = player;
}
protected IBaseServerEvent getEaglerEvent() {
return this.eaglerEvent;
}
public final Object getJavaEvent() {
return this.javaEvent;
}
public final EnumConnectionType getConnectionType() {
return this.connectionType;
}
public final OPlayer getPlayer() {
return this.player;
}
}

View File

@@ -0,0 +1,19 @@
package xyz.webmc.originblacklist.base.events;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.util.OPlayer;
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftLoginEvent;
@SuppressWarnings({ "rawtypes" })
public final class OriginBlacklistLoginEvent extends OriginBlacklistEvent {
public OriginBlacklistLoginEvent(final IEaglercraftLoginEvent eaglerEvent, final Object javaEvent,
final EnumConnectionType connectionType, final OPlayer player) {
super(eaglerEvent, javaEvent, connectionType, player);
}
@Override
public final IEaglercraftLoginEvent getEaglerEvent() {
return (IEaglercraftLoginEvent) super.getEaglerEvent();
}
}

View File

@@ -0,0 +1,19 @@
package xyz.webmc.originblacklist.base.events;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.util.OPlayer;
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftMOTDEvent;
@SuppressWarnings({ "rawtypes" })
public final class OriginBlacklistMOTDEvent extends OriginBlacklistEvent {
public OriginBlacklistMOTDEvent(final IEaglercraftMOTDEvent eaglerEvent, final Object javaEvent,
final EnumConnectionType connectionType, final OPlayer player) {
super(eaglerEvent, javaEvent, connectionType, player);
}
@Override
public final IEaglercraftMOTDEvent getEaglerEvent() {
return (IEaglercraftMOTDEvent) super.getEaglerEvent();
}
}

View File

@@ -0,0 +1,40 @@
package xyz.webmc.originblacklist.base.http;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import java.nio.charset.StandardCharsets;
import net.lax1dude.eaglercraft.backend.server.api.webserver.IRequestContext;
import net.lax1dude.eaglercraft.backend.server.api.webserver.IRequestHandler;
import net.lax1dude.eaglercraft.backend.server.api.webserver.RouteDesc;
public class OriginBlacklistRequestHandler implements IRequestHandler {
private static final RouteDesc route = RouteDesc.create("/originblacklist/v2/");
private final OriginBlacklist plugin;
public OriginBlacklistRequestHandler(final OriginBlacklist plugin) {
this.plugin = plugin;
}
@Override
public final void handleRequest(final IRequestContext ctx) {
final String path = ctx.getPath();
if (route.getPattern().equals(path)) {
final byte[] bytes = this.plugin.getBlacklistShare().getBytes(StandardCharsets.UTF_8);
ctx.addResponseHeader("Content-Type", "application/json; charset=utf-8");
ctx.setResponseCode(200);
ctx.setResponseBody(bytes);
} else {
ctx.getServer().get404Handler().handleRequest(ctx);
}
}
public static final void register(final OriginBlacklist plugin) {
plugin.getEaglerAPI().getWebServer().registerRoute(plugin, route, new OriginBlacklistRequestHandler(plugin));
}
public static final void unRegister(final OriginBlacklist plugin) {
plugin.getEaglerAPI().getWebServer().unregisterRoute(plugin, route);
}
}

View File

@@ -0,0 +1,20 @@
package xyz.webmc.originblacklist.base.util;
import java.io.InputStream;
import java.util.Properties;
public final class BuildInfo {
private static final Properties properties;
public static final String get(final String key) {
return properties.getProperty(key).trim();
}
static {
properties = new Properties();
try (final InputStream in = BuildInfo.class.getClassLoader().getResourceAsStream("build.properties")) {
properties.load(in);
} catch (final Throwable t) {
}
}
}

View File

@@ -0,0 +1,29 @@
package xyz.webmc.originblacklist.base.util;
public final class ChatFormat {
private static final String SYMBOL = "§";
public static final String BLACK = SYMBOL + "0";
public static final String DARK_BLUE = SYMBOL + "1";
public static final String DARK_GREEN = SYMBOL + "2";
public static final String CYAN = SYMBOL + "3";
public static final String DARK_RED = SYMBOL + "4";
public static final String DARK_PURPLE = SYMBOL + "5";
public static final String GOLD = SYMBOL + "6";
public static final String GRAY = SYMBOL + "7";
public static final String DARK_GRAY = SYMBOL + "8";
public static final String BLUE = SYMBOL + "9";
public static final String GREEN = SYMBOL + "a";
public static final String AQUA = SYMBOL + "b";
public static final String RED = SYMBOL + "c";
public static final String LIGHT_PURPLE = SYMBOL + "d";
public static final String YELLOW = SYMBOL + "e";
public static final String WHITE = SYMBOL + "f";
public static final String OBFUSCATED = SYMBOL + "k";
public static final String BOLD = SYMBOL + "l";
public static final String STRIKETHROUGH = SYMBOL + "m";
public static final String UNDERLINE = SYMBOL + "n";
public static final String ITALIC = SYMBOL + "o";
public static final String RESET = SYMBOL + "r";
}

View File

@@ -0,0 +1,5 @@
package xyz.webmc.originblacklist.base.util;
public final class EaglerEventPriority {
public static final int EAGLER_MOTD_EVENT = 100;
}

View File

@@ -0,0 +1,37 @@
package xyz.webmc.originblacklist.base.util;
import xyz.webmc.originblacklist.base.enums.EnumLogLevel;
import xyz.webmc.originblacklist.base.events.OriginBlacklistLoginEvent;
import xyz.webmc.originblacklist.base.events.OriginBlacklistMOTDEvent;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import net.kyori.adventure.text.Component;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
import org.semver4j.Semver;
@SuppressWarnings({ "rawtypes" })
public interface IOriginBlacklistPlugin {
public String getPluginId();
public Semver getPluginVersion();
public Path getPluginJarPath();
public IEaglerXServerAPI getEaglerAPI();
public void log(final EnumLogLevel level, final String txt);
public void kickPlayer(final Component txt, final OriginBlacklistLoginEvent event);
public void setMOTD(final Component txt, final OriginBlacklistMOTDEvent event);
public String parsePlaceholders(final OPlayer player, final String str);
public void scheduleRepeat(final Runnable task, final int period, final TimeUnit unit);
public void runAsync(final Runnable task);
public void shutdown();
}

View File

@@ -0,0 +1,14 @@
package xyz.webmc.originblacklist.base.util;
import org.semver4j.Semver;
public final class IncompatibleDependencyException extends RuntimeException {
public IncompatibleDependencyException(final String name, final Semver requiredVersion, final Semver currentVersion) {
super("Incompatible version of " + name + " is present! Required " + requiredVersion + ", but found "
+ currentVersion + ".");
}
public IncompatibleDependencyException(final String name) {
super("Missing dependency " + name + "!");
}
}

View File

@@ -0,0 +1,159 @@
package xyz.webmc.originblacklist.base.util;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.UUID;
import net.lax1dude.eaglercraft.backend.server.api.EnumWebSocketHeader;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerConnection;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerLoginConnection;
public final class OPlayer {
private final String origin;
private final String addr;
private final String name;
private final UUID uuid;
private final String brand;
private final String vhost;
private final boolean rewind;
private final int pvn;
public OPlayer(final IEaglerConnection conn, final String name, final UUID uuid, final String addr,
final String brand, final String vhost, final int pvn) {
this.name = name;
this.uuid = uuid;
if (conn != null) {
this.origin = conn.getWebSocketHeader(EnumWebSocketHeader.HEADER_ORIGIN);
this.addr = formatSocketAddress(conn.getSocketAddress());
this.vhost = conn.isWebSocketSecure() ? "wss://" : "ws://" + conn.getWebSocketHost();
if (conn instanceof IEaglerLoginConnection) {
final IEaglerLoginConnection loginConn = (IEaglerLoginConnection) conn;
this.brand = loginConn.getEaglerBrandString();
this.rewind = loginConn.isEaglerXRewindPlayer();
this.pvn = this.rewind ? loginConn.getRewindProtocolVersion() : loginConn.getMinecraftProtocol();
} else {
this.brand = OriginBlacklist.UNKNOWN_STR;
this.rewind = false;
this.pvn = pvn;
}
} else {
this.origin = OriginBlacklist.UNKNOWN_STR;
this.addr = formatIPAddress(addr);
this.brand = brand;
this.vhost = vhost;
this.rewind = false;
this.pvn = pvn;
}
}
public OPlayer(final IEaglerConnection conn, final String name, final UUID uuid) {
this(conn, name, uuid, null, null, null, -1);
}
public final String getOrigin() {
return this.origin;
}
public final String getAddr() {
return this.addr;
}
public final String getName() {
return this.name;
}
public final UUID getUUID() {
return this.uuid;
}
public final String getBrand() {
return this.brand;
}
public final String getVHost() {
return this.vhost;
}
public final boolean isRewind() {
return this.rewind;
}
public final int getPVN() {
return this.pvn;
}
private static final String formatIPAddress(String addr) {
if (OriginBlacklist.isNonNull(addr)) {
if (addr.startsWith("/")) {
addr = addr.substring(1);
}
int i = addr.lastIndexOf('/');
if (i != -1) {
addr = addr.substring(i + 1);
}
if (addr.startsWith("[")) {
i = addr.indexOf(']');
if (i != -1) {
addr = addr.substring(1, i);
} else {
addr = addr.substring(1);
}
} else {
i = addr.lastIndexOf(':');
if (i != -1) {
String a = addr.substring(0, i);
String p = addr.substring(i + 1);
boolean port = !p.isEmpty();
for (int j = 0; j < p.length() && port; j++) {
char c = p.charAt(j);
port = (c >= '0' && c <= '9');
}
if (port) {
if (a.indexOf('.') != -1) {
addr = a;
}
}
}
}
int c = 0;
boolean hex = true;
for (int j = 0; j < addr.length(); j++) {
char ch = addr.charAt(j);
if (ch == ':') {
c++;
} else if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) {
hex = false;
break;
}
}
if (hex && c == 6 && addr.indexOf("::") == -1) {
addr = addr + "::";
}
} else {
addr = OriginBlacklist.UNKNOWN_STR;
}
return addr;
}
private static final String formatSocketAddress(final SocketAddress saddr) {
if (saddr instanceof InetSocketAddress) {
final InetSocketAddress isa = (InetSocketAddress) saddr;
if (isa.getAddress() != null) {
return isa.getAddress().getHostAddress();
} else {
return isa.getHostString();
}
} else {
return formatIPAddress(saddr.toString());
}
}
}

View File

@@ -0,0 +1,101 @@
package xyz.webmc.originblacklist.base.util;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import de.marhali.json5.Json5;
import de.marhali.json5.Json5Array;
import de.marhali.json5.Json5Element;
import de.marhali.json5.Json5Object;
import org.semver4j.Semver;
import org.semver4j.Semver.VersionDiff;
public final class UpdateChecker {
private static final Json5 json5 = Json5.builder(builder -> builder.build());
public static final String checkForUpdates(final String repo, final Semver currentVersion,
final boolean allowSnapshots) {
try {
final URL url = new URL("https://api.github.com/repos/" + repo + "/releases");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("User-Agent", OriginBlacklist.getUserAgent());
conn.setRequestProperty("Accept", "application/vnd.github+json");
conn.connect();
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String ret = null;
Json5Element element = json5.parse(reader);
reader.close();
Json5Object rel = null;
Json5Object snap = null;
if (element instanceof Json5Array) {
final Json5Array arr = element.getAsJson5Array();
for (int i = 0; i < arr.size(); i++) {
element = arr.get(i);
if (element instanceof Json5Object) {
final Json5Object obj = element.getAsJson5Object();
if (!obj.has("published_at")) {
continue;
}
final boolean pre = obj.get("prerelease").getAsBoolean();
if (!pre) {
if (rel == null
|| obj.get("published_at").getAsString().compareTo(rel.get("published_at").getAsString()) > 0) {
rel = obj;
}
} else {
if (snap == null
|| obj.get("published_at").getAsString().compareTo(snap.get("published_at").getAsString()) > 0) {
snap = obj;
}
}
}
continue;
}
for (int i = 0; i < 2; i++) {
final Json5Object obj = i == 0 ? rel : snap;
if (obj == null || (i == 1 && !allowSnapshots)) {
continue;
}
final String tag = obj.get("tag_name").getAsString();
final Semver ver = new Semver(tag.startsWith("v") ? tag.substring(1) : tag);
String comm;
try {
comm = ver.getBuild().get(0).trim();
} catch (final Throwable t) {
comm = "";
}
if (ver.isGreaterThan(currentVersion) || (allowSnapshots && currentVersion.diff(ver) == VersionDiff.BUILD
&& OriginBlacklist.isNonNull(comm) && !BuildInfo.get("git_cm_hash").startsWith(comm))) {
element = obj.get("assets");
if (element instanceof Json5Array) {
final Json5Array aArr = element.getAsJson5Array();
if (aArr.size() > 0) {
element = aArr.get(0);
if (element instanceof Json5Object) {
ret = element.getAsJson5Object().get("browser_download_url").getAsString();
break;
}
}
}
}
}
}
conn.disconnect();
return ret;
} catch (final Throwable t) {
t.printStackTrace();
return null;
}
}
}

View File

@@ -0,0 +1,254 @@
package xyz.webmc.originblacklist.bukkit;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.enums.EnumLogLevel;
import xyz.webmc.originblacklist.base.events.OriginBlacklistLoginEvent;
import xyz.webmc.originblacklist.base.events.OriginBlacklistMOTDEvent;
import xyz.webmc.originblacklist.base.util.IOriginBlacklistPlugin;
import xyz.webmc.originblacklist.base.util.IncompatibleDependencyException;
import xyz.webmc.originblacklist.base.util.OPlayer;
import xyz.webmc.originblacklist.bukkit.command.OriginBlacklistCommandBukkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import net.kyori.adventure.text.Component;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.bukkit.event.EaglercraftMOTDEvent;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.AdvancedPie;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.CachedServerIcon;
import org.semver4j.Semver;
@SuppressWarnings({ "rawtypes" })
public final class OriginBlacklistBukkit extends JavaPlugin implements Listener, IOriginBlacklistPlugin {
private boolean papiPlaceholdersEnabled;
private Object papi;
private OriginBlacklist blacklist;
private Metrics metrics;
private CachedServerIcon iconCache;
@Override
public final void onEnable() {
final Plugin eagx = this.getServer().getPluginManager().getPlugin("EaglercraftXServer");
if (eagx == null) {
throw new IncompatibleDependencyException("EaglercraftXServer");
} else {
final Semver version = new Semver(eagx.getDescription().getVersion());
if (version.isLowerThan(OriginBlacklist.REQUIRED_API_VER)) {
throw new IncompatibleDependencyException("EaglerXServer", OriginBlacklist.REQUIRED_API_VER, version);
}
}
this.papiPlaceholdersEnabled = this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null;
if (this.papiPlaceholdersEnabled) {
try {
this.papi = Class.forName("me.clip.placeholderapi.PlaceholderAPI");
} catch (final Throwable t) {
this.papi = null;
this.papiPlaceholdersEnabled = false;
}
} else {
this.papi = null;
}
this.blacklist = new OriginBlacklist(this);
this.getCommand("originblacklist").setExecutor(new OriginBlacklistCommandBukkit(this.blacklist));
this.getServer().getPluginManager().registerEvents(this, this);
this.blacklist.init();
if (this.blacklist.isMetricsEnabled()) {
this.metrics = new Metrics(this, OriginBlacklist.BSTATS.BUKKIT);
this.metrics.addCustomChart(new AdvancedPie("player_types", () -> {
final Map<String, Integer> playerMap = new HashMap<>();
for (final Player player : Bukkit.getOnlinePlayers()) {
final boolean eagler = this.getEaglerAPI().isEaglerPlayerByUUID(player.getUniqueId());
final String key = eagler ? "Eagler" : "Java";
playerMap.put(key, playerMap.getOrDefault(key, 0) + 1);
}
return playerMap;
}));
}
}
@Override
public void onDisable() {
this.blacklist.shutdown();
}
@EventHandler(priority = EventPriority.NORMAL)
public final void onEaglerLogin(final EaglercraftLoginEvent event) {
final OPlayer player = new OPlayer(event.getLoginConnection(), event.getProfileUsername(), event.getProfileUUID());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(event, null, EnumConnectionType.EAGLER, player));
}
@EventHandler(priority = EventPriority.HIGHEST)
public final void onEaglerMOTD(final EaglercraftMOTDEvent event) {
final OPlayer player = new OPlayer(event.getMOTDConnection(), null, null);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(event, null, EnumConnectionType.EAGLER, player));
}
@EventHandler(priority = EventPriority.LOWEST)
public final void onJavaLogin(final AsyncPlayerPreLoginEvent event) {
final OPlayer player = new OPlayer(null, event.getName(), event.getUniqueId(), event.getAddress().toString(),
OriginBlacklist.UNKNOWN_STR, OriginBlacklist.UNKNOWN_STR, -1);
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(null, event, EnumConnectionType.JAVA, player));
}
@EventHandler(priority = EventPriority.HIGHEST)
public final void onJavaMOTD(final ServerListPingEvent event) {
final OPlayer player = new OPlayer(null, null, null, event.getAddress().toString(), null, null, -1);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(null, event, EnumConnectionType.JAVA, player));
}
@Override
public final String getPluginId() {
return this.getDescription().getName();
}
@Override
public final Semver getPluginVersion() {
return new Semver(this.getDescription().getVersion());
}
@Override
public final Path getPluginJarPath() {
return Paths.get(this.getFile().getAbsolutePath());
}
@Override
public final IEaglerXServerAPI getEaglerAPI() {
return EaglerXServerAPI.instance();
}
@Override
public final void log(final EnumLogLevel level, final String txt) {
if (level == EnumLogLevel.WARN) {
this.getLogger().warning(txt);
} else if (level == EnumLogLevel.ERROR) {
this.getLogger().severe(txt);
} else if (level == EnumLogLevel.DEBUG) {
if (this.blacklist != null && this.blacklist.isDebugEnabled()) {
this.getLogger().info(txt);
}
} else {
this.getLogger().info(txt);
}
}
@Override
public final void kickPlayer(final Component comp, final OriginBlacklistLoginEvent event) {
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
event.getEaglerEvent().setKickMessage(OriginBlacklist.getComponentString(comp));
} else {
final Object javaEvent = event.getJavaEvent();
final String msg = OriginBlacklist.getComponentString(comp);
if (javaEvent instanceof AsyncPlayerPreLoginEvent pre) {
pre.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, msg);
} else if (javaEvent instanceof PlayerJoinEvent join) {
join.getPlayer().kickPlayer(msg);
}
}
}
@Override
public final void setMOTD(final Component comp, final OriginBlacklistMOTDEvent event) {
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
this.blacklist.setEaglerMOTD(comp, event);
} else {
final ServerListPingEvent javaEvent = (ServerListPingEvent) event.getJavaEvent();
javaEvent.setMotd(OriginBlacklist.getComponentString(comp));
javaEvent.setMaxPlayers(0);
final CachedServerIcon icon = this.loadIcon();
if (icon != null) {
try {
javaEvent.setServerIcon(icon);
} catch (final Throwable t) {
}
}
}
}
private final CachedServerIcon loadIcon() {
if (this.iconCache != null)
return this.iconCache;
final String uri = this.blacklist.getConfig().getIconBase64URI();
if (uri == null || uri.isEmpty())
return null;
try {
String b64 = uri;
final int i = b64.indexOf("base64,");
if (i != -1)
b64 = b64.substring(i + "base64,".length());
final byte[] png = Base64.getDecoder().decode(b64);
final BufferedImage img = javax.imageio.ImageIO.read(new ByteArrayInputStream(png));
if (img != null) {
try {
this.iconCache = Bukkit.loadServerIcon(img);
} catch (final Throwable t) {
return null;
}
} else {
return null;
}
return this.iconCache;
} catch (final Throwable t) {
return null;
}
}
@Override
public final String parsePlaceholders(final OPlayer player, final String txt) {
if (this.papiPlaceholdersEnabled) {
try {
final UUID uuid = player.getUUID();
final Player bp = uuid != null ? (Player) Bukkit.getPlayer(uuid) : null;
if (bp != null) {
return (String) ((Class<?>) this.papi)
.getMethod("setPlaceholders", org.bukkit.entity.Player.class, String.class).invoke(null, bp, txt);
}
} catch (final Throwable t) {
}
}
return txt;
}
@Override
public final void scheduleRepeat(final Runnable task, final int period, final TimeUnit unit) {
long ms = unit.toMillis((long) period);
long ticks = Math.max(1L, ms / 50L);
Bukkit.getScheduler().runTaskTimer(this, task, 0, ticks);
}
@Override
public final void runAsync(final Runnable task) {
Bukkit.getScheduler().runTaskAsynchronously(this, task);
}
@Override
public final void shutdown() {
this.metrics.shutdown();
Bukkit.getScheduler().cancelTasks(this);
}
}

View File

@@ -0,0 +1,43 @@
package xyz.webmc.originblacklist.bukkit.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.CommandContext;
import org.bukkit.command.CommandSender;
public final class BKTCommandContext implements CommandContext {
private final OriginBlacklist plugin;
private final CommandSender sender;
private final String[] args;
public BKTCommandContext(final OriginBlacklist plugin, final CommandSender sender, final String[] args) {
this.plugin = plugin;
this.sender = sender;
this.args = args;
}
@Override
public final OriginBlacklist getPlugin() {
return this.plugin;
}
@Override
public final String getPlayerName() {
return this.sender.getName();
}
@Override
public final void reply(final String message) {
this.sender.sendMessage(OriginBlacklist.getLegacyFromMiniMessage(message));
}
@Override
public final boolean hasPermission(final String permission) {
return this.sender.hasPermission(permission);
}
@Override
public final String[] getArgs() {
return this.args;
}
}

View File

@@ -0,0 +1,30 @@
package xyz.webmc.originblacklist.bukkit.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.OriginBlacklistCommand;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
public final class OriginBlacklistCommandBukkit extends OriginBlacklistCommand implements TabExecutor {
private final OriginBlacklist plugin;
public OriginBlacklistCommandBukkit(OriginBlacklist plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
return super.execute(new BKTCommandContext(this.plugin, sender, args));
}
@Override
public List<String> onTabComplete(final CommandSender sender, final Command command, final String label,
final String[] args) {
return super.suggest(new BKTCommandContext(this.plugin, sender, args));
}
}

View File

@@ -0,0 +1,232 @@
package xyz.webmc.originblacklist.bungee;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.enums.EnumLogLevel;
import xyz.webmc.originblacklist.base.events.OriginBlacklistLoginEvent;
import xyz.webmc.originblacklist.base.events.OriginBlacklistMOTDEvent;
import xyz.webmc.originblacklist.base.util.EaglerEventPriority;
import xyz.webmc.originblacklist.base.util.IOriginBlacklistPlugin;
import xyz.webmc.originblacklist.base.util.IncompatibleDependencyException;
import xyz.webmc.originblacklist.base.util.OPlayer;
import xyz.webmc.originblacklist.bungee.command.OriginBlacklistCommandBungee;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import net.kyori.adventure.text.Component;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bungee.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.bungee.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.bungee.event.EaglercraftMOTDEvent;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
import org.bstats.bungeecord.Metrics;
import org.bstats.charts.AdvancedPie;
import org.semver4j.Semver;
@SuppressWarnings({ "deprecation", "rawtypes" })
public final class OriginBlacklistBungee extends Plugin implements Listener, IOriginBlacklistPlugin {
private ProxyServer proxy;
private boolean papiPlaceholdersEnabled;
private Object papi;
private OriginBlacklist blacklist;
private Metrics metrics;
@Override
public final void onEnable() {
this.proxy = ProxyServer.getInstance();
final Plugin eagx = this.getProxy().getPluginManager().getPlugin("EaglercraftXServer");
if (eagx == null) {
throw new IncompatibleDependencyException("EaglercraftXServer");
} else {
final Semver version = new Semver(eagx.getDescription().getVersion());
if (version.isLowerThan(OriginBlacklist.REQUIRED_API_VER)) {
throw new IncompatibleDependencyException("EaglerXServer", OriginBlacklist.REQUIRED_API_VER, version);
}
}
this.papiPlaceholdersEnabled = this.getProxy().getPluginManager().getPlugin("PAPIProxyBridge") != null;
if (this.papiPlaceholdersEnabled) {
try {
this.papi = Class.forName("net.william278.papiproxybridge.api.PlaceholderAPI").getMethod("createInstance")
.invoke(null);
} catch (final Throwable t) {
this.papi = null;
this.papiPlaceholdersEnabled = false;
}
} else {
this.papi = null;
}
this.blacklist = new OriginBlacklist(this);
this.getProxy().getPluginManager().registerCommand(this,
new OriginBlacklistCommandBungee(this, this.blacklist, "originblacklist"));
this.getProxy().getPluginManager().registerListener(this, this);
this.blacklist.init();
if (this.blacklist.isMetricsEnabled()) {
this.metrics = new Metrics(this, OriginBlacklist.BSTATS.BUNGEE);
this.metrics.addCustomChart(new AdvancedPie("player_types", () -> {
final Map<String, Integer> playerMap = new HashMap<>();
for (final ProxiedPlayer player : this.proxy.getPlayers()) {
final boolean eagler = this.getEaglerAPI().isEaglerPlayerByUUID(player.getUniqueId());
final String key = eagler ? "Eagler" : "Java";
playerMap.put(key, playerMap.getOrDefault(key, 0) + 1);
}
return playerMap;
}));
}
}
@Override
public void onDisable() {
this.blacklist.shutdown();
}
@EventHandler(priority = EventPriority.HIGHEST)
public final void onEaglerLogin(final EaglercraftLoginEvent event) {
final OPlayer player = new OPlayer(event.getLoginConnection(), event.getProfileUsername(), event.getProfileUUID());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(event, null, EnumConnectionType.EAGLER, player));
}
@EventHandler(priority = EaglerEventPriority.EAGLER_MOTD_EVENT)
public final void onEaglerMOTD(final EaglercraftMOTDEvent event) {
final OPlayer player = new OPlayer(event.getMOTDConnection(), null, null);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(event, null, EnumConnectionType.EAGLER, player));
}
@EventHandler(priority = EventPriority.HIGHEST)
public final void onJavaLogin(final PostLoginEvent event) {
final PendingConnection conn = event.getPlayer().getPendingConnection();
final InetSocketAddress vhost = conn.getVirtualHost();
final ProxiedPlayer aPlayer = event.getPlayer();
final OPlayer bPlayer = new OPlayer(null, aPlayer.getName(), aPlayer.getUniqueId(),
aPlayer.getAddress().toString(), aPlayer.getClientBrand(), vhost.getHostString() + vhost.getPort(),
conn.getVersion());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(null, event, EnumConnectionType.JAVA, bPlayer));
}
@EventHandler(priority = EventPriority.HIGHEST)
public final void onJavaHandshake(final PreLoginEvent event) {
final PendingConnection conn = event.getConnection();
final InetSocketAddress vhost = conn.getVirtualHost();
final OPlayer player = new OPlayer(null, null, null, conn.getAddress().toString(), OriginBlacklist.UNKNOWN_STR,
vhost.getHostString() + vhost.getPort(), conn.getVersion());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(null, event, EnumConnectionType.JAVA, player));
}
@EventHandler(priority = EventPriority.LOWEST)
public final void onJavaMOTD(final ProxyPingEvent event) {
final PendingConnection conn = event.getConnection();
final InetSocketAddress vhost = conn.getVirtualHost();
final OPlayer player = new OPlayer(null, null, null, conn.getAddress().toString(), null,
vhost.getHostString() + vhost.getPort(), -1);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(null, event, EnumConnectionType.JAVA, player));
}
@Override
public final String getPluginId() {
return this.getDescription().getName();
}
@Override
public final Semver getPluginVersion() {
return new Semver(this.getDescription().getVersion());
}
@Override
public final Path getPluginJarPath() {
return Paths.get(this.getFile().getAbsolutePath());
}
@Override
public final IEaglerXServerAPI getEaglerAPI() {
return EaglerXServerAPI.instance();
}
@Override
public final void log(final EnumLogLevel level, final String txt) {
if (level == EnumLogLevel.WARN) {
this.getLogger().warning(txt);
} else if (level == EnumLogLevel.ERROR) {
this.getLogger().severe(txt);
} else if (level == EnumLogLevel.DEBUG) {
if (this.blacklist != null && this.blacklist.isDebugEnabled()) {
this.getLogger().info(txt);
}
} else {
this.getLogger().info(txt);
}
}
@Override
public final void kickPlayer(final Component comp, final OriginBlacklistLoginEvent event) {
final String str = OriginBlacklist.getComponentString(comp);
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
event.getEaglerEvent().setKickMessage(str);
} else {
final Object javaEvent = event.getJavaEvent();
if (javaEvent instanceof PreLoginEvent preLoginEvent) {
preLoginEvent.getConnection().disconnect(str);
} else if (javaEvent instanceof PostLoginEvent postLoginEvent) {
postLoginEvent.getPlayer().disconnect(str);
}
}
}
@Override
public final void setMOTD(final Component comp, final OriginBlacklistMOTDEvent event) {
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
this.blacklist.setEaglerMOTD(comp, event);
} else {
final ProxyPingEvent javaEvent = (ProxyPingEvent) event.getJavaEvent();
final ServerPing ping = javaEvent.getResponse();
ping.setDescription(OriginBlacklist.getComponentString(comp));
ping.setFavicon(this.blacklist.getConfig().getIconBase64URI());
ping.getPlayers().setOnline(0);
ping.getPlayers().setMax(0);
javaEvent.setResponse(ping);
}
}
@Override
public final String parsePlaceholders(final OPlayer player, final String txt) {
if (this.papiPlaceholdersEnabled && this.papi != null) {
try {
return (String) this.papi.getClass().getMethod("formatPlaceholders", String.class, java.util.UUID.class)
.invoke(this.papi, txt, player.getUUID());
} catch (final Throwable t) {
}
}
return txt;
}
@Override
public final void scheduleRepeat(final Runnable task, final int period, final TimeUnit unit) {
this.proxy.getScheduler().schedule(this, task, 0, period, unit);
}
@Override
public final void runAsync(final Runnable task) {
this.proxy.getScheduler().runAsync(this, task);
}
@Override
public final void shutdown() {
this.metrics.shutdown();
this.proxy.getScheduler().cancel(this);
}
}

View File

@@ -0,0 +1,44 @@
package xyz.webmc.originblacklist.bungee.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.CommandContext;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.TextComponent;
public final class BNGCommandContext implements CommandContext {
private final OriginBlacklist plugin;
private final CommandSender sender;
private final String[] args;
public BNGCommandContext(final OriginBlacklist plugin, final CommandSender sender, final String[] args) {
this.plugin = plugin;
this.sender = sender;
this.args = args;
}
@Override
public final OriginBlacklist getPlugin() {
return this.plugin;
}
@Override
public final String getPlayerName() {
return this.sender.getName();
}
@Override
public final void reply(final String message) {
this.sender.sendMessage(TextComponent.fromLegacy(OriginBlacklist.getLegacyFromMiniMessage(message)));
}
@Override
public final boolean hasPermission(final String permission) {
return this.sender.hasPermission(permission);
}
@Override
public final String[] getArgs() {
return this.args;
}
}

View File

@@ -0,0 +1,33 @@
package xyz.webmc.originblacklist.bungee.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.OriginBlacklistCommand;
import xyz.webmc.originblacklist.bungee.OriginBlacklistBungee;
import java.util.List;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.TabExecutor;
public final class OriginBlacklistCommandBungee extends Command implements TabExecutor {
private final OriginBlacklistCommand cmd;
private final OriginBlacklist blacklist;
public OriginBlacklistCommandBungee(final OriginBlacklistBungee plugin, final OriginBlacklist blacklist,
final String command) {
super(command);
this.cmd = new OriginBlacklistCommand(blacklist);
this.blacklist = blacklist;
}
@Override
public final void execute(final CommandSender sender, final String[] args) {
this.cmd.execute(new BNGCommandContext(this.blacklist, sender, args));
}
@Override
public final List<String> onTabComplete(final CommandSender sender, final String[] args) {
return this.cmd.suggest(new BNGCommandContext(this.blacklist, sender, args));
}
}

View File

@@ -0,0 +1,262 @@
package xyz.webmc.originblacklist.velocity;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.enums.EnumConnectionType;
import xyz.webmc.originblacklist.base.enums.EnumLogLevel;
import xyz.webmc.originblacklist.base.events.OriginBlacklistLoginEvent;
import xyz.webmc.originblacklist.base.events.OriginBlacklistMOTDEvent;
import xyz.webmc.originblacklist.base.util.EaglerEventPriority;
import xyz.webmc.originblacklist.base.util.IOriginBlacklistPlugin;
import xyz.webmc.originblacklist.base.util.IncompatibleDependencyException;
import xyz.webmc.originblacklist.base.util.OPlayer;
import xyz.webmc.originblacklist.velocity.command.OriginBlacklistCommandVelocity;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.google.inject.Inject;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.event.player.PlayerClientBrandEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.proxy.InboundConnection;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.server.ServerPing;
import com.velocitypowered.api.scheduler.ScheduledTask;
import com.velocitypowered.api.util.Favicon;
import net.kyori.adventure.text.Component;
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.velocity.EaglerXServerAPI;
import net.lax1dude.eaglercraft.backend.server.api.velocity.event.EaglercraftLoginEvent;
import net.lax1dude.eaglercraft.backend.server.api.velocity.event.EaglercraftMOTDEvent;
import org.bstats.charts.AdvancedPie;
import org.bstats.velocity.Metrics;
import org.bstats.velocity.Metrics.Factory;
import org.semver4j.Semver;
import org.slf4j.Logger;
@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
public final class OriginBlacklistVelocity implements IOriginBlacklistPlugin {
private final PluginContainer plugin;
private final Factory metricsFactory;
private final ProxyServer proxy;
private final Logger logger;
private boolean papiPlaceholdersEnabled;
private Object papi;
private OriginBlacklist blacklist;
private Metrics metrics;
@Inject
public OriginBlacklistVelocity(final PluginContainer plugin, Factory metricsFactory, final ProxyServer proxy,
final Logger logger) {
this.plugin = plugin;
this.metricsFactory = metricsFactory;
this.proxy = proxy;
this.logger = logger;
}
@Subscribe
public final void onProxyInitialization(ProxyInitializeEvent event) {
this.proxy.getPluginManager().getPlugin("eaglerxserver").ifPresentOrElse(plugin -> {
final Semver version = new Semver(plugin.getDescription().getVersion().orElse("1.0.0"));
if (version.isLowerThan(OriginBlacklist.REQUIRED_API_VER)) {
throw new IncompatibleDependencyException("EaglerXServer", OriginBlacklist.REQUIRED_API_VER, version);
}
}, () -> {
throw new IncompatibleDependencyException("EaglerXServer");
});
this.papiPlaceholdersEnabled = this.proxy.getPluginManager().getPlugin("papiproxybridge").isPresent();
if (this.papiPlaceholdersEnabled) {
try {
this.papi = Class.forName("net.william278.papiproxybridge.api.PlaceholderAPI").getMethod("createInstance")
.invoke(null);
} catch (final Throwable t) {
this.papi = null;
this.papiPlaceholdersEnabled = false;
}
} else {
this.papi = null;
}
this.blacklist = new OriginBlacklist(this);
this.proxy.getCommandManager().register("originblacklist", new OriginBlacklistCommandVelocity(this.blacklist));
this.blacklist.init();
if (this.blacklist.isMetricsEnabled()) {
this.metrics = this.metricsFactory.make(this, OriginBlacklist.BSTATS.VELOCITY);
this.metrics.addCustomChart(new AdvancedPie("player_types", () -> {
final Map<String, Integer> playerMap = new HashMap<>();
for (final Player player : this.proxy.getAllPlayers()) {
final boolean eagler = this.getEaglerAPI().isEaglerPlayerByUUID(player.getUniqueId());
final String key = eagler ? "Eagler" : "Java";
playerMap.put(key, playerMap.getOrDefault(key, 0) + 1);
}
return playerMap;
}));
}
}
@Subscribe
public final void onProxyShutdown(final ProxyShutdownEvent e) {
this.blacklist.shutdown();
}
@Subscribe(order = PostOrder.FIRST)
public final void onEaglerLogin(final EaglercraftLoginEvent event) {
final OPlayer player = new OPlayer(event.getLoginConnection(), event.getProfileUsername(), event.getProfileUUID());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(event, null, EnumConnectionType.EAGLER, player));
}
@Subscribe(priority = EaglerEventPriority.EAGLER_MOTD_EVENT, order = PostOrder.LAST)
public final void onEaglerMOTD(final EaglercraftMOTDEvent event) {
final OPlayer player = new OPlayer(event.getMOTDConnection(), null, null);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(event, null, EnumConnectionType.EAGLER, player));
}
@Subscribe(order = PostOrder.FIRST)
public final void onJavaLogin(final PreLoginEvent event) {
final InboundConnection conn = event.getConnection();
final InetSocketAddress vhost = conn.getVirtualHost().orElseThrow();
final OPlayer player = new OPlayer(null, event.getUsername(), event.getUniqueId(),
conn.getRemoteAddress().toString(), OriginBlacklist.UNKNOWN_STR, vhost.getHostString() + vhost.getPort(),
conn.getProtocolVersion().getProtocol());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(null, event, EnumConnectionType.JAVA, player));
}
@Subscribe(order = PostOrder.FIRST)
public final void onJavaHandshake(final PlayerClientBrandEvent event) {
final InetSocketAddress vhost = event.getPlayer().getVirtualHost().orElseThrow();
final Player aPlayer = event.getPlayer();
final OPlayer bPlayer = new OPlayer(null, aPlayer.getUsername(), aPlayer.getUniqueId(),
aPlayer.getRemoteAddress().getAddress().toString(), event.getBrand(), vhost.getHostString() + vhost.getPort(),
event.getPlayer().getProtocolVersion().getProtocol());
this.blacklist.handleLogin(new OriginBlacklistLoginEvent(null, event, EnumConnectionType.JAVA, bPlayer));
}
@Subscribe(order = PostOrder.LAST)
public final void onJavaMOTD(final ProxyPingEvent event) {
final InboundConnection conn = event.getConnection();
final InetSocketAddress vhost = conn.getVirtualHost().orElseThrow();
final OPlayer player = new OPlayer(null, null, null, conn.getRemoteAddress().getHostString(),
vhost.getHostString() + vhost.getPort(),
null, -1);
this.blacklist.handleMOTD(new OriginBlacklistMOTDEvent(null, event, EnumConnectionType.JAVA, player));
}
@Override
public final String getPluginId() {
return this.plugin.getDescription().getId();
}
@Override
public final Semver getPluginVersion() {
return new Semver(this.plugin.getDescription().getVersion().get());
}
@Override
public final Path getPluginJarPath() {
try {
return Paths.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toAbsolutePath();
} catch (final Throwable t) {
throw new RuntimeException("Unable to determine plugin JAR path");
}
}
@Override
public final IEaglerXServerAPI getEaglerAPI() {
return EaglerXServerAPI.instance();
}
@Override
public final void log(final EnumLogLevel level, final String txt) {
if (level == EnumLogLevel.WARN) {
this.logger.warn(txt);
} else if (level == EnumLogLevel.ERROR) {
this.logger.error(txt);
} else if (level == EnumLogLevel.DEBUG) {
if (this.blacklist.isDebugEnabled()) {
this.logger.info(txt);
}
} else {
this.logger.info(txt);
}
}
@Override
public final void kickPlayer(final Component comp, final OriginBlacklistLoginEvent event) {
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
event.getEaglerEvent().setKickMessage(comp);
} else {
final Object javaEvent = event.getJavaEvent();
if (javaEvent instanceof PreLoginEvent loginEvent) {
loginEvent.setResult(PreLoginEvent.PreLoginComponentResult.denied(comp));
} else if (javaEvent instanceof PlayerClientBrandEvent brandEvent) {
brandEvent.getPlayer().disconnect(comp);
}
}
}
@Override
public final void setMOTD(final Component comp, final OriginBlacklistMOTDEvent event) {
if (event.getConnectionType() == EnumConnectionType.EAGLER) {
blacklist.setEaglerMOTD(comp, event);
} else {
final ProxyPingEvent javaEvent = (ProxyPingEvent) event.getJavaEvent();
ServerPing ping = ServerPing.builder()
.description(comp)
.version(new ServerPing.Version(0, ""))
.samplePlayers(List.of())
.onlinePlayers(0)
.maximumPlayers(0)
.favicon(new Favicon(this.blacklist.getConfig().getIconBase64URI()))
.build();
javaEvent.setPing(ping);
}
}
@Override
public final String parsePlaceholders(final OPlayer player, final String txt) {
if (this.papiPlaceholdersEnabled && this.papi != null) {
try {
return (String) this.papi.getClass().getMethod("formatPlaceholders", String.class, java.util.UUID.class)
.invoke(this.papi, txt, player.getUUID());
} catch (final Throwable t) {
}
}
return txt;
}
@Override
public final void scheduleRepeat(final Runnable task, final int period, final TimeUnit unit) {
this.proxy.getScheduler()
.buildTask(this, task)
.repeat(period, unit)
.schedule();
}
@Override
public final void runAsync(final Runnable task) {
this.proxy.getScheduler()
.buildTask(this, task)
.schedule();
}
@Override
public final void shutdown() {
this.metrics.shutdown();
for (ScheduledTask task : this.proxy.getScheduler().tasksByPlugin(this.plugin)) {
task.cancel();
}
}
}

View File

@@ -0,0 +1,27 @@
package xyz.webmc.originblacklist.velocity.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.OriginBlacklistCommand;
import java.util.List;
import com.velocitypowered.api.command.SimpleCommand;
public final class OriginBlacklistCommandVelocity extends OriginBlacklistCommand implements SimpleCommand {
private final OriginBlacklist plugin;
public OriginBlacklistCommandVelocity(OriginBlacklist plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
public final void execute(final Invocation invocation) {
super.execute(new VCommandContext(this.plugin, invocation));
}
@Override
public final List<String> suggest(final Invocation invocation) {
return super.suggest(new VCommandContext(this.plugin, invocation));
}
}

View File

@@ -0,0 +1,42 @@
package xyz.webmc.originblacklist.velocity.command;
import xyz.webmc.originblacklist.base.OriginBlacklist;
import xyz.webmc.originblacklist.base.command.CommandContext;
import com.velocitypowered.api.command.SimpleCommand.Invocation;
import net.kyori.adventure.text.minimessage.MiniMessage;
public final class VCommandContext implements CommandContext {
private final OriginBlacklist plugin;
private final Invocation invocation;
public VCommandContext(final OriginBlacklist plugin, final Invocation invocation) {
this.plugin = plugin;
this.invocation = invocation;
}
@Override
public final OriginBlacklist getPlugin() {
return this.plugin;
}
@Override
public final String getPlayerName() {
return this.invocation.source().toString();
}
@Override
public final void reply(final String message) {
this.invocation.source().sendMessage(MiniMessage.miniMessage().deserialize(message));
}
@Override
public final boolean hasPermission(final String permission) {
return this.invocation.source().hasPermission(permission);
}
@Override
public final String[] getArgs() {
return this.invocation.arguments();
}
}

View File

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@@ -1,7 +1,10 @@
name: OriginBlacklist name: ${plugin_name}
version: ${version} version: ${plugin_vers}
main: dev.colbster937.originblacklist.bungee.OriginBlacklistBungee main: xyz.webmc.${plugin_iden}.bungee.${plugin_name}Bungee
description: ${description} description: ${plugin_desc}
author: Colbster937 website: ${plugin_site}
depends: author: ${plugin_athr}
- EaglercraftXServer contributors: ${plugin_ctbr}
depends: ${plugin_depb}
provides: ${plugin_prov}
softdepend: ${plugin_sdpb}

View File

@@ -1,68 +0,0 @@
messages:
# Valid Placeholders:
# - %blocked% - The player's origin/brand that was blocked
# - %blocktype% - Shows what the player was blocked for
# - %easyblocktype% - Shows what the player was blocked for in an eagler-kid readable form
# - %host% - The IP the player pinged
# - %help% - The configured help message for the block type
kick: |
<red>This %easyblocktype% is not allowed on the server!</red>
<dark_gray>»</dark_gray> <gray>%blocked%</gray> <dark_gray>«</dark_gray>
%help%
<gray>Think this is a mistake? Join our discord:</gray>
<blue>discord.gg/changethisintheconfig</blue>
# Please note that help is only supported in the kick message, not the MOTD
help:
generic: "<gray>Please switch to a different %easyblocktype%.</gray>"
player: "<gray>Please change your %easyblocktype%.</gray>"
motd:
enabled: true
text: |
<red>This %easyblocktype% is not allowed!</red>
<dark_gray>»</dark_gray> <gray>%blocked%</gray> <dark_gray>«</dark_gray>
icon: "blacklisted.png"
# Origin + Brand blacklist supports wildcards
# Everything should be lowercase
blacklist:
origins:
- "hack.example.com"
brands:
- "*dragonx*"
- "*piclient*"
players:
- "Admin"
discord:
webhook: ""
# :>

View File

@@ -1,9 +1,12 @@
name: OriginBlacklist name: ${plugin_name}
version: ${version} version: ${plugin_vers}
main: dev.colbster937.originblacklist.bukkit.OriginBlacklistBukkit main: xyz.webmc.${plugin_iden}.bukkit.${plugin_name}Bukkit
description: ${description} description: ${plugin_desc}
author: Colbster937 website: ${plugin_site}
depend: authors: ${plugin_athr}
- EaglercraftXServer contributors: ${plugin_ctbr}
depend: ${plugin_depa}
provides: ${plugin_prov}
softdepend: ${plugin_sdpa}
commands: commands:
originblacklist: ${plugin_iden}:

View File

@@ -1,14 +1,10 @@
{ {
"id": "originblacklist", "id": "${plugin_iden}",
"name": "OriginBlacklist", "name": "${plugin_name}",
"version": "${version}", "version": "${plugin_vers}",
"description": "${description}", "description": "${plugin_desc}",
"main": "dev.colbster937.originblacklist.velocity.OriginBlacklistVelocity", "website": "${plugin_site}",
"authors": ["Colbster937"], "main": "xyz.webmc.${plugin_iden}.velocity.${plugin_name}Velocity",
"dependencies": [ "authors": ${plugin_athr},
{ "dependencies": ${plugin_depc}
"id": "eaglerxserver",
"optional": false
}
]
} }