Initial commit

This commit is contained in:
Tracker-Friendly 2024-09-28 19:41:34 +01:00
commit 42d478ec48
84 changed files with 7477 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.idea

660
LICENSE.md Normal file
View File

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

69
README.md Normal file
View File

@ -0,0 +1,69 @@
# Fulgens Web Server
A simple and fast plugin-based web server written in Golang.
It utilises Chi and the Go standard library to provide a fast and efficient web server, with the ability to add plugins to extend its functionality.
## Features
- Fast and efficient
- Plugin-based
- Easy to use
- Comes with OAuth2 and Blob storage (known as the "nucleus" services)
- SQLite and PostgreSQL support
- Easy to extend
## Installation
To install, git clone the repository:
```sh
git clone https://git.ailur.dev/Ailur/fulgens.git --depth 1
```
Then, build the server:
```sh
./build.sh
```
## Usage
To run the server, simply run the binary:
```sh
./fulgens
```
## Configuration
The server can be configured using a `config.json` file. An example configuration file is provided in the repository.
### Global
- `port` - The port the server listens on
- `ip` - The IP address the server listens on
- `serviceDirectory` - The directory where services are stored
- `resourceDirectory` - The directory where service resources are stored
### Logging
- `enabled` - Whether file logging is enabled
- `file` - The file to log to
### Database
- `type` - The type of database to use (sqlite or postgres)
- `connectionString` - The connection string for the database (postgres only)
- `databasePath` - The **directory** to store the databases (sqlite only)
It is necessary to have a separate directory for each service, as SQLite does not support multiple schemas in a single file.
### Services
#### For all services
- `subdomain` - The subdomain the service is hosted on (optional, will run on the root domain if not specified)
#### Storage
**Note** the storage service is unfinished and should not be used in production.
- `path` - The path to store blobs
- `defaultQuota` - The maximum size of the storage in bytes
#### Auth
- `privacyPolicy` - The URL to the privacy policy
- `url` - The URL it is being hosted on
- `testAppEnabled` - Whether to enable the OAuth2 test app
- `testAppIsInteralApp` - Whether the test app should have seamless logon like an internal service (required if `testAppEnabled` is true)
- `identifier` - The name of the OAuth2 service
- `adminKey` - The key used to access the admin panel and list users
## Contributing
Contributions are welcome! Please open a pull request with your changes.
## Plugin development
Plugins require the use of the `library` package, found [here](https://pkg.go.dev/git.ailur.dev/Ailur/fulgens/library).
This provides them with the necessary resources to interact with the rest of the server
## Enterprise support
For enterprise support, please visit [Ailur Enterprise](https://ailur.dev/enterprise).

13
build.sh Executable file
View File

@ -0,0 +1,13 @@
#!/bin/sh
path=$(realpath "$(dirname "$0")") || exit 1
search_dir="$path/services-src"
find "$search_dir" -type f -name "build.sh" | while read -r build_script; do
echo "Running $build_script..."
build_dir=$(dirname "$build_script")
(cd "$build_dir" && ./build.sh) || {
echo "Error: $build_script failed."
exit 1
}
done
go build --ldflags "-s -w" -o "$path/fulgens" || exit 1
echo "Fulgens has been built successfully."

29
config.json Normal file
View File

@ -0,0 +1,29 @@
{
"global": {
"ip": "0.0.0.0",
"port": "8000",
"serviceDirectory": "./services",
"resourceDirectory": "./resources"
},
"logging": {
"enabled": true,
"file": "fulgens.log"
},
"database": {
"databaseType": "sqlite",
"databasePath": "./databases"
},
"services": {
"storage": {
"path": "./blob"
},
"auth": {
"privacyPolicy": "https://git.ailur.dev/Paperwork/nucleus/src/commit/5d191eea87cffae8bdca42017ac26dc19e6cb3de/Privacy.md",
"url": "http://localhost:8000",
"identifier": "Authenticator",
"adminKey": "supersecretkey",
"testAppIsInternalApp": true,
"testAppEnabled": true
}
}
}

36
go.mod Normal file
View File

@ -0,0 +1,36 @@
module git.ailur.dev/ailur/fulgens
go 1.23.0
require (
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5
github.com/cespare/xxhash/v2 v2.3.0
github.com/go-chi/chi v1.5.5
github.com/go-playground/validator/v10 v10.22.1
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/google/uuid v1.6.0
github.com/lib/pq v1.10.9
golang.org/x/crypto v0.27.0
modernc.org/sqlite v1.33.1
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
)

85
go.sum Normal file
View File

@ -0,0 +1,85 @@
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 h1:QGICG5QsXtGVDV0YjR4bXiEV2kWQ96riPR9qFWuFpr4=
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5/go.mod h1:dDulL+Bfr47BPmvSPRkRD3uOVNsfM6yOTwhdAkctZU4=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA=
github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM=
modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=

40
library/main.go Normal file
View File

@ -0,0 +1,40 @@
package library
import (
"github.com/go-chi/chi"
"github.com/google/uuid"
"io/fs"
"time"
)
type Permissions struct {
Authenticate bool `validate:"required"`
Database bool `validate:"required"`
BlobStorage bool `validate:"required"`
InterServiceCommunication bool `validate:"required"`
Resources bool `validate:"required"`
}
type Service struct {
Name string `validate:"required"`
Permissions Permissions `validate:"required"`
ServiceID uuid.UUID `validate:"required"`
}
type InterServiceMessage struct {
ServiceID uuid.UUID `validate:"required"`
ForServiceID uuid.UUID `validate:"required"`
MessageType uint64 `validate:"required"`
SentAt time.Time `validate:"required"`
Message any `validate:"required"`
}
type ServiceInitializationInformation struct {
ServiceID uuid.UUID `validate:"required"`
Domain string `validate:"required"`
Outbox chan<- InterServiceMessage `validate:"required"`
Inbox <-chan InterServiceMessage `validate:"required"`
Router *chi.Mux `validate:"required"`
Configuration map[string]interface{}
ResourceDir fs.FS
}

694
main.go Normal file
View File

@ -0,0 +1,694 @@
package main
import (
"errors"
"fmt"
"git.ailur.dev/ailur/fulgens/library"
"github.com/go-chi/chi/middleware"
"io"
"log"
"os"
"plugin"
"sort"
"time"
"database/sql"
"encoding/json"
"log/slog"
"net/http"
"path/filepath"
"github.com/go-chi/chi"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
_ "github.com/lib/pq"
_ "modernc.org/sqlite"
)
type Config struct {
Global struct {
IP string `json:"ip" validate:"required,ip_addr"`
Port string `json:"port" validate:"required"`
ServiceDirectory string `json:"serviceDirectory" validate:"required"`
ResourceDirectory string `json:"resourceDirectory" validate:"required"`
} `json:"global" validate:"required"`
Logging struct {
Enabled bool `json:"enabled"`
File string `json:"file" validate:"required_if=Enabled true"`
} `json:"logging"`
Database struct {
DatabaseType string `json:"databaseType" validate:"required,oneof=sqlite postgres"`
ConnectionString string `json:"connectionString" validate:"required_if=DatabaseType postgres"`
DatabasePath string `json:"databasePath" validate:"required_if=DatabaseType sqlite,isDirectory"`
} `json:"database" validate:"required"`
Services map[string]interface{} `json:"services"`
}
type ActiveService struct {
ServiceID uuid.UUID
Inbox chan library.InterServiceMessage
ActivationConfirmed bool
}
var (
logger = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
slog.Info(r.Method + " " + r.URL.Path)
})
}
validate *validator.Validate
activeServices = make(map[uuid.UUID]ActiveService)
services = make(map[uuid.UUID]library.Service)
)
func processInterServiceMessage(channel chan library.InterServiceMessage, config Config) {
for {
message := <-channel
if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000000") {
// Broadcast message
for _, service := range activeServices {
// We don't want to overwhelm a non-activated service
if service.ActivationConfirmed {
service.Inbox <- message
}
}
} else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000001") {
// Service initialization service
switch message.MessageType {
case 0:
// Service initialization message, register the service
inbox := activeServices[message.ServiceID].Inbox
activeServices[message.ServiceID] = ActiveService{
ServiceID: message.ServiceID,
Inbox: inbox,
ActivationConfirmed: true,
}
// Report a successful activation
inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 0,
SentAt: time.Now(),
Message: true,
}
case 1:
// Service database initialization message
// Check if the service has the necessary permissions
if services[message.ServiceID].Permissions.Database {
// Check if we are using sqlite or postgres
if config.Database.DatabaseType == "sqlite" {
// Open the database and return the connection
pluginConn, err := sql.Open("sqlite", filepath.Join(config.Database.DatabasePath, message.ServiceID.String()+".db"))
if err != nil {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: err,
}
} else {
// Report a successful activation
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 2,
SentAt: time.Now(),
Message: pluginConn,
}
}
} else if config.Database.DatabaseType == "postgres" {
// Connect to the database
conn, err := sql.Open("postgres", config.Database.ConnectionString)
if err != nil {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: err,
}
} else {
// Try to create the schema
_, err = conn.Exec("CREATE SCHEMA IF NOT EXISTS " + message.ServiceID.String())
if err != nil {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: err,
}
} else {
// Create a new connection to the database
pluginConn, err := sql.Open("postgres", config.Database.ConnectionString+" dbname="+message.ServiceID.String())
if err != nil {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: err,
}
} else {
// Try to switch schemas
_, err = pluginConn.Exec("SET search_path TO " + message.ServiceID.String())
if err != nil {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: err,
}
} else {
// Report a successful activation
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 2,
SentAt: time.Now(),
Message: pluginConn,
}
}
}
}
}
}
} else {
// Report an error
activeServices[message.ServiceID].Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("database access not permitted"),
}
}
}
} else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000002") {
// Logger service
service, ok := services[message.ServiceID]
if ok {
if message.MessageType == 0 {
// Log message
slog.Info(service.Name + " says: " + message.Message.(string))
} else if message.MessageType == 1 {
// Warn message
slog.Warn(service.Name + " warns: " + message.Message.(string))
} else if message.MessageType == 2 {
// Error message
slog.Error(service.Name + " complains: " + message.Message.(string))
} else {
// Fatal message
slog.Error(service.Name + "'s dying wish: " + message.Message.(string))
os.Exit(1)
}
}
} else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000003") {
// We need to check if the service is allowed to access the Blob Storage service
serviceMetadata, ok := services[message.ServiceID]
if ok && serviceMetadata.Permissions.BlobStorage {
// Send message to Blob Storage service
service, ok := activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000003")]
if ok && service.ActivationConfirmed {
service.Inbox <- message
} else if !ok {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("blob storage service not found"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("blob storage is not yet available"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("blob storage is not permitted"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
fmt.Println(message.ServiceID, message.ForServiceID)
os.Exit(1)
}
}
} else if message.ForServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000004") {
// We need to check if the service is allowed to access the Authentication service
serviceMetadata, ok := services[message.ServiceID]
if ok && serviceMetadata.Permissions.Authenticate {
// Send message to Authentication service
service, ok := activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000004")]
if ok && service.ActivationConfirmed {
service.Inbox <- message
} else if !ok {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("authentication service not found"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("authentication service not yet available"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("authentication not permitted"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
}
} else {
serviceMetadata, ok := services[message.ServiceID]
if ok && serviceMetadata.Permissions.InterServiceCommunication {
// Send message to specific service
service, ok := activeServices[message.ForServiceID]
if ok && service.ActivationConfirmed {
service.Inbox <- message
} else if !ok {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("requested service not found"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("requested service not yet available"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
}
} else {
// Send error message
service, ok := activeServices[message.ServiceID]
if ok {
service.Inbox <- library.InterServiceMessage{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
ForServiceID: message.ServiceID,
MessageType: 1,
SentAt: time.Now(),
Message: errors.New("inter-service communication not permitted"),
}
} else {
// This should never happen
slog.Error("Bit flip error: Impossible service ID. Move away from radiation or use ECC memory.")
os.Exit(1)
}
}
}
}
}
func parseConfig(path string) Config {
// Register the custom validators
validate = validator.New()
// Register the custom isDirectory validator
err := validate.RegisterValidation("isDirectory", func(fl validator.FieldLevel) bool {
// Check if it exists
fileInfo, err := os.Stat(fl.Field().String())
if err != nil {
return false
}
// Check if it is a directory
return fileInfo.IsDir()
})
if err != nil {
slog.Error("Error registering custom validator: ", err)
os.Exit(1)
}
// Parse the configuration file
configFile, err := os.ReadFile(path)
if err != nil {
slog.Error("Error reading configuration file: ", err)
os.Exit(1)
}
// Parse the configuration file
var config Config
err = json.Unmarshal(configFile, &config)
if err != nil {
slog.Error("Error parsing configuration file: ", err)
os.Exit(1)
}
// Validate the configuration
err = validate.Struct(config)
if err != nil {
slog.Error(fmt.Sprintf("Invalid configuration: \n%s", err))
os.Exit(1)
}
// Check if we are logging to a file
if config.Logging != (Config{}.Logging) && config.Logging.Enabled {
// Check if the log file is set
logFilePath := config.Logging.File
// Set the log file
logFile, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
slog.Error("Error opening log file: ", err)
os.Exit(1)
}
log.SetOutput(io.MultiWriter(os.Stdout, logFile))
}
return config
}
func main() {
// Parse the configuration file
var config Config
if len(os.Args) < 2 {
info, err := os.Stat("config.json")
if err != nil {
if errors.Is(err, os.ErrNotExist) {
slog.Error("No configuration file provided")
os.Exit(1)
} else {
slog.Error("Error reading configuration file: ", err)
os.Exit(1)
}
}
if info.IsDir() {
slog.Error("No configuration file provided")
os.Exit(1)
}
config = parseConfig("config.json")
} else {
config = parseConfig(os.Args[1])
}
// Create the router
router := chi.NewRouter()
router.Use(logger)
var globalOutbox = make(chan library.InterServiceMessage)
// Initialize the service discovery, health-check, and logging services
// Since these are core services, always allocate them the service IDs 0, 1, and 2
// These are not dynamically loaded, as they are integral to the system functioning
go processInterServiceMessage(globalOutbox, config)
// Initialize the storage service
// The storage service does not need a subdomain
// Since it is a core service, always allocate it the service ID 3
// Load it from the services directory
storagePlugin, err := plugin.Open(config.Global.ServiceDirectory + "/storage.fgs")
if err != nil {
slog.Error("Could not load blob storage service: ", err)
os.Exit(1)
}
// Load up the service information
storageServiceInformation, err := storagePlugin.Lookup("ServiceInformation")
if err != nil {
slog.Error("Blob storage service lacks necessary information: ", err)
os.Exit(1)
}
services[uuid.MustParse("00000000-0000-0000-0000-000000000003")] = *storageServiceInformation.(*library.Service)
// Load up the main function
storageMain, err := storagePlugin.Lookup("Main")
if err != nil {
slog.Error("Blob storage service lacks necessary main function: ", err)
os.Exit(1)
}
// Initialize the storage service
var storageInbox = make(chan library.InterServiceMessage)
activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000003")] = ActiveService{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"),
Inbox: storageInbox,
ActivationConfirmed: false,
}
storageMain.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"),
Domain: "",
Configuration: config.Services["storage"].(map[string]interface{}),
Outbox: globalOutbox,
Inbox: storageInbox,
})
// Initialize the authentication service
// The authentication service does not need a subdomain
// Since it is a core service, always allocate it the service ID 4
// Load it from the services directory
authPlugin, err := plugin.Open(config.Global.ServiceDirectory + "/auth.fgs")
if err != nil {
slog.Error("Could not load authentication service: ", err)
os.Exit(1)
}
// Load up the service information
authServiceInformation, err := authPlugin.Lookup("ServiceInformation")
if err != nil {
slog.Error("Authentication service lacks necessary information: ", err)
os.Exit(1)
}
services[uuid.MustParse("00000000-0000-0000-0000-000000000004")] = *authServiceInformation.(*library.Service)
// Load up the main function
authMain, err := authPlugin.Lookup("Main")
if err != nil {
slog.Error("Authentication service lacks necessary main function: ", err)
os.Exit(1)
}
// Initialize the authentication service
var authInbox = make(chan library.InterServiceMessage)
activeServices[uuid.MustParse("00000000-0000-0000-0000-000000000004")] = ActiveService{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"),
Inbox: authInbox,
ActivationConfirmed: false,
}
// Check if they want a subdomain
var authRouter *chi.Mux
if config.Services["auth"].(map[string]interface{})["subdomain"] != nil {
subdomainRouter := chi.NewRouter()
router.Use(middleware.RouteHeaders().
Route("Host", config.Services["auth"].(map[string]interface{})["subdomain"].(string), middleware.New(subdomainRouter)).
Handler)
authRouter = subdomainRouter
} else {
authRouter = router
}
authMain.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"),
Domain: "",
Configuration: config.Services["auth"].(map[string]interface{}),
Outbox: globalOutbox,
Inbox: authInbox,
ResourceDir: os.DirFS(filepath.Join(config.Global.ResourceDirectory, "00000000-0000-0000-0000-000000000004")),
Router: authRouter,
})
// Initialize all custom services
plugins := make(map[time.Time]string)
err = filepath.Walk(config.Global.ServiceDirectory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || filepath.Ext(path) != ".fgs" || filepath.Base(path) == "auth.fgs" || filepath.Base(path) == "storage.fgs" {
return nil
}
// Add the plugin to the list of plugins
plugins[info.ModTime()] = path
return nil
})
if err != nil {
slog.Error("Error walking the services directory: ", err)
os.Exit(1)
}
// Sort the plugins by modification time, newest last
var keys []time.Time
for k := range plugins {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].Before(keys[j])
})
for _, k := range keys {
// Get the plugin path
pluginPath := plugins[k]
// Load the plugin
servicePlugin, err := plugin.Open(pluginPath)
if err != nil {
slog.Error("Could not load service: ", err)
os.Exit(1)
}
// Load the service information
serviceInformation, err := servicePlugin.Lookup("ServiceInformation")
if err != nil {
slog.Error("Service lacks necessary information: ", err)
os.Exit(1)
}
// Load the main function
main, err := servicePlugin.Lookup("Main")
if err != nil {
slog.Error("Service lacks necessary main function: ", err)
os.Exit(1)
}
// Initialize the service
var inbox = make(chan library.InterServiceMessage)
activeServices[serviceInformation.(*library.Service).ServiceID] = ActiveService{
ServiceID: serviceInformation.(*library.Service).ServiceID,
Inbox: inbox,
ActivationConfirmed: false,
}
// Check if they want a subdomain
var finalRouter *chi.Mux
if config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{})["subdomain"] != nil {
subdomainRouter := chi.NewRouter()
router.Use(middleware.RouteHeaders().
Route("Host", config.Services["auth"].(map[string]interface{})["subdomain"].(string), middleware.New(subdomainRouter)).
Handler)
finalRouter = subdomainRouter
} else {
finalRouter = router
}
// Check if they want a resource directory
if serviceInformation.(*library.Service).Permissions.Resources {
main.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{
ServiceID: serviceInformation.(*library.Service).ServiceID,
Domain: serviceInformation.(*library.Service).Name,
Configuration: config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{}),
Outbox: globalOutbox,
Inbox: inbox,
ResourceDir: os.DirFS(filepath.Join(config.Global.ServiceDirectory, serviceInformation.(*library.Service).ServiceID.String())),
Router: finalRouter,
})
} else {
main.(func(library.ServiceInitializationInformation))(library.ServiceInitializationInformation{
ServiceID: serviceInformation.(*library.Service).ServiceID,
Domain: serviceInformation.(*library.Service).Name,
Configuration: config.Services[serviceInformation.(*library.Service).Name].(map[string]interface{}),
Outbox: globalOutbox,
Inbox: inbox,
Router: router,
})
}
}
// Start the server
slog.Info(fmt.Sprintf("Starting server on %s:%s", config.Global.IP, config.Global.Port))
err = http.ListenAndServe(config.Global.IP+":"+config.Global.Port, router)
if err != nil {
slog.Error("Error starting server: ", err)
os.Exit(1)
}
}

