Initial commit

This commit is contained in:
Jonas L 2019-02-25 00:00:00 +00:00
commit 22c372e246
200 changed files with 27781 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
build
node_modules
test.db

20
.gitlab-ci.yml Normal file
View file

@ -0,0 +1,20 @@
image: docker:stable
services:
- docker:dind
variables:
CONTAINER_IMAGE: registry.gitlab.com/$CI_PROJECT_PATH
DOCKER_HOST: tcp://docker:2375
DOCKER_DRIVER: overlay2
before_script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
build:
stage: build
script:
- docker pull $CONTAINER_IMAGE:$CI_COMMIT_REF_NAME || true
- docker build --cache-from $CONTAINER_IMAGE:latest --tag $CONTAINER_IMAGE:$CI_COMMIT_REF_NAME .
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
- docker push $CONTAINER_IMAGE:$CI_COMMIT_REF_NAME

13
Dockerfile Normal file
View file

@ -0,0 +1,13 @@
FROM node:11-alpine
# Create app directories
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY . /usr/src/app/
RUN npm install --no-optional && npm run build && npm prune --production && rm -rf ./src
# Start the App
EXPOSE 8080
CMD [ "npm", "start" ]

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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
<http://www.gnu.org/licenses/>.

62
Readme.md Normal file
View file

@ -0,0 +1,62 @@
# TimeLimit-Server
This is the server for the connected mode in TimeLimit.
## Clustering
This application only supports running a single instance of it.
When clustering, push messages do not work anymore between devices
connected to different devices and the rate limiting is per instance.
## Running
Option 1: Use a prebuilt docker image
Option 2: Install Node.JS (see below for detailed usage)
## Commands
### npm start
This runs all pending migrations and starts the server.
### npm run build
This "compiles" the application.
### npm run lint:fix
This fixes the causes of lint warnings (where possible).
## Configuration (environment variables)
- DATABASE_URL
- this specifies the database to use
- default value: ``sqlite://test.db`` (sqlite database in the source code directory)
- supports mysql, postgresql and sqlite (sqlite in development builds only because it's declared as dev dependency)
- looks like ``postgres://user:pass@example.com:5432/dbname``
- no extra setup needed
- when starting the application, the database tables are created/ migrated
- this only works for upgrading; if you intend to eventually downgrade, make a backup first (you should make backups in all cases before an upgrade)
- PORT
- the port at which the server should listen
- NODE_ENV
- should be set to ``production`` in production
- when using ``development``, then mails are not sent; instead they are written to a html file which is opened
- GOOGLE_PLAY_PUBLIC_KEY
- key for validating purchases
- purchases using google play don't work without it
- GOOGLE_SIGN_IN_CLIENT_ID
- token for validating sign in with google requests
- sign in with Google does not work without it
- MAIL_SENDER
- sender (for the from-field) for sent mails
- MAIL_TRANSPORT
- a JSON encoded configuration for nodemailer (object with service and auth)
- see <https://nodemailer.com/smtp/well-known/> for examples
- default value is ``null``
- MAIL_IMPRINT
- a string which is added to the footer of the sent mails
- default value: ``not defined``
- STATUS_MESSAGE
- a message which is shown to all users in the overview screen
- default: null/ no shown message

310
other/mail/login/html.ejs Normal file
View file

@ -0,0 +1,310 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title> </title>
<!--[if !mso]><!-- -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#outlook a {
padding: 0;
}
.ReadMsgBody {
width: 100%;
}
.ExternalClass {
width: 100%;
}
.ExternalClass * {
line-height: 100%;
}
body {
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
</style>
<!--[if !mso]><!-->
<style type="text/css">
@media only screen and (max-width:480px) {
@-ms-viewport {
width: 320px;
}
@viewport {
width: 320px;
}
}
</style>
<!--<![endif]-->
<!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
}
</style>
<style type="text/css">
</style>
</head>
<body>
<div style="">
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="background:#009688;background-color:#009688;Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#009688;background-color:#009688;width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:left;color:#ffffff;"> TimeLimit </div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p>
<%= introtext %>
</p>
<p><b><%= code %></b></p>
<p>
<%= outrotext %>
</p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td style="font-size:0px;padding:10px 25px;word-break:break-word;">
<p style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:100%;"> </p>
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px"
>
<tr>
<td style="height:0;line-height:0;">
&nbsp;
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p> You got this mail because your mail address was entered at the TimeLimit App for signing in. If you did not request this mail, then you can ignore it. If you have got any questions, then you can reply to this messagge. </p>
<p>
Sie erhalten diese Nachricht, da Ihre E-Mail-Adresse in der TimeLimit-App zum Anmelden eingegeben wurde. Wenn Sie diese E-Mail nicht angefordert haben, können Sie diese ignorieren. Falls Sie Fragen haben können Sie einfach auf
diese E-Mail antworten. </p>
<p> &copy;
<%= mailimprint %>
</p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</div>
</body>
</html>

View file

@ -0,0 +1,40 @@
<mjml>
<mj-body>
<mj-section background-color="#009688">
<mj-column>
<mj-text font-size="20px" color="#ffffff">TimeLimit</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
<%= introtext %>
</p>
<p><b><%= code %></b></p>
<p><%= outrotext %></p>
</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-divider border-width="1px" border-style="dashed" border-color="lightgrey" />
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
You got this mail because your mail address was entered at the TimeLimit App for signing in. If you did not request this mail, then you can ignore it. If you have got any questions, then you can reply to this messagge.
</p>
<p>
Sie erhalten diese Nachricht, da Ihre E-Mail-Adresse in der TimeLimit-App zum Anmelden eingegeben wurde. Wenn Sie diese E-Mail nicht angefordert haben, können Sie diese ignorieren. Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
</p>
<p>
&copy; <%= mailimprint %>
</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>

View file

@ -0,0 +1 @@
<%= subject %>

17
other/mail/login/text.ejs Normal file
View file

@ -0,0 +1,17 @@
<%= introtext %>
<%= code %>
<%= outrotext %>
----------------------
You got this mail because your mail address was entered at the TimeLimit App for signing in.
If you did not request this mail, then you can ignore it.
If you have got any questions, then you can reply to this messagge.
Sie erhalten diese Nachricht, da Ihre E-Mail-Adresse in der TimeLimit-App zum Anmelden eingegeben wurde.
Wenn Sie diese E-Mail nicht angefordert haben, können Sie diese ignorieren.
Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
<C> <%= mailimprint %>

View file

@ -0,0 +1,308 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title> </title>
<!--[if !mso]><!-- -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#outlook a {
padding: 0;
}
.ReadMsgBody {
width: 100%;
}
.ExternalClass {
width: 100%;
}
.ExternalClass * {
line-height: 100%;
}
body {
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
</style>
<!--[if !mso]><!-->
<style type="text/css">
@media only screen and (max-width:480px) {
@-ms-viewport {
width: 320px;
}
@viewport {
width: 320px;
}
}
</style>
<!--<![endif]-->
<!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
}
</style>
<style type="text/css">
</style>
</head>
<body>
<div style="">
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="background:#009688;background-color:#009688;Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#009688;background-color:#009688;width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:left;color:#ffffff;"> TimeLimit </div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p> Die TimeLimit-Installation von dem Gerät
<%= deviceName %> hat eine Manipulation gemeldet. Sie können die Details dazu in der TimeLimit-App einsehen. <br /> Solange Sie nicht die Warnung in TimeLimit bestätigen (ignorieren und/ oder beheben) erhalten Sie keine weitere Manipulationsbenachrichtigungen
für dieses Gerät. </p>
<p> TimeLimit at
<%= deviceName %> reported a manipulation. You can see the details in the TimeLimit App. <br /> You will not get any further warnings for this device until you confirm (ignore and/ or fix) the manipulation in the TimeLimit App. </p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td style="font-size:0px;padding:10px 25px;word-break:break-word;">
<p style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:100%;"> </p>
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px"
>
<tr>
<td style="height:0;line-height:0;">
&nbsp;
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p> Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben. Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen
nicht mehr erhalten möchten. Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten. </p>
<p> You got this mail because you enable mail notifications for this in TimeLimit. You can disable getting these messages in the TimeLimit App or by replying to this message that you don't want to get these notifications anymore. If
you have got any questions, then you can reply to this messagge. </p>
<p> &copy;
<%= mailimprint %>
</p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</div>
</body>
</html>

View file

@ -0,0 +1,56 @@
<mjml>
<mj-body>
<mj-section background-color="#009688">
<mj-column>
<mj-text font-size="20px" color="#ffffff">TimeLimit</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
Die TimeLimit-Installation von dem Gerät <%= deviceName %> hat eine Manipulation gemeldet.
Sie können die Details dazu in der TimeLimit-App einsehen.
<br />
Solange Sie nicht die Warnung in TimeLimit bestätigen (ignorieren und/ oder beheben)
erhalten Sie keine weitere Manipulationsbenachrichtigungen für dieses Gerät.
</p>
<p>
TimeLimit at <%= deviceName %> reported a manipulation.
You can see the details in the TimeLimit App.
<br />
You will not get any further warnings for this device
until you confirm (ignore and/ or fix) the manipulation in the TimeLimit App.
</p>
</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-divider border-width="1px" border-style="dashed" border-color="lightgrey" />
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben.
Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem
Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen nicht mehr erhalten möchten.
Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
</p>
<p>
You got this mail because you enable mail notifications for this in TimeLimit.
You can disable getting these messages in the TimeLimit App or by
replying to this message that you don't want to get these notifications anymore.
If you have got any questions, then you can reply to this messagge.
</p>
<p>
&copy; <%= mailimprint %>
</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>

View file

@ -0,0 +1 @@
<%= subject %>

View file

@ -0,0 +1,26 @@
Die TimeLimit-Installation von dem Gerät <%= deviceName %> hat eine Manipulation gemeldet.
Sie können die Details dazu in der TimeLimit-App einsehen.
Solange Sie nicht die Warnung in TimeLimit bestätigen (ignorieren und/ oder beheben)
erhalten Sie keine weitere Manipulationsbenachrichtigungen für dieses Gerät.
TimeLimit at <%= deviceName %> reported a manipulation.
You can see the details in the TimeLimit App.
You will not get any further warnings for this device
until you confirm (ignore and/ or fix) the manipulation in the TimeLimit App.
----------------------
Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben.
Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem
Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen nicht mehr erhalten möchten.
Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
You got this mail because you enable mail notifications for this in TimeLimit.
You can disable getting these messages in the TimeLimit App or by
replying to this message that you don't want to get these notifications anymore.
If you have got any questions, then you can reply to this messagge.
<C> <%= mailimprint %>

View file

@ -0,0 +1,307 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title> </title>
<!--[if !mso]><!-- -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#outlook a {
padding: 0;
}
.ReadMsgBody {
width: 100%;
}
.ExternalClass {
width: 100%;
}
.ExternalClass * {
line-height: 100%;
}
body {
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
</style>
<!--[if !mso]><!-->
<style type="text/css">
@media only screen and (max-width:480px) {
@-ms-viewport {
width: 320px;
}
@viewport {
width: 320px;
}
}
</style>
<!--<![endif]-->
<!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
}
</style>
<style type="text/css">
</style>
</head>
<body>
<div style="">
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="background:#009688;background-color:#009688;Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#009688;background-color:#009688;width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:left;color:#ffffff;"> TimeLimit </div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p> TimeLimit wurde von dem Gerät
<%= deviceName %> entfernt. </p>
<p> TimeLimit was removed from
<%= deviceName %>. </p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td style="font-size:0px;padding:10px 25px;word-break:break-word;">
<p style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:100%;"> </p>
<!--[if mso | IE]>
<table
align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:dashed 1px lightgrey;font-size:1;margin:0px auto;width:550px;" role="presentation" width="550px"
>
<tr>
<td style="height:0;line-height:0;">
&nbsp;
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<table
align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"
>
<tr>
<td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">
<![endif]-->
<div style="Margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;vertical-align:top;">
<!--[if mso | IE]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td
class="" style="vertical-align:top;width:600px;"
>
<![endif]-->
<div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tr>
<td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;">
<div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">
<p> Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben. Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen
nicht mehr erhalten möchten. Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten. </p>
<p> You got this mail because you enable mail notifications for this in TimeLimit. You can disable getting these messages in the TimeLimit App or by replying to this message that you don't want to get these notifications anymore. If
you have got any questions, then you can reply to this messagge. </p>
<p> &copy;
<%= mailimprint %>
</p>
</div>
</td>
</tr>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]>
</td>
</tr>
</table>
<![endif]-->
</div>
</body>
</html>

View file

@ -0,0 +1,48 @@
<mjml>
<mj-body>
<mj-section background-color="#009688">
<mj-column>
<mj-text font-size="20px" color="#ffffff">TimeLimit</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
TimeLimit wurde von dem Gerät <%= deviceName %> entfernt.
</p>
<p>
TimeLimit was removed from <%= deviceName %>.
</p>
</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-divider border-width="1px" border-style="dashed" border-color="lightgrey" />
</mj-column>
</mj-section>
<mj-section>
<mj-column>
<mj-text>
<p>
Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben.
Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem
Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen nicht mehr erhalten möchten.
Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
</p>
<p>
You got this mail because you enable mail notifications for this in TimeLimit.
You can disable getting these messages in the TimeLimit App or by
replying to this message that you don't want to get these notifications anymore.
If you have got any questions, then you can reply to this messagge.
</p>
<p>
&copy; <%= mailimprint %>
</p>
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>

View file

@ -0,0 +1 @@
<%= subject %>

View file

@ -0,0 +1,17 @@
TimeLimit wurde von dem Gerät <%= deviceName %> entfernt.
TimeLimit was removed from <%= deviceName %>.
----------------------
Sie erhalten diese Nachricht, weil Sie E-Mail-Benachrichtigungen in TimeLimit aktiviert haben.
Sie können die Nachrichten in der TimeLimit-App abbestellen, oder indem
Sie auf diese Nachricht antworten, dass Sie diese Benachrichtigungen nicht mehr erhalten möchten.
Falls Sie Fragen haben können Sie einfach auf diese E-Mail antworten.
You got this mail because you enable mail notifications for this in TimeLimit.
You can disable getting these messages in the TimeLimit App or by
replying to this message that you don't want to get these notifications anymore.
If you have got any questions, then you can reply to this messagge.
<C> <%= mailimprint %>

5634
other/wordlist/de.txt Normal file

File diff suppressed because it is too large Load diff

6501
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

64
package.json Normal file
View file

@ -0,0 +1,64 @@
{
"name": "timelimit-server-2018",
"version": "0.0.0",
"private": true,
"description": "",
"scripts": {
"start": "node ./build/index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "tslint --project .",
"lint:fix": "tslint --project . --fix",
"build": "npm run build:json && npm run build:ts && npm run lint",
"build:json": "node ./scripts/build-schemas.js",
"build:ts": "tsc",
"watch": "nodemon ./build/index.js"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/timelimit.io/timelimit-server-2018.git"
},
"author": "Jonas Lochmann",
"license": "AGPL-3.0",
"bugs": {
"url": "https://gitlab.com/timelimit.io/timelimit-server-2018/issues"
},
"homepage": "https://gitlab.com/timelimit.io/timelimit-server-2018#README",
"devDependencies": {
"@types/body-parser": "^1.17.0",
"@types/email-templates": "^3.5.0",
"@types/express": "^4.16.0",
"@types/http-errors": "^1.6.1",
"@types/lodash": "^4.14.116",
"@types/sequelize": "^4.27.24",
"@types/socket.io": "^1.4.36",
"@types/tokgen": "^1.0.0",
"@types/umzug": "^2.2.0",
"nodemon": "^1.18.3",
"tslint": "^5.11.0",
"tslint-config-standard": "^7.1.0",
"typescript": "^2.9.2",
"typescript-json-schema": "^0.31.0"
},
"dependencies": {
"ajv": "^6.5.2",
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"email-templates": "^5.0.4",
"express": "^4.16.3",
"google-auth-library": "^1.6.1",
"http-errors": "^1.7.0",
"iab_verifier": "^0.1.2",
"lodash": "^4.17.11",
"mysql2": "^1.6.1",
"pg": "^7.8.0",
"pg-hstore": "^2.3.2",
"rate-limiter-flexible": "^0.21.2",
"sequelize": "^4.38.0",
"socket.io": "^2.1.1",
"tokgen": "^1.0.0",
"umzug": "^2.1.0"
},
"optionalDependencies": {
"sqlite3": "^4.0.6"
}
}

