Compare commits
No commits in common. "master" and "rewrite" have entirely different histories.
3
.gitmodules
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
[submodule "paws/Lib/izzylib"]
|
||||
path = paws/Lib/izzylib
|
||||
url = https://git.barkshark.xyz/izaliamae/izzylib.git
|
614
LICENSE
|
@ -1,614 +0,0 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http s ://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 s ue 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 <http s ://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 <http
|
||||
s ://www.gnu.org/licenses/>.
|
178
README.md
|
@ -1,178 +0,0 @@
|
|||
# ![PAWS logo](https://git.barkshark.xyz/izaliamae/paws/raw/branch/master/paws/templates/media/logo-small.png "PAWS logo") Protection Against Web Scrapers (PAWS)
|
||||
|
||||
Web proxy for Mastodon that puts public profiles behind an auth layer.
|
||||
|
||||
## How it works
|
||||
|
||||
PAWS sits between Mastodon and your front-facing web proxy to intercept incoming requests. If a profile, toot, or any related json is requested, it will be blocked unless authenticated. If authenticated fetches on mastodon are disabled, PAWS will check signatures instead
|
||||
|
||||
## Installation
|
||||
|
||||
Python 3.6.0+ (3.8.0 recommended)
|
||||
|
||||
`python3 -m pip install -r requirements.txt --user`
|
||||
|
||||
## Configuration
|
||||
|
||||
data/production.env:
|
||||
|
||||
```
|
||||
# Path to mastodon instance. Defaults to current working dir
|
||||
MASTOPATH=/home/mastodon/glitch-soc
|
||||
|
||||
# The address to mastodon
|
||||
MASTOHOST=localhost:3000
|
||||
|
||||
# Listen address and port for PAWS. Can safely be ignored if running on same host as web server
|
||||
PAWS_HOST=127.0.0.1
|
||||
PAWS_PORT=3001
|
||||
|
||||
# Domain to list in the actor. Only needed if you plan on using the whitelist
|
||||
PAWS_DOMAIN=bappypaws.example.com
|
||||
```
|
||||
|
||||
Extra environment variables (cannot be put in production.env):
|
||||
- LOGDATE: boolean (default: yes). Set to no to remove access times from the console log
|
||||
|
||||
If Mastodon is on a different host, you'll have to copy Mastodon's .env.production to the working directory or mount the Mastodon directory to make it accessible to PAWS
|
||||
|
||||
### Caddy
|
||||
|
||||
Append this to caddy's mastodon config:
|
||||
|
||||
```
|
||||
rewrite {
|
||||
if_op and
|
||||
if {path} starts_with /users
|
||||
if {path} not_ends_with inbox
|
||||
to {path} /auth/{path}
|
||||
}
|
||||
|
||||
rewrite {
|
||||
if_op or
|
||||
if {path} starts_with /@
|
||||
if {path} starts_with /paws
|
||||
to {path} /auth/{path}
|
||||
}
|
||||
|
||||
proxy /auth localhost:3001 {
|
||||
without /auth
|
||||
transparent
|
||||
}
|
||||
```
|
||||
|
||||
Config for PAWS domain:
|
||||
|
||||
```
|
||||
paws.bappypaws.example.com {
|
||||
proxy / localhost:3001 {
|
||||
transparent
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Nginx
|
||||
|
||||
Append this to the mastodon config (Thanks to [@finkeldoodle@transfur.online](https://transfur.online/@frinkeldoodle) for the conversion)
|
||||
|
||||
```
|
||||
## Note: Order of location blocks is IMPORTANT.
|
||||
## Nginx matches longest non-regex location block, then **FIRST** matching regex block takes preference.
|
||||
## (regex blocks are ones with ~ or ~* before the path)
|
||||
|
||||
## This file is designed to be dropped into the Mastodon server block, probably before all the location blocks.
|
||||
|
||||
## If starts with /users, ends with inbox, bypass filter
|
||||
location ~* ^/users[\s\S]*inbox {
|
||||
try_files $uri @proxy;
|
||||
}
|
||||
|
||||
## If starts with /users, /@, or /paws, enter filter
|
||||
location ~* ^/(users|@|paws) {
|
||||
try_files '' @paws;
|
||||
}
|
||||
|
||||
|
||||
location @paws {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header Proxy "";
|
||||
proxy_pass_header Server;
|
||||
|
||||
proxy_pass http://localhost:3001;
|
||||
}
|
||||
```
|
||||
|
||||
Config for PAWS domain:
|
||||
|
||||
```
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name paws.bappypaws.example.com;
|
||||
root /home/mastodon/live/public;
|
||||
location /.well-known/acme-challenge/ { allow all; }
|
||||
location / { return 301 https://$host$request_uri; }
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name paws.bappypaws.example.com;
|
||||
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
|
||||
# Uncomment these lines once you acquire a certificate:
|
||||
# ssl_certificate /etc/letsencrypt/live/paws.bappypaws.example.com/fullchain.pem;
|
||||
# ssl_certificate_key /etc/letsencrypt/live/paws.bappypaws.example.com/privkey.pem;
|
||||
|
||||
keepalive_timeout 70;
|
||||
sendfile on;
|
||||
client_max_body_size 80m;
|
||||
|
||||
gzip on;
|
||||
gzip_disable "msie6";
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_buffers 16 8k;
|
||||
gzip_http_version 1.1;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000";
|
||||
|
||||
location / {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header Proxy "";
|
||||
proxy_pass_header Server;
|
||||
|
||||
proxy_pass http://localhost:3001;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Mastodon
|
||||
|
||||
While it isn't necessary, I highly recommend turning on authorized fetches (v3.0+) to let PAWS pass json requests directly through to mastodon. Also upgrade to at least v3.0 to be able to properly interact with other instances that have auth fetches turned on.
|
||||
|
||||
.env.production:
|
||||
|
||||
```
|
||||
AUTHORIZED_FETCH=true
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Start the server with `./server.py`. If you want to edit the config, just run `./server.py edit`.
|
||||
|
||||
## WebUI usage
|
||||
|
||||
If your account is an admin account according to Mastodon, you can manage the PAWS whitelist at {domain}/paws. Instances in this whitelist will have their fetches signed if they don't sign them themselves.
|
|
@ -1,13 +0,0 @@
|
|||
[Unit]
|
||||
Description = PAWS
|
||||
After = network.target
|
||||
[Service]
|
||||
User = [user]
|
||||
Group = [user]
|
||||
WorkingDirectory = /home/[user]/paws
|
||||
Environment = LOGDATE=no
|
||||
ExecStart = /usr/bin/python3 ./server.py
|
||||
Restart = always
|
||||
RestartSec = 3
|
||||
[Install]
|
||||
WantedBy = multi-user.target
|
1
paws/Lib/izzylib
Submodule
|
@ -0,0 +1 @@
|
|||
Subproject commit 2df57656b4a6a3c62bca24a6b49af450b34690cc
|
|
@ -1,14 +1,14 @@
|
|||
from os.path import dirname, abspath
|
||||
from IzzyLib import logging, template
|
||||
from IzzyLib.misc import config_dir
|
||||
###
|
||||
# PAWS
|
||||
# by Zoey Mae - https://git.barkshark.xyz/izaliamae/paws
|
||||
###
|
||||
__version__ = '0.1'
|
||||
|
||||
|
||||
stor_path = config_dir(__file__)
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
logging.setConfig({'level': 'info'})
|
||||
logging.debug(f'Config: {logging.getConfig()}')
|
||||
syspath = Path(__file__).parent.joinpath('Lib')
|
||||
|
||||
templates = abspath(dirname(__file__))+'/templates'
|
||||
template.addSearchPath(templates)
|
||||
template.addBuildPath('default', templates+'/pages', stor_path+'/templates')
|
||||
template.setup()
|
||||
for path in syspath.iterdir():
|
||||
sys.path.insert(0, str(path))
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
#!/usr/bin/env python3
|
||||
from .routes import main
|
||||
from IzzyLib import logging
|
||||
|
||||
main()
|
||||
from .server import start
|
||||
|
||||
|
||||
start()
|
||||
|
|
184
paws/config.py
|
@ -1,32 +1,32 @@
|
|||
import sys
|
||||
import os
|
||||
import os, sys, sanic, socket
|
||||
|
||||
from os import environ as env
|
||||
from os.path import isdir, isfile, abspath, dirname, basename
|
||||
|
||||
from IzzyLib import logging, __version__ as IzzyVersion
|
||||
from IzzyLib.misc import DefaultDict, DotDict, Path, Boolean, GetIp, RandomGen
|
||||
from IzzyLib.template import Template
|
||||
from envbash import load_envbash
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.misc import boolean
|
||||
|
||||
VERSION = '0.3.0b'
|
||||
|
||||
full_path = abspath(sys.executable) if getattr(sys, 'frozen', False) else abspath(__file__)
|
||||
script_path = getattr(sys, '_MEIPASS', dirname(abspath(__file__)))
|
||||
script_name = basename(full_path)
|
||||
stor_path = abspath(f'{os.getcwd()}/data')
|
||||
from . import __version__ as Version
|
||||
|
||||
|
||||
if not isdir(stor_path):
|
||||
os.makedirs(stor_path, exist_ok=True)
|
||||
dbtypes = ['sqlite', 'postgresql', 'mysql', 'mssql']
|
||||
|
||||
|
||||
if not boolean(env.get('LOGDATE', 'yes').lower()):
|
||||
logging.setConfig({'date': False})
|
||||
script_path = Path(__file__).parent()
|
||||
store_path = script_path.parent(True).join('data')
|
||||
pyenv = store_path.join('prod.env')
|
||||
|
||||
|
||||
if not isfile(f'{stor_path}/production.env'):
|
||||
logging.error(f'PAWS environment file doesn\'t exist: {stor_path}/production.env')
|
||||
logging.info('Creating a new config file. Be sure to edit it and restart PAWS')
|
||||
if not store_path.exists():
|
||||
store_path.mkdir()
|
||||
|
||||
|
||||
try:
|
||||
load_envbash(pyenv.str())
|
||||
|
||||
except FileNotFoundError:
|
||||
logging.error('Bash environment file not found:', pyenv.str())
|
||||
|
||||
new_config = '''###
|
||||
# Uncomment and adjust any values as necessary
|
||||
|
@ -36,11 +36,13 @@ if not isfile(f'{stor_path}/production.env'):
|
|||
#PAWS_HOST=127.0.0.1
|
||||
#PAWS_PORT=3001
|
||||
|
||||
#PAWS_DOMAIN=bappypaws.example.com
|
||||
#PAWS_NORSS=true
|
||||
|
||||
### Require approval for unknown instances. They can be accepted or denied at {{MASTODOMAIN}}/paws/list/requests
|
||||
#PAWS_REQ_APPROVAL=false
|
||||
### Set the paws db name at minimum. All other db options will get pulled from mastodon if not set
|
||||
#PAWS_DB_NAME=paws
|
||||
#PAWS_DB_HOST=/var/run/postgresql
|
||||
#PAWS_DB_PORT=5432
|
||||
#PAWS_DB_USER=mastodon
|
||||
#PAWS_DB_PASS=
|
||||
#PAWS_DB_MAXCONNECTIONS=25
|
||||
|
||||
### Override domain in mastodon's config
|
||||
#MASTODOMAIN=mastodon.example.com
|
||||
|
@ -50,43 +52,119 @@ if not isfile(f'{stor_path}/production.env'):
|
|||
#MASTOHOST=localhost:3000
|
||||
'''
|
||||
|
||||
with open(f'{stor_path}/production.env', 'w') as pawsconf:
|
||||
pawsconf.write(new_config)
|
||||
with pyenv.open('w') as fd:
|
||||
fd.write(new_config)
|
||||
|
||||
logging.info(f'Created new config at {stor_path}/production.env')
|
||||
logging.info('Created a new environment file. Now exiting.')
|
||||
sys.exit()
|
||||
|
||||
|
||||
masto_path = Path(env.get('MASTOPATH')) if env.get('MASTOPATH') else None
|
||||
mastoenv = masto_path.join('.env.production')
|
||||
|
||||
if not masto_path:
|
||||
logging.error('"MASTOPATH" in environment file is not set')
|
||||
sys.exit()
|
||||
|
||||
elif not mastoenv.exists():
|
||||
logging.error('Cannot find Mastodon\'s ".env.production"')
|
||||
sys.exit()
|
||||
|
||||
load_envbash(mastoenv.str())
|
||||
|
||||
|
||||
listen = env.get('PAWS_HOST', '127.0.0.1')
|
||||
port = int(env.get('PAWS_PORT', 3001))
|
||||
user = env.get('USER', 'paws')
|
||||
|
||||
config = DotDict({
|
||||
'env': pyenv,
|
||||
'path': script_path,
|
||||
'data': store_path,
|
||||
'frontend': script_path.join('frontend', True),
|
||||
'version': Version,
|
||||
'dbversion': 20210203,
|
||||
'listen': listen,
|
||||
'port': port,
|
||||
'host': f'{listen}:{port}',
|
||||
'salt': env.get('PASS_SALT', RandomGen(40)),
|
||||
'secret': env.get('FORWARDED_SECRET', RandomGen(20)),
|
||||
'log': DotDict({
|
||||
'level': env.get('LOG_LEVEL', 'INFO').upper(),
|
||||
'errors': Boolean(env.get('LOG_ERRORS')),
|
||||
'date': Boolean(env.get('LOG_DATE', True))
|
||||
}),
|
||||
'proxy': DotDict({
|
||||
'proxy_type': env.get('PROXY_TYPE', 'https'),
|
||||
'proxy_host': env.get('PROXY_HOST', None),
|
||||
'proxy_port': env.get('PROXY_PORT', 443)
|
||||
}),
|
||||
'mastodon': DotDict({
|
||||
'domain': env.get('LOCAL_DOMAIN'),
|
||||
'web_domain': env.get('WEB_DOMAIN', env.get('LOCAL_DOMAIN')),
|
||||
'alt_domains': [v for v in env.get('ALTERNATIVE_DOMAINS', '').split(',')],
|
||||
'path': masto_path,
|
||||
'host': env.get('MASTOHOST', 'localhost:3000')
|
||||
}),
|
||||
'db': DotDict({
|
||||
'host': env.get('PAWS_DB_HOST', env.get('DB_HOST', '/var/run/postgresql')),
|
||||
'port': int(env.get('PAWS_DB_PORT', env.get('DB_PORT', 5432))),
|
||||
'user': env.get('PAWS_DB_USER', env.get('DB_USER', user)),
|
||||
'pass': env.get('PAWS_DB_PASS', env.get('DB_PASS')),
|
||||
'name': env.get('PAWS_DB_NAME', 'paws'),
|
||||
'maxconnections': int(env.get('PAWS_DB_MAXCONNECTIONS', 25))
|
||||
}),
|
||||
'mastodb': DotDict({
|
||||
'host': env.get('DB_HOST', '/var/run/postgresql'),
|
||||
'port': int(env.get('DB_PORT', 5432)),
|
||||
'user': env.get('DB_USER', user),
|
||||
'password': env.get('DB_PASS'),
|
||||
'database': env.get('DB_NAME', 'mastodon_production'),
|
||||
'maxconnections': int(env.get('PAWS_DB_MAXCONNECTIONS', 25))
|
||||
}),
|
||||
'sqfile': store_path.join(env.get('SQ_DATABASE', 'database.sqlite3'))
|
||||
})
|
||||
|
||||
config.agent = f'IzzyLib/{IzzyVersion} (Barkshark-Social/{Version}; +https://{config.mastodon.web_domain}/)',
|
||||
|
||||
if not config.log.date:
|
||||
log_date = ''
|
||||
|
||||
else:
|
||||
load_envbash(f'{stor_path}/production.env')
|
||||
log_date = '[%(asctime)s] '
|
||||
|
||||
logging.setConfig({'level': config.log.level})
|
||||
config.data.join('template').mkdir()
|
||||
|
||||
req_approval = boolean(env.get('PAWS_REQ_APPROVAL'), False)
|
||||
config.template = Template(
|
||||
search=[
|
||||
config.data.join('template'),
|
||||
config.frontend
|
||||
],
|
||||
autoescape=False
|
||||
)
|
||||
|
||||
def Context(context, globals):
|
||||
config = globals.config
|
||||
request = context.request
|
||||
|
||||
PAWSCONFIG = {
|
||||
'host': env.get('PAWS_HOST', '127.0.0.1'),
|
||||
'port': int(env.get('PAWS_PORT', 3001)),
|
||||
'domain': env.get('PAWS_DOMAIN', 'bappypaws.example.com'),
|
||||
'disable_rss': boolean(env.get('PAWS_DISABLE_RSS', True)),
|
||||
'require_approval': req_approval,
|
||||
'mastopath': env.get('MASTOPATH', os.getcwd()),
|
||||
'mastohost': env.get('MASTOHOST', 'localhost:3000'),
|
||||
}
|
||||
try:
|
||||
user = request.cookie.user
|
||||
except AttributeError:
|
||||
user = None
|
||||
|
||||
with globals.mastodb.session() as s:
|
||||
data = {
|
||||
'cookie_user': user,
|
||||
'menu_left': user.config.get('menu_left', False) if user else False,
|
||||
'color_theme': request.cookies.get('theme', 'pink'),
|
||||
'settings': DefaultDict(),
|
||||
'var': {
|
||||
'base': 'https://'+request.headers.get('host', config.mastodon.web_domain),
|
||||
'name': s.get.config('site_title')
|
||||
}
|
||||
}
|
||||
|
||||
masto_path = PAWSCONFIG['mastopath']
|
||||
return data
|
||||
|
||||
if not isfile(f'{masto_path}/.env.production'):
|
||||
logging.error(f'Mastodon environment file doesn\'t exist: {masto_path}/.env.production')
|
||||
|
||||
else:
|
||||
load_envbash(f'{masto_path}/.env.production')
|
||||
|
||||
MASTOCONFIG={
|
||||
'domain': env.get('MASTODOMAIN', env.get('WEB_DOMAIN', env.get('LOCAL_DOMAIN', 'localhost:3000'))),
|
||||
'auth_fetch': boolean(env.get('AUTHORIZED_FETCH')),
|
||||
'dbhost': env.get('DB_HOST', '/var/run/postgresql'),
|
||||
'dbport': int(env.get('DB_PORT', 5432)),
|
||||
'dbname': env.get('DB_NAME', 'mastodon_production'),
|
||||
'dbuser': env.get('DB_USER', env.get('USER')),
|
||||
'dbpass': env.get('DB_PASS')
|
||||
}
|
||||
config.template.func_context = Context
|
||||
|
|
518
paws/database.py
|
@ -1,338 +1,262 @@
|
|||
import sys
|
||||
import urllib3
|
||||
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
from json.decoder import JSONDecodeError
|
||||
import sys, traceback
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.cache import LRUCache
|
||||
from IzzyLib.misc import boolean
|
||||
from DBUtils.PooledPg import PooledPg as DB
|
||||
from tinydb import TinyDB, Query, where
|
||||
from tinydb_smartcache import SmartCacheTable
|
||||
from tinyrecord import transaction as trans
|
||||
from tldextract import extract
|
||||
from Crypto.PublicKey import RSA
|
||||
from mastodon import Mastodon
|
||||
from mastodon.Mastodon import MastodonUnauthorizedError, MastodonBadGatewayError, MastodonNetworkError
|
||||
from IzzyLib.misc import DotDict, RandomGen
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.exc import OperationalError, ProgrammingError
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from .config import stor_path, PAWSCONFIG, MASTOCONFIG as mdb
|
||||
from .functions import fetch, get_nodeinfo
|
||||
from .config import config
|
||||
from .database_func import Get, Put, Migrate
|
||||
from .database_schema import tables, Base
|
||||
from .database_mastodon import DB
|
||||
from .functions import Datetime
|
||||
|
||||
|
||||
def jsondb():
|
||||
try:
|
||||
db = TinyDB(f'{stor_path}/db.json', indent=4)
|
||||
|
||||
except JSONDecodeError as e:
|
||||
logging.critical(f'Failed to load DB: {e}. Exiting...')
|
||||
sys.exit()
|
||||
|
||||
db.table_class = SmartCacheTable
|
||||
|
||||
class table:
|
||||
keys = db.table('keys')
|
||||
instances = db.table('instances')
|
||||
users = db.table('users')
|
||||
whitelist = db.table('whitelist')
|
||||
request = db.table('request')
|
||||
|
||||
return table
|
||||
class DataBase():
|
||||
def __init__(self, tables=None, dbtype='postgresql+psycopg2', **kwargs):
|
||||
self.engine_string = self.__engine_string(dbtype, kwargs)
|
||||
self.db = create_engine(self.engine_string)
|
||||
self.table = tables
|
||||
self.classes = CustomRows()
|
||||
self.session = lambda : Session(self)
|
||||
|
||||
|
||||
def pgdb():
|
||||
try:
|
||||
if mdb['dbpass']:
|
||||
return DB(dbname=mdb['dbname'], host=mdb['dbhost'], port=mdb['dbport'], user=mdb['dbuser'], passwd=mdb['dbpass']).connection()
|
||||
|
||||
else:
|
||||
return DB(dbname=mdb['dbname'], host=mdb['dbhost'], port=mdb['dbport'], user=mdb['dbuser']).connection()
|
||||
|
||||
except Exception as e:
|
||||
logging.critical(f'Failed to connect to DB: {e}. Exiting...')
|
||||
sys.exit()
|
||||
|
||||
|
||||
def keys(actor):
|
||||
if pawsdb.keys.get(query.actor == actor) == None:
|
||||
logging.info(f'No RSA key. Generating one for {actor}...')
|
||||
PRIV = RSA.generate(4096)
|
||||
PUB = PRIV.publickey()
|
||||
|
||||
keydata = {
|
||||
'actor': actor,
|
||||
'pubkey': PUB.exportKey('PEM').decode('utf-8'),
|
||||
'privkey': PRIV.exportKey('PEM').decode('utf-8')
|
||||
}
|
||||
|
||||
with trans(pawsdb.keys) as tr:
|
||||
tr.insert(keydata)
|
||||
|
||||
|
||||
return pawsdb.keys.get(query.actor == actor)
|
||||
|
||||
|
||||
def get_handle(userid):
|
||||
user_data = mastodb.query(f'SELECT username,domain FROM public.accounts WHERE id = \'{userid}\'').dictresult()
|
||||
|
||||
if len(user_data) < 1:
|
||||
return
|
||||
|
||||
return (user_data[0]['username'].lower(), user_data[0]['domain'].lower())
|
||||
|
||||
|
||||
def get_user(handle):
|
||||
user_data = mastodb.query(f'SELECT * FROM public.accounts WHERE username = \'{handle}\' and domain is NULL').dictresult()
|
||||
return user_data[0] if len(user_data) > 0 else None
|
||||
|
||||
|
||||
def get_toot(tootid):
|
||||
toot = mastodb.query(f'SELECT * FROM public.statuses WHERE id = \'{tootid}\'').dictresult()
|
||||
return toot[0] if len(toot) > 0 else None
|
||||
|
||||
|
||||
def get_bans(suspend=True, details=False):
|
||||
domains = mastodb.query('SELECT * FROM public.domain_blocks;').dictresult()
|
||||
banlist = {} if details else []
|
||||
|
||||
for domain in domains:
|
||||
instance = domain['domain']
|
||||
severity = domain['severity']
|
||||
|
||||
if suspend and severity != 1:
|
||||
continue
|
||||
|
||||
if details:
|
||||
banlist[instance] = {
|
||||
'severity': domain['severity'],
|
||||
'media': boolean(domain['reject_media']),
|
||||
'reports': boolean(domain['reject_reports']),
|
||||
'private': domain['private_comment'],
|
||||
'public': domain['public_comment'],
|
||||
'updated': domain['updated_at']
|
||||
}
|
||||
|
||||
else:
|
||||
banlist.append(instance)
|
||||
|
||||
return banlist
|
||||
|
||||
|
||||
def banned_user_check(access_user):
|
||||
if not access_user:
|
||||
return
|
||||
|
||||
users = mastodb.query('SELECT username, domain FROM accounts WHERE suspended_at is not NULL').dictresult()
|
||||
|
||||
if not users:
|
||||
return
|
||||
|
||||
allbans = [(user['username'].lower(), user['domain'].lower()) for user in users]
|
||||
|
||||
if access_user in allbans:
|
||||
return True
|
||||
|
||||
|
||||
def ban_check(url):
|
||||
instance = urlparse(url).netloc if url.startswith('http') else url
|
||||
domain = extract(url)
|
||||
parsed = f'{domain.domain}.{domain.suffix}'
|
||||
banlist = get_bans()
|
||||
|
||||
for ban in banlist:
|
||||
if parsed in ban or parsed == ban:
|
||||
return True
|
||||
|
||||
logging.debug(f'{parsed} not in blocklist')
|
||||
|
||||
|
||||
def user_ban_check(user, access_user):
|
||||
user_data = mastodb.query(f'SELECT id FROM public.accounts WHERE LOWER(username) = \'{user}\' and domain is NULL').dictresult()
|
||||
|
||||
if len(user_data) < 1:
|
||||
return
|
||||
|
||||
userid = user_data[0]['id']
|
||||
userban_query = mastodb.query(f'SELECT * FROM public.blocks WHERE account_id = \'{userid}\'').dictresult()
|
||||
userbans = []
|
||||
|
||||
for ban in userban_query:
|
||||
acct_id = ban['target_account_id']
|
||||
user = get_handle(acct_id)
|
||||
def __engine_string(self, dbtype, kwargs):
|
||||
engine_string = dbtype + '://'
|
||||
user = kwargs.get('user')
|
||||
password = kwargs.get('pass')
|
||||
host = kwargs.get('host', '/var/run/postgresql')
|
||||
port = kwargs.get('port', 5432)
|
||||
name = kwargs.get('name', 'postgres')
|
||||
maxconn = kwargs.get('maxconnections', 25)
|
||||
|
||||
if user:
|
||||
userbans.append(user)
|
||||
if password:
|
||||
engine_string += f'{user}:{password}@'
|
||||
else:
|
||||
engine_string += user + '@'
|
||||
|
||||
if host == '/var/run/postgresql':
|
||||
engine_string += '/' + name
|
||||
|
||||
else:
|
||||
logging.warning(f'Invalid userid: {acct_id}')
|
||||
engine_string += f'{host}:{port}/{name}'
|
||||
|
||||
if access_user in userbans:
|
||||
return True
|
||||
|
||||
return False
|
||||
return engine_string
|
||||
|
||||
|
||||
def user_domain_ban_check(handle, access_domain):
|
||||
user_data = get_user(handle)
|
||||
def CreateDatabase(self):
|
||||
if self.engine_string.startswith('postgresql'):
|
||||
predb = create_engine(db.engine_string.replace(config.db.name, 'postgres', -1))
|
||||
conn = predb.connect()
|
||||
conn.execute('commit')
|
||||
|
||||
if not user_data:
|
||||
return
|
||||
try:
|
||||
conn.execute(f'CREATE DATABASE {config.db.name}')
|
||||
|
||||
userid = user_data['id']
|
||||
ban_data = mastodb.query(f'SELECT * FROM public.account_domain_blocks WHERE account_id = \'{userid}\' and domain = \'{access_domain}\'').dictresult()
|
||||
except ProgrammingError:
|
||||
'The database already exists, so just move along'
|
||||
|
||||
return ban_data
|
||||
except Exception as e:
|
||||
conn.close()
|
||||
raise e from None
|
||||
|
||||
conn.close()
|
||||
|
||||
Base.metadata.create_all(self.db)
|
||||
|
||||
|
||||
def wl_check(domain):
|
||||
data = pawsdb.whitelist.get(query.domain == domain)
|
||||
return data
|
||||
def execute(self, *args, **kwargs):
|
||||
with self.session() as s:
|
||||
return s.execute(*args, **kwargs)
|
||||
|
||||
|
||||
def admin_check(handle):
|
||||
user = get_user(handle)
|
||||
class Session(object):
|
||||
def __init__(self, db):
|
||||
self.db = db
|
||||
self.classes = self.db.classes
|
||||
self.session = sessionmaker(bind=db.db)()
|
||||
self.table = self.db.table
|
||||
self.cache = DotDict()
|
||||
|
||||
if not user:
|
||||
return
|
||||
# session aliases
|
||||
self.s = self.session
|
||||
self.commit = self.s.commit
|
||||
self.rollback = self.s.rollback
|
||||
self.query = self.s.query
|
||||
self.execute = self.s.execute
|
||||
|
||||
userid = user['id']
|
||||
user_data = mastodb.query(f'SELECT * FROM public.users WHERE account_id = \'{userid}\'').dictresult()
|
||||
# extra function aliases
|
||||
self.get = Get(self)
|
||||
self.put = Put(self)
|
||||
|
||||
if not user_data or not user_data[0]['admin']:
|
||||
return
|
||||
|
||||
return True
|
||||
for name in self.table.keys():
|
||||
self.cache[name] = LRUCache()
|
||||
|
||||
|
||||
def whitelist(action, instance):
|
||||
domain = pawsdb.whitelist.get(query.domain == instance)
|
||||
|
||||
if action == 'add':
|
||||
if not domain:
|
||||
with trans(pawsdb.whitelist) as tr:
|
||||
tr.insert({'domain': instance})
|
||||
|
||||
elif action == 'remove':
|
||||
if domain:
|
||||
with trans(pawsdb.whitelist) as tr:
|
||||
tr.remove(query.domain == instance)
|
||||
|
||||
else:
|
||||
return 'InvalidAction'
|
||||
def __enter__(self):
|
||||
self.sessionid = RandomGen(10)
|
||||
return self
|
||||
|
||||
|
||||
def get_instances(domain=None, state=None):
|
||||
if domain:
|
||||
rows = pawsdb.instances.get(query.domain == domain)
|
||||
def __exit__(self, exctype, value, tb):
|
||||
if tb:
|
||||
self.rollback()
|
||||
#print(exctype, value)
|
||||
#traceback.print_tb(tb)
|
||||
|
||||
elif state:
|
||||
rows = pawsdb.instances.search(query.state == state)
|
||||
|
||||
else:
|
||||
rows = pawsdb.instances.all()
|
||||
|
||||
return rows
|
||||
else:
|
||||
self.commit()
|
||||
|
||||
|
||||
def instances(action, instance, state='request'):
|
||||
logging.debug(', '.join([action, instance, state]))
|
||||
|
||||
if None in [action, instance, state]:
|
||||
return False
|
||||
|
||||
domain = urlparse(instance).netloc if instance.startswith('http') else instance
|
||||
instance_data = pawsdb.instances.get(query.domain == domain)
|
||||
state = state.lower()
|
||||
|
||||
if action == 'add':
|
||||
if instance_data:
|
||||
logging.debug(f'Updating instance state: {domain}, {state}')
|
||||
with trans(pawsdb.instances) as tr:
|
||||
tr.update({'state': state}, doc_ids=[instance_data.doc_id])
|
||||
|
||||
return
|
||||
|
||||
ni_software = get_nodeinfo(domain)
|
||||
|
||||
if not ni_software:
|
||||
logging.debug(f'Failed to get nodeinfo data from instance: {domain}')
|
||||
return
|
||||
|
||||
data = {
|
||||
'domain': domain,
|
||||
'software': ni_software['name'],
|
||||
'state': state,
|
||||
'timestamp': datetime.timestamp(datetime.now())
|
||||
}
|
||||
|
||||
with trans(pawsdb.instances) as tr:
|
||||
tr.insert(data)
|
||||
|
||||
elif action == 'remove':
|
||||
if not instance_data:
|
||||
logging.debug(f'Domain not in request list: {domain}')
|
||||
|
||||
with trans(pawsdb.instances) as tr:
|
||||
tr.remove(doc_ids=[instance_data.doc_id])
|
||||
def count(self, table_name, **kwargs):
|
||||
return self.s.query(self.table[table_name]).filter_by(**kwargs).count()
|
||||
|
||||
|
||||
def instance_check(domain):
|
||||
timestamp = datetime.timestamp(datetime.now())
|
||||
instance = pawsdb.instances.get(query.domain == domain)
|
||||
state = instance.get('state') if instance else None
|
||||
|
||||
if not domain:
|
||||
return False
|
||||
|
||||
if state == 'accept' or domain == mdb['domain']:
|
||||
return True
|
||||
|
||||
elif state == 'deny':
|
||||
return False
|
||||
|
||||
elif not state:
|
||||
result = instances('add', domain)
|
||||
|
||||
return
|
||||
def execute(self, string, values=[]):
|
||||
return self.s.execute(string, values)
|
||||
|
||||
|
||||
def cleanup_users(invalid_check=None):
|
||||
timestamp = datetime.timestamp(datetime.now())
|
||||
invalid_offset = 60 * 15
|
||||
def fetch(self, table_name, single=True, **kwargs):
|
||||
RowClass = self.classes.get(table_name.capitalize())
|
||||
|
||||
with trans(pawsdb.users) as tr:
|
||||
for user in pawsdb.users.all():
|
||||
if not user.get('timestamp'):
|
||||
logging.debug(f'adding timestamp for user: {user["handle"]}@{user["domain"]}')
|
||||
tr.update({'timestamp': timestamp}, doc_ids=[user.doc_id])
|
||||
continue
|
||||
rows = self.s.query(self.table[table_name]).filter_by(**kwargs).all()
|
||||
|
||||
if invalid_check:
|
||||
if user['timestamp'] < timestamp - invalid_offset and not user['token']:
|
||||
logging.debug(f'old and incomplete access token for {user["handle"]}@{user["domain"]}')
|
||||
tr.remove(doc_ids=[user.doc_id])
|
||||
continue
|
||||
if single:
|
||||
return RowClass(rows[0], db, self) if len(rows) > 0 else None
|
||||
|
||||
else:
|
||||
if not user['token']:
|
||||
logging.debug(f'no access token for {user["handle"]}@{user["domain"]}')
|
||||
continue
|
||||
|
||||
client = Mastodon(api_base_url=user['domain'], access_token=user['token'])
|
||||
|
||||
try:
|
||||
client.me()
|
||||
logging.debug(f'valid token for {user["handle"]}@{user["domain"]}')
|
||||
|
||||
except MastodonUnauthorizedError:
|
||||
logging.debug(f'invalid token for {user["handle"]}@{user["domain"]}')
|
||||
tr.remove(doc_ids=[user.doc_id])
|
||||
|
||||
except (urllib3.exceptions.NewConnectionError, MastodonBadGatewayError, MastodonNetworkError):
|
||||
logging.debug(f'failed to connect to domain for {user["handle"]}@{user["domain"]}')
|
||||
return [RowClass(row, db, self) for row in rows]
|
||||
|
||||
|
||||
pawsdb = jsondb()
|
||||
query = Query()
|
||||
mastodb = pgdb()
|
||||
def insert(self, table_name, **kwargs):
|
||||
table = self.table[table_name]
|
||||
|
||||
if getattr(table, 'timestamp', None) and not kwargs.get('timestamp'):
|
||||
kwargs['timestamp'] = datetime.now()
|
||||
|
||||
data = self.s.add(table(**kwargs))
|
||||
return self.fetch(table_name, **kwargs)
|
||||
|
||||
|
||||
def DropTables(self):
|
||||
tables = self.GetTables()
|
||||
|
||||
for table in tables:
|
||||
self.s.execute(f'DROP TABLE {table}')
|
||||
|
||||
|
||||
def GetTables(self):
|
||||
rows = self.s.execute("SELECT name FROM sqlite_master WHERE type IN ('table','view') and name NOT LIKE 'sqlite_%'")
|
||||
return [row[0] for row in rows]
|
||||
|
||||
|
||||
class CustomRows(object):
|
||||
def get(self, name):
|
||||
return getattr(self, name, self.Row)
|
||||
|
||||
|
||||
class Row(DotDict):
|
||||
_filter_columns = lambda self, row: [attr for attr in dir(row) if not attr.startswith('_') and attr != 'metadata']
|
||||
|
||||
|
||||
def __init__(self, row, db, s):
|
||||
if not row:
|
||||
return
|
||||
|
||||
self._db = db
|
||||
self._table_name = row.__tablename__
|
||||
self._table = db.table[row.__tablename__]
|
||||
self._columns = self._filter_columns(row)
|
||||
|
||||
super().__init__()
|
||||
|
||||
for k in self._columns:
|
||||
v = getattr(row, k)
|
||||
|
||||
if type(v) == datetime:
|
||||
v = Datetime(v)
|
||||
|
||||
if type(v) == dict:
|
||||
v = DotDict(v)
|
||||
|
||||
self[k] = v
|
||||
|
||||
self.__run__(s)
|
||||
|
||||
|
||||
## Subclass Row and redefine this function
|
||||
def __run__(self, s):
|
||||
pass
|
||||
|
||||
|
||||
def _filter_data(self):
|
||||
data = {k: v for k,v in self.items() if k in self._columns}
|
||||
|
||||
for k,v in self.items():
|
||||
if v.__class__ == DotDict:
|
||||
data[k] = v.asDict()
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def asDict(self):
|
||||
return self._filter_data()
|
||||
|
||||
|
||||
def _update(self, new_data={}, **kwargs):
|
||||
kwargs.update(new_data)
|
||||
|
||||
for k,v in kwargs.items():
|
||||
self[k] = v
|
||||
|
||||
|
||||
def delete(self):
|
||||
with self._db.session() as s:
|
||||
row = s.query(self._table).filter_by(id=self.id)
|
||||
row.delete()
|
||||
|
||||
return True if not row.all() else False
|
||||
|
||||
|
||||
def delete_session(self, s):
|
||||
row = s.query(self._table).filter_by(id=self.id)
|
||||
row.delete()
|
||||
|
||||
return True if not row.all() else False
|
||||
|
||||
|
||||
def update(self, dict_data={}, **data):
|
||||
self._update(data)
|
||||
self._update(dict(dict_data))
|
||||
|
||||
data = self._filter_data()
|
||||
|
||||
with self._db.session() as s:
|
||||
s.query(self._table).filter_by(id=self.id).update(data)
|
||||
|
||||
|
||||
def update_session(self, s, dict_data={}, **data):
|
||||
self._update(data)
|
||||
self._update(dict_data)
|
||||
|
||||
data = self._filter_data()
|
||||
|
||||
row = s.query(self._table).filter_by(id=self.id)
|
||||
row.update(data)
|
||||
|
||||
|
||||
db = DataBase(tables, **config.db.asDict())
|
||||
mastodb = DB(**config.mastodb.asDict())
|
||||
|
||||
try:
|
||||
with db.session() as s:
|
||||
config_version = s.get.config('version', 0)
|
||||
except (OperationalError, ProgrammingError):
|
||||
config_version = 0
|
||||
|
||||
if config_version < config.dbversion:
|
||||
Migrate(config_version, db)
|
||||
|
|
154
paws/database_func.py
Normal file
|
@ -0,0 +1,154 @@
|
|||
import sys, traceback
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.misc import Boolean, DefaultDict, DotDict, RandomGen
|
||||
from datetime import datetime, timedelta
|
||||
from sqlalchemy_paginator import Paginator
|
||||
|
||||
from .config import config
|
||||
from .functions import Datetime
|
||||
|
||||
|
||||
subtypes = {
|
||||
'str': str,
|
||||
'int': int,
|
||||
'bool': Boolean,
|
||||
'datetime': int
|
||||
}
|
||||
|
||||
|
||||
config_defaults = {
|
||||
'version': [config.dbversion, 'int'],
|
||||
'require_allow': [False, 'bool']
|
||||
}
|
||||
|
||||
|
||||
def SetupClass(self, session):
|
||||
self.session = session
|
||||
self.s = session.s
|
||||
self.classes = session.db.classes
|
||||
self.db = session.db
|
||||
|
||||
self.cache = session.cache
|
||||
self.count = session.count
|
||||
self.fetch = session.fetch
|
||||
self.insert = session.insert
|
||||
self.table = session.table
|
||||
|
||||
self.query = session.s.query
|
||||
self.execute = session.s.execute
|
||||
|
||||
|
||||
class Get():
|
||||
def __init__(self, session):
|
||||
SetupClass(self, session)
|
||||
|
||||
|
||||
def __parse_config(self, row):
|
||||
typefunc = subtypes[row.type] if row.type else str
|
||||
value = typefunc(row.value)
|
||||
|
||||
if row.key == 'emoji_size_limit':
|
||||
value = value * 1024
|
||||
|
||||
return Datetime(datetime.fromtimestamp(value)) if row.type == 'datetime' else value
|
||||
|
||||
|
||||
def config(self, key, default=None, cache=True):
|
||||
cached = self.cache.config.fetch(key)
|
||||
|
||||
if cached and cache:
|
||||
return cached
|
||||
|
||||
row = self.fetch('config', key=key)
|
||||
|
||||
if row:
|
||||
var = self.__parse_config(row)
|
||||
self.cache.config.store(key, var)
|
||||
|
||||
return var
|
||||
|
||||
if not default:
|
||||
value = config_defaults.get(key)
|
||||
return value * 1000 if key == 'emoji_size_limit' else value
|
||||
|
||||
return default
|
||||
|
||||
|
||||
def configs(self, cache=True):
|
||||
data = DotDict()
|
||||
|
||||
for key, value in config_defaults.items():
|
||||
data[key] = self.config(key, value, cache=cache)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def cookie(self, cache=True):
|
||||
return None
|
||||
|
||||
|
||||
class Put():
|
||||
def __init__(self, session):
|
||||
SetupClass(self, session)
|
||||
|
||||
|
||||
def config(self, key, value, subtype='str'):
|
||||
row = self.fetch('config', key=key)
|
||||
typefunc = subtypes[row.type] if row else str
|
||||
|
||||
if subtype == 'bool':
|
||||
new_value = 'True' if Boolean(value) else 'False'
|
||||
|
||||
else:
|
||||
new_value = int(value.timestamp()) if subtype == 'datetime' else typefunc(value)
|
||||
|
||||
if row:
|
||||
if row.value == new_value:
|
||||
return
|
||||
|
||||
row.value = new_value
|
||||
row.update_session(self.s)
|
||||
|
||||
else:
|
||||
self.insert('config',
|
||||
key=key,
|
||||
value=new_value,
|
||||
type=subtype
|
||||
)
|
||||
|
||||
self.cache.config.remove(key)
|
||||
|
||||
|
||||
def configs(self, *args):
|
||||
for config in args:
|
||||
key = config.get('key')
|
||||
value = config.get('value')
|
||||
subtype = config.get('subtype')
|
||||
|
||||
if None in [key, value]:
|
||||
logging.warning(f'db.put.configs: Missing key or value for config: key={key}, value={value}')
|
||||
continue
|
||||
|
||||
self.config(key, value, subtype)
|
||||
|
||||
|
||||
def Setup(db):
|
||||
try:
|
||||
db.CreateDatabase()
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
logging.error('Failed to create database. Exiting...')
|
||||
sys.exit()
|
||||
|
||||
with db.session() as s:
|
||||
for k,v in config_defaults.items():
|
||||
s.put.config(k, v[0], v[1])
|
||||
|
||||
|
||||
def Migrate(dbversion, db):
|
||||
if dbversion == 0:
|
||||
Setup(db)
|
||||
return
|
||||
|
||||
logging.info('Migrated database to version', config.dbversion)
|
243
paws/database_mastodon.py
Normal file
|
@ -0,0 +1,243 @@
|
|||
import psycopg2, traceback, sys, json
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.misc import Boolean, DotDict, Path
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from dbutils.pooled_db import PooledDB
|
||||
|
||||
|
||||
class DB(PooledDB):
|
||||
def __init__(self, **kwargs):
|
||||
kwargs['maxusage'] = 1
|
||||
super().__init__(psycopg2, **kwargs)
|
||||
|
||||
self.session = lambda : Session(self)
|
||||
|
||||
|
||||
def query(self, string, args: list=[]):
|
||||
with self.session() as s:
|
||||
return self.query(string, args)
|
||||
|
||||
|
||||
def fetch(self, *args, **kwargs):
|
||||
with self.session(False) as s:
|
||||
return self.fetch(*args, **kwargs)
|
||||
|
||||
|
||||
class Session(object):
|
||||
def __init__(self, db, trans=False):
|
||||
self.db = db
|
||||
self.trans = trans
|
||||
self.conn = None
|
||||
self.cursor = None
|
||||
self.get = Get(self)
|
||||
self.put = Put(self)
|
||||
|
||||
|
||||
def __enter__(self):
|
||||
self.conn = self.db.connection()
|
||||
|
||||
if self.trans:
|
||||
self.conn.begin()
|
||||
self.cursor = self.conn.cursor()
|
||||
|
||||
return self
|
||||
|
||||
|
||||
def __exit__(self, exctype, value, tb):
|
||||
self.cursor.close()
|
||||
|
||||
if self.trans:
|
||||
if tb:
|
||||
self.conn.rollback()
|
||||
#print(exctype, value)
|
||||
#traceback.print_tb(tb)
|
||||
|
||||
else:
|
||||
self.commit()
|
||||
|
||||
self.close()
|
||||
|
||||
|
||||
def close(self):
|
||||
self.conn.close()
|
||||
|
||||
|
||||
def query(self, string, values=[]):
|
||||
values = list(values)
|
||||
self.cursor.execute(string, values)
|
||||
return self.cursor
|
||||
|
||||
|
||||
def fetch(self, table, single=True, sort=None, **kwargs):
|
||||
rowid = kwargs.get('id')
|
||||
querysort = f'ORDER BY {sort}'
|
||||
|
||||
resultOpts = [self, table, self.cursor]
|
||||
|
||||
if rowid:
|
||||
rows = self.query(f"SELECT * FROM {table} WHERE id = ?", [rowid])
|
||||
|
||||
elif kwargs:
|
||||
placeholders = [f'{k} = %s' for k in kwargs.keys()]
|
||||
values = kwargs.values()
|
||||
|
||||
where = ' and '.join(placeholders)
|
||||
query = f"SELECT * FROM {table} WHERE {where} {querysort if sort else ''}"
|
||||
rows = self.query(query, values)
|
||||
|
||||
else:
|
||||
rows = self.query(f'SELECT * FROM {table} {querysort if sort else ""}')
|
||||
|
||||
rows = rows.fetchall() if not single else rows.fetchone()
|
||||
|
||||
if rows:
|
||||
if single:
|
||||
return DBResult(rows, *resultOpts)
|
||||
|
||||
return [DBResult(row, *resultOpts) for row in rows]
|
||||
|
||||
return None if single else []
|
||||
|
||||
|
||||
def insert(self, table, data={}, **kwargs):
|
||||
data.update(kwargs)
|
||||
placeholders = ",".join(['?' for _ in data.keys()])
|
||||
values = tuple(data.values())
|
||||
keys = ','.join(data.keys())
|
||||
|
||||
#if 'timestamp' in self.main.tables[table].keys() and 'timestamp' not in keys:
|
||||
#data['timestamp'] = datetime.now()
|
||||
|
||||
query = f'INSERT INTO {table} ({keys}) VALUES ({placeholders})'
|
||||
self.query(query, values)
|
||||
return True
|
||||
|
||||
|
||||
def remove(self, table, **kwargs):
|
||||
keys = []
|
||||
values = []
|
||||
|
||||
for k,v in kwargs.items():
|
||||
keys.append(k)
|
||||
values.append(v)
|
||||
|
||||
keydata = ','.join([f'{k} = ?' for k in keys])
|
||||
query = f'DELETE FROM {table} WHERE {keydata}'
|
||||
|
||||
self.query(query, values)
|
||||
|
||||
|
||||
def update(self, table, rowid, data={}, **kwargs):
|
||||
data.update(kwargs)
|
||||
newdata = {k: v for k, v in data.items() if k in self.main.tables[table].keys()}
|
||||
keys = list(newdata.keys())
|
||||
values = list(newdata.values())
|
||||
|
||||
if len(newdata) < 1:
|
||||
logging.debug('No data provided to update row')
|
||||
return False
|
||||
|
||||
query_data = ', '.join(f'{k} = ?' for k in keys)
|
||||
query = f'UPDATE {table} SET {query_data} WHERE id = {rowid}'
|
||||
|
||||
self.query(query, values)
|
||||
|
||||
|
||||
def count(self, table):
|
||||
data = self.query(f'SELECT COUNT(*) FROM {table}')
|
||||
return data.fetchone()[0]
|
||||
|
||||
|
||||
class Get():
|
||||
def __init__(self, session):
|
||||
ParseSession(self, session)
|
||||
|
||||
|
||||
def config(self, key, default=None):
|
||||
row = self.fetch('settings', var=key)
|
||||
|
||||
if not row:
|
||||
return default
|
||||
|
||||
return row.value[4:]
|
||||
|
||||
|
||||
def configs(self):
|
||||
data = DotDict()
|
||||
|
||||
for row in self.fetch('settings', single=False):
|
||||
data[row.var] = row.value
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class Put():
|
||||
def __init__(self, session):
|
||||
ParseSession(self, session)
|
||||
|
||||
|
||||
class DBResult(DotDict):
|
||||
def __init__(self, row, db, table, cursor):
|
||||
super().__init__()
|
||||
|
||||
self.db = db
|
||||
self.table = table
|
||||
self.columns = []
|
||||
|
||||
for idx, col in enumerate(cursor.description):
|
||||
self.columns.append(col[0])
|
||||
self[col[0]] = row[idx]
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self.json()
|
||||
|
||||
|
||||
def _filter_data(self):
|
||||
data = {k: v for k,v in self.items() if k in self.columns}
|
||||
|
||||
for k,v in data.items():
|
||||
if v.__class__ == DotDict:
|
||||
data[k] = v.asDict()
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def Dict(self):
|
||||
return self._filter_data()
|
||||
|
||||
|
||||
def Json(self, indent=None):
|
||||
data = self.asDict()
|
||||
|
||||
for k,v in data.items():
|
||||
if v.__class__ == datetime:
|
||||
data[k] = str(v)
|
||||
|
||||
return json.dumps(data, indent=indent)
|
||||
|
||||
|
||||
def Update(self, data={}):
|
||||
with self.db.session(True) as s:
|
||||
self.update(data)
|
||||
s.update(self.table, self.id, self.AsDict())
|
||||
|
||||
|
||||
def Remove(self):
|
||||
with self.db.session(True) as s:
|
||||
s.remove(self.table, id=self.id)
|
||||
|
||||
|
||||
def ParseSession(self, session):
|
||||
self.session = session
|
||||
self.db = session.db
|
||||
|
||||
# Basic function aliases
|
||||
self.query = session.query
|
||||
self.fetch = session.fetch
|
||||
self.insert = session.insert
|
||||
self.remove = session.remove
|
||||
self.update = session.update
|
||||
self.count = session.count
|
57
paws/database_schema.py
Normal file
|
@ -0,0 +1,57 @@
|
|||
from IzzyLib.misc import DotDict
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
|
||||
Base = declarative_base()
|
||||
tables = DotDict()
|
||||
|
||||
class Config(Base):
|
||||
__tablename__ = 'config'
|
||||
|
||||
id = Column('id', Integer, primary_key=True, autoincrement=True)
|
||||
key = Column('key', String, unique=True)
|
||||
value = Column('value', String)
|
||||
type = Column('type', String, default='str')
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return f'Config(id={self.id}, key="{self.key}", value="{self.value}", type="{self.type}")'
|
||||
|
||||
|
||||
class Cookie(Base):
|
||||
__tablename__ = 'cookie'
|
||||
|
||||
id = Column('id', Integer, primary_key=True, autoincrement=True)
|
||||
userid = Column('userid', Integer, nullable=False)
|
||||
token = Column('token', String, nullable=False, unique=True)
|
||||
access = Column('access', DateTime)
|
||||
timestamp = Column('timestamp', DateTime)
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return f'Cookie(id={self.id}, cookie="{self.cookie}")'
|
||||
|
||||
|
||||
class Domain(Base):
|
||||
__tablename__ = 'domain'
|
||||
|
||||
id = Column('id', Integer, primary_key=True, autoincrement=True)
|
||||
domain = Column('domain', String, nullable=False, unique=True)
|
||||
web_domain = Column('web_domain', String, nullable=False, unique=True)
|
||||
name = Column('name', String)
|
||||
admin = Column('admin', String)
|
||||
description = Column('description', String)
|
||||
allow = Column('allow', Boolean, default=False)
|
||||
timestamp = Column('timestamp', DateTime)
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return f'Domain(id={self.id}, domain="{self.domain}", name="{self.name}")'
|
||||
|
||||
|
||||
tables.update({
|
||||
'config': Config,
|
||||
'cookie': Cookie,
|
||||
'domain': Domain
|
||||
})
|
47
paws/errors.py
Normal file
|
@ -0,0 +1,47 @@
|
|||
import traceback
|
||||
|
||||
from sanic import response
|
||||
from sanic import exceptions as exc
|
||||
from IzzyLib import logging
|
||||
|
||||
from .database import db
|
||||
from .functions import Error
|
||||
|
||||
|
||||
@exc.add_status_code(418)
|
||||
class Teapot(exc.SanicException):
|
||||
pass
|
||||
|
||||
|
||||
def generic(request, exception):
|
||||
try:
|
||||
status = exception.status_code
|
||||
except:
|
||||
status = 500
|
||||
|
||||
if status == 400:
|
||||
print(exception)
|
||||
|
||||
return Error(request, status, str(exception))
|
||||
|
||||
|
||||
def server_error(request, exception):
|
||||
if not request:
|
||||
logging.debug('Empty request')
|
||||
return
|
||||
|
||||
traceback.print_exc()
|
||||
msg = 'OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our headquarters are working VEWY HAWD to fix this!'
|
||||
return Error(request, 500, msg)
|
||||
|
||||
|
||||
def orm_detached_instance(request, exception):
|
||||
msg = 'Sqlalchemy is fucking up again :/'
|
||||
#return response.text(msg, status=500)
|
||||
return Error(request, 500, msg)
|
||||
|
||||
|
||||
def missing_template(request, exception):
|
||||
logging.error(f'This template is missing: {exception}, {request.path}')
|
||||
msg = f'I\'m a dumbass and forgot to create this template: {str(exception)}'
|
||||
return response.text(msg, status=500)
|
68
paws/frontend/base.haml
Normal file
|
@ -0,0 +1,68 @@
|
|||
<!DOCTYPE html>
|
||||
%html
|
||||
%head
|
||||
%title << {{var.name}}: {{page}}
|
||||
%link rel='stylesheet' type='text/css' href='{{var.base}}/paws/style-{{CssTimestamp("style")}}.css'
|
||||
%meta charset='UTF-8'
|
||||
%meta name='viewport' content='width=device-width, initial-scale=1'
|
||||
|
||||
%body
|
||||
#body
|
||||
#header.flex-container
|
||||
-if menu_left
|
||||
#btn.section
|
||||
.page-title.section -> %a.title href='{{var.base}}/paws' << {{var.name}}
|
||||
|
||||
-else
|
||||
.page-title.section -> %a.title href='{{var.base}}/paws' << {{var.name}}
|
||||
#btn.section
|
||||
|
||||
-if message
|
||||
#message.section << {{message}}
|
||||
|
||||
-if error
|
||||
#error.secion << {{error}}
|
||||
|
||||
#menu.section
|
||||
.title-item.item << Menu
|
||||
#items
|
||||
.item -> %a href='{{var.base}}/' << Home
|
||||
-if settings.rules
|
||||
%a.item href='{{var.base}}/about/rules' << Rules
|
||||
%a.item href='{{var.base}}/about' << About
|
||||
|
||||
-if cookie_user
|
||||
%a.item.name href='{{var.base}}/@{{cookie_user.handle}}' << Profile
|
||||
%details open
|
||||
%summary.item << Preferences
|
||||
%a.item.sub-item href='{{var.base}}/preferences/profile' << Profile
|
||||
|
||||
-if cookie_user and cookie_user.permissions < 3
|
||||
%details open
|
||||
%summary.item << Admin
|
||||
%a.item.sub-item href='{{var.base}}/admin/dashboard' << Dashboard
|
||||
%a.item.sub-item href='{{var.base}}/admin/settings' << Settings
|
||||
%a.item href='{{var.base}}/logout' << Logout
|
||||
|
||||
-else
|
||||
%a.item href='{{var.base}}/login' << Login
|
||||
%a.item href='{{var.base}}/register' << Register
|
||||
|
||||
#content-body.section
|
||||
-block content
|
||||
|
||||
#footer.grid-container.section
|
||||
-if cookie_user
|
||||
.avatar
|
||||
%img src='{{var.base}}/{{cookie_user.avatar}}?20'
|
||||
|
||||
.user
|
||||
%a href='{{base}}/@{{cookie_user.handle}}' -> =cookie_user.name
|
||||
-else
|
||||
.user
|
||||
Guest
|
||||
|
||||
.source
|
||||
%a href='https://git.barkshark.xyz/izaliamae/paws' target='_new' << PAWS/{{config.version}}
|
||||
|
||||
%script type='application/javascript' src='{{var.base}}/paws/static/js/menu.js'
|
18
paws/frontend/component/status.haml
Normal file
|
@ -0,0 +1,18 @@
|
|||
.status
|
||||
.header.grid-container
|
||||
.grid-item.avatar
|
||||
%a href='{{var.base}}/@{{status.user.handle}}'
|
||||
%img src="{{var.base}}/{{status.user.avatar}}?50"
|
||||
.grid-item
|
||||
.user-info
|
||||
.user -> %a href='{{var.base}}/@{{status.user.handle}}' -> =status.user.name
|
||||
.handle << @{{status.user.handle}}@{{status.user.domain}}
|
||||
.date -> %a href='{{var.base}}/:{{status.id}}' -> =status.timestamp.string('%d %B %Y %H:%M:%S')
|
||||
|
||||
.content
|
||||
-if status.warning
|
||||
%details
|
||||
%summary << CW: {{status.warning}}
|
||||
=status.content
|
||||
-else
|
||||
=status.content
|
8
paws/frontend/error.haml
Normal file
|
@ -0,0 +1,8 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Error'
|
||||
-block content
|
||||
%center
|
||||
%font size='8'
|
||||
HTTP {{data.code}}
|
||||
%br
|
||||
=data.msg
|
26
paws/frontend/pages/about.haml
Normal file
|
@ -0,0 +1,26 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'About'
|
||||
-block content
|
||||
#about
|
||||
.title << {{page}}
|
||||
-if about
|
||||
{{about}}
|
||||
|
||||
-else
|
||||
No description
|
||||
|
||||
.title << Admins
|
||||
-for acct in admins
|
||||
%p.user
|
||||
%a.avatar href='{{var.base}}/@{{acct.handle}}'
|
||||
%img src='{{var.base}}/{{acct.avatar}}'
|
||||
%a href='{{var.base}}/@{{acct.handle}}'
|
||||
=acct.name
|
||||
|
||||
.title << Moderators
|
||||
-for acct in mods
|
||||
%p.user
|
||||
%a.avatar href='{{var.base}}/@{{acct.handle}}'
|
||||
%img src='{{var.base}}/{{acct.avatar}}'
|
||||
%a href='{{var.base}}/@{{acct.handle}}'
|
||||
=acct.name
|
11
paws/frontend/pages/admin/dashboard.haml
Normal file
|
@ -0,0 +1,11 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Admin: Panel'
|
||||
-block content
|
||||
#admin
|
||||
.title << Admin Panel
|
||||
.info
|
||||
.flex-item << Local users: {{local_users}}
|
||||
.flex-item << Remote users: {{remote_users}}
|
||||
.flex-item << Local statuses: {{local_statuses}}
|
||||
.flex-item << Remote statuses: {{remote_statuses}}
|
||||
.flex-item << Database size: {{dbsize}}
|
63
paws/frontend/pages/admin/settings.haml
Normal file
|
@ -0,0 +1,63 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Admin: Instance Settings'
|
||||
-block content
|
||||
#admin.settings
|
||||
.title << Instance Settings
|
||||
%form#settings method='POST' enctype='multipart/form-data' autocomplete='off' action='{{var.base}}/admin/settings'
|
||||
.grid-container
|
||||
.grid-item.label
|
||||
%lable for='name' << Instance Name
|
||||
|
||||
.grid-item.input
|
||||
%input.tooltip id='name' name='name' placeholder='Barkshark Social' value='{{settings.name}}'
|
||||
|
||||
.grid-item.label
|
||||
%lable for='admin' << Admin Contact
|
||||
|
||||
.grid-item.input
|
||||
%select id='admin' name='admin' value='{{settings.admin}}'
|
||||
%option value='none' << None
|
||||
-for admin in admins
|
||||
-if admin == settings.admin
|
||||
%option value='{{admin}}' selected << {{admin}}
|
||||
-else
|
||||
%option value='{{admin}}' << {{admin}}
|
||||
|
||||
.grid-item.label
|
||||
%label for='robotstxt' << Robots.txt
|
||||
|
||||
.grid-item.input
|
||||
%textarea id='robotstxt' name='robotstxt' << {{settings.robotstxt if settings.robotstxt else ""}}
|
||||
|
||||
.grid-item.label
|
||||
%label for='description' << Instance Description
|
||||
|
||||
.grid-item.input
|
||||
%textarea id='description' name='description' << {{settings.description if settings.description else ""}}
|
||||
|
||||
.grid-item.label
|
||||
%label for='short_description' << Short Description
|
||||
|
||||
.grid-item.input
|
||||
%input id='short_description' name='short_description' placeholder='a short blurb about the instance' value="{{settings.short_description if settings.short_description else ''}}"
|
||||
|
||||
.grid-item.label
|
||||
|
||||
.grid-item.input
|
||||
.bools
|
||||
%input.tooltip id='open' name='open' type='checkbox' {{'checked' if settings.open}}
|
||||
%label for='open' << Registration Enabled
|
||||
%br
|
||||
|
||||
%input.tooltip id='require_approval' name='require_approval' type='checkbox' {{'checked' if settings.require_approval}}
|
||||
%label for='require_approval' << Require Registration Approval
|
||||
%br
|
||||
|
||||
%input.tooltip id='domain_approval' name='domain_approval' type='checkbox' {{'checked' if settings.domain_approval}}
|
||||
%label for='domain_approval' << Require Instance Approval
|
||||
%br
|
||||
|
||||
%input.tooltip id='secure' name='secure' type='checkbox' {{'checked' if settings.secure}}
|
||||
%label for='secure' << Secure Mode
|
||||
|
||||
%center -> %input.submit type='submit' value='Submit'
|
4
paws/frontend/pages/home.haml
Normal file
|
@ -0,0 +1,4 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Home'
|
||||
-block content
|
||||
{{settings.description.replace('\n', '<br />\n')}}
|
19
paws/frontend/pages/login.haml
Normal file
|
@ -0,0 +1,19 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Login'
|
||||
-block content
|
||||
.title << Login
|
||||
%form action='{{var.base}}/login' method='post' id='logreg_form'
|
||||
%center
|
||||
.error.message
|
||||
-if msg
|
||||
{{msg}}
|
||||
|
||||
-else
|
||||
%br
|
||||
|
||||
%input type='text' name='username' placeholder='Username'
|
||||
%input type='password' name='password' placeholder='Password'
|
||||
%input type='hidden' name='redir' value='{{redir.path}}'
|
||||
%input type='hidden' name='redir_data' value='{{redir.data}}'
|
||||
%input type='hidden' name='login_type' value='password'
|
||||
%input type='submit' value='Login'
|
21
paws/frontend/pages/login_keypair.haml
Normal file
|
@ -0,0 +1,21 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Login'
|
||||
-block content
|
||||
.title << Login
|
||||
%form action='{{var.base}}/login' method='post' id='logreg_form'
|
||||
%center
|
||||
.error.message
|
||||
-if msg
|
||||
{{msg}}
|
||||
|
||||
-else
|
||||
%br
|
||||
|
||||
%input type='text' name='username' placeholder='Username'
|
||||
%input type='password' name='password' placeholder='Password'
|
||||
%input type='hidden' name='redir' value='{{redir.path}}'
|
||||
%input type='hidden' name='redir_data' value='{{redir.data}}'
|
||||
%input type='hidden' name='login_type' value='keypair'
|
||||
%input#login_value type='hidden' name='login_value' value='{{rand}}'
|
||||
%input type='hidden' name='encrypt_value' value='{{str(uuid4)}}'
|
||||
%input type='submit' value='Login'
|
7
paws/frontend/pages/moderation/blocks.haml
Normal file
|
@ -0,0 +1,7 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Moderation: Instance Bans'
|
||||
-block content
|
||||
#mod.bans
|
||||
.title << Instance Bans
|
||||
|
||||
heck
|
16
paws/frontend/pages/oauth/authenticate.haml
Normal file
|
@ -0,0 +1,16 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Application Authentication'
|
||||
-block content
|
||||
%form#oauth action='{{var.base}}/oauth/authorize'
|
||||
%a href='{{app.url}}' << {{app.name}}
|
||||
wants to access your account
|
||||
%br
|
||||
|
||||
Scopes: {{app.scope}}
|
||||
%br
|
||||
|
||||
-for k,v in args.items()
|
||||
%input type='hidden' name='{{k}}' value='{{v}}'
|
||||
|
||||
%input.accept type='submit' name='accept' value='Accept'
|
||||
%input.reject type='submit' name='accept' value='Reject'
|
9
paws/frontend/pages/oauth/code.haml
Normal file
|
@ -0,0 +1,9 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Application Authentication'
|
||||
-block content
|
||||
%form#oauth action='{{var.base}}/oauth/authorize'
|
||||
Authorization code for
|
||||
%a href='{{app.url}}' << {{app.name}}
|
||||
%br
|
||||
|
||||
.message -> =code
|
59
paws/frontend/pages/preferences/profile.haml
Normal file
|
@ -0,0 +1,59 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Settings - Profile'
|
||||
-block content
|
||||
.settings
|
||||
.title << Settings
|
||||
%form#preferences method='POST' enctype='multipart/form-data' autocomplete='off' action='{{var.base}}/preferences/profile'
|
||||
.grid-container
|
||||
.grid-item.label.img
|
||||
%label for='avatar' << Avatar
|
||||
.grid-item.input
|
||||
%input id='avatar' name='avatar' type='file'
|
||||
%img src='{{var.base}}/{{cookie_user.avatar}}?100'
|
||||
|
||||
.grid-item.label.img
|
||||
%label for='header_img' << Header
|
||||
.grid-item.input
|
||||
%input id='header_img' name='header' type='file'
|
||||
%img src='{{var.base}}/{{cookie_user.header}}?height=100'
|
||||
|
||||
.grid-item.label
|
||||
%label for='name' << Display Name
|
||||
.grid-item.input
|
||||
%input id='name' name='name' placeholder='Funny display name goes here' value='{{cookie_user.name if cookie_user.bio else ""}}'
|
||||
|
||||
.grid-item.label
|
||||
%label for='email' << E-Mail
|
||||
.grid-item.input
|
||||
%input id='email' name='email' type='email' placeholder='user@domain.com' value='{{cookie_user.email if cookie_user.email else ""}}'
|
||||
|
||||
.grid-item.label
|
||||
%label for='password' << Password
|
||||
.grid-item.input
|
||||
%input id='password' name='oldpassword' type='password' placeholder='Current password'
|
||||
%input name='password1' type='password' placeholder='New password'
|
||||
%input name='password2' type='password' placeholder='New password again'
|
||||
|
||||
.grid-item.label
|
||||
%label for='bio' << Bio
|
||||
.grid-item.input
|
||||
%textarea id='bio' name='bio' << {{cookie_user.bio if cookie_user.bio else ""}}
|
||||
|
||||
.grid-item.label
|
||||
%label for='theme' << Color Theme
|
||||
.grid-item.input
|
||||
%select id='theme' name='color_theme'
|
||||
-for color in color_themes
|
||||
-if (cookie_user and color == cookie_user.config.theme) or (color == 'pink' and (not cookie_user or not cookie_user.config.theme))
|
||||
%option value='{{color}}' selected << {{color.capitalize()}}
|
||||
-else
|
||||
%option value='{{color}}' << {{color.capitalize()}}
|
||||
|
||||
.grid-item.label
|
||||
|
||||
.grid-item.input
|
||||
.bool
|
||||
%input id='private' name='private' type='checkbox' {{'checked' if cookie_user.config.get("private", False)}}
|
||||
%label for='private' << Locked Account
|
||||
|
||||
%center -> %input.submit type='submit' value='Submit'
|
41
paws/frontend/pages/profile.haml
Normal file
|
@ -0,0 +1,41 @@
|
|||
-extends 'base.haml'
|
||||
-set page = user.name
|
||||
-block content
|
||||
#profile
|
||||
.header -> %img src='{{var.base}}/{{user.header}}'
|
||||
#user.grid-container
|
||||
.grid-item.icon -> %img src='{{var.base}}/{{user.avatar}}?100'
|
||||
.grid-item.info
|
||||
.name -> =user.name
|
||||
.handle -> @{{user.handle}}@{{user.domain}}
|
||||
.bio -> -if user.bio -> =user.bio
|
||||
|
||||
-if user.info_table
|
||||
#tablediv
|
||||
%table#table
|
||||
-for key, value in user.info_table.items()
|
||||
%tr
|
||||
%td.key << {{key}}
|
||||
%td.value << {{value}}
|
||||
|
||||
#posts
|
||||
.title << Posts
|
||||
.pagination
|
||||
-if page_data.has_previous()
|
||||
%a.prev href='{{var.base}}/@{{user.handle}}?page={{page_data.previous_page_number}}' << Previous
|
||||
|
||||
-if page_data.has_next()
|
||||
%a.next href='{{var.base}}/@{{user.handle}}?page={{page_data.next_page_number}}' << Next
|
||||
|
||||
-if not posts
|
||||
%center -> No posts :/
|
||||
-else
|
||||
-for status in posts
|
||||
-include 'component/status.haml'
|
||||
|
||||
.pagination
|
||||
-if page_data.has_previous()
|
||||
%a.prev href='{{var.base}}/@{{user.handle}}?page={{page_data.previous_page_number}}' << Previous
|
||||
|
||||
-if page_data.has_next()
|
||||
%a.next href='{{var.base}}/@{{user.handle}}?page={{page_data.next_page_number}}' << Next
|
19
paws/frontend/pages/register.haml
Normal file
|
@ -0,0 +1,19 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Register'
|
||||
-block content
|
||||
.title << Register
|
||||
%form action="{{var.base}}/register" method="post" id="logreg_form" autocomplete="new-password"
|
||||
%center
|
||||
.error.message
|
||||
-if msg
|
||||
{{msg}}
|
||||
|
||||
-else
|
||||
%br
|
||||
|
||||
%input type="text" name="username" placeholder="Username"
|
||||
%input type="text" name="name" placeholder="Display Name"
|
||||
%input type="password" name="newpassword1" placeholder="New password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number, one uppercase & lowercase letter, and at least 8 or more characters" autocomplete="new-password"
|
||||
%input type="password" name="newpassword2" placeholder="Repeat new password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number, one uppercase & lowercase letter, and at least 8 or more characters" autocomplete="new-password"
|
||||
%input type="email" name="email" placeholder="E-mail"
|
||||
%input type="submit" value="Register"
|
9
paws/frontend/pages/rules.haml
Normal file
|
@ -0,0 +1,9 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Rules'
|
||||
-block content
|
||||
#rules
|
||||
.title << Rules
|
||||
-if settings.rules
|
||||
=settings.rules
|
||||
-else
|
||||
Not set
|
4
paws/frontend/pages/status.haml
Normal file
|
@ -0,0 +1,4 @@
|
|||
-extends 'base.haml'
|
||||
-set page = 'Status'
|
||||
-block content
|
||||
-include 'component/status.haml'
|
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Black.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Black.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-BlackItalic.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-BlackItalic.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Bold.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Bold.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-BoldItalic.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-BoldItalic.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-ExtraBold.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-ExtraBold.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-ExtraBoldItalic.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-ExtraLight.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-ExtraLight.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Italic.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Italic.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Light.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Light.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-LightItalic.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-LightItalic.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Regular.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-Regular.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-SemiBold.ttf
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-SemiBold.woff2
Normal file
BIN
paws/frontend/static/fonts/nunito/NunitoSans-SemiBoldItalic.ttf
Normal file
44
paws/frontend/static/fonts/nunito/SIL Open Font License.txt
Normal file
|
@ -0,0 +1,44 @@
|
|||
Copyright 2016 The Nunito Project Authors (contact@sansoxygen.com),
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
5
paws/frontend/static/img/delete.svg
Normal file
|
@ -0,0 +1,5 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg width="25" height="25">
|
||||
<path d="M5 5 L20 20" style="stroke-width:5px;stroke-linecap:round;"/>
|
||||
<path d="M5 20 L20 5" style="stroke-width:5px;stroke-linecap:round;" />
|
||||
</svg>
|
After Width: | Height: | Size: 236 B |
BIN
paws/frontend/static/img/icon-512.png
Normal file
After Width: | Height: | Size: 64 KiB |
BIN
paws/frontend/static/img/icon-64.png
Normal file
After Width: | Height: | Size: 3.8 KiB |
84
paws/frontend/static/img/menu.svg
Normal file
|
@ -0,0 +1,84 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
sodipodi:docname="menu.svg"
|
||||
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
|
||||
id="svg8"
|
||||
version="1.1"
|
||||
viewBox="0 0 132.29167 79.375002"
|
||||
height="300"
|
||||
width="500">
|
||||
<defs
|
||||
id="defs2" />
|
||||
<sodipodi:namedview
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:window-y="36"
|
||||
inkscape:window-x="36"
|
||||
inkscape:window-height="990"
|
||||
inkscape:window-width="1644"
|
||||
units="px"
|
||||
showgrid="true"
|
||||
inkscape:document-rotation="0"
|
||||
inkscape:current-layer="layer2"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:cy="151.34478"
|
||||
inkscape:cx="232.18877"
|
||||
inkscape:zoom="1.4"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
borderopacity="1.0"
|
||||
bordercolor="#666666"
|
||||
pagecolor="#ffffff"
|
||||
id="base"
|
||||
inkscape:snap-text-baseline="true"
|
||||
inkscape:snap-intersection-paths="true"
|
||||
inkscape:snap-bbox="true"
|
||||
inkscape:bbox-nodes="true"
|
||||
fit-margin-top="0"
|
||||
fit-margin-left="0"
|
||||
fit-margin-right="0"
|
||||
fit-margin-bottom="0">
|
||||
<inkscape:grid
|
||||
dotted="true"
|
||||
id="grid1402"
|
||||
type="xygrid"
|
||||
originx="-7.9375001"
|
||||
originy="-27.781234" />
|
||||
</sodipodi:namedview>
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="Layer 1"
|
||||
id="layer2"
|
||||
inkscape:groupmode="layer"
|
||||
transform="translate(-7.9374999,-27.781233)">
|
||||
<path
|
||||
style="fill:none;fill-opacity:1;stroke:#cfcfcf;stroke-width:13.2292;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 15.875,67.468765 c 116.41667,0 116.41667,0 116.41667,0 z"
|
||||
id="path1590" />
|
||||
<path
|
||||
style="fill:none;fill-opacity:1;stroke:#cfcfcf;stroke-width:13.2292;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 15.875,35.718766 c 116.41667,0 116.41667,0 116.41667,0 z"
|
||||
id="path1590-7" />
|
||||
<path
|
||||
style="fill:none;fill-opacity:1;stroke:#cfcfcf;stroke-width:13.2292;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 15.875,99.218766 c 116.41667,0 116.41667,0 116.41667,0 z"
|
||||
id="path1590-7-8" />
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 2.8 KiB |
250
paws/frontend/static/img/missing_header.svg
Normal file
After Width: | Height: | Size: 148 KiB |
157
paws/frontend/static/img/missing_pfp.svg
Normal file
|
@ -0,0 +1,157 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="256"
|
||||
height="256"
|
||||
viewBox="0 0 67.733333 67.733333"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
|
||||
sodipodi:docname="missing_pfp.svg">
|
||||
<defs
|
||||
id="defs2">
|
||||
<rect
|
||||
x="10.583333"
|
||||
y="11.90625"
|
||||
width="47.625"
|
||||
height="38.364583"
|
||||
id="rect908" />
|
||||
</defs>
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="2.99"
|
||||
inkscape:cx="101.08211"
|
||||
inkscape:cy="131.6607"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:current-layer="layer3"
|
||||
inkscape:document-rotation="0"
|
||||
showgrid="true"
|
||||
units="px"
|
||||
inkscape:window-width="1226"
|
||||
inkscape:window-height="957"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="38"
|
||||
inkscape:window-maximized="1">
|
||||
<inkscape:grid
|
||||
type="xygrid"
|
||||
id="grid833" />
|
||||
</sodipodi:namedview>
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:groupmode="layer"
|
||||
id="layer2"
|
||||
inkscape:label="head"
|
||||
style="display:inline">
|
||||
<circle
|
||||
style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.79324;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;paint-order:markers fill stroke;stroke-opacity:1"
|
||||
id="path850"
|
||||
cx="33.734375"
|
||||
cy="42.259773"
|
||||
r="22.380424" />
|
||||
</g>
|
||||
<g
|
||||
inkscape:groupmode="layer"
|
||||
id="layer3"
|
||||
inkscape:label="ears">
|
||||
<path
|
||||
style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:1.32292;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal"
|
||||
d="M 13.229168,35.718749 11.90625,9.2604167 23.812501,22.489583 Z"
|
||||
id="path853"
|
||||
sodipodi:nodetypes="cccc" />
|
||||
<path
|
||||
style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:1.32292;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:normal"
|
||||
d="M 54.239584,35.718749 55.5625,9.2604167 43.65625,22.489583 Z"
|
||||
id="path853-3"
|
||||
sodipodi:nodetypes="cccc" />
|
||||
</g>
|
||||
<g
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"
|
||||
inkscape:label="head 1"
|
||||
style="display:inline">
|
||||
<text
|
||||
xml:space="preserve"
|
||||
id="text906"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;white-space:pre;shape-inside:url(#rect908);fill:#000000;fill-opacity:1;stroke:none;" />
|
||||
<g
|
||||
aria-label="Missing
|
||||
Avatar"
|
||||
id="text914"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.264583">
|
||||
<path
|
||||
d="m 14.918419,28.03003 h 1.555455 l 1.968866,5.250309 1.979201,-5.250309 h 1.555456 v 7.715266 h -1.018023 v -6.774758 l -1.989536,5.29165 H 17.92081 l -1.989537,-5.29165 v 6.774758 h -1.012854 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path939" />
|
||||
<path
|
||||
d="m 24.008275,29.957554 h 0.950843 v 5.787742 h -0.950843 z m 0,-2.253085 h 0.950843 v 1.204057 h -0.950843 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path941" />
|
||||
<path
|
||||
d="m 30.63834,30.128086 v 0.899167 q -0.403075,-0.206705 -0.837155,-0.310057 -0.434081,-0.103353 -0.899167,-0.103353 -0.707965,0 -1.064531,0.21704 -0.351399,0.217041 -0.351399,0.651121 0,0.330729 0.253214,0.521931 0.253213,0.186034 1.018022,0.356566 l 0.325561,0.07235 q 1.012854,0.21704 1.4366,0.614947 0.428913,0.39274 0.428913,1.100705 0,0.80615 -0.640786,1.276404 -0.635618,0.470254 -1.751825,0.470254 -0.465087,0 -0.971514,-0.09302 -0.50126,-0.08785 -1.059364,-0.268716 v -0.981849 q 0.527098,0.273884 1.038693,0.41341 0.511595,0.134358 1.012855,0.134358 0.671792,0 1.033525,-0.227375 0.361734,-0.232544 0.361734,-0.651121 0,-0.387572 -0.263549,-0.594277 -0.258381,-0.206706 -1.142045,-0.397908 l -0.330728,-0.07751 q -0.883664,-0.186035 -1.276404,-0.568439 -0.39274,-0.387572 -0.39274,-1.059364 0,-0.816485 0.578775,-1.260901 0.578774,-0.444415 1.643305,-0.444415 0.527098,0 0.992184,0.07751 0.465087,0.07751 0.857826,0.232543 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path943" />
|
||||
<path
|
||||
d="m 36.152197,30.128086 v 0.899167 q -0.403075,-0.206705 -0.837155,-0.310057 -0.434081,-0.103353 -0.899167,-0.103353 -0.707965,0 -1.064532,0.21704 -0.351398,0.217041 -0.351398,0.651121 0,0.330729 0.253213,0.521931 0.253214,0.186034 1.018023,0.356566 l 0.32556,0.07235 q 1.012855,0.21704 1.436601,0.614947 0.428913,0.39274 0.428913,1.100705 0,0.80615 -0.640786,1.276404 -0.635618,0.470254 -1.751825,0.470254 -0.465087,0 -0.971514,-0.09302 -0.50126,-0.08785 -1.059364,-0.268716 v -0.981849 q 0.527098,0.273884 1.038693,0.41341 0.511595,0.134358 1.012855,0.134358 0.671792,0 1.033525,-0.227375 0.361734,-0.232544 0.361734,-0.651121 0,-0.387572 -0.263549,-0.594277 -0.258381,-0.206706 -1.142045,-0.397908 l -0.330728,-0.07751 q -0.883665,-0.186035 -1.276404,-0.568439 -0.39274,-0.387572 -0.39274,-1.059364 0,-0.816485 0.578774,-1.260901 0.578775,-0.444415 1.643306,-0.444415 0.527098,0 0.992184,0.07751 0.465086,0.07751 0.857826,0.232543 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path945" />
|
||||
<path
|
||||
d="m 37.97637,29.957554 h 0.950844 v 5.787742 H 37.97637 Z m 0,-2.253085 h 0.950844 v 1.204057 H 37.97637 Z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path947" />
|
||||
<path
|
||||
d="m 45.727811,32.251981 v 3.493315 h -0.950843 v -3.462309 q 0,-0.821653 -0.320393,-1.229896 -0.320393,-0.408242 -0.961179,-0.408242 -0.769976,0 -1.214392,0.490924 -0.444416,0.490925 -0.444416,1.338416 v 3.271107 h -0.956011 v -5.787742 h 0.956011 v 0.899168 q 0.341063,-0.521931 0.800982,-0.780312 0.465087,-0.258381 1.069699,-0.258381 0.997352,0 1.508947,0.620115 0.511595,0.614947 0.511595,1.813837 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path949" />
|
||||
<path
|
||||
d="m 51.432872,32.784246 q 0,-1.033525 -0.428913,-1.601964 -0.423745,-0.568439 -1.193722,-0.568439 -0.764809,0 -1.193722,0.568439 -0.423745,0.568439 -0.423745,1.601964 0,1.028358 0.423745,1.596797 0.428913,0.568439 1.193722,0.568439 0.769977,0 1.193722,-0.568439 0.428913,-0.568439 0.428913,-1.596797 z m 0.950843,2.24275 q 0,1.477942 -0.656288,2.196242 -0.656289,0.723467 -2.010207,0.723467 -0.50126,0 -0.945676,-0.07751 -0.444416,-0.07235 -0.862993,-0.227375 V 36.71681 q 0.418577,0.227376 0.82682,0.335896 0.408242,0.10852 0.831988,0.10852 0.93534,0 1.400427,-0.490924 0.465086,-0.485757 0.465086,-1.472774 v -0.470254 q -0.294555,0.511595 -0.754474,0.764809 -0.459918,0.253213 -1.100704,0.253213 -1.064531,0 -1.715652,-0.811317 -0.651121,-0.811317 -0.651121,-2.149733 0,-1.343583 0.651121,-2.1549 0.651121,-0.811317 1.715652,-0.811317 0.640786,0 1.100704,0.253213 0.459919,0.253214 0.754474,0.764809 v -0.878497 h 0.950843 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path951" />
|
||||
<path
|
||||
d="m 20.052456,42.287512 -1.41593,3.839547 h 2.837027 z m -0.58911,-1.028358 h 1.183387 l 2.94038,7.715267 H 22.501911 L 21.799114,46.99522 h -3.477813 l -0.702797,1.979201 h -1.100705 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path953" />
|
||||
<path
|
||||
d="m 23.370072,43.186679 h 1.007688 l 1.808669,4.857569 1.808669,-4.857569 h 1.007688 l -2.170404,5.787742 h -1.291906 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path955" />
|
||||
<path
|
||||
d="m 32.945685,46.065047 q -1.152381,0 -1.596797,0.263549 -0.444416,0.263549 -0.444416,0.899167 0,0.506428 0.330728,0.80615 0.335896,0.294555 0.909503,0.294555 0.790646,0 1.266068,-0.558104 0.480589,-0.563271 0.480589,-1.493444 v -0.211873 z m 1.896519,-0.392739 v 3.302113 H 33.89136 v -0.878497 q -0.32556,0.527098 -0.811317,0.780312 -0.485757,0.248046 -1.188554,0.248046 -0.888832,0 -1.41593,-0.496092 -0.52193,-0.50126 -0.52193,-1.338415 0,-0.976682 0.651121,-1.472774 0.656288,-0.496092 1.953363,-0.496092 h 1.333247 v -0.09302 q 0,-0.656289 -0.43408,-1.012855 -0.428913,-0.361734 -1.209225,-0.361734 -0.496092,0 -0.966346,0.118855 -0.470254,0.118856 -0.904335,0.356567 v -0.878497 q 0.52193,-0.201537 1.012855,-0.299722 0.490925,-0.103353 0.956011,-0.103353 1.255733,0 1.875848,0.651121 0.620116,0.651121 0.620116,1.974034 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path957" />
|
||||
<path
|
||||
d="m 37.741242,41.543374 v 1.643305 h 1.958531 v 0.738971 h -1.958531 v 3.141917 q 0,0.707965 0.191202,0.909502 0.19637,0.201538 0.790647,0.201538 h 0.976682 v 0.795814 h -0.976682 q -1.100704,0 -1.519282,-0.408242 -0.418578,-0.413411 -0.418578,-1.498612 V 43.92565 h -0.697629 v -0.738971 h 0.697629 v -1.643305 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path959" />
|
||||
<path
|
||||
d="m 43.580661,46.065047 q -1.152381,0 -1.596797,0.263549 -0.444416,0.263549 -0.444416,0.899167 0,0.506428 0.330729,0.80615 0.335895,0.294555 0.909502,0.294555 0.790647,0 1.266068,-0.558104 0.48059,-0.563271 0.48059,-1.493444 v -0.211873 z m 1.896519,-0.392739 v 3.302113 h -0.950843 v -0.878497 q -0.325561,0.527098 -0.811318,0.780312 -0.485757,0.248046 -1.188554,0.248046 -0.888832,0 -1.41593,-0.496092 -0.52193,-0.50126 -0.52193,-1.338415 0,-0.976682 0.651121,-1.472774 0.656289,-0.496092 1.953363,-0.496092 h 1.333248 v -0.09302 q 0,-0.656289 -0.434081,-1.012855 -0.428913,-0.361734 -1.209225,-0.361734 -0.496092,0 -0.966346,0.118855 -0.470254,0.118856 -0.904334,0.356567 v -0.878497 q 0.52193,-0.201537 1.012854,-0.299722 0.490925,-0.103353 0.956011,-0.103353 1.255734,0 1.875849,0.651121 0.620115,0.651121 0.620115,1.974034 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path961" />
|
||||
<path
|
||||
d="m 50.789499,44.075511 q -0.160196,-0.09302 -0.351398,-0.134358 -0.186035,-0.04651 -0.41341,-0.04651 -0.80615,0 -1.240231,0.527098 -0.428913,0.52193 -0.428913,1.503779 v 3.0489 h -0.956011 v -5.787742 h 0.956011 v 0.899167 q 0.299723,-0.527098 0.780312,-0.780312 0.480589,-0.258381 1.167884,-0.258381 0.09818,0 0.21704,0.0155 0.118855,0.01034 0.263549,0.03617 z"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.5833px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-align:center;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.264583"
|
||||
id="path963" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 15 KiB |
BIN
paws/frontend/static/img/one.png
Normal file
After Width: | Height: | Size: 68 B |
199
paws/frontend/static/js/login.js
Normal file
|
@ -0,0 +1,199 @@
|
|||
const login_value = document.getElementById("login_value").value
|
||||
const encodedMessage = enc.encode('hello');
|
||||
const localStorage.setItem('privkey', privateKey);
|
||||
const localStorage.setItem('pubkey', publicKey);
|
||||
|
||||
|
||||
var privateKey;
|
||||
var publicKey;
|
||||
|
||||
|
||||
var iv;
|
||||
|
||||
|
||||
function asciiToUint8Array(str) {
|
||||
var chars = [];
|
||||
for (var i = 0; i < str.length; ++i)
|
||||
chars.push(str.charCodeAt(i));
|
||||
return new Uint8Array(chars);
|
||||
}
|
||||
|
||||
function RSAPSS_Sign(plainText) {
|
||||
var cryptoObj = window.crypto || window.msCrypto;
|
||||
|
||||
if(!cryptoObj)
|
||||
{
|
||||
alert("Crypto API is not supported by the Browser");
|
||||
return;
|
||||
}
|
||||
|
||||
window.crypto.subtle.generateKey({
|
||||
name: 'RSA-PSS',
|
||||
modulusLength: 2048, //can be 1024, 2048, or 4096
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
hash: {name: 'SHA-256'},
|
||||
},
|
||||
true,
|
||||
['sign', 'verify']
|
||||
)
|
||||
.then(function(key) {
|
||||
|
||||
publicKey = key.publicKey;
|
||||
privateKey = key.privateKey;
|
||||
// For Demo Purpos Only Exported in JWK format
|
||||
window.crypto.subtle.exportKey('jwk', key.publicKey).then(
|
||||
function(keydata) {
|
||||
publicKeyhold = keydata;
|
||||
publicKeyJson = JSON.stringify(publicKeyhold);
|
||||
document.getElementById("rsapublic").value = publicKeyJson;
|
||||
}
|
||||
);
|
||||
|
||||
window.crypto.subtle.exportKey("jwk", key.privateKey).then(
|
||||
function(keydata) {
|
||||
privateKeyhold = keydata;
|
||||
privateKeyJson = JSON.stringify(privateKeyhold);
|
||||
document.getElementById("rsaprivate").value = privateKeyJson;
|
||||
}
|
||||
);
|
||||
|
||||
window.crypto.subtle.sign({
|
||||
name: "RSA-PSS",
|
||||
saltLength: 128, //the length of the salt
|
||||
},
|
||||
privateKey, //from generateKey or importKey above
|
||||
asciiToUint8Array(plainText) //ArrayBuffer of data you want to sign
|
||||
)
|
||||
.then(function(signature) {
|
||||
//returns an ArrayBuffer containing the signature
|
||||
document.getElementById("cipherText").value = bytesToHexString(signature);
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error(err);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
function RSAPSS_Verify() {
|
||||
var cryptoObj = window.crypto || window.msCrypto;
|
||||
|
||||
if(!cryptoObj)
|
||||
{
|
||||
alert("Crypto API is not supported by the Browser");
|
||||
return;
|
||||
}
|
||||
|
||||
var cipherText = document.getElementById("cipherText").value;
|
||||
var plainText = document.getElementById("plainText").value;
|
||||
|
||||
if(!publicKey)
|
||||
{
|
||||
alert("Generate RSA-PSS Keys First")
|
||||
return;
|
||||
}
|
||||
|
||||
window.crypto.subtle.verify({
|
||||
name: "RSA-PSS",
|
||||
saltLength: 128, //the length of the salt
|
||||
},
|
||||
publicKey, //from generateKey or importKey above
|
||||
hexStringToUint8Array(cipherText), //ArrayBuffer of the data
|
||||
asciiToUint8Array(plainText)
|
||||
)
|
||||
.then(function(decrypted) {
|
||||
alert("Verified " + decrypted);
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function bytesToASCIIString(bytes) {
|
||||
return String.fromCharCode.apply(null, new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
function bytesToHexString(bytes) {
|
||||
if (!bytes)
|
||||
return null;
|
||||
|
||||
bytes = new Uint8Array(bytes);
|
||||
var hexBytes = [];
|
||||
|
||||
for (var i = 0; i < bytes.length; ++i) {
|
||||
var byteString = bytes[i].toString(16);
|
||||
if (byteString.length < 2)
|
||||
byteString = "0" + byteString;
|
||||
hexBytes.push(byteString);
|
||||
}
|
||||
|
||||
return hexBytes.join("");
|
||||
}
|
||||
|
||||
function hexStringToUint8Array(hexString) {
|
||||
if (hexString.length % 2 != 0)
|
||||
throw "Invalid hexString";
|
||||
var arrayBuffer = new Uint8Array(hexString.length / 2);
|
||||
|
||||
for (var i = 0; i < hexString.length; i += 2) {
|
||||
var byteValue = parseInt(hexString.substr(i, 2), 16);
|
||||
if (byteValue == NaN)
|
||||
throw "Invalid hexString";
|
||||
arrayBuffer[i / 2] = byteValue;
|
||||
}
|
||||
|
||||
return arrayBuffer;
|
||||
}
|
||||
|
||||
|
||||
function failAndLog(error) {
|
||||
console.log(error);
|
||||
alert(error);
|
||||
}
|
||||
|
||||
|
||||
function sign_uuid() {
|
||||
var uuid = document.getElementById("plainText").value;
|
||||
}
|
||||
|
||||
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
|
||||
function generate_key() {
|
||||
keypair = window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: 'RSA-PSS',
|
||||
modulusLength: 2048, //can be 1024, 2048, or 4096
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
hash: {name: 'SHA-256'},
|
||||
},
|
||||
true,
|
||||
['sign', 'verify']
|
||||
)
|
||||
|
||||
return keypair.then(function(key) {
|
||||
publicKey = key.publicKey;
|
||||
privateKey = key.privateKey;
|
||||
privkey = window.crypto.subtle.exportKey('jwk', key.publicKey)
|
||||
|
||||
return privkey.then(
|
||||
function(keydata) {
|
||||
publicKeyhold = keydata;
|
||||
publicKeyJson = JSON.stringify(publicKeyhold);
|
||||
return publicKeyJson;
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
generate_key()
|
29
paws/frontend/static/js/menu.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
const sidebarBox = document.querySelector('#menu'),
|
||||
sidebarBtn = document.querySelector('#btn'),
|
||||
pageWrapper = document.querySelector('html');
|
||||
header = document.querySelector('#header')
|
||||
|
||||
sidebarBtn.addEventListener('click', event => {
|
||||
sidebarBtn.classList.toggle('active');
|
||||
sidebarBox.classList.toggle('active');
|
||||
});
|
||||
|
||||
pageWrapper.addEventListener('click', event => {
|
||||
itemId = event.srcElement.id
|
||||
itemClass = event.srcElement.className
|
||||
indexId = ['menu', 'btn', 'items'].indexOf(itemId)
|
||||
indexClass = ['item', 'item name', 'items'].indexOf(itemClass)
|
||||
|
||||
if (sidebarBox.classList.contains('active') && (indexId == -1 && indexClass == -1)) {
|
||||
sidebarBtn.classList.remove('active');
|
||||
sidebarBox.classList.remove('active');
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('keydown', event => {
|
||||
|
||||
if (sidebarBox.classList.contains('active') && event.keyCode === 27) {
|
||||
sidebarBtn.classList.remove('active');
|
||||
sidebarBox.classList.remove('active');
|
||||
}
|
||||
});
|
29
paws/frontend/static/menu.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
const sidebarBox = document.querySelector('#menu'),
|
||||
sidebarBtn = document.querySelector('#btn'),
|
||||
pageWrapper = document.querySelector('html');
|
||||
header = document.querySelector('#header')
|
||||
|
||||
sidebarBtn.addEventListener('click', event => {
|
||||
sidebarBtn.classList.toggle('active');
|
||||
sidebarBox.classList.toggle('active');
|
||||
});
|
||||
|
||||
pageWrapper.addEventListener('click', event => {
|
||||
itemId = event.srcElement.id
|
||||
itemClass = event.srcElement.className
|
||||
indexId = ['menu', 'btn', 'items'].indexOf(itemId)
|
||||
indexClass = ['item', 'item name', 'items'].indexOf(itemClass)
|
||||
|
||||
if (sidebarBox.classList.contains('active') && (indexId == -1 && indexClass == -1)) {
|
||||
sidebarBtn.classList.remove('active');
|
||||
sidebarBox.classList.remove('active');
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('keydown', event => {
|
||||
|
||||
if (sidebarBox.classList.contains('active') && event.keyCode === 27) {
|
||||
sidebarBtn.classList.remove('active');
|
||||
sidebarBox.classList.remove('active');
|
||||
}
|
||||
});
|
298
paws/frontend/style.css
Normal file
|
@ -0,0 +1,298 @@
|
|||
{% set speed = 250 %}
|
||||
:root {
|
||||
--text: #eee;
|
||||
--hover: {{lighten(desaturate(primary, 0.5), 0.5)}};
|
||||
--primary: {{primary}};
|
||||
--background: {{background}};
|
||||
--ui: {{lighten(desaturate(primary, 0.25), 0.5)}};
|
||||
--ui-background: {{lighten(background, 0.075)}};
|
||||
--shadow-color: {{rgba('#000', 0.5)}};
|
||||
--shadow: 0 4px 4px 0 var(--shadow-color), 3px 0 4px 0 var(--shadow-color);
|
||||
|
||||
--negative: {{negative}};
|
||||
--negative-dark: {{darken(negative, 0.85)}};
|
||||
--positive: {{positive}};
|
||||
--positive-dark: {{darken(positive, 0.85)}};
|
||||
|
||||
--message: var(--positive);
|
||||
--error: var(--negative);
|
||||
--gap: 15px;
|
||||
/* --easing: cubic-bezier(.6, .05, .28, .91); */
|
||||
--trans-speed: {{speed}}ms;
|
||||
}
|
||||
|
||||
body {
|
||||
color: var(--text);
|
||||
background-color: var(--background);
|
||||
font-family: sans undertale;
|
||||
font-size: 16px;
|
||||
margin: 15px 0;
|
||||
}
|
||||
|
||||
a, a:visited {
|
||||
color: var(--primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: var(--hover);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
input:not([type='checkbox']), select, textarea {
|
||||
margin: 1px 0;
|
||||
color: var(--text);
|
||||
background-color: var(--background);
|
||||
border: 1px solid var(--background);
|
||||
box-shadow: 0 2px 2px 0 var(--shadow-color);
|
||||
}
|
||||
|
||||
input:hover, select:hover, textarea:hover {
|
||||
border-color: var(--hover);
|
||||
}
|
||||
|
||||
input:focus, select:focus, textarea:focus {
|
||||
outline: 0;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
details:focus, summary:focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
/* Classes */
|
||||
.grid-container {
|
||||
display: grid;
|
||||
grid-template-columns: auto;
|
||||
grid-gap: var(--gap);
|
||||
}
|
||||
|
||||
.grid-item {
|
||||
display: inline-grid;
|
||||
}
|
||||
|
||||
.flex-container {
|
||||
display: flex;
|
||||
flex-wrap; wrap;
|
||||
}
|
||||
|
||||
.menu {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.menu li {
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
min-width: 60px;
|
||||
background-color: {{lighten(background, 0.2)}};
|
||||
}
|
||||
|
||||
.menu li a {
|
||||
display: block;
|
||||
padding-left: 5px;
|
||||
padding-right: 5px;
|
||||
}
|
||||
|
||||
.menu li:hover {
|
||||
background-color: {{desaturate(lighten(primary, 0.25), 0.25)}};
|
||||
}
|
||||
|
||||
.menu li a:hover {
|
||||
text-decoration: none;
|
||||
color: {{desaturate(darken(primary, 0.90), 0.5)}};
|
||||
}
|
||||
|
||||
.section {
|
||||
padding: 8px;
|
||||
background-color: var(--ui-background);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.shadow {
|
||||
box-shadow: 0 4px 4px 0 var(--shadow-color), 3px 0 4px 0 var(--shadow-color);
|
||||
}
|
||||
|
||||
.message {
|
||||
line-height: 2em;
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* # this is kinda hacky and needs to be replaced */
|
||||
.tooltip:hover::after {
|
||||
position: relative;
|
||||
padding: 8px;
|
||||
bottom: 35px;
|
||||
border-radius: 5px;
|
||||
white-space: nowrap;
|
||||
border: 1px solid var(--text);
|
||||
color: var(--text);
|
||||
background-color: {{darken(desaturate(primary, 0.5), 0.75)}};
|
||||
box-shadow: var(--shadow);
|
||||
/*z-index: -1;*/
|
||||
}
|
||||
|
||||
|
||||
/* ids */
|
||||
#message, #error {
|
||||
padding: 10px;
|
||||
color: var(--background);
|
||||
margin-bottom: var(--gap);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#message {
|
||||
background-color: var(--message);
|
||||
}
|
||||
|
||||
#error {
|
||||
background-color: var(--error);
|
||||
}
|
||||
|
||||
#body {
|
||||
width: 790px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
#header {
|
||||
display: flex;
|
||||
margin-bottom: var(--gap);
|
||||
text-align: center;
|
||||
font-size: 2em;
|
||||
line-height: 40px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#header > div {
|
||||
/*display: inline-block;*/
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
#header .page-title {
|
||||
text-align: {% if menu_left %}right{% else %}left{% endif %};
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#content-body .title {
|
||||
text-align: center;
|
||||
font-size: 1.5em;
|
||||
font-weight: bold;
|
||||
color: var(--primary)
|
||||
}
|
||||
|
||||
#footer {
|
||||
margin-top: var(--gap);
|
||||
display: flex;
|
||||
grid-gap: 5px;
|
||||
font-size: 0.80em;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
#footer > div {
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
#footer .avatar img {
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
#footer .user {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#footer .source {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
{% for file in cssfiles %}
|
||||
{% include 'style/'+file.name %}
|
||||
{% endfor %}
|
||||
|
||||
|
||||
/* responsive design */
|
||||
@media (max-width: 810px) {
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#body {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
#logreg_form input:not(input[submit]), #logreg_form textarea {
|
||||
width: 75%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 610px) {
|
||||
.settings .grid-container {
|
||||
grid-template-columns: auto;
|
||||
}
|
||||
|
||||
.settings .label {
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
/*@media screen and (orientation:portrait) and (max-width: 610px) {
|
||||
#menu {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#menu .item {
|
||||
text-align: center;
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
/* scrollbar */
|
||||
body {scrollbar-width: 15px; scrollbar-color: var(--primary) {{darken(background, 0.1)}};}
|
||||
::-webkit-scrollbar {width: 15px;}
|
||||
::-webkit-scrollbar-track {background: {{darken(background, 0.1)}};}
|
||||
/*::-webkit-scrollbar-button {background: var(--primary);}
|
||||
::-webkit-scrollbar-button:hover {background: var(--text);}*/
|
||||
::-webkit-scrollbar-thumb {background: var(--primary);}
|
||||
::-webkit-scrollbar-thumb:hover {background: {{lighten(primary, 0.25)}};}
|
||||
|
||||
|
||||
/* page font */
|
||||
@font-face {
|
||||
font-family: 'sans undertale';
|
||||
src: local('Nunito Sans Bold'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-SemiBold.woff2') format('woff2'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-SemiBold.ttf') format('ttf');
|
||||
font-weight: bold;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'sans undertale';
|
||||
src: local('Nunito Sans Light Italic'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-ExtraLightItalic.woff2') format('woff2'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-ExtraLightItalic.ttf') format('ttf');
|
||||
font-weight: normal;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'sans undertale';
|
||||
src: local('Nunito Sans Bold Italic'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-Italic.woff2') format('woff2'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-Italic.ttf') format('ttf');
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'sans undertale';
|
||||
src: local('Nunito Sans Light'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-Light.woff2') format('woff2'),
|
||||
url('{{var.base}}/paws/static/fonts/nunito/NunitoSans-Light.ttf') format('ttf');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
14
paws/frontend/style/about.css
Normal file
|
@ -0,0 +1,14 @@
|
|||
/* About page */
|
||||
#about .user a {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
#about .user img {
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
#about .user .avatar {
|
||||
width: 50px;
|
||||
text-align: center;
|
||||
display: inline-block;
|
||||
}
|
11
paws/frontend/style/admin.css
Normal file
|
@ -0,0 +1,11 @@
|
|||
/* admin pages */
|
||||
#admin .info {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
#admin .info .flex-item {
|
||||
width: 250px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
19
paws/frontend/style/login-register.css
Normal file
|
@ -0,0 +1,19 @@
|
|||
/* Login/Register forms */
|
||||
#logreg_form textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
#logreg_form input, #logreg_form textarea {
|
||||
display: block;
|
||||
margin: 5px 0;
|
||||
line-height: 1.2em;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#logreg_form input:not(input[type="submit"]), #logreg_form textarea {
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
#logreg_form input[type="submit"] {
|
||||
margin-top: 15px;
|
||||
}
|
143
paws/frontend/style/menu.css
Normal file
|
@ -0,0 +1,143 @@
|
|||
/* Main menu */
|
||||
#btn {
|
||||
cursor: pointer;
|
||||
/* transition: left 500ms var(--easing); */
|
||||
}
|
||||
|
||||
#btn {
|
||||
transition: background-color var(--trans-speed);
|
||||
width: 55px;
|
||||
margin-left: var(--gap);
|
||||
background-image: url('{{base}}/paws/static/img/menu.svg');
|
||||
background-size: 50px;
|
||||
background-position: center center;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
#btn div {
|
||||
transition: transform var(--trans-speed) ease, opacity var(--trans-speed), background-color var(--trans-speed);
|
||||
}
|
||||
|
||||
#btn.active {
|
||||
margin-left: 0;
|
||||
position: fixed;
|
||||
z-index: 5;
|
||||
top: 12px;
|
||||
{% if menu_left %}right: calc(100% - 250px + 12px){% else %}right: 12px;{% endif %};
|
||||
background-color: {{darken(primary, 0.75)}};
|
||||
color: {{background}};
|
||||
}
|
||||
|
||||
/*#btn.active div {
|
||||
width: 35px;
|
||||
height: 2px;
|
||||
margin-bottom: 8px;
|
||||
}*/
|
||||
|
||||
#btn.active:parent {
|
||||
grid-template-columns: auto;
|
||||
}
|
||||
|
||||
|
||||
#menu {
|
||||
position: fixed;
|
||||
z-index: 4;
|
||||
overflow: auto;
|
||||
top: 0px;
|
||||
opacity: 0;
|
||||
padding: 20px 0px;
|
||||
width: 250px;
|
||||
height: 100%;
|
||||
transition: all var(--trans-speed) ease;
|
||||
{% if menu_left %}left{% else %}right{% endif %}: -250px;
|
||||
}
|
||||
|
||||
#menu.active {
|
||||
{% if menu_left %}left{% else %}right{% endif %}: 0;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#menu #items {
|
||||
/*margin-top: 50px;*/
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
#menu a:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#menu {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#menu .item {
|
||||
display: block;
|
||||
position: relative;
|
||||
font-size: 2em;
|
||||
transition: all var(--trans-speed);
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
#menu .title-item {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
#items .sub-item {
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
#items .item:not(.title-item):hover {
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
#items .sub-item:hover {
|
||||
padding-left: 60px !important;
|
||||
}
|
||||
|
||||
/*#menu details .item:hover {
|
||||
padding-left: 60px;
|
||||
}*/
|
||||
|
||||
#items summary {
|
||||
cursor: pointer;
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
#items details[open]>.item:not(details) {
|
||||
animation-name: fadeInDown;
|
||||
animation-duration: var(--trans-speed);
|
||||
}
|
||||
|
||||
|
||||
#items summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#items details summary:after {
|
||||
content: " +";
|
||||
}
|
||||
|
||||
#items details[open] summary:after {
|
||||
content: " -";
|
||||
}
|
||||
|
||||
|
||||
#btn, #btn * {
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
#menu {
|
||||
will-change: transform, opacity;
|
||||
}
|
||||
|
||||
|
||||
@keyframes fadeInDown {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-1.25em);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
12
paws/frontend/style/oauth.css
Normal file
|
@ -0,0 +1,12 @@
|
|||
/* Oauth pages */
|
||||
#oauth {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#oauth .accept {
|
||||
background-color: {{darken(positive, 0.8)}};
|
||||
}
|
||||
|
||||
#oauth .reject {
|
||||
background-color: {{darken(negative, 0.8)}};
|
||||
}
|
82
paws/frontend/style/profile.css
Normal file
|
@ -0,0 +1,82 @@
|
|||
/* Profile page */
|
||||
#profile #user.grid-container {
|
||||
grid-template-columns: 100px auto;
|
||||
}
|
||||
|
||||
#profile .header img {
|
||||
max-height: 500px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
#profile .icon img {
|
||||
height: 100px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
#profile .info .name {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#tablediv {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
#table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 2px 2px;
|
||||
width: 100%;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
#table td {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#table .key {
|
||||
min-width: 100px;
|
||||
background-color: {{darken(primary, 0.9)}};
|
||||
}
|
||||
|
||||
#table .value {
|
||||
background-color: {{desaturate(darken(primary, 0.9), 0.85)}};
|
||||
}
|
||||
/*
|
||||
#posts {
|
||||
margin-top: 15px;
|
||||
}*/
|
||||
|
||||
#posts .title {
|
||||
margin: var(--gap) 0;
|
||||
}
|
||||
|
||||
#profile .pagination {
|
||||
margin: var(--gap) 0;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#profile .pagination a {
|
||||
padding: 8px;
|
||||
box-shadow: var(--shadow)
|
||||
}
|
||||
|
||||
#profile .pagination a:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#profile .pagination .prev {
|
||||
background-color: var(--negative-dark);
|
||||
}
|
||||
|
||||
#profile .pagination .next {
|
||||
background-color: var(--positive-dark);
|
||||
}
|
||||
|
||||
#profile .pagination .prev:hover {
|
||||
color: var(--background);
|
||||
background-color: var(--negative);
|
||||
}
|
||||
|
||||
#profile .pagination .next:hover {
|
||||
color: var(--background);
|
||||
background-color: var(--positive);
|
||||
}
|
50
paws/frontend/style/settings.css
Normal file
|
@ -0,0 +1,50 @@
|
|||
/* generic settings */
|
||||
.settings .grid-container {
|
||||
grid-template-columns: 150px auto;
|
||||
}
|
||||
|
||||
.settings .label {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.settings input {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.settings textarea {
|
||||
height: 5em;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.settings .submit {
|
||||
margin-top: var(--gap);
|
||||
}
|
||||
|
||||
.settings .input img {
|
||||
margin: 20px auto 0 auto;
|
||||
}
|
||||
|
||||
|
||||
/* admin settings page */
|
||||
{% if cookie_user and cookie_user.config.get('enable_tooltips', True) %}
|
||||
#settings #name:hover::after{
|
||||
content: "Instance info displayed on the homepage";
|
||||
}
|
||||
|
||||
#settings #open:hover::after {
|
||||
content: "Allow new user registrations";
|
||||
}
|
||||
|
||||
#require_approval:hover::after {
|
||||
content: "Require an admin or mod to approve new accounts";
|
||||
}
|
||||
|
||||
#domain_approval:hover::after {
|
||||
content: "Require an admin or mod to approve an instance for federation";
|
||||
/*left: -100px;*/
|
||||
}
|
||||
|
||||
#secure:hover::after {
|
||||
content: "Require other instances to sign GETs";
|
||||
}
|
||||
{% endif %}
|
26
paws/frontend/style/status.css
Normal file
|
@ -0,0 +1,26 @@
|
|||
.status .header {
|
||||
grid-template-columns: 50px auto;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.status .avatar a {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.status .avatar img {
|
||||
max-width: 50;
|
||||
/* max-height: 100px; */
|
||||
}
|
||||
|
||||
.status .user-info {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.status .user-info .user {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.status .content {
|
||||
margin-top: var(--gap);
|
||||
}
|
|
@ -1,209 +1,195 @@
|
|||
import json, socket, os, re
|
||||
import aiohttp, validators, urllib3
|
||||
import functools, json, os, pytz, re, sys, socket
|
||||
|
||||
from IzzyLib import logging, color
|
||||
from IzzyLib.http import HttpClient, SetClient
|
||||
from IzzyLib.misc import DefaultDict, DotDict
|
||||
from base64 import b64decode, b64encode
|
||||
from sanic import response
|
||||
from datetime import datetime
|
||||
from hashlib import md5
|
||||
from pytz import timezone
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.template import aiohttpTemplate
|
||||
from IzzyLib.cache import LRUCache
|
||||
|
||||
from .config import VERSION
|
||||
from .config import config
|
||||
|
||||
|
||||
httpclient = urllib3.PoolManager(num_pools=100, timeout=urllib3.Timeout(connect=15, read=15))
|
||||
themes = {
|
||||
'blue': {'primary': '#55e'},
|
||||
'green': {'primary': '#2e5'},
|
||||
'orange': {'primary': '#e52'},
|
||||
'red': {'primary': '#e24'},
|
||||
'pink': {'primary': '#e29'},
|
||||
'purple': {'primary': '#a2e'},
|
||||
'yellow': {'primary': '#ed2'}
|
||||
}
|
||||
|
||||
|
||||
class cache:
|
||||
url = LRUCache()
|
||||
def mkhash(string, salt=config.salt, alg='blake'):
|
||||
hashalg = hashalgs.get(alg.lower())
|
||||
|
||||
if not hashalg:
|
||||
raise KeyError(f'Not a valid hash algorithm: {alg}')
|
||||
|
||||
string = string.encode('UTF-8') if type(string) != bytes else string
|
||||
salt = salt.encode('UTF-8') if type(salt) != bytes else salt
|
||||
|
||||
newhash = hashalg() if alg == 'md5' else hashalg.new()
|
||||
newhash.update(string)
|
||||
newhash.update(salt)
|
||||
return newhash.hexdigest()
|
||||
|
||||
|
||||
def error(request, code, msg, isjson=False):
|
||||
if isjson or request.get('jsonreq'):
|
||||
return json_error(code, msg)
|
||||
|
||||
|
||||
def GetTheme(name):
|
||||
defaults = {
|
||||
'primary': '#e7a',
|
||||
'secondary': '#e7a',
|
||||
'background': '#191919',
|
||||
'positive': '#ada',
|
||||
'negative': '#daa'
|
||||
}
|
||||
|
||||
defaults.update(themes.get(name, {}))
|
||||
return defaults
|
||||
|
||||
|
||||
def CssTimestamp(*args):
|
||||
timestamp = 0
|
||||
|
||||
for name in args:
|
||||
filename = config.frontend.join(f'{name}.css')
|
||||
timestamp += int(filename.mtime())
|
||||
|
||||
return timestamp
|
||||
|
||||
|
||||
def Error(request, code, msg=None):
|
||||
message = msg if msg else ''
|
||||
|
||||
if any(map(request.path.startswith, ['/status', '/actor'])) or JsonCheck(request):
|
||||
return JsonResp({'error': message}, code)
|
||||
|
||||
else:
|
||||
return http_error(request, code, msg)
|
||||
cont_type = 'text/html'
|
||||
data = {
|
||||
'login_token': request.cookies.get('login_token') if not isinstance(request, str) else '',
|
||||
'code': str(code),
|
||||
'msg': msg
|
||||
}
|
||||
|
||||
return config.template.response(f'error.haml', request, {'data': data, 'msg': message}, status=code)
|
||||
|
||||
|
||||
def json_error(code, error):
|
||||
error_body = json.dumps({'error': error})
|
||||
cont_type = 'application/json'
|
||||
return aiohttp.web.Response(body=error_body, content_type=cont_type, status=code)
|
||||
def FetchActor(url, user=None):
|
||||
url = url.split('#')[0]
|
||||
headers = {'Accept': 'application/activity+json'}
|
||||
|
||||
if user:
|
||||
resp = Client.signed_request(user.privkey, f'https://{config.web_domain}/actor/{user.handle}', url, headers=headers)
|
||||
|
||||
def http_error(request, code, msg):
|
||||
data = {'msg': msg, 'code': str(code)}
|
||||
return aiohttpTemplate('error.html', data, request, status=code)
|
||||
else:
|
||||
resp = Client.request(url, headers=headers)
|
||||
|
||||
|
||||
def fed_domain(user, domain):
|
||||
data = fetch(f'https://{domain}/.well-known/webfinger?resource=acct:{user}@{domain}')
|
||||
|
||||
if not data:
|
||||
logging.error(f'User doesn\'t exist: {user}@{domain}')
|
||||
if not resp.json():
|
||||
logging.verbose('functions.FetchActor: Failed to fetch actor:', url)
|
||||
logging.debug(f'Error {resp.status}: {resp.body}')
|
||||
return
|
||||
|
||||
wf_data = data.get('subject')
|
||||
user_data = wf_data.replace('acct:', '').split('@')
|
||||
actor = resp.json()
|
||||
actor.web_domain = urlparse(url).netloc
|
||||
actor.shared_inbox = actor.inbox
|
||||
actor.pubkey = None
|
||||
actor.handle = actor.preferredUsername
|
||||
|
||||
return user_data[1]
|
||||
if actor.get('endpoints'):
|
||||
actor.shared_inbox = actor.endpoints.get('sharedInbox', actor.inbox)
|
||||
|
||||
if actor.get('publicKey'):
|
||||
actor.pubkey = actor.publicKey.get('publicKeyPem')
|
||||
|
||||
return actor
|
||||
|
||||
|
||||
def get_nodeinfo(instance):
|
||||
domain = urlparse(instance).netloc if instance.startswith('http') else instance
|
||||
|
||||
nodeinfo = fetch(f'https://{domain}/nodeinfo/2.0.json')
|
||||
|
||||
if not nodeinfo or (isinstance(nodeinfo, dict) and nodeinfo.get('error')):
|
||||
logging.debug('Wrong nodeinfo url. Finding correct one...')
|
||||
wk_url = f'https://{domain}/.well-known/nodeinfo'
|
||||
well_known = fetch(wk_url)
|
||||
|
||||
if not well_known:
|
||||
logging.debug(f'failed to fetch {wk_url}')
|
||||
return
|
||||
|
||||
ni_url = None
|
||||
|
||||
try:
|
||||
for link in well_known['links']:
|
||||
if link['rel'].startswith('http://nodeinfo.diaspora.software/ns/schema/2'):
|
||||
ni_url = link['href']
|
||||
|
||||
except Exception as e:
|
||||
logging.debug(f'Invalid nodeinfo data, Error: {e}')
|
||||
return
|
||||
|
||||
nodeinfo = fetch(ni_url)
|
||||
|
||||
if not nodeinfo:
|
||||
logging.debug(f'Failed to fetch nodeinfo for {domain}')
|
||||
|
||||
return nodeinfo['software'] if nodeinfo else None
|
||||
def FetchApi(domain):
|
||||
return Client.request(f'https://{domain}/api/v1/instance').json()
|
||||
|
||||
|
||||
def domain_check(domain):
|
||||
stripped = domain.replace(' ', '')
|
||||
return stripped if validators.domain(stripped) else None
|
||||
@functools.lru_cache(maxsize=2048)
|
||||
def FetchWebfingerAcct(handle, domain):
|
||||
data = DefaultDict({'actor': None})
|
||||
webfinger = Client.request(f'https://{domain}/.well-known/webfinger?resource=acct:{handle}@{domain}')
|
||||
|
||||
if not webfinger.body:
|
||||
return
|
||||
|
||||
data.handle, data.domain = webfinger.json().subject.replace('acct:', '').split('@')
|
||||
|
||||
for link in webfinger.json().links:
|
||||
if link['rel'] == 'self' and link['type'] == 'application/activity+json':
|
||||
data.actor = link['href']
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def user_check(path):
|
||||
parsed = path.replace('.json', '').split('/')
|
||||
def JsonCheck(request):
|
||||
if any(map(request.path.startswith, ['/actor', '/inbox', '/status'])) or request.path.endswith('.json'):
|
||||
return True
|
||||
|
||||
if (parsed[1] == 'users' and len(parsed) < 4) or (parsed[1].startswith('@') and len(parsed) < 3):
|
||||
try:
|
||||
int(parsed[-1])
|
||||
return False
|
||||
accept = request.headers.get('Accept')
|
||||
|
||||
except ValueError:
|
||||
return True
|
||||
if not accept:
|
||||
return
|
||||
|
||||
mimes = accept.split(',')
|
||||
|
||||
if any(mime in ['application/json', 'application/activity+json'] for mime in mimes):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def parse_sig(signature, short=False):
|
||||
if not signature:
|
||||
return
|
||||
|
||||
for line in signature.split(','):
|
||||
if 'keyid' in line.lower():
|
||||
actor = line.split('=')[1].split('#')[0].replace('"', '')
|
||||
return urlparse(actor).netloc if short else actor
|
||||
|
||||
|
||||
def parse_ua(agent):
|
||||
if not agent:
|
||||
return
|
||||
|
||||
url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]))+', agent)
|
||||
|
||||
if not url:
|
||||
if 'mozilla' not in agent.lower():
|
||||
logging.debug('Failed to find url in user agent')
|
||||
|
||||
return 'unknown'
|
||||
|
||||
return urlparse(url[0]).netloc
|
||||
|
||||
|
||||
def dig(domain):
|
||||
if not domain or domain == 'unknown':
|
||||
return
|
||||
|
||||
try:
|
||||
return socket.gethostbyname(domain)
|
||||
|
||||
except socket.gaierror as e:
|
||||
logging.info(f'Failed to resolve IP: {e}')
|
||||
|
||||
|
||||
def distill_query(querydata):
|
||||
rawquery = ''
|
||||
|
||||
if len(querydata) > 0:
|
||||
for var in querydata:
|
||||
if rawquery == '':
|
||||
rawquery += f'{var}={querydata[var]}'
|
||||
|
||||
else:
|
||||
rawquery += f'&{var}={querydata[var]}'
|
||||
|
||||
return rawquery if rawquery != '?' else ''
|
||||
|
||||
|
||||
def css_ts():
|
||||
from .config import script_path
|
||||
|
||||
css_check = lambda css_file : int(os.path.getmtime(f'{script_path}/templates/{css_file}.css'))
|
||||
|
||||
color = css_check('color')
|
||||
layout = css_check('layout')
|
||||
|
||||
return color + layout
|
||||
|
||||
|
||||
def fetch(url, cached=True):
|
||||
if not url:
|
||||
logging.debug(f'Fetch was not fed a url')
|
||||
return
|
||||
|
||||
cached_data = cache.url.fetch(url)
|
||||
|
||||
if cached and cached_data:
|
||||
logging.debug(f'Returning cached data for {url}')
|
||||
return cached_data
|
||||
|
||||
headers = {
|
||||
'User-Agent': f'PAWS/{VERSION}',
|
||||
'Accept': 'application/json'
|
||||
def JsonResponse(data, status=200, headers=None, activity=False):
|
||||
kwargs = {
|
||||
'status': status
|
||||
}
|
||||
|
||||
try:
|
||||
logging.debug(f'Fetching new data for {url}')
|
||||
response = httpclient.request('GET', url, headers=headers)
|
||||
if activity:
|
||||
kwargs['content_type'] = 'application/activity+json'
|
||||
|
||||
except Exception as e:
|
||||
logging.debug(f'Failed to fetch {url}')
|
||||
logging.debug(e)
|
||||
return
|
||||
if headers:
|
||||
kwargs['headers'] = headers
|
||||
|
||||
if response.data == b'':
|
||||
logging.debug(f'Received blank data while fetching url: {url}')
|
||||
return
|
||||
return response.json(json.dumps(data), **kwargs)
|
||||
|
||||
try:
|
||||
data = json.loads(response.data)
|
||||
|
||||
if cached:
|
||||
logging.debug(f'Caching {url}')
|
||||
cache.url.store(url, data)
|
||||
class Datetime(object):
|
||||
def __init__(self, date: datetime=None):
|
||||
self.date = date if date else datetime.utcnow()
|
||||
|
||||
if data.get('error'):
|
||||
return
|
||||
|
||||
return data
|
||||
def __str__(self):
|
||||
return f'{self.string("%Y-%m-%d %H:%M:%S")}'
|
||||
|
||||
except Exception as e:
|
||||
logging.debug(f'Failed to load data: {response.data}')
|
||||
logging.debug(e)
|
||||
return
|
||||
|
||||
def ap_string(self):
|
||||
return self.string('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
|
||||
def string(self, format):
|
||||
return self.date.strftime(format)
|
||||
|
||||
|
||||
def timestamp(self, integer=True):
|
||||
ts = self.date.timestamp()
|
||||
return int(ts) if integer else ts
|
||||
|
||||
|
||||
def tz(self, timezone):
|
||||
return pytz.timezone(timezone).localize(self.date)
|
||||
|
||||
|
||||
Client = HttpClient(useragent=config.agent, **config.proxy.asDict(), timeout=5)
|
||||
SetClient(Client)
|
||||
|
|
|
@ -1,325 +1,191 @@
|
|||
import asyncio, json, binascii, base64, traceback, aiohttp
|
||||
import binascii, base64, json, hashlib, multiprocessing, traceback
|
||||
|
||||
from urllib.parse import urlparse, quote_plus, unquote_plus
|
||||
from random import choice
|
||||
from os.path import isfile
|
||||
from http import client as HTTP
|
||||
from urllib.parse import quote, urlparse, unquote
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.misc import boolean
|
||||
from aiohttp.http_exceptions import *
|
||||
from aiohttp.client_exceptions import *
|
||||
from Crypto.PublicKey import RSA
|
||||
from IzzyLib.cache import LRUCache
|
||||
from IzzyLib.http import ParseSig, PkcsHeaders, VerifyRequest
|
||||
from IzzyLib.misc import DefaultDict, DotDict
|
||||
from base64 import b64encode, b64decode
|
||||
from sanic.request import Request as SanicRequest
|
||||
from sanic.response import raw, redirect, json as rjson
|
||||
from sanic import exceptions as exc
|
||||
from tldextract import extract
|
||||
from urllib.parse import parse_qsl
|
||||
|
||||
from .signature import validate, pass_hash, sign_headers
|
||||
from .functions import error, user_check, domain_check, parse_sig, parse_ua, dig, distill_query, get_nodeinfo, httpclient
|
||||
from .config import MASTOCONFIG, PAWSCONFIG, VERSION, script_path
|
||||
from .database import pawsdb, query, trans, ban_check, user_ban_check, banned_user_check, wl_check, keys, user_domain_ban_check, admin_check, instance_check, instances
|
||||
from .config import config
|
||||
from .database import db
|
||||
from .errors import Teapot
|
||||
from .functions import Client, FetchActor, FetchWebfingerAcct
|
||||
|
||||
|
||||
paws_host = PAWSCONFIG['domain']
|
||||
masto_host = MASTOCONFIG['domain']
|
||||
masto_path = PAWSCONFIG['mastopath']
|
||||
|
||||
blocked_agents = [
|
||||
'gabsocial',
|
||||
'kiwifarms',
|
||||
'fedichive',
|
||||
'liveview',
|
||||
'freespeech',
|
||||
'shitposter.club',
|
||||
'baraag',
|
||||
'gameliberty',
|
||||
'neckbeard',
|
||||
'soapbox',
|
||||
'qoto',
|
||||
'archive'
|
||||
'spinster',
|
||||
'kiwifarms'
|
||||
]
|
||||
|
||||
auth_paths = [
|
||||
'/@',
|
||||
'/users'
|
||||
domain_bans = [
|
||||
'b77625108b127dc1b15640ac536c8e2991b83ea20841a42e70927f96434fe9c2',
|
||||
'f1e9527ea188da343fe79f23855f80476cedb017e3880432ab22467eaf992f44',
|
||||
'a67a3f85d90881ae32716d0eaf5a348b53096e07ea38a20797d74824074e281b',
|
||||
'75e80dd194bc635186cf0b4a07524d7746b4b261cbd5fb15007189e4fccfbbb6',
|
||||
'56638777979b0e88cd6cd67723f4fc152eae7ada5c266cdab45e8bb29af6be24',
|
||||
'acb2a6826ab0741142935b0e0454b381c0b32a5dfcf54bd43c354379263aec1f',
|
||||
'e249dc1503a399ad9fb807ded9be6dd42ca9ea04fa04adb8f794435e1ddb8554',
|
||||
'feea7dc93ff4b6b7c06bc3d2dbd6868b259dccd664309c859ed56d3480971617',
|
||||
'f0f7b4b28f4142e276d39b1fddfe621e81f72d3be86296a6323d303164f423a2',
|
||||
'bfaa1ed5a206867a79f7fbd187f98e035a1cee5fa1e3821740dfc0a9cb3d6ecc',
|
||||
'0dbb3144d7b6dff976d97a54be2e94da3559d089eb5c00f871e18318afb4f047',
|
||||
'56da8b2c7030ff79b9acba7a23fb6750a165a88505e0dcac85478d537d88e90f',
|
||||
'6dd58fd367069c428c481182a8a6f62af21b7a33207b12cb15140da06b8401af',
|
||||
'e7c641cf9cd8b5c4513e22d0dfd3f914835a16bd4011801dfa0976fedf61bf02',
|
||||
'a3da30d2dfb76009289509cb3f35abd0a43b0736f0abf1ddd17c05685902a6fb',
|
||||
'19452ff02670099643197b3fec15c0d43e42a3dbbe83b0fb4d039d5f77d1932e',
|
||||
'e8bd7afb2125b7ea5e1b885fac2a657d817eec289ed870aa3d1d0acbe6aded8f'
|
||||
]
|
||||
|
||||
admin_paths = [
|
||||
'/paws/action',
|
||||
'/paws/list'
|
||||
]
|
||||
|
||||
error_msgs = {
|
||||
404: 'Not found',
|
||||
500: 'Server did an oopsie'
|
||||
}
|
||||
|
||||
|
||||
def parse_headers(headers, enc=True):
|
||||
new_headers = {}
|
||||
|
||||
for header in headers:
|
||||
key, value = [item.decode() for item in header]
|
||||
|
||||
if key.lower() in ['content-encoding', 'transfer-encoding'] and not enc:
|
||||
continue
|
||||
|
||||
if key in new_headers:
|
||||
new_headers[key] + '; ' + value
|
||||
|
||||
else:
|
||||
new_headers[key] = value
|
||||
|
||||
return new_headers
|
||||
|
||||
|
||||
async def passthrough2(request, headers):
|
||||
mastohost = PAWSCONFIG['mastohost']
|
||||
raw_data = await request.read()
|
||||
is_json = request.get('jsonreq', False)
|
||||
Headers = parse_headers(request.raw_headers)
|
||||
Headers['Proxy'] = ''
|
||||
|
||||
try:
|
||||
timeout = aiohttp.ClientTimeout(total=5)
|
||||
async with aiohttp.request(request.method, f'http://{mastohost}{request.path}?{request.query_string}', headers=Headers, data=raw_data, timeout=timeout, allow_redirects=False) as resp:
|
||||
data = await resp.read()
|
||||
|
||||
if resp.status not in [200, 202, 301, 302]:
|
||||
if data in [b'Request not signed', 'Request not signed']:
|
||||
err_msg = 'Missing signature'
|
||||
logging.debug(err_msg)
|
||||
|
||||
else:
|
||||
err_msg = f'Recieved error {resp.status} from Mastodon'
|
||||
logging.debug(err_msg)
|
||||
|
||||
return error(request, resp.status, f'Failed to forward request')
|
||||
|
||||
resp_headers = parse_headers(resp.raw_headers, False)
|
||||
|
||||
return aiohttp.web.Response(body=data, headers=resp_headers, status=resp.status)
|
||||
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return error(request, 504, f'Failed to connect to Mastodon')
|
||||
|
||||
|
||||
async def passthrough(request, headers):
|
||||
mastohost = PAWSCONFIG['mastohost']
|
||||
req_data = await request.read() if request.body_exists else None
|
||||
is_json = request.get('jsonreq', False)
|
||||
|
||||
try:
|
||||
resp = httpclient.request(request.method, f'http://{mastohost}{request.path}?{request.query_string}', body=req_data, headers=headers, redirect=False)
|
||||
data = resp.data
|
||||
|
||||
if resp.status not in [200, 202, 301, 302]:
|
||||
if data in [b'Request not signed', 'Request not signed']:
|
||||
err_msg = 'Missing signature'
|
||||
logging.debug(err_msg)
|
||||
|
||||
else:
|
||||
err_msg = f'Recieved error {resp.status} from Mastodon'
|
||||
logging.debug(err_msg)
|
||||
|
||||
return error(request, resp.status, f'Failed to forward request')
|
||||
|
||||
resp_headers = dict(resp.headers)
|
||||
|
||||
if resp_headers.get('Content-Encoding'):
|
||||
del resp_headers['Content-Encoding']
|
||||
|
||||
if resp_headers.get('Transfer-Encoding'):
|
||||
del resp_headers['Transfer-Encoding']
|
||||
|
||||
return aiohttp.web.Response(body=data, headers=resp_headers, status=resp.status)
|
||||
|
||||
except ClientConnectorError:
|
||||
traceback.print_exc()
|
||||
return error(request, 504, f'Failed to connect to Mastodon')
|
||||
|
||||
|
||||
async def http_filter(app, handler):
|
||||
async def http_filter_handler(request):
|
||||
signature = request.headers.get('signature')
|
||||
sig_domain = parse_sig(signature, short=True)
|
||||
|
||||
ua = request.headers.get('user-agent').lower()
|
||||
ua_domain = parse_ua(ua)
|
||||
domain = ua_domain if not sig_domain else sig_domain
|
||||
|
||||
token = request.cookies.get('paws_token')
|
||||
user_data = None if not token else pawsdb.users.get(query.token == token)
|
||||
user = (user_data['handle'], user_data['instance']) if user_data and user_data.get('instance') else (None, None)
|
||||
|
||||
real_ip = request.headers.get('X-Real-Ip', request.remote)
|
||||
ua_ip = dig(ua_domain)
|
||||
|
||||
instance = domain if domain != 'unknown' else user[1]
|
||||
allow = instance_check(instance)
|
||||
request['jsonreq'] = True if 'json' in request.headers.get('Accept', '') or request.path.endswith('.json') else False
|
||||
|
||||
# add logged in user data to the request for the frontend
|
||||
request['user'] = user_data
|
||||
request['admin'] = admin_check(user_data['handle']) if user_data else None
|
||||
|
||||
# block nazis and general garbage
|
||||
for agent in blocked_agents:
|
||||
if agent in ua:
|
||||
logging.debug(f'Blocked garbage: {domain}')
|
||||
return error(request, 418, 'This teapot kills fascists')
|
||||
|
||||
# Disable rss feeds
|
||||
if PAWSCONFIG['disable_rss'] and request.path.endswith('.rss'):
|
||||
return error(request, 403, 'RSS feeds disabled')
|
||||
|
||||
if request.path in ['/paws/actor', '/paws/inbox', '/.well-known/webfinger'] and request.host != paws_host:
|
||||
return aiohttp.web.HTTPFound('/paws')
|
||||
|
||||
# give up if a domain can't be found'
|
||||
if not domain:
|
||||
return error(request, 401, 'Can\'t find instance domain')
|
||||
|
||||
# block any suspended instances
|
||||
if ban_check(domain):
|
||||
logging.debug(f'Blocked instance: {domain}')
|
||||
return error(request, 403, 'Forbidden')
|
||||
|
||||
# block any suspended users
|
||||
if banned_user_check(user):
|
||||
logging.debug(f'Blocked user: {domain}')
|
||||
return error(request, 403, 'Access Denied')
|
||||
|
||||
# prevent unauthed users from accessing the instance lists
|
||||
if any(map(request.path.startswith, admin_paths)) and not request['admin']:
|
||||
return aiohttp.web.HTTPFound('/paws/login')
|
||||
|
||||
if any(map(request.path.startswith, auth_paths)) and request.method == 'GET':
|
||||
# Check signatures if auth fetches are off
|
||||
if not user_check(request.path):
|
||||
if PAWSCONFIG['require_approval'] and not allow:
|
||||
if allow != False:
|
||||
status, message = (401, 'Instance awaiting approval or rejection')
|
||||
instances('add', instance)
|
||||
|
||||
else:
|
||||
status, message = (403, 'Rejected')
|
||||
|
||||
return error(request, status, message)
|
||||
|
||||
if not MASTOCONFIG['auth_fetch']:
|
||||
if signature:
|
||||
actor = parse_sig(signature)
|
||||
|
||||
if not (await validate(actor, request)):
|
||||
logging.warning(f'Signature validation failed for: {actor}')
|
||||
return error(request, 401, 'signature check failed, signature did not match key')
|
||||
|
||||
elif real_ip == ua_ip and wl_check(domain):
|
||||
logging.info(f'Letting {domain} through')
|
||||
|
||||
else:
|
||||
msg = 'missing signature'
|
||||
logging.warning(msg)
|
||||
return error(request, 401, msg)
|
||||
|
||||
if not request['jsonreq']:
|
||||
if not token or not user_data:
|
||||
return aiohttp.web.HTTPFound(f'/paws/login?redir={quote_plus(request.path)}')
|
||||
|
||||
split_path = request.path.split('/')
|
||||
user = split_path[1].replace('@', '') if request.path.startswith('/@') else split_path[2]
|
||||
|
||||
if user_ban_check(user.lower(), (user_data['handle'].lower(), user_data['instance'])) or user_domain_ban_check(user.lower(), user_data['instance']):
|
||||
return error(request, 403, 'Access Denied')
|
||||
|
||||
if signature and wl_check(domain) and request.method == 'GET':
|
||||
logging.warning(f'{domain} has started signing requests and can be removed from the whitelist')
|
||||
|
||||
if not signature and real_ip == ua_ip and wl_check(domain) and request.method == 'GET':
|
||||
logging.debug(f'Signing fetch for whitelisted instance: {domain}')
|
||||
|
||||
HEADERS = {
|
||||
'(request-target)': f'get {request.path}',
|
||||
'Accept': 'application/json',
|
||||
'User-Agent': f'PAWS/{VERSION}; https://{masto_host}',
|
||||
'Host': masto_host,
|
||||
'X-Forwarded-For': request.headers.get('X-Forwarded-For', request.remote),
|
||||
'X-Forwarded-Port': '443',
|
||||
'X-Forwarded-Proto': 'https',
|
||||
'X-Real-Ip': request.headers.get('X-Real-Ip', request.remote)
|
||||
}
|
||||
HEADERS['signature'] = sign_headers(HEADERS, 'default', f'https://{paws_host}/paws/actor#main-key')
|
||||
HEADERS.pop('(request-target)')
|
||||
|
||||
else:
|
||||
HEADERS = request.headers
|
||||
|
||||
if not request.path.startswith('/paws'):
|
||||
masto_file = f'{masto_path}/public{request.path}'
|
||||
|
||||
if isfile(masto_file):
|
||||
return aiohttp.web.FileResponse(masto_file, headers=HEADERS)
|
||||
|
||||
return_data = await passthrough(request, HEADERS)
|
||||
return return_data
|
||||
|
||||
return (await handler(request))
|
||||
return http_filter_handler
|
||||
|
||||
|
||||
# Fucking trailing slashes
|
||||
async def http_trailing_slash(app, handler):
|
||||
async def http_trailing_slash_handler(request):
|
||||
if request.path != '/' and request.path.endswith('/'):
|
||||
return aiohttp.web.HTTPFound(request.path[:-1])
|
||||
|
||||
return (await handler(request))
|
||||
return http_trailing_slash_handler
|
||||
|
||||
|
||||
# Custom error handler
|
||||
async def http_error(app, handler):
|
||||
async def http_error_handler(request):
|
||||
try:
|
||||
response = await handler(request)
|
||||
|
||||
#except aiohttp.web.HTTPException as ex:
|
||||
# message = error_msgs.get(ex.status, 'Server did an oopsie')
|
||||
# response = error(request, ex.status, message)
|
||||
|
||||
except Exception as e:
|
||||
if getattr(e, 'status', None):
|
||||
message = error_msgs.get(e.status, 'Server did an oopsie')
|
||||
response = error(request, e.status, message)
|
||||
|
||||
else:
|
||||
traceback.print_exc()
|
||||
response = error(request, 500, e)
|
||||
|
||||
return response
|
||||
return http_error_handler
|
||||
|
||||
|
||||
async def http_server_header(request, response):
|
||||
response.headers['Server'] = f'PAWS/{VERSION}'
|
||||
|
||||
phrases = [
|
||||
'trans rights are human rights',
|
||||
'trans rights',
|
||||
'be gay, do crimes',
|
||||
'punch nazis',
|
||||
'eat the rich',
|
||||
'im gay',
|
||||
'heck'
|
||||
blocked_domains = [extract(domain) for domain in domain_bans]
|
||||
hash_cache = LRUCache(4096)
|
||||
|
||||
paths = DotDict({
|
||||
'anon_api': [
|
||||
'/api/v1/apps',
|
||||
'/api/v1/instance'
|
||||
],
|
||||
'ap': [
|
||||
'/status',
|
||||
'/actor',
|
||||
'/inbox'
|
||||
],
|
||||
'cookie': [
|
||||
'/@',
|
||||
'/:',
|
||||
'/welcome',
|
||||
'/preferences',
|
||||
'/admin',
|
||||
'/oauth/authorize'
|
||||
],
|
||||
'log_ignore': [
|
||||
'/media',
|
||||
'/static',
|
||||
'/style',
|
||||
'/manifest',
|
||||
'/favicon'
|
||||
]
|
||||
})
|
||||
|
||||
value = choice(phrases)
|
||||
|
||||
response.headers['msg'] = value
|
||||
async def http_bans(request):
|
||||
# Let the request go through if it's basic resources needed for the error page
|
||||
if request.paths.media:
|
||||
return
|
||||
|
||||
if [agent for agent in blocked_agents if agent in request.headers.get('User-Agent', '').lower()]:
|
||||
raise Teapot('This teapot kills fascists')
|
||||
|
||||
domain_hash = hash_cache.fetch(request.ap.top_domain)
|
||||
|
||||
if not domain_hash:
|
||||
domain = request.ap.top_domain
|
||||
domain_hash = hashlib.sha256(domain.encode("utf-8")).hexdigest()
|
||||
hash_cache.store(domain, domain_hash)
|
||||
|
||||
if domain_hash in blocked_domains:
|
||||
raise Teapot('This teapot kills fascists')
|
||||
|
||||
|
||||
async def http_auth(request):
|
||||
if request.paths.media:
|
||||
return
|
||||
|
||||
if request.ap.web_domain == config.web_domain:
|
||||
return rjson({'error': 'unwilling to handle self'}, status=403)
|
||||
|
||||
if not request.paths.api_anon and request.paths.api:
|
||||
resp = handle_api_path(request)
|
||||
|
||||
if resp:
|
||||
return resp
|
||||
|
||||
if request.paths.ap:
|
||||
resp = handle_ap_path(request)
|
||||
|
||||
if resp:
|
||||
return
|
||||
return resp
|
||||
|
||||
if request.paths.cookie:
|
||||
resp = handle_web_path(request)
|
||||
|
||||
if resp:
|
||||
return resp
|
||||
|
||||
|
||||
async def http_headers(request, response):
|
||||
if not response.headers.get('Cache-Control'):
|
||||
if request.path.startswith('/system') or any(map(request.path.endswith, ['woff2'])):
|
||||
response.headers['Cache-Control'] = 'public,max-age=2628000,immutable'
|
||||
|
||||
else:
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
|
||||
response.headers['Server'] = f'PAWS/{config.version}'
|
||||
response.headers['Trans'] = 'Rights'
|
||||
|
||||
|
||||
async def http_access_log(request, response):
|
||||
if not request.path.endswith(('js', 'css', 'png', 'jpg', 'gif')):
|
||||
uagent = request.headers.get('user-agent')
|
||||
client_ip = request.headers.get('X-Real-IP', request.remote)
|
||||
if request.paths.log_ignore or response.status == 302:
|
||||
return
|
||||
|
||||
logging.info(f'{client_ip} {request.method} {request.path_qs} {response.status} "{uagent}"')
|
||||
uagent = request.headers.get('user-agent')
|
||||
address = request.forwarded.get('for', request.remote_addr)
|
||||
|
||||
logging.info(f'({multiprocessing.current_process().name}) {address} {request.method} {request.path} {response.status} "{uagent}"')
|
||||
|
||||
|
||||
def handle_web_path(request):
|
||||
with db.session() as s:
|
||||
handle = request.match_info.get('user')
|
||||
statusid = request.match_info.get('statusid')
|
||||
|
||||
if any(map(request.path.startswith, ['/@', '/:'])) and request.paths.json:
|
||||
return
|
||||
|
||||
if request.path.startswith('/@'):
|
||||
domainid = s.get.domainid(config.domain)
|
||||
user = s.fetch('user', handle=handle, domainid=domainid)
|
||||
|
||||
if not user or user.config.get('public'):
|
||||
return
|
||||
|
||||
if not request.cookie.token:
|
||||
if request.paths.json:
|
||||
return rjson({'error': 'Missing token'}, status=401)
|
||||
|
||||
else:
|
||||
return redirect(f'/login?redir={quote(request.path)}&query={quote(request.query_string)}')
|
||||
|
||||
elif not request.cookie.token:
|
||||
return redirect(f'/login?redir={quote(request.path)}&msg=InvalidToken')
|
||||
|
||||
|
||||
def handle_api_path(request):
|
||||
if not request.api.token or not request.api.user:
|
||||
logging.debug('middleware.http_auth: Invalid token:', request.api.token)
|
||||
return rjson({'error': 'Invalid token'}, status=401)
|
||||
|
||||
|
||||
def handle_ap_path(request):
|
||||
if not request.verify():
|
||||
logging.debug('middleware.http_auth: Signature verify failed')
|
||||
|
||||
if request.method == 'GET' and request.path.startswith('/actor') and len(request.path.split('/')) == 3:
|
||||
pass
|
||||
|
||||
else:
|
||||
return rjson({'error': 'Failed to verify signature'}, status=401)
|
||||
|
||||
class InvalidAttr(object):
|
||||
pass
|
||||
|
|
105
paws/oauth.py
|
@ -1,105 +0,0 @@
|
|||
import os
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import http.client as http
|
||||
|
||||
from IzzyLib import logging
|
||||
from urllib.parse import urlencode, urlparse
|
||||
from mastodon import Mastodon
|
||||
|
||||
from .config import PAWSCONFIG, MASTOCONFIG, VERSION, stor_path
|
||||
|
||||
|
||||
HEADERS = {
|
||||
'User-Agent': f'PAWS/{VERSION}',
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
SCOPES = ['read:accounts']
|
||||
REDIR_URI = f'https://{MASTOCONFIG["domain"]}/paws/auth'
|
||||
WEBSITE = 'https://git.barkshark.xyz/izaliamae/paws'
|
||||
|
||||
|
||||
# some instances use a different domain for federation
|
||||
def get_webhost(domain):
|
||||
try:
|
||||
conn = http.HTTPSConnection(domain)
|
||||
conn.request('GET', '/.well-known/host-meta', headers=HEADERS)
|
||||
response = conn.getresponse()
|
||||
|
||||
if response.status == 301:
|
||||
url = response.msg.get('Location')
|
||||
return urlparse(url).netloc
|
||||
|
||||
elif response.status != 200:
|
||||
return ('error', f'Failed to fetch host-meta: received error {response.status}', 'heck')
|
||||
|
||||
except:
|
||||
msg = f'Failed to connect to {domain}'
|
||||
logging.error(msg)
|
||||
return ('error', msg, 'heck')
|
||||
|
||||
return domain
|
||||
|
||||
|
||||
def create_app(domain):
|
||||
instance = get_webhost(domain)
|
||||
|
||||
if 'error' in instance:
|
||||
return instance
|
||||
|
||||
try:
|
||||
app_id, app_secret = Mastodon.create_app(
|
||||
f'PAWS @ {MASTOCONFIG["domain"]}',
|
||||
api_base_url=instance,
|
||||
scopes=SCOPES,
|
||||
redirect_uris=REDIR_URI,
|
||||
website=WEBSITE
|
||||
)
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
logging.error(f'Failed to create app: {e}')
|
||||
return ('error', 'Failed to create app', 'heck')
|
||||
|
||||
try:
|
||||
client = Mastodon(
|
||||
api_base_url=instance,
|
||||
client_id=app_id,
|
||||
client_secret=app_secret
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
logging.error(f'Failed to create app: {e}')
|
||||
return ('error', 'Failed to create app', 'heck')
|
||||
|
||||
return (app_id, app_secret, client.auth_request_url(redirect_uris=REDIR_URI, scopes=SCOPES))
|
||||
|
||||
|
||||
def login(user, code):
|
||||
fetch = Mastodon(
|
||||
api_base_url=user['domain'],
|
||||
client_id=user['appid'],
|
||||
client_secret=user['appsecret']
|
||||
)
|
||||
|
||||
try:
|
||||
token = fetch.log_in(redirect_uri=REDIR_URI, scopes=SCOPES, code=code)
|
||||
|
||||
except:
|
||||
msg = 'Failed to fetch token'
|
||||
logging.error(msg)
|
||||
return ('error', msg)
|
||||
|
||||
try:
|
||||
client = Mastodon(api_base_url=user['domain'], access_token=token)
|
||||
fetch_user = client.me()
|
||||
|
||||
except:
|
||||
msg = 'Failed to get user info'
|
||||
logging.error(msg)
|
||||
return ('error', msg)
|
||||
|
||||
return (token, fetch_user)
|
204
paws/request.py
Normal file
|
@ -0,0 +1,204 @@
|
|||
import json
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.cache import LRUCache
|
||||
from IzzyLib.http import ParseSig, PkcsHeaders, VerifyHeaders, VerifyRequest
|
||||
from IzzyLib.misc import DotDict
|
||||
from sanic.request import Request
|
||||
from sanic.response import raw, redirect, json as rjson
|
||||
from tldextract import extract
|
||||
from urllib.parse import parse_qsl, quote, urlparse, unquote
|
||||
|
||||
from .config import config
|
||||
from .database import db
|
||||
from .errors import Teapot
|
||||
from .functions import Client, FetchActor, FetchWebfingerAcct
|
||||
|
||||
|
||||
paths = DotDict({
|
||||
'anon_api': [
|
||||
'/api/v1/apps',
|
||||
'/api/v1/instance'
|
||||
],
|
||||
'ap': [
|
||||
'/status',
|
||||
'/actor',
|
||||
'/inbox'
|
||||
],
|
||||
'cookie': [
|
||||
'/@',
|
||||
'/:',
|
||||
'/welcome',
|
||||
'/preferences',
|
||||
'/admin',
|
||||
'/oauth/authorize'
|
||||
],
|
||||
'log_ignore': [
|
||||
'/media',
|
||||
'/static',
|
||||
'/style',
|
||||
'/manifest',
|
||||
'/favicon'
|
||||
],
|
||||
'log_ext_ignore': [
|
||||
'png',
|
||||
'svg',
|
||||
'js',
|
||||
'jpg',
|
||||
'css',
|
||||
'woff2',
|
||||
'ttf'
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
class Headers(DotDict):
|
||||
def __init__(self, headers: dict):
|
||||
headers_lower = {k.lower(): v for k,v in headers.items()}
|
||||
super().__init__(headers_lower)
|
||||
|
||||
|
||||
def __setitem__(self, k, v):
|
||||
DotDict.__setitem__(self, k.lower(), v)
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return ', '.join([f'{k}={v}' for k,v in self.items()])
|
||||
|
||||
|
||||
def getall(self, k, default=None):
|
||||
return self.get(k.lower(), default)
|
||||
|
||||
|
||||
class Data(object):
|
||||
def __init__(self, request):
|
||||
self.request = request
|
||||
|
||||
|
||||
@property
|
||||
def combined(self):
|
||||
data = DotDict()
|
||||
|
||||
for item in [self.form, self.query, self.json]:
|
||||
data.update(item)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@property
|
||||
def query(self):
|
||||
data = {k: v for k,v in parse_qsl(self.request.query_string)}
|
||||
return DotDict(data)
|
||||
|
||||
|
||||
@property
|
||||
def form(self):
|
||||
data = {k: v[0] for k,v in self.request.form.items()}
|
||||
return DotDict(data)
|
||||
|
||||
|
||||
@property
|
||||
def files(self):
|
||||
return DotDict({k:v[0] for k,v in self.request.files.items()})
|
||||
|
||||
|
||||
### body functions
|
||||
@property
|
||||
def raw(self):
|
||||
try:
|
||||
return self.request.body
|
||||
except Exception as e:
|
||||
logging.error('middleware.Content.raw: failed to get body')
|
||||
logging.debug(f'{e.__class__.__name__}: {e}')
|
||||
return b''
|
||||
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
try:
|
||||
return self.raw.decode()
|
||||
except Exception as e:
|
||||
logging.error('middleware.Content.text: failed to get body')
|
||||
logging.debug(f'{e.__class__.__name__}: {e}')
|
||||
return ''
|
||||
|
||||
|
||||
@property
|
||||
def json(self):
|
||||
try:
|
||||
return DotDict(self.text)
|
||||
except Exception as e:
|
||||
logging.error('middleware.Content.json: failed to get body')
|
||||
logging.debug(f'{e.__class__.__name__}: {e}')
|
||||
data = '{}'
|
||||
return {}
|
||||
|
||||
|
||||
class HTTPRequest(Request):
|
||||
def __init__(self, url_bytes, headers, version, method, transport, app):
|
||||
super().__init__(url_bytes, headers, version, method, transport, app)
|
||||
|
||||
self.headers = Headers(headers)
|
||||
self.data = Data(self)
|
||||
self.cookie = DotDict({'token': None, 'user': None})
|
||||
self.__parse_path()
|
||||
|
||||
if self.paths.media:
|
||||
return
|
||||
|
||||
with db.session() as s:
|
||||
self.__parse_cookie(s)
|
||||
|
||||
|
||||
def alldata(self):
|
||||
return self.__combine_dicts(self.data.json, self.data.query, self.data.form)
|
||||
|
||||
|
||||
def __try_func(self, func, *args, default=None, **kwargs):
|
||||
try:
|
||||
return func(*args, *kwargs)
|
||||
except Exception as e:
|
||||
return default
|
||||
|
||||
|
||||
def __combine_dicts(self, *dicts):
|
||||
data = DotDict()
|
||||
|
||||
for item in dicts:
|
||||
data.update(item)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def __parse_path(self):
|
||||
self.paths = DotDict()
|
||||
self.paths.media = self.path.startswith('/paws/static')
|
||||
self.paths.log_ignore = any(map(self.path.endswith, paths.log_ext_ignore))
|
||||
self.paths.api = self.path.startswith('/api')
|
||||
self.paths.api_anon = any(map(self.path.startswith, paths.anon_api))
|
||||
self.paths.ap = any(map(self.path.startswith, paths.ap))
|
||||
self.paths.cookie = any(map(self.path.startswith, paths.cookie))
|
||||
self.paths.json = self.__json_check()
|
||||
|
||||
|
||||
def __json_check(self):
|
||||
if any(map(self.path.startswith, paths.ap)) or self.path.endswith('.json'):
|
||||
return True
|
||||
|
||||
accept = self.headers.get('Accept')
|
||||
|
||||
if accept:
|
||||
mimes = accept.split(',')
|
||||
|
||||
if any(mime in ['application/json', 'application/activity+json'] for mime in mimes):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def __parse_cookie(self, s):
|
||||
login_token = self.cookies.get('login_token')
|
||||
cookie = s.get.cookie(login_token)
|
||||
|
||||
if login_token and cookie:
|
||||
self.cookie = cookie
|
125
paws/routes.py
|
@ -1,125 +0,0 @@
|
|||
import os, sys, asyncio, aiohttp, aiohttp_jinja2, jinja2
|
||||
|
||||
from IzzyLib import logging, template, color
|
||||
from IzzyLib.template import buildTemplates, templateWatcher
|
||||
from ipaddress import ip_address as address
|
||||
from urllib.parse import urlparse
|
||||
from mastodon import Mastodon
|
||||
|
||||
from .config import PAWSCONFIG, MASTOCONFIG, VERSION, script_path
|
||||
from .functions import css_ts
|
||||
from .database import cleanup_users, admin_check
|
||||
from . import middleware, views, stor_path
|
||||
|
||||
|
||||
def webserver():
|
||||
web = aiohttp.web.Application(middlewares=[
|
||||
middleware.http_filter,
|
||||
middleware.http_trailing_slash,
|
||||
middleware.http_error
|
||||
])
|
||||
|
||||
web.on_response_prepare.append(middleware.http_server_header)
|
||||
web.on_response_prepare.append(middleware.http_access_log)
|
||||
|
||||
web.add_routes([
|
||||
aiohttp.web.route('GET', '/paws', views.get_paws),
|
||||
aiohttp.web.route('GET', '/paws/imgay', views.get_gay),
|
||||
aiohttp.web.route('POST', '/paws/action/{action}', views.post_paws),
|
||||
aiohttp.web.view('/paws/list/{list}', views.lists),
|
||||
aiohttp.web.view('/paws/login', views.login),
|
||||
aiohttp.web.route('GET', '/paws/logout', views.get_logout),
|
||||
aiohttp.web.route('GET', '/paws/auth', views.get_auth),
|
||||
aiohttp.web.route('GET', '/paws/style-{timestamp}.css', views.get_style),
|
||||
|
||||
aiohttp.web.route('GET', '/.well-known/webfinger', views.get_webfinger),
|
||||
aiohttp.web.route('POST', '/paws/inbox', views.post_inbox),
|
||||
aiohttp.web.route('GET', '/paws/actor', views.get_actor),
|
||||
|
||||
#aiohttp.web.route('GET', '/paws/outbox', views.get_outbox),
|
||||
#aiohttp.web.route('GET', '/paws/imgay', views.get_gay)
|
||||
])
|
||||
|
||||
template.addEnv({
|
||||
'css_ts': css_ts,
|
||||
'domain': MASTOCONFIG['domain'],
|
||||
'VERSION': VERSION,
|
||||
'len': len,
|
||||
'urlparse': urlparse,
|
||||
'admin_check': admin_check
|
||||
})
|
||||
|
||||
return web
|
||||
|
||||
|
||||
async def start_webserver():
|
||||
app = webserver()
|
||||
runner = aiohttp.web.AppRunner(app, access_log_format='%{X-Real-Ip}i %s %b "%r" "%{User-Agent}i"')
|
||||
await runner.setup()
|
||||
|
||||
listen = PAWSCONFIG['host']
|
||||
port = PAWSCONFIG['port']
|
||||
|
||||
if listen.startswith('unix:'):
|
||||
if sys.platform != 'win32':
|
||||
sock_listen = listen.replace('unix:', '')
|
||||
|
||||
logging.info(f'Starting webserver at socket: {sock_listen}')
|
||||
site = aiohttp.web.UnixSite(runner, sock_listen)
|
||||
os.chmod(sock_listen, 0o664)
|
||||
|
||||
else:
|
||||
logging.error('Windows cannot use unix sockets. Use an IP address instead. Exiting...')
|
||||
sys.exit()
|
||||
|
||||
else:
|
||||
try:
|
||||
address(listen)
|
||||
|
||||
except ValueError:
|
||||
logging.warning('Invalid IP address. Listening on "127.0.0.1" instead.')
|
||||
listen = '127.0.0.1'
|
||||
|
||||
try:
|
||||
int(port)
|
||||
|
||||
except ValueError:
|
||||
logging.warning('Invalid port. Using 3001 instead.')
|
||||
port = 3001
|
||||
|
||||
logging.info(f'Starting webserver at address: {listen}:{port}')
|
||||
site = aiohttp.web.TCPSite(runner, listen, port)
|
||||
|
||||
await site.start()
|
||||
|
||||
|
||||
async def cleanup_tokens():
|
||||
while True:
|
||||
await asyncio.sleep(60*60)
|
||||
logging.debug('Cleaning up tokens')
|
||||
cleanup_users()
|
||||
|
||||
|
||||
async def cleanup_invalid_users():
|
||||
while True:
|
||||
logging.debug('Cleaning up invalid users')
|
||||
cleanup_users(True)
|
||||
await asyncio.sleep(60*15)
|
||||
|
||||
|
||||
def main():
|
||||
buildTemplates()
|
||||
observer = templateWatcher()
|
||||
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
asyncio.ensure_future(start_webserver())
|
||||
asyncio.ensure_future(cleanup_tokens())
|
||||
asyncio.ensure_future(cleanup_invalid_users())
|
||||
loop.run_forever()
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.info('Bye!')
|
||||
|
||||
observer.stop()
|
||||
|
120
paws/server.py
Normal file
|
@ -0,0 +1,120 @@
|
|||
import asyncio, signal, sys, json, os
|
||||
|
||||
import sanic
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.misc import GetIp
|
||||
from sanic import exceptions as exc
|
||||
from jinja2.exceptions import TemplateNotFound
|
||||
from sqlalchemy.orm.exc import DetachedInstanceError
|
||||
from uuid import uuid4
|
||||
|
||||
from . import views, errors, middleware
|
||||
from .database import db, mastodb
|
||||
from .config import config
|
||||
from .functions import CssTimestamp
|
||||
from .errors import Teapot
|
||||
from .request import HTTPRequest
|
||||
|
||||
|
||||
config.template.updateEnv({
|
||||
'config': config,
|
||||
'db': db,
|
||||
'mastodb': mastodb,
|
||||
'CssTimestamp': CssTimestamp
|
||||
})
|
||||
|
||||
web = sanic.Sanic('social', request_class=HTTPRequest)
|
||||
web.config['FORWARDED_SECRET'] = config.secret
|
||||
|
||||
|
||||
def safe_stop(*args):
|
||||
#logging.debug('Saving updated timestamps')
|
||||
#update_timestamps()
|
||||
|
||||
logging.info('Bye')
|
||||
sys.exit()
|
||||
|
||||
|
||||
def setupRoutes():
|
||||
error_handlers = [
|
||||
(exc.NotFound, errors.generic),
|
||||
(exc.MethodNotSupported, errors.generic),
|
||||
(exc.InvalidUsage, errors.generic),
|
||||
(exc.Unauthorized, errors.generic),
|
||||
(exc.Forbidden, errors.generic),
|
||||
(Teapot, errors.generic),
|
||||
(TemplateNotFound, errors.missing_template),
|
||||
(DetachedInstanceError, errors.orm_detached_instance),
|
||||
(Exception, errors.server_error)
|
||||
]
|
||||
|
||||
for handler in error_handlers:
|
||||
web.error_handler.add(*handler)
|
||||
|
||||
middlewares = [
|
||||
#(middleware.http_domain_user_check, 'request'),
|
||||
#(middleware.http_bans, 'request'),
|
||||
#(middleware.http_auth, 'request'),
|
||||
(middleware.http_headers, 'response'),
|
||||
(middleware.http_access_log, 'response')
|
||||
]
|
||||
|
||||
for m, a in middlewares:
|
||||
web.register_middleware(m, attach_to=a)
|
||||
|
||||
web_routes = [
|
||||
(views.MastoBase, '/'),
|
||||
(views.MastoBase, '/<path:[A-z0-9_\-/@:%.()&$#@]+>'),
|
||||
(views.MastoUser, '/@<user>'),
|
||||
(views.MastoStatus, '/:<statusid:int>')
|
||||
]
|
||||
|
||||
for view, route in web_routes:
|
||||
web.add_route(view, route, methods=['GET', 'POST', 'HEAD', 'PUT'])
|
||||
|
||||
|
||||
paws_routes = [
|
||||
(views.Home, '/paws'),
|
||||
(views.Settings, '/paws/settings'),
|
||||
(views.Instances, '/paws/instances'),
|
||||
(views.Login, '/paws/login'),
|
||||
(views.Logout, '/paws/logout'),
|
||||
(views.Style, '/paws/style-<timestamp:int>.css'),
|
||||
]
|
||||
|
||||
for view, route in paws_routes:
|
||||
web.add_route(view.as_view(), route)
|
||||
|
||||
|
||||
# Media
|
||||
web.static('/paws/static', config.frontend.join('static').str())
|
||||
web.static('/packs', config.mastodon.path.join('public/packs').str())
|
||||
|
||||
|
||||
def start():
|
||||
setupRoutes()
|
||||
|
||||
signal.signal(signal.SIGHUP, safe_stop)
|
||||
signal.signal(signal.SIGINT, safe_stop)
|
||||
signal.signal(signal.SIGQUIT, safe_stop)
|
||||
signal.signal(signal.SIGTERM, safe_stop)
|
||||
|
||||
listen = config.listen
|
||||
port = config.port
|
||||
workers = os.cpu_count()
|
||||
|
||||
logging.info(f'Starting PAWS at {listen}:{port}')
|
||||
try:
|
||||
web.run(
|
||||
host=listen,
|
||||
port=port,
|
||||
workers=workers if workers else 1,
|
||||
debug=False,
|
||||
access_log=False
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print('server exit error:', e.__class__.__name__, e)
|
||||
|
||||
safe_stop()
|
|
@ -1,160 +0,0 @@
|
|||
import aiohttp
|
||||
import aiohttp.web
|
||||
import binascii
|
||||
import base64
|
||||
import json
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.cache import LRUCache, TTLCache
|
||||
from aiohttp.http_exceptions import *
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Hash import SHA, SHA256, SHA512
|
||||
from Crypto.Signature import PKCS1_v1_5
|
||||
|
||||
from .config import MASTOCONFIG, VERSION
|
||||
from .database import keys
|
||||
|
||||
|
||||
class cache:
|
||||
messages = LRUCache()
|
||||
actors = TTLCache()
|
||||
keys = LRUCache()
|
||||
sigstrings = LRUCache()
|
||||
|
||||
|
||||
def pass_hash():
|
||||
password_hash = SHA512.new(NET['api_pass'].encode('UTF-8'))
|
||||
return password_hash.hexdigest()
|
||||
|
||||
|
||||
HASHES = {
|
||||
'sha1': SHA,
|
||||
'sha256': SHA256,
|
||||
'sha512': SHA512
|
||||
}
|
||||
|
||||
|
||||
def split_signature(sig):
|
||||
default = {"headers": "date"}
|
||||
|
||||
sig = sig.strip().split(',')
|
||||
|
||||
for chunk in sig:
|
||||
k, _, v = chunk.partition('=')
|
||||
v = v.strip('\"')
|
||||
default[k] = v
|
||||
|
||||
default['headers'] = default['headers'].split()
|
||||
return default
|
||||
|
||||
|
||||
def build_signing_string(headers, used_headers):
|
||||
return '\n'.join(map(lambda x: ': '.join([x.lower(), headers[x]]), used_headers))
|
||||
|
||||
|
||||
def sign_signing_string(sigstring, key):
|
||||
if sigstring not in cache.sigstrings:
|
||||
pkcs = PKCS1_v1_5.new(key)
|
||||
h = SHA256.new()
|
||||
h.update(sigstring.encode('ascii'))
|
||||
sigdata = pkcs.sign(h)
|
||||
|
||||
sigdata = base64.b64encode(sigdata)
|
||||
cache.sigstrings.store(sigstring, sigdata.decode('ascii'))
|
||||
|
||||
return cache.sigstrings.fetch(sigstring)
|
||||
|
||||
|
||||
def sign_headers(headers, keyname, key_id):
|
||||
keydata = keys(keyname)
|
||||
key = RSA.importKey(keydata['privkey'])
|
||||
headers = {x.lower(): y for x, y in headers.items()}
|
||||
used_headers = headers.keys()
|
||||
sig = {
|
||||
'keyId': key_id,
|
||||
'algorithm': 'rsa-sha256',
|
||||
'headers': ' '.join(used_headers)
|
||||
}
|
||||
sigstring = build_signing_string(headers, used_headers)
|
||||
sig['signature'] = sign_signing_string(sigstring, key)
|
||||
|
||||
chunks = ['{}="{}"'.format(k, v) for k, v in sig.items()]
|
||||
return ','.join(chunks)
|
||||
|
||||
|
||||
async def fetch_actor(uri, force=False):
|
||||
domain = MASTOCONFIG["domain"]
|
||||
|
||||
try:
|
||||
headers = {
|
||||
'Accept': 'application/activity+json',
|
||||
'User-Agent': f'PAWS/{VERSION}; https://{domain}'
|
||||
}
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(uri, headers=headers) as resp:
|
||||
if resp.status != 200:
|
||||
print(await resp.read())
|
||||
return
|
||||
|
||||
data = await resp.json(encoding='utf-8')
|
||||
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
logging.info('Caught %r while fetching actor %r.', e, uri)
|
||||
return None
|
||||
|
||||
|
||||
async def fetch_actor_key(actor):
|
||||
if actor not in cache.keys:
|
||||
actor_data = await fetch_actor(actor)
|
||||
|
||||
if not actor_data:
|
||||
logging.debug('Failed to fetch actor')
|
||||
return None
|
||||
|
||||
if 'publicKey' not in actor_data:
|
||||
logging.debug('publicKey not in actor')
|
||||
return None
|
||||
|
||||
if 'publicKeyPem' not in actor_data['publicKey']:
|
||||
logging.debug('Missing pubkey in actor')
|
||||
return None
|
||||
|
||||
cache.keys.store(actor, actor_data['publicKey']['publicKeyPem'])
|
||||
|
||||
return RSA.importKey(cache.keys.fetch(actor))
|
||||
|
||||
|
||||
async def validate(actor, request):
|
||||
pubkey = await fetch_actor_key(actor)
|
||||
if not pubkey:
|
||||
logging.debug(f'Failed to fetch pubkey for actor: {actor}')
|
||||
return False
|
||||
|
||||
logging.debug(f'actor key: {pubkey}')
|
||||
|
||||
headers = request.headers.copy()
|
||||
headers['(request-target)'] = ' '.join([request.method.lower(), request.path])
|
||||
|
||||
sig = split_signature(headers['signature'])
|
||||
logging.debug(f'sigdata: {sig}')
|
||||
|
||||
sigstring = build_signing_string(headers, sig['headers'])
|
||||
logging.debug(f'sigstring: {sigstring}')
|
||||
|
||||
sign_alg, _, hash_alg = sig['algorithm'].partition('-')
|
||||
logging.debug(f'sign alg: {sign_alg}, hash alg: {hash_alg}')
|
||||
|
||||
sigdata = base64.b64decode(sig['signature'])
|
||||
|
||||
pkcs = PKCS1_v1_5.new(pubkey)
|
||||
h = HASHES[hash_alg].new()
|
||||
h.update(sigstring.encode('ascii'))
|
||||
result = pkcs.verify(h, sigdata)
|
||||
|
||||
request['validated'] = result
|
||||
|
||||
logging.debug(f'validates? {result}')
|
||||
return result
|
|
@ -1,117 +0,0 @@
|
|||
{% set primary = '#C6C' %}
|
||||
{% set secondary = '#68C' %}
|
||||
{% set error = '#C64' %}
|
||||
{% set background = '#202020' %}
|
||||
{% set text = '#DDD' %}
|
||||
|
||||
/* variables */
|
||||
:root {
|
||||
--text: {{text}};
|
||||
--bg-color: {{background}};
|
||||
--bg-color-dark: {{desaturate(darken(primary, 0.85), 0.8)}};
|
||||
--bg-color-lighter: {{lighten(background, 0.075)}};
|
||||
--bg-dark: {{desaturate(darken(primary, 0.90), 0.5)}};
|
||||
--primary: {{primary}};
|
||||
--error: {{desaturate(darken('red', 0.2), 0.25)}};
|
||||
--valid: {{desaturate(darken('green', 0.2), 0.25)}};
|
||||
--shadow-color: {{rgba('black', 0.5)}};
|
||||
|
||||
--shadow: 0 4px 4px 0 var(--shadow-color), 0 6px 10px 0 var(--shadow-color);
|
||||
--border-radius: 10px;
|
||||
}
|
||||
|
||||
|
||||
/* general */
|
||||
input, a {
|
||||
transition-property: color, background-color, border, width, height;
|
||||
transition-timing-function: ease-in-out;
|
||||
transition-duration: 0.35s;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--bg-dark);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
a {
|
||||
color: {{saturate(lighten(primary, 0.4), 0.2)}};
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
select {
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
}
|
||||
|
||||
input, textarea, select {
|
||||
color: var(--text);
|
||||
border: 1px solid transparent;
|
||||
background-color: var(--bg-color);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
input:hover, textarea:hover, select:hover {
|
||||
color: {{desaturate(primary, 0.6)}};
|
||||
border-color: {{desaturate(primary, 0.6)}};
|
||||
}
|
||||
|
||||
input:focus, textarea:focus, select:focus {
|
||||
color: {{primary}};
|
||||
background-color: var(--bg-dark);
|
||||
border-color: {{primary}};
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: {{saturate(primary, 0.8)}};
|
||||
}
|
||||
|
||||
#paw_logo circle {
|
||||
fill: var(--text)
|
||||
}
|
||||
|
||||
#content {
|
||||
background-color: var(--bg-color);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.section {
|
||||
background-color: var(--bg-color-lighter);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
tr {
|
||||
border: 1px solid black;
|
||||
border-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
tr:nth-child(odd):not(.header) td {
|
||||
background-color: {{desaturate(darken(primary, 0.80), 0.9)}};
|
||||
}
|
||||
|
||||
tr:nth-child(even) td {
|
||||
background-color: {{desaturate(darken(primary, 0.75), 1)}};
|
||||
}
|
||||
|
||||
tr:not(.header):hover td {
|
||||
color: var(--bg-color-dark);
|
||||
background-color: {{desaturate(primary, 0.2)}};
|
||||
}
|
||||
|
||||
tr:not(.header):hover td a {
|
||||
color: var(--bg-color-dark);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--error);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
|
||||
/* Dropdown menus */
|
||||
.menu {
|
||||
background-color: var(--bg-color-dark);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
|
||||
{% include 'layout.css' %}
|
|
@ -1,162 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="300"
|
||||
height="400"
|
||||
viewBox="0 0 79.374999 105.83333"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
|
||||
sodipodi:docname="logo.svg"
|
||||
inkscape:export-filename="/home/zoey/Desktop/logo.svg.png"
|
||||
inkscape:export-xdpi="96"
|
||||
inkscape:export-ydpi="96">
|
||||
<title
|
||||
id="title817">Gently Protected by PAWS</title>
|
||||
<defs
|
||||
id="defs2" />
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="1.4142136"
|
||||
inkscape:cx="-9.008941"
|
||||
inkscape:cy="193.715"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:current-layer="svg8"
|
||||
showgrid="true"
|
||||
guidetolerance="10000"
|
||||
units="px"
|
||||
inkscape:window-width="1280"
|
||||
inkscape:window-height="972"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:snap-text-baseline="true">
|
||||
<inkscape:grid
|
||||
type="xygrid"
|
||||
id="grid815" />
|
||||
</sodipodi:namedview>
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title>Gently Protected by PAWS</dc:title>
|
||||
<cc:license
|
||||
rdf:resource="http://creativecommons.org/licenses/by-nc-sa/4.0/" />
|
||||
</cc:Work>
|
||||
<cc:License
|
||||
rdf:about="http://creativecommons.org/licenses/by-nc-sa/4.0/">
|
||||
<cc:permits
|
||||
rdf:resource="http://creativecommons.org/ns#Reproduction" />
|
||||
<cc:permits
|
||||
rdf:resource="http://creativecommons.org/ns#Distribution" />
|
||||
<cc:requires
|
||||
rdf:resource="http://creativecommons.org/ns#Notice" />
|
||||
<cc:requires
|
||||
rdf:resource="http://creativecommons.org/ns#Attribution" />
|
||||
<cc:prohibits
|
||||
rdf:resource="http://creativecommons.org/ns#CommercialUse" />
|
||||
<cc:permits
|
||||
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
|
||||
<cc:requires
|
||||
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
|
||||
</cc:License>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="Layer 1"
|
||||
id="layer1"
|
||||
transform="translate(0,-191.16667)"
|
||||
inkscape:groupmode="layer">
|
||||
<rect
|
||||
style="fill:#2b0b1a;fill-opacity:1;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;paint-order:markers fill stroke"
|
||||
id="rect823"
|
||||
width="79.375"
|
||||
height="105.83333"
|
||||
x="0"
|
||||
y="191.16667"
|
||||
ry="15.874998" />
|
||||
<path
|
||||
style="fill:#5f0029;fill-opacity:0.99719891;stroke:#000000;stroke-width:0;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 0,204.39584 c 3.1481224,75.36347 79.375466,35.7162 79.375,35.71875 l 0.02339,41.00745 C 79.407325,296.79004 63.5,297 63.5,297 H 15.875 C 0,297 0,281.125 0,281.125 v -76.72916"
|
||||
id="path825"
|
||||
inkscape:connector-curvature="0"
|
||||
sodipodi:nodetypes="ccscscc" />
|
||||
</g>
|
||||
<g
|
||||
inkscape:label="logo"
|
||||
id="paw_logo"
|
||||
transform="translate(0,-244.08334)"
|
||||
inkscape:groupmode="layer"
|
||||
style="display:inline">
|
||||
<circle
|
||||
id="pawpad"
|
||||
cx="39.026043"
|
||||
cy="280.46356"
|
||||
r="13.229166"
|
||||
style="fill:#ffebeb;fill-opacity:1;stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean1"
|
||||
cx="31.088533"
|
||||
cy="259.29691"
|
||||
r="5.2916665"
|
||||
style="fill:#ffebeb;fill-opacity:1;stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean2"
|
||||
cx="46.963547"
|
||||
cy="259.29691"
|
||||
r="5.2916665"
|
||||
style="fill:#ffebeb;fill-opacity:1;stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="tobean3"
|
||||
cx="59.134399"
|
||||
cy="269.88037"
|
||||
r="5.2916665"
|
||||
style="display:inline;fill:#ffebeb;fill-opacity:1;stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean4"
|
||||
cx="18.917707"
|
||||
cy="269.88037"
|
||||
r="5.2916665"
|
||||
style="display:inline;fill:#ffebeb;fill-opacity:1;stroke-width:0.26458332" />
|
||||
</g>
|
||||
<flowRoot
|
||||
xml:space="preserve"
|
||||
id="textContainer"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:40.47038651px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;display:inline;fill:#f5f5f5;fill-opacity:1;stroke:none"
|
||||
transform="matrix(0.2966959,0,0,0.28422717,-4.0751446,-2.6908806)"
|
||||
inkscape:label="text"><flowRegion
|
||||
id="text"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:40.47038651px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#f5f5f5;fill-opacity:1"><rect
|
||||
id="rect4533"
|
||||
width="235"
|
||||
height="150"
|
||||
x="30"
|
||||
y="225"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:40.47038651px;font-family:sans-serif;-inkscape-font-specification:'sans-serif, Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#f5f5f5;fill-opacity:1" /></flowRegion><flowPara
|
||||
id="gently"
|
||||
style="text-align:center">Gently</flowPara><flowPara
|
||||
id="secured"
|
||||
style="text-align:center">Secured</flowPara><flowPara
|
||||
id="byPAWS"
|
||||
style="text-align:center">by PAWS</flowPara></flowRoot> <g
|
||||
inkscape:groupmode="layer"
|
||||
id="layer4"
|
||||
inkscape:label="text" />
|
||||
</svg>
|
Before Width: | Height: | Size: 6.4 KiB |
|
@ -1,62 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
width="200"
|
||||
height="200"
|
||||
viewBox="0 0 52.916666 52.916666"
|
||||
version="1.1"
|
||||
id="paw_logo_container">
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="logo"
|
||||
inkscape:groupmode="layer"
|
||||
id="paw_logo"
|
||||
transform="translate(0,-244.08334)">
|
||||
<circle
|
||||
id="pawpad"
|
||||
cx="26.458332"
|
||||
cy="277.15625"
|
||||
r="13.229166"
|
||||
style="stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean1"
|
||||
cx="18.520826"
|
||||
cy="255.98961"
|
||||
r="5.2916665"
|
||||
style="stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean2"
|
||||
cx="34.395836"
|
||||
cy="255.98961"
|
||||
r="5.2916665"
|
||||
style="stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="tobean3"
|
||||
cx="46.566689"
|
||||
cy="266.57306"
|
||||
r="5.2916665"
|
||||
style="stroke-width:0.26458332" />
|
||||
<circle
|
||||
id="toebean4"
|
||||
cx="6.3499994"
|
||||
cy="266.57306"
|
||||
r="5.2916665"
|
||||
style="stroke-width:0.26458332" />
|
||||
</g>
|
||||
</svg>
|
Before Width: | Height: | Size: 1.4 KiB |
|
@ -1,224 +0,0 @@
|
|||
/* general */
|
||||
body {
|
||||
font-family: "Noto Sans", Sans-Serif;
|
||||
font-size: 12pt;
|
||||
margin: 0px;
|
||||
}
|
||||
|
||||
input, textarea, select, div.placeholder {
|
||||
height: 22px;
|
||||
padding: 2px 7px;
|
||||
-moz-border-radius: var(--border-radius);
|
||||
border-radius: var(--border-radius);
|
||||
margin: 5px;
|
||||
}
|
||||
|
||||
select {
|
||||
height: 28px !important;
|
||||
}
|
||||
|
||||
summary:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#paw_logo_container {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
#content {
|
||||
width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding-bottom: 1px;
|
||||
border-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
#header h1 {
|
||||
margin: 0px;
|
||||
padding-top: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#header div {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#footer {
|
||||
grid-template-columns: 100px auto 100px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#footer .col2 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#footer .col3 {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#footer p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin: 15px auto;
|
||||
padding: 10px;
|
||||
width: calc(100% - 45px);
|
||||
border-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
.section .title {
|
||||
margin-top: 0;
|
||||
margin-bottom: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input.placeholder {
|
||||
height: 21px;
|
||||
}
|
||||
|
||||
label.placeholder {
|
||||
height: 19px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
tr:nth-child(2) .col1 {
|
||||
border-top-left-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
tr:nth-child(2) .col2 {
|
||||
border-top-right-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
tr:last-child .col1 {
|
||||
border-bottom-left-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
tr:last-child .col2 {
|
||||
border-bottom-right-radius: var(--border-radius);
|
||||
}
|
||||
|
||||
.indent1 {
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.indent2 {
|
||||
padding-left: 40px;
|
||||
}
|
||||
|
||||
.indent3 {
|
||||
padding-left: 60px;
|
||||
}
|
||||
|
||||
|
||||
/* Grids */
|
||||
.grid-container {
|
||||
display: grid;
|
||||
grid-gap: 0;
|
||||
grid-template-columns: 50% auto;
|
||||
}
|
||||
|
||||
.grid-item {
|
||||
display: inline-grid;
|
||||
}
|
||||
|
||||
.msg, .error {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
|
||||
/* Login */
|
||||
#auth {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input[type=text] {
|
||||
width: 25%;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
input[type=text]:hover {
|
||||
width: 35%;
|
||||
}
|
||||
|
||||
input[type=text]:focus {
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
|
||||
/* lists */
|
||||
.list .col1 {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.list .button {
|
||||
text-align: center;
|
||||
width: 75px;
|
||||
}
|
||||
|
||||
.list .button input {
|
||||
width: calc(100% - 10px);
|
||||
}
|
||||
|
||||
/* Errors */
|
||||
#error .msg {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#error .title {
|
||||
font-size: 48px;
|
||||
}
|
||||
|
||||
|
||||
/* Dropdown menu */
|
||||
.menu {
|
||||
position: fixed;
|
||||
display: block;
|
||||
right: 0;
|
||||
padding: 5px;
|
||||
text-align: center;
|
||||
z-index: 10;
|
||||
top: 0;
|
||||
border-radius: 0 0 0 5px;
|
||||
}
|
||||
|
||||
.menu a {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.menu .title {
|
||||
font-weight: bold;
|
||||
font-size: 14pt;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.menu .item {
|
||||
padding: 5px 0;
|
||||
text-transform: uppercase;
|
||||
font-size: 14pt;
|
||||
}
|
||||
|
||||
.menu-right details[open] summary ~ * {
|
||||
animation: sweep-left .5s ease-in-out;
|
||||
}
|
||||
|
||||
|
||||
/* mobile/small screen */
|
||||
@media (max-width : 1000px) {
|
||||
#content {
|
||||
width: 100%;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.grid-container {
|
||||
grid-template-columns: auto;
|
||||
}
|
||||
}
|
Before Width: | Height: | Size: 25 KiB |
Before Width: | Height: | Size: 578 B |
Before Width: | Height: | Size: 2.6 KiB |
|
@ -1,71 +0,0 @@
|
|||
-set default_open = 'open'
|
||||
{% set logo_svg %}
|
||||
{% include 'components/logo.svg' %}
|
||||
{% endset %}
|
||||
|
||||
!!! Strict
|
||||
%html
|
||||
%head
|
||||
%title<
|
||||
PAWS@{{domain}}: {{page}}
|
||||
|
||||
%link{'rel': 'stylesheet', 'href': '/paws/style-{{css_ts()}}.css', 'media': 'screen'}
|
||||
%meta{'name': 'viewport', 'content': 'width=device-width, initial-scale=1, shrink-to-fit=no'}
|
||||
|
||||
%body
|
||||
%div{'class': 'menu menu-right'}
|
||||
%details
|
||||
%summary{'class': "title"}
|
||||
%a
|
||||
-if request.user:
|
||||
{{request.user.handle}}
|
||||
-else
|
||||
Guest
|
||||
|
||||
.item
|
||||
%a{'href': '/about', 'target': '_self'} Masto Home
|
||||
.item
|
||||
%a{'href': '/paws', 'target': '_self'} Paws Home
|
||||
-if request.user
|
||||
-if request.admin
|
||||
.item
|
||||
%a{'href': '/paws/list/instances', 'target': '_self'} Instances
|
||||
.item
|
||||
%a{'href': '/paws/list/requests', 'target': '_self'} Requests
|
||||
.item
|
||||
%a{'href': '/paws/list/signlist', 'target': '_self'} Signlist
|
||||
.item
|
||||
%a{'href': '/paws/logout', 'target': '_self'} Logout
|
||||
-else
|
||||
.item
|
||||
%a{'href': '/paws/login', 'target': '_self'} Login
|
||||
|
||||
#content
|
||||
#header
|
||||
%h1{'id': 'name'}= logo_svg
|
||||
|
||||
#body
|
||||
-block content
|
||||
|
||||
#footer{'class': 'section grid-container'}
|
||||
%div{'class': 'grid-item col1'}
|
||||
%p
|
||||
%a{'href': '/about'}<
|
||||
{{domain}}
|
||||
|
||||
%div{'class': 'grid-item col2'}
|
||||
%p<
|
||||
-if request.user
|
||||
{{request.user.handle}}@{{request.user.instance}} [
|
||||
%a{'href': '/paws/logout'}> logout
|
||||
]
|
||||
|
||||
-else
|
||||
Guest [
|
||||
%a{'href': '/paws/login'}> login
|
||||
]
|
||||
|
||||
%div{'class': 'grid-item col3'}
|
||||
%p
|
||||
%a{'href': 'https://git.barkshark.xyz/izalia/paws', 'target': '_new'}
|
||||
PAWS/{{VERSION}}
|
|
@ -1,9 +0,0 @@
|
|||
-extends 'base.html'
|
||||
-set page = 'Error ' + code
|
||||
|
||||
-block content
|
||||
#error{'class': 'section'}
|
||||
%h2{'class': 'title'}
|
||||
Error {{code}}
|
||||
|
||||
.msg= msg
|
|
@ -1,111 +0,0 @@
|
|||
-extends 'base.html'
|
||||
-set page = 'Home'
|
||||
|
||||
-block content
|
||||
#panel{'class': 'section'}
|
||||
-if listtype == 'signlist'
|
||||
%center
|
||||
%h2{'class': 'title'} Signlist
|
||||
|
||||
%table{'id': 'signlist', 'class': 'list'}
|
||||
%tr{'class': 'header'}
|
||||
%td
|
||||
%td
|
||||
|
||||
-if len(signlist) > 0
|
||||
-for instance in signlist
|
||||
%tr{'class': 'instance'}
|
||||
%td{'class': 'col1'}
|
||||
%a{'href': 'https://{{instance}}/about', 'target': '_new'}= instance
|
||||
%td{'class': 'col2 button'}
|
||||
%form{'action': '/paws/action/remove', 'method': 'post'}
|
||||
%input{'name': 'name', 'value': '{{instance}}', 'hidden': None}
|
||||
%input{'type': 'submit', 'value': 'Remove'}
|
||||
|
||||
-else
|
||||
%tr{'class': 'instance'}
|
||||
%td none
|
||||
%td
|
||||
|
||||
%tr{'class': 'instance'}
|
||||
%form{'action': '/paws/action/add', 'method': 'post'}
|
||||
%td{'class': 'col1'}
|
||||
%input{'type': 'text', 'name': 'name', 'placeholder': 'mastodon.social'}
|
||||
%td{'class': 'col2'}
|
||||
%input{'type': 'submit', 'value': 'Add'}
|
||||
|
||||
-if listtype == 'requests'
|
||||
%center
|
||||
%h2{'class': 'title'} Requests
|
||||
|
||||
%table{'id': 'request', 'class': 'list'}
|
||||
-if len(requests) > 0
|
||||
-for instance in requests
|
||||
%tr{'class': 'instance'}
|
||||
%td{'class': 'col1'}
|
||||
%a{'href': 'https://{{instance.domain}}/about', 'target': '_new'}= instance.domain
|
||||
%td{'class': 'button'}= instance.software
|
||||
%form{'action': '/paws/action/add?list=={listtype}', 'method': 'post'}
|
||||
%input{'name': 'name', 'value': '{{instance.domain}}', 'hidden': None}
|
||||
%td{'class': 'button'}
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Accept'}
|
||||
%td{'class': 'button'}
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Deny'}
|
||||
|
||||
%form{'action': '/paws/action/remove?list=={listtype}', 'method': 'post'}
|
||||
%input{'name': 'name', 'value': '{{instance.domain}}', 'hidden': None}
|
||||
%td{'class': 'col2 button'}
|
||||
%input{'type': 'submit', 'value': 'Remove'}
|
||||
|
||||
-else
|
||||
%tr{'class': 'instance'}
|
||||
%td none
|
||||
%td
|
||||
|
||||
-if listtype == 'instances'
|
||||
%center
|
||||
%h2{'class': 'title'} Instances
|
||||
%a{'href': '?'} All
|
||||
|
|
||||
%a{'href': '?type=accept'} Accepted
|
||||
|
|
||||
%a{'href': '?type=deny'} Denied
|
||||
%br
|
||||
%br
|
||||
|
||||
%table{'id': 'accept', 'class': 'list'}
|
||||
-if len(instances) > 0
|
||||
-for instance in instances
|
||||
%tr{'class': 'instance'}
|
||||
%td{'class': 'col1'}
|
||||
%a{'href': 'https://{{instance.domain}}/about', 'target': '_new'}= instance.domain
|
||||
%td{'class': 'button'}= instance.software
|
||||
%form{'action': '/paws/action/add?list=={listtype}', 'method': 'post'}
|
||||
%input{'name': 'name', 'value': '{{instance.domain}}', 'hidden': None}
|
||||
%td{'class': 'button'}
|
||||
-if instance.state == 'accept'
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Deny'}
|
||||
|
||||
-elif instance.state == 'deny'
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Accept'}
|
||||
|
||||
%form{'action': '/paws/action/remove?list=={listtype}', 'method': 'post'}
|
||||
%input{'name': 'name', 'value': '{{instance.domain}}', 'hidden': None}
|
||||
%td{'class': 'col2 button'}
|
||||
%input{'type': 'submit', 'value': 'Remove'}
|
||||
|
||||
-else
|
||||
%tr{'class': 'instance'}
|
||||
%td none
|
||||
%td
|
||||
|
||||
%tr{'class': 'instance'}
|
||||
%form{'action': '/paws/action/add', 'method': 'post'}
|
||||
%td{'class': 'col1'}
|
||||
%input{'type': 'text', 'name': 'name', 'placeholder': 'mastodon.social'}
|
||||
%td{'class': 'button'}
|
||||
%td{'class': 'button'}
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Accept'}
|
||||
%td{'class': 'col2 button'}
|
||||
%input{'type': 'submit', 'name': 'action', 'value': 'Deny'}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
-extends 'base.html'
|
||||
-set page = 'Login'
|
||||
|
||||
-block content
|
||||
#auth{'class': 'section'}
|
||||
%h2{'class': 'title'} Login
|
||||
|
||||
-if msg
|
||||
.error= msg
|
||||
|
||||
%form{'action': '/paws/login', 'method': 'post'}
|
||||
.msg This instance requires you to login via oauth to view public pages
|
||||
%br
|
||||
Please input the instance of the account you'd like to login with
|
||||
|
||||
%input{'type': 'hidden', 'name': 'redir', 'value': '{{redir}}'}
|
||||
%input{'type': 'hidden', 'name': 'numid', 'value': '{{numid}}'}
|
||||
%input{'type': 'text', 'name': 'domain', 'placeholder': 'mastodon.social'}
|
||||
%br
|
||||
%input{'type': 'submit', 'value': 'Login'}
|
|
@ -1 +0,0 @@
|
|||
Missing template file
|
|
@ -1,8 +0,0 @@
|
|||
-extends 'base.html'
|
||||
-set page = 'Home'
|
||||
|
||||
-block content
|
||||
#panel{'class': 'section'}
|
||||
%h2{'class': 'title'} PAWS
|
||||
%p
|
||||
PAWS is an extra auth layer for public profiles and posts. The main purpose is to prevent web scrapers from hoarding posts, but it also prevents banned users from viewing toots they shouldn't see
|
377
paws/views.py
|
@ -1,339 +1,110 @@
|
|||
import aiohttp
|
||||
import random
|
||||
import traceback
|
||||
|
||||
from operator import itemgetter
|
||||
|
||||
from IzzyLib import logging
|
||||
from IzzyLib.cache import TTLCache
|
||||
from IzzyLib.template import aiohttpTemplate
|
||||
from urllib.parse import quote_plus, unquote_plus, urlparse
|
||||
from IzzyLib.misc import Path
|
||||
from datetime import datetime
|
||||
from sanic import response
|
||||
from sanic.views import HTTPMethodView
|
||||
|
||||
from . import oauth
|
||||
from .database import pawsdb, trans, query, where, keys, ban_check, get_user, get_toot, admin_check, whitelist, instances
|
||||
from .functions import error, fed_domain, domain_check, css_ts
|
||||
from .config import MASTOCONFIG, PAWSCONFIG
|
||||
from .config import config
|
||||
from .database import db
|
||||
from .functions import Error, GetTheme, Client
|
||||
|
||||
|
||||
paws_host = PAWSCONFIG['domain']
|
||||
masto_host = MASTOCONFIG['domain']
|
||||
async def MastoBase(request, path=None):
|
||||
if path:
|
||||
filepath = config.mastodon.path.join('public').join(path)
|
||||
|
||||
if filepath.isfile():
|
||||
return await response.file(filepath.str())
|
||||
|
||||
else:
|
||||
path = '/'
|
||||
|
||||
host = request.headers.get('host', config.mastodon.web_domain)
|
||||
|
||||
masto = Client.request(f'http://{config.mastodon.host}{request.path}',
|
||||
headers = request.headers.asDict(),
|
||||
method = request.method,
|
||||
data = request.data.text
|
||||
)
|
||||
|
||||
masto.headers.pop('transfer-encoding', None)
|
||||
|
||||
resp = response.raw(masto.body(False),
|
||||
headers = masto.headers.asDict(),
|
||||
status = masto.status,
|
||||
content_type = masto.headers.get('content-type', 'text/html')
|
||||
)
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
class login(aiohttp.web.View):
|
||||
async def get(self):
|
||||
parms = self.request.rel_url.query
|
||||
redir = parms.get('redir')
|
||||
numid = random.randint(1*1000000, 10*1000000-1)
|
||||
|
||||
if self.request['user']:
|
||||
return aiohttp.web.HTTPFound('/paws')
|
||||
|
||||
data = {'redir': redir, 'numid': numid}
|
||||
return aiohttpTemplate('login.html', data, self.request)
|
||||
async def MastoUser(request, path=None):
|
||||
pass
|
||||
|
||||
|
||||
async def post(self):
|
||||
data = await self.request.post()
|
||||
domain = data.get('domain')
|
||||
redir = data.get('redir')
|
||||
numid = data.get('numid')
|
||||
|
||||
if 'DROP ' in domain:
|
||||
return aiohttp.web.HTTPFound('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
|
||||
|
||||
domain = domain_check(domain)
|
||||
|
||||
if not domain:
|
||||
return error(self.request, 400, 'Invalid domain')
|
||||
|
||||
if ban_check(domain):
|
||||
return error(self.request, 403, 'Instance banned')
|
||||
|
||||
appid, appsecret, redir_url = oauth.create_app(domain)
|
||||
|
||||
if appid == 'error':
|
||||
return error(self.request, 500, appsecret)
|
||||
async def MastoStatus(request, path=None):
|
||||
pass
|
||||
|
||||
|
||||
with trans(pawsdb.users) as tr:
|
||||
tr.insert({
|
||||
'handle': data['numid'],
|
||||
'domain': data['domain'].lower(),
|
||||
'appid': appid,
|
||||
'appsecret': appsecret,
|
||||
'token': None,
|
||||
'timestamp': datetime.timestamp(datetime.now())
|
||||
})
|
||||
|
||||
response = aiohttp.web.HTTPFound(redir_url)
|
||||
response.set_cookie('paws_numid', numid, max_age=60*60, path='/paws')
|
||||
|
||||
if redir not in ['', None]:
|
||||
response.set_cookie('paws_redir', redir, max_age=60*60, path='/paws')
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class lists(aiohttp.web.View):
|
||||
async def get(self):
|
||||
request = self.request
|
||||
listtype = request.match_info['list']
|
||||
state = request.query.get('type', None)
|
||||
|
||||
if request['admin']:
|
||||
if state not in ['accept', 'deny']:
|
||||
instances = pawsdb.instances.search(query.state != 'request')
|
||||
|
||||
else:
|
||||
instances = pawsdb.instances.search(query.state == state)
|
||||
|
||||
requests = pawsdb.instances.search(query.state == 'request')
|
||||
signlist = [line['domain'] for line in pawsdb.whitelist.all()]
|
||||
signlist.sort()
|
||||
data = {
|
||||
'listtype': listtype,
|
||||
'signlist': signlist,
|
||||
'requests': sorted(requests, key=lambda k: k['domain']),
|
||||
'instances': sorted(instances, key=lambda k: k['domain'])
|
||||
}
|
||||
|
||||
else:
|
||||
data = {}
|
||||
|
||||
if listtype not in data.keys():
|
||||
return error(request, 404, 'Invalid list type')
|
||||
|
||||
return aiohttpTemplate('lists.html', data, request)
|
||||
|
||||
async def post(self):
|
||||
class Home(HTTPMethodView):
|
||||
async def get(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def get_home(request):
|
||||
return aiohttpTemplate('home.html', {}, request)
|
||||
async def post(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def get_paws(request):
|
||||
data = {}
|
||||
return aiohttpTemplate('panel.html', data, request)
|
||||
class Settings(HTTPMethodView):
|
||||
async def get(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def post_paws(request):
|
||||
data = await request.post()
|
||||
user_data = request['user']
|
||||
domain = data.get('name')
|
||||
action = request.match_info['action'].lower()
|
||||
action = 'add' if action == 'update' else action
|
||||
admin = admin_check(user_data['handle']) if user_data else None
|
||||
page = request.query.get('list', 'instances')
|
||||
|
||||
if not admin:
|
||||
return error(request, 403, 'Not an admin')
|
||||
|
||||
if None in [action, domain]:
|
||||
return error(request, 400, 'Missing action or doamin')
|
||||
|
||||
domain = urlparse(domain.replace(' ', ''))
|
||||
parsed_domain = domain.netloc if domain.netloc != '' else domain.path
|
||||
|
||||
if action not in ['add', 'remove']:
|
||||
error(request, 400, 'Invalid action')
|
||||
|
||||
result = instances(action, parsed_domain, data.get('action', 'request'))
|
||||
print(result)
|
||||
|
||||
return aiohttp.web.HTTPFound(f'/paws/list/{page}')
|
||||
async def post(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def get_auth(request):
|
||||
parms = request.rel_url.query
|
||||
cookies = request.cookies
|
||||
redir = cookies.get('paws_redir')
|
||||
numid = cookies.get('paws_numid')
|
||||
code = parms.get('code')
|
||||
|
||||
if None in [numid, code]:
|
||||
return error(request, 500, 'Missing temporary userid or auth code')
|
||||
|
||||
if redir in ['', 'None', None]:
|
||||
redir = '/paws'
|
||||
|
||||
user = pawsdb.users.get(query.handle == str(numid))
|
||||
token, userinfo = oauth.login(user, code)
|
||||
|
||||
if token == 'error':
|
||||
return error(request, 500, userinfo)
|
||||
|
||||
instance = fed_domain(userinfo['username'], user['domain'])
|
||||
|
||||
with trans(pawsdb.users) as tr:
|
||||
tr.update(
|
||||
{
|
||||
'handle': userinfo['username'],
|
||||
'instance': instance,
|
||||
'appid': None,
|
||||
'appsecret': None,
|
||||
'token': token
|
||||
},
|
||||
where('handle') == numid
|
||||
)
|
||||
|
||||
response = aiohttp.web.HTTPFound(redir)
|
||||
response.set_cookie('paws_token', token, max_age=60*60*24*14)
|
||||
response.del_cookie('paws_redir', path='/paws')
|
||||
response.del_cookie('paws_numid', path='/paws')
|
||||
return response
|
||||
class Instances(HTTPMethodView):
|
||||
async def get(self, request, msg=None, error=None):
|
||||
pass
|
||||
|
||||
|
||||
async def get_logout(request):
|
||||
if not request['user']:
|
||||
return aiohttp.web.HTTPFound('/paws/login')
|
||||
|
||||
token_id = request['user'].doc_id
|
||||
|
||||
with trans(pawsdb.users) as tr:
|
||||
tr.remove(doc_ids=[token_id])
|
||||
|
||||
response = aiohttp.web.HTTPFound('/paws/login')
|
||||
response.del_cookie('token')
|
||||
|
||||
return response
|
||||
async def post(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def get_style(request):
|
||||
maxage = 60*60*24*7
|
||||
|
||||
response = aiohttpTemplate('color.css', {}, request, content_type='text/css')
|
||||
response.headers['Cache-Control'] = 'public,max-age={maxage},immutable'
|
||||
|
||||
return response
|
||||
|
||||
|
||||
async def get_webfinger(request):
|
||||
res = request.rel_url.query.get('resource')
|
||||
|
||||
if not res or res != f'acct:paws@{paws_host}':
|
||||
data = {}
|
||||
|
||||
else:
|
||||
class Login(HTTPMethodView):
|
||||
async def get(self, request, msg=None, error=None):
|
||||
data = {
|
||||
"aliases": [
|
||||
f"https://{paws_host}/paws/actor"
|
||||
],
|
||||
"links": [
|
||||
{
|
||||
"href": f"https://{paws_host}/paws/actor",
|
||||
"rel": "self",
|
||||
"type": "application/activity+json"
|
||||
},
|
||||
{
|
||||
"href": f"https://{paws_host}/paws/actor",
|
||||
"rel": "self",
|
||||
"type": "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""
|
||||
}
|
||||
],
|
||||
"subject": f"acct:paws@{paws_host}"
|
||||
'msg': msg,
|
||||
'error': error,
|
||||
'redir': {
|
||||
'path': request.data.query.get('redir'),
|
||||
'data': request.data.query.get('query')
|
||||
}
|
||||
}
|
||||
|
||||
return aiohttp.web.json_response(data)
|
||||
return config.template.response('pages/login.haml', request, data)
|
||||
|
||||
|
||||
async def get_actor(request):
|
||||
rsakey = keys('default')
|
||||
|
||||
if not rsakey:
|
||||
return error(request, 500, 'Missing actor keys')
|
||||
|
||||
PUBKEY = rsakey['pubkey']
|
||||
|
||||
data = {
|
||||
'@context': [
|
||||
'https://www.w3.org/ns/activitystreams'
|
||||
],
|
||||
#'endpoints': {
|
||||
#'sharedInbox': f'https://{masto_host}/inbox'
|
||||
#},
|
||||
#'following': f'https://{host}/paws/following',
|
||||
#'followers': f'https://{host}/paws/followers',
|
||||
'inbox': f'https://{paws_host}/paws/inbox',
|
||||
#'outbox': f'https://{host}/paws/outbox',
|
||||
'name': f'PAWS @ {masto_host}',
|
||||
'type': 'Application',
|
||||
'id': f'https://{paws_host}/paws/actor',
|
||||
'publicKey': {
|
||||
'id': f'https://{paws_host}/paws/actor#main-key',
|
||||
'owner': f'https://{paws_host}/paws/actor',
|
||||
'publicKeyPem': PUBKEY
|
||||
},
|
||||
'summary': 'PAWS Actor',
|
||||
'preferredUsername': 'paws',
|
||||
'url': f'https://{paws_host}/paws/actor'
|
||||
}
|
||||
|
||||
return aiohttp.web.json_response(data)
|
||||
async def post(self, request):
|
||||
pass
|
||||
|
||||
|
||||
async def post_inbox(request):
|
||||
return aiohttp.web.json_response('UvU', status=202)
|
||||
class Logout(HTTPMethodView):
|
||||
async def get(self, request):
|
||||
pass
|
||||
|
||||
|
||||
# failed attempt at creating a status
|
||||
async def get_outbox(request):
|
||||
if not request.rel_url.query.get('page'):
|
||||
class Style(HTTPMethodView):
|
||||
async def get(self, request, timestamp=None):
|
||||
user_config = request.cookie.user.config if request.cookie.user else {}
|
||||
theme = user_config.get('theme', 'pink')
|
||||
path = config.frontend.join('style')
|
||||
|
||||
data = {
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"id": f"https://{paws_host}/paws/outbox",
|
||||
"type": "OrderedCollection",
|
||||
"totalItems": 1,
|
||||
"first": f"https://{paws_host}/paws/outbox?page=true",
|
||||
"last": f"https://{paws_host}/paws/outbox?page=true"
|
||||
}
|
||||
|
||||
else:
|
||||
data = {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
{
|
||||
"ostatus": "http://ostatus.org#",
|
||||
"atomUri": "ostatus:atomUri",
|
||||
"inReplyToAtomUri": "ostatus:inReplyToAtomUri",
|
||||
"conversation": "ostatus:conversation",
|
||||
"sensitive": "as:sensitive",
|
||||
"toot": "http://joinmastodon.org/ns#",
|
||||
"votersCount": "toot:votersCount",
|
||||
"blurhash": "toot:blurhash",
|
||||
"focalPoint": {
|
||||
"@container": "@list",
|
||||
"@id": "toot:focalPoint"
|
||||
},
|
||||
"Emoji": "toot:Emoji"
|
||||
}
|
||||
],
|
||||
"id": f"https://{paws_host}/paws/outbox?page=true",
|
||||
"type": "OrderedCollectionPage",
|
||||
"partOf": f"https://{paws_host}/paws/outbox",
|
||||
"orderedItems": [imgay]
|
||||
'cssfiles': [css for css in path.listdir() if css.str().endswith('css')]
|
||||
}
|
||||
data.update(GetTheme(theme))
|
||||
|
||||
return aiohttp.web.json_response(data)
|
||||
|
||||
async def get_gay(request):
|
||||
data = imgay
|
||||
|
||||
return aiohttp.web.json_response(data)
|
||||
|
||||
|
||||
imgay = {
|
||||
"id": f"https://{paws_host}/paws/imgay",
|
||||
"type": "Note",
|
||||
"published": '2020-01-20T09:45:00Z',
|
||||
"attributedTo": f"https://{paws_host}/paws/actor",
|
||||
"content": '<p>im gay</p>',
|
||||
"to": [
|
||||
"https://www.w3.org/ns/activitystreams#Public"
|
||||
],
|
||||
"cc": [
|
||||
f"https://{paws_host}/paws/actor/followers"
|
||||
]
|
||||
}
|
||||
return config.template.response('style.css', request, data, ctype='text/css')
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
PAWS_HOST=127.0.0.1
|
||||
PAWS_PORT=3001
|
||||
|
||||
PAWS_DOMAIN=bappypaws.example.com
|
||||
|
||||
MASTOPATH=/home/mastodon/glitch-soc
|