View File

@ -0,0 +1,157 @@
# GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
## 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
## 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
## 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
## 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
## 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
## 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
## 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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 Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

23
services-src/auth/build.sh Executable file
View File

@ -0,0 +1,23 @@
#!/bin/sh
path=$(realpath "$(dirname "$0")") || exit 1
resourceDir="$path/../../resources/00000000-0000-0000-0000-000000000004"
rm -rf "$resourceDir" || exit 1
rm -rf "$path/../../services/auth.fgs" || exit 1
cd "$path" || exit 1
go build -o "$path/../../services/auth.fgs" --buildmode=plugin -ldflags "-s -w" || exit 1
mkdir -p "$resourceDir/static/wasm" || exit 1
cd "$path/resources/wasm/login" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/login.wasm" -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/signup" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/signup.wasm" -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/authorize" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/authorize.wasm" -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/dashboard" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/dashboard.wasm" -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/testApp" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/testApp.wasm" -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/clientKeyShare" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/clientKeyShare.wasm" -ldflags "-s -w" || exit 1
cp -r "$path/resources/static" "$resourceDir/" || exit 1
cp -r "$path/resources/templates" "$resourceDir/" || exit 1

View File

@ -0,0 +1,14 @@
package library
type OAuthInformation struct {
Token string `json:"token"`
Name string `json:"name"`
RedirectUri string `json:"redirectUri"`
KeyShareUri string `json:"keyShareUri"`
Scopes []string `json:"scopes"`
}
type OAuthResponse struct {
AppID string `json:"appId"`
SecretKey string `json:"secretKey"`
}

1807
services-src/auth/main.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
module git.ailur.dev/fulgens/services-src/auth/resources-src
go 1.23.0
require (
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5
github.com/cespare/xxhash/v2 v2.3.0
golang.org/x/crypto v0.27.0
)
require golang.org/x/sys v0.25.0 // indirect

View File

@ -0,0 +1,8 @@
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5 h1:QGICG5QsXtGVDV0YjR4bXiEV2kWQ96riPR9qFWuFpr4=
git.ailur.dev/ailur/pow-argon2 v0.0.0-20240922143345-8f9af6dce3a5/go.mod h1:dDulL+Bfr47BPmvSPRkRD3uOVNsfM6yOTwhdAkctZU4=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

View File

@ -0,0 +1,309 @@
@import url("../fonts/inter.css");
:root {
--invertdm: 0%;
--text-color: #000000;
--editor: #ffffff;
--border-color: #dadada;
--theme-color: #1c71d8;
--hover-theme-color: #4990e7;
--nonimporant-theme-color: #EBEBEB;
--hover-nonimportant-theme-color: #dbdbdb;
--nonimportant-text-color: #000;
--inOutDiv: #fafafa;
}
/* dark mode */
@media (prefers-color-scheme: dark) {
:root {
--invertdm: 100%;
--inOutDiv: #2d2f31;
--text-color: #ffffff;
--editor: #1E1E1E;
--nonimportant-text-color: #fff;
--border-color: #393b3d;
}
.inOutDiv p {
color: white !important;
}
.inOutDiv a {
color: #969696 !important;
}
.inOutDiv input {
color: white;
background-color: var(--editor);
}
}
p,
li,
h1,
h2,
h3,
h4,
h5,
h6 {
color: var(--text-color);
white-space: break-spaces;
}
p#statusBox {
overflow-wrap: break-word;
}
body {
margin: 0;
background-color: var(--editor);
font-family: "Inter", sans-serif;
}
/* Sign up/log in div */
.inOutDiv {
border-radius: 8px;
margin: 10%;
padding: 30px;
border: solid 1px var(--border-color);
background-color: var(--inOutDiv);
}
table {
border-spacing: 0;
}
input {
width: calc(100% - 35px);
margin-left: 10px;
margin-right: 10px;
height: 30px;
padding-left: 10px;
padding-right: 10px;
border: solid;
border-color: var(--border-color);
border-width: 1px;
border-radius: 8px;
min-width: 20px;
}
.inputBox input {
margin-left: 5px;
margin-right: 0;
}
@media only screen and (max-width: 600px) {
body {
background-color: var(--inOutDiv);
}
.inOutDiv {
position: absolute;
top: 0;
left: 10px;
right: 10px;
border-radius: 0;
min-width: calc(100% - 20px);
min-height: 100%;
transform: none;
padding: 5px;
overflow-y: auto;
overflow-x: auto;
margin: 0;
border: 0;
}
.inOutDiv p {
font-size: 14px;
}
.inOutDiv h2 {
font-size: 21px;
}
.background {
display: none;
}
.inOutDiv input {
width: calc(100% - 32px);
}
}
.inOutDiv img {
min-width: 200px;
max-width: 100%;
border-radius: 20px;
background-color: white;
}
.iframe {
position: fixed;
right: 5px;
top: 47px;
border: none;
height: 278px;
width: 400px;
transform: translateX(26px);
}
.spacer {
margin-top: 30px;
}
.credit {
position: fixed;
left: 5px;
color: white;
z-index: -1;
margin: 0;
bottom: 5px;
text-shadow: black 1px 1px 5px;
}
.newOauth, .oauthList, .sessionEntry, .oauthEntry {
text-align: center;
width: calc(100% - 17.5vh);
margin-top: 7vh;
margin-left: 7vh;
margin-right: 7vh;
padding: 15px 10px 30px;
border-style: solid;
border-image: none;
border-radius: 8px;
border-width: 1px;
font-size: 17px;
background-color: var(--inOutDiv);
border-color: var(--border-color);
}
.oauthEntry, .sessionEntry {
display: flex;
flex-direction: column;
justify-content: center;
padding: 5px;
margin-top: 0;
margin-bottom: 20px;
}
.oauthEntry button, .sessionEntry button {
padding: 10px;
background-color: red;
color: white
}
.oauthEntry button:hover, .sessionEntry button:hover {
background-color: black;
}
.oauthEntry img, .sessionEntry img {
max-height: 64px;
margin-top: 10px;
}
button {
background-color: var(--theme-color);
color: white;
margin-right: 5px;
padding: 10px 20px;
border: none;
border-radius: 25px;
font-size: 14px;
transition: 0.125s;
}
button:hover {
background-color: var(--hover-theme-color);
transition: all 0.3s ease 0s;
}
.inOutDiv .inputContainer {
margin-bottom: 20px;
margin-right: 20px;
width: 100%;
display: flex;
}
.inOutDiv .inputBox {
width: 100%;
}
.unimportant {
background-color: var(--nonimporant-theme-color);
color: var(--nonimportant-text-color) !important;
}
.unimportant:hover {
background-color: var(--hover-nonimportant-theme-color);
transition: all 0.3s ease 0s;
}
h2 {
display: block;
margin-top: 20px;
font-weight: 300;
}
.inOutDiv a {
color: grey;
text-align: center;
}
.background {
position: fixed;
z-index: -2;
top: 0;
width: 100%;
height: 100%;
object-fit: cover;
-webkit-user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
pointer-events: none;
}
.vAlign {
display: flex;
flex-direction: column;
justify-content: center;
}
.hidden {
display: none !important;
}
.w100 {
font-weight: 300;
}
.w200 {
font-weight: 300;
}
.w300 {
font-weight: 300;
}
.w400 {
font-weight: 400;
}
.w500 {
font-weight: 500;
}
.w600 {
font-weight: 600;
}
.w700 {
font-weight: 700;
}
.w800 {
font-weight: 800;
}
.w900 {
font-weight: 900;
}

View File