114
scripts/build-schemas.js Normal file
View file

@ -0,0 +1,114 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
const { resolve } = require('path')
const TJS = require('typescript-json-schema')
const { writeFileSync } = require('fs')
const { each, isEqual } = require('lodash')
const randomString = 'WK9fxjlOcM'
const types = [
'ClientPushChangesRequest',
'ClientPullChangesRequest',
'SignInWithGoogleRequest',
'MailAuthTokenRequestBody',
'CreateFamilyByMailTokenRequest',
'SignIntoFamilyRequest',
'RecoverParentPasswordRequest',
'CanRecoverPasswordRequest',
'RegisterChildDeviceRequest',
'SerializedParentAction',
'SerializedAppLogicAction',
'SerializedChildAction',
'CreateRegisterDeviceTokenRequest',
'CanDoPurchaseRequest',
'FinishPurchaseByGooglePlayRequest',
'LinkParentMailAddressRequest',
'UpdatePrimaryDeviceRequest',
'RemoveDeviceRequest',
'RequestWithAuthToken',
'SendMailLoginCodeRequest',
'SignInByMailCodeRequest'
]
const settings = {
required: true,
noExtraProps: true
};
const compilerOptions = {
strictNullChecks: true,
lib: ['es2015']
}
// optionally pass a base path
const program = TJS.getProgramFromFiles([
resolve(__dirname, '../src/api/schema.ts')
], compilerOptions, __dirname)
const generator = TJS.buildGenerator(program, settings)
let definitions = {}
let schemas = {}
let output = ''
types.forEach((type) => {
const schema = generator.getSchemaForSymbol(type)
schemas[type] = schema
if (schema.definitions) {
each(schema.definitions, (value, name) => {
if (!definitions[name]) {
definitions[name] = value
} else {
if (!isEqual(definitions[name], value)) {
throw new Error('different schemas for ' + name)
}
}
})
}
})
output += '// tslint:disable \n'
output += 'import { ' + types.join(', ') + ' } from \'./schema\'\n'
output += 'const Ajv = require(\'ajv\')\n'
output += 'const ajv = new Ajv()\n'
output += '\n'
output += 'const definitions = ' + JSON.stringify(definitions, null, 2) + '\n\n'
types.forEach((type) => {
const schema = schemas[type]
let schemaString
if (schema.definitions) {
schemaString = JSON.stringify({
...schema,
definitions: randomString
}, null, 2).replace(JSON.stringify(randomString), 'definitions')
} else {
schemaString = JSON.stringify(schema, null, 2)
}
const functionBody = 'ajv.compile(' + schemaString + ')'
const functionName = 'is' + type.substr(0, 1).toUpperCase() + type.substr(1)
output += 'export const ' + functionName + ': (value: object) => value is ' + type + ' = ' + functionBody + '\n'
})
writeFileSync(resolve(__dirname, '../src/api/validator.ts'), output)

View file

@ -0,0 +1,51 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertNonEmptyListWithoutDuplicates } from '../util/list'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class AddCategoryAppsAction extends ParentAction {
readonly categoryId: string
readonly packageNames: Array<string>
constructor ({ categoryId, packageNames }: {categoryId: string, packageNames: Array<string>}) {
super()
assertIdWithinFamily(categoryId)
assertNonEmptyListWithoutDuplicates(packageNames)
this.categoryId = categoryId
this.packageNames = packageNames
}
serialize = (): SerializedAddCategoryAppsAction => ({
type: 'ADD_CATEGORY_APPS',
categoryId: this.categoryId,
packageNames: this.packageNames
})
static parse = ({ categoryId, packageNames }: SerializedAddCategoryAppsAction) => (
new AddCategoryAppsAction({ categoryId, packageNames })
)
}
export interface SerializedAddCategoryAppsAction {
type: 'ADD_CATEGORY_APPS'
categoryId: string
packageNames: Array<string>
}

View file

@ -0,0 +1,48 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { InstalledApp, SerializedInstalledApp } from '../model/installedapp'
import { assertNonEmptyListWithoutDuplicates } from '../util/list'
import { AppLogicAction } from './basetypes'
export class AddInstalledAppsAction extends AppLogicAction {
readonly apps: Array<InstalledApp>
constructor ({ apps }: {apps: Array<InstalledApp>}) {
super()
assertNonEmptyListWithoutDuplicates(apps.map((app) => app.packageName))
this.apps = apps
}
serialize = (): SerializedAddInstalledAppsAction => ({
type: 'ADD_INSTALLED_APPS',
apps: this.apps.map((app) => app.serialize())
})
static parse = ({ apps }: SerializedAddInstalledAppsAction) => (
new AddInstalledAppsAction({
apps: apps.map((app) => InstalledApp.parse(app))
})
)
}
export interface SerializedAddInstalledAppsAction {
type: 'ADD_INSTALLED_APPS'
apps: Array<SerializedInstalledApp>
}

79
src/action/addusedtime.ts Normal file
View file

@ -0,0 +1,79 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { AppLogicAction } from './basetypes'
export class AddUsedTimeAction extends AppLogicAction {
readonly categoryId: string
readonly dayOfEpoch: number
readonly timeToAdd: number
readonly extraTimeToSubtract: number
constructor ({ categoryId, dayOfEpoch, timeToAdd, extraTimeToSubtract }: {
categoryId: string
dayOfEpoch: number
timeToAdd: number
extraTimeToSubtract: number
}) {
super()
assertIdWithinFamily(categoryId)
if (dayOfEpoch < 0 || (!Number.isSafeInteger(dayOfEpoch))) {
throw new Error('illegal dayOfEpoch')
}
if (timeToAdd < 0 || (!Number.isSafeInteger(timeToAdd))) {
throw new Error('illegal timeToAdd')
}
if (extraTimeToSubtract < 0 || (!Number.isSafeInteger(extraTimeToSubtract))) {
throw new Error('illegal extra time to subtract')
}
this.categoryId = categoryId
this.dayOfEpoch = dayOfEpoch
this.timeToAdd = timeToAdd
this.extraTimeToSubtract = extraTimeToSubtract
}
serialize = (): SerializedAddUsedTimeAction => ({
type: 'ADD_USED_TIME',
categoryId: this.categoryId,
day: this.dayOfEpoch,
timeToAdd: this.timeToAdd,
extraTimeToSubtract: this.extraTimeToSubtract
})
static parse = ({ categoryId, day, timeToAdd, extraTimeToSubtract }: SerializedAddUsedTimeAction) => (
new AddUsedTimeAction({
categoryId,
dayOfEpoch: day,
timeToAdd,
extraTimeToSubtract
})
)
}
export interface SerializedAddUsedTimeAction {
type: 'ADD_USED_TIME'
categoryId: string
day: number
timeToAdd: number
extraTimeToSubtract: number
}

84
src/action/adduser.ts Normal file
View file

@ -0,0 +1,84 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertParentPasswordValid, ParentPassword } from '../api/schema'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class AddUserAction extends ParentAction {
readonly userId: string
readonly name: string
readonly userType: 'parent' | 'child'
readonly password?: ParentPassword
readonly timeZone: string
constructor ({ userId, name, userType, password, timeZone }: {
userId: string
name: string
userType: 'parent' | 'child'
password?: ParentPassword
timeZone: string
}) {
super()
assertIdWithinFamily(userId)
this.userId = userId
this.name = name
this.userType = userType
this.password = password
this.timeZone = timeZone
if (userType === 'parent') {
if (!password) {
throw new Error('parent users must have got an password')
}
}
if (password) {
assertParentPasswordValid(password)
}
}
serialize = (): SerializedAddUserAction => ({
type: 'ADD_USER',
name: this.name,
userType: this.userType,
userId: this.userId,
password: this.password,
timeZone: this.timeZone
})
static parse = ({ name, userId, userType, password, timeZone }: SerializedAddUserAction) => (
new AddUserAction({
name,
userId,
userType,
password,
timeZone
})
)
}
export interface SerializedAddUserAction {
type: 'ADD_USER'
name: string
userType: 'parent' | 'child'
userId: string
password?: ParentPassword
timeZone: string
}

26
src/action/basetypes.ts Normal file
View file

@ -0,0 +1,26 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
export abstract class Action {
abstract serialize: () => object
}
export abstract class AppLogicAction extends Action {}
export abstract class ParentAction extends Action {}
export abstract class ChildAction extends Action {}

View file

@ -0,0 +1,126 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { createDecipheriv, createHash } from 'crypto'
import { assertIsHexString } from '../util/hexstring'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class ChangeParentPasswordAction extends ParentAction {
readonly parentUserId: string
readonly newPasswordFirstHash: string
readonly newPasswordSecondSalt: string
readonly newPasswordSecondHashEncrypted: string
readonly integrity: string
constructor ({ parentUserId, newPasswordFirstHash, newPasswordSecondSalt, newPasswordSecondHashEncrypted, integrity }: {
parentUserId: string
newPasswordFirstHash: string
newPasswordSecondSalt: string
newPasswordSecondHashEncrypted: string
integrity: string
}) {
super()
assertIdWithinFamily(parentUserId)
if (
(!parentUserId) ||
(!newPasswordFirstHash) ||
(!newPasswordSecondSalt) ||
(!newPasswordSecondHashEncrypted) ||
(!integrity)
) {
throw new Error('missing required parameter for change parent password')
}
if (integrity.length !== 128) {
throw new Error('wrong length of integrity data')
}
assertIsHexString(newPasswordSecondHashEncrypted)
assertIsHexString(integrity)
this.parentUserId = parentUserId
this.newPasswordFirstHash = newPasswordFirstHash
this.newPasswordSecondSalt = newPasswordSecondSalt
this.newPasswordSecondHashEncrypted = newPasswordSecondHashEncrypted
this.integrity = integrity
}
serialize = (): SerializedChangeParentPasswordAction => ({
type: 'CHANGE_PARENT_PASSWORD',
userId: this.parentUserId,
hash: this.newPasswordFirstHash,
secondSalt: this.newPasswordSecondSalt,
secondHashEncrypted: this.newPasswordSecondHashEncrypted,
integrity: this.integrity
})
static parse = ({ userId, hash, secondSalt, secondHashEncrypted, integrity }: SerializedChangeParentPasswordAction) => (
new ChangeParentPasswordAction({
parentUserId: userId,
newPasswordFirstHash: hash,
newPasswordSecondSalt: secondSalt,
newPasswordSecondHashEncrypted: secondHashEncrypted,
integrity
})
)
assertIntegrityValid ({ oldPasswordSecondHash }: {oldPasswordSecondHash: string}) {
const integrityData = oldPasswordSecondHash +
this.parentUserId +
this.newPasswordFirstHash +
this.newPasswordSecondSalt +
this.newPasswordSecondHashEncrypted
const expected = createHash('sha512').update(integrityData).digest('hex')
if (expected !== this.integrity) {
throw new Error('invalid integrity for change parent password action')
}
}
decryptSecondHash ({ oldPasswordSecondHash }: {oldPasswordSecondHash: string}) {
if (this.newPasswordSecondHashEncrypted.length <= 70) {
throw new Error('wrong length of the new password')
}
const ivHex = this.newPasswordSecondHashEncrypted.substring(0, 32)
const salt = this.newPasswordSecondHashEncrypted.substring(32, 64)
const encryptedData = this.newPasswordSecondHashEncrypted.substring(64)
const keyData = oldPasswordSecondHash + salt
const key = createHash('sha512').update(keyData).digest().slice(0, 16)
const decipher = createDecipheriv('aes-128-ctr', key, Buffer.from(ivHex, 'hex'))
decipher.setAutoPadding(false)
const decryptedSecondHash = decipher.update(Buffer.from(encryptedData, 'hex')).toString() + decipher.final().toString()
return decryptedSecondHash
}
}
export interface SerializedChangeParentPasswordAction {
type: 'CHANGE_PARENT_PASSWORD'
userId: string
hash: string
secondSalt: string
secondHashEncrypted: string
integrity: string
}

View file

@ -0,0 +1,47 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertParentPasswordValid, ParentPassword } from '../api/schema'
import { ChildAction } from './basetypes'
export class ChildChangePasswordAction extends ChildAction {
readonly password: ParentPassword
constructor ({ password }: {
password: ParentPassword
}) {
super()
assertParentPasswordValid(password)
this.password = password
}
serialize = (): SerializedChildChangePasswordAction => ({
type: 'CHILD_CHANGE_PASSWORD',
password: this.password
})
static parse = ({ password }: SerializedChildChangePasswordAction) => (
new ChildChangePasswordAction({ password })
)
}
export interface SerializedChildChangePasswordAction {
type: 'CHILD_CHANGE_PASSWORD'
password: ParentPassword
}

36
src/action/childsignin.ts Normal file
View file

@ -0,0 +1,36 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { ChildAction } from './basetypes'
export class ChildSignInAction extends ChildAction {
constructor () {
super()
}
serialize = (): SerializedChildSignInAction => ({
type: 'CHILD_SIGN_IN'
})
static parse = (action: SerializedChildSignInAction) => (
new ChildSignInAction()
)
}
export interface SerializedChildSignInAction {
type: 'CHILD_SIGN_IN'
}

View file

@ -0,0 +1,54 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class CreateCategoryAction extends ParentAction {
readonly categoryId: string
readonly childId: string
readonly title: string
constructor ({ categoryId, childId, title }: {categoryId: string, childId: string, title: string}) {
super()
assertIdWithinFamily(categoryId)
assertIdWithinFamily(childId)
this.categoryId = categoryId
this.childId = childId
this.title = title
}
serialize = (): SerializedCreateCategoryAction => ({
type: 'CREATE_CATEGORY',
childId: this.childId,
categoryId: this.categoryId,
title: this.title
})
static parse = ({ childId, categoryId, title }: SerializedCreateCategoryAction) => (
new CreateCategoryAction({ childId, categoryId, title })
)
}
export interface SerializedCreateCategoryAction {
type: 'CREATE_CATEGORY'
childId: string
categoryId: string
title: string
}

View file

@ -0,0 +1,45 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { SerializedTimeLimitRule, TimelimitRule } from '../model/timelimitrule'
import { ParentAction } from './basetypes'
export class CreateTimeLimitRuleAction extends ParentAction {
rule: TimelimitRule
constructor ({ rule }: {rule: TimelimitRule}) {
super()
this.rule = rule
}
serialize = (): SerializedCreateTimelimtRuleAction => ({
type: 'CREATE_TIMELIMIT_RULE',
rule: this.rule.serialize()
})
static parse = ({ rule }: SerializedCreateTimelimtRuleAction) => (
new CreateTimeLimitRuleAction({
rule: TimelimitRule.parse(rule)
})
)
}
export interface SerializedCreateTimelimtRuleAction {
type: 'CREATE_TIMELIMIT_RULE'
rule: SerializedTimeLimitRule
}

View file

@ -0,0 +1,45 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class DeleteCategoryAction extends ParentAction {
readonly categoryId: string
constructor ({ categoryId }: {categoryId: string}) {
super()
assertIdWithinFamily(categoryId)
this.categoryId = categoryId
}
serialize = (): SerializedDeleteCategoryAction => ({
type: 'DELETE_CATEGORY',
categoryId: this.categoryId
})
static parse = ({ categoryId }: SerializedDeleteCategoryAction) => (
new DeleteCategoryAction({ categoryId })
)
}
export interface SerializedDeleteCategoryAction {
type: 'DELETE_CATEGORY'
categoryId: string
}

View file

@ -0,0 +1,45 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class DeleteTimeLimitRuleAction extends ParentAction {
readonly ruleId: string
constructor ({ ruleId }: {ruleId: string}) {
super()
assertIdWithinFamily(ruleId)
this.ruleId = ruleId
}
serialize = (): SerializedDeleteTimeLimitRuleAction => ({
type: 'DELETE_TIMELIMIT_RULE',
ruleId: this.ruleId
})
static parse = ({ ruleId }: SerializedDeleteTimeLimitRuleAction) => (
new DeleteTimeLimitRuleAction({ ruleId })
)
}
export interface SerializedDeleteTimeLimitRuleAction {
type: 'DELETE_TIMELIMIT_RULE'
ruleId: string
}

View file

@ -0,0 +1,95 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class IgnoreManipulationAction extends ParentAction {
readonly deviceId: string
readonly ignoreDeviceAdminManipulation: boolean
readonly ignoreDeviceAdminManipulationAttempt: boolean
readonly ignoreAppDowngrade: boolean
readonly ignoreNotificationAccessManipulation: boolean
readonly ignoreUsageStatsAccessManipulation: boolean
readonly ignoreDidReboot: boolean
readonly ignoreHadManipulation: boolean
constructor ({
deviceId, ignoreDeviceAdminManipulation, ignoreDeviceAdminManipulationAttempt,
ignoreAppDowngrade, ignoreNotificationAccessManipulation, ignoreUsageStatsAccessManipulation,
ignoreDidReboot, ignoreHadManipulation
}: {
deviceId: string
ignoreDeviceAdminManipulation: boolean
ignoreDeviceAdminManipulationAttempt: boolean
ignoreAppDowngrade: boolean
ignoreNotificationAccessManipulation: boolean
ignoreUsageStatsAccessManipulation: boolean
ignoreDidReboot: boolean
ignoreHadManipulation: boolean
}) {
super()
assertIdWithinFamily(deviceId)
this.deviceId = deviceId
this.ignoreDeviceAdminManipulation = ignoreDeviceAdminManipulation
this.ignoreDeviceAdminManipulationAttempt = ignoreDeviceAdminManipulationAttempt
this.ignoreAppDowngrade = ignoreAppDowngrade
this.ignoreNotificationAccessManipulation = ignoreNotificationAccessManipulation
this.ignoreUsageStatsAccessManipulation = ignoreUsageStatsAccessManipulation
this.ignoreDidReboot = ignoreDidReboot
this.ignoreHadManipulation = ignoreHadManipulation
}
serialize = (): SerializedIgnoreManipulationAction => ({
type: 'IGNORE_MANIPULATION',
deviceId: this.deviceId,
admin: this.ignoreDeviceAdminManipulation,
adminA: this.ignoreDeviceAdminManipulationAttempt,
downgrade: this.ignoreAppDowngrade,
notification: this.ignoreNotificationAccessManipulation,
usageStats: this.ignoreUsageStatsAccessManipulation,
hadManipulation: this.ignoreHadManipulation
})
static parse = ({ deviceId, admin, adminA, downgrade, notification, usageStats, reboot, hadManipulation }: SerializedIgnoreManipulationAction) => (
new IgnoreManipulationAction({
deviceId,
ignoreDeviceAdminManipulation: admin,
ignoreDeviceAdminManipulationAttempt: adminA,
ignoreAppDowngrade: downgrade,
ignoreUsageStatsAccessManipulation: usageStats,
ignoreNotificationAccessManipulation: notification,
ignoreDidReboot: !!reboot,
ignoreHadManipulation: hadManipulation
})
)
}
export interface SerializedIgnoreManipulationAction {
type: 'IGNORE_MANIPULATION'
deviceId: string
admin: boolean
adminA: boolean
downgrade: boolean
notification: boolean
usageStats: boolean
hadManipulation: boolean
// was added at a later version
reboot?: boolean
}

View file

@ -0,0 +1,53 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class IncrementCategoryExtraTimeAction extends ParentAction {
readonly categoryId: string
readonly addedExtraTime: number
constructor ({ categoryId, addedExtraTime }: {categoryId: string, addedExtraTime: number}) {
super()
assertIdWithinFamily(categoryId)
if (addedExtraTime <= 0 || (!Number.isSafeInteger(addedExtraTime))) {
throw new Error('must add some extra time with IncrementCategoryExtraTimeAction')
}
this.categoryId = categoryId
this.addedExtraTime = addedExtraTime
}
serialize = (): SerializedIncrementCategoryExtraTimeAction => ({
type: 'INCREMENT_CATEGORY_EXTRATIME',
categoryId: this.categoryId,
addedExtraTime: this.addedExtraTime
})
static parse = ({ categoryId, addedExtraTime }: SerializedIncrementCategoryExtraTimeAction) => (
new IncrementCategoryExtraTimeAction({ categoryId, addedExtraTime })
)
}
export interface SerializedIncrementCategoryExtraTimeAction {
type: 'INCREMENT_CATEGORY_EXTRATIME'
categoryId: string
addedExtraTime: number
}

59
src/action/index.ts Normal file
View file

@ -0,0 +1,59 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
export { AppLogicAction, ChildAction, ParentAction } from './basetypes'
export { AddCategoryAppsAction } from './addcategoryapps'
export { AddUserAction } from './adduser'
export { AddInstalledAppsAction } from './addinstalledapps'
export { AddUsedTimeAction } from './addusedtime'
export { ChangeParentPasswordAction } from './changeparentpassword'
export { ChildChangePasswordAction } from './childchangepassword'
export { ChildSignInAction } from './childsignin'
export { CreateCategoryAction } from './createcategory'
export { CreateTimeLimitRuleAction } from './createtimelimitrule'
export { DeleteCategoryAction } from './deletecategory'
export { DeleteTimeLimitRuleAction } from './deletetimelimitrule'
export { IgnoreManipulationAction } from './ignoremanipulation'
export { IncrementCategoryExtraTimeAction } from './incrementcategoryextratime'
export { RemoveCategoryAppsAction } from './removecategoryapps'
export { RemoveInstalledAppsAction } from './removeinstalledapps'
export { RemoveUserAction } from './removeuser'
export { RenameChildAction } from './renamechild'
export { SetCategoryExtraTimeAction } from './setcategoryextratime'
export { SetCategoryForUnassignedAppsAction } from './setcategoryforunassignedapps'
export { SetChildPasswordAction } from './setchildpassword'
export { SetConsiderRebootManipulationAction } from './setconsiderrebootmanipulation'
export { SetDeviceDefaultUserAction } from './setdevicedefaultuser'
export { SetDeviceDefaultUserTimeoutAction } from './setdevicedefaultusertimeout'
export { SetDeviceUserAction } from './setdeviceuser'
export { SetKeepSignedInAction } from './setkeepsignedin'
export { SetParentCategoryAction } from './setparentcategory'
export { SetRelaxPrimaryDeviceAction } from './setrelaxprimarydevice'
export { SetSendDeviceConnected } from './setsenddeviceconnected'
export { SetUserDisableLimitsUntilAction } from './setuserdisablelimitsuntil'
export { SetUserTimezoneAction } from './setusertimezone'
export { SignOutAtDeviceAction } from './signoutatdevice'
export { TriedDisablingDeviceAdminAction } from './trieddisablingdeviceadmin'
export { UpdateCategoryBlockedTimesAction } from './updatecategoryblockedtimes'
export { UpdateCategoryTemporarilyBlockedAction } from './updatecategorytemporarilyblocked'
export { UpdateCategoryTitleAction } from './updatecategorytitle'
export { UpdateDeviceNameAction } from './updatedevicename'
export { UpdateDeviceStatusAction } from './updatedevicestatus'
export { UpdateNetworkTimeVerificationAction } from './updatenetworktimeverification'
export { UpdateParentNotificationFlagsAction } from './updateparentnotificationflags'
export { UpdateTimelimitRuleAction } from './updatetimelimitrule'

View file

@ -0,0 +1,51 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertNonEmptyListWithoutDuplicates } from '../util/list'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class RemoveCategoryAppsAction extends ParentAction {
readonly categoryId: string
readonly packageNames: Array<string>
constructor ({ categoryId, packageNames }: {categoryId: string, packageNames: Array<string>}) {
super()
assertIdWithinFamily(categoryId)
assertNonEmptyListWithoutDuplicates(packageNames)
this.categoryId = categoryId
this.packageNames = packageNames
}
serialize = (): SerializedRemoveCategoryAppsAction => ({
type: 'REMOVE_CATEGORY_APPS',
categoryId: this.categoryId,
packageNames: this.packageNames
})
static parse = ({ categoryId, packageNames }: SerializedRemoveCategoryAppsAction) => (
new RemoveCategoryAppsAction({ categoryId, packageNames })
)
}
export interface SerializedRemoveCategoryAppsAction {
type: 'REMOVE_CATEGORY_APPS'
categoryId: string
packageNames: Array<string>
}

View file

@ -0,0 +1,45 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertNonEmptyListWithoutDuplicates } from '../util/list'
import { AppLogicAction } from './basetypes'
export class RemoveInstalledAppsAction extends AppLogicAction {
readonly packageNames: Array<string>
constructor ({ packageNames }: {packageNames: Array<string>}) {
super()
assertNonEmptyListWithoutDuplicates(packageNames)
this.packageNames = packageNames
}
serialize = (): SerializedRemoveInstalledAppsAction => ({
type: 'REMOVE_INSTALLED_APPS',
packageNames: this.packageNames
})
static parse = ({ packageNames }: SerializedRemoveInstalledAppsAction) => (
new RemoveInstalledAppsAction({ packageNames })
)
}
export interface SerializedRemoveInstalledAppsAction {
type: 'REMOVE_INSTALLED_APPS'
packageNames: Array<string>
}

55
src/action/removeuser.ts Normal file
View file

@ -0,0 +1,55 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class RemoveUserAction extends ParentAction {
readonly userId: string
// required for deleting parent users
// parent users can only be removed by other parent users
// this should be the value of sha512(userId + secondPasswordHash + 'remove').substring(0, 16)
readonly authentication?: string
constructor ({ userId, authentication }: {
userId: string
authentication?: string
}) {
super()
assertIdWithinFamily(userId)
this.userId = userId
this.authentication = authentication
}
serialize = (): SerializedRemoveUserAction => ({
type: 'REMOVE_USER',
userId: this.userId,
authentication: this.authentication
})
static parse = ({ userId, authentication }: SerializedRemoveUserAction) => (
new RemoveUserAction({ userId, authentication })
)
}
export interface SerializedRemoveUserAction {
type: 'REMOVE_USER'
userId: string
authentication?: string
}

56
src/action/renamechild.ts Normal file
View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class RenameChildAction extends ParentAction {
readonly childId: string
readonly newName: string
constructor ({ childId, newName }: {
childId: string
newName: string
}) {
super()
assertIdWithinFamily(childId)
if (newName === '') {
throw new Error('new name must not be empty')
}
this.childId = childId
this.newName = newName
}
serialize = (): SerializedRenameChildAction => ({
type: 'RENAME_CHILD',
childId: this.childId,
newName: this.newName
})
static parse = ({ childId, newName }: SerializedRenameChildAction) => (
new RenameChildAction({ childId, newName })
)
}
export interface SerializedRenameChildAction {
type: 'RENAME_CHILD'
childId: string
newName: string
}

View file

@ -0,0 +1,50 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { AddInstalledAppsAction, SerializedAddInstalledAppsAction } from '../addinstalledapps'
import { AddUsedTimeAction, SerializedAddUsedTimeAction } from '../addusedtime'
import { AppLogicAction } from '../basetypes'
import { RemoveInstalledAppsAction, SerializedRemoveInstalledAppsAction } from '../removeinstalledapps'
import { SerializedSignOutAtDeviceAction, SignOutAtDeviceAction } from '../signoutatdevice'
import { SerialiezdTriedDisablingDeviceAdminAction, TriedDisablingDeviceAdminAction } from '../trieddisablingdeviceadmin'
import { SerializedUpdateDeviceStatusAction, UpdateDeviceStatusAction } from '../updatedevicestatus'
export type SerializedAppLogicAction =
SerializedAddInstalledAppsAction |
SerializedAddUsedTimeAction |
SerializedRemoveInstalledAppsAction |
SerializedSignOutAtDeviceAction |
SerialiezdTriedDisablingDeviceAdminAction |
SerializedUpdateDeviceStatusAction
export const parseAppLogicAction = (serialized: SerializedAppLogicAction): AppLogicAction => {
if (serialized.type === 'ADD_USED_TIME') {
return AddUsedTimeAction.parse(serialized)
} else if (serialized.type === 'ADD_INSTALLED_APPS') {
return AddInstalledAppsAction.parse(serialized)
} else if (serialized.type === 'REMOVE_INSTALLED_APPS') {
return RemoveInstalledAppsAction.parse(serialized)
} else if (serialized.type === 'SIGN_OUT_AT_DEVICE') {
return SignOutAtDeviceAction.parse(serialized)
} else if (serialized.type === 'TRIED_DISABLING_DEVICE_ADMIN') {
return new TriedDisablingDeviceAdminAction()
} else if (serialized.type === 'UPDATE_DEVICE_STATUS') {
return UpdateDeviceStatusAction.parse(serialized)
} else {
throw new Error('illegal state: unsupported type at parseAppLogicAction')
}
}

View file

@ -0,0 +1,31 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { ChildChangePasswordAction, SerializedChildChangePasswordAction } from '../childchangepassword'
import { ChildSignInAction, SerializedChildSignInAction } from '../childsignin'
export type SerializedChildAction = SerializedChildChangePasswordAction | SerializedChildSignInAction
export const parseChildAction = (serialized: SerializedChildAction) => {
if (serialized.type === 'CHILD_CHANGE_PASSWORD') {
return ChildChangePasswordAction.parse(serialized)
} else if (serialized.type === 'CHILD_SIGN_IN') {
return ChildSignInAction.parse(serialized)
} else {
throw new Error('illegal state: unsupported type at parseChildAction')
}
}

View file

@ -0,0 +1,20 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
export { parseAppLogicAction, SerializedAppLogicAction } from './applogicaction'
export { parseChildAction, SerializedChildAction } from './childaction'
export { parseParentAction, SerializedParentAction } from './parentaction'

View file