@ -0,0 +1,57 @@
/* Variable fonts usage:
:root { font-family: "Inter", sans-serif; }
@supports (font-variation-settings: normal) {
:root { font-family: "InterVariable", sans-serif; font-optical-sizing: auto; }
} */
@font-face {
font-family: InterVariable;
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url("InterVariable.woff2") format("woff2");
}
@font-face {
font-family: InterVariable;
font-style: italic;
font-weight: 100 900;
font-display: swap;
src: url("InterVariable-Italic.woff2") format("woff2");
}
/* static fonts */
@font-face { font-family: "Inter"; font-style: normal; font-weight: 100; font-display: swap; src: url("Inter-Thin.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 100; font-display: swap; src: url("Inter-ThinItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 200; font-display: swap; src: url("Inter-ExtraLight.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 200; font-display: swap; src: url("Inter-ExtraLightItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 300; font-display: swap; src: url("Inter-Light.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 300; font-display: swap; src: url("Inter-LightItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 400; font-display: swap; src: url("Inter-Regular.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 400; font-display: swap; src: url("Inter-Italic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 500; font-display: swap; src: url("Inter-Medium.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 500; font-display: swap; src: url("Inter-MediumItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 600; font-display: swap; src: url("Inter-SemiBold.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 600; font-display: swap; src: url("Inter-SemiBoldItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 700; font-display: swap; src: url("Inter-Bold.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 700; font-display: swap; src: url("Inter-BoldItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 800; font-display: swap; src: url("Inter-ExtraBold.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 800; font-display: swap; src: url("Inter-ExtraBoldItalic.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: normal; font-weight: 900; font-display: swap; src: url("Inter-Black.woff2") format("woff2"); }
@font-face { font-family: "Inter"; font-style: italic; font-weight: 900; font-display: swap; src: url("Inter-BlackItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 100; font-display: swap; src: url("InterDisplay-Thin.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 100; font-display: swap; src: url("InterDisplay-ThinItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 200; font-display: swap; src: url("InterDisplay-ExtraLight.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 200; font-display: swap; src: url("InterDisplay-ExtraLightItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 300; font-display: swap; src: url("InterDisplay-Light.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 300; font-display: swap; src: url("InterDisplay-LightItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 400; font-display: swap; src: url("InterDisplay-Regular.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 400; font-display: swap; src: url("InterDisplay-Italic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 500; font-display: swap; src: url("InterDisplay-Medium.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 500; font-display: swap; src: url("InterDisplay-MediumItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 600; font-display: swap; src: url("InterDisplay-SemiBold.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 600; font-display: swap; src: url("InterDisplay-SemiBoldItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 700; font-display: swap; src: url("InterDisplay-Bold.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 700; font-display: swap; src: url("InterDisplay-BoldItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 800; font-display: swap; src: url("InterDisplay-ExtraBold.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 800; font-display: swap; src: url("InterDisplay-ExtraBoldItalic.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: normal; font-weight: 900; font-display: swap; src: url("InterDisplay-Black.woff2") format("woff2"); }
@font-face { font-family: "InterDisplay"; font-style: italic; font-weight: 900; font-display: swap; src: url("InterDisplay-BlackItalic.woff2") format("woff2"); }

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

View File

@ -0,0 +1,7 @@
// @license magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt LGPL-3.0
// This sad excuse for a script is used so LibreJS doesn't scream at me
localStorage.clear()
window.location.replace("/login" + window.location.search)
// @license-end

View File

@ -0,0 +1,583 @@
// @license magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt LGPL-3.0
/*
* wasm_helper
* (c) Arzumify
* @license LGPL-3.0
*/
async function loadWasm(url) {
const go = new Go();
WebAssembly.instantiateStreaming(fetch(url), go.importObject).then((result) => {
go.run(result.instance);
})
}
// @license-end
// @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause
/*
* wasm_exec (https://github.com/golang/go)
* (c) The Go Authors
* @license BSD-3-Clause
*/
"use strict";
(() => {
const enosys = () => {
const err = new Error("not implemented");
err.code = "ENOSYS";
return err;
};
if (!globalThis.fs) {
let outputBuf = "";
globalThis.fs = {
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
writeSync(fd, buf) {
outputBuf += decoder.decode(buf);
const nl = outputBuf.lastIndexOf("\n");
if (nl != -1) {
console.log(outputBuf.substring(0, nl));
outputBuf = outputBuf.substring(nl + 1);
}
return buf.length;
},
write(fd, buf, offset, length, position, callback) {
if (offset !== 0 || length !== buf.length || position !== null) {
callback(enosys());
return;
}
const n = this.writeSync(fd, buf);
callback(null, n);
},
chmod(path, mode, callback) { callback(enosys()); },
chown(path, uid, gid, callback) { callback(enosys()); },
close(fd, callback) { callback(enosys()); },
fchmod(fd, mode, callback) { callback(enosys()); },
fchown(fd, uid, gid, callback) { callback(enosys()); },
fstat(fd, callback) { callback(enosys()); },
fsync(fd, callback) { callback(null); },
ftruncate(fd, length, callback) { callback(enosys()); },
lchown(path, uid, gid, callback) { callback(enosys()); },
link(path, link, callback) { callback(enosys()); },
lstat(path, callback) { callback(enosys()); },
mkdir(path, perm, callback) { callback(enosys()); },
open(path, flags, mode, callback) { callback(enosys()); },
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
readdir(path, callback) { callback(enosys()); },
readlink(path, callback) { callback(enosys()); },
rename(from, to, callback) { callback(enosys()); },
rmdir(path, callback) { callback(enosys()); },
stat(path, callback) { callback(enosys()); },
symlink(path, link, callback) { callback(enosys()); },
truncate(path, length, callback) { callback(enosys()); },
unlink(path, callback) { callback(enosys()); },
utimes(path, atime, mtime, callback) { callback(enosys()); },
};
}
if (!globalThis.process) {
globalThis.process = {
getuid() { return -1; },
getgid() { return -1; },
geteuid() { return -1; },
getegid() { return -1; },
getgroups() { throw enosys(); },
pid: -1,
ppid: -1,
umask() { throw enosys(); },
cwd() { throw enosys(); },
chdir() { throw enosys(); },
}
}
if (!globalThis.crypto) {
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
}
if (!globalThis.performance) {
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
}
if (!globalThis.TextEncoder) {
throw new Error("globalThis.TextEncoder is not available, polyfill required");
}
if (!globalThis.TextDecoder) {
throw new Error("globalThis.TextDecoder is not available, polyfill required");
}
const encoder = new TextEncoder("utf-8");
const decoder = new TextDecoder("utf-8");
globalThis.Go = class {
constructor() {
this.argv = ["js"];
this.env = {};
this.exit = (code) => {
if (code !== 0) {
console.warn("exit code:", code);
}
};
this._exitPromise = new Promise((resolve) => {
this._resolveExitPromise = resolve;
});
this._pendingEvent = null;
this._scheduledTimeouts = new Map();
this._nextCallbackTimeoutID = 1;
const setInt64 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
}
const setInt32 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
}
const getInt64 = (addr) => {
const low = this.mem.getUint32(addr + 0, true);
const high = this.mem.getInt32(addr + 4, true);
return low + high * 4294967296;
}
const loadValue = (addr) => {
const f = this.mem.getFloat64(addr, true);
if (f === 0) {
return undefined;
}
if (!isNaN(f)) {
return f;
}
const id = this.mem.getUint32(addr, true);
return this._values[id];
}
const storeValue = (addr, v) => {
const nanHead = 0x7FF80000;
if (typeof v === "number" && v !== 0) {
if (isNaN(v)) {
this.mem.setUint32(addr + 4, nanHead, true);
this.mem.setUint32(addr, 0, true);
return;
}
this.mem.setFloat64(addr, v, true);
return;
}
if (v === undefined) {
this.mem.setFloat64(addr, 0, true);
return;
}
let id = this._ids.get(v);
if (id === undefined) {
id = this._idPool.pop();
if (id === undefined) {
id = this._values.length;
}
this._values[id] = v;
this._goRefCounts[id] = 0;
this._ids.set(v, id);
}
this._goRefCounts[id]++;
let typeFlag = 0;
switch (typeof v) {
case "object":
if (v !== null) {
typeFlag = 1;
}
break;
case "string":
typeFlag = 2;
break;
case "symbol":
typeFlag = 3;
break;
case "function":
typeFlag = 4;
break;
}
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
this.mem.setUint32(addr, id, true);
}
const loadSlice = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
}
const loadSliceOfValues = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
const a = new Array(len);
for (let i = 0; i < len; i++) {
a[i] = loadValue(array + i * 8);
}
return a;
}
const loadString = (addr) => {
const saddr = getInt64(addr + 0);
const len = getInt64(addr + 8);
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
}
const timeOrigin = Date.now() - performance.now();
this.importObject = {
_gotest: {
add: (a, b) => a + b,
},
gojs: {
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
// This changes the SP, thus we have to update the SP used by the imported function.
// func wasmExit(code int32)
"runtime.wasmExit": (sp) => {
sp >>>= 0;
const code = this.mem.getInt32(sp + 8, true);
this.exited = true;
delete this._inst;
delete this._values;
delete this._goRefCounts;
delete this._ids;
delete this._idPool;
this.exit(code);
},
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
"runtime.wasmWrite": (sp) => {
sp >>>= 0;
const fd = getInt64(sp + 8);
const p = getInt64(sp + 16);
const n = this.mem.getInt32(sp + 24, true);
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
},
// func resetMemoryDataView()
"runtime.resetMemoryDataView": (sp) => {
sp >>>= 0;
this.mem = new DataView(this._inst.exports.mem.buffer);
},
// func nanotime1() int64
"runtime.nanotime1": (sp) => {
sp >>>= 0;
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
},
// func walltime() (sec int64, nsec int32)
"runtime.walltime": (sp) => {
sp >>>= 0;
const msec = (new Date).getTime();
setInt64(sp + 8, msec / 1000);
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
},
// func scheduleTimeoutEvent(delay int64) int32
"runtime.scheduleTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this._nextCallbackTimeoutID;
this._nextCallbackTimeoutID++;
this._scheduledTimeouts.set(id, setTimeout(
() => {
this._resume();
while (this._scheduledTimeouts.has(id)) {
// for some reason Go failed to register the timeout event, log and try again
// (temporary workaround for https://github.com/golang/go/issues/28975)
console.warn("scheduleTimeoutEvent: missed timeout event");
this._resume();
}
},
getInt64(sp + 8),
));
this.mem.setInt32(sp + 16, id, true);
},
// func clearTimeoutEvent(id int32)
"runtime.clearTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this.mem.getInt32(sp + 8, true);
clearTimeout(this._scheduledTimeouts.get(id));
this._scheduledTimeouts.delete(id);
},
// func getRandomData(r []byte)
"runtime.getRandomData": (sp) => {
sp >>>= 0;
crypto.getRandomValues(loadSlice(sp + 8));
},
// func finalizeRef(v ref)
"syscall/js.finalizeRef": (sp) => {
sp >>>= 0;
const id = this.mem.getUint32(sp + 8, true);
this._goRefCounts[id]--;
if (this._goRefCounts[id] === 0) {
const v = this._values[id];
this._values[id] = null;
this._ids.delete(v);
this._idPool.push(id);
}
},
// func stringVal(value string) ref
"syscall/js.stringVal": (sp) => {
sp >>>= 0;
storeValue(sp + 24, loadString(sp + 8));
},
// func valueGet(v ref, p string) ref
"syscall/js.valueGet": (sp) => {
sp >>>= 0;
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 32, result);
},
// func valueSet(v ref, p string, x ref)
"syscall/js.valueSet": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
},
// func valueDelete(v ref, p string)
"syscall/js.valueDelete": (sp) => {
sp >>>= 0;
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
},
// func valueIndex(v ref, i int) ref
"syscall/js.valueIndex": (sp) => {
sp >>>= 0;
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
},
// valueSetIndex(v ref, i int, x ref)
"syscall/js.valueSetIndex": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
},
// func valueCall(v ref, m string, args []ref) (ref, bool)
"syscall/js.valueCall": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const m = Reflect.get(v, loadString(sp + 16));
const args = loadSliceOfValues(sp + 32);
const result = Reflect.apply(m, v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, result);
this.mem.setUint8(sp + 64, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, err);
this.mem.setUint8(sp + 64, 0);
}
},
// func valueInvoke(v ref, args []ref) (ref, bool)
"syscall/js.valueInvoke": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.apply(v, undefined, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueNew(v ref, args []ref) (ref, bool)
"syscall/js.valueNew": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.construct(v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueLength(v ref) int
"syscall/js.valueLength": (sp) => {
sp >>>= 0;
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
},
// valuePrepareString(v ref) (ref, int)
"syscall/js.valuePrepareString": (sp) => {
sp >>>= 0;
const str = encoder.encode(String(loadValue(sp + 8)));
storeValue(sp + 16, str);
setInt64(sp + 24, str.length);
},
// valueLoadString(v ref, b []byte)
"syscall/js.valueLoadString": (sp) => {
sp >>>= 0;
const str = loadValue(sp + 8);
loadSlice(sp + 16).set(str);
},
// func valueInstanceOf(v ref, t ref) bool
"syscall/js.valueInstanceOf": (sp) => {
sp >>>= 0;
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
},
// func copyBytesToGo(dst []byte, src ref) (int, bool)
"syscall/js.copyBytesToGo": (sp) => {
sp >>>= 0;
const dst = loadSlice(sp + 8);
const src = loadValue(sp + 32);
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
// func copyBytesToJS(dst ref, src []byte) (int, bool)
"syscall/js.copyBytesToJS": (sp) => {
sp >>>= 0;
const dst = loadValue(sp + 8);
const src = loadSlice(sp + 16);
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
"debug": (value) => {
console.log(value);
},
}
};
}
async run(instance) {
if (!(instance instanceof WebAssembly.Instance)) {
throw new Error("Go.run: WebAssembly.Instance expected");
}
this._inst = instance;
this.mem = new DataView(this._inst.exports.mem.buffer);
this._values = [ // JS values that Go currently has references to, indexed by reference id
NaN,
0,
null,
true,
false,
globalThis,
this,
];
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
this._ids = new Map([ // mapping from JS values to reference ids
[0, 1],
[null, 2],
[true, 3],
[false, 4],
[globalThis, 5],
[this, 6],
]);
this._idPool = []; // unused ids that have been garbage collected
this.exited = false; // whether the Go program has exited
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
let offset = 4096;
const strPtr = (str) => {
const ptr = offset;
const bytes = encoder.encode(str + "\0");
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
offset += bytes.length;
if (offset % 8 !== 0) {
offset += 8 - (offset % 8);
}
return ptr;
};
const argc = this.argv.length;
const argvPtrs = [];
this.argv.forEach((arg) => {
argvPtrs.push(strPtr(arg));
});
argvPtrs.push(0);
const keys = Object.keys(this.env).sort();
keys.forEach((key) => {
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
});
argvPtrs.push(0);
const argv = offset;
argvPtrs.forEach((ptr) => {
this.mem.setUint32(offset, ptr, true);
this.mem.setUint32(offset + 4, 0, true);
offset += 8;
});
// The linker guarantees global data starts from at least wasmMinDataAddr.
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
const wasmMinDataAddr = 4096 + 8192;
if (offset >= wasmMinDataAddr) {
throw new Error("total length of command line and environment variables exceeds limit");
}
this._inst.exports.run(argc, argv);
if (this.exited) {
this._resolveExitPromise();
}
await this._exitPromise;
}
_resume() {
if (this.exited) {
throw new Error("Go program has already exited");
}
this._inst.exports.resume();
if (this.exited) {
this._resolveExitPromise();
}
}
_makeFuncWrapper(id) {
const go = this;
return function () {
const event = { id: id, this: this, args: arguments };
go._pendingEvent = event;
go._resume();
return event.result;
};
}
}
})();
// @license-end

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M70-120q-12.75 0-21.375-8.675Q40-137.351 40-150.175 40-163 48.625-171.5T70-180h820q12.75 0 21.375 8.675 8.625 8.676 8.625 21.5 0 12.825-8.625 21.325T890-120H70Zm70-120q-24 0-42-18t-18-42v-480q0-24 18-42t42-18h680q24 0 42 18t18 42v480q0 24-18 42t-42 18H140Zm0-60h680v-480H140v480Zm0 0v-480 480Z"/></svg>

After

Width:  |  Height:  |  Size: 399 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="40px" viewBox="0 -960 960 960" width="40px" fill="#000000"><path d="M480-278.67q-15.38 0-26.69-11.31T442-316.67q0-15.38 11.31-26.69T480-354.67q15.38 0 26.69 11.31T518-316.67q0 15.38-11.31 26.69T480-278.67Zm-26.67-128.66q0-45.34 7.84-63.67 7.83-18.33 37.5-40.33 24.66-18 34.33-31.17 9.67-13.17 9.67-38.17 0-25.33-16.5-40.66-16.5-15.34-46.5-15.34T433-618.5q-16.67 18.17-22.33 37.17l-49.34-18Q376-639 405.57-663.83q29.57-24.84 74.43-24.84 49 0 82.5 27.84Q596-633 596-581.33q0 30.66-12.67 52-12.66 21.33-42 44.66-24 20-29.33 31.67-5.33 11.67-5.33 45.67h-53.34ZM266.67-40q-27 0-46.84-19.83Q200-79.67 200-106.67v-746.66q0-27 19.83-46.84Q239.67-920 266.67-920h426.66q27 0 46.84 19.83Q760-880.33 760-853.33v746.66q0 27-19.83 46.84Q720.33-40 693.33-40H266.67Zm0-100v33.33h426.66V-140H266.67Zm0-66.67h426.66v-546.66H266.67v546.66Zm0-613.33h426.66v-33.33H266.67V-820Zm0 0v-33.33V-820Zm0 680v33.33V-140Z"/></svg>

After

Width:  |  Height:  |  Size: 948 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M260-40q-24 0-42-18t-18-42v-760q0-24 18-42t42-18h440q24 0 42 18t18 42v760q0 24-18 42t-42 18H260Zm0-90v30h440v-30H260Zm0-60h440v-580H260v580Zm0-640h440v-30H260v30Zm0 0v-30 30Zm0 700v30-30Z"/></svg>

After

Width:  |  Height:  |  Size: 293 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M140-160q-24 0-42-18t-18-42v-520q0-24 18-42t42-18h680q24 0 42 18t18 42v520q0 24-18 42t-42 18H140Zm0-60h680v-436H140v436Zm160-72-42-42 103-104-104-104 43-42 146 146-146 146Zm190 4v-60h220v60H490Z"/></svg>

After

Width:  |  Height:  |  Size: 300 B

View File

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 26.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 1000000 1000000"
xml:space="preserve"
width="1000000"
height="1000000"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"><defs
id="defs124" />
<g
transform="matrix(2.0000001,0,0,2.0000001,-480.73603,-500.00106)"
id="g124">
<path
style="fill:#f6d2a2"
d="m 312.793,520.329 c 0.704,14.774 15.634,7.817 22.122,3.283 6.488,-4.534 7.817,-0.704 8.755,-9.381 0.576,-5.661 0.811,-11.352 0.704,-17.041 -9.851,-1.008 -19.74,1.513 -27.907,7.114 -4.065,2.97 -11.647,12.351 -3.752,15.634"
id="path92" />
<path
style="fill:#010101"
d="m 320.454,531.039 c -1.461,0.02 -2.906,-0.301 -4.221,-0.938 -3.063,-1.768 -4.921,-5.063 -4.847,-8.599 -1.966,-0.979 -3.293,-2.897 -3.518,-5.081 0.567,-5.266 3.427,-10.013 7.817,-12.976 8.433,-5.806 18.662,-8.411 28.845,-7.348 h 1.173 v 1.173 c 0.163,4.46 0.033,8.925 -0.391,13.367 v 3.909 c -0.391,6.097 -1.563,7.035 -4.69,7.817 -1.668,0.516 -3.249,1.281 -4.69,2.267 -4.498,3.473 -9.841,5.686 -15.478,6.409 z m 19.855,-32.285 c -8.21,-0.127 -16.251,2.335 -22.982,7.035 -3.535,2.441 -5.91,6.229 -6.566,10.475 0.196,1.491 1.229,2.737 2.658,3.205 h 0.782 v 0.86 c -0.23,2.761 1.019,5.438 3.283,7.035 5.994,0.93 12.092,-0.845 16.65,-4.847 1.631,-1.144 3.422,-2.039 5.316,-2.658 2.032,-0.703 2.501,-0.86 2.814,-5.706 v -3.909 c 0.366,-3.897 0.522,-7.812 0.469,-11.726 h -2.423 v 0.236 z"
id="path93" />
<path
style="fill:#c7b199"
d="m 312.793,520.329 c 2.234,-0.495 4.274,-1.637 5.863,-3.283"
id="path94" />
<path
style="fill:#010101"
d="m 312.793,521.736 c -0.756,0.237 -1.56,-0.182 -1.798,-0.938 -0.237,-0.755 0.183,-1.56 0.938,-1.798 h 0.938 c 1.652,-0.383 3.15,-1.255 4.299,-2.501 0.475,-0.626 1.367,-0.749 1.993,-0.274 0.626,0.475 0.749,1.367 0.274,1.993 v 0 c -1.478,1.698 -3.443,2.899 -5.628,3.44 h -1.016 z"
id="path95" />
<path
style="fill:#74cddd"
d="m 346.875,344.522 c -56.518,-15.634 -14.462,-87.786 31.268,-58.237 z"
id="path96" />
<path
style="fill:#010101"
d="m 347.579,346.164 h -1.094 c -16.103,-4.534 -26.031,-14.071 -27.907,-26.813 -1.356,-14.13 5.394,-27.812 17.432,-35.333 13.121,-8.301 29.982,-7.743 42.525,1.407 l 1.094,0.704 z m 7.817,-65.507 c -6.415,0.008 -12.689,1.882 -18.058,5.394 -11.143,6.915 -17.411,19.541 -16.181,32.597 1.72,11.335 10.475,19.934 24.78,24.233 l 29.705,-56.049 c -6.009,-3.758 -12.926,-5.812 -20.012,-5.941 z"
id="path97" />
<path
style="fill:#74cddd"
d="m 597.961,280.891 c 44.714,-31.268 85.128,39.086 33.145,57.299 z"
id="path98" />
<path
style="fill:#010101"
d="m 630.48,339.91 -34.395,-59.41 1.016,-0.704 c 11.708,-9.385 27.933,-10.745 41.04,-3.44 12.329,7.221 19.552,20.759 18.683,35.021 -0.782,7.817 -5.003,21.184 -25.249,28.142 z m -30.643,-58.628 31.894,55.189 c 11.834,-3.209 20.605,-13.18 22.279,-25.327 0.835,-13.209 -5.849,-25.761 -17.276,-32.441 -11.685,-6.699 -26.258,-5.681 -36.897,2.579 z"
id="path99" />
<path
style="fill:#f6d2a2"
d="m 607.576,701.999 c 11.335,7.035 32.128,28.298 15.087,38.617 -16.338,15.009 -25.562,-16.494 -39.945,-20.794 5.58,-9.016 14.528,-15.432 24.858,-17.823 z"
id="path100" />
<path
style="fill:#010101"
d="m 613.986,746.009 h -0.625 c -6.488,-0.391 -11.804,-6.723 -16.963,-12.742 -3.565,-5.187 -8.413,-9.361 -14.071,-12.117 l -1.876,-0.547 1.173,-1.954 c 5.815,-9.275 15.059,-15.878 25.718,-18.37 h 1.016 c 7.27,4.534 22.279,17.667 22.201,29.549 -0.092,4.782 -2.791,9.131 -7.035,11.335 -2.423,2.801 -5.847,4.541 -9.538,4.846 z m -29.08,-26.891 c 5.303,3.119 9.906,7.297 13.524,12.273 3.418,5.614 8.747,9.806 15.009,11.804 2.993,-0.128 5.809,-1.451 7.817,-3.674 3.476,-1.699 5.709,-5.2 5.785,-9.068 0,-9.537 -12.038,-21.497 -20.403,-26.891 -8.911,2.291 -16.638,7.842 -21.653,15.556 z"
id="path101" />
<path
style="fill:#010101"
d="m 622.663,742.101 c -0.531,-0.004 -1.015,-0.306 -1.251,-0.782 -0.827,-1.73 -1.557,-3.505 -2.189,-5.316 -0.951,-3.538 -2.718,-6.805 -5.159,-9.537 -0.561,-0.54 -0.579,-1.432 -0.039,-1.993 0.54,-0.561 1.432,-0.579 1.993,-0.039 2.699,2.947 4.679,6.479 5.785,10.319 0.613,1.705 1.317,3.375 2.111,5.003 0.34,0.691 0.062,1.527 -0.625,1.876 z"
id="path102" />
<path
style="fill:#f6d2a2"
d="m 404.566,725.997 c -13.367,2.032 -20.872,14.071 -31.972,20.168 -3.934,3.631 -10.066,3.386 -13.697,-0.547 -0.839,-0.909 -1.497,-1.97 -1.937,-3.127 -1.572,0.037 -3.073,-0.655 -4.065,-1.876 -9.693,-15.634 10.084,-26.5 20.481,-34.161 14.617,-2.814 23.607,9.615 31.19,19.543 z"
id="path103" />
<path
style="fill:#010101"
d="m 365.558,749.918 c -0.83,0.11 -1.671,0.11 -2.501,0 -2.964,-0.959 -5.416,-3.073 -6.801,-5.863 -1.532,-0.011 -2.962,-0.77 -3.83,-2.032 -9.381,-14.774 6.566,-25.953 17.119,-33.379 l 3.674,-2.658 c 14.774,-2.971 24.155,9.224 31.659,19.074 l 2.111,2.814 h -2.345 c -7.543,1.802 -14.409,5.737 -19.777,11.335 -3.6,3.31 -7.529,6.243 -11.726,8.755 -2.321,1.283 -4.93,1.956 -7.583,1.954 z m -9.38,-9.068 c 0.541,-0.119 1.101,-0.119 1.642,0 h 0.391 l 0.625,1.251 c 1.027,2.234 2.917,3.955 5.237,4.768 2.75,0.413 5.554,-0.259 7.817,-1.876 4.054,-2.423 7.852,-5.252 11.335,-8.442 5.276,-5.274 11.735,-9.214 18.839,-11.491 -7.192,-9.38 -15.634,-19.543 -27.907,-17.198 l -3.518,2.501 c -10.788,7.817 -24.155,17.041 -16.416,29.471 0.351,0.596 0.956,0.999 1.642,1.094 z"
id="path104" />
<path
style="fill:#010101"
d="m 357.194,743.977 c -0.776,0.045 -1.441,-0.548 -1.486,-1.323 -0.011,-0.188 0.016,-0.376 0.079,-0.553 0.576,-3.755 2.141,-7.289 4.534,-10.24 1.132,-1.552 2.126,-3.2 2.97,-4.925 0.324,-0.712 1.164,-1.027 1.876,-0.704 0.712,0.323 1.027,1.164 0.704,1.876 -0.908,1.889 -1.98,3.694 -3.205,5.394 -2.064,2.656 -3.386,5.812 -3.83,9.146 -0.032,0.776 -0.688,1.38 -1.464,1.348 -0.06,-0.003 -0.119,-0.009 -0.178,-0.019 z m -7.974,-419.31 c -7.817,-3.909 -12.898,-9.302 -8.364,-17.901 4.534,-8.599 12.038,-7.114 19.543,-3.205 z m 270.082,-7.505 c 7.817,-3.909 12.898,-9.302 8.364,-17.901 -4.534,-8.599 -12.038,-7.114 -19.543,-3.205 z"
id="path105" />
<path
style="fill:#f6d2a2"
d="m 670.66,518.453 c -0.704,14.774 -15.634,7.817 -22.122,3.283 -6.488,-4.534 -7.817,-0.704 -8.755,-9.381 -0.576,-5.661 -0.811,-11.352 -0.703,-17.041 9.851,-1.008 19.74,1.513 27.907,7.114 4.065,2.971 11.648,12.351 3.752,15.634"
id="path106" />
<path
style="fill:#010101"
d="m 662.999,528.85 c -5.373,-0.584 -10.509,-2.521 -14.931,-5.628 -1.441,-0.986 -3.022,-1.75 -4.69,-2.267 -3.127,-1.094 -4.299,-2.032 -4.69,-7.817 v -3.909 c -0.424,-4.442 -0.554,-8.908 -0.391,-13.367 v -1.876 h 1.173 c 10.183,-1.063 20.412,1.542 28.845,7.348 4.39,2.963 7.25,7.711 7.817,12.976 -0.225,2.184 -1.552,4.102 -3.518,5.081 0.074,3.536 -1.783,6.831 -4.847,8.599 -1.487,0.696 -3.131,0.992 -4.768,0.86 z m -22.748,-32.207 c -0.053,3.914 0.104,7.828 0.469,11.726 v 3.909 c 0,4.768 0.704,4.925 2.814,5.706 1.893,0.619 3.685,1.514 5.316,2.658 4.553,4.011 10.656,5.788 16.65,4.847 2.264,-1.598 3.513,-4.274 3.283,-7.035 v -0.938 h 0.782 c 1.429,-0.468 2.462,-1.714 2.658,-3.205 -0.657,-4.245 -3.031,-8.034 -6.566,-10.475 -7.406,-5.214 -16.366,-7.751 -25.406,-7.193 z"
id="path107" />
<path
style="fill:#c7b199"
d="m 670.66,518.453 c -2.208,-0.429 -4.244,-1.488 -5.863,-3.049"
id="path108" />
<path
style="fill:#010101"
d="m 670.66,519.86 h -1.485 c -2.189,-0.696 -4.103,-2.064 -5.472,-3.909 -0.475,-0.626 -0.352,-1.518 0.274,-1.993 0.626,-0.475 1.518,-0.352 1.993,0.274 1.149,1.247 2.648,2.118 4.299,2.501 h 0.938 c 0.863,0.151 1.441,0.974 1.29,1.837 -0.151,0.864 -0.974,1.441 -1.837,1.29 z"
id="path109" />
<path
style="fill:#74cddd"
d="m 486.098,251.03 c 56.596,0 109.44,7.817 137.268,62.537 24.78,60.895 15.634,126.637 19.777,190.972 3.283,55.267 10.475,119.133 -15.165,170.413 -26.813,53.782 -94.509,67.149 -150.01,65.351 -43.619,-1.563 -96.307,-15.634 -120.931,-55.658 -28.923,-46.903 -15.243,-116.319 -13.133,-168.302 2.501,-61.599 -16.729,-123.432 3.518,-183.78 21.028,-62.537 77.624,-76.686 138.597,-81.532"
id="path110" />
<path
style="fill:#010101"
d="m 487.583,742.101 h -9.693 c -23.301,-0.655 -46.323,-5.254 -68.087,-13.602 -22.158,-8.032 -41.113,-23.036 -54.016,-42.76 -23.451,-37.835 -19.23,-90.053 -15.634,-136.174 0.938,-11.569 1.798,-22.591 2.189,-32.91 0.414,-21.873 -0.526,-43.751 -2.814,-65.507 -3.283,-39.086 -6.723,-79.5 6.41,-118.664 8.567,-27.82 28.42,-50.764 54.72,-63.24 21.106,-10.319 46.903,-16.26 84.816,-19.23 55.814,-0.391 110.847,7.426 139.145,62.85 18.136,44.558 18.37,92.398 18.683,138.676 0,17.354 0,35.255 1.251,52.766 0,5.316 0.625,10.709 1.016,16.103 3.283,50.733 7.035,108.345 -16.338,154.935 -29.238,58.314 -102.718,66.757 -141.648,66.757 z m -1.485,-489.664 c -58.863,5.003 -116.24,17.667 -137.347,80.594 -12.976,38.617 -9.537,78.718 -6.332,117.257 2.296,21.861 3.236,43.843 2.814,65.82 -0.391,10.397 -1.329,21.419 -2.189,33.066 -3.596,45.652 -7.817,97.479 15.087,134.454 9.615,15.634 40.571,52.14 119.836,54.72 34.317,1.251 117.257,-2.658 148.525,-64.726 22.982,-45.965 19.308,-103.108 16.025,-153.528 0,-5.472 -0.704,-10.866 -1.016,-16.103 -0.86,-17.041 -1.251,-35.021 -1.251,-52.375 0,-45.965 -0.469,-93.805 -18.448,-137.581 -11.565,-23.797 -32.039,-42.079 -56.987,-50.889 -25.435,-8.035 -52.059,-11.657 -78.717,-10.709 z"
id="path111" />
<path
style="fill:#ffffff"
d="m 496.026,326.934 c 10.162,59.019 106.625,43.463 92.789,-16.103 -12.429,-53.391 -96.151,-38.617 -92.789,16.103"
id="path112" />
<path
style="fill:#010101"
d="m 541.912,365.472 c -6.009,0.025 -11.98,-0.952 -17.667,-2.892 -15.784,-5.222 -27.237,-18.948 -29.549,-35.411 -1.062,-12.778 3.373,-25.403 12.195,-34.708 8.366,-8.583 19.383,-14.091 31.268,-15.634 10.893,-1.724 22.051,0.2 31.737,5.472 10.451,6.104 17.812,16.364 20.246,28.22 4.292,15.119 -0.375,31.364 -12.038,41.9 -10.085,8.588 -22.945,13.226 -36.192,13.053 z m -44.479,-38.694 c 2.183,15.449 12.937,28.324 27.751,33.223 17.592,5.883 36.978,2.213 51.202,-9.693 10.742,-9.913 15.054,-24.992 11.178,-39.086 -4.99,-22.11 -26.712,-36.199 -48.935,-31.737 -24.239,2.074 -42.465,22.998 -41.196,47.293 z"
id="path113" />
<path
style="fill:#ffffff"
d="m 380.723,336.549 c 13.133,51.358 95.369,38.147 92.32,-13.367 -3.674,-61.756 -104.905,-50.108 -92.32,13.367"
id="path114" />
<path
style="fill:#010101"
d="m 424.656,370.397 c -8.362,0.063 -16.608,-1.952 -23.999,-5.863 -10.701,-5.799 -18.411,-15.899 -21.184,-27.751 -4.163,-16.329 1.579,-33.587 14.696,-44.167 15.808,-12.062 36.86,-14.746 55.189,-7.035 14.958,6.54 24.731,21.199 25.015,37.522 1.642,27.36 -20.09,43.307 -40.883,46.903 -2.931,0.358 -5.884,0.489 -8.834,0.391 z m -42.369,-34.161 c 5.629,22.608 28.348,36.525 51.046,31.268 19.699,-3.127 40.258,-18.136 38.695,-43.854 -0.193,-15.363 -9.369,-29.189 -23.451,-35.333 -17.426,-7.314 -37.434,-4.75 -52.453,6.723 -12.199,9.896 -17.589,25.944 -13.837,41.196 z"
id="path115" />
<path
style="fill:#ffffff"
d="m 507.361,398.148 c 0.752,8.139 0.752,16.329 0,24.468 -2.289,2.897 -5.528,4.891 -9.146,5.628 -4.521,-0.694 -8.379,-3.639 -10.24,-7.817 -0.502,-9.228 -0.267,-18.482 0.704,-27.673 z"
id="path116" />
<path
style="fill:#010101"
d="m 499.074,429.416 h -0.391 c -5.052,-0.785 -9.339,-4.126 -11.335,-8.833 -0.649,-6.315 -0.649,-12.68 0,-18.996 0,-2.892 0.469,-5.941 0.547,-8.911 v -2.345 l 21.106,6.488 v 1.329 c 0,2.501 0,5.159 0.391,7.817 0.706,5.58 0.706,11.227 0,16.807 v 0.391 c -1.655,2.703 -4.334,4.62 -7.426,5.316 l -2.423,0.938 h -0.469 z m -9.067,-9.849 c 1.588,3.625 4.866,6.229 8.755,6.957 l 2.189,-0.86 c 2.356,-0.567 4.401,-2.024 5.706,-4.065 0.62,-5.193 0.62,-10.441 0,-15.634 0,-2.423 0,-4.768 -0.391,-7.114 l -15.634,-4.768 c 0,2.423 0,4.847 -0.469,7.192 -0.693,6.048 -0.771,12.15 -0.235,18.214 z"
id="path117" />
<ellipse
style="fill:#010101"
cx="403.39301"
cy="328.10599"
rx="13.914"
ry="15.087"
id="ellipse117" />
<ellipse
style="fill:#ffffff"
cx="409.72501"
cy="331.54599"
rx="3.283"
ry="3.8299999"
id="ellipse118" />
<ellipse
style="fill:#010101"
cx="519.86798"
cy="324.354"
rx="13.68"
ry="15.087"
id="ellipse119" />
<ellipse
style="fill:#ffffff"
cx="526.04401"
cy="327.79401"
rx="3.2049999"
ry="3.8299999"
id="ellipse120" />
<path
style="fill:#ffffff"
d="m 468.275,396.975 c -6.097,14.696 3.361,44.088 19.855,22.435 -0.502,-9.228 -0.267,-18.482 0.704,-27.673 z"
id="path120" />
<path
style="fill:#010101"
d="m 476.796,428.556 c -1.43,0.014 -2.836,-0.365 -4.065,-1.094 -6.645,-3.83 -10.788,-19.543 -6.097,-31.268 v -0.625 l 23.451,-5.941 v 1.876 c 0,3.049 0,6.097 -0.547,8.99 -0.637,6.133 -0.637,12.315 0,18.448 v 1.016 c -2.571,4.791 -7.337,8.007 -12.742,8.598 z m -7.739,-30.408 c -3.361,9.146 -0.704,23.451 5.159,26.813 4.221,2.423 8.911,-1.798 12.195,-6.019 -0.595,-6.135 -0.595,-12.313 0,-18.448 0,-2.267 0,-4.69 0.469,-7.035 z"
id="path121" />
<path
style="fill:#f6d2a2"
d="m 470.073,368.677 c -9.842,0.937 -17.061,9.674 -16.125,19.517 0.181,1.897 0.663,3.753 1.429,5.498 7.817,14.071 25.171,-1.251 35.959,0 12.429,0 22.67,13.133 32.676,2.345 11.1,-12.038 -4.768,-23.451 -17.198,-29.001 z"
id="path122" />
<path
style="fill:#231f20"
d="m 515.178,401.978 c -3.974,-0.331 -7.848,-1.419 -11.413,-3.205 -3.866,-1.909 -8.055,-3.075 -12.351,-3.44 -4.477,-0.002 -8.902,0.958 -12.976,2.814 -8.755,3.049 -18.683,6.488 -24.311,-3.596 -2.839,-5.104 -2.839,-11.312 0,-16.416 3.084,-5.967 8.956,-9.99 15.634,-10.709 l 37.6,-1.642 c 9.224,3.909 19.777,11.022 21.575,19.308 1.099,8.172 -4.635,15.689 -12.807,16.788 -0.316,0.044 -0.633,0.076 -0.951,0.098 z m -23.452,-9.459 c 4.622,0.375 9.131,1.622 13.289,3.674 7.035,2.97 12.586,5.237 18.214,-0.86 2.612,-2.4 3.82,-5.966 3.205,-9.459 -1.563,-7.192 -11.491,-13.758 -19.621,-17.198 l -36.35,1.485 c -5.68,0.696 -10.651,4.147 -13.289,9.224 -2.351,4.257 -2.351,9.423 0,13.68 4.456,7.817 12.429,5.237 20.95,2.345 4.279,-1.913 8.915,-2.899 13.602,-2.891 z"
id="path123" />
<path
style="fill:#010101"
d="m 468.275,368.13 c -0.86,-19.543 36.506,-22.044 40.883,-5.628 4.378,16.416 -39.085,20.168 -40.883,5.628 z"
id="path124" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,32 @@
<html lang="en">
<head>
<title>Authorize application - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<span id="passThrough" style="display: none;">{{ .name }}</span>
<span id="autoAccept" style="display: none;">0</span>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2 class="w300">Authorise Application</h2>
<p id="statusBox">Loading...</p>
<br>
<div style="display: flex;justify-content: center;">
<button id="allowButton" style="width: 100%;margin: 0 3px 0 0;">Allow</button>
<button id="denyButton" style="width: 100%;margin: 0 0 0 3px;">Deny</button>
</div>
<br>
<a href="/dashboard">Return to Dashboard</a>
</div>
<script>
loadWasm("/static/wasm/authorize.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,25 @@
<html lang="en">
<head>
<title>Redirecting... - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<span id="passThrough" style="display: none;">{{ .name }}</span>
<span id="autoAccept" style="display: none;">1</span>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2 class="w300">Authorizing application</h2>
<p id="statusBox">Please wait...</p>
</div>
<script>
loadWasm("/static/wasm/authorize.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Key Exchange - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2>Relaying back information, please wait...</h2>
<p id="statusBox">Processing information sent...</p>
</div>
<script>
loadWasm("/static/wasm/clientKeyShare.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dashboard - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<img src="/static/img/background.png" class="background" alt="">
<div class="newOauth">
<h2>Dashboard</h2>
<p>Welcome to the {{ .identifier }} dashboard!</p>
<button id="devAccountSwitcher">Switch to developer view</button>
</div>
<div id="developers" class="hidden">
<div class="newOauth">
<h2>Submit a new OAuth2 App</h2>
<p id="statusBox"></p>
<p>App Name:</p>
<input id="nameBox">
<p>Redirect URI:</p>
<input id="redirectUriBox">
<p>Enable OpenID:</p>
<input type="checkbox" id="openIdBox">
<p>Client key-share URI (optional, will add the clientKeyShare scope):</p>
<input id="clientKeyShareBox">
<br>
<button style="margin-top: 10px;" id="submitButton">Submit</button>
</div>
<div class="oauthList" id="oauthList" style="margin-bottom: 30px;">
<h2>Your existing apps</h2>
</div>
</div>
<div id="account">
<div class="newOauth">
<h2>Account settings</h2>
<p id="usernameBox">Loading...</p>
<p id="dateBox"></p>
<button id="logoutButton">Logout</button><br style="">
<button id="deleteAccountButton" style="margin-top: 5px;">Delete Account</button>
</div>
<div class="oauthList" id="sessionList" style="margin-bottom: 30px;">
<h2>Sessions</h2>
</div>
</div>
<script>
loadWasm("/static/wasm/dashboard.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<span id="passThrough" style="display: none;">{{ .identifier }}</span>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2 class="w300">Login</h2>
<p id="statusBox"></p>
<div class="inputContainer" id="inputContainer">
<div class="vAlign"><span id="inputNameBox"></span></div>
<input id="usernameBox" class="hidden" type="text" placeholder="Enter your username">
<input id="passwordBox" class="hidden" type="password" placeholder="Enter your password">
</div>
<button id="nextButton">Next</button>
<button id="backButton" class="hidden unimportant">Back</button>
<button id="signupButton" class="unimportant">Signup</button>
<br>
<br>
<a href="/privacy" id="privacyButton">Privacy &amp; Terms</a>
</div>
<script>
loadWasm("/static/wasm/login.wasm")
</script>
</body>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Log out - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<script src="/static/js/logout.js"></script>
</head>
<body>
<p>Logging out...</p>
</body>
</html>

View File

@ -0,0 +1,9 @@
{
"issuer": "{{ .hostName }}",
"authorization_endpoint": "{{ .hostName }}/authorize",
"token_endpoint": "{{ .hostName }}/api/oauth/token",
"userinfo_endpoint": "{{ .hostName }}/api/oauth/userinfo",
"jwks_uri": "{{ .hostName }}/.well-known/keys.json",
"response_types_supported": ["code"],
"subject_types_supported": ["public"]
}

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<meta http-equiv="refresh" content="0">
<title>Please wait...</title>
<script>
window.location.reload()
</script>
</head>
<body>
<p>Please wait...</p>
<p>If your browser does not refresh, please refresh the page manually.</p>
</body>
</html>

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signup - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
</head>
<body>
<p style="display: none;" id="passthrough">{{ .unique_token }}</p>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2 class="w300">Signup</h2>
<p>Signup to {{ .identifier }}!</p>
<p id="statusBox"></p>
<table id="inputContainer">
<tr>
<td><span id="inputNameBox">Username:</span></td>
<td class="inputBox"><input id="usernameBox" type="text" placeholder="Username"></td>
</tr>
<tr>
<td><span id="inputPasswordBox">Password: </span></td>
<td class="inputBox"><input id="passwordBox" type="password" placeholder="Password"><br></td>
</tr>
</table>
<br>
<button id="signupButton">Signup</button>
<button id="loginButton" class="unimportant">Login</button>
<br><br>
<a href="/privacy">Privacy &amp; Terms</a>
</div>
<script src="/static/js/wasm_exec.js"></script>
<script>
loadWasm("/static/wasm/signup.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tester - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2>{{ .identifier }} Tester</h2>
<p id="statusBox">Click authorize to begin the test</p>
<button id="authorizeButton">Authorize</button>
</div>
<script>
loadWasm("/static/wasm/testApp.wasm")
</script>
</body>
</html>

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tester - {{ .identifier }}</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="icon" href="/static/svg/favicon.svg">
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
</head>
<body>
<img src="/static/img/background.png" class="background" alt="">
<div class="inOutDiv">
<h2>{{ .identifier }} Tester</h2>
<p>The tester has been disabled by the administrator.</p>
</div>
</body>
</html>

View File

@ -0,0 +1,217 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"syscall/js"
)
func authorize(deny bool, query url.Values) {
// Get the token from local storage
localStorage := js.Global().Get("localStorage")
token := localStorage.Call("getItem", "DONOTSHARE-secretKey").String()
// Fetch /api/authorize
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/authorize")
if err != nil {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error joining URL: "+err.Error())
return
}
authorizeBody := map[string]interface{}{
"token": token,
"deny": deny,
"appId": query.Get("client_id"),
"redirectUri": query.Get("redirect_uri"),
}
// Append the nonce if it exists
if query.Has("nonce") {
authorizeBody["nonce"] = query.Get("nonce")
}
// Append the PKCE code challenge if it exists
if query.Has("code_challenge") {
authorizeBody["PKCECode"] = query.Get("code_challenge")
authorizeBody["PKCEMethod"] = query.Get("code_challenge_method")
}
// Marshal the body
body, err := json.Marshal(authorizeBody)
if err != nil {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error marshaling authorize body: "+err.Error())
return
}
// Send the request
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
if deny {
// Redirect to the redirect_uri with an error
denyUri := query.Get("redirect_uri") + "?error=access_denied"
if query.Has("state") {
denyUri += "&state=" + query.Get("state")
}
js.Global().Get("window").Get("location").Call("replace", denyUri)
} else {
// Redirect to the redirect_uri with the code
allowUri := query.Get("redirect_uri") + "?code=" + responseMap["exchangeCode"].(string)
if query.Has("state") {
allowUri += "&state=" + query.Get("state")
}
js.Global().Get("window").Get("location").Call("replace", allowUri)
}
} else if response.StatusCode == 401 {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "OAuth screening failed! We could have just saved you from a bad actor!")
} else if response.StatusCode != 500 {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", responseMap["error"].(string))
} else {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}
func main() {
// Redirect to log-in if not signed in
localStorage := js.Global().Get("localStorage")
if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String())
}
var query url.Values
// Redirect to dashboard if client_id is not a URL parameter
if js.Global().Get("window").Get("location").Get("search").String() == "" {
js.Global().Get("window").Get("location").Call("replace", "/dashboard")
} else {
// Parse the url parameters using url.ParseQuery
var err error
query, err = url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?"))
if err != nil {
js.Global().Get("document").Call("getElementById", "statusBox").Set("innerText", "Error parsing URL query: "+err.Error())
return
}
// Redirect to dashboard if client_id is not a URL parameter
if !query.Has("client_id") {
js.Global().Get("window").Get("location").Call("replace", "/dashboard")
return
}
}
var statusBox = js.Global().Get("document").Call("getElementById", "statusBox")
var autoAccept = js.Global().Get("document").Call("getElementById", "autoAccept")
// Check if the token is valid
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
loggedInBody := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
body, err := json.Marshal(loggedInBody)
if err != nil {
statusBox.Set("innerText", "Error marshaling signup body: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Check if the response is 200
if response.StatusCode == 401 {
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Redirect to log-out if not signed in
js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String())
return
} else if response.StatusCode == 500 {
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Alert the user if the server is down
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if autoAccept.Get("innerText").String() == "0" {
// Change the status box to the authorization dialog
statusBox.Set("innerText", "Would you like to allow "+js.Global().Get("document").Call("getElementById", "passThrough").Get("innerText").String()+" to access your user information? You will be redirected to "+query.Get("redirect_uri")+" after you make your decision.")
// Add an event listener to the Deny button
js.Global().Get("document").Call("getElementById", "denyButton").Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} {
// We still partially authorize the user to prevent open redirects
go authorize(true, query)
return nil
}))
// Add an event listener to the Allow button
js.Global().Get("document").Call("getElementById", "allowButton").Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} {
go authorize(false, query)
return nil
}))
} else {
// Auto-accept the request, as it's from an internal service
go authorize(false, query)
}
// Wait for events
select {}
}

View File

@ -0,0 +1,184 @@
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"syscall/js"
)
func main() {
// Redirect to log-in if not signed in
localStorage := js.Global().Get("localStorage")
if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String())
}
statusBox := js.Global().Get("document").Call("getElementById", "statusBox")
// Check if the token is valid
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
loggedInBody := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
body, err := json.Marshal(loggedInBody)
if err != nil {
statusBox.Set("innerText", "Error marshaling signup body: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Check if the response is 200
if response.StatusCode == 401 {
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Redirect to log-out if not signed in
js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String())
return
} else if response.StatusCode == 500 {
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Alert the user if the server is down
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
query, err := url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?"))
if err != nil {
statusBox.Set("innerText", "Error parsing query: "+err.Error())
return
}
// Check if the access token we were given is valid and that the scope is correct
requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/clientKeyShare")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
request, err := http.NewRequest("GET", requestUri, nil)
if err != nil {
statusBox.Set("innerText", "Error creating request: "+err.Error())
return
}
request.Header.Set("Authorization", "Bearer "+query.Get("accessToken"))
response, err = http.DefaultClient.Do(request)
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
// Get the ECDH public key from the query string
clientKeyBytes, err := base64.URLEncoding.DecodeString(query.Get("ecdhPublicKey"))
if err != nil {
statusBox.Set("innerText", "Error decoding ECDH public key: "+err.Error())
return
}
// Encode the ECDH public key
key, err := ecdh.X25519().NewPublicKey(clientKeyBytes)
if err != nil {
statusBox.Set("innerText", "Error encoding ECDH public key: "+err.Error())
return
}
// Generate a new ECDH key pair
privateKey, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
statusBox.Set("innerText", "Error generating ECDH key pair: "+err.Error())
return
}
// Generate the shared secret
sharedSecret, err := privateKey.ECDH(key)
if err != nil {
statusBox.Set("innerText", "Error generating shared secret: "+err.Error())
return
}
// AES-GCM encrypt the DONOTSHARE-clientKey
block, err := aes.NewCipher(sharedSecret)
if err != nil {
statusBox.Set("innerText", "Error creating AES cipher: "+err.Error())
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
statusBox.Set("innerText", "Error creating GCM cipher: "+err.Error())
return
}
nonce := make([]byte, gcm.NonceSize())
_, err = rand.Read(nonce)
if err != nil {
statusBox.Set("innerText", "Error generating nonce: "+err.Error())
return
}
// Un-base64 the client key
decodedClientKey, err := base64.StdEncoding.DecodeString(localStorage.Call("getItem", "DONOTSHARE-clientKey").String())
if err != nil {
statusBox.Set("innerText", "Error decoding client key: "+err.Error())
return
}
encryptedClientKey := gcm.Seal(nil, nonce, decodedClientKey, nil)
// Redirect back to the referrer with the encrypted client key
redirectUri := strings.Split(js.Global().Get("document").Get("referrer").String(), "?")[0]
js.Global().Get("window").Get("location").Call("replace", redirectUri+"?ecdhPublicKey="+base64.URLEncoding.EncodeToString(privateKey.PublicKey().Bytes())+"&nonce="+base64.URLEncoding.EncodeToString(nonce)+"&cipherText="+base64.URLEncoding.EncodeToString(encryptedClientKey))
}
}

View File

@ -0,0 +1,683 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"syscall/js"
"time"
)
func fetchOauthClients(oauthList js.Value, localStorage js.Value, body []byte) {
// Fetch the OAuth clients
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/list")
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error joining URL: "+err.Error())
oauthList.Call("appendChild", statusText)
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error contacting server: "+err.Error())
oauthList.Call("appendChild", statusText)
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error decoding server response: "+err.Error())
oauthList.Call("appendChild", statusText)
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
for i := 0; i < oauthList.Get("childNodes").Length(); i++ {
this := oauthList.Get("childNodes").Index(i)
if this.Get("tagName").String() != "H2" {
this.Call("remove")
}
}
clients, ok := responseMap["apps"].([]interface{})
if !ok {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Hi there! You don't have any OAuth2 clients yet. Create one above!")
oauthList.Call("appendChild", statusText)
} else {
for _, app := range clients {
var oauthElement = js.Global().Get("document").Call("createElement", "div")
var oauthText = js.Global().Get("document").Call("createElement", "p")
var oauthName = js.Global().Get("document").Call("createElement", "p")
var oauthUrl = js.Global().Get("document").Call("createElement", "p")
var oauthRemoveButton = js.Global().Get("document").Call("createElement", "button")
oauthText.Set("innerText", app.(map[string]interface{})["appId"].(string))
oauthName.Set("innerText", app.(map[string]interface{})["name"].(string))
oauthUrl.Set("innerText", app.(map[string]interface{})["redirectUri"].(string))
oauthRemoveButton.Set("innerText", "Delete permanently")
oauthRemoveButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
if js.Global().Call("confirm", "Are you sure you want to delete this client? This action cannot be undone.").Bool() {
// Create the request body
requestBody := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
"appId": app.(map[string]interface{})["appId"].(string),
}
// Marshal the body
bodyBytes, err := json.Marshal(requestBody)
if err != nil {
js.Global().Call("alert", "Error marshaling body: "+err.Error())
return
}
// Send the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/remove")
if err != nil {
js.Global().Call("alert", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
js.Global().Call("alert", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
oauthElement.Call("remove")
if oauthList.Get("childNodes").Length() == 1 {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Hi there! You don't have any OAuth2 clients yet. Create one above!")
oauthList.Call("appendChild", statusText)
}
} else if response.StatusCode != 500 {
js.Global().Call("alert", responseMap["error"].(string))
} else {
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}
}()
return nil
}))
oauthElement.Call("append", oauthName)
oauthElement.Call("append", oauthText)
oauthElement.Call("append", oauthUrl)
openId := false
clientKeyShare := false
scopes, ok := app.(map[string]interface{})["scopes"].([]interface{})
if ok {
for _, scope := range scopes {
if scope.(string) == "openid" {
openId = true
} else if scope.(string) == "clientKeyShare" {
if app.(map[string]interface{})["keyShareUri"].(string) != "" {
clientKeyShare = true
keyShareUri := js.Global().Get("document").Call("createElement", "p")
keyShareUri.Set("innerText", "Key Share URI: "+app.(map[string]interface{})["keyShareUri"].(string))
oauthElement.Call("append", keyShareUri)
}
}
}
oauthScopes := js.Global().Get("document").Call("createElement", "p")
var scopeText strings.Builder
if openId {
scopeText.WriteString("OpenID")
}
if clientKeyShare {
if openId {
scopeText.WriteString(", ")
}
scopeText.WriteString("clientKeyShare")
}
oauthScopes.Set("innerText", "Scopes: "+scopeText.String())
oauthElement.Call("append", oauthScopes)
}
oauthElement.Call("append", oauthRemoveButton)
oauthElement.Get("classList").Call("add", "oauthEntry")
oauthList.Call("appendChild", oauthElement)
}
}
} else if response.StatusCode != 500 {
statusText := js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", responseMap["error"].(string))
oauthList.Call("appendChild", statusText)
} else {
statusText := js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
oauthList.Call("appendChild", statusText)
}
}
func main() {
// Redirect to log-in if not signed in
localStorage := js.Global().Get("localStorage")
if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String())
}
var submitButton = js.Global().Get("document").Call("getElementById", "submitButton")
var nameBox = js.Global().Get("document").Call("getElementById", "nameBox")
var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox")
var dateBox = js.Global().Get("document").Call("getElementById", "dateBox")
var clientKeyShareBox = js.Global().Get("document").Call("getElementById", "clientKeyShareBox")
var redirectUriBox = js.Global().Get("document").Call("getElementById", "redirectUriBox")
var openIdBox = js.Global().Get("document").Call("getElementById", "openIdBox")
var statusBox = js.Global().Get("document").Call("getElementById", "statusBox")
var oauthList = js.Global().Get("document").Call("getElementById", "oauthList")
var sessionList = js.Global().Get("document").Call("getElementById", "sessionList")
var deleteAccountButton = js.Global().Get("document").Call("getElementById", "deleteAccountButton")
var logoutButton = js.Global().Get("document").Call("getElementById", "logoutButton")
var devAccountSwitcher = js.Global().Get("document").Call("getElementById", "devAccountSwitcher")
var developers = js.Global().Get("document").Call("getElementById", "developers")
var account = js.Global().Get("document").Call("getElementById", "account")
// Fetch the OAuth clients and sessions
go func() {
// Check if the token is valid
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn")
if err != nil {
js.Global().Call("alert", "Error joining URL: "+err.Error())
return
}
loggedInBody := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
body, err := json.Marshal(loggedInBody)
if err != nil {
js.Global().Call("alert", "Error marshaling signup body: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
js.Global().Call("alert", "Error contacting server: "+err.Error())
return
}
// Check if the response is 200
if response.StatusCode == 401 {
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Redirect to log-out if not signed in
js.Global().Get("window").Get("location").Call("replace", "/logout")
return
} else if response.StatusCode == 500 {
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Alert the user if the server is down
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Fetch the OAuth clients
fetchOauthClients(oauthList, localStorage, body)
// Fetch the sessions
requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/list")
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error joining URL: "+err.Error())
sessionList.Call("appendChild", statusText)
return
}
response, err = http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error contacting server: "+err.Error())
sessionList.Call("appendChild", statusText)
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Error decoding server response: "+err.Error())
sessionList.Call("appendChild", statusText)
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
if len(responseMap["sessions"].([]interface{})) == 0 {
var statusText = js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Hi there! You don't have any sessions logged in, somehow. Congrats on breaking the laws of physics!")
sessionList.Call("appendChild", statusText)
} else {
for i := 0; i < sessionList.Get("childNodes").Length(); i++ {
this := sessionList.Get("childNodes").Index(i)
if this.Get("tagName").String() != "H2" {
this.Call("remove")
}
}
for _, session := range responseMap["sessions"].([]interface{}) {
var sessionElement = js.Global().Get("document").Call("createElement", "div")
var sessionDevice = js.Global().Get("document").Call("createElement", "p")
var sessionImage = js.Global().Get("document").Call("createElement", "img")
var sessionRemoveButton = js.Global().Get("document").Call("createElement", "button")
if session.(map[string]interface{})["session"].(string) == localStorage.Call("getItem", "DONOTSHARE-secretKey").String() {
sessionDevice.Set("innerText", "(current) "+session.(map[string]interface{})["device"].(string))
} else {
sessionDevice.Set("innerText", session.(map[string]interface{})["device"].(string))
}
if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "nt") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "macintosh") {
sessionImage.Set("src", "/static/svg/device_computer.svg")
} else if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "iphone") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "android") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "ipod") {
sessionImage.Set("src", "/static/svg/device_smartphone.svg")
} else if strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "curl") || strings.Contains(strings.ToLower(session.(map[string]interface{})["device"].(string)), "go-http-client") {
sessionImage.Set("src", "/static/svg/device_terminal.svg")
} else {
sessionImage.Set("src", "/static/svg/device_other.svg")
}
sessionRemoveButton.Set("innerText", "Force log out")
sessionRemoveButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
// Create the request body
body := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
"session": session.(map[string]interface{})["session"].(string),
}
// Marshal the body
bodyBytes, err := json.Marshal(body)
if err != nil {
js.Global().Call("alert", "Error marshaling body: "+err.Error())
return
}
// Send the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/remove")
if err != nil {
js.Global().Call("alert", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
js.Global().Call("alert", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
sessionElement.Call("remove")
if session.(map[string]interface{})["session"].(string) == localStorage.Call("getItem", "DONOTSHARE-secretKey").String() {
js.Global().Get("window").Get("location").Call("replace", "/logout")
}
} else if response.StatusCode != 500 {
js.Global().Call("alert", responseMap["error"].(string))
} else {
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}()
return nil
}))
sessionElement.Call("append", sessionImage)
sessionElement.Call("append", sessionDevice)
sessionElement.Call("append", sessionRemoveButton)
sessionElement.Get("classList").Call("add", "sessionEntry")
sessionList.Call("appendChild", sessionElement)
}
}
} else if response.StatusCode != 500 {
statusText := js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", responseMap["error"].(string))
sessionList.Call("appendChild", statusText)
} else {
statusText := js.Global().Get("document").Call("createElement", "p")
statusText.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
sessionList.Call("appendChild", statusText)
}
// Fetch user information
requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/userinfo")
if err != nil {
js.Global().Call("alert", "Error joining URL: "+err.Error())
return
}
// Re-use the body variable for this request
response, err = http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
js.Global().Call("alert", "Error contacting server: "+err.Error())
return
}
// Read the response
decoder = json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
js.Global().Call("alert", "Could not close response body: "+err.Error()+", memory leaks may occur")
}
if response.StatusCode == 200 {
usernameBox.Set("innerText", "Username: "+responseMap["username"].(string))
dateBox.Set("innerText", "Account created: "+time.Unix(int64(responseMap["created"].(float64)), 0).Format("2006-01-02 15:04:05"))
} else if response.StatusCode != 500 {
js.Global().Call("alert", responseMap["error"].(string))
} else {
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}()
submitButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
// Validate the input
if nameBox.Get("value").String() == "" {
statusBox.Set("innerText", "An App Name is required!")
return
} else if redirectUriBox.Get("value").String() == "" {
statusBox.Set("innerText", "A Redirect URI is required!")
return
}
// Check for scopes
var scopes []string
if openIdBox.Get("checked").Bool() {
scopes = append(scopes, "openid")
}
if clientKeyShareBox.Get("value").String() != "" {
scopes = append(scopes, "clientKeyShare")
}
// Create the request body
body := map[string]interface{}{
"name": nameBox.Get("value").String(),
"redirectUri": redirectUriBox.Get("value").String(),
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
"scopes": scopes,
"keyShareUri": redirectUriBox.Get("value").String(),
}
// Marshal the body
bodyBytes, err := json.Marshal(body)
if err != nil {
statusBox.Set("innerText", "Error marshaling body: "+err.Error())
return
}
// Send the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/add")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
statusBox.Set("innerText", "Your secret key is: "+responseMap["key"].(string)+" and your client ID is: "+responseMap["appId"].(string)+". This will only ever be shown once!")
// Update the OAuth clients
bodyMap := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
body, err := json.Marshal(bodyMap)
if err != nil {
fmt.Println("Error marshaling body: " + err.Error() + ", this is non-fatal.")
return
}
// Perform the request
fetchOauthClients(oauthList, localStorage, body)
} else if response.StatusCode != 500 {
statusBox.Set("innerText", responseMap["error"].(string))
} else {
statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}()
return nil
}))
deleteAccountButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
if js.Global().Call("confirm", "Are you sure you would like to delete your account forever? This cannot be undone.").Bool() {
// Create the request body
body := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
bodyBytes, err := json.Marshal(body)
if err != nil {
statusBox.Set("innerText", "Error marshaling body: "+err.Error())
return
}
// Send the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/deleteAccount")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
js.Global().Get("window").Get("location").Call("replace", "/logout")
} else if response.StatusCode != 500 {
js.Global().Call("alert", responseMap["error"].(string))
} else {
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}
}()
return nil
}))
devAccountSwitcher.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
developers.Get("classList").Call("toggle", "hidden")
account.Get("classList").Call("toggle", "hidden")
if devAccountSwitcher.Get("innerText").String() == "Switch to developer view" {
devAccountSwitcher.Set("innerText", "Switch to account view")
} else {
devAccountSwitcher.Set("innerText", "Switch to developer view")
}
return nil
}))
logoutButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
// Try to remove the session
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/session/remove")
if err != nil {
js.Global().Call("alert", "Error joining URL: "+err.Error())
return
}
// Create the request body
body := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
"session": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
bodyBytes, err := json.Marshal(body)
if err != nil {
js.Global().Call("alert", "Error marshaling body: "+err.Error())
return
}
// Send the request
response, err := http.Post(requestUri, "application/json", bytes.NewReader(bodyBytes))
if err != nil {
js.Global().Call("alert", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// We don't care about the response, we're logging out anyway
js.Global().Get("window").Get("location").Call("replace", "/logout")
}()
return nil
}))
// Wait for events
select {}
}