@ -0,0 +1,154 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { AddCategoryAppsAction, SerializedAddCategoryAppsAction } from '../addcategoryapps'
import { AddUserAction, SerializedAddUserAction } from '../adduser'
import { ParentAction } from '../basetypes'
import { ChangeParentPasswordAction, SerializedChangeParentPasswordAction } from '../changeparentpassword'
import { CreateCategoryAction, SerializedCreateCategoryAction } from '../createcategory'
import { CreateTimeLimitRuleAction, SerializedCreateTimelimtRuleAction } from '../createtimelimitrule'
import { DeleteCategoryAction, SerializedDeleteCategoryAction } from '../deletecategory'
import { DeleteTimeLimitRuleAction, SerializedDeleteTimeLimitRuleAction } from '../deletetimelimitrule'
import { IgnoreManipulationAction, SerializedIgnoreManipulationAction } from '../ignoremanipulation'
import { IncrementCategoryExtraTimeAction, SerializedIncrementCategoryExtraTimeAction } from '../incrementcategoryextratime'
import { RemoveCategoryAppsAction, SerializedRemoveCategoryAppsAction } from '../removecategoryapps'
import { RemoveUserAction, SerializedRemoveUserAction } from '../removeuser'
import { RenameChildAction, SerializedRenameChildAction } from '../renamechild'
import { SerializedSetCategoryExtraTimeAction, SetCategoryExtraTimeAction } from '../setcategoryextratime'
import { SerializedSetCategoryForUnassignedAppsAction, SetCategoryForUnassignedAppsAction } from '../setcategoryforunassignedapps'
import { SerializedSetChildPasswordAction, SetChildPasswordAction } from '../setchildpassword'
import { SerializedSetConsiderRebootManipulationAction, SetConsiderRebootManipulationAction } from '../setconsiderrebootmanipulation'
import { SerializedSetDeviceDefaultUserAction, SetDeviceDefaultUserAction } from '../setdevicedefaultuser'
import { SerializedSetDeviceDefaultUserTimeoutAction, SetDeviceDefaultUserTimeoutAction } from '../setdevicedefaultusertimeout'
import { SerializedSetDeviceUserAction, SetDeviceUserAction } from '../setdeviceuser'
import { SerializedSetKeepSignedInAction, SetKeepSignedInAction } from '../setkeepsignedin'
import { SerializedSetParentCategoryAction, SetParentCategoryAction } from '../setparentcategory'
import { SerializedSetRelaxPrimaryDeviceAction, SetRelaxPrimaryDeviceAction } from '../setrelaxprimarydevice'
import { SerializedSetSendDeviceConnected, SetSendDeviceConnected } from '../setsenddeviceconnected'
import { SerializedSetUserDisableLimitsUntilAction, SetUserDisableLimitsUntilAction } from '../setuserdisablelimitsuntil'
import { SerializedSetUserTimezoneAction, SetUserTimezoneAction } from '../setusertimezone'
import { SerializedUpdateCategoryBlockedTimesAction, UpdateCategoryBlockedTimesAction } from '../updatecategoryblockedtimes'
import { SerializedUpdateCategoryTemporarilyBlockedAction, UpdateCategoryTemporarilyBlockedAction } from '../updatecategorytemporarilyblocked'
import { SerializedUpdateCategoryTitleAction, UpdateCategoryTitleAction } from '../updatecategorytitle'
import { SerializedUpdateDeviceNameAction, UpdateDeviceNameAction } from '../updatedevicename'
import { SerialiizedUpdateNetworkTimeVerificationAction, UpdateNetworkTimeVerificationAction } from '../updatenetworktimeverification'
import { SerializedUpdateParentNotificationFlagsAction, UpdateParentNotificationFlagsAction } from '../updateparentnotificationflags'
import { SerializedUpdateTimelimitRuleAction, UpdateTimelimitRuleAction } from '../updatetimelimitrule'
export type SerializedParentAction =
SerializedAddCategoryAppsAction |
SerializedAddUserAction |
SerializedChangeParentPasswordAction |
SerializedCreateCategoryAction |
SerializedCreateTimelimtRuleAction |
SerializedDeleteCategoryAction |
SerializedDeleteTimeLimitRuleAction |
SerializedIgnoreManipulationAction |
SerializedIncrementCategoryExtraTimeAction |
SerializedRemoveCategoryAppsAction |
SerializedRemoveUserAction |
SerializedRenameChildAction |
SerializedSetCategoryForUnassignedAppsAction |
SerializedSetChildPasswordAction |
SerializedSetConsiderRebootManipulationAction |
SerializedSetDeviceDefaultUserAction |
SerializedSetDeviceDefaultUserTimeoutAction |
SerializedSetCategoryExtraTimeAction |
SerializedSetDeviceUserAction |
SerializedSetKeepSignedInAction |
SerializedSetParentCategoryAction |
SerializedSetRelaxPrimaryDeviceAction |
SerializedSetSendDeviceConnected |
SerializedSetUserDisableLimitsUntilAction |
SerializedSetUserTimezoneAction |
SerializedUpdateCategoryBlockedTimesAction |
SerializedUpdateCategoryTemporarilyBlockedAction |
SerializedUpdateCategoryTitleAction |
SerializedUpdateDeviceNameAction |
SerialiizedUpdateNetworkTimeVerificationAction |
SerializedUpdateParentNotificationFlagsAction |
SerializedUpdateTimelimitRuleAction
export const parseParentAction = (action: SerializedParentAction): ParentAction => {
if (action.type === 'ADD_CATEGORY_APPS') {
return AddCategoryAppsAction.parse(action)
} else if (action.type === 'ADD_USER') {
return AddUserAction.parse(action)
} else if (action.type === 'CHANGE_PARENT_PASSWORD') {
return ChangeParentPasswordAction.parse(action)
} else if (action.type === 'CREATE_CATEGORY') {
return CreateCategoryAction.parse(action)
} else if (action.type === 'CREATE_TIMELIMIT_RULE') {
return CreateTimeLimitRuleAction.parse(action)
} else if (action.type === 'DELETE_CATEGORY') {
return DeleteCategoryAction.parse(action)
} else if (action.type === 'DELETE_TIMELIMIT_RULE') {
return DeleteTimeLimitRuleAction.parse(action)
} else if (action.type === 'IGNORE_MANIPULATION') {
return IgnoreManipulationAction.parse(action)
} else if (action.type === 'INCREMENT_CATEGORY_EXTRATIME') {
return IncrementCategoryExtraTimeAction.parse(action)
} else if (action.type === 'REMOVE_CATEGORY_APPS') {
return RemoveCategoryAppsAction.parse(action)
} else if (action.type === 'REMOVE_USER') {
return RemoveUserAction.parse(action)
} else if (action.type === 'RENAME_CHILD') {
return RenameChildAction.parse(action)
} else if (action.type === 'SET_CATEGORY_EXTRA_TIME') {
return SetCategoryExtraTimeAction.parse(action)
} else if (action.type === 'SET_CATEGORY_FOR_UNASSIGNED_APPS') {
return SetCategoryForUnassignedAppsAction.parse(action)
} else if (action.type === 'SET_CHILD_PASSWORD') {
return SetChildPasswordAction.parse(action)
} else if (action.type === 'SET_CONSIDER_REBOOT_MANIPULATION') {
return SetConsiderRebootManipulationAction.parse(action)
} else if (action.type === 'SET_DEVICE_DEFAULT_USER') {
return SetDeviceDefaultUserAction.parse(action)
} else if (action.type === 'SET_DEVICE_DEFAULT_USER_TIMEOUT') {
return SetDeviceDefaultUserTimeoutAction.parse(action)
} else if (action.type === 'SET_DEVICE_USER') {
return SetDeviceUserAction.parse(action)
} else if (action.type === 'SET_KEEP_SIGNED_IN') {
return SetKeepSignedInAction.parse(action)
} else if (action.type === 'SET_PARENT_CATEGORY') {
return SetParentCategoryAction.parse(action)
} else if (action.type === 'SET_RELAX_PRIMARY_DEVICE') {
return SetRelaxPrimaryDeviceAction.parse(action)
} else if (action.type === 'SET_SEND_DEVICE_CONNECTED') {
return SetSendDeviceConnected.parse(action)
} else if (action.type === 'SET_USER_DISABLE_LIMITS_UNTIL') {
return SetUserDisableLimitsUntilAction.parse(action)
} else if (action.type === 'SET_USER_TIMEZONE') {
return SetUserTimezoneAction.parse(action)
} else if (action.type === 'UPDATE_CATEGORY_BLOCKED_TIMES') {
return UpdateCategoryBlockedTimesAction.parse(action)
} else if (action.type === 'UPDATE_CATEGORY_TITLE') {
return UpdateCategoryTitleAction.parse(action)
} else if (action.type === 'UPDATE_CATEGORY_TEMPORARILY_BLOCKED') {
return UpdateCategoryTemporarilyBlockedAction.parse(action)
} else if (action.type === 'UPDATE_DEVICE_NAME') {
return UpdateDeviceNameAction.parse(action)
} else if (action.type === 'UPDATE_NETWORK_TIME_VERIFICATION') {
return UpdateNetworkTimeVerificationAction.parse(action)
} else if (action.type === 'UPDATE_PARENT_NOTIFICATION_FLAGS') {
return UpdateParentNotificationFlagsAction.parse(action)
} else if (action.type === 'UPDATE_TIMELIMIT_RULE') {
return UpdateTimelimitRuleAction.parse(action)
} else {
throw new Error('illegal state: invalid type for action at parseParentAction')
}
}

View file

@ -0,0 +1,53 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetCategoryExtraTimeAction extends ParentAction {
readonly categoryId: string
readonly newExtraTime: number
constructor ({ categoryId, newExtraTime }: {categoryId: string, newExtraTime: number}) {
super()
assertIdWithinFamily(categoryId)
if (newExtraTime < 0 || (!Number.isSafeInteger(newExtraTime))) {
throw Error('newExtraTime must be >= 0')
}
this.categoryId = categoryId
this.newExtraTime = newExtraTime
}
serialize = (): SerializedSetCategoryExtraTimeAction => ({
type: 'SET_CATEGORY_EXTRA_TIME',
categoryId: this.categoryId,
newExtraTime: this.newExtraTime
})
static parse = ({ categoryId, newExtraTime }: SerializedSetCategoryExtraTimeAction) => (
new SetCategoryExtraTimeAction({ categoryId, newExtraTime })
)
}
export interface SerializedSetCategoryExtraTimeAction {
type: 'SET_CATEGORY_EXTRA_TIME'
categoryId: string
newExtraTime: number
}

View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetCategoryForUnassignedAppsAction extends ParentAction {
readonly childId: string
readonly categoryId: string
constructor ({ childId, categoryId }: {
childId: string
categoryId: string
}) {
super()
assertIdWithinFamily(childId)
if (categoryId !== '') {
assertIdWithinFamily(categoryId)
}
this.childId = childId
this.categoryId = categoryId
}
serialize = (): SerializedSetCategoryForUnassignedAppsAction => ({
type: 'SET_CATEGORY_FOR_UNASSIGNED_APPS',
childId: this.childId,
categoryId: this.categoryId
})
static parse = ({ childId, categoryId }: SerializedSetCategoryForUnassignedAppsAction) => (
new SetCategoryForUnassignedAppsAction({ childId, categoryId })
)
}
export interface SerializedSetCategoryForUnassignedAppsAction {
type: 'SET_CATEGORY_FOR_UNASSIGNED_APPS'
childId: string
categoryId: string
}

View file

@ -0,0 +1,57 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertParentPasswordValid, ParentPassword } from '../api/schema'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetChildPasswordAction extends ParentAction {
readonly childUserId: string
readonly newPassword: ParentPassword
constructor ({ childUserId, newPassword }: {
childUserId: string
newPassword: ParentPassword
}) {
super()
assertIdWithinFamily(childUserId)
assertParentPasswordValid(newPassword)
this.childUserId = childUserId
this.newPassword = newPassword
}
serialize = (): SerializedSetChildPasswordAction => ({
type: 'SET_CHILD_PASSWORD',
childId: this.childUserId,
newPassword: this.newPassword
})
static parse = ({ childId, newPassword }: SerializedSetChildPasswordAction) => (
new SetChildPasswordAction({
childUserId: childId,
newPassword
})
)
}
export interface SerializedSetChildPasswordAction {
type: 'SET_CHILD_PASSWORD'
childId: string
newPassword: ParentPassword
}

View file

@ -0,0 +1,49 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetConsiderRebootManipulationAction extends ParentAction {
readonly deviceId: string
readonly enable: boolean
constructor ({ deviceId, enable }: {deviceId: string, enable: boolean}) {
super()
assertIdWithinFamily(deviceId)
this.deviceId = deviceId
this.enable = enable
}
serialize = (): SerializedSetConsiderRebootManipulationAction => ({
type: 'SET_CONSIDER_REBOOT_MANIPULATION',
deviceId: this.deviceId,
enable: this.enable
})
static parse = ({ deviceId, enable }: SerializedSetConsiderRebootManipulationAction) => (
new SetConsiderRebootManipulationAction({ deviceId, enable })
)
}
export interface SerializedSetConsiderRebootManipulationAction {
type: 'SET_CONSIDER_REBOOT_MANIPULATION'
deviceId: string
enable: boolean
}

View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetDeviceDefaultUserAction extends ParentAction {
readonly deviceId: string
readonly defaultUserId: string
constructor ({ deviceId, defaultUserId }: {
deviceId: string
defaultUserId: string
}) {
super()
assertIdWithinFamily(deviceId)
if (defaultUserId !== '') {
assertIdWithinFamily(defaultUserId)
}
this.deviceId = deviceId
this.defaultUserId = defaultUserId
}
serialize = (): SerializedSetDeviceDefaultUserAction => ({
type: 'SET_DEVICE_DEFAULT_USER',
deviceId: this.deviceId,
defaultUserId: this.defaultUserId
})
static parse = ({ deviceId, defaultUserId }: SerializedSetDeviceDefaultUserAction) => (
new SetDeviceDefaultUserAction({ deviceId, defaultUserId })
)
}
export interface SerializedSetDeviceDefaultUserAction {
type: 'SET_DEVICE_DEFAULT_USER'
deviceId: string
defaultUserId: string
}

View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetDeviceDefaultUserTimeoutAction extends ParentAction {
readonly deviceId: string
readonly timeout: number
constructor ({ deviceId, timeout }: {
deviceId: string
timeout: number
}) {
super()
assertIdWithinFamily(deviceId)
if ((!Number.isInteger(timeout)) || (timeout < 0)) {
throw new Error('timeout must be a non-negative integer')
}
this.deviceId = deviceId
this.timeout = timeout
}
serialize = (): SerializedSetDeviceDefaultUserTimeoutAction => ({
type: 'SET_DEVICE_DEFAULT_USER_TIMEOUT',
deviceId: this.deviceId,
timeout: this.timeout
})
static parse = ({ deviceId, timeout }: SerializedSetDeviceDefaultUserTimeoutAction) => (
new SetDeviceDefaultUserTimeoutAction({ deviceId, timeout })
)
}
export interface SerializedSetDeviceDefaultUserTimeoutAction {
type: 'SET_DEVICE_DEFAULT_USER_TIMEOUT'
deviceId: string
timeout: number
}

View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetDeviceUserAction extends ParentAction {
readonly deviceId: string
readonly userId: string // user id can be ""
constructor ({ deviceId, userId }: {
deviceId: string
userId: string
}) {
super()
assertIdWithinFamily(deviceId)
if (userId !== '') {
assertIdWithinFamily(userId)
}
this.deviceId = deviceId
this.userId = userId
}
serialize = (): SerializedSetDeviceUserAction => ({
type: 'SET_DEVICE_USER',
deviceId: this.deviceId,
userId: this.userId
})
static parse = ({ deviceId, userId }: SerializedSetDeviceUserAction) => (
new SetDeviceUserAction({ deviceId, userId })
)
}
export interface SerializedSetDeviceUserAction {
type: 'SET_DEVICE_USER'
deviceId: string
userId: string
}

View file

@ -0,0 +1,55 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetKeepSignedInAction extends ParentAction {
readonly deviceId: string
readonly keepSignedIn: boolean
constructor ({ deviceId, keepSignedIn }: {
deviceId: string
keepSignedIn: boolean
}) {
super()
assertIdWithinFamily(deviceId)
this.deviceId = deviceId
this.keepSignedIn = keepSignedIn
}
serialize = (): SerializedSetKeepSignedInAction => ({
type: 'SET_KEEP_SIGNED_IN',
deviceId: this.deviceId,
keepSignedIn: this.keepSignedIn
})
static parse = ({ deviceId, keepSignedIn }: SerializedSetKeepSignedInAction) => (
new SetKeepSignedInAction({
deviceId,
keepSignedIn
})
)
}
export interface SerializedSetKeepSignedInAction {
type: 'SET_KEEP_SIGNED_IN'
deviceId: string
keepSignedIn: boolean
}

View file

@ -0,0 +1,59 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetParentCategoryAction extends ParentAction {
readonly categoryId: string
readonly parentCategory: string
constructor ({ categoryId, parentCategory }: {
categoryId: string
parentCategory: string
}) {
super()
assertIdWithinFamily(categoryId)
if (parentCategory !== '') {
assertIdWithinFamily(parentCategory)
}
this.categoryId = categoryId
this.parentCategory = parentCategory
}
serialize = (): SerializedSetParentCategoryAction => ({
type: 'SET_PARENT_CATEGORY',
categoryId: this.categoryId,
parentCategory: this.parentCategory
})
static parse = ({ categoryId, parentCategory }: SerializedSetParentCategoryAction) => (
new SetParentCategoryAction({
categoryId,
parentCategory
})
)
}
export interface SerializedSetParentCategoryAction {
type: 'SET_PARENT_CATEGORY'
categoryId: string
parentCategory: string
}

View file