View File

@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"syscall/js"
"time"
"golang.org/x/crypto/argon2"
)
var currentInputType = 0
func hashPassword(password string, salt []byte) string {
return base64.StdEncoding.EncodeToString(
argon2.IDKey(
[]byte(password),
salt,
32,
19264,
1,
32,
),
)
}
func showInput(inputType int, inputContainer js.Value, usernameBox js.Value, signupButton js.Value, passwordBox js.Value, backButton js.Value, inputNameBox js.Value, statusBox js.Value, nextButton js.Value) {
if inputType == 0 {
// Show login
inputContainer.Get("classList").Call("remove", "hidden")
usernameBox.Get("classList").Call("remove", "hidden")
signupButton.Get("classList").Call("remove", "hidden")
passwordBox.Get("classList").Call("add", "hidden")
backButton.Get("classList").Call("add", "hidden")
inputNameBox.Set("innerText", "Username:")
// Get the current service name
serviceName := js.Global().Get("document").Call("getElementById", "passThrough").Get("innerText").String()
// Set the service name
statusBox.Set("innerText", "Login to your "+serviceName+" account!")
// Set the current input type
currentInputType = 0
} else if inputType == 1 {
inputContainer.Get("classList").Call("remove", "hidden")
signupButton.Get("classList").Call("add", "hidden")
usernameBox.Get("classList").Call("add", "hidden")
passwordBox.Get("classList").Call("remove", "hidden")
backButton.Get("classList").Call("remove", "hidden")
inputNameBox.Get("classList").Call("remove", "hidden")
nextButton.Get("classList").Call("remove", "hidden")
inputNameBox.Get("classList").Call("remove", "hidden")
inputNameBox.Set("innerText", "Password:")
currentInputType = 1
} else if inputType == 2 {
signupButton.Get("classList").Call("add", "hidden")
nextButton.Get("classList").Call("add", "hidden")
backButton.Get("classList").Call("add", "hidden")
inputContainer.Get("classList").Call("add", "hidden")
inputNameBox.Get("classList").Call("add", "hidden")
passwordBox.Get("classList").Call("add", "hidden")
usernameBox.Get("classList").Call("add", "hidden")
currentInputType = 2
}
}
func main() {
// Redirect to app if already signed in
localStorage := js.Global().Get("localStorage")
if !localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String())
}
var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox")
var passwordBox = js.Global().Get("document").Call("getElementById", "passwordBox")
var statusBox = js.Global().Get("document").Call("getElementById", "statusBox")
var nextButton = js.Global().Get("document").Call("getElementById", "nextButton")
var backButton = js.Global().Get("document").Call("getElementById", "backButton")
var signupButton = js.Global().Get("document").Call("getElementById", "signupButton")
var inputNameBox = js.Global().Get("document").Call("getElementById", "inputNameBox")
var inputContainer = js.Global().Get("document").Call("getElementById", "inputContainer")
// Show the login screen
showInput(0, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
nextButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
if currentInputType == 0 {
if usernameBox.Get("value").IsNull() {
statusBox.Set("innerText", "A username is required!")
return
} else {
statusBox.Set("innerText", "Welcome back, "+usernameBox.Get("value").String()+"!")
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
}
} else if currentInputType == 1 {
password := passwordBox.Get("value").String()
username := usernameBox.Get("value").String()
if passwordBox.Get("value").IsNull() {
statusBox.Set("innerText", "A password is required!")
return
}
showInput(2, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
// Hash the password
statusBox.Set("innerText", "Hashing password...")
fmt.Println("Hashing password...")
// Fetch the salt from the server
body, err := json.Marshal(map[string]interface{}{
"username": username,
})
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error marshaling salt body: "+err.Error())
return
}
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loginChallenge")
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Decode the salt
salt, err := base64.StdEncoding.DecodeString(responseMap["salt"].(string))
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error decoding salt: "+err.Error())
return
}
hashedPassword := hashPassword(password, salt)
// Hashed password computed, contact server
statusBox.Set("innerText", "Contacting server...")
signupBody := map[string]interface{}{
"username": username,
"password": hashedPassword,
}
// Marshal the body
body, err = json.Marshal(signupBody)
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error marshaling signup body: "+err.Error())
return
}
// Send the password to the server
requestUri, err = url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/login")
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
// Send the request
fmt.Println("Sending request to", requestUri)
response, err = http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Read the response
fmt.Println("Reading response...")
decoder = json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
// Logged in
fmt.Println("Logged in!")
statusBox.Set("innerText", "Setting up encryption keys...")
localStorage.Call("setItem", "DONOTSHARE-secretKey", responseMap["key"].(string))
localStorage.Call("setItem", "DONOTSHARE-clientKey", hashPassword(password, []byte("fg-auth-client")))
// Redirect to app
statusBox.Set("innerText", "Welcome!")
time.Sleep(time.Second)
js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String())
} else if response.StatusCode == 401 {
// Login failed
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Username or password incorrect!")
} else {
// Unknown error
showInput(1, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}
}()
return nil
}))
backButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
showInput(0, inputContainer, usernameBox, signupButton, passwordBox, backButton, inputNameBox, statusBox, nextButton)
return
}()
return nil
}))
signupButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
js.Global().Get("window").Get("location").Call("replace", "/signup"+js.Global().Get("window").Get("location").Get("search").String())
return nil
}))
// Wait for events
select {}
}