@ -0,0 +1,52 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetRelaxPrimaryDeviceAction extends ParentAction {
readonly userId: string
readonly relax: boolean
constructor ({ userId, relax }: {
userId: string
relax: boolean
}) {
super()
assertIdWithinFamily(userId)
this.userId = userId
this.relax = relax
}
serialize = (): SerializedSetRelaxPrimaryDeviceAction => ({
type: 'SET_RELAX_PRIMARY_DEVICE',
userId: this.userId,
relax: this.relax
})
static parse = ({ userId, relax }: SerializedSetRelaxPrimaryDeviceAction) => (
new SetRelaxPrimaryDeviceAction({ userId, relax })
)
}
export interface SerializedSetRelaxPrimaryDeviceAction {
type: 'SET_RELAX_PRIMARY_DEVICE'
userId: string
relax: boolean
}

View file

@ -0,0 +1,55 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetSendDeviceConnected extends ParentAction {
readonly deviceId: string
readonly enable: boolean
constructor ({ deviceId, enable }: {
deviceId: string
enable: boolean
}) {
super()
assertIdWithinFamily(deviceId)
this.deviceId = deviceId
this.enable = enable
}
serialize = (): SerializedSetSendDeviceConnected => ({
type: 'SET_SEND_DEVICE_CONNECTED',
deviceId: this.deviceId,
enable: this.enable
})
static parse = ({ deviceId, enable }: SerializedSetSendDeviceConnected) => (
new SetSendDeviceConnected({
deviceId,
enable
})
)
}
export interface SerializedSetSendDeviceConnected {
type: 'SET_SEND_DEVICE_CONNECTED'
deviceId: string
enable: boolean
}

View file

@ -0,0 +1,59 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetUserDisableLimitsUntilAction extends ParentAction {
readonly childId: string
readonly timestamp: number
constructor ({ childId, timestamp }: {
childId: string
timestamp: number
}) {
super()
assertIdWithinFamily(childId)
if (timestamp < 0 || (!Number.isSafeInteger(timestamp))) {
throw new Error('timestamp for set user disabe limits until must be >= 0')
}
this.childId = childId
this.timestamp = timestamp
}
serialize = (): SerializedSetUserDisableLimitsUntilAction => ({
type: 'SET_USER_DISABLE_LIMITS_UNTIL',
childId: this.childId,
time: this.timestamp
})
static parse = ({ childId, time }: SerializedSetUserDisableLimitsUntilAction) => (
new SetUserDisableLimitsUntilAction({
childId,
timestamp: time
})
)
}
export interface SerializedSetUserDisableLimitsUntilAction {
type: 'SET_USER_DISABLE_LIMITS_UNTIL'
childId: string
time: number
}

View file

@ -0,0 +1,52 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class SetUserTimezoneAction extends ParentAction {
readonly userId: string
readonly timezone: string
constructor ({ userId, timezone }: {
userId: string
timezone: string
}) {
super()
assertIdWithinFamily(userId)
this.userId = userId
this.timezone = timezone
}
serialize = (): SerializedSetUserTimezoneAction => ({
type: 'SET_USER_TIMEZONE',
userId: this.userId,
timezone: this.timezone
})
static parse = ({ userId, timezone }: SerializedSetUserTimezoneAction) => (
new SetUserTimezoneAction({ userId, timezone })
)
}
export interface SerializedSetUserTimezoneAction {
type: 'SET_USER_TIMEZONE'
userId: string
timezone: string
}

View file

@ -0,0 +1,36 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { AppLogicAction } from './basetypes'
export class SignOutAtDeviceAction extends AppLogicAction {
static instance = new SignOutAtDeviceAction()
private constructor () {
super()
}
serialize = (): SerializedSignOutAtDeviceAction => ({
type: 'SIGN_OUT_AT_DEVICE'
})
static parse = (action: SerializedSignOutAtDeviceAction) => SignOutAtDeviceAction.instance
}
export interface SerializedSignOutAtDeviceAction {
type: 'SIGN_OUT_AT_DEVICE'
}

View file

@ -0,0 +1,32 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { AppLogicAction } from './basetypes'
export class TriedDisablingDeviceAdminAction extends AppLogicAction {
constructor () {
super()
}
serialize = (): SerialiezdTriedDisablingDeviceAdminAction => ({
type: 'TRIED_DISABLING_DEVICE_ADMIN'
})
}
export interface SerialiezdTriedDisablingDeviceAdminAction {
type: 'TRIED_DISABLING_DEVICE_ADMIN'
}

View file

@ -0,0 +1,57 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { validateBitmask } from '../util/bitmask'
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateCategoryBlockedTimesAction extends ParentAction {
readonly categoryId: string
readonly blockedTimes: string
constructor ({ categoryId, blockedTimes }: {
categoryId: string
blockedTimes: string
}) {
super()
assertIdWithinFamily(categoryId)
validateBitmask(blockedTimes, 60 * 24 * 7 /* number of minutes per week */)
this.categoryId = categoryId
this.blockedTimes = blockedTimes
}
serialize = (): SerializedUpdateCategoryBlockedTimesAction => ({
type: 'UPDATE_CATEGORY_BLOCKED_TIMES',
categoryId: this.categoryId,
times: this.blockedTimes
})
static parse = ({ categoryId, times }: SerializedUpdateCategoryBlockedTimesAction) => (
new UpdateCategoryBlockedTimesAction({
categoryId,
blockedTimes: times
})
)
}
export interface SerializedUpdateCategoryBlockedTimesAction {
type: 'UPDATE_CATEGORY_BLOCKED_TIMES'
categoryId: string
times: string
}

View file

@ -0,0 +1,49 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateCategoryTemporarilyBlockedAction extends ParentAction {
readonly categoryId: string
readonly blocked: boolean
constructor ({ categoryId, blocked }: {categoryId: string, blocked: boolean}) {
super()
assertIdWithinFamily(categoryId)
this.categoryId = categoryId
this.blocked = blocked
}
serialize = (): SerializedUpdateCategoryTemporarilyBlockedAction => ({
type: 'UPDATE_CATEGORY_TEMPORARILY_BLOCKED',
categoryId: this.categoryId,
blocked: this.blocked
})
static parse = ({ categoryId, blocked }: SerializedUpdateCategoryTemporarilyBlockedAction) => (
new UpdateCategoryTemporarilyBlockedAction({ categoryId, blocked })
)
}
export interface SerializedUpdateCategoryTemporarilyBlockedAction {
type: 'UPDATE_CATEGORY_TEMPORARILY_BLOCKED'
categoryId: string
blocked: boolean
}

View file

@ -0,0 +1,49 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateCategoryTitleAction extends ParentAction {
readonly categoryId: string
readonly newTitle: string
constructor ({ categoryId, newTitle }: {categoryId: string, newTitle: string}) {
super()
assertIdWithinFamily(categoryId)
this.categoryId = categoryId
this.newTitle = newTitle
}
serialize = (): SerializedUpdateCategoryTitleAction => ({
type: 'UPDATE_CATEGORY_TITLE',
categoryId: this.categoryId,
newTitle: this.newTitle
})
static parse = ({ categoryId, newTitle }: SerializedUpdateCategoryTitleAction) => (
new UpdateCategoryTitleAction({ categoryId, newTitle })
)
}
export interface SerializedUpdateCategoryTitleAction {
type: 'UPDATE_CATEGORY_TITLE'
categoryId: string
newTitle: string
}

View file

@ -0,0 +1,56 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateDeviceNameAction extends ParentAction {
readonly deviceId: string
readonly name: string
constructor ({ deviceId, name }: {
deviceId: string
name: string
}) {
super()
this.deviceId = deviceId
this.name = name
assertIdWithinFamily(deviceId)
if (name.trim().length === 0) {
throw new Error('new device name must not be blank')
}
}
serialize = (): SerializedUpdateDeviceNameAction => ({
type: 'UPDATE_DEVICE_NAME',
deviceId: this.deviceId,
name: this.name
})
static parse = ({ deviceId, name }: SerializedUpdateDeviceNameAction) => (
new UpdateDeviceNameAction({ deviceId, name })
)
}
export interface SerializedUpdateDeviceNameAction {
type: 'UPDATE_DEVICE_NAME'
deviceId: string
name: string
}

View file

@ -0,0 +1,79 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { NewPermissionStatus } from '../model/newpermissionstatus'
import { ProtectionLevel } from '../model/protectionlevel'
import { RuntimePermissionStatus } from '../model/runtimepermissionstatus'
import { AppLogicAction } from './basetypes'
export class UpdateDeviceStatusAction extends AppLogicAction {
readonly newProtetionLevel?: ProtectionLevel
readonly newUsageStatsPermissionStatus?: RuntimePermissionStatus
readonly newNotificationAccessPermission?: NewPermissionStatus
readonly newAppVersion?: number
readonly didReboot: boolean
constructor ({ newProtetionLevel, newUsageStatsPermissionStatus, newNotificationAccessPermission, newAppVersion, didReboot }: {
newProtetionLevel?: ProtectionLevel
newUsageStatsPermissionStatus?: RuntimePermissionStatus
newNotificationAccessPermission?: NewPermissionStatus
newAppVersion?: number
didReboot: boolean
}) {
super()
if (newAppVersion !== undefined) {
if (!Number.isSafeInteger(newAppVersion) || (newAppVersion < 0)) {
throw new Error('invalid new ap version')
}
}
this.newProtetionLevel = newProtetionLevel
this.newUsageStatsPermissionStatus = newUsageStatsPermissionStatus
this.newNotificationAccessPermission = newNotificationAccessPermission
this.newAppVersion = newAppVersion
this.didReboot = didReboot
}
serialize = (): SerializedUpdateDeviceStatusAction => ({
type: 'UPDATE_DEVICE_STATUS',
protectionLevel: this.newProtetionLevel,
usageStats: this.newUsageStatsPermissionStatus,
notificationAccess: this.newNotificationAccessPermission,
appVersion: this.newAppVersion,
didReboot: this.didReboot
})
static parse = ({ protectionLevel, usageStats, notificationAccess, appVersion, didReboot }: SerializedUpdateDeviceStatusAction) => (
new UpdateDeviceStatusAction({
newProtetionLevel: protectionLevel,
newUsageStatsPermissionStatus: usageStats,
newNotificationAccessPermission: notificationAccess,
newAppVersion: appVersion,
didReboot: !!didReboot
})
)
}
export interface SerializedUpdateDeviceStatusAction {
type: 'UPDATE_DEVICE_STATUS'
protectionLevel?: ProtectionLevel
usageStats?: RuntimePermissionStatus
notificationAccess?: NewPermissionStatus
appVersion?: number
didReboot?: boolean
}

View file

@ -0,0 +1,55 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateNetworkTimeVerificationAction extends ParentAction {
readonly deviceId: string
readonly mode: 'disabled' | 'if possible' | 'enabled'
constructor ({ deviceId, mode }: {
deviceId: string
mode: 'disabled' | 'if possible' | 'enabled'
}) {
super()
assertIdWithinFamily(deviceId)
this.deviceId = deviceId
this.mode = mode
}
serialize = (): SerialiizedUpdateNetworkTimeVerificationAction => ({
type: 'UPDATE_NETWORK_TIME_VERIFICATION',
deviceId: this.deviceId,
mode: this.mode
})
static parse = ({ deviceId, mode }: SerialiizedUpdateNetworkTimeVerificationAction) => (
new UpdateNetworkTimeVerificationAction({
deviceId,
mode
})
)
}
export interface SerialiizedUpdateNetworkTimeVerificationAction {
type: 'UPDATE_NETWORK_TIME_VERIFICATION'
deviceId: string
mode: 'disabled' | 'if possible' | 'enabled'
}

View file

@ -0,0 +1,65 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateParentNotificationFlagsAction extends ParentAction {
readonly parentId: string
readonly flags: number
readonly set: boolean
constructor ({ parentId, flags, set }: {
parentId: string
flags: number
set: boolean
}) {
super()
assertIdWithinFamily(parentId)
if (!Number.isSafeInteger(flags)) {
throw new Error('flags must be an integer')
}
if (flags < 0 || flags > 1) {
throw new Error('flags are out of the valid range')
}
this.parentId = parentId
this.flags = flags
this.set = set
}
serialize = (): SerializedUpdateParentNotificationFlagsAction => ({
type: 'UPDATE_PARENT_NOTIFICATION_FLAGS',
parentId: this.parentId,
flags: this.flags,
set: this.set
})
static parse = ({ parentId, flags, set }: SerializedUpdateParentNotificationFlagsAction) => (
new UpdateParentNotificationFlagsAction({ parentId, flags, set })
)
}
export interface SerializedUpdateParentNotificationFlagsAction {
type: 'UPDATE_PARENT_NOTIFICATION_FLAGS'
parentId: string
flags: number
set: boolean
}

View file

@ -0,0 +1,79 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateTimelimitRuleAction extends ParentAction {
readonly ruleId: string
readonly maximumTimeInMillis: number
readonly dayMask: number
readonly applyToExtraTimeUsage: boolean
constructor ({ ruleId, maximumTimeInMillis, dayMask, applyToExtraTimeUsage }: {
ruleId: string
maximumTimeInMillis: number
dayMask: number
applyToExtraTimeUsage: boolean
}) {
super()
this.ruleId = ruleId
this.maximumTimeInMillis = maximumTimeInMillis
this.dayMask = dayMask
this.applyToExtraTimeUsage = applyToExtraTimeUsage
assertIdWithinFamily(ruleId)
if (maximumTimeInMillis < 0 || (!Number.isSafeInteger(maximumTimeInMillis))) {
throw new Error('maximumTimeInMillis must be >= 0')
}
if (!(
Number.isSafeInteger(dayMask) ||
dayMask < 0 ||
dayMask > (1 | 2 | 4 | 8 | 16 | 32 | 64)
)) {
throw new Error('invalid day mask')
}
}
serialize = (): SerializedUpdateTimelimitRuleAction => ({
type: 'UPDATE_TIMELIMIT_RULE',
ruleId: this.ruleId,
time: this.maximumTimeInMillis,
days: this.dayMask,
extraTime: this.applyToExtraTimeUsage
})
static parse = ({ ruleId, time, days, extraTime }: SerializedUpdateTimelimitRuleAction) => (
new UpdateTimelimitRuleAction({
ruleId,
maximumTimeInMillis: time,
dayMask: days,
applyToExtraTimeUsage: extraTime
})
)
}
export interface SerializedUpdateTimelimitRuleAction {
type: 'UPDATE_TIMELIMIT_RULE'
ruleId: string
time: number
days: number
extraTime: boolean
}

130
src/api/auth.ts Normal file
View file

@ -0,0 +1,130 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { json } from 'body-parser'
import { Router } from 'express'
import { OAuth2Client } from 'google-auth-library'
import { BadRequest } from 'http-errors'
import { Database } from '../database'
import { createAuthTokenByMailAddress } from '../function/authentication'
import { sendLoginCode, signInByMailCode } from '../function/authentication/login-by-mail'
import {
isSendMailLoginCodeRequest,
isSignInByMailCodeRequest,
isSignInWithGoogleRequest
} from './validator'
const CLIENT_ID = process.env.GOOGLE_SIGN_IN_CLIENT_ID || ''
const client = new OAuth2Client(CLIENT_ID)
const getMailByGoogleAuthToken = async (idToken: string) => {
const ticket = await client.verifyIdToken({
idToken,
audience: CLIENT_ID
})
if (!ticket) {
throw new BadRequest()
}
const payload = ticket.getPayload()
if (!payload) {
throw new BadRequest()
}
if (!payload.email_verified) {
throw new BadRequest()
}
const mail = payload.email
if (!mail) {
throw new BadRequest()
}
if (!(
mail.endsWith('@gmail.com') ||
mail.endsWith('@googlemail.com')
)) {
throw new BadRequest()
}
return mail
}
export const createAuthRouter = (database: Database) => {
const router = Router()
router.post('/sign-in-with-google', json(), async (req, res, next) => {
try {
if (!isSignInWithGoogleRequest(req.body)) {
res.sendStatus(400)
return
}
const { googleAuthToken } = req.body
const mail = await getMailByGoogleAuthToken(googleAuthToken)
const mailAuthToken = await createAuthTokenByMailAddress({ mail, database })
res.json({
mailAuthToken
})
} catch (ex) {
next(ex)
}
})
router.post('/send-mail-login-code', json(), async (req, res, next) => {
try {
if (!isSendMailLoginCodeRequest(req.body)) {
throw new BadRequest()
}
const { mailLoginToken } = await sendLoginCode({
mail: req.body.mail,
locale: req.body.locale,
database
})
res.json({ mailLoginToken })
} catch (ex) {
next(ex)
}
})
router.post('/sign-in-by-mail-code', json(), async (req, res, next) => {
try {
if (!isSignInByMailCodeRequest(req.body)) {
throw new BadRequest()
}
const { mailAuthToken } = await signInByMailCode({
receivedCode: req.body.receivedCode,
mailLoginToken: req.body.mailLoginToken,
database
})
res.json({ mailAuthToken })
} catch (ex) {
next(ex)
}
})
return router
}