View File

@ -0,0 +1,195 @@
package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"time"
"encoding/json"
"net/http"
"net/url"
"git.ailur.dev/ailur/pow-argon2/library"
"golang.org/x/crypto/argon2"
"syscall/js"
)
func showElements(show bool, elements ...js.Value) {
for _, element := range elements {
if show {
element.Get("classList").Call("remove", "hidden")
} else {
element.Get("classList").Call("add", "hidden")
}
}
}
func hashPassword(password string, salt []byte) string {
return base64.StdEncoding.EncodeToString(
argon2.IDKey(
[]byte(password),
salt,
32,
19264,
1,
32,
),
)
}
func main() {
// Redirect to app if already signed in
localStorage := js.Global().Get("localStorage")
if !localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String())
}
var usernameBox = js.Global().Get("document").Call("getElementById", "usernameBox")
var passwordBox = js.Global().Get("document").Call("getElementById", "passwordBox")
var statusBox = js.Global().Get("document").Call("getElementById", "statusBox")
var signupButton = js.Global().Get("document").Call("getElementById", "signupButton")
var loginButton = js.Global().Get("document").Call("getElementById", "loginButton")
var inputContainer = js.Global().Get("document").Call("getElementById", "inputContainer")
signupButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go func() {
var username = usernameBox.Get("value").String()
var password = passwordBox.Get("value").String()
if username == "" {
statusBox.Set("innerText", "A username is required!")
return
} else if len(username) > 20 {
statusBox.Set("innerText", "Username cannot be more than 20 characters!")
return
} else if password == "" {
statusBox.Set("innerText", "A password is required!")
return
} else if len(password) < 8 {
statusBox.Set("innerText", "Password must be at least 8 characters!")
return
}
// Start the signup process
fmt.Println("Starting signup process for user: " + username)
showElements(false, inputContainer, signupButton, loginButton)
// Wait about 10ms to allow the UI to update
var pow string
if localStorage.Call("getItem", "DEBUG-customPoW").IsNull() {
var err error
statusBox.Set("innerText", "Computing PoW Challenge...\nThe UI may be unresponsive during this time, as we are performing a lot of work! Please wait a few minutes for the process to complete.")
time.Sleep(time.Millisecond * 10)
pow, err = library.PoW(3, "fg-auth-signup")
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error computing PoW challenge: "+err.Error())
return
}
} else {
pow = localStorage.Call("getItem", "DEBUG-customPoW").String()
}
// PoW challenge computed, hash password
statusBox.Set("innerText", "Hashing password...")
// Generate a random salt
salt := make([]byte, 32)
_, err := rand.Read(salt)
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error generating salt: "+err.Error())
return
}
// Hash the password
hashedPassword := hashPassword(password, salt)
// Hashed password computed, contact server
statusBox.Set("innerText", "Contacting server...")
signupBody := map[string]interface{}{
"username": username,
"password": hashedPassword,
"salt": base64.StdEncoding.EncodeToString(salt),
"proofOfWork": pow,
}
// Marshal the body
body, err := json.Marshal(signupBody)
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error marshaling signup body: "+err.Error())
return
}
// Send the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/signup")
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Get all our ducks in a row
var responseMap map[string]interface{}
// Read the response
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
// Signup successful
statusBox.Set("innerText", "Setting up encryption keys...")
localStorage.Call("setItem", "DONOTSHARE-secretKey", responseMap["key"].(string))
localStorage.Call("setItem", "DONOTSHARE-clientKey", hashPassword(password, []byte("fg-auth-client")))
// Redirect to app
statusBox.Set("innerText", "Welcome!")
time.Sleep(time.Second)
js.Global().Get("window").Get("location").Call("replace", "/authorize"+js.Global().Get("window").Get("location").Get("search").String())
} else if response.StatusCode == 409 {
// Username taken
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Username or password taken!")
} else if response.StatusCode != 500 {
// Other error
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", responseMap["error"].(string))
} else {
// Other error
showElements(true, inputContainer, signupButton, loginButton)
statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
}()
return nil
}))
loginButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String())
return nil
}))
// Wait for events
select {}
}

View File

@ -0,0 +1,327 @@
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/cespare/xxhash/v2"
"net/http"
"net/url"
"strconv"
"strings"
"syscall/js"
)
func sha256Base64(s string) string {
hashed := sha256.Sum256([]byte(s))
encoded := base64.URLEncoding.EncodeToString(hashed[:])
encoded = strings.TrimRight(encoded, "=")
return encoded
}
func randomChars(length int) (string, error) {
var saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
if length <= 0 {
return "", errors.New("salt length must be greater than 0")
}
salt := make([]byte, length)
randomBytes := make([]byte, length)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
for i := range salt {
salt[i] = saltChars[int(randomBytes[i])%len(saltChars)]
}
return string(salt), nil
}
func main() {
// Redirect to log-in if not signed in
localStorage := js.Global().Get("localStorage")
if localStorage.Call("getItem", "DONOTSHARE-secretKey").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/login"+js.Global().Get("window").Get("location").Get("search").String())
}
statusBox := js.Global().Get("document").Call("getElementById", "statusBox")
authorizeButton := js.Global().Get("document").Call("getElementById", "authorizeButton")
// Check if the token is valid
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/loggedIn")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
loggedInBody := map[string]interface{}{
"token": localStorage.Call("getItem", "DONOTSHARE-secretKey").String(),
}
// Marshal the body
body, err := json.Marshal(loggedInBody)
if err != nil {
statusBox.Set("innerText", "Error marshaling signup body: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/json", bytes.NewReader(body))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Check if the response is 200
if response.StatusCode == 401 {
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Redirect to log-out if not signed in
js.Global().Get("window").Get("location").Call("replace", "/logout"+js.Global().Get("window").Get("location").Get("search").String())
return
} else if response.StatusCode == 500 {
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
js.Global().Call("alert", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Alert the user if the server is down
js.Global().Call("alert", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Check if the URL has a code
urlParams, err := url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?"))
if err != nil {
statusBox.Set("innerText", "Error parsing URL: "+err.Error())
return
}
if urlParams.Has("code") {
// Set the status box
statusBox.Set("innerText", "Authenticating...")
// Create the form data
var formData = url.Values{}
formData.Set("grant_type", "authorization_code")
formData.Set("code", urlParams.Get("code"))
formData.Set("client_id", "TestApp-DoNotUse")
formData.Set("redirect_uri", js.Global().Get("window").Get("location").Get("origin").String()+"/testApp")
formData.Set("code_verifier", localStorage.Call("getItem", "TESTER-verifier").String())
// Create the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/token")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
response, err := http.Post(requestUri, "application/x-www-form-urlencoded", strings.NewReader(formData.Encode()))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
// Fetch userinfo
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/userinfo")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
return
}
// Create the request
request, err := http.NewRequest("GET", requestUri, nil)
if err != nil {
statusBox.Set("innerText", "Error creating request: "+err.Error())
return
}
// Set the authorization header
request.Header.Set("Authorization", "Bearer "+responseMap["id_token"].(string))
// Send the request
response, err := http.DefaultClient.Do(request)
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
return
}
// Read the response
decoder = json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Set the username
localStorage.Call("setItem", "TESTER-username", responseMap["username"].(string))
// Generate the keypair
privateKey, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
statusBox.Set("innerText", "Error generating private key: "+err.Error())
return
}
// Save the private key
localStorage.Call("setItem", "TESTER-privateKey", base64.StdEncoding.EncodeToString(privateKey.Bytes()))
// Redirect to the client key exchange endpoint
js.Global().Get("window").Get("location").Call("replace", "/clientKeyShare?ecdhPublicKey="+base64.URLEncoding.EncodeToString(privateKey.PublicKey().Bytes())+"&accessToken="+responseMap["access_token"].(string))
return
} else if response.StatusCode != 500 {
statusBox.Set("innerText", responseMap["error"].(string))
} else {
statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
}
} else if urlParams.Has("error") {
if urlParams.Get("error") == "access_denied" {
statusBox.Set("innerText", "Access denied")
} else {
statusBox.Set("innerText", "Authentication failed (error code: "+urlParams.Get("error")+")")
}
} else if urlParams.Has("ecdhPublicKey") {
publicKeyByte, err := base64.URLEncoding.DecodeString(urlParams.Get("ecdhPublicKey"))
if err != nil {
statusBox.Set("innerText", "Error decoding public key: "+err.Error())
return
}
publicKey, err := ecdh.X25519().NewPublicKey(publicKeyByte)
if err != nil {
statusBox.Set("innerText", "Error encoding public key: "+err.Error())
return
}
privateKeyBytes, err := base64.StdEncoding.DecodeString(localStorage.Call("getItem", "TESTER-privateKey").String())
if err != nil {
statusBox.Set("innerText", "Error decoding private key: "+err.Error())
return
}
privateKey, err := ecdh.X25519().NewPrivateKey(privateKeyBytes)
if err != nil {
statusBox.Set("innerText", "Error encoding private key: "+err.Error())
return
}
nonce, err := base64.URLEncoding.DecodeString(urlParams.Get("nonce"))
if err != nil {
statusBox.Set("innerText", "Error decoding nonce: "+err.Error())
return
}
ciphertext, err := base64.URLEncoding.DecodeString(urlParams.Get("cipherText"))
if err != nil {
statusBox.Set("innerText", "Error decoding ciphertext: "+err.Error())
return
}
// Generate the shared secret
sharedSecret, err := privateKey.ECDH(publicKey)
if err != nil {
statusBox.Set("innerText", "Error generating shared secret: "+err.Error())
return
}
// Decrypt the ciphertext
block, err := aes.NewCipher(sharedSecret)
if err != nil {
statusBox.Set("innerText", "Error creating AES cipher: "+err.Error())
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
statusBox.Set("innerText", "Error creating GCM cipher: "+err.Error())
return
}
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
statusBox.Set("innerText", "Error decrypting ciphertext: "+err.Error())
return
}
statusBox.Set("innerText", "Authentication complete! Authenticated as "+localStorage.Call("getItem", "TESTER-username").String()+" with client key "+strconv.FormatUint(xxhash.Sum64(plaintext), 10))
// Remove all our temporary data
localStorage.Call("removeItem", "TESTER-verifier")
localStorage.Call("removeItem", "TESTER-username")
localStorage.Call("removeItem", "TESTER-privateKey")
}
// Add event listener for authorize button
authorizeButton.Call("addEventListener", "click", js.FuncOf(func(this js.Value, p []js.Value) interface{} {
go func() {
verifier, err := randomChars(128)
if err != nil {
statusBox.Set("innerText", "Error generating verifier: "+err.Error())
return
}
// Generate the challenge
verifierChallenge := sha256Base64(verifier)
// Save the verifier
localStorage.Call("setItem", "TESTER-verifier", verifier)
// Redirect to the authorization page
js.Global().Get("window").Get("location").Call("replace", "/authorize?response_type=code&client_id=TestApp-DoNotUse&redirect_uri="+url.QueryEscape(js.Global().Get("window").Get("location").Get("origin").String()+"/testApp")+"&code_challenge="+verifierChallenge+"&code_challenge_method=S256")
}()
return nil
}))
// Wait for events
select {}
}