98
src/api/child.ts Normal file
View file

@ -0,0 +1,98 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest } from 'http-errors'
import { Database } from '../database'
import { addChildDevice } from '../function/child/add-device'
import { logoutAtPrimaryDevice } from '../function/child/logout-at-primary-device'
import { setPrimaryDevice } from '../function/child/set-primary-device'
import { WebsocketApi } from '../websocket'
import { isRegisterChildDeviceRequest, isRequestWithAuthToken, isUpdatePrimaryDeviceRequest } from './validator'
export const createChildRouter = ({ database, websocket }: {
database: Database,
websocket: WebsocketApi
}) => {
const router = Router()
router.post('/add-device', json(), async (req, res, next) => {
try {
if (!isRegisterChildDeviceRequest(req.body)) {
throw new BadRequest()
}
const { deviceAuthToken, deviceId } = await addChildDevice({
request: req.body,
database,
websocket
})
res.json({
deviceAuthToken,
ownDeviceId: deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/update-primary-device', json(), async (req, res, next) => {
try {
if (!isUpdatePrimaryDeviceRequest(req.body)) {
throw new BadRequest()
}
const response = await setPrimaryDevice({
database,
deviceAuthToken: req.body.authToken,
currentUserId: req.body.currentUserId,
websocket,
action: req.body.action
})
res.json({
status: response
})
} catch (ex) {
next(ex)
}
})
router.post('/logout-at-primary-device', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
await logoutAtPrimaryDevice({
deviceAuthToken: req.body.deviceAuthToken,
database,
websocket
})
res.json({
ok: true
})
} catch (ex) {
next(ex)
}
})
return router
}

50
src/api/index.ts Normal file
View file

@ -0,0 +1,50 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as express from 'express'
import { VisibleConnectedDevicesManager } from '../connected-devices'
import { Database } from '../database'
import { WebsocketApi } from '../websocket'
import { createAuthRouter } from './auth'
import { createChildRouter } from './child'
import { createParentRouter } from './parent'
import { createPurchaseRouter } from './purchase'
import { createSyncRouter } from './sync'
export const createApi = ({ database, websocket, connectedDevicesManager }: {
database: Database
websocket: WebsocketApi
connectedDevicesManager: VisibleConnectedDevicesManager
}) => {
const app = express()
app.disable('x-powered-by')
app.get('/time', (req, res) => {
res.json({
ms: Date.now()
})
})
app.use('/auth', createAuthRouter(database))
app.use('/child', createChildRouter({ database, websocket }))
app.use('/parent', createParentRouter({ database, websocket }))
app.use('/purchase', createPurchaseRouter({ database, websocket }))
app.use('/sync', createSyncRouter({ database, websocket, connectedDevicesManager }))
return app
}

257
src/api/parent.ts Normal file
View file

@ -0,0 +1,257 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Unauthorized } from 'http-errors'
import { Database } from '../database'
import { removeDevice } from '../function/device/remove-device'
import { canRecoverPassword } from '../function/parent/can-recover-password'
import { createAddDeviceToken } from '../function/parent/create-add-device-token'
import { createFamily } from '../function/parent/create-family'
import { getStatusByMailToken } from '../function/parent/get-status-by-mail-address'
import { linkMailAddress } from '../function/parent/link-mail-address'
import { recoverParentPassword } from '../function/parent/recover-parent-password'
import { signInIntoFamily } from '../function/parent/sign-in-into-family'
import { WebsocketApi } from '../websocket'
import {
isCanRecoverPasswordRequest, isCreateFamilyByMailTokenRequest,
isCreateRegisterDeviceTokenRequest, isLinkParentMailAddressRequest,
isMailAuthTokenRequestBody, isRecoverParentPasswordRequest,
isRemoveDeviceRequest, isSignIntoFamilyRequest
} from './validator'
export const createParentRouter = ({ database, websocket }: {database: Database, websocket: WebsocketApi}) => {
const router = Router()
router.post('/get-status-by-mail-address', json(), async (req, res, next) => {
try {
if (!isMailAuthTokenRequestBody(req.body)) {
throw new BadRequest()
}
const { mailAuthToken } = req.body
const { status, mail } = await getStatusByMailToken({ database, mailAuthToken })
res.json({ status, mail })
} catch (ex) {
next(ex)
}
})
router.post('/create-family', json(), async (req, res, next) => {
try {
if (!isCreateFamilyByMailTokenRequest(req.body)) {
throw new BadRequest()
}
const result = await createFamily({
database,
firstParentDevice: req.body.parentDevice,
mailAuthToken: req.body.mailAuthToken,
password: req.body.parentPassword,
deviceName: req.body.deviceName,
parentName: req.body.parentName,
timeZone: req.body.timeZone
})
res.json({
deviceAuthToken: result.deviceAuthToken,
ownDeviceId: result.deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/sign-in-into-family', json(), async (req, res, next) => {
try {
if (!isSignIntoFamilyRequest(req.body)) {
throw new BadRequest()
}
const result = await signInIntoFamily({
database,
newDeviceInfo: req.body.parentDevice,
mailAuthToken: req.body.mailAuthToken,
deviceName: req.body.deviceName,
websocket
})
res.json({
deviceAuthToken: result.deviceAuthToken,
ownDeviceId: result.deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/can-recover-password', json(), async (req, res, next) => {
try {
if (!isCanRecoverPasswordRequest(req.body)) {
throw new BadRequest()
}
const canRecover = await canRecoverPassword({
database,
parentUserId: req.body.parentUserId,
mailAuthToken: req.body.mailAuthToken
})
res.json({ canRecover })
} catch (ex) {
next(ex)
}
})
router.post('/recover-parent-password', json(), async (req, res, next) => {
try {
if (!isRecoverParentPasswordRequest(req.body)) {
throw new BadRequest()
}
await recoverParentPassword({
database,
websocket,
password: req.body.password,
mailAuthToken: req.body.mailAuthToken
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
async function assertAuthValidAndReturnDeviceEntry ({ deviceAuthToken, parentId, secondPasswordHash }: {
deviceAuthToken: string
parentId: string
secondPasswordHash: string
}) {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken: deviceAuthToken
}
})
if (!deviceEntry) {
throw new Unauthorized()
}
if (secondPasswordHash === 'device') {
if (!deviceEntry.isUserKeptSignedIn) {
throw new Unauthorized()
}
const parentEntry = await database.user.findOne({
where: {
familyId: deviceEntry.familyId,
type: 'parent',
userId: deviceEntry.currentUserId
}
})
if (!parentEntry) {
throw new Unauthorized()
}
} else {
const parentEntry = await database.user.findOne({
where: {
familyId: deviceEntry.familyId,
type: 'parent',
userId: parentId,
secondPasswordHash: secondPasswordHash
}
})
if (!parentEntry) {
throw new Unauthorized()
}
}
return deviceEntry
}
router.post('/create-add-device-token', json(), async (req, res, next) => {
try {
if (!isCreateRegisterDeviceTokenRequest(req.body)) {
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
const { token, deviceId } = await createAddDeviceToken({ familyId: deviceEntry.familyId, database })
res.json({ token, deviceId })
} catch (ex) {
next(ex)
}
})
router.post('/link-mail-address', json(), async (req, res, next) => {
try {
if (!isLinkParentMailAddressRequest(req.body)) {
throw new BadRequest()
}
await linkMailAddress({
mailAuthToken: req.body.mailAuthToken,
deviceAuthToken: req.body.deviceAuthToken,
parentPasswordSecondHash: req.body.parentPasswordSecondHash,
parentUserId: req.body.parentUserId,
websocket,
database
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
router.post('/remove-device', json(), async (req, res, next) => {
try {
if (!isRemoveDeviceRequest(req.body)) {
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentUserId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
await removeDevice({
database,
familyId: deviceEntry.familyId,
deviceId: req.body.deviceId,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
return router
}

129
src/api/purchase.ts Normal file
View file

@ -0,0 +1,129 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Conflict, Unauthorized } from 'http-errors'
import { Database } from '../database'
import {
addPurchase,
areGooglePlayPaymentsPossible,
canDoNextPurchase,
isGooglePlayPurchaseSignatureValid,
requireFamilyEntry
} from '../function/purchase'
import { WebsocketApi } from '../websocket'
import { isCanDoPurchaseRequest, isFinishPurchaseByGooglePlayRequest } from './validator'
export const createPurchaseRouter = ({ database, websocket }: {
database: Database
websocket: WebsocketApi
}) => {
const router = Router()
router.post('/can-do-purchase', json(), async (req, res, next) => {
if (!areGooglePlayPaymentsPossible) {
res.json({ canDoPurchase: 'no because not supported by the server' })
return
}
try {
if (!isCanDoPurchaseRequest(req.body)) {
throw new BadRequest()
}
const familyEntry = await requireFamilyEntry({
database,
deviceAuthToken: req.body.deviceAuthToken
})
const result = canDoNextPurchase({ fullVersionUntil: parseInt(familyEntry.fullVersionUntil, 10) })
res.json({
canDoPurchase: result ? 'yes' : 'no due to old purchase'
})
} catch (ex) {
next(ex)
}
})
router.post('/finish-purchase-by-google-play', json(), async (req, res, next) => {
try {
if (!isFinishPurchaseByGooglePlayRequest(req.body)) {
throw new BadRequest()
}
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
},
attributes: ['familyId']
})
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
const deviceEntry = {
familyId: deviceEntryUnsafe.familyId
}
if (!isGooglePlayPurchaseSignatureValid({
receipt: req.body.receipt,
signature: req.body.signature
})) {
throw new Conflict()
}
const receipt = JSON.parse(req.body.receipt)
if (typeof receipt !== 'object') {
throw new Conflict()
}
let type: 'month' | 'year'
if (receipt.productId === 'premium_year_2018') {
type = 'year'
} else if (receipt.productId === 'premium_month_2018') {
type = 'month'
} else {
throw new Conflict()
}
const orderId = receipt.orderId
if (typeof orderId !== 'string') {
throw new Conflict()
}
await addPurchase({
database,
familyId: deviceEntry.familyId,
type,
transactionId: orderId,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
return router
}

147
src/api/schema.ts Normal file
View file

@ -0,0 +1,147 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { ClientDataStatus } from '../object/clientdatastatus'
import { optionalPasswordRegex, optionalSaltRegex } from '../util/password'
export interface ClientPushChangesRequest {
deviceAuthToken: string
actions: Array<{
encodedAction: string
sequenceNumber: number
integrity: string
type: 'appLogic' | 'parent' | 'child'
userId: string
}>
}
export interface ClientPullChangesRequest {
deviceAuthToken: string
status: ClientDataStatus
}
export interface SignInWithGoogleRequest {
googleAuthToken: string
}
export interface MailAuthTokenRequestBody {
mailAuthToken: string
}
export interface NewDeviceInfo {
model: string
}
export interface ParentPassword {
hash: string
secondHash: string
secondSalt: string
}
export const assertParentPasswordValid = (password: ParentPassword) => {
if (password.hash === '' || password.secondHash === '' || password.secondSalt === '') {
throw new Error('missing fields at parent password')
}
if (!(optionalPasswordRegex.test(password.hash) && optionalPasswordRegex.test(password.secondHash) && optionalSaltRegex.test(password.secondSalt))) {
throw new Error('invalid parent password')
}
}
export interface CreateFamilyByMailTokenRequest {
mailAuthToken: string
parentPassword: ParentPassword
parentDevice: NewDeviceInfo
deviceName: string
timeZone: string
parentName: string
}
export interface SignIntoFamilyRequest {
mailAuthToken: string
parentDevice: NewDeviceInfo
deviceName: string
}
export interface RecoverParentPasswordRequest {
mailAuthToken: string
password: ParentPassword
}
export interface CanRecoverPasswordRequest {
mailAuthToken: string
parentUserId: string
}
export interface RegisterChildDeviceRequest {
registerToken: string
childDevice: NewDeviceInfo
deviceName: string
}
export interface CreateRegisterDeviceTokenRequest {
deviceAuthToken: string
parentId: string
parentPasswordSecondHash: string
}
export interface CanDoPurchaseRequest {
type: 'googleplay' | 'any'
deviceAuthToken: string
}
export interface FinishPurchaseByGooglePlayRequest {
deviceAuthToken: string
receipt: string
signature: string
}
export interface LinkParentMailAddressRequest {
mailAuthToken: string
deviceAuthToken: string
parentUserId: string
parentPasswordSecondHash: string
}
export interface UpdatePrimaryDeviceRequest {
action: 'set this device' | 'unset this device'
currentUserId: string
authToken: string
}
export interface RemoveDeviceRequest {
deviceAuthToken: string
parentUserId: string
parentPasswordSecondHash: string
deviceId: string
}
export interface RequestWithAuthToken {
deviceAuthToken: string
}
export interface SendMailLoginCodeRequest {
mail: string
locale: string
}
export interface SignInByMailCodeRequest {
mailLoginToken: string
receivedCode: string
}
export { SerializedParentAction, SerializedChildAction, SerializedAppLogicAction } from '../action/serialization'

151
src/api/sync.ts Normal file
View file

@ -0,0 +1,151 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Unauthorized } from 'http-errors'
import { VisibleConnectedDevicesManager } from '../connected-devices'
import { Database } from '../database'
import { reportDeviceRemoved } from '../function/device/report-device-removed'
import { applyActionsFromDevice } from '../function/sync/apply-actions'
import { generateServerDataStatus } from '../function/sync/get-server-data-status'
import { WebsocketApi } from '../websocket'
import { isClientPullChangesRequest, isClientPushChangesRequest, isRequestWithAuthToken } from './validator'
const getRoundedTimestampForLastConnectivity = () => {
const now = Date.now()
return now - (now % (1000 * 60 * 60 * 12 /* 12 hours */))
}
export const createSyncRouter = ({ database, websocket, connectedDevicesManager }: {
database: Database
websocket: WebsocketApi
connectedDevicesManager: VisibleConnectedDevicesManager
}) => {
const router = Router()
router.post('/push-actions', json(), async (req, res, next) => {
try {
if (!isClientPushChangesRequest(req.body)) {
throw new BadRequest()
}
const { shouldDoFullSync } = await applyActionsFromDevice({
request: req.body,
database,
websocket,
connectedDevicesManager
})
res.json({
shouldDoFullSync
})
} catch (ex) {
next(ex)
}
})
router.post('/pull-status', json(), async (req, res, next) => {
try {
const { body } = req
if (!isClientPullChangesRequest(body)) {
throw new BadRequest()
}
await database.transaction(async (transaction) => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: body.deviceAuthToken
},
attributes: ['familyId', 'lastConnectivity'],
transaction
})
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
const { familyId, lastConnectivity } = deviceEntryUnsafe
const now = getRoundedTimestampForLastConnectivity()
if (parseInt(lastConnectivity, 10) !== now) {
await database.device.update({
lastConnectivity: now.toString(10)
}, {
where: {
deviceAuthToken: body.deviceAuthToken
},
transaction
})
}
const serverStatus = await generateServerDataStatus({
database,
familyId,
clientStatus: body.status,
transaction
})
res.json(serverStatus)
})
} catch (ex) {
next(ex)
}
})
router.post('/report-removed', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
await reportDeviceRemoved({
database,
deviceAuthToken: req.body.deviceAuthToken,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
router.post('/is-device-removed', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
const removedEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
}
})
res.json({
isDeviceRemoved: !!removedEntry
})
} catch (ex) {
next(ex)
}
})
return router
}

1681
src/api/validator.ts Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,214 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { EventEmitter } from 'events'
import { Database } from '../database'
export class ConnectedDevicesManager {
private deviceConnectionCounters = new Map<string, number>()
// event name = key, value = boolean/ isConnected
deviceConnectionChangeEmitter = new EventEmitter()
static buildKey = ({ familyId, deviceId }: {familyId: string, deviceId: string}) => `${familyId}_${deviceId}`
reportDeviceConnected = ({ key }: {key: string}) => {
const oldValue = this.deviceConnectionCounters.get(key) || 0
const newValue = oldValue + 1
this.deviceConnectionCounters.set(key, newValue)
if (oldValue === 0) {
this.deviceConnectionChangeEmitter.emit(key, true)
}
}
reportDeviceDisconnected = ({ key }: {key: string}) => {
const oldValue = this.deviceConnectionCounters.get(key) || 0
const newValue = Math.max(0, oldValue - 1)
if (newValue === 0) {
this.deviceConnectionCounters.delete(key)
} else {
this.deviceConnectionCounters.set(key, newValue)
}
if (oldValue !== 0 && newValue === 0) {
this.deviceConnectionChangeEmitter.emit(key, false)
}
}
isDeviceConnected = ({ key }: {key: string}) => (
this.deviceConnectionCounters.has(key) &&
(this.deviceConnectionCounters.get(key) !== 0)
)
}
export class VisibleConnectedDevicesManager {
connectedDevicesManager = new ConnectedDevicesManager()
private database: Database
constructor ({ database }: {
database: Database
}) {
this.database = database
}
private familyDeviceShareConnectedChangeEmitter = new EventEmitter()
notifyShareConnectedChanged = ({ familyId, deviceId, showDeviceConnected }: { familyId: string, deviceId: string, showDeviceConnected: boolean }) => {
this.familyDeviceShareConnectedChangeEmitter.emit(familyId, { deviceId, showDeviceConnected })
}
observeConnectedDevicesOfFamily = ({ familyId, listener }: {
familyId: string
listener: (deviceIds: Array<string>) => void
}): {
shutdown: () => void
} => {
let observesDevices = new Set<string>()
let devicesWithSharingEnabled = new Set<string>()
let connectedDevices = new Set<string>()
let sentConnectedDevices = new Set<string>()
let hasShutDown = false
let shutdownHooks: Array<() => void> = []
const shutdown = () => {
hasShutDown = true
shutdownHooks.forEach((hook) => hook())
}
const sendStatus = () => {
if (hasShutDown) {
return
}
let result: Array<string> = []
sentConnectedDevices.forEach((deviceId) => result.push(deviceId))
listener(result)
}
const addDevice = ({ deviceId, showDeviceConnected }: {
deviceId: string
showDeviceConnected: boolean
}) => {
const key = ConnectedDevicesManager.buildKey({ familyId, deviceId })
const isConnected = this.connectedDevicesManager.isDeviceConnected({ key })
if (!observesDevices.has(deviceId)) {
observesDevices.add(deviceId)
if (isConnected) {
connectedDevices.add(deviceId)
}
if (!hasShutDown) {
const listener = (nowConnected: boolean) => {
const oldConnected = connectedDevices.has(deviceId)
if (oldConnected !== nowConnected) {
if (nowConnected) {
connectedDevices.add(deviceId)
if (devicesWithSharingEnabled.has(deviceId)) {
sentConnectedDevices.add(deviceId)
sendStatus()
}
} else {
connectedDevices.delete(deviceId)
if (devicesWithSharingEnabled.has(deviceId)) {
sentConnectedDevices.delete(deviceId)
sendStatus()
}
}
}
}
this.connectedDevicesManager.deviceConnectionChangeEmitter.addListener(key, listener)
shutdownHooks.push(() => {
this.connectedDevicesManager.deviceConnectionChangeEmitter.removeListener(key, listener)
})
}
}
if (showDeviceConnected) {
if (!devicesWithSharingEnabled.has(deviceId)) {
devicesWithSharingEnabled.add(deviceId)
}
if (isConnected) {
if (!sentConnectedDevices.has(deviceId)) {
sentConnectedDevices.add(deviceId)
sendStatus()
}
}
} else {
if (devicesWithSharingEnabled.has(deviceId)) {
devicesWithSharingEnabled.delete(deviceId)
if (sentConnectedDevices.has(deviceId)) {
sentConnectedDevices.delete(deviceId)
sendStatus()
}
}
}
}
// add all current devices
;(async () => {
const devicesUnsafe = await this.database.device.findAll({
where: {
familyId
},
attributes: [
'deviceId',
'showDeviceConnected'
]
})
const devices = devicesUnsafe.map(({ deviceId, showDeviceConnected }) => ({
deviceId, showDeviceConnected
}))
devices.forEach(({ deviceId, showDeviceConnected }) => {
addDevice({ deviceId, showDeviceConnected })
})
})().catch((ex) => { /* ignore */ })
{
// add all new devices + apply changes of sharing
const listener = ({ deviceId, showDeviceConnected }: {
deviceId: string
showDeviceConnected: boolean
}) => {
addDevice({
deviceId,
showDeviceConnected
})
}
this.familyDeviceShareConnectedChangeEmitter.addListener(familyId, listener)
shutdownHooks.push(() => this.familyDeviceShareConnectedChangeEmitter.removeListener(familyId, listener))
}
return { shutdown }
}
}

View file

@ -0,0 +1,42 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { familyIdColumn, idWithinFamilyColumn, labelColumn, timestampColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface AddDeviceTokenAttributes {
token: string
familyId: string
deviceId: string
createdAt: string
}
export type AddDeviceTokenInstance = Sequelize.Instance<AddDeviceTokenAttributes> & AddDeviceTokenAttributes
export type AddDeviceTokenModel = Sequelize.Model<AddDeviceTokenInstance, AddDeviceTokenAttributes>
export const attributes: SequelizeAttributes<AddDeviceTokenAttributes> = {
token: {
...labelColumn,
primaryKey: true
},
familyId: { ...familyIdColumn },
deviceId: { ...idWithinFamilyColumn },
createdAt: { ...timestampColumn }
}
export const createAddDeviceTokenModel = (sequelize: Sequelize.Sequelize): AddDeviceTokenModel => sequelize.define<AddDeviceTokenInstance, AddDeviceTokenInstance>('AddDeviceToken', attributes)

57
src/database/app.ts Normal file
View file

@ -0,0 +1,57 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { AppRecommendation, appRecommendationValues } from '../model/apprecommendation'
import { booleanColumn, createEnumColumn, familyIdColumn, idWithinFamilyColumn, optionalLabelColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface AppAttributes {
familyId: string
deviceId: string
packageName: string
title: string
isLaunchable: boolean
recommendation: AppRecommendation
}
export type AppInstance = Sequelize.Instance<AppAttributes> & AppAttributes
export type AppModel = Sequelize.Model<AppInstance, AppAttributes>
export const attributes: SequelizeAttributes<AppAttributes> = {
familyId: {
...familyIdColumn,
primaryKey: true
},
deviceId: {
...idWithinFamilyColumn,
primaryKey: true
},
packageName: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
},
primaryKey: true
},
title: { ...optionalLabelColumn },
isLaunchable: { ...booleanColumn },
recommendation: createEnumColumn(appRecommendationValues)
}
export const createAppModel = (sequelize: Sequelize.Sequelize): AppModel => sequelize.define<AppInstance, AppAttributes>('App', attributes)

46
src/database/authtoken.ts Normal file
View file

@ -0,0 +1,46 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { authTokenColumn, timestampColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface AuthTokenAttributes {
token: string
mail: string
createdAt: string
}
export type AuthTokenInstance = Sequelize.Instance<AuthTokenAttributes> & AuthTokenAttributes
export type AuthTokenModel = Sequelize.Model<AuthTokenInstance, AuthTokenAttributes>
export const attributes: SequelizeAttributes<AuthTokenAttributes> = {
token: {
...authTokenColumn,
primaryKey: true
},
mail: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
createdAt: { ...timestampColumn }
}
export const createAuthtokenModel = (sequelize: Sequelize.Sequelize): AuthTokenModel => sequelize.define<AuthTokenInstance, AuthTokenAttributes>('AuthToken', attributes)

90
src/database/category.ts Normal file
View file

@ -0,0 +1,90 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { serializedBitmaskRegex } from '../util/bitmask'
import { booleanColumn, familyIdColumn, idWithinFamilyColumn, labelColumn, optionalIdWithinFamilyColumn, versionColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface CategoryAttributesVersion1 {
familyId: string
categoryId: string
childId: string
title: string
blockedMinutesInWeek: string
extraTimeInMillis: number
temporarilyBlocked: boolean
baseVersion: string
assignedAppsVersion: string
timeLimitRulesVersion: string
usedTimesVersion: string
}
export interface CategoryAttributesVersion2 {
parentCategoryId: string
}
export type CategoryAttributes = CategoryAttributesVersion1 & CategoryAttributesVersion2
export type CategoryInstance = Sequelize.Instance<CategoryAttributes> & CategoryAttributes
export type CategoryModel = Sequelize.Model<CategoryInstance, CategoryAttributes>
export const attributesVersion1: SequelizeAttributes<CategoryAttributesVersion1> = {
familyId: {
...familyIdColumn,
primaryKey: true
},
categoryId: {
...idWithinFamilyColumn,
primaryKey: true
},
childId: { ...idWithinFamilyColumn },
title: { ...labelColumn },
blockedMinutesInWeek: {
type: Sequelize.TEXT,
allowNull: false,
validate: {
is: serializedBitmaskRegex
}
},
extraTimeInMillis: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
min: 0
}
},
temporarilyBlocked: { ...booleanColumn },
baseVersion: { ...versionColumn },
assignedAppsVersion: { ...versionColumn },
timeLimitRulesVersion: { ...versionColumn },
usedTimesVersion: { ...versionColumn }
}
export const attributesVersion2: SequelizeAttributes<CategoryAttributesVersion2> = {
parentCategoryId: {
...optionalIdWithinFamilyColumn,
defaultValue: ''
}
}
export const attributes: SequelizeAttributes<CategoryAttributes> = {
...attributesVersion1,
...attributesVersion2
}
export const createCategoryModel = (sequelize: Sequelize.Sequelize): CategoryModel => sequelize.define<CategoryInstance, CategoryAttributes>('Category', attributes)

View file

@ -0,0 +1,50 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { familyIdColumn, idWithinFamilyColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface CategoryAppAttributes {
familyId: string
categoryId: string
packageName: string
}
export type CategoryAppInstance = Sequelize.Instance<CategoryAppAttributes> & CategoryAppAttributes
export type CategoryAppModel = Sequelize.Model<CategoryAppInstance, CategoryAppAttributes>
export const attributes: SequelizeAttributes<CategoryAppAttributes> = {
familyId: {
...familyIdColumn,
primaryKey: true
},
categoryId: {
...idWithinFamilyColumn,
primaryKey: true
},
packageName: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
},
primaryKey: true
}
}
export const createCategoryAppModel = (sequelize: Sequelize.Sequelize): CategoryAppModel => sequelize.define<CategoryAppInstance, CategoryAppAttributes>('CategoryApp', attributes)

97
src/database/columns.ts Normal file
View file

@ -0,0 +1,97 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
export const familyIdColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING(10),
allowNull: false,
validate: {
notEmpty: true,
is: /^[a-zA-Z0-9]{10}$/
}
}
export const idWithinFamilyColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING(6),
allowNull: false,
validate: {
notEmpty: true,
is: /^[a-zA-Z0-9]{6}$/
}
}
export const optionalIdWithinFamilyColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING(6),
allowNull: false,
validate: {
is: /^([a-zA-Z0-9]{6})?$/
}
}
export const versionColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING(4),
allowNull: false,
validate: {
notEmpty: true,
is: /^[a-zA-Z0-9]{4}$/
}
}
export const labelColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
}
export const optionalLabelColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING,
allowNull: false
}
export const createEnumColumn = (possibleValues: Array<string>): Sequelize.DefineAttributeColumnOptions => ({
type: Sequelize.STRING,
allowNull: false,
validate: {
isIn: [possibleValues],
notEmpty: true
}
})
// warning: this results in an string field
export const timestampColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.BIGINT,
allowNull: false,
validate: {
min: 0
}
}
export const booleanColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.BOOLEAN,
allowNull: false
}
export const authTokenColumn: Sequelize.DefineAttributeColumnOptions = {
type: Sequelize.STRING(32),
allowNull: false,
validate: {
notEmpty: true,
is: /^[a-zA-Z0-9]{32}$/
}
}

204
src/database/device.ts Normal file
View file

@ -0,0 +1,204 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { NewPermissionStatus, newPermissionStatusValues } from '../model/newpermissionstatus'
import { ProtectionLevel, protetionLevels } from '../model/protectionlevel'
import { RuntimePermissionStatus, runtimePermissionStatusValues } from '../model/runtimepermissionstatus'
import { authTokenColumn, booleanColumn, createEnumColumn, familyIdColumn, idWithinFamilyColumn, labelColumn, optionalIdWithinFamilyColumn, timestampColumn, versionColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface DeviceAttributesVersion1 {
familyId: string
deviceId: string
name: string
model: string
addedAt: string
currentUserId: string
installedAppsVersion: string
deviceAuthToken: string
networkTime: 'disabled' | 'if possible' | 'enabled'
nextSequenceNumber: number
currentProtectionLevel: ProtectionLevel
highestProtectionLevel: ProtectionLevel
currentUsageStatsPermission: RuntimePermissionStatus
highestUsageStatsPermission: RuntimePermissionStatus
currentNotificationAccessPermission: NewPermissionStatus
highestNotificationAccessPermission: NewPermissionStatus
currentAppVersion: number
highestAppVersion: number
triedDisablingDeviceAdmin: boolean
hadManipulation: boolean
}
export interface DeviceAttributesVersion2 {
lastConnectivity: string
notSeenForLongTime: boolean
didDeviceReportUninstall: boolean
}
export interface DeviceAttributesVersion3 {
isUserKeptSignedIn: boolean
}
export interface DeviceAttributesVersion4 {
showDeviceConnected: boolean
}
export interface DeviceAttributesVersion5 {
defaultUserId: string
defaultUserTimeout: number
}
export interface DeviceAttributesVersion6 {
didReboot: boolean
considerRebootManipulation: boolean
}
export type DeviceAttributes = DeviceAttributesVersion1 & DeviceAttributesVersion2 &
DeviceAttributesVersion3 & DeviceAttributesVersion4 & DeviceAttributesVersion5 &
DeviceAttributesVersion6
export type DeviceInstance = Sequelize.Instance<DeviceAttributes> & DeviceAttributes
export type DeviceModel = Sequelize.Model<DeviceInstance, DeviceAttributes>
export const attributesVersion1: SequelizeAttributes<DeviceAttributesVersion1> = {
familyId: {
...familyIdColumn,
primaryKey: true
},
deviceId: {
...idWithinFamilyColumn,
primaryKey: true
},
name: { ...labelColumn },
model: { ...labelColumn },
addedAt: { ...timestampColumn },
currentUserId: { ...optionalIdWithinFamilyColumn },
installedAppsVersion: { ...versionColumn },
deviceAuthToken: { ...authTokenColumn },
networkTime: createEnumColumn(['disabled', 'if possible', 'enabled']),
nextSequenceNumber: {
type: Sequelize.INTEGER,
allowNull: false
},
currentProtectionLevel: createEnumColumn(protetionLevels),
highestProtectionLevel: createEnumColumn(protetionLevels),
currentUsageStatsPermission: createEnumColumn(runtimePermissionStatusValues),
highestUsageStatsPermission: createEnumColumn(runtimePermissionStatusValues),
currentNotificationAccessPermission: createEnumColumn(newPermissionStatusValues),
highestNotificationAccessPermission: createEnumColumn(newPermissionStatusValues),
currentAppVersion: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
min: 0
}
},
highestAppVersion: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
min: 0
}
},
triedDisablingDeviceAdmin: { ...booleanColumn },
hadManipulation: { ...booleanColumn }
}
export const attributesVersion2: SequelizeAttributes<DeviceAttributesVersion2> = {
lastConnectivity: {
...timestampColumn,
defaultValue: 0
},
notSeenForLongTime: {
...booleanColumn,
defaultValue: false
},
didDeviceReportUninstall: {
...booleanColumn,
defaultValue: false
}
}
export const attributesVersion3: SequelizeAttributes<DeviceAttributesVersion3> = {
isUserKeptSignedIn: {
...booleanColumn,
defaultValue: false
}
}
export const attributesVersion4: SequelizeAttributes<DeviceAttributesVersion4> = {
showDeviceConnected: {
...booleanColumn,
defaultValue: false
}
}
export const attributesVersion5: SequelizeAttributes<DeviceAttributesVersion5> = {
defaultUserId: {
...optionalIdWithinFamilyColumn,
defaultValue: ''
},
defaultUserTimeout: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
validate: {
min: 0
}
}
}
export const attributesVersion6: SequelizeAttributes<DeviceAttributesVersion6> = {
didReboot: {
...booleanColumn,
defaultValue: false
},
considerRebootManipulation: {
...booleanColumn,
defaultValue: false
}
}
export const attributes: SequelizeAttributes<DeviceAttributes> = {
...attributesVersion1,
...attributesVersion2,
...attributesVersion3,
...attributesVersion4,
...attributesVersion5,
...attributesVersion6
}
export const createDeviceModel = (sequelize: Sequelize.Sequelize): DeviceModel => sequelize.define<DeviceInstance, DeviceAttributes>('Device', attributes)
export const hasDeviceManipulation = (device: DeviceAttributes) => {
const manipulationOfProtectionLevel = device.currentProtectionLevel !== device.highestProtectionLevel
const manipulationOfUsageStats = device.currentUsageStatsPermission !== device.highestUsageStatsPermission
const manipulationOfNotificationAccess = device.currentNotificationAccessPermission !== device.highestNotificationAccessPermission
const manipulationOfAppVersion = device.currentAppVersion !== device.highestAppVersion
const hasActiveManipulationWarning = manipulationOfProtectionLevel ||
manipulationOfUsageStats ||
manipulationOfNotificationAccess ||
manipulationOfAppVersion ||
device.triedDisablingDeviceAdmin ||
device.didReboot
const hasAnyManipulation = hasActiveManipulationWarning || device.hadManipulation
return hasAnyManipulation
}

48
src/database/family.ts Normal file
View file

@ -0,0 +1,48 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { booleanColumn, familyIdColumn, optionalLabelColumn, timestampColumn, versionColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface FamilyAttributes {
familyId: string
name: string
createdAt: string
userListVersion: string
deviceListVersion: string
fullVersionUntil: string
hasFullVersion: boolean
}
export type FamilyInstance = Sequelize.Instance<FamilyAttributes> & FamilyAttributes
export type FamilyModel = Sequelize.Model<FamilyInstance, FamilyAttributes>
export const attributes: SequelizeAttributes<FamilyAttributes> = {
familyId: {
...familyIdColumn,
primaryKey: true
},
name: { ...optionalLabelColumn },
createdAt: { ...timestampColumn },
userListVersion: { ...versionColumn },
deviceListVersion: { ...versionColumn },
fullVersionUntil: { ...timestampColumn },
hasFullVersion: { ...booleanColumn }
}
export const createFamilyModel = (sequelize: Sequelize.Sequelize): FamilyModel => sequelize.define<FamilyInstance, FamilyAttributes>('Family', attributes)

79
src/database/index.ts Normal file
View file

@ -0,0 +1,79 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { AddDeviceTokenModel, createAddDeviceTokenModel } from './adddevicetoken'
import { AppModel, createAppModel } from './app'
import { AuthTokenModel, createAuthtokenModel } from './authtoken'
import { CategoryModel, createCategoryModel } from './category'
import { CategoryAppModel, createCategoryAppModel } from './categoryapp'
import { createDeviceModel, DeviceModel } from './device'
import { createFamilyModel, FamilyModel } from './family'
import { createMailLoginTokenModel, MailLoginTokenModel } from './maillogintoken'
import { createUmzug } from './migration/umzug'
import { createOldDeviceModel, OldDeviceModel } from './olddevice'
import { createPurchaseModel, PurchaseModel } from './purchase'
import { createTimelimitRuleModel, TimelimitRuleModel } from './timelimitrule'
import { createUsedTimeModel, UsedTimeModel } from './usedtime'
import { createUserModel, UserModel } from './user'
export interface Database {
addDeviceToken: AddDeviceTokenModel
authtoken: AuthTokenModel
app: AppModel
category: CategoryModel
categoryApp: CategoryAppModel
device: DeviceModel
family: FamilyModel
mailLoginToken: MailLoginTokenModel
oldDevice: OldDeviceModel
purchase: PurchaseModel
timelimitRule: TimelimitRuleModel
usedTime: UsedTimeModel
user: UserModel
transaction: <T> (autoCallback: (t: Sequelize.Transaction) => Promise<T>) => Promise<T>
}
const createDatabase = (sequelize: Sequelize.Sequelize): Database => ({
addDeviceToken: createAddDeviceTokenModel(sequelize),
authtoken: createAuthtokenModel(sequelize),
app: createAppModel(sequelize),
category: createCategoryModel(sequelize),
categoryApp: createCategoryAppModel(sequelize),
device: createDeviceModel(sequelize),
family: createFamilyModel(sequelize),
mailLoginToken: createMailLoginTokenModel(sequelize),
oldDevice: createOldDeviceModel(sequelize),
purchase: createPurchaseModel(sequelize),
timelimitRule: createTimelimitRuleModel(sequelize),
usedTime: createUsedTimeModel(sequelize),
user: createUserModel(sequelize),
transaction: <T> (autoCallback: (transaction: Sequelize.Transaction) => Promise<T>) => (sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
}, autoCallback) as any) as Promise<T>
})
export const sequelize = new Sequelize(process.env.DATABASE_URL || 'sqlite://test.db', {
define: {
timestamps: false
},
operatorsAliases: false,
logging: false
})
export const defaultDatabase = createDatabase(sequelize)
export const defaultUmzug = createUmzug(sequelize)

View file

@ -0,0 +1,62 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { authTokenColumn, timestampColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface MailLoginTokenAttributes {
mailLoginToken: string
receivedCode: string
mail: string
createdAt: string
remainingAttempts: number
}
export type MailLoginTokenInstance = Sequelize.Instance<MailLoginTokenAttributes> & MailLoginTokenAttributes
export type MailLoginTokenModel = Sequelize.Model<MailLoginTokenInstance, MailLoginTokenAttributes>
export const attributes: SequelizeAttributes<MailLoginTokenAttributes> = {
mailLoginToken: {
...authTokenColumn,
primaryKey: true
},
receivedCode: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
mail: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
createdAt: { ...timestampColumn },
remainingAttempts: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
min: 0
}
}
}
export const createMailLoginTokenModel = (sequelize: Sequelize.Sequelize): MailLoginTokenModel => sequelize.define<MailLoginTokenInstance, MailLoginTokenAttributes>('MailLoginToken', attributes)

View file

@ -0,0 +1,51 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributes as addDeviceTokenAttributes } from '../../adddevicetoken'
import { attributes as appAttributes } from '../../app'
import { attributes as authTokenAttributes } from '../../authtoken'
import { attributesVersion1 as categoryAttributes } from '../../category'
import { attributes as categoryAppAttributes } from '../../categoryapp'
import { attributesVersion1 as deviceAttributes } from '../../device'
import { attributes as familyAttributes } from '../../family'
import { attributes as purchaseAttributes } from '../../purchase'
import { attributes as timelimitruleAttributes } from '../../timelimitrule'
import { attributesVersion1 as usedTimeAttribute } from '../../usedtime'
import { attributesVersion1 as userAttributes } from '../../user'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.createTable('AddDeviceTokens', addDeviceTokenAttributes, { transaction })
await queryInterface.createTable('Apps', appAttributes, { transaction })
await queryInterface.createTable('AuthTokens', authTokenAttributes, { transaction })
await queryInterface.createTable('Categories', categoryAttributes, { transaction })
await queryInterface.createTable('CategoryApps', categoryAppAttributes, { transaction })
await queryInterface.createTable('Devices', deviceAttributes, { transaction })
await queryInterface.createTable('Families', familyAttributes, { transaction })
await queryInterface.createTable('Purchases', purchaseAttributes, { transaction })
await queryInterface.createTable('TimelimitRules', timelimitruleAttributes, { transaction })
await queryInterface.createTable('UsedTimes', usedTimeAttribute, { transaction })
await queryInterface.createTable('Users', userAttributes, { transaction })
})
}
export async function down () {
throw new Error('not possible')
}