View File

@ -0,0 +1,157 @@
# GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
## 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
## 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
## 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
## 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
## 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
## 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
## 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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 Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

5
services-src/storage/build.sh Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
path=$(realpath "$(dirname "$0")") || exit 1
rm -rf "$path/../../services/storage.fgs" || exit 1
go build -o "$path/../../services/storage.fgs" --buildmode=plugin -ldflags "-s -w" || exit 1

View File

@ -0,0 +1,376 @@
package main
import (
"database/sql"
"git.ailur.dev/ailur/fulgens/library"
"path/filepath"
"io"
"os"
"time"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
)
type InsertFile struct {
File File `validate:"required"`
Stream io.Reader `validate:"required"`
}
type ReadFile struct {
File File `validate:"required"`
Stream io.Writer `validate:"required"`
}
type File struct {
Name string `validate:"required"`
Size int64 `validate:"required"`
User uuid.UUID `validate:"required"`
}
var ServiceInformation = library.Service{
Name: "Storage",
Permissions: library.Permissions{
Authenticate: false, // This service does not require authentication
Database: true, // This service requires database access to store quotas
BlobStorage: false, // This service *is* the blob storage
InterServiceCommunication: true, // This service does require inter-service communication
},
ServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000003"),
}
var conn *sql.DB
func getQuota(user uuid.UUID, information library.ServiceInitializationInformation) (int64, error) {
// Get the user's quota from the database
var quota int64
err := conn.QueryRow("SELECT quota FROM quotas WHERE id = $1", user).Scan(&quota)
if err != nil {
return 0, err
}
return quota, nil
}
func getUsed(user uuid.UUID, information library.ServiceInitializationInformation) (int64, error) {
// Check the user's used space via the filesystem
var used int64
err := filepath.Walk(filepath.Join(information.Configuration["path"].(string), user.String()), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
used += info.Size()
return nil
})
if err != nil {
return 0, err
}
return used, nil
}
func logFunc(message string, messageType uint64, information library.ServiceInitializationInformation) {
// Log the error message to the logger service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000002"), // Logger service
MessageType: messageType,
SentAt: time.Now(),
Message: message,
}
}
func storeFile(file InsertFile, serviceID uuid.UUID, information library.ServiceInitializationInformation) {
// Create a folder for the user if it doesn't exist
err := os.MkdirAll(filepath.Join(information.Configuration["path"].(string), file.File.User.String()), 0755)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Check if the user has enough space to store the file
quota, err := getQuota(file.File.User, information)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
used, err := getUsed(file.File.User, information)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Check if the user has enough space to store the file
if used+file.File.Size > quota {
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 3, // It's the user's fault (never say that to the customer ;P)
SentAt: time.Now(),
Message: "User has exceeded their quota",
}
}
// Create a folder within that for the service if it doesn't exist
err = os.MkdirAll(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String()), 0755)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Store the file
fileStream, err := os.OpenFile(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String(), file.File.Name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Write the file
_, err = io.Copy(fileStream, file.Stream)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Close the file
err = fileStream.Close()
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Report success
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 0, // Success
SentAt: time.Now(),
Message: nil,
}
}
func readFile(file ReadFile, serviceID uuid.UUID, information library.ServiceInitializationInformation) {
// Open the file
fileStream, err := os.Open(filepath.Join(information.Configuration["path"].(string), file.File.User.String(), serviceID.String(), file.File.Name))
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Read the file
_, err = io.Copy(file.Stream, fileStream)
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Close the file
err = fileStream.Close()
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Report success
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 0, // Success
SentAt: time.Now(),
Message: nil,
}
}
func removeFile(file File, serviceID uuid.UUID, information library.ServiceInitializationInformation) {
// Remove the file
err := os.Remove(filepath.Join(information.Configuration["path"].(string), file.User.String(), serviceID.String(), file.Name))
if err != nil {
// First contact the logger service
logFunc(err.Error(), 2, information)
// Then send the error message to the requesting service
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 1, // An error that's not your fault
SentAt: time.Now(),
Message: err.Error(),
}
}
// Report success
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: serviceID,
MessageType: 0, // Success
SentAt: time.Now(),
Message: nil,
}
}
func Main(information library.ServiceInitializationInformation) {
go func() {
for {
message := <-information.Inbox
if message.ServiceID == uuid.MustParse("00000000-0000-0000-0000-000000000001") {
if message.MessageType == 1 {
// We've received an error message. This should never happen.
logFunc("Bit flip error: Error given to non-errored service. Move away from radiation or use ECC memory.", 3, information)
}
} else {
switch message.MessageType {
case 0:
// Insert file
validate := validator.New()
err := validate.Struct(message.Message.(InsertFile))
if err != nil {
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: message.ServiceID,
MessageType: 2, // An error that's your fault
SentAt: time.Now(),
Message: err.Error(),
}
} else {
// Store file
storeFile(message.Message.(InsertFile), message.ServiceID, information)
}
case 1:
// Read file
validate := validator.New()
err := validate.Struct(message.Message.(ReadFile))
if err != nil {
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: message.ServiceID,
MessageType: 2, // An error that's your fault
SentAt: time.Now(),
Message: err.Error(),
}
} else {
// Read file
readFile(message.Message.(ReadFile), message.ServiceID, information)
}
case 2:
// Remove file
validate := validator.New()
err := validate.Struct(message.Message.(File))
if err != nil {
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: message.ServiceID,
MessageType: 2, // An error that's your fault
SentAt: time.Now(),
Message: err.Error(),
}
} else {
// Remove file
removeFile(message.Message.(File), message.ServiceID, information)
}
}
}
}
}()
// Report a successful activation
information.Outbox <- library.InterServiceMessage{
ServiceID: information.ServiceID,
ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), // Activation service
MessageType: 0,
SentAt: time.Now(),
Message: true,
}
}