View file

@ -0,0 +1,58 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion2 } from '../../device'
import { attributes as oldDeviceAttributes } from '../../olddevice'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Devices', 'lastConnectivity', {
...attributesVersion2.lastConnectivity
}, {
transaction
})
await queryInterface.addColumn('Devices', 'notSeenForLongTime', {
...attributesVersion2.notSeenForLongTime
}, {
transaction
})
await queryInterface.addColumn('Devices', 'didDeviceReportUninstall', {
...attributesVersion2.didDeviceReportUninstall
}, {
transaction
})
await queryInterface.createTable('OldDevices', oldDeviceAttributes, { transaction })
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Devices', 'lastConnectivity', { transaction })
await queryInterface.removeColumn('Devices', 'notSeenForLongTime', { transaction })
await queryInterface.removeColumn('Devices', 'didDeviceReportUninstall', { transaction })
await queryInterface.dropTable('OldDevices', { transaction })
})
}

View file

@ -0,0 +1,35 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributes as mailLoginTokenAttributes } from '../../maillogintoken'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.createTable('MailLoginTokens', mailLoginTokenAttributes, { transaction })
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.dropTable('MailLoginTokens', { transaction })
})
}

View file

@ -0,0 +1,39 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion3 } from '../../device'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Devices', 'isUserKeptSignedIn', {
...attributesVersion3.isUserKeptSignedIn
}, {
transaction
})
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Devices', 'isUserKeptSignedIn', { transaction })
})
}

View file

@ -0,0 +1,39 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion2 } from '../../user'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Users', 'categoryForNotAssignedApps', {
...attributesVersion2.categoryForNotAssignedApps
}, {
transaction
})
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Users', 'categoryForNotAssignedApps', { transaction })
})
}

View file

@ -0,0 +1,39 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion2 } from '../../category'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Categories', 'parentCategoryId', {
...attributesVersion2.parentCategoryId
}, {
transaction
})
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Categories', 'parentCategoryId', { transaction })
})
}

View file

@ -0,0 +1,39 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion4 } from '../../device'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Devices', 'showDeviceConnected', {
...attributesVersion4.showDeviceConnected
}, {
transaction
})
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Devices', 'showDeviceConnected', { transaction })
})
}

View file

@ -0,0 +1,42 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion2 } from '../../usedtime'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('UsedTimes', 'lastUpdate', {
...attributesVersion2.lastUpdate
}, {
transaction
})
})
await queryInterface.addIndex('UsedTimes', ['lastUpdate'])
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeIndex('UsedTimes', ['lastUpdate'], { transaction })
await queryInterface.removeColumn('UsedTimes', 'lastUpdate', { transaction })
})
}

View file

@ -0,0 +1,53 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion5 as deviceAttributes } from '../../device'
import { attributesVersion3 as userAttributes } from '../../user'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
// users
await queryInterface.addColumn('Users', 'relaxPrimaryDeviceRule', {
...userAttributes.relaxPrimaryDeviceRule
}, { transaction })
// devices
await queryInterface.addColumn('Devices', 'defaultUserId', {
...deviceAttributes.defaultUserId
}, { transaction })
await queryInterface.addColumn('Devices', 'defaultUserTimeout', {
...deviceAttributes.defaultUserTimeout
}, { transaction })
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
// users
await queryInterface.removeColumn('Users', 'relaxPrimaryDeviceRule', { transaction })
// devices
await queryInterface.removeColumn('Devices', 'defaultUserId', { transaction })
await queryInterface.removeColumn('Devices', 'defaultUserTimeout', { transaction })
})
}

View file

@ -0,0 +1,46 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion6 } from '../../device'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Devices', 'considerRebootManipulation', {
...attributesVersion6.considerRebootManipulation
}, {
transaction
})
await queryInterface.addColumn('Devices', 'didReboot', {
...attributesVersion6.didReboot
}, {
transaction
})
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Devices', 'considerRebootManipulation', { transaction })
await queryInterface.removeColumn('Devices', 'didReboot', { transaction })
})
}

View file

@ -0,0 +1,37 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { QueryInterface, Sequelize } from 'sequelize'
import { attributesVersion4 as userAttributes } from '../../user'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.addColumn('Users', 'mailNotificationFlags', {
...userAttributes.mailNotificationFlags
}, { transaction })
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: 'EXCLUSIVE'
}, async (transaction) => {
await queryInterface.removeColumn('Users', 'mailNotificationFlags', { transaction })
})
}

View file

@ -0,0 +1,34 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import { resolve } from 'path'
import { Sequelize } from 'sequelize'
import * as Umzug from 'umzug'
export const createUmzug = (sequelize: Sequelize) => (
new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize
},
migrations: {
params: [sequelize.getQueryInterface(), sequelize],
path: resolve(__dirname, '../../../build/database/migration/migrations'),
pattern: /^\d+[\w-]+\.js$/
}
})
)

36
src/database/olddevice.ts Normal file
View file

@ -0,0 +1,36 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { authTokenColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface OldDeviceAttributes {
deviceAuthToken: string
}
export type OldDeviceInstance = Sequelize.Instance<OldDeviceAttributes> & OldDeviceAttributes
export type OldDeviceModel = Sequelize.Model<OldDeviceInstance, OldDeviceAttributes>
export const attributes: SequelizeAttributes<OldDeviceAttributes> = {
deviceAuthToken: {
...authTokenColumn,
primaryKey: true
}
}
export const createOldDeviceModel = (sequelize: Sequelize.Sequelize): OldDeviceModel => sequelize.define<OldDeviceInstance, OldDeviceAttributes>('OldDevice', attributes)

51
src/database/purchase.ts Normal file
View file

@ -0,0 +1,51 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
*
* 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, version 3 of the License.
*
* 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/>.
*/
import * as Sequelize from 'sequelize'
import { createEnumColumn, familyIdColumn, timestampColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface PurchaseAttributes {
familyId: string
service: 'googleplay'
transactionId: string
type: 'month' | 'year'
loggedAt: string
previousFullVersionEndTime: string
newFullVersionEndTime: string
}
export type PurchaseInstance = Sequelize.Instance<PurchaseAttributes> & PurchaseAttributes
export type PurchaseModel = Sequelize.Model<PurchaseInstance, PurchaseAttributes>
export const attributes: SequelizeAttributes<PurchaseAttributes> = {
familyId: { ...familyIdColumn },
service: {
...createEnumColumn(['googleplay']),
primaryKey: true
},
transactionId: {
type: Sequelize.STRING,
primaryKey: true
},
type: createEnumColumn(['month', 'year']),
loggedAt: timestampColumn,
previousFullVersionEndTime: timestampColumn,
newFullVersionEndTime: timestampColumn
}
export const createPurchaseModel = (sequelize: Sequelize.Sequelize): PurchaseModel => sequelize.define<PurchaseInstance, PurchaseAttributes>('Purchase', attributes)

Some files were not shown because too many files have changed in this diff Show more