Initial commit
This commit is contained in:
2
.browserslistrc
Normal file
2
.browserslistrc
Normal file
@@ -0,0 +1,2 @@
|
||||
> 1%
|
||||
last 2 versions
|
||||
91
.github/workflows/build-and-deploy.yaml
vendored
Normal file
91
.github/workflows/build-and-deploy.yaml
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
name: Build & deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
-
|
||||
name: "Prepare: Checkout"
|
||||
uses: actions/checkout@v1
|
||||
-
|
||||
name: "Prepare: Create AWS user profile"
|
||||
run: >-
|
||||
bash "aws/scripts/configure/create-user-profile.sh" \
|
||||
--profile user \
|
||||
--access-key-id ${{secrets.AWS_DEPLOYMENT_USER_ACCESS_KEY_ID}} \
|
||||
--secret-access-key ${{secrets.AWS_DEPLOYMENT_USER_SECRET_ACCESS_KEY}} \
|
||||
--region us-east-1
|
||||
-
|
||||
name: "Infrastructure: Deploy IAM stack"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/deploy-stack.sh" \
|
||||
--template-file aws/iam-stack.yaml \
|
||||
--stack-name privacysexy-iam-stack \
|
||||
--capabilities CAPABILITY_IAM \
|
||||
--region us-east-1 --role-arn ${{secrets.AWS_IAM_STACK_DEPLOYMENT_ROLE_ARN}} \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
-
|
||||
name: "Infrastructure: Deploy certificate stack"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/deploy-stack.sh" \
|
||||
--template-file aws/certificate-stack.yaml \
|
||||
--stack-name privacysexy-certificate-stack \
|
||||
--region us-east-1 \
|
||||
--role-arn ${{secrets.AWS_CERTIFICATE_STACK_DEPLOYMENT_ROLE_ARN}} \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
-
|
||||
name: "Infrastructure: Deploy DNS stack"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/deploy-stack.sh" \
|
||||
--template-file aws/dns-stack.yaml \
|
||||
--stack-name privacysexy-dns-stack \
|
||||
--region us-east-1 \
|
||||
--role-arn ${{secrets.AWS_DNS_STACK_DEPLOYMENT_ROLE_ARN}} \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
-
|
||||
name: "Infrastructure: Deploy web stack"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/deploy-stack.sh" \
|
||||
--template-file aws/web-stack.yaml \
|
||||
--stack-name privacysexy-web-stack \
|
||||
--region us-east-1 \
|
||||
--role-arn ${{secrets.AWS_WEB_STACK_DEPLOYMENT_ROLE_ARN}} \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
-
|
||||
name: "App: Setup node"
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '11.x'
|
||||
-
|
||||
name: "App: Install dependencies"
|
||||
run: npm install
|
||||
-
|
||||
name: "App: Run tests"
|
||||
run: npm run test:unit
|
||||
-
|
||||
name: "App: Build"
|
||||
run: npm run build
|
||||
-
|
||||
name: "App: Deploy to S3"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/deploy-to-s3.sh" \
|
||||
--folder dist \
|
||||
--web-stack-name privacysexy-web-stack --web-stack-s3-name-output-name S3BucketName \
|
||||
--storage-class ONEZONE_IA \
|
||||
--role-arn ${{secrets.AWS_S3_SITE_DEPLOYMENT_ROLE_ARN}} \
|
||||
--region us-east-1 \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
-
|
||||
name: "App: Invalidate CloudFront cache"
|
||||
run: >-
|
||||
bash "aws/scripts/deploy/invalidate-cloudfront-cache.sh" \
|
||||
--paths "/*" \
|
||||
--web-stack-name privacysexy-web-stack --web-stack-cloudfront-arn-output-name CloudFrontDistributionArn \
|
||||
--role-arn ${{secrets.AWS_CLOUDFRONT_SITE_DEPLOYMENT_ROLE_ARN}} \
|
||||
--region us-east-1 \
|
||||
--profile user --session ${{github.actor}}-${{github.event_name}}-${{github.sha}}
|
||||
26
.github/workflows/run-tests.yaml
vendored
Normal file
26
.github/workflows/run-tests.yaml
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
name: Run tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
- '!master'
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
uses: actions/checkout@v1
|
||||
-
|
||||
name: Setup node
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '11.x'
|
||||
-
|
||||
name: Install dependencies
|
||||
run: npm install
|
||||
-
|
||||
name: Run tests
|
||||
run: npm run test:unit
|
||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
/dist
|
||||
.vs
|
||||
.vscode
|
||||
21
Dockerfile
Normal file
21
Dockerfile
Normal file
@@ -0,0 +1,21 @@
|
||||
# +-+-+-+-+-+ +-+-+-+-+-+
|
||||
# |B|u|i|l|d| |S|t|a|g|e|
|
||||
# +-+-+-+-+-+ +-+-+-+-+-+
|
||||
FROM node:lts-alpine as build-stage
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
# For testing purposes, it's easy to run http-server on lts-alpine such as continuing from here:
|
||||
# RUN npm install -g http-server
|
||||
# EXPOSE 8080
|
||||
# CMD [ "http-server", "dist" ]
|
||||
|
||||
# +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+
|
||||
# |P|r|o|d|u|c|t|i|o|n| |S|t|a|g|e|
|
||||
# +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+
|
||||
FROM nginx:stable-alpine as production-stage
|
||||
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
119
README.md
Normal file
119
README.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# privacy.sexy
|
||||
|
||||
Privacy & security generator tool for Windows.
|
||||
|
||||
> because privacy is sexy 🍑🍆
|
||||
|
||||
[https://privacy.sexy](https://privacy.sexy)
|
||||
|
||||
In this repo you find:
|
||||
|
||||
- Application & infrastructure code of privacy.sexy, simply everything is code & open-sourced.
|
||||
- Fully automated CI/CD pipeline to AWS for provisioning serverless infrastructure using GitHub actions.
|
||||
- Vue.js application in conjunction with domain-driven design, event-driven architecture & data-driven programming.
|
||||
|
||||
## Commands
|
||||
|
||||
- Setup and run
|
||||
- For development:
|
||||
- `npm install` to project setup.
|
||||
- `npm run serve` to compile & hot-reload for development.
|
||||
- Production (using Docker):
|
||||
- Build `docker build -t undergroundwires/privacy.sexy .`
|
||||
- Run `docker run -it -p 8080:8080 --rm --name privacy.sexy-1 undergroundwires/privacy.sexy`
|
||||
- Prepare for production: `npm run build`
|
||||
- Run tests: `npm run test:unit`
|
||||
- Lint and fix files: `npm run lint`
|
||||
|
||||
## Extend scripts
|
||||
|
||||
Fork it & add more scripts in `src/application/application.yml` and send a pull request 👌
|
||||
|
||||
## Architecture
|
||||
|
||||
### Application
|
||||
|
||||
- Powered by **TypeScript** + **Vue.js** 💪
|
||||
- and driven by **Domain-driven design**, **Event-driven architecture**, **Data-driven programming** concepts.
|
||||
- Application uses highly decoupled models & services in different DDD layers.
|
||||
- **Domain layer** is where the application is modelled with validation logic.
|
||||
- **Presentation Layer**
|
||||
- Consists of Vue.js components & UI stuff.
|
||||
- Event driven as in components simply listens to events from the state and act accordingly.
|
||||
- **Application Layer**
|
||||
- Keeps the application state
|
||||
- The [state](src/application/State/ApplicationState.ts) is a mutable singleton & event producer.
|
||||
- The application is defined & controlled in a [single YAML file](`\application\application.yaml`) (see [Data-driven programming](https://en.wikipedia.org/wiki/Data-driven_programming))
|
||||
|
||||

|
||||
|
||||
### AWS Infrastructure
|
||||
|
||||
- The application runs in AWS 100% serverless and automatically provisioned using [CloudFormation files](/aws) and GitHub Actions.
|
||||
- Maximum security & automation and minimum AWS costs were the highest priorities of the design.
|
||||
|
||||

|
||||
|
||||
#### GitOps: CI/CD to AWS
|
||||
|
||||
- Everything that's merged in the master goes directly to production.
|
||||
- Deploy infrastructure ► Deploy web application ► Invalidate CloudFront Cache
|
||||
- See more at [build-and-deploy.yaml](.GitHub/workflows/build-and-deploy.yaml)
|
||||
|
||||

|
||||
|
||||
##### CloudFormation
|
||||
|
||||

|
||||
|
||||
- AWS infrastructure is defined as code with following files:
|
||||
- `iam-stack`: Creates & updates the deployment user.
|
||||
- Everything in IAM layer is fine-grained using least privileges principle.
|
||||
- Each deployment step has its own temporary credentials with own permissions.
|
||||
- `certificate-stack.yaml`
|
||||
- It'll generate SSL certification for the root domain and www subdomain.
|
||||
- ❗ It [must](https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-invalid-viewer-certificate/) be deployed in `us-east-1` to be able to be used by CloudFront by `web-stack`.
|
||||
- It uses CustomResource and a lambda instead of native `AWS::CertificateManager::Certificate` because:
|
||||
- Problem:
|
||||
- AWS variant waits until a certificate is validated.
|
||||
- There's no way to automate validation without workaround.
|
||||
- Solution:
|
||||
- Deploy a lambda that deploys the certificate (so we don't wait until certificate is validated)
|
||||
- Get DNS records to be used in validation & export it to be used later.
|
||||
- `web-stack.yaml`: It'll deploy S3 bucket and CloudFront in front of it.
|
||||
- `dns-stack.yaml`: It'll deploy Route53 hosted zone
|
||||
- Each time Route53 hosted zone is re-created it's required to update the DNS records in the domain registrar. See *Configure your domain registrar*.
|
||||
- I use cross stacks instead of single stack or nested stacks because:
|
||||
- Easier to test & maintain & smaller files and different lifecycles for different areas.
|
||||
- It allows to deploy web bucket in different region than others as other stacks are global (`us-east-1`) resources.
|
||||
|
||||
##### Initial deployment
|
||||
|
||||
- ❗ Prerequisite: A registered domain name for website.
|
||||
|
||||
1. **Configure build agent (GitHub actions)**
|
||||
- Deploy manually `iam-stack.yaml` with stack name `privacysexy-iam-stack` (to follow the convention)
|
||||
- It'll give you deploy user. Go to console & generate secret id + key (Security credentials => Create access key) for the user [IAM users](https://console.aws.amazon.com/iam/home#/users).
|
||||
- 🚶 Deploy secrets:
|
||||
- Add secret id & key in GitHub Secrets.
|
||||
- `AWS_DEPLOYMENT_USER_ACCESS_KEY_ID`, `AWS_DEPLOYMENT_USER_SECRET_ACCESS_KEY`
|
||||
- Add more secrets given from Outputs section of the CloudFormation stack.
|
||||
- Run GitHub actions to deploy rest of the application.
|
||||
- It'll run `certificate-stack.yaml` and then `iam-stack.yaml`.
|
||||
|
||||
2. **Configure your domain registrar**
|
||||
- ❗ **Web stack will fail** after DNS stack because you need to validate your domain.
|
||||
- 🚶 Go to your domain registrar and change name servers to NS values
|
||||
- `dns-stack.yaml` outputs those in CloudFormation stack.
|
||||
- You can alternatively find those in [Route53](https://console.aws.amazon.com/route53/home#hosted-zones)
|
||||
- When nameservers of your domain updated, the certification will get validated automatically, you can then delete the failed stack in CloudFormation & re-run the GitHub actions.
|
||||
|
||||
## Thank you for the awesome projects 🍺
|
||||
|
||||
- [Vue.js](https://vuejs.org/) the only big JavaScript framework that's not backed by companies that make money off your data.
|
||||
- [liquor-tree](https://GitHub.com/amsik/liquor-tree) for the awesome & super extensible tree component.
|
||||
- [Ace](https://ace.c9.io/) for code box.
|
||||
- [FileSaver.js](https://GitHub.com/eligrey/FileSaver.js) for save file dialog.
|
||||
- [chai](https://GitHub.com/chaijs/chai) & [mocha](https://GitHub.com/mochajs/mocha) for making testing fun.
|
||||
- [js-yaml-loader](https://GitHub.com/wwilsman/js-yaml-loader) for ahead of time loading `application.yml`
|
||||
- [v-tooltip](https://GitHub.com/Akryum/v-tooltip) takes seconds to have a tooltip, exactly what I needed.
|
||||
1
aws.drawio
Normal file
1
aws.drawio
Normal file
@@ -0,0 +1 @@
|
||||
<mxfile host="www.draw.io" modified="2019-12-27T14:40:11.720Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" etag="6t_Q0ZRAKXZ_lLm1WdcF" version="12.4.3" type="device" pages="1"><diagram id="pFg2tUHn5hOZkmQyf_J4" name="Page-1">7Vvtd6I4F/9r+lEOEMLLR23rzJzdme3qPLMvXzwUomaLxA2x1f3rnwSIEoIWFdqd3bXnKLmEJNz7u69Jb8DtavuBhuvlZxKj5MY24+0NuLux7SAA/FsQdgXBD8yCsKA4LkjWgTDFf6GSKLttcIwypSMjJGF4rRIjkqYoYgotpJS8qN3mJFFnXYcLpBGmUZjo1F9wzJblW0DzQP+I8GIpZ7bM8s4qlJ1LQrYMY/JSIYH7G3BLCWHF1Wp7ixLBO8mX4rnxkbv7hVGUsjYPfB19Hf0+Wf6+DcbR9Mtksvm2hANYjPIcJpvyhe/IKsQpp03QAmeMhrRcPttJnqwJThmi9898ZsFe6waM9m9n8kYcZksUl40lWyWyE6PkCd2ShFBOSUnKBxzNcZJI0o0NoCn+OD0JH1HyQDLMMEn5vQiJSfmNZ0QZ5hL6sdbhkTBGVpUOwwQvxA1G1pxKNizBKZ9dAkVMEpZd9oPz91iL11xtFwLPBpnPcYSMDNFn/psZVHJlVpL4M7okSuGIhaBthVRK5gMiK8Tojncp79qeXzxSqgmQ+H85gA66BWlZwRu0S6iXMF/sRz4ggV+UYDgDGJatIUPDASWbNN7L+WWJGZquQ8GSuxfOPFX2e0xYNZmXMFCxwYEQe8GjaXbDXslNyd1A564r9bTKXuCYffEXvM5fiUW8yo1UlZvNEH9VM3KdGoXR0yKXXYXb8/zDu+STDbN1RUdkY463QoKjcj13S8aEFR4KTtjjKE5tA3M7PMccFdSI+Iz2OA5ZyH8EPeO/4Sr8i6SD8CUbZAylEU4ENTea4y/8xrRQqtmUT4m55s0ist7NZsNfprPbhGxijkvfWKeLDjAxMA1gBpWP76kgcW0dJIGOEUm7BiJ/bp/idPL8FMApjNFk+8N6+/NA18CcBWNK+DvXsdJo3ea8Z0XG/G8s5h9x0xZjpNwLHHg3tiv37jDlAxX4SQkVHNBM9RCYI9iku3s0KZ7gQsOt2eiKHog3LIMGy5btkiuN2K3bd45Ehxv1jGxohD5FYj0j3iyu1F6R4P485343RslXrZJrAg1w0i1UASdpnQNON0lTTjJHm+gJdY841xwC4J2HONvzLMv91yAuA90gDToq0mDgGa7zvmDTI0+JM/OBJDjadQu45mDzCJ7Kzn87KB0JvHV4rQsOdgIexwlU8EDdTEHfkAMr0WkH0VMjeFwNPBOODsRJcnH/uca3NFRUcH8GOzJXAKjmyrGC97VVnh6JCXHw+DTMQfc5THlErCfKjcjrW+4NYgRGdFjvbFWsdmbrsPVgcHvKfHZhTmquCDiNrggYsCHUBj0J2NcEfJ/OCYc9z07cRMR7j1y67kJcffz69WGqiRrFCyS1S5gEsiBpmNwfqCM1Wz70+ZEIkeai+wMxtit1NtwwogqW85zufq02fhODGVA277bl4EVrV209IIo5rwRY7k4m1YW6n+BVmZawkC4Qe11pBGNO4oKiJGT4Wa23NUm4fPRBOMFKFO2qlRPoBgb0LMf2i29PHbB4vXKMarWsNqzt2IbFAed5rmfbZmB558xSMEebJcfm/tUvh6ulB08TFOdeKXsPZBZOTtZH7avg5baEl/028OKiNZQigQoDD14GL+Aq8PIDeHrcngEli0//smpUil4GOxTSgYhyko1YnyALfzSukAZm0GHdybUMT5U2MC3dATZUI72+wmlbz/xVbq4pfg6jnZGhrZ6XfWcGRkK7amFO7Y30bWGAr+ZXPN9SXIt7oQfbF7nLce2gBp++bYqjgSqf63vyUKdw8aqHclvip5SXaXCnUD5zLaQsqxdI2Y5v+JWBaoUB4LYC2JDScFfptt6j4piC1HZvHLuG12LE2tNyeDKfZ6gfhOtpA0/1GE43ZMPfx4zROiG6vbw+Edhi9qsM7vl1JQ3grUMWIBoyCejUgrbVAHCuBlhWYCuyHgTXKcQbgECPxT9gttw8fv8BlPlqAEUiJi8tUxj88SqkT4NFzoAuYya3VhFym6sGPQVNz2vPu/92v8tcb/fTty+TzAzmA0uT+08UL/KjE8MoQpmwAJ9i/s6YvUkt+9azgDX+59WyKUkOpScNMg3AOn7IwndUhwVB220Qx+kJRXri9TG8JEK6JCaqHtnh6o0jxVdUoGXmH9FrQ5/3hzgajXtnNaXjOnfCf0DLUVMrv5N4qn46B/r2ZQEUcLiP24dh/FsZ1gXtykjnBlB8veryPbdNACXPSfhNHO3UsTbKWk8fhkkizvMJcYbxu6QRHUK+IYa6APID0zDBlTGS3CSGgeF7PAfJt0UDUxW7C4Im5J6rAC6oQd6EhgUq9bVeFMDR9NdvowD9Y1zfx3wz69+XKQc6ro/j/xSubUv11t2kxrC2twi9GuTaIhlaavbrgnbllXOxq53daGe8Zf4kz3H2j2V9k3TyXmb6WLLbV6xyXBF62I/oagcCng5FeisWNns53RL+L0M6eN6ldtIleNq6/cLcdQ4fLZEOLoQPdKChhtqOC7jN5jmV5zqO67mB86YIatjDeAU95xxYF42HkPGENc0pttn2GPujz1l1QNFVCSw0a9Jr2DgKGmogltnBGeVmruvVr32U/kI5f/tU4b3a/la506UKnwTapQ7gEOFAt7YRuPfWV2q5452y7bB+jKa1zgNvf8xvd5jJdDzXCuR3K6V/yxjb1l3Lp+FnTuAOhmro/K8w17owF8Zxfiaw2TZ2Yu4CDW+O/p87jfW6vqq+tqdBphrQlkKtVtM6s3DmSQunVPOOV/C6Co1bm8YTHa+Ibq6SoYxtNYvwgfumtSZfDmDWlF80Ofma6s/9CEVRk4bWFXmF4zhPfpqiEtVltghM3jHWsM/XPHHaZv9vsIXZP/wvMbj/Pw==</diagram></mxfile>
|
||||
211
aws/certificate-stack.yaml
Normal file
211
aws/certificate-stack.yaml
Normal file
@@ -0,0 +1,211 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Description: Creates certificate for the root + www subdomain. !! It must be deployed in us-east-1 to be able to be used by CloudFront.
|
||||
|
||||
Parameters:
|
||||
|
||||
RootDomainName:
|
||||
Type: String
|
||||
Default: privacy.sexy
|
||||
Description: The root DNS name of the website e.g. privacy.sexy
|
||||
AllowedPattern: (?!-)[a-zA-Z0-9-.]{1,63}(?<!-)
|
||||
ConstraintDescription: Must be a valid root domain name
|
||||
|
||||
IamStackName:
|
||||
Type: String
|
||||
Default: privacysexy-iam-stack
|
||||
Description: Name of the IAM stack.
|
||||
|
||||
Resources:
|
||||
|
||||
# The lambda workaround exists to be able to automate certificate deployment.
|
||||
# Problem:
|
||||
# Normally AWS AWS::CertificateManager::Certificate waits until a certificate is validated
|
||||
# And there's no way to get validation DNS records from it to validate it.
|
||||
# Solution:
|
||||
# Deploy a lambda that deploys the certificate (so we don't wait until certificate is validated)
|
||||
# Get DNS records to be used in validation & export it to be used later.
|
||||
|
||||
AcmCertificateForHostedZone:
|
||||
Type: Custom::VerifiableCertificate #A Can use AWS::CloudFormation::CustomResource or Custom::String
|
||||
Properties:
|
||||
ServiceToken: !GetAtt ResolveCertificateLambda.Arn
|
||||
# Lambda gets the following data:
|
||||
RootDomainName: !Ref RootDomainName # Lambda will create both for root and www.root
|
||||
Tags:
|
||||
-
|
||||
Key: Name
|
||||
Value: !Ref RootDomainName
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
|
||||
ResolveCertificateLambda:
|
||||
Type: AWS::Lambda::Function
|
||||
Properties:
|
||||
Description: Deploys certificate for root domain name + www and returns immediately arn + verification records.
|
||||
Role:
|
||||
Fn::ImportValue: !Join [':', [!Ref IamStackName, ResolveCertificateLambdaRoleArn]]
|
||||
FunctionName: !Sub ${AWS::StackName}-cert-resolver-lambda # StackName- required for role to function
|
||||
Handler: index.handler
|
||||
Runtime: nodejs12.x
|
||||
Timeout: 30
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
Code:
|
||||
# Inline script is not the best way. Some variables are named shortly to not exceed the limit 4096 but it's the cheapest way (no s3 file)
|
||||
ZipFile: >
|
||||
'use strict';
|
||||
const aws = require('aws-sdk');
|
||||
const acm = new aws.ACM();
|
||||
const log = (t) => console.log(t);
|
||||
|
||||
exports.handler = async (event, context) => {
|
||||
log(`Request recieved:\n${JSON.stringify(event)}`);
|
||||
const userData = event.ResourceProperties;
|
||||
const rootDomain = userData.RootDomainName;
|
||||
let data = null;
|
||||
try {
|
||||
switch(event.RequestType) {
|
||||
case 'Create':
|
||||
data = await handleCreateAsync(rootDomain, userData.Tags);
|
||||
break;
|
||||
case 'Update':
|
||||
data = await handleUpdateAsync();
|
||||
break;
|
||||
case 'Delete':
|
||||
data = await handleDeleteAsync(rootDomain);
|
||||
break;
|
||||
}
|
||||
await sendResponseAsync(event, context, 'SUCCESS', data);
|
||||
} catch(error) {
|
||||
await sendResponseAsync(event, context, 'ERROR', {
|
||||
title: `Failed to ${event.RequestType}, see error`,
|
||||
error: error
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateAsync(rootDomain, tags) {
|
||||
const { CertificateArn } = await acm.requestCertificate({
|
||||
DomainName: rootDomain,
|
||||
SubjectAlternativeNames: [`www.${rootDomain}`],
|
||||
Tags: tags,
|
||||
ValidationMethod: 'DNS',
|
||||
}).promise();
|
||||
log(`Cert requested:${CertificateArn}`);
|
||||
const waitAsync = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const maxAttempts = 10;
|
||||
let options = undefined;
|
||||
for (let attempt = 0; attempt < maxAttempts && !options; attempt++) {
|
||||
await waitAsync(2000);
|
||||
const { Certificate } = await acm.describeCertificate({ CertificateArn }).promise();
|
||||
if(Certificate.DomainValidationOptions.filter((o) => o.ResourceRecord).length === 2) {
|
||||
options = Certificate.DomainValidationOptions;
|
||||
}
|
||||
}
|
||||
if(!options) {
|
||||
throw new Error(`No records after ${maxAttempts} attempts.`);
|
||||
}
|
||||
return getResponseData(options, CertificateArn, rootDomain);
|
||||
}
|
||||
|
||||
async function handleDeleteAsync(rootDomain) {
|
||||
const certs = await acm.listCertificates({}).promise();
|
||||
const cert = certs.CertificateSummaryList.find((cert) => cert.DomainName === rootDomain);
|
||||
if (cert) {
|
||||
await acm.deleteCertificate({ CertificateArn: cert.CertificateArn }).promise();
|
||||
log(`Deleted ${cert.CertificateArn}`);
|
||||
} else {
|
||||
log('Cannot find'); // Do not fail, delete can be called when e.g. CF fails before creating cert
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleUpdateAsync() {
|
||||
throw new Error(`Not yet implemented update`);
|
||||
}
|
||||
|
||||
function getResponseData(options, arn, rootDomain) {
|
||||
const findRecord = (url) => options.find(option => option.DomainName === url).ResourceRecord;
|
||||
const root = findRecord(rootDomain);
|
||||
const www = findRecord(`www.${rootDomain}`);
|
||||
const data = {
|
||||
CertificateArn: arn,
|
||||
RootVerificationRecordName: root.Name,
|
||||
RootVerificationRecordValue: root.Value,
|
||||
WwwVerificationRecordName: www.Name,
|
||||
WwwVerificationRecordValue: www.Value,
|
||||
};
|
||||
return data;
|
||||
}
|
||||
|
||||
/* cfn-response can't async / await :( */
|
||||
async function sendResponseAsync(event, context, responseStatus, responseData, physicalResourceId) {
|
||||
return new Promise((s, f) => {
|
||||
var b = JSON.stringify({
|
||||
Status: responseStatus,
|
||||
Reason: `See the details in CloudWatch Log Stream: ${context.logStreamName}`,
|
||||
PhysicalResourceId: physicalResourceId || context.logStreamName,
|
||||
StackId: event.StackId,
|
||||
RequestId: event.RequestId,
|
||||
LogicalResourceId: event.LogicalResourceId,
|
||||
Data: responseData
|
||||
});
|
||||
log(`Response body:\n${b}`);
|
||||
var u = require("url").parse(event.ResponseURL);
|
||||
var r = require("https").request(
|
||||
{
|
||||
hostname: u.hostname,
|
||||
port: 443,
|
||||
path: u.path,
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"content-type": "",
|
||||
"content-length": b.length
|
||||
}
|
||||
}, (p) => {
|
||||
log(`Status code: ${p.statusCode}`);
|
||||
log(`Status message: ${p.statusMessage}`);
|
||||
s(context.done());
|
||||
});
|
||||
r.on("error", (e) => {
|
||||
log(`request failed: ${e}`);
|
||||
f(context.done(e));
|
||||
});
|
||||
r.write(b);
|
||||
r.end();
|
||||
});
|
||||
}
|
||||
|
||||
Outputs:
|
||||
CertificateArn:
|
||||
Description: The Amazon Resource Name (ARN) of an AWS Certificate Manager (ACM) certificate.
|
||||
Value: !GetAtt AcmCertificateForHostedZone.CertificateArn
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', CertificateArn ]]
|
||||
|
||||
RootVerificationRecordName:
|
||||
Description: Name for root domain CNAME verification record
|
||||
Value: !GetAtt AcmCertificateForHostedZone.RootVerificationRecordName
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', RootVerificationRecordName ]]
|
||||
|
||||
RootVerificationRecordValue:
|
||||
Description: Value for root domain name CNAME verification record
|
||||
Value: !GetAtt AcmCertificateForHostedZone.RootVerificationRecordValue
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', RootVerificationRecordValue ]]
|
||||
|
||||
WwwVerificationRecordName:
|
||||
Description: Name for www domain name CNAME verification record
|
||||
Value: !GetAtt AcmCertificateForHostedZone.WwwVerificationRecordName
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', WwwVerificationRecordName ]]
|
||||
|
||||
WwwVerificationRecordValue:
|
||||
Description: Value for www domain name CNAME verification record
|
||||
Value: !GetAtt AcmCertificateForHostedZone.WwwVerificationRecordValue
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', WwwVerificationRecordValue ]]
|
||||
61
aws/dns-stack.yaml
Normal file
61
aws/dns-stack.yaml
Normal file
@@ -0,0 +1,61 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Description: Creates hosted zone & sets up records for the CloudFront URL.
|
||||
|
||||
Parameters:
|
||||
|
||||
RootDomainName:
|
||||
Type: String
|
||||
Default: privacy.sexy
|
||||
Description: The root DNS name of the website e.g. privacy.sexy
|
||||
AllowedPattern: (?!-)[a-zA-Z0-9-.]{1,63}(?<!-)
|
||||
ConstraintDescription: Must be a valid root domain name
|
||||
|
||||
CertificateStackName:
|
||||
Type: String
|
||||
Default: privacysexy-certificate-stack
|
||||
Description: Name of the certificate stack.
|
||||
|
||||
Resources:
|
||||
|
||||
DNSHostedZone:
|
||||
Type: AWS::Route53::HostedZone
|
||||
Properties:
|
||||
Name: !Ref RootDomainName
|
||||
HostedZoneConfig:
|
||||
Comment: !Join ['', ['Hosted zone for ', !Ref RootDomainName]]
|
||||
HostedZoneTags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
|
||||
CertificateValidationDNSRecords:
|
||||
Type: AWS::Route53::RecordSetGroup
|
||||
Properties:
|
||||
HostedZoneId: !Ref DNSHostedZone
|
||||
RecordSets:
|
||||
-
|
||||
Name:
|
||||
Fn::ImportValue: !Join [':', [!Ref CertificateStackName, RootVerificationRecordName]]
|
||||
Type: 'CNAME'
|
||||
TTL: '60'
|
||||
ResourceRecords:
|
||||
- Fn::ImportValue: !Join [':', [!Ref CertificateStackName, RootVerificationRecordValue]]
|
||||
-
|
||||
Name:
|
||||
Fn::ImportValue: !Join [':', [!Ref CertificateStackName, WwwVerificationRecordName]]
|
||||
Type: 'CNAME'
|
||||
TTL: '60'
|
||||
ResourceRecords:
|
||||
- Fn::ImportValue: !Join [':', [!Ref CertificateStackName, WwwVerificationRecordValue]]
|
||||
|
||||
Outputs:
|
||||
|
||||
DNSHostedZoneNameServers:
|
||||
Description: Name servers to update in domain registrar.
|
||||
Value: !Join [' ', !GetAtt DNSHostedZone.NameServers]
|
||||
|
||||
DNSHostedZoneId:
|
||||
Description: The ID of the hosted zone that you want to create the record in.
|
||||
Value: !Ref DNSHostedZone
|
||||
Export:
|
||||
Name: !Join [':', [ !Ref 'AWS::StackName', DNSHostedZoneId ]]
|
||||
496
aws/iam-stack.yaml
Normal file
496
aws/iam-stack.yaml
Normal file
@@ -0,0 +1,496 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Description: |-
|
||||
> Deploys the identity management for the deployment
|
||||
|
||||
# Granulatiy cheatsheet: https://iam.cloudonaut.io/
|
||||
|
||||
Parameters:
|
||||
WebStackName:
|
||||
Type: String
|
||||
Default: privacysexy-web-stack
|
||||
Description: Name of the web stack.
|
||||
DnsStackName:
|
||||
Type: String
|
||||
Default: privacysexy-dns-stack
|
||||
Description: Name of the DNS stack.
|
||||
CertificateStackName:
|
||||
Type: String
|
||||
Default: privacysexy-certificate-stack
|
||||
Description: Name of the IAM stack.
|
||||
|
||||
Resources:
|
||||
|
||||
# -----------------------------
|
||||
# ------ User & Group ---------
|
||||
# -----------------------------
|
||||
DeploymentGroup:
|
||||
Type: AWS::IAM::Group
|
||||
Properties:
|
||||
# GroupName: No hardcoded naming because of easier CloudFormation management
|
||||
ManagedPolicyArns:
|
||||
- !Ref AllowValidateTemplatePolicy
|
||||
|
||||
DeploymentUser:
|
||||
Type: AWS::IAM::User
|
||||
Properties:
|
||||
# # UserName: No hardcoded naming because of easier CloudFormation management
|
||||
# # Policies: Assing policies on group level
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
|
||||
AddDeploymentUserToDeploymentGroup:
|
||||
Type: AWS::IAM::UserToGroupAddition
|
||||
Properties:
|
||||
GroupName: !Ref DeploymentGroup
|
||||
Users:
|
||||
- !Ref DeploymentUser
|
||||
|
||||
# -----------------------------
|
||||
# ----------- Roles -----------
|
||||
# -----------------------------
|
||||
IamStackDeployRole:
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Description: Allows to deploy IAM stack
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref CloudFormationDeployPolicy
|
||||
- !Ref PolicyDeployPolicy
|
||||
- !Ref IamStackDeployPolicy
|
||||
|
||||
CertificateStackDeployRole:
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Description: Allows to deploy certificate stack
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref CloudFormationDeployPolicy
|
||||
- !Ref LambdaBackedCustomResourceDeployPolicy
|
||||
|
||||
DnsStackDeployRole:
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Description: Allows to deploy DNS stack
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref CloudFormationDeployPolicy
|
||||
- !Ref DnsStackDeployPolicy
|
||||
|
||||
WebStackDeployRole:
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Description: Allows to deploy web stack
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref CloudFormationDeployPolicy
|
||||
- !Ref WebStackDeployPolicy
|
||||
|
||||
S3SiteDeployRole:
|
||||
Type: 'AWS::IAM::Role'
|
||||
Properties:
|
||||
Description: "Allows to deploy website to S3"
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref S3SiteDeployPolicy
|
||||
- !Ref StackExportReaderPolicy
|
||||
|
||||
CloudFrontSiteDeployRole:
|
||||
Type: 'AWS::IAM::Role'
|
||||
Properties:
|
||||
Description: "Allows to informs to CloudFront to renew its cache from S3"
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
AWS: !GetAtt DeploymentUser.Arn
|
||||
Action: sts:AssumeRole
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
ManagedPolicyArns:
|
||||
- !Ref CloudFrontInvalidationPolicy
|
||||
- !Ref StackExportReaderPolicy
|
||||
|
||||
ResolveCertificateLambdaRole: # See certificate stack
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Description: Allow deployment of certificates
|
||||
AssumeRolePolicyDocument:
|
||||
Statement:
|
||||
-
|
||||
Effect: Allow
|
||||
Principal:
|
||||
Service: lambda.amazonaws.com
|
||||
Action: sts:AssumeRole
|
||||
ManagedPolicyArns:
|
||||
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
|
||||
- !Ref CertificateDeployPolicy
|
||||
|
||||
# --------------------------------
|
||||
# ----------- Policies -----------
|
||||
# --------------------------------
|
||||
|
||||
AllowValidateTemplatePolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: "No read & writes to resources, reveals just basic CloudFormation API to be used for validating templates"
|
||||
# ManagedPolicyName: No hardcoded naming because of easier CloudFormation management
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCloudFormationTemplateValidation
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudformation:ValidateTemplate
|
||||
Resource: '*'
|
||||
|
||||
CloudFormationDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: "Allows deploying CloudFormation using CLI command 'aws cloudformation deploy' (with change sets)"
|
||||
# ManagedPolicyName: No hardcoded naming because of easier CloudFormation management
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCloudFormationStackOperations
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudformation:GetTemplateSummary
|
||||
- cloudformation:DescribeStacks
|
||||
- cloudformation:CreateChangeSet
|
||||
- cloudformation:ExecuteChangeSet
|
||||
- cloudformation:DescribeChangeSet
|
||||
Resource:
|
||||
- !Sub arn:aws:cloudformation:*:${AWS::AccountId}:stack/${WebStackName}/*
|
||||
- !Sub arn:aws:cloudformation:*:${AWS::AccountId}:stack/${DnsStackName}/*
|
||||
- !Sub arn:aws:cloudformation:*:${AWS::AccountId}:stack/${AWS::StackName}/*
|
||||
- !Sub arn:aws:cloudformation:*:${AWS::AccountId}:stack/${CertificateStackName}/*
|
||||
|
||||
IamStackDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deploying IAM CloudFormation stack.
|
||||
# ManagedPolicyName: No hardcoded naming because of easier CloudFormation management
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowUserArnExport
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:GetUser
|
||||
Resource:
|
||||
- !GetAtt DeploymentUser.Arn
|
||||
-
|
||||
Sid: AllowTagging
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:TagResource
|
||||
Resource:
|
||||
- !Sub arn:aws:cloudformation::${AWS::AccountId}:stack/${AWS::StackName}/*
|
||||
- !GetAtt DeploymentUser.Arn
|
||||
-
|
||||
Sid: AllowRoleDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:CreateRole
|
||||
Resource:
|
||||
- !Sub arn:aws:iam::${AWS::AccountId}:role/${AWS::StackName}-*
|
||||
|
||||
LambdaBackedCustomResourceDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deploying a lambda-backed custom resource.
|
||||
# ManagedPolicyName: # ManagedPolicyName: No hardcoded naming because of easier CloudFormation management
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowLambdaDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- lambda:GetFunction
|
||||
- lambda:DeleteFunction
|
||||
- lambda:CreateFunction
|
||||
- lambda:GetFunctionConfiguration
|
||||
- lambda:InvokeFunction
|
||||
Resource:
|
||||
- !Sub arn:aws:lambda:*:${AWS::AccountId}:function:${CertificateStackName}*
|
||||
-
|
||||
Sid: AllowPassingLambdaRole
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:PassRole
|
||||
Resource:
|
||||
- !GetAtt ResolveCertificateLambdaRole.Arn
|
||||
|
||||
CertificateDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deploying certifications stack.
|
||||
# ManagedPolicyName: # ManagedPolicyName: No hardcoded naming because of easier CloudFormation management
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCertificateDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- acm:RequestCertificate
|
||||
- acm:DescribeCertificate
|
||||
- acm:DeleteCertificate
|
||||
- acm:AddTagsToCertificate
|
||||
- acm:ListCertificates
|
||||
Resource: '*' # Certificate Manager does not support resource level IAM
|
||||
|
||||
PolicyDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deployment of policies
|
||||
# ManagedPolicyName: Commented out because CloudFormation requires to rename when replacing custom-named resource
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowPolicyUpdates
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:ListPolicyVersions
|
||||
- iam:CreatePolicyVersion
|
||||
- iam:DeletePolicyVersion
|
||||
- iam:CreatePolicy
|
||||
- iam:DeletePolicy
|
||||
- iam:GetPolicy
|
||||
Resource:
|
||||
- !Sub arn:aws:iam::${AWS::AccountId}:policy/${AWS::StackName}-* # when ManagedPolicyName is not given policies get name like StackName-*
|
||||
-
|
||||
Sid: AllowPoliciesOnRoles
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:AttachRolePolicy
|
||||
- iam:DetachRolePolicy
|
||||
- iam:GetRole
|
||||
Resource:
|
||||
- !Sub arn:aws:iam::${AWS::AccountId}:role/${AWS::StackName}-*
|
||||
-
|
||||
Sid: AllowPolicyAssigmentToGroup
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:AttachGroupPolicy
|
||||
- iam:DetachGroupPolicy
|
||||
Resource:
|
||||
- !GetAtt DeploymentGroup.Arn
|
||||
-
|
||||
Sid: AllowGettingGroupInformation
|
||||
Effect: Allow
|
||||
Action:
|
||||
- iam:GetGroup
|
||||
Resource: !Sub arn:aws:iam::${AWS::AccountId}:group/${DeploymentGroup}
|
||||
|
||||
DnsStackDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deployment of DNS stack
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowHostedZoneDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- route53:CreateHostedZone
|
||||
- route53:ListQueryLoggingConfigs
|
||||
- route53:DeleteHostedZone
|
||||
- route53:GetChange
|
||||
- route53:ChangeTagsForResource
|
||||
- route53:GetHostedZone
|
||||
- route53:ChangeResourceRecordSets
|
||||
Resource: '*' # Does not support resource-level permissions https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html#access-control-manage-access-intro-resource-policies
|
||||
|
||||
WebStackDeployPolicy:
|
||||
# We need a role to run s3:PutBucketPolicy, IAM users cannot run it. See https://stackoverflow.com/a/48551383
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows deployment of web stack
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCloudFrontOAIDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudfront:GetCloudFrontOriginAccessIdentity
|
||||
- cloudfront:CreateCloudFrontOriginAccessIdentity
|
||||
- cloudfront:GetCloudFrontOriginAccessIdentityConfig
|
||||
- cloudfront:DeleteCloudFrontOriginAccessIdentity
|
||||
Resource: '*' # Does not support resource-level permissions https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cf-api-permissions-ref.html
|
||||
-
|
||||
Sid: AllowCloudFrontDistributionDeployment
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudfront:CreateDistribution
|
||||
- cloudfront:DeleteDistribution
|
||||
- cloudfront:UpdateDistribution
|
||||
- cloudfront:GetDistribution
|
||||
- cloudfront:TagResource
|
||||
- cloudfront:UpdateCloudFrontOriginAccessIdentity
|
||||
Resource: !Sub arn:aws:cloudfront::${AWS::AccountId}:*
|
||||
-
|
||||
Sid: AllowS3BucketPolicyAccess
|
||||
Effect: Allow
|
||||
Action:
|
||||
- s3:CreateBucket
|
||||
- s3:DeleteBucket
|
||||
- s3:PutBucketWebsite
|
||||
- s3:DeleteBucketPolicy
|
||||
- s3:PutBucketPolicy
|
||||
- s3:GetBucketPolicy
|
||||
Resource: !Sub arn:aws:s3:::${WebStackName}*
|
||||
-
|
||||
Sid: AllowRecordDeploymentToRoute53
|
||||
Effect: Allow
|
||||
Action:
|
||||
- route53:GetHostedZone
|
||||
- route53:ChangeResourceRecordSets
|
||||
- route53:GetChange
|
||||
- route53:ListResourceRecordSets
|
||||
Resource: '*' # Does not support resource-level permissions https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html#access-control-manage-access-intro-resource-policies
|
||||
|
||||
S3SiteDeployPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows listing buckets to be able to list objects in a bucket
|
||||
# ManagedPolicyName: Commented out because CloudFormation requires to rename when replacing custom-named resources
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowListingObjects
|
||||
Effect: Allow
|
||||
Action:
|
||||
- s3:ListBucket # To allow ListObjectsV2
|
||||
Resource: !Sub arn:aws:s3:::${WebStackName}*
|
||||
-
|
||||
Sid: AllowUpdatingObjects
|
||||
Effect: Allow
|
||||
Action:
|
||||
- s3:PutObject
|
||||
- s3:DeleteObject
|
||||
Resource: !Sub arn:aws:s3:::${WebStackName}*/*
|
||||
|
||||
CloudFrontInvalidationPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows creating invalidations on CloudFront
|
||||
# ManagedPolicyName: Commented out because CloudFormation requires to rename when replacing custom-named resource
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCloudFrontInvalidations
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudfront:CreateInvalidation
|
||||
Resource: "*" # Does not support resource-level permissions https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cf-api-permissions-ref.html
|
||||
|
||||
StackExportReaderPolicy:
|
||||
Type: AWS::IAM::ManagedPolicy
|
||||
Properties:
|
||||
Description: Allows creating invalidations on CloudFront
|
||||
# ManagedPolicyName: Commented out because CloudFormation requires to rename when replacing custom-named resource
|
||||
PolicyDocument:
|
||||
Version: 2012-10-17
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowGettingBucketName
|
||||
Effect: Allow
|
||||
Action:
|
||||
- cloudformation:DescribeStacks
|
||||
Resource: !Sub arn:aws:cloudformation:*:${AWS::AccountId}:stack/${WebStackName}/*
|
||||
|
||||
Outputs:
|
||||
ResolveCertificateLambdaRoleArn:
|
||||
Description: The Amazon Resource Name (ARN) of the lambda for deploying certificates.
|
||||
Value: !GetAtt ResolveCertificateLambdaRole.Arn
|
||||
Export:
|
||||
Name: !Join [ ':', [ !Ref 'AWS::StackName', ResolveCertificateLambdaRoleArn ] ]
|
||||
|
||||
CertificateStackDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_CERTIFICATE_STACK_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt CertificateStackDeployRole.Arn
|
||||
|
||||
DnsStackDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_DNS_STACK_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt DnsStackDeployRole.Arn
|
||||
|
||||
IamStackDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_IAM_STACK_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt IamStackDeployRole.Arn
|
||||
|
||||
WebStackDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_WEB_STACK_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt WebStackDeployRole.Arn
|
||||
|
||||
S3SiteDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_S3_SITE_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt S3SiteDeployRole.Arn
|
||||
|
||||
CloudFrontSiteDeployRoleArn:
|
||||
Description: "GitHub secret: AWS_CLOUDFRONT_SITE_DEPLOYMENT_ROLE_ARN"
|
||||
Value: !GetAtt CloudFrontSiteDeployRole.Arn
|
||||
36
aws/scripts/configure/create-role-profile.sh
Normal file
36
aws/scripts/configure/create-role-profile.sh
Normal file
@@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--user-profile) USER_PROFILE="$2"; shift;;
|
||||
--role-profile) ROLE_PROFILE="$2"; shift;;
|
||||
--role-arn) ROLE_ARN="$2"; shift;;
|
||||
--session) SESSION="$2";shift;;
|
||||
--region) REGION="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$USER_PROFILE" ]; then echo "User profile name is not set."; exit 1; fi;
|
||||
if [ -z "$ROLE_PROFILE" ]; then echo "Role profile name is not set."; exit 1; fi;
|
||||
if [ -z "$ROLE_ARN" ]; then echo "Role ARN is not set"; exit 1; fi;
|
||||
if [ -z "$SESSION" ]; then echo "Session name is not set."; exit 1; fi;
|
||||
if [ -z "$REGION" ]; then echo "Region is not set."; exit 1; fi;
|
||||
|
||||
creds=$(aws sts assume-role --role-arn $ROLE_ARN --role-session-name $SESSION --profile $USER_PROFILE)
|
||||
|
||||
aws_access_key_id=$(echo $creds | jq -r '.Credentials.AccessKeyId')
|
||||
echo ::add-mask::$aws_access_key_id
|
||||
aws_secret_access_key=$(echo $creds | jq -r '.Credentials.SecretAccessKey')
|
||||
echo ::add-mask::$aws_secret_access_key
|
||||
aws_session_token=$(echo $creds | jq -r '.Credentials.SessionToken')
|
||||
echo ::add-mask::$aws_session_token
|
||||
|
||||
aws configure --profile $ROLE_PROFILE set aws_access_key_id $aws_access_key_id
|
||||
aws configure --profile $ROLE_PROFILE set aws_secret_access_key $aws_secret_access_key
|
||||
aws configure --profile $ROLE_PROFILE set aws_session_token $aws_session_token
|
||||
aws configure --profile $ROLE_PROFILE set region $REGION
|
||||
|
||||
echo Profile $ROLE_PROFILE is created
|
||||
|
||||
bash "${BASH_SOURCE%/*}/mask-identity.sh" --profile $ROLE_PROFILE
|
||||
25
aws/scripts/configure/create-user-profile.sh
Normal file
25
aws/scripts/configure/create-user-profile.sh
Normal file
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--profile) PROFILE="$2"; shift;;
|
||||
--access-key-id) ACCESS_KEY_ID="$2"; shift;;
|
||||
--secret-access-key) SECRET_ACCESS_KEY="$2"; shift;;
|
||||
--region) REGION="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$PROFILE" ]; then echo "Profile name is not set."; exit 1; fi;
|
||||
echo $PROFILE
|
||||
if [ -z "$ACCESS_KEY_ID" ]; then echo "Access key ID is not set"; exit 1; fi;
|
||||
if [ -z "$SECRET_ACCESS_KEY" ]; then echo "Secret access key is not set."; exit 1; fi;
|
||||
if [ -z "$REGION" ]; then echo "Region is not set."; exit 1; fi;
|
||||
|
||||
aws configure --profile $PROFILE set aws_access_key_id $ACCESS_KEY_ID
|
||||
aws configure --profile $PROFILE set aws_secret_access_key $SECRET_ACCESS_KEY
|
||||
aws configure --profile $PROFILE set region $REGION
|
||||
|
||||
echo Profile $PROFILE is created
|
||||
|
||||
bash "${BASH_SOURCE%/*}/mask-identity.sh" --profile $PROFILE
|
||||
17
aws/scripts/configure/mask-identity.sh
Normal file
17
aws/scripts/configure/mask-identity.sh
Normal file
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--profile) PROFILE="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$PROFILE" ]; then echo "Profile name is not set."; exit 1; fi;
|
||||
|
||||
aws_identity=$(aws sts get-caller-identity --profile $PROFILE)
|
||||
echo ::add-mask::$(echo $aws_identity | jq -r '.Account')
|
||||
echo ::add-mask::$(echo $aws_identity | jq -r '.UserId')
|
||||
echo ::add-mask::$(echo $aws_identity | jq -r '.Arn')
|
||||
|
||||
echo Credentials are masked
|
||||
43
aws/scripts/deploy/deploy-stack.sh
Normal file
43
aws/scripts/deploy/deploy-stack.sh
Normal file
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--template-file) TEMPLATE_FILE="$2"; shift;;
|
||||
--stack-name) STACK_NAME="$2"; shift;;
|
||||
--profile) PROFILE="$2"; shift;;
|
||||
--capabilities) CAPABILITY_IAM="$2"; shift;;
|
||||
--role-arn) ROLE_ARN="$2";shift;;
|
||||
--session) SESSION="$2";shift;;
|
||||
--region) REGION="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$TEMPLATE_FILE" ]; then echo "Template file is not set."; exit 1; fi;
|
||||
if [ -z "$STACK_NAME" ]; then echo "Template file is not set."; exit 1; fi;
|
||||
if [ -z "$PROFILE" ]; then echo "Profile is not set."; exit 1; fi;
|
||||
if [ -z "$ROLE_ARN" ]; then echo "Role ARN is not set."; exit 1; fi;
|
||||
if [ -z "$SESSION" ]; then echo "Role session is not set."; exit 1; fi;
|
||||
|
||||
|
||||
echo Validating stack "$STACK_NAME"
|
||||
aws cloudformation validate-template \
|
||||
--template-body file://$TEMPLATE_FILE \
|
||||
--profile $PROFILE
|
||||
|
||||
ROLE_PROFILE=$STACK_NAME
|
||||
|
||||
echo Assuming role
|
||||
bash "${BASH_SOURCE%/*}/../configure/create-role-profile.sh" \
|
||||
--role-profile $ROLE_PROFILE --user-profile $PROFILE \
|
||||
--role-arn $ROLE_ARN \
|
||||
--session $SESSION \
|
||||
--region $REGION
|
||||
|
||||
echo Deploying stack "$TEMPLATE_FILE"
|
||||
aws cloudformation deploy \
|
||||
--template-file $TEMPLATE_FILE \
|
||||
--stack-name $STACK_NAME \
|
||||
${CAPABILITY_IAM:+ --capabilities $CAPABILITY_IAM} \
|
||||
--no-fail-on-empty-changeset \
|
||||
--profile $ROLE_PROFILE
|
||||
47
aws/scripts/deploy/deploy-to-s3.sh
Normal file
47
aws/scripts/deploy/deploy-to-s3.sh
Normal file
@@ -0,0 +1,47 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--folder) FOLDER="$2"; shift;;
|
||||
--web-stack-name) WEB_STACK_NAME="$2"; shift;;
|
||||
--web-stack-s3-name-output-name) WEB_STACK_S3_NAME_OUTPUT_NAME="$2"; shift;;
|
||||
--storage-class) STORAGE_CLASS="$2"; shift;;
|
||||
--profile) PROFILE="$2"; shift;;
|
||||
--role-arn) ROLE_ARN="$2";shift;;
|
||||
--session) SESSION="$2";shift;;
|
||||
--region) REGION="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$FOLDER" ]; then echo "Folder is not set."; exit 1; fi;
|
||||
if [ -z "$PROFILE" ]; then echo "Profile is not set."; exit 1; fi;
|
||||
if [ -z "$ROLE_ARN" ]; then echo "Role ARN is not set."; exit 1; fi;
|
||||
if [ -z "$SESSION" ]; then echo "Role session is not set."; exit 1; fi;
|
||||
if [ -z "$WEB_STACK_NAME" ]; then echo "Web stack name is not set."; exit 1; fi;
|
||||
if [ -z "$WEB_STACK_S3_NAME_OUTPUT_NAME" ]; then echo "S3 name output name is not set."; exit 1; fi;
|
||||
if [ -z "$STORAGE_CLASS" ]; then echo "S3 object storage class is not set."; exit 1; fi;
|
||||
|
||||
echo Assuming role
|
||||
ROLE_PROFILE=deploy-s3
|
||||
bash "${BASH_SOURCE%/*}/../configure/create-role-profile.sh" \
|
||||
--role-profile $ROLE_PROFILE --user-profile $PROFILE \
|
||||
--role-arn $ROLE_ARN \
|
||||
--session $SESSION \
|
||||
--region $REGION
|
||||
|
||||
echo Getting S3 bucket name from stack "$WEB_STACK_NAME" with output "$WEB_STACK_S3_NAME_OUTPUT_NAME"
|
||||
S3_BUCKET_NAME=$(aws cloudformation describe-stacks \
|
||||
--stack-name $WEB_STACK_NAME \
|
||||
--query "Stacks[0].Outputs[?OutputKey=='$WEB_STACK_S3_NAME_OUTPUT_NAME'].OutputValue" \
|
||||
--output text \
|
||||
--profile $ROLE_PROFILE)
|
||||
if [ -z "$S3_BUCKET_NAME" ]; then echo "Could not read S3 bucket name"; exit 1; fi;
|
||||
echo ::add-mask::$S3_BUCKET_NAME # Just being extra cautious
|
||||
|
||||
echo Syncing folder to S3
|
||||
|
||||
aws s3 sync $FOLDER s3://$S3_BUCKET_NAME \
|
||||
--storage-class $STORAGE_CLASS \
|
||||
--no-progress --follow-symlinks --delete \
|
||||
--profile $ROLE_PROFILE
|
||||
45
aws/scripts/deploy/invalidate-cloudfront-cache.sh
Normal file
45
aws/scripts/deploy/invalidate-cloudfront-cache.sh
Normal file
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Parse parameters
|
||||
while [[ "$#" -gt 0 ]]; do case $1 in
|
||||
--paths) PATHS="$2"; shift;;
|
||||
--web-stack-name) WEB_STACK_NAME="$2"; shift;;
|
||||
--web-stack-cloudfront-arn-output-name) WEB_STACK_CLOUDFRONT_ARN_OUTPUT_NAME="$2"; shift;;
|
||||
--profile) PROFILE="$2"; shift;;
|
||||
--role-arn) ROLE_ARN="$2";shift;;
|
||||
--session) SESSION="$2";shift;;
|
||||
--region) REGION="$2";shift;;
|
||||
*) echo "Unknown parameter passed: $1"; exit 1;;
|
||||
esac; shift; done
|
||||
|
||||
# Verify parameters
|
||||
if [ -z "$PATHS" ]; then echo "Paths is not set."; exit 1; fi;
|
||||
if [ -z "$PROFILE" ]; then echo "Profile is not set."; exit 1; fi;
|
||||
if [ -z "$ROLE_ARN" ]; then echo "Role ARN is not set."; exit 1; fi;
|
||||
if [ -z "$SESSION" ]; then echo "Role session is not set."; exit 1; fi;
|
||||
if [ -z "$WEB_STACK_NAME" ]; then echo "Web stack name is not set."; exit 1; fi;
|
||||
if [ -z "$WEB_STACK_CLOUDFRONT_ARN_OUTPUT_NAME" ]; then echo "CloudFront ARN output name is not set."; exit 1; fi;
|
||||
|
||||
|
||||
echo Assuming role
|
||||
ROLE_PROFILE=invalidate-cloudfront
|
||||
bash "${BASH_SOURCE%/*}/../configure/create-role-profile.sh" \
|
||||
--role-profile $ROLE_PROFILE --user-profile $PROFILE \
|
||||
--role-arn $ROLE_ARN \
|
||||
--session $SESSION \
|
||||
--region $REGION
|
||||
|
||||
echo Getting CloudFront ARN from stack "$WEB_STACK_NAME" with output "$WEB_STACK_CLOUDFRONT_ARN_OUTPUT_NAME"
|
||||
CLOUDFRONT_ARN=$(aws cloudformation describe-stacks \
|
||||
--stack-name $WEB_STACK_NAME \
|
||||
--query "Stacks[0].Outputs[?OutputKey=='$WEB_STACK_CLOUDFRONT_ARN_OUTPUT_NAME'].OutputValue" \
|
||||
--output text \
|
||||
--profile $ROLE_PROFILE)
|
||||
if [ -z "$CLOUDFRONT_ARN" ]; then echo "Could not read CloudFront ARN"; exit 1; fi;
|
||||
echo :add-mask::$CLOUDFRONT_ARN
|
||||
|
||||
echo Syncing folder to S3
|
||||
aws cloudfront create-invalidation \
|
||||
--paths $PATHS \
|
||||
--distribution-id $CLOUDFRONT_ARN \
|
||||
--profile $ROLE_PROFILE
|
||||
138
aws/web-stack.yaml
Normal file
138
aws/web-stack.yaml
Normal file
@@ -0,0 +1,138 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
|
||||
Description: |-
|
||||
> Creates an S3 bucket configured for hosting a static webpage.
|
||||
> Creates CloudFront distribution that has access to read the S3 bucket.
|
||||
|
||||
Parameters:
|
||||
|
||||
RootDomainName:
|
||||
Type: String
|
||||
Default: privacy.sexy
|
||||
Description: The root DNS name of the website e.g. privacy.sexy
|
||||
AllowedPattern: (?!-)[a-zA-Z0-9-.]{1,63}(?<!-)
|
||||
ConstraintDescription: Must be a valid root domain name
|
||||
|
||||
CertificateStackName:
|
||||
Type: String
|
||||
Default: privacysexy-certificate-stack
|
||||
Description: Name of the certificate stack.
|
||||
|
||||
DnsStackName:
|
||||
Type: String
|
||||
Default: privacysexy-dns-stack
|
||||
Description: Name of the certificate stack.
|
||||
|
||||
PriceClass:
|
||||
Type: String
|
||||
Description: The CloudFront distribution price class
|
||||
Default: 'PriceClass_100'
|
||||
AllowedValues:
|
||||
- 'PriceClass_100'
|
||||
- 'PriceClass_200'
|
||||
- 'PriceClass_All'
|
||||
|
||||
Resources:
|
||||
|
||||
S3Bucket:
|
||||
Type: AWS::S3::Bucket
|
||||
Properties:
|
||||
BucketName: !Sub ${AWS::StackName}-${RootDomainName} # Must have stack name for IAM to allow
|
||||
WebsiteConfiguration:
|
||||
IndexDocument: index.html
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
|
||||
S3BucketPolicy:
|
||||
Type: AWS::S3::BucketPolicy
|
||||
Properties:
|
||||
Bucket: !Ref S3Bucket
|
||||
PolicyDocument: # Only used for CloudFront as it's the only way, otherwise use IAM roles in IAM stack.
|
||||
Statement:
|
||||
-
|
||||
Sid: AllowCloudFrontRead
|
||||
Action: s3:GetObject
|
||||
Effect: Allow
|
||||
Principal:
|
||||
CanonicalUser: !GetAtt CloudFrontOriginAccessIdentity.S3CanonicalUserId
|
||||
Resource: !Join ['', ['arn:aws:s3:::', !Ref S3Bucket, /*]]
|
||||
|
||||
CloudFrontOriginAccessIdentity:
|
||||
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
|
||||
Properties:
|
||||
CloudFrontOriginAccessIdentityConfig:
|
||||
Comment: !Sub 'CloudFront OAI for ${S3Bucket}'
|
||||
|
||||
CloudFrontDistribution:
|
||||
Type: AWS::CloudFront::Distribution
|
||||
Properties:
|
||||
DistributionConfig:
|
||||
Comment: Cloudfront Distribution pointing to S3 bucket
|
||||
Origins:
|
||||
-
|
||||
DomainName: !GetAtt S3Bucket.DomainName
|
||||
Id: S3Origin
|
||||
S3OriginConfig:
|
||||
OriginAccessIdentity: !Sub "origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}"
|
||||
Enabled: true
|
||||
HttpVersion: 'http2'
|
||||
DefaultRootObject: index.html
|
||||
Aliases:
|
||||
- !Ref RootDomainName
|
||||
- !Sub 'www.${RootDomainName}'
|
||||
DefaultCacheBehavior:
|
||||
AllowedMethods:
|
||||
- GET
|
||||
- HEAD
|
||||
Compress: true
|
||||
TargetOriginId: S3Origin
|
||||
ForwardedValues:
|
||||
QueryString: true
|
||||
Cookies:
|
||||
Forward: none
|
||||
ViewerProtocolPolicy: redirect-to-https
|
||||
PriceClass: !Ref PriceClass
|
||||
ViewerCertificate:
|
||||
AcmCertificateArn:
|
||||
# Certificate must be validated before it can be used here
|
||||
Fn::ImportValue: !Join [':', [!Ref CertificateStackName, CertificateArn]]
|
||||
SslSupportMethod: sni-only
|
||||
MinimumProtocolVersion: TLSv1.1_2016
|
||||
Tags:
|
||||
-
|
||||
Key: Application
|
||||
Value: privacy.sexy
|
||||
|
||||
CloudFrontDNSRecords:
|
||||
Type: AWS::Route53::RecordSetGroup
|
||||
Properties:
|
||||
HostedZoneId:
|
||||
Fn::ImportValue: !Join [':', [!Ref DnsStackName, DNSHostedZoneId]]
|
||||
RecordSets:
|
||||
-
|
||||
Name: !Ref RootDomainName
|
||||
Type: A
|
||||
AliasTarget:
|
||||
DNSName: !GetAtt CloudFrontDistribution.DomainName
|
||||
EvaluateTargetHealth: false
|
||||
HostedZoneId: Z2FDTNDATAQYW2 # Static CloudFront distribution zone https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-hostedzoneid
|
||||
-
|
||||
Name: !Join ['', ['www.', !Ref RootDomainName]]
|
||||
Type: A
|
||||
AliasTarget:
|
||||
DNSName: !GetAtt CloudFrontDistribution.DomainName
|
||||
EvaluateTargetHealth: false
|
||||
HostedZoneId: Z2FDTNDATAQYW2 # Static CloudFront distribution zone https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-hostedzoneid
|
||||
Outputs:
|
||||
|
||||
CloudFrontDistributionArn: # Used by deployment script to be able to deploy to right S3 bucket
|
||||
Description: Tthe Amazon Resource Name (ARN) of the CloudFront distribution.
|
||||
Value: !Ref CloudFrontDistribution
|
||||
|
||||
S3BucketName: # Used by deployment script to be able to deploy to right S3 bucket
|
||||
Description: Name of the S3 bucket.
|
||||
Value: !Ref S3Bucket
|
||||
|
||||
|
||||
1
docs/app-ddd.drawio
Normal file
1
docs/app-ddd.drawio
Normal file
@@ -0,0 +1 @@
|
||||
<mxfile host="www.draw.io" modified="2019-12-27T03:04:27.829Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" etag="O-1eaon4mqUmgvki0auB" version="12.4.3" pages="1"><diagram id="rhL8jzEM8kVVyiS98U7u" name="Page-1">3Zpdk6I4FIZ/jZdakPDlpa3tzlTNbnVVV83OzE1XhACZAUKF2Or8+k0wCBhau1f8GrpayUkC5HlzTg7IAE7T9V8M5fHfNMDJABjBegBnAwA8YIpPadhsDS50t4aIkWBrMmvDM/mNldFQ1iUJcNFqyClNOMnbRp9mGfZ5y4YYo6t2s5Am7bPmKMKa4dlHiW79lwQ8VsOyjdr+CZMors5sGqomRVVjZShiFNBVwwQfB3DKKOXbvXQ9xYlkV3HZ9pu/Ubu7MIYz/p4OD0/efJxMXmZfs6kd/vj2Txp+HlrVxfFNNWIcCACqSBmPaUQzlDzW1gdGl1mA5WENUarbfKE0F0ZTGH9izjdKTbTkVJhiniaqFq8J/ya7j2xV+t6oma3VkcvCpipknG0anWTxe7Ou7laWqn4FZ/QXntKEsnJ8cFxuomY7cjncN4kqU0GXzMcHMFYzE7EI8wPtwE534S+YplhcqejHcII4eW1fB1IzN9q1q8UVO0rfj2gNrqL1TreWarWI96AbPFG3suuEMbRpNMgpyXjROPKTNIgGKnZC5Zsqctp77n24NTDtvQmzPX09fXbjOGFGwatGj0bsMEbAfmf4uONpaF0zfKjjvqJkqc70xHAhxirOTTNtIrRlXsWE4+cclRhWIlNoSxqSJGkwDmzsBVYXfQ8soOPIHjTj1TyrrgwzjteHxdDhqQ6O23Yf5U2res2H1coeN9Z7xzgTbehc07XMlmu907PMtmeBm3AtcCHX+n8RftwO2iZsBe2j7YHrnj/IQ+9eUsSbmlCnpgwnRQ+gxepJnifE7yNUtwKvFrpDW/51ieGUmzpCw77ddiKdFMXtdhTf3Yw1wzjoCOPu2cK4fS/Oc9P3V/AeEiSoOd2Mpoj0mxotzCAIO7mbhgvH+Ayp0XjPqca6UwGrw6nsczmVpYH+nIUMCSJLny8Z7hV46PnY97uALzzbso0zAHf3clGnA7h3ySjmaMDxK1aZzRugzY+DDrHTDTpwxwvD6GeF8PbYujpbtwMtOBdaV0PLcE4Lwqk6+F3jhR0L8EXxenqoeMw44ffIdj8uXB3uWIPLY4ZRQLLoD8B79dBg6ll8Kn9e6TfsLpDvBbALLoCWZQf9wBXJSRuuYelw7ZHZgRecC6+er4ldEhy7R7pVxMA2R+Obg2xrkAuO+KEU7R18e6C15+xm9ZTjiqjOk2X1MbOc47DMrqej52Olp02o+YDDSGhE/NsDZ+pLymXBVWPoBjfaiNFfG9rtMdMXCg1SEaNc7pK0fJ+giUTCEHyTSUKiTNi4fIizs35BC5w8yYRfTlw4W1DOaSoaJLLiAfm/olKAVjokN9GkPNmkyLfvPcg0CFWFkKylZA/qemYx5/KFiYkkAeZ+kFkj4tMsJEJaNvLFGcFcrHxIfEm7iDlz4UK0GKIsGC6Y+JQmW6Ykc+i4L1+X+GfxIpuINMUb5VXG1+t9r60Jb1/yMQPQ16771x1+WPchCugC79QHnvfyjIqiR91NcGPC6yvx/QtvHhV+ka3Ep5B1Lf7FnlgYpFk+3Sp6Uhq4+zkqBCNdbQh1tStb/2rrucT9q20cVTukLMLZsMBU/rI/d8Stwjwn5fPTYkhzTlLyu0wKenR0WN0O7MTXpbc6pLc+LL0o1m/WbX8JrV9PhI//AQ==</diagram></mxfile>
|
||||
BIN
docs/app-ddd.png
Normal file
BIN
docs/app-ddd.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
1
docs/aws-cloudformation.drawio
Normal file
1
docs/aws-cloudformation.drawio
Normal file
File diff suppressed because one or more lines are too long
BIN
docs/aws-cloudformation.png
Normal file
BIN
docs/aws-cloudformation.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 240 KiB |
1
docs/aws-solution.drawio
Normal file
1
docs/aws-solution.drawio
Normal file
@@ -0,0 +1 @@
|
||||
<mxfile host="www.draw.io" modified="2019-12-29T21:35:34.328Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" etag="LWtfN3d2vMzgiAxeFzmX" version="12.4.7" type="device"><diagram id="BVMBOj3UG5-BUR7rQ3gz" name="Page-1">7Zpbb9s2FIB/TYDtwYIo6vpoO/FWtBuKeli7vRiMRMlcZdGj6Njur9+hRMm6xU5SGUu7yQEkHVK8nPOdw1tu8Hxz+EmQ7foXHtH0xjKjww2+vbEsZGIPbkpyLCUTZDulJBEs0rlOgiX7QqtPtXTHIpq3MkrOU8m2bWHIs4yGsiUjQvB9O1vM03atW5LQnmAZkrQv/cgiuS6lvmOe5D9TlqyrmpGpUzakyqwF+ZpEfN8Q4bsbPBecy/Jpc5jTVGmv0kv53eKR1LphgmbyKR+8+/TpYf/Gu//D/fDbW28VWn8e3k50KQ8k3ekO68bKY6UBwXdZRFUh5g2e7ddM0uWWhCp1D0YH2VpuUnhD8BizNJ3zlIviWxzH1A1DkOdS8M+0kRJ5wb2pCkwEiRh0ofWVuiBNN44KSQ+P9hrVugQKKd9QKY6QRX+AK0tpAJFVGWh/MqcdaNm6YUrL00KiEUrqwk9ahget6Gco3eopfZ7yXbQQHPrUVT/fyZRloLqKb6W0mLcUBr+Fqn9ImYHt3C6sRtotE1AQ4xmkZ1woHXTN5kyxOXOGzFabJiL5uoZCWYiBz7wj9zR9z3Omi7/nUvJNI8M0ZYlKkFxxQ/RbCK2iogMS9FBHA2RV71orKp3k21IdMTuodszAvbYqcXNIVCgyyD63DUFzvhMhfROq9szgtXxq5wqV9uNC+3iWdvpQNy5q6A1KLfQ2AqCOhwzf7zBq9xn1/D6ilWx0QnGP0CUenUzXnGIYH55FpuV5CLn/GTJzrNLqAIzK0sphpAieKclz/RzyDQv18whcetg0zMaFXhmidg/R3xmYF3Doclrpn22Ksb5py2HrX4SmiBEzEn5OCtsMUVhUNq1QMIe40O25XUupJjNTpQ9rEUaZZTBgIWZgdWGAWUEaEUngpuQ53DO6nxwpEROFUbpT7VNiF5SyaIgmZjBBlm9ss+RcZOvR3kb661myumOwbffhGRiCrzYCOz14bvmGsAxkH2jCILiQPkdbzpR+7h6g1/mQN7YiT4OydqzKeEYHhlxT/c5Z6YWhbDBK9yzejVE8jllIjZyKB7jnEK60VlZadA1KkNfBxME9TBy3j4ljXQkTt4fJRLVmvze2gj2Q8AgKOkA1bqpmDveAjJuoJ5WrnaODEo1gkaFf1UDHE56R9O4knbVn3ac877iyaoHVX1TKox6JyE7yIeiqNYvVJy4i1I8H5+ZlwG9gktJY1qOKavt5C0NXi7HtcvSWRCRUXnLUR4mZqCEKOy1qKkAETYlkD+2mDhGiS3+vvPtUtO25RoA90/F9cE4rcLtodkJT2WNdSHMV9rxybWQbQQfnUkmXi55U7qILw52hF3w6p60iCqeo1fpyP/F6flL7ROUSHyAOUdXAUg7V1En/L3kuTywHJxBfMbEUyhwrB4+0yA58I7Bf2QTR70FZDOB5sYP0rUbkEUOw88QQ7F0KwTBMd6KYP0oI9q0+VL7zsrBr2b7h2cHpulTwxaB7/aga9AAWtNyEyL9VfB9ZOFVT4naIvwb03hOhty7OOwIraCEUjMI8Nu1LnBq4cb3QHWxzIGD7nuE/XvQrcAjU362mWcyhxyqol8vo87vX18A+dtRvCHu3uIoUIuRUnUaooV/t2bCwEi9YWlVVTzCql/dEwiwhKySWic64yHnHGtGBrCc6ELIveRBynbYHWXgUF7J9mGHbjZ0r51mcP9mFXNewz1SDXd9wfQuZyHURzJDc1+dO/XOIkIRr+p2OLv+CE+CzPqAWr6hNzTiDyGUP6My5n8q8E2DD7m7S+MHrI7t/ftFj+jvcFSYb8oVnE1jgTXJJs5ClSlqcSC9+hYRluXW3WkKVLGbhKuTb42o1/bhcFQeQ9V7xCCtCFBiO9+jpAcL9xSGsIbG2W3N92BCPvkRE/UOEaoMi35KsBYz7906d1M/C0qxT5abJ/Q/QD/iD6s3G04+n7NUmx1zRAzonkkKOX0gGVhaN3ZCyvittiCwcGyaVz9sQmXsIo8Wr3RAZ/Qz4ZJ/VprTO6oq7I9i92u6IOgKq/6mkjKin/83Bd/8A</diagram></mxfile>
|
||||
BIN
docs/aws-solution.png
Normal file
BIN
docs/aws-solution.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
1
docs/ci-cd.drawio
Normal file
1
docs/ci-cd.drawio
Normal file
@@ -0,0 +1 @@
|
||||
<mxfile host="www.draw.io" modified="2019-12-30T13:07:22.931Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" etag="vfXOAJJrIONaUEloGBPR" version="12.4.7" type="device"><diagram id="ymF_tBZ9P2_Wfw9L8arg" name="Page-1">5Vpbb9s2FP41AbYHC7zp9hjHdVqsGwpkQNu9FIxEy2xlUaWo2N6v36FEOZLlXNw6S7IpQUwd3j9+/M4hnTN6sdpcal4uf1epyM8ISjdndHZGSOQT+GsN29YwIRFqLZmWaWvDt4Yr+bdwxq5YLVNRDQoapXIjy6ExUUUhEjOwca3VelhsofJhryXPxMhwlfB8bP0oU7Ps5oVu7W+FzJZdzxi5nBXvCjtDteSpWvdM9M0ZvdBKmTa12lyI3ILX4dLWm9+RuxuYFoV5TAWx2swv/wy+49kff33Kok8f39/8NnHLc8Pz2k14JspcbStbsVhoXhldJ6bWwk3CbDtktKqLVNjG0RmdKm2WKlMFz98rVYIRg/GrMGbr1pTXRoFpaVa5y015tWzqdy8fuDFCF42FIGsdz9FNu1K1TsQ9E2OOK1xnwtxTDvttQZEOeOAgvBRqJYzeQgHH6AnyCGVBW8mRmro2tMi5kTdD5nBHwGzX1K71D0rCtHZN05B6FB4/ZiGNCQoHneAgxF7Mho22MLh2+mu/17QfIA8F8e0zbBrHyMOxH0IyojgkZNhLC+LDvezNWC0WlRjUgEQP01tTw9QjWEtHrJ3WMk+rRgdSoGqQw5pPrzWkMptqSQ3Za3FtR1iWuUxgrVTxH6V1eDSrEQuGhCPsNKxm2KMIIYZY5Ef0dJwOgsALaLij9HBPYqC71yN87B/J6adnMRux+FKat7Ul6HliuVmNyAk+pLRJuWrcVp92N0Ib4HR+nsvMcs1Yuu6s7/m1yD+oSjacp7NrZYxaQYHcZkx58i1riH+hcqWbvuiieaBI09l5Vbbu1e4K3r0s5MZSferGM1saY/3yucWKzJO0YJ4Ez7yQsKW0l0CPZJ5yw+HD2iv7qYou6WPiMiaVSiTPJ5k0y/p6gknklUUGHS1knndjLFRhMViowlw5iA44RWeyQIjNY/YCCXwvYOj2YUNikcA59PVtPAADbG3LfizQGQ9tlgGZjmWOP2LOuwJeJEArGhHkyfKFOezHKhE4IhoPEacnEqKYgl7c6QMp6IUfhjTwGWUhi+kPelofeywaNs380KMEiERiGuGXKEXBiFAXuarTuVZuTH0eqdrkshAXu4gbuV3YEw/4mdv+p5nmqRSDvJj5sznp5c2kFokTpsLycm+jQx3/nKKpD3aIR9U3cUimduxEj9G9w3LJ3VsCoxJ6yP5GZ9qtgclIdw6IYifWq01mz0YeX1fM06Jl0rvEjmcKr21qWCqx6C8a9J1E9+awG1zaww1abXA7gQAepDAdi154QPPCp5K8cMTQK3pyZgbonNLwOGaSMMQ4+N8ws6I2b+dJcNtae7C108tyXlUuDf5eJi59El5SL9p3xpH/vLyMRryciZvXH7eRB+O2QqwnW8H1xPImr128Og9ggeY90wTFvfDtTikb0fvUUZ0PJ5z+Q/d5FI95hA7wCD0Rj+IRj8q6qaXF91pUNgyQ1fhguxIQO6TNpVhz51RZ9J4j8IOV0dtProvm5bN98fzudbbpZ862D+nCg0dht/MePAqz4wJQOApTTIcyc6KjMEN0cLLA+xEo82gckBgHPmE4+tEINACZJHfGuYwhj4Uh8eMwBK8eBi8uGO2ufnt74fULKn1QUMVKfZUTbPnaqugXmGO5/VKtZC6295+BD8Qyu1GfQDztsexY9SQH1JM8lXpiPKLMmDPQjiwrC9d6KY24KnmjL2sIbvbiqWGEt1iIIEkORXhpGF8j9ATeiu0Dvne5hSPidRrVw5ziMeb0yTAff3cwjshfE+bB/ZhD/PnMgI+vvdmrBjxi9wJOGX1mwMc3tPg1A473g+ARw8eH/H8X8PHFZhfyViUvBsAH32v7zSkcMhvgzm14ll3/AkODX+ge9VK/2qT1hMhCOlm7udg6oS3XtdVF1e3ll9Ir9xVROwSYUjuKttCICT97+zCnjEVH3otNLzD1X+7tw8EY6afvxXYL82TXCqA9h/zriW4W7Al597V/GzXf/vMEffMP</diagram></mxfile>
|
||||
BIN
docs/ci-cd.png
Normal file
BIN
docs/ci-cd.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
11303
package-lock.json
generated
Normal file
11303
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
42
package.json
Normal file
42
package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "privacy.sexy",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
"build": "vue-cli-service build",
|
||||
"lint": "vue-cli-service lint",
|
||||
"test:unit": "vue-cli-service test:unit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^1.2.26",
|
||||
"@fortawesome/free-brands-svg-icons": "^5.12.0",
|
||||
"@fortawesome/free-regular-svg-icons": "^5.12.0",
|
||||
"@fortawesome/free-solid-svg-icons": "^5.12.0",
|
||||
"@fortawesome/vue-fontawesome": "^0.1.9",
|
||||
"ace-builds": "^1.4.7",
|
||||
"file-saver": "^2.0.2",
|
||||
"inversify": "^5.0.1",
|
||||
"liquor-tree": "^0.2.70",
|
||||
"v-tooltip": "^2.0.2",
|
||||
"vue": "^2.6.11",
|
||||
"vue-class-component": "^7.1.0",
|
||||
"vue-property-decorator": "^8.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/chai": "^4.2.7",
|
||||
"@types/mocha": "^5.2.7",
|
||||
"@types/ace": "0.0.42",
|
||||
"@types/file-saver": "^2.0.1",
|
||||
"@vue/cli-plugin-typescript": "^4.1.1",
|
||||
"@vue/cli-plugin-unit-mocha": "^4.1.1",
|
||||
"@vue/cli-service": "^4.1.1",
|
||||
"@vue/test-utils": "1.0.0-beta.30",
|
||||
"chai": "^4.2.0",
|
||||
"sass": "^1.24.0",
|
||||
"sass-loader": "^8.0.0",
|
||||
"js-yaml-loader": "^1.2.2",
|
||||
"typescript": "^3.7.4",
|
||||
"vue-template-compiler": "^2.6.11"
|
||||
}
|
||||
}
|
||||
5
postcss.config.js
Normal file
5
postcss.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
autoprefixer: {}
|
||||
}
|
||||
}
|
||||
BIN
public/favicon.ico
Normal file
BIN
public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
21
public/index.html
Normal file
21
public/index.html
Normal file
@@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||
<title>Privacy is sexy 🍑🍆</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<strong>
|
||||
The page does not work without JavaScript enabled.
|
||||
Please enable it to continue.
|
||||
There's no shady stuff as 100% of the website is open source.
|
||||
</strong>
|
||||
</noscript>
|
||||
<div id="app"></div>
|
||||
<!-- built files will be auto injected -->
|
||||
</body>
|
||||
</html>
|
||||
83
src/App.vue
Normal file
83
src/App.vue
Normal file
@@ -0,0 +1,83 @@
|
||||
<template>
|
||||
<div id="app">
|
||||
<div class="wrapper">
|
||||
<TheHeader
|
||||
class="row"
|
||||
github-url="https://github.com/undergroundwires/privacy.sexy"/>
|
||||
<!-- <TheSearchBar> </TheSearchBar> -->
|
||||
<!-- <div style="display: flex; justify-content: space-between;"> -->
|
||||
<!-- <TheGrouper></TheGrouper> -->
|
||||
<TheSelector class="row" />
|
||||
<!-- </div> -->
|
||||
<CardList />
|
||||
<TheCodeArea class="row" theme="xcode"/>
|
||||
<TheCodeButtons class="row" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Vue, Prop } from 'vue-property-decorator';
|
||||
import { ApplicationState, IApplicationState } from '@/application/State/ApplicationState';
|
||||
import TheHeader from './presentation/TheHeader.vue';
|
||||
import TheCodeArea from './presentation/TheCodeArea.vue';
|
||||
import TheCodeButtons from './presentation/TheCodeButtons.vue';
|
||||
import TheSearchBar from './presentation/TheSearchBar.vue';
|
||||
import TheSelector from './presentation/Scripts/Selector/TheSelector.vue';
|
||||
import TheGrouper from './presentation/Scripts/TheGrouper.vue';
|
||||
import CardList from './presentation/Scripts/Cards/CardList.vue';
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
TheHeader,
|
||||
TheCodeArea,
|
||||
TheCodeButtons,
|
||||
TheSearchBar,
|
||||
TheGrouper,
|
||||
CardList,
|
||||
TheSelector,
|
||||
},
|
||||
})
|
||||
export default class App extends Vue {
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
@import "@/presentation/styles/fonts.scss";
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
background: $light-gray;
|
||||
font-family: 'Slabo 27px', serif;
|
||||
color: $slate;
|
||||
}
|
||||
|
||||
|
||||
#app {
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
max-width: 1500px;
|
||||
|
||||
.wrapper {
|
||||
margin: 0% 2% 0% 2%;
|
||||
background-color: white;
|
||||
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.06);
|
||||
padding: 2%;
|
||||
display:flex;
|
||||
flex-direction: column;
|
||||
|
||||
.row {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@import "@/presentation/styles/tooltip.scss";
|
||||
@import "@/presentation/styles/tree.scss";
|
||||
</style>
|
||||
103
src/application/ApplicationParser.ts
Normal file
103
src/application/ApplicationParser.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Category } from '../domain/Category';
|
||||
import { Application } from '../domain/Application';
|
||||
import { Script } from '@/domain/Script';
|
||||
// import applicationFile from 'js-yaml-loader!@/application/application.yaml';
|
||||
// import applicationFile from 'json-loader!yaml-loader!@/application/application.yaml';
|
||||
import applicationFile, { YamlCategory, YamlScript, YamlDocumentable } from 'js-yaml-loader!./application.yaml';
|
||||
// import test from './test-loader!./test.txt';
|
||||
|
||||
interface ApplicationResult {
|
||||
readonly application: Application;
|
||||
readonly selectedScripts: Script[];
|
||||
}
|
||||
|
||||
export class ApplicationParser {
|
||||
|
||||
public static buildApplication(): ApplicationResult {
|
||||
const name = applicationFile.name as string;
|
||||
const version = applicationFile.version as number;
|
||||
const categories = new Array<Category>();
|
||||
const selectedScripts = new Array<Script>();
|
||||
if (!applicationFile.actions || applicationFile.actions.length <= 0) {
|
||||
throw new Error('Application does not define any action');
|
||||
}
|
||||
for (const action of applicationFile.actions) {
|
||||
const category = ApplicationParser.parseCategory(action, selectedScripts);
|
||||
categories.push(category);
|
||||
}
|
||||
const app = new Application(name, version, categories);
|
||||
return {application: app, selectedScripts};
|
||||
}
|
||||
private static categoryIdCounter = 0;
|
||||
|
||||
private static parseCategory(category: YamlCategory, selectedScripts: Script[]): Category {
|
||||
if (!category.children || category.children.length <= 0) {
|
||||
throw Error('Category has no children');
|
||||
}
|
||||
const subCategories = new Array<Category>();
|
||||
const subScripts = new Array<Script>();
|
||||
for (const categoryOrScript of category.children) {
|
||||
if (ApplicationParser.isCategory(categoryOrScript)) {
|
||||
const subCategory = ApplicationParser.parseCategory(categoryOrScript as YamlCategory, selectedScripts);
|
||||
subCategories.push(subCategory);
|
||||
} else if (ApplicationParser.isScript(categoryOrScript)) {
|
||||
const yamlScript = categoryOrScript as YamlScript;
|
||||
const script = new Script(
|
||||
/* name */ yamlScript.name,
|
||||
/* code */ yamlScript.code,
|
||||
/* docs */ this.parseDocUrls(yamlScript));
|
||||
subScripts.push(script);
|
||||
if (yamlScript.default === true) {
|
||||
selectedScripts.push(script);
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Child element is neither a category or a script.
|
||||
Parent: ${category.category}, element: ${categoryOrScript}`);
|
||||
}
|
||||
}
|
||||
return new Category(
|
||||
/*id*/ ApplicationParser.categoryIdCounter++,
|
||||
/*name*/ category.category,
|
||||
/*docs*/ this.parseDocUrls(category),
|
||||
/*categories*/ subCategories,
|
||||
/*scripts*/ subScripts,
|
||||
);
|
||||
}
|
||||
|
||||
private static parseDocUrls(documentable: YamlDocumentable): ReadonlyArray<string> {
|
||||
if (!documentable.docs) {
|
||||
return [];
|
||||
}
|
||||
const docs = documentable.docs;
|
||||
const result = new Array<string>();
|
||||
const addDoc = (doc: string) => {
|
||||
if (!doc) {
|
||||
throw new Error('Documentiton url is null or empty');
|
||||
}
|
||||
if (doc.includes('\n')) {
|
||||
throw new Error('Documentation url cannot be multi-lined.');
|
||||
}
|
||||
result.push(doc);
|
||||
};
|
||||
if (docs instanceof Array) {
|
||||
for (const doc of docs) {
|
||||
if (typeof doc !== 'string') {
|
||||
throw new Error('Docs field (documentation url) must be an array of strings');
|
||||
}
|
||||
addDoc(doc as string);
|
||||
}
|
||||
} else if (typeof docs === 'string') {
|
||||
addDoc(docs as string);
|
||||
} else {
|
||||
throw new Error('Docs field (documentation url) must a string or array of strings');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static isScript(categoryOrScript: any): boolean {
|
||||
return categoryOrScript.code && categoryOrScript.code.length > 0;
|
||||
}
|
||||
private static isCategory(categoryOrScript: any): boolean {
|
||||
return categoryOrScript.category && categoryOrScript.category.length > 0;
|
||||
}
|
||||
}
|
||||
65
src/application/State/ApplicationState.ts
Normal file
65
src/application/State/ApplicationState.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { UserFilter } from './Filter/UserFilter';
|
||||
import { IUserFilter } from './Filter/IUserFilter';
|
||||
import { ApplicationCode } from './Code/ApplicationCode';
|
||||
import { UserSelection } from './Selection/UserSelection';
|
||||
import { IUserSelection } from './Selection/IUserSelection';
|
||||
import { AsyncLazy } from '../../infrastructure/Threading/AsyncLazy';
|
||||
import { Signal } from '../../infrastructure/Events/Signal';
|
||||
import { ICategory } from '../../domain/ICategory';
|
||||
import { ApplicationParser } from '../ApplicationParser';
|
||||
import { IApplicationState } from './IApplicationState';
|
||||
import { Script } from '../../domain/Script';
|
||||
import { Application } from '../../domain/Application';
|
||||
import { IApplicationCode } from './Code/IApplicationCode';
|
||||
|
||||
/** Mutatable singleton application state that's the single source of truth throughout the application */
|
||||
export class ApplicationState implements IApplicationState {
|
||||
/** Get singleton application state */
|
||||
public static GetAsync(): Promise<IApplicationState> {
|
||||
return ApplicationState.instance.getValueAsync();
|
||||
}
|
||||
|
||||
/** Application instance with all scripts. */
|
||||
private static instance = new AsyncLazy<IApplicationState>(() => {
|
||||
const app = ApplicationParser.buildApplication();
|
||||
const state = new ApplicationState(app.application, app.selectedScripts);
|
||||
return Promise.resolve(state);
|
||||
});
|
||||
|
||||
public readonly code: IApplicationCode;
|
||||
public readonly stateChanged = new Signal<IApplicationState>();
|
||||
public readonly selection: IUserSelection;
|
||||
public readonly filter: IUserFilter;
|
||||
|
||||
private constructor(
|
||||
/** Inner instance of the all scripts */
|
||||
private readonly app: Application,
|
||||
/** Initially selected scripts */
|
||||
public readonly defaultScripts: Script[]) {
|
||||
this.selection = new UserSelection(app, defaultScripts);
|
||||
this.code = new ApplicationCode(this.selection, app.version.toString());
|
||||
this.filter = new UserFilter(app);
|
||||
}
|
||||
|
||||
public getCategory(categoryId: number): ICategory | undefined {
|
||||
return this.app.findCategory(categoryId);
|
||||
}
|
||||
|
||||
public get categories(): ReadonlyArray<ICategory> {
|
||||
return this.app.categories;
|
||||
}
|
||||
|
||||
public get appName(): string {
|
||||
return this.app.name;
|
||||
}
|
||||
|
||||
public get appVersion(): number {
|
||||
return this.app.version;
|
||||
}
|
||||
|
||||
public get appTotalScripts(): number {
|
||||
return this.app.totalScripts;
|
||||
}
|
||||
}
|
||||
|
||||
export { IApplicationState, IUserFilter };
|
||||
27
src/application/State/Code/ApplicationCode.ts
Normal file
27
src/application/State/Code/ApplicationCode.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { CodeBuilder } from './CodeBuilder';
|
||||
import { IUserSelection } from './../Selection/IUserSelection';
|
||||
import { Signal } from '@/infrastructure/Events/Signal';
|
||||
import { IApplicationCode } from './IApplicationCode';
|
||||
import { IScript } from '@/domain/IScript';
|
||||
|
||||
export class ApplicationCode implements IApplicationCode {
|
||||
public readonly changed = new Signal<string>();
|
||||
public current: string;
|
||||
|
||||
private readonly codeBuilder: CodeBuilder;
|
||||
|
||||
constructor(userSelection: IUserSelection, private readonly version: string) {
|
||||
if (!userSelection) { throw new Error('userSelection is null or undefined'); }
|
||||
if (!version) { throw new Error('version is null or undefined'); }
|
||||
this.codeBuilder = new CodeBuilder();
|
||||
this.setCode(userSelection.selectedScripts);
|
||||
userSelection.changed.on((scripts) => {
|
||||
this.setCode(scripts);
|
||||
});
|
||||
}
|
||||
|
||||
private setCode(scripts: ReadonlyArray<IScript>) {
|
||||
this.current = this.codeBuilder.buildCode(scripts, this.version);
|
||||
this.changed.notify(this.current);
|
||||
}
|
||||
}
|
||||
27
src/application/State/Code/CodeBuilder.ts
Normal file
27
src/application/State/Code/CodeBuilder.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { AdminRightsFunctionRenderer } from './Renderer/AdminRightsFunctionRenderer';
|
||||
import { AsciiArtRenderer } from './Renderer/AsciiArtRenderer';
|
||||
import { FunctionRenderer } from './Renderer/FunctionRenderer';
|
||||
import { Script } from '@/domain/Script';
|
||||
|
||||
export class CodeBuilder {
|
||||
private readonly functionRenderer: FunctionRenderer;
|
||||
private readonly adminRightsFunctionRenderer: AdminRightsFunctionRenderer;
|
||||
private readonly asciiArtRenderer: AsciiArtRenderer;
|
||||
|
||||
public constructor() {
|
||||
this.functionRenderer = new FunctionRenderer();
|
||||
this.adminRightsFunctionRenderer = new AdminRightsFunctionRenderer();
|
||||
this.asciiArtRenderer = new AsciiArtRenderer();
|
||||
}
|
||||
|
||||
public buildCode(scripts: ReadonlyArray<Script>, version: string): string {
|
||||
if (!scripts) { throw new Error('scripts is undefined'); }
|
||||
if (!version) { throw new Error('version is undefined'); }
|
||||
return `@echo off\n\n${this.asciiArtRenderer.renderAsciiArt(version)}\n\n`
|
||||
+ `${this.adminRightsFunctionRenderer.renderAdminRightsFunction()}\n\n`
|
||||
+ scripts.map((script) => this.functionRenderer.renderFunction(script.name, script.code)).join('\n\n')
|
||||
+ '\n\n'
|
||||
+ 'pause\n'
|
||||
+ 'exit /b 0';
|
||||
}
|
||||
}
|
||||
6
src/application/State/Code/IApplicationCode.ts
Normal file
6
src/application/State/Code/IApplicationCode.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { ISignal } from '@/infrastructure/Events/ISignal';
|
||||
|
||||
export interface IApplicationCode {
|
||||
readonly changed: ISignal<string>;
|
||||
readonly current: string;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { FunctionRenderer } from './FunctionRenderer';
|
||||
|
||||
export class AdminRightsFunctionRenderer {
|
||||
private readonly functionRenderer: FunctionRenderer;
|
||||
constructor() {
|
||||
this.functionRenderer = new FunctionRenderer();
|
||||
}
|
||||
public renderAdminRightsFunction() {
|
||||
const name = 'Ensure admin priviliges';
|
||||
const code = 'fltmc >nul 2>&1 || (\n' +
|
||||
' echo This batch script requires administrator privileges. Right-click on\n' +
|
||||
' echo the script and select "Run as administrator".\n' +
|
||||
' pause\n' +
|
||||
' exit 1\n' +
|
||||
')';
|
||||
return this.functionRenderer.renderFunction(name, code);
|
||||
}
|
||||
}
|
||||
16
src/application/State/Code/Renderer/AsciiArtRenderer.ts
Normal file
16
src/application/State/Code/Renderer/AsciiArtRenderer.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { CodeRenderer } from './CodeRenderer';
|
||||
|
||||
export class AsciiArtRenderer extends CodeRenderer {
|
||||
public renderAsciiArt(version: string): string {
|
||||
if (!version) { throw new Error('Version is not defined'); }
|
||||
return (
|
||||
'██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ██████╗██╗ ██╗███████╗███████╗██╗ ██╗██╗ ██╗\n' +
|
||||
'██╔══██╗██╔══██╗██║██║ ██║██╔══██╗██╔════╝╚██╗ ██╔╝██╔════╝██╔════╝╚██╗██╔╝╚██╗ ██╔╝\n' +
|
||||
'██████╔╝██████╔╝██║██║ ██║███████║██║ ╚████╔╝ ███████╗█████╗ ╚███╔╝ ╚████╔╝ \n' +
|
||||
'██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║██║ ╚██╔╝ ╚════██║██╔══╝ ██╔██╗ ╚██╔╝ \n' +
|
||||
'██║ ██║ ██║██║ ╚████╔╝ ██║ ██║╚██████╗ ██║██╗███████║███████╗██╔╝ ██╗ ██║ \n' +
|
||||
'╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ')
|
||||
.split('\n').map((line) => this.renderComment(line)).join('\n')
|
||||
+ `\n${this.renderComment(`https://privacy.sexy — v${version} — ${new Date().toUTCString()}`)}`;
|
||||
}
|
||||
}
|
||||
11
src/application/State/Code/Renderer/CodeRenderer.ts
Normal file
11
src/application/State/Code/Renderer/CodeRenderer.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
|
||||
export abstract class CodeRenderer {
|
||||
|
||||
protected readonly totalFunctionSeparatorChars = 58;
|
||||
|
||||
protected readonly trailingHyphens = '-'.repeat(this.totalFunctionSeparatorChars);
|
||||
|
||||
protected renderComment(line?: string): string {
|
||||
return line ? `:: ${line}` : ':: ';
|
||||
}
|
||||
}
|
||||
31
src/application/State/Code/Renderer/FunctionRenderer.ts
Normal file
31
src/application/State/Code/Renderer/FunctionRenderer.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { CodeRenderer } from './CodeRenderer';
|
||||
|
||||
export class FunctionRenderer extends CodeRenderer {
|
||||
public renderFunction(name: string, code: string) {
|
||||
if (!name) { throw new Error('name cannot be empty or null'); }
|
||||
if (!code) { throw new Error('code cannot be empty or null'); }
|
||||
return this.renderFunctionStartComment(name) + '\n'
|
||||
+ `echo --- ${name}` + '\n'
|
||||
+ code + '\n'
|
||||
+ this.renderFunctionEndComment();
|
||||
}
|
||||
|
||||
private renderFunctionStartComment(functionName: string): string {
|
||||
if (functionName.length >= this.totalFunctionSeparatorChars) {
|
||||
return this.renderComment(functionName);
|
||||
}
|
||||
return this.renderComment(this.trailingHyphens) + '\n' +
|
||||
this.renderFunctionName(functionName) + '\n' +
|
||||
this.renderComment(this.trailingHyphens);
|
||||
}
|
||||
|
||||
private renderFunctionName(functionName: string) {
|
||||
const autoFirstHypens = '-'.repeat(Math.floor((this.totalFunctionSeparatorChars - functionName.length) / 2));
|
||||
const secondHypens = '-'.repeat(Math.ceil((this.totalFunctionSeparatorChars - functionName.length) / 2));
|
||||
return `${this.renderComment()}${autoFirstHypens}${functionName}${secondHypens}`;
|
||||
}
|
||||
|
||||
private renderFunctionEndComment(): string {
|
||||
return this.renderComment(this.trailingHyphens);
|
||||
}
|
||||
}
|
||||
7
src/application/State/Filter/IFilterMatches.ts
Normal file
7
src/application/State/Filter/IFilterMatches.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { IScript, ICategory } from '@/domain/ICategory';
|
||||
|
||||
export interface IFilterMatches {
|
||||
readonly scriptMatches: ReadonlyArray<IScript>;
|
||||
readonly categoryMatches: ReadonlyArray<ICategory>;
|
||||
readonly query: string;
|
||||
}
|
||||
9
src/application/State/Filter/IUserFilter.ts
Normal file
9
src/application/State/Filter/IUserFilter.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IFilterMatches } from './IFilterMatches';
|
||||
import { ISignal } from '@/infrastructure/Events/Signal';
|
||||
|
||||
export interface IUserFilter {
|
||||
readonly filtered: ISignal<IFilterMatches>;
|
||||
readonly filterRemoved: ISignal<void>;
|
||||
setFilter(filter: string): void;
|
||||
removeFilter(): void;
|
||||
}
|
||||
34
src/application/State/Filter/UserFilter.ts
Normal file
34
src/application/State/Filter/UserFilter.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { IFilterMatches } from './IFilterMatches';
|
||||
import { Application } from '../../../domain/Application';
|
||||
import { IUserFilter } from './IUserFilter';
|
||||
import { Signal } from '@/infrastructure/Events/Signal';
|
||||
|
||||
export class UserFilter implements IUserFilter {
|
||||
public readonly filtered = new Signal<IFilterMatches>();
|
||||
public readonly filterRemoved = new Signal<void>();
|
||||
|
||||
constructor(private application: Application) {
|
||||
|
||||
}
|
||||
|
||||
public setFilter(filter: string): void {
|
||||
if (!filter) {
|
||||
throw new Error('Filter must be defined and not empty. Use removeFilter() to remove the filter');
|
||||
}
|
||||
const filteredScripts = this.application.getAllScripts().filter(
|
||||
(script) => script.name.toLowerCase().includes(filter.toLowerCase())
|
||||
|| script.code.toLowerCase().includes(filter.toLowerCase()));
|
||||
|
||||
const matches: IFilterMatches = {
|
||||
scriptMatches: filteredScripts,
|
||||
categoryMatches: null,
|
||||
query: filter,
|
||||
};
|
||||
|
||||
this.filtered.notify(matches);
|
||||
}
|
||||
|
||||
public removeFilter(): void {
|
||||
this.filterRemoved.notify();
|
||||
}
|
||||
}
|
||||
21
src/application/State/IApplicationState.ts
Normal file
21
src/application/State/IApplicationState.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { IUserFilter } from './Filter/IUserFilter';
|
||||
import { IUserSelection } from './Selection/IUserSelection';
|
||||
import { ISignal } from '@/infrastructure/Events/ISignal';
|
||||
import { ICategory, IScript } from '@/domain/ICategory';
|
||||
import { IApplicationCode } from './Code/IApplicationCode';
|
||||
export { IUserSelection, IApplicationCode, IUserFilter };
|
||||
|
||||
export interface IApplicationState {
|
||||
/** Event that fires when the application states changes with new application state as parameter */
|
||||
readonly code: IApplicationCode;
|
||||
readonly filter: IUserFilter;
|
||||
readonly stateChanged: ISignal<IApplicationState>;
|
||||
readonly categories: ReadonlyArray<ICategory>;
|
||||
readonly appName: string;
|
||||
readonly appVersion: number;
|
||||
readonly appTotalScripts: number;
|
||||
readonly selection: IUserSelection;
|
||||
readonly defaultScripts: ReadonlyArray<IScript>;
|
||||
getCategory(categoryId: number): ICategory | undefined;
|
||||
}
|
||||
|
||||
14
src/application/State/Selection/IUserSelection.ts
Normal file
14
src/application/State/Selection/IUserSelection.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ISignal } from '@/infrastructure/Events/Signal';
|
||||
import { IScript } from '@/domain/IScript';
|
||||
|
||||
export interface IUserSelection {
|
||||
readonly changed: ISignal<ReadonlyArray<IScript>>;
|
||||
readonly selectedScripts: ReadonlyArray<IScript>;
|
||||
readonly totalSelected: number;
|
||||
addSelectedScript(scriptId: string): void;
|
||||
removeSelectedScript(scriptId: string): void;
|
||||
selectOnly(scripts: ReadonlyArray<IScript>): void;
|
||||
isSelected(script: IScript): boolean;
|
||||
selectAll(): void;
|
||||
deselectAll(): void;
|
||||
}
|
||||
86
src/application/State/Selection/UserSelection.ts
Normal file
86
src/application/State/Selection/UserSelection.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { IApplication } from '@/domain/IApplication';
|
||||
import { IUserSelection } from './IUserSelection';
|
||||
import { InMemoryRepository } from '@/infrastructure/Repository/InMemoryRepository';
|
||||
import { IScript } from '@/domain/Script';
|
||||
import { Signal } from '@/infrastructure/Events/Signal';
|
||||
|
||||
export class UserSelection implements IUserSelection {
|
||||
public readonly changed = new Signal<ReadonlyArray<IScript>>();
|
||||
|
||||
private readonly scripts = new InMemoryRepository<string, IScript>();
|
||||
|
||||
constructor(
|
||||
private readonly app: IApplication,
|
||||
/** Initially selected scripts */
|
||||
selectedScripts: ReadonlyArray<IScript>) {
|
||||
if (selectedScripts && selectedScripts.length > 0) {
|
||||
for (const script of selectedScripts) {
|
||||
this.scripts.addItem(script);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a script to users application */
|
||||
public addSelectedScript(scriptId: string): void {
|
||||
const script = this.app.findScript(scriptId);
|
||||
if (!script) {
|
||||
throw new Error(`Cannot add (id: ${scriptId}) as it is unknown`);
|
||||
}
|
||||
this.scripts.addItem(script);
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
|
||||
/** Remove a script from users application */
|
||||
public removeSelectedScript(scriptId: string): void {
|
||||
this.scripts.removeItem(scriptId);
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
|
||||
public isSelected(script: IScript): boolean {
|
||||
return this.scripts.exists(script);
|
||||
}
|
||||
|
||||
/** Get users scripts based on his/her selections */
|
||||
public get selectedScripts(): ReadonlyArray<IScript> {
|
||||
return this.scripts.getItems();
|
||||
}
|
||||
|
||||
public get totalSelected(): number {
|
||||
return this.scripts.getItems().length;
|
||||
}
|
||||
|
||||
public selectAll(): void {
|
||||
for (const script of this.app.getAllScripts()) {
|
||||
if (!this.scripts.exists(script)) {
|
||||
this.scripts.addItem(script);
|
||||
}
|
||||
}
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
|
||||
public deselectAll(): void {
|
||||
const selectedScriptIds = this.scripts.getItems().map((script) => script.id);
|
||||
for (const scriptId of selectedScriptIds) {
|
||||
this.scripts.removeItem(scriptId);
|
||||
}
|
||||
this.changed.notify([]);
|
||||
}
|
||||
|
||||
public selectOnly(scripts: readonly IScript[]): void {
|
||||
if (!scripts || scripts.length === 0) {
|
||||
throw new Error('Scripts are empty. Use deselectAll() if you want to deselect everything');
|
||||
}
|
||||
// Unselect from selected scripts
|
||||
if (this.scripts.length !== 0) {
|
||||
this.scripts.getItems()
|
||||
.filter((existing) => !scripts.some((script) => existing.id === script.id))
|
||||
.map((script) => script.id)
|
||||
.forEach((scriptId) => this.scripts.removeItem(scriptId));
|
||||
}
|
||||
// Select from unselected scripts
|
||||
scripts
|
||||
.filter((script) => !this.scripts.exists(script))
|
||||
.forEach((script) => this.scripts.addItem(script));
|
||||
this.changed.notify(this.scripts.getItems());
|
||||
}
|
||||
}
|
||||
1026
src/application/application.yaml
Normal file
1026
src/application/application.yaml
Normal file
File diff suppressed because it is too large
Load Diff
23
src/application/application.yaml.d.ts
vendored
Normal file
23
src/application/application.yaml.d.ts
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
declare module 'js-yaml-loader!*' {
|
||||
type CategoryOrScript = YamlCategory | YamlScript;
|
||||
type DocumentationUrls = ReadonlyArray<string> | string;
|
||||
export interface YamlDocumentable {
|
||||
docs?: DocumentationUrls;
|
||||
}
|
||||
export interface YamlScript extends YamlDocumentable {
|
||||
name: string;
|
||||
code: string;
|
||||
default: boolean;
|
||||
}
|
||||
export interface YamlCategory extends YamlDocumentable {
|
||||
children: ReadonlyArray<CategoryOrScript>;
|
||||
category: string;
|
||||
}
|
||||
interface ApplicationYaml {
|
||||
name: string;
|
||||
version: number;
|
||||
actions: ReadonlyArray<YamlCategory>;
|
||||
}
|
||||
const content: ApplicationYaml;
|
||||
export default content;
|
||||
}
|
||||
118
src/domain/Application.ts
Normal file
118
src/domain/Application.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { IEntity } from '../infrastructure/Entity/IEntity';
|
||||
import { ICategory } from './ICategory';
|
||||
import { IScript } from './IScript';
|
||||
import { IApplication } from './IApplication';
|
||||
|
||||
export class Application implements IApplication {
|
||||
private static mustHaveCategories(categories: ReadonlyArray<ICategory>) {
|
||||
if (!categories || categories.length === 0) {
|
||||
throw new Error('an application must consist of at least one category');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks all categories against duplicates, throws exception if it find any duplicates
|
||||
* @return {number} Total unique categories
|
||||
*/
|
||||
/** Checks all categories against duplicates, throws exception if it find any duplicates returns total categories */
|
||||
private static mustNotHaveDuplicatedCategories(categories: ReadonlyArray<ICategory>): number {
|
||||
return Application.ensureNoDuplicateEntities(categories, Application.visitAllCategoriesOnce);
|
||||
}
|
||||
/**
|
||||
* Checks all scripts against duplicates, throws exception if it find any scripts duplicates total scripts.
|
||||
* @return {number} Total unique scripts
|
||||
*/
|
||||
private static mustNotHaveDuplicatedScripts(categories: ReadonlyArray<ICategory>): number {
|
||||
return Application.ensureNoDuplicateEntities(categories, Application.visitAllScriptsOnce);
|
||||
}
|
||||
/**
|
||||
* Checks entities against duplicates using a visit function, throws exception if it find any duplicates.
|
||||
* @return {number} Result from the visit function
|
||||
*/
|
||||
private static ensureNoDuplicateEntities<TKey>(
|
||||
categories: ReadonlyArray<ICategory>,
|
||||
visitFunction: (categories: ReadonlyArray<ICategory>,
|
||||
handler: (entity: IEntity<TKey>) => any) => number): number {
|
||||
const totalOccurencesById = new Map<TKey, number>();
|
||||
const totalVisited = visitFunction(categories,
|
||||
(entity) =>
|
||||
totalOccurencesById.set(entity.id,
|
||||
(totalOccurencesById.get(entity.id) || 0) + 1));
|
||||
const duplicatedIds = new Array<TKey>();
|
||||
totalOccurencesById.forEach((count, id) => {
|
||||
if (count > 1) {
|
||||
duplicatedIds.push(id);
|
||||
}
|
||||
});
|
||||
if (duplicatedIds.length > 0) {
|
||||
const duplicatedIdsText = duplicatedIds.map((id) => `"${id}"`).join(',');
|
||||
throw new Error(
|
||||
`Duplicate entities are detected with following id(s): ${duplicatedIdsText}`);
|
||||
}
|
||||
return totalVisited;
|
||||
}
|
||||
// Runs handler on each category and returns sum of total visited categories
|
||||
private static visitAllCategoriesOnce(
|
||||
categories: ReadonlyArray<ICategory>, handler: (category: ICategory) => any): number {
|
||||
let total = 0;
|
||||
for (const category of categories) {
|
||||
handler(category);
|
||||
total++;
|
||||
if (category.subCategories && category.subCategories.length > 0) {
|
||||
total += Application.visitAllCategoriesOnce(
|
||||
category.subCategories as ReadonlyArray<ICategory>, handler);
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
// Runs handler on each script and returns sum of total visited scripts
|
||||
private static visitAllScriptsOnce(
|
||||
categories: ReadonlyArray<ICategory>, handler: (script: IScript) => any): number {
|
||||
let total = 0;
|
||||
Application.visitAllCategoriesOnce(categories, (category) => {
|
||||
if (category.scripts) {
|
||||
for (const script of category.scripts) {
|
||||
handler(script);
|
||||
total++;
|
||||
}
|
||||
}
|
||||
});
|
||||
return total;
|
||||
}
|
||||
public readonly totalScripts: number;
|
||||
public readonly totalCategories: number;
|
||||
|
||||
constructor(
|
||||
public readonly name: string,
|
||||
public readonly version: number,
|
||||
public readonly categories: ReadonlyArray<ICategory>) {
|
||||
Application.mustHaveCategories(categories);
|
||||
this.totalCategories = Application.mustNotHaveDuplicatedCategories(categories);
|
||||
this.totalScripts = Application.mustNotHaveDuplicatedScripts(categories);
|
||||
}
|
||||
|
||||
public findCategory(categoryId: number): ICategory | undefined {
|
||||
let result: ICategory | undefined;
|
||||
Application.visitAllCategoriesOnce(this.categories, (category) => {
|
||||
if (category.id === categoryId) {
|
||||
result = category;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
public findScript(scriptId: string): IScript | undefined {
|
||||
let result: IScript | undefined;
|
||||
Application.visitAllScriptsOnce(this.categories, (script) => {
|
||||
if (script.id === scriptId) {
|
||||
result = script;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
public getAllScripts(): IScript[] {
|
||||
const result = new Array<IScript>();
|
||||
Application.visitAllScriptsOnce(this.categories, (script) => {
|
||||
result.push(script);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
25
src/domain/Category.ts
Normal file
25
src/domain/Category.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { BaseEntity } from '../infrastructure/Entity/BaseEntity';
|
||||
import { IScript } from './IScript';
|
||||
import { ICategory } from './ICategory';
|
||||
|
||||
export class Category extends BaseEntity<number> implements ICategory {
|
||||
private static validate(category: ICategory) {
|
||||
if (!category.name) {
|
||||
throw new Error('name is null or empty');
|
||||
}
|
||||
if ((!category.subCategories || category.subCategories.length === 0)
|
||||
&& (!category.scripts || category.scripts.length === 0)) {
|
||||
throw new Error('A category must have at least one sub-category or scripts');
|
||||
}
|
||||
}
|
||||
|
||||
constructor(
|
||||
id: number,
|
||||
public readonly name: string,
|
||||
public readonly documentationUrls: ReadonlyArray<string>,
|
||||
public readonly subCategories?: ReadonlyArray<ICategory>,
|
||||
public readonly scripts?: ReadonlyArray<IScript>) {
|
||||
super(id);
|
||||
Category.validate(this);
|
||||
}
|
||||
}
|
||||
12
src/domain/IApplication.ts
Normal file
12
src/domain/IApplication.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { IScript } from '@/domain/IScript';
|
||||
import { ICategory } from '@/domain/ICategory';
|
||||
|
||||
export interface IApplication {
|
||||
readonly categories: ReadonlyArray<ICategory>;
|
||||
findCategory(categoryId: number): ICategory | undefined;
|
||||
findScript(scriptId: string): IScript | undefined;
|
||||
getAllScripts(): ReadonlyArray<IScript>;
|
||||
}
|
||||
|
||||
export { IScript } from '@/domain/IScript';
|
||||
export { ICategory } from '@/domain/ICategory';
|
||||
13
src/domain/ICategory.ts
Normal file
13
src/domain/ICategory.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { IEntity } from '../infrastructure/Entity/IEntity';
|
||||
import { IScript } from './IScript';
|
||||
import { IDocumentable } from './IDocumentable';
|
||||
|
||||
export interface ICategory extends IEntity<number>, IDocumentable {
|
||||
readonly id: number;
|
||||
readonly name: string;
|
||||
readonly subCategories?: ReadonlyArray<ICategory>;
|
||||
readonly scripts?: ReadonlyArray<IScript>;
|
||||
}
|
||||
|
||||
export { IEntity } from '../infrastructure/Entity/IEntity';
|
||||
export { IScript } from './IScript';
|
||||
3
src/domain/IDocumentable.ts
Normal file
3
src/domain/IDocumentable.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface IDocumentable {
|
||||
readonly documentationUrls: ReadonlyArray<string>;
|
||||
}
|
||||
8
src/domain/IScript.ts
Normal file
8
src/domain/IScript.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { IEntity } from './../infrastructure/Entity/IEntity';
|
||||
import { IDocumentable } from './IDocumentable';
|
||||
|
||||
export interface IScript extends IEntity<string>, IDocumentable {
|
||||
readonly name: string;
|
||||
readonly code: string;
|
||||
readonly documentationUrls: ReadonlyArray<string>;
|
||||
}
|
||||
51
src/domain/Script.ts
Normal file
51
src/domain/Script.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { BaseEntity } from '@/infrastructure/Entity/BaseEntity';
|
||||
import { IScript } from './IScript';
|
||||
|
||||
export class Script extends BaseEntity<string> implements IScript {
|
||||
private static ensureNoEmptyLines(name: string, code: string): void {
|
||||
if (code.split('\n').some((line) => line.trim().length === 0)) {
|
||||
throw Error(`Script has empty lines "${name}"`);
|
||||
}
|
||||
}
|
||||
|
||||
private static ensureCodeHasUniqueLines(name: string, code: string): void {
|
||||
const lines = code.split('\n');
|
||||
if (lines.length === 0) {
|
||||
return;
|
||||
}
|
||||
const checkForDuplicates = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 1 && trimmed === ')' || trimmed === '(') {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const duplicateLines = new Array<string>();
|
||||
const uniqueLines = new Set<string>();
|
||||
let validatedLineCount = 0;
|
||||
for (const line of lines) {
|
||||
if (!checkForDuplicates(line)) {
|
||||
continue;
|
||||
}
|
||||
uniqueLines.add(line);
|
||||
if (uniqueLines.size !== validatedLineCount + 1) {
|
||||
duplicateLines.push(line);
|
||||
}
|
||||
validatedLineCount++;
|
||||
}
|
||||
if (duplicateLines.length !== 0) {
|
||||
throw Error(`Duplicates detected in script "${name}":\n ${duplicateLines.join('\n')}`);
|
||||
}
|
||||
}
|
||||
|
||||
constructor(public name: string, public code: string, public documentationUrls: ReadonlyArray<string>) {
|
||||
super(name);
|
||||
if (code == null || code.length === 0) {
|
||||
throw new Error('Code is empty or null');
|
||||
}
|
||||
Script.ensureCodeHasUniqueLines(name, code);
|
||||
Script.ensureNoEmptyLines(name, code);
|
||||
}
|
||||
}
|
||||
|
||||
export { IScript } from './IScript';
|
||||
59
src/global.d.ts
vendored
Normal file
59
src/global.d.ts
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
|
||||
// Two ways of typing other libraries: https://stackoverflow.com/a/53070501
|
||||
|
||||
declare module 'liquor-tree' {
|
||||
import { PluginObject } from 'vue';
|
||||
import { VueClass } from 'vue-class-component/lib/declarations';
|
||||
// https://github.com/amsik/liquor-tree/blob/master/src/lib/Tree.js
|
||||
export interface ILiquorTree {
|
||||
readonly model: ReadonlyArray<ILiquorTreeExistingNode>;
|
||||
filter(query: string): void;
|
||||
clearFilter(): void;
|
||||
setModel(nodes: ReadonlyArray<ILiquorTreeNewNode>): void;
|
||||
}
|
||||
interface ICustomLiquorTreeData {
|
||||
documentationUrls: ReadonlyArray<string>;
|
||||
}
|
||||
/**
|
||||
* Returned from Node tree view events.
|
||||
* See constructor in https://github.com/amsik/liquor-tree/blob/master/src/lib/Node.js
|
||||
*/
|
||||
export interface ILiquorTreeExistingNode {
|
||||
id: string;
|
||||
data: ILiquorTreeNodeData;
|
||||
states: ILiquorTreeNodeState | undefined;
|
||||
children: ReadonlyArray<ILiquorTreeExistingNode> | undefined;
|
||||
}
|
||||
/**
|
||||
* Sent to liquor tree to define of new nodes.
|
||||
* https://github.com/amsik/liquor-tree/blob/master/src/lib/Node.js
|
||||
*/
|
||||
export interface ILiquorTreeNewNode {
|
||||
id: string;
|
||||
text: string;
|
||||
state: ILiquorTreeNodeState | undefined;
|
||||
children: ReadonlyArray<ILiquorTreeNewNode> | undefined;
|
||||
data: ICustomLiquorTreeData;
|
||||
}
|
||||
// https://github.com/amsik/liquor-tree/blob/master/src/lib/Node.js
|
||||
interface ILiquorTreeNodeState {
|
||||
checked: boolean;
|
||||
}
|
||||
interface ILiquorTreeNodeData extends ICustomLiquorTreeData {
|
||||
text: string;
|
||||
}
|
||||
// https://github.com/amsik/liquor-tree/blob/master/src/components/TreeRoot.vue
|
||||
interface ILiquorTreeOptions {
|
||||
checkbox: boolean;
|
||||
checkOnSelect: boolean;
|
||||
filter: ILiquorTreeFilter;
|
||||
deletion(node: ILiquorTreeNewNode): boolean;
|
||||
}
|
||||
// https://github.com/amsik/liquor-tree/blob/master/src/components/TreeRoot.vue
|
||||
interface ILiquorTreeFilter {
|
||||
emptyText: string;
|
||||
matcher(query: string, node: ILiquorTreeNewNode): boolean;
|
||||
}
|
||||
const LiquorTree: PluginObject<any> & VueClass<any>;
|
||||
export default LiquorTree;
|
||||
}
|
||||
14
src/infrastructure/Clipboard.ts
Normal file
14
src/infrastructure/Clipboard.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
export class Clipboard {
|
||||
public static copyText(text: string): void {
|
||||
const el = document.createElement('textarea');
|
||||
el.value = text;
|
||||
el.setAttribute('readonly', ''); // to avoid focus
|
||||
el.style.position = 'absolute';
|
||||
el.style.left = '-9999px';
|
||||
document.body.appendChild(el);
|
||||
el.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(el);
|
||||
}
|
||||
}
|
||||
14
src/infrastructure/Entity/BaseEntity.ts
Normal file
14
src/infrastructure/Entity/BaseEntity.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { IEntity } from './IEntity';
|
||||
|
||||
export abstract class BaseEntity<TId> implements IEntity<TId> {
|
||||
constructor(public id: TId) {
|
||||
if (typeof id !== 'number' && !id) {
|
||||
throw new Error('Id cannot be null or empty');
|
||||
}
|
||||
}
|
||||
public equals(otherId: TId): boolean {
|
||||
return this.id === otherId;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
5
src/infrastructure/Entity/IEntity.ts
Normal file
5
src/infrastructure/Entity/IEntity.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
/** Aggregate root */
|
||||
export interface IEntity<TId> {
|
||||
id: TId;
|
||||
equals(other: TId): boolean;
|
||||
}
|
||||
4
src/infrastructure/Events/ISignal.ts
Normal file
4
src/infrastructure/Events/ISignal.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export interface ISignal<T> {
|
||||
on(handler: (data: T) => void): void;
|
||||
off(handler: (data: T) => void): void;
|
||||
}
|
||||
18
src/infrastructure/Events/Signal.ts
Normal file
18
src/infrastructure/Events/Signal.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { ISignal } from './ISignal';
|
||||
export { ISignal };
|
||||
|
||||
export class Signal<T> implements ISignal<T> {
|
||||
private handlers: Array<(data: T) => void> = [];
|
||||
|
||||
public on(handler: (data: T) => void): void {
|
||||
this.handlers.push(handler);
|
||||
}
|
||||
|
||||
public off(handler: (data: T) => void): void {
|
||||
this.handlers = this.handlers.filter((h) => h !== handler);
|
||||
}
|
||||
|
||||
public notify(data: T) {
|
||||
this.handlers.slice(0).forEach((h) => h(data));
|
||||
}
|
||||
}
|
||||
9
src/infrastructure/Repository/IRepository.ts
Normal file
9
src/infrastructure/Repository/IRepository.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IEntity } from '../Entity/IEntity';
|
||||
|
||||
export interface IRepository<TKey, TEntity extends IEntity<TKey>> {
|
||||
readonly length: number;
|
||||
getItems(predicate?: (entity: TEntity) => boolean): TEntity[];
|
||||
addItem(item: TEntity): void;
|
||||
removeItem(id: TKey): void;
|
||||
exists(item: TEntity): boolean;
|
||||
}
|
||||
40
src/infrastructure/Repository/InMemoryRepository.ts
Normal file
40
src/infrastructure/Repository/InMemoryRepository.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { IEntity } from '../Entity/IEntity';
|
||||
import { IRepository } from './IRepository';
|
||||
|
||||
export class InMemoryRepository<TKey, TEntity extends IEntity<TKey>> implements IRepository<TKey, TEntity> {
|
||||
private readonly items: TEntity[];
|
||||
constructor(items?: TEntity[]) {
|
||||
this.items = items || new Array<TEntity>();
|
||||
}
|
||||
|
||||
public get length(): number {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
public getItems(predicate?: (entity: TEntity) => boolean): TEntity[] {
|
||||
return predicate ? this.items.filter(predicate) : this.items;
|
||||
}
|
||||
|
||||
public addItem(item: TEntity): void {
|
||||
if (!item) {
|
||||
throw new Error('Item is null');
|
||||
}
|
||||
if (this.exists(item)) {
|
||||
throw new Error(`Cannot add (id: ${item.id}) as it is already exists`);
|
||||
}
|
||||
this.items.push(item);
|
||||
}
|
||||
|
||||
public removeItem(id: TKey): void {
|
||||
const index = this.items.findIndex((item) => item.id === id);
|
||||
if (index === -1) {
|
||||
throw new Error(`Cannot remove (id: ${id}) as it does not exist`);
|
||||
}
|
||||
this.items.splice(index, 1);
|
||||
}
|
||||
|
||||
public exists(entity: TEntity): boolean {
|
||||
const index = this.items.findIndex((item) => item.id === entity.id);
|
||||
return index !== -1;
|
||||
}
|
||||
}
|
||||
16
src/infrastructure/SaveFileDialog.ts
Normal file
16
src/infrastructure/SaveFileDialog.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import fileSaver from 'file-saver';
|
||||
|
||||
export class SaveFileDialog {
|
||||
public static saveText(text: string, fileName: string): void {
|
||||
this.saveBlob(text, 'text/plain;charset=utf-8', fileName);
|
||||
}
|
||||
|
||||
private static saveBlob(file: BlobPart, fileType: string, fileName: string): void {
|
||||
try {
|
||||
const blob = new Blob([file], { type: fileType });
|
||||
fileSaver.saveAs(blob, fileName);
|
||||
} catch (e) {
|
||||
window.open('data:' + fileType + ',' + encodeURIComponent(file.toString()), '_blank', '');
|
||||
}
|
||||
}
|
||||
}
|
||||
34
src/infrastructure/Threading/AsyncLazy.ts
Normal file
34
src/infrastructure/Threading/AsyncLazy.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Signal } from '../Events/Signal';
|
||||
|
||||
export class AsyncLazy<T> {
|
||||
private valueCreated = new Signal();
|
||||
private isValueCreated = false;
|
||||
private isCreatingValue = false;
|
||||
private value: T | undefined;
|
||||
|
||||
constructor(private valueFactory: () => Promise<T>) { }
|
||||
|
||||
public setValueFactory(valueFactory: () => Promise<T>) {
|
||||
this.valueFactory = valueFactory;
|
||||
}
|
||||
|
||||
public async getValueAsync(): Promise<T> {
|
||||
// If value is already created, return the value directly
|
||||
if (this.isValueCreated) {
|
||||
return Promise.resolve(this.value as T);
|
||||
}
|
||||
// If value is being created, wait until the value is created and then return it.
|
||||
if (this.isCreatingValue) {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
// Return/result when valueCreated event is triggered.
|
||||
this.valueCreated.on(() => resolve(this.value));
|
||||
});
|
||||
}
|
||||
this.isCreatingValue = true;
|
||||
this.value = await this.valueFactory();
|
||||
this.isCreatingValue = false;
|
||||
this.isValueCreated = true;
|
||||
this.valueCreated.notify(null);
|
||||
return Promise.resolve(this.value);
|
||||
}
|
||||
}
|
||||
10
src/main.ts
Normal file
10
src/main.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import Vue from 'vue';
|
||||
import App from './App.vue';
|
||||
import { ApplicationBootstrapper } from './presentation/Bootstrapping/ApplicationBootstrapper';
|
||||
|
||||
new ApplicationBootstrapper()
|
||||
.bootstrap(Vue);
|
||||
|
||||
new Vue({
|
||||
render: (h) => h(App),
|
||||
}).$mount('#app');
|
||||
24
src/presentation/Bootstrapping/ApplicationBootstrapper.ts
Normal file
24
src/presentation/Bootstrapping/ApplicationBootstrapper.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { TreeBootstrapper } from './Modules/TreeBootstrapper';
|
||||
import { IconBootstrapper } from './Modules/IconBootstrapper';
|
||||
import { VueConstructor, IVueBootstrapper } from './IVueBootstrapper';
|
||||
import { VueBootstrapper } from './Modules/VueBootstrapper';
|
||||
import { TooltipBootstrapper } from './Modules/TooltipBootstrapper';
|
||||
|
||||
export class ApplicationBootstrapper implements IVueBootstrapper {
|
||||
public bootstrap(vue: VueConstructor): void {
|
||||
vue.config.productionTip = false;
|
||||
const bootstrappers = this.getAllBootstrappers();
|
||||
for (const bootstrapper of bootstrappers) {
|
||||
bootstrapper.bootstrap(vue);
|
||||
}
|
||||
}
|
||||
|
||||
private getAllBootstrappers(): IVueBootstrapper[] {
|
||||
return [
|
||||
new IconBootstrapper(),
|
||||
new TreeBootstrapper(),
|
||||
new VueBootstrapper(),
|
||||
new TooltipBootstrapper(),
|
||||
];
|
||||
}
|
||||
}
|
||||
7
src/presentation/Bootstrapping/IVueBootstrapper.ts
Normal file
7
src/presentation/Bootstrapping/IVueBootstrapper.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { VueConstructor } from 'vue';
|
||||
|
||||
export interface IVueBootstrapper {
|
||||
bootstrap(vue: VueConstructor): void;
|
||||
}
|
||||
|
||||
export { VueConstructor };
|
||||
18
src/presentation/Bootstrapping/Modules/IconBootstrapper.ts
Normal file
18
src/presentation/Bootstrapping/Modules/IconBootstrapper.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { IVueBootstrapper, VueConstructor } from './../IVueBootstrapper';
|
||||
import { library } from '@fortawesome/fontawesome-svg-core';
|
||||
import { faGithub } from '@fortawesome/free-brands-svg-icons';
|
||||
/** BRAND ICONS (PREFIX: fab) */
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
|
||||
/** REGULAR ICONS (PREFIX: far) */
|
||||
import { faFolderOpen, faFolder } from '@fortawesome/free-regular-svg-icons';
|
||||
/** SOLID ICONS (PREFIX: fas (default)) */
|
||||
import { faTimes, faFileDownload, faCopy, faSearch, faInfoCircle } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
|
||||
export class IconBootstrapper implements IVueBootstrapper {
|
||||
public bootstrap(vue: VueConstructor): void {
|
||||
library.add(faGithub, faFolderOpen, faFolder,
|
||||
faTimes, faFileDownload, faCopy, faSearch, faInfoCircle);
|
||||
vue.component('font-awesome-icon', FontAwesomeIcon);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { VueConstructor, IVueBootstrapper } from '../IVueBootstrapper';
|
||||
import VTooltip from 'v-tooltip';
|
||||
|
||||
export class TooltipBootstrapper implements IVueBootstrapper {
|
||||
public bootstrap(vue: VueConstructor): void {
|
||||
vue.use(VTooltip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import LiquorTree from 'liquor-tree';
|
||||
import { VueConstructor, IVueBootstrapper } from './../IVueBootstrapper';
|
||||
|
||||
export class TreeBootstrapper implements IVueBootstrapper {
|
||||
public bootstrap(vue: VueConstructor): void {
|
||||
vue.use(LiquorTree);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { VueConstructor, IVueBootstrapper } from './../IVueBootstrapper';
|
||||
|
||||
export class VueBootstrapper implements IVueBootstrapper {
|
||||
public bootstrap(vue: VueConstructor): void {
|
||||
vue.config.productionTip = false;
|
||||
}
|
||||
}
|
||||
74
src/presentation/IconButton.vue
Normal file
74
src/presentation/IconButton.vue
Normal file
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<button class="button" @click="onClicked">
|
||||
<font-awesome-icon
|
||||
class="button__icon"
|
||||
:icon="[iconPrefix, iconName]" size="2x" />
|
||||
<div class="button__text">{{text}}</div>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from 'vue-property-decorator';
|
||||
import { StatefulVue, IApplicationState } from './StatefulVue';
|
||||
import { SaveFileDialog } from './../infrastructure/SaveFileDialog';
|
||||
import { Clipboard } from './../infrastructure/Clipboard';
|
||||
|
||||
@Component
|
||||
export default class IconButton extends StatefulVue {
|
||||
@Prop() public text!: number;
|
||||
@Prop() public iconPrefix!: string;
|
||||
@Prop() public iconName!: string;
|
||||
|
||||
@Emit('click')
|
||||
public onClicked() {
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
|
||||
.button {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
|
||||
background-color: $accent;
|
||||
border: none;
|
||||
color: $white;
|
||||
padding:20px;
|
||||
transition-duration: 0.4s;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 3px 9px $dark-slate;
|
||||
border-radius: 4px;
|
||||
|
||||
cursor: pointer;
|
||||
// border: 0.1em solid $slate;
|
||||
// border-radius: 80px;
|
||||
// padding: 0.5em;
|
||||
width: 10%;
|
||||
min-width: 90px;
|
||||
&:hover {
|
||||
background: $white;
|
||||
box-shadow: 0px 2px 10px 5px $accent;
|
||||
color: $black;
|
||||
}
|
||||
&:hover>&__text {
|
||||
display: block;
|
||||
}
|
||||
&:hover>&__icon {
|
||||
display: none;
|
||||
}
|
||||
&__text {
|
||||
display: none;
|
||||
font-family: 'Yesteryear', cursive;
|
||||
font-size: 1.5em;
|
||||
color: $gray;
|
||||
font-weight: 500;
|
||||
line-height: 1.1;
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
62
src/presentation/Scripts/Cards/CardList.vue
Normal file
62
src/presentation/Scripts/Cards/CardList.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<template>
|
||||
<div>
|
||||
<div v-if="categoryIds != null && categoryIds.length > 0" class="cards">
|
||||
<CardListItem
|
||||
class="card"
|
||||
v-for="categoryId of categoryIds"
|
||||
v-bind:key="categoryId"
|
||||
:categoryId="categoryId"
|
||||
:activeCategoryId="activeCategoryId"
|
||||
v-on:selected="onSelected(categoryId, $event)">
|
||||
</CardListItem>
|
||||
</div>
|
||||
<div v-else class="error">Something went bad 😢</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import CardListItem from './CardListItem.vue';
|
||||
import { StatefulVue, IApplicationState } from '@/presentation/StatefulVue';
|
||||
import { ICategory } from '@/domain/ICategory';
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
CardListItem,
|
||||
},
|
||||
})
|
||||
export default class CardList extends StatefulVue {
|
||||
public categoryIds: number[] = [];
|
||||
public activeCategoryId?: number = null;
|
||||
|
||||
public async mounted() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.setCategories(state.categories);
|
||||
}
|
||||
|
||||
public onSelected(categoryId: number, isExpanded: boolean) {
|
||||
this.activeCategoryId = isExpanded ? categoryId : undefined;
|
||||
}
|
||||
|
||||
private setCategories(categories: ReadonlyArray<ICategory>): void {
|
||||
this.categoryIds = categories.map((category) => category.id);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/fonts.scss";
|
||||
.cards {
|
||||
display: flex;
|
||||
flex-flow: row wrap;
|
||||
.card {
|
||||
|
||||
}
|
||||
}
|
||||
.error {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
font-size: 3.5em;
|
||||
font: $default-font;
|
||||
}
|
||||
</style>
|
||||
248
src/presentation/Scripts/Cards/CardListItem.vue
Normal file
248
src/presentation/Scripts/Cards/CardListItem.vue
Normal file
@@ -0,0 +1,248 @@
|
||||
<template>
|
||||
<div class="card"
|
||||
v-on:click="onSelected(!isExpanded)"
|
||||
v-bind:class="{
|
||||
'is-collapsed': !isExpanded,
|
||||
'is-inactive': activeCategoryId && activeCategoryId != categoryId,
|
||||
'is-expanded': isExpanded}">
|
||||
<div class="card__inner">
|
||||
<span v-if="cardTitle && cardTitle.length > 0">{{cardTitle}}</span>
|
||||
<span v-else>Oh no 😢</span>
|
||||
<font-awesome-icon :icon="['far', isExpanded ? 'folder-open' : 'folder']" class="expand-button" />
|
||||
</div>
|
||||
<div class="card__expander" v-on:click.stop>
|
||||
<font-awesome-icon :icon="['fas', 'times']" class="close-button" v-on:click="onSelected(false)"/>
|
||||
<CardListItemScripts :categoryId="categoryId"></CardListItemScripts>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Watch, Emit } from 'vue-property-decorator';
|
||||
import CardListItemScripts from './CardListItemScripts.vue';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
CardListItemScripts,
|
||||
},
|
||||
})
|
||||
export default class CardListItem extends StatefulVue {
|
||||
@Prop() public categoryId!: number;
|
||||
@Prop() public activeCategoryId!: number;
|
||||
public cardTitle?: string = '';
|
||||
public isExpanded: boolean = false;
|
||||
|
||||
@Emit('selected')
|
||||
public onSelected(isExpanded: boolean) {
|
||||
this.isExpanded = isExpanded;
|
||||
}
|
||||
|
||||
@Watch('activeCategoryId')
|
||||
public async onActiveCategoryChanged(value: |number) {
|
||||
this.isExpanded = value === this.categoryId;
|
||||
}
|
||||
|
||||
public async mounted() {
|
||||
this.cardTitle = this.categoryId ? await this.getCardTitleAsync(this.categoryId) : undefined;
|
||||
}
|
||||
|
||||
@Watch('categoryId')
|
||||
public async onCategoryIdChanged(value: |number) {
|
||||
this.cardTitle = value ? await this.getCardTitleAsync(value) : undefined;
|
||||
}
|
||||
|
||||
|
||||
private async getCardTitleAsync(categoryId: number): Promise<string | undefined> {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
const category = state.getCategory(this.categoryId);
|
||||
return category ? category.name : undefined;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
|
||||
.card {
|
||||
margin: 15px;
|
||||
width: calc((100% / 3) - 30px);
|
||||
transition: all 0.2s ease-in-out;
|
||||
|
||||
//media queries for stacking cards
|
||||
@media screen and (max-width: 991px) {
|
||||
width: calc((100% / 2) - 30px);
|
||||
}
|
||||
|
||||
@media screen and (max-width: 767px) {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 380px) {
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.card__inner {
|
||||
background-color: $accent;
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
&__inner {
|
||||
width: 100%;
|
||||
padding: 30px;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
|
||||
background-color: $gray;
|
||||
color: $light-gray;
|
||||
font-size: 1.5em;
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
|
||||
transition: all 0.2s ease-in-out;
|
||||
|
||||
&:after {
|
||||
transition: all 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.expand-button {
|
||||
width: 100%;
|
||||
margin-top: .25em;
|
||||
}
|
||||
}
|
||||
|
||||
//Expander
|
||||
&__expander {
|
||||
transition: all 0.2s ease-in-out;
|
||||
background-color: $slate;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
text-transform: uppercase;
|
||||
color: $light-gray;
|
||||
font-size: 1.5em;
|
||||
|
||||
.close-button {
|
||||
font-size: 0.75em;
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.is-collapsed {
|
||||
|
||||
.card__inner {
|
||||
&:after {
|
||||
content: "";
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
.card__expander {
|
||||
max-height: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
margin-top: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
&.is-expanded {
|
||||
|
||||
.card__inner {
|
||||
background-color: $accent;
|
||||
|
||||
&:after{
|
||||
content: "";
|
||||
opacity: 1;
|
||||
display: block;
|
||||
height: 0;
|
||||
width: 0;
|
||||
position: absolute;
|
||||
bottom: -30px;
|
||||
left: calc(50% - 15px);
|
||||
border-left: 15px solid transparent;
|
||||
border-right: 15px solid transparent;
|
||||
border-bottom: 15px solid #333a45;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.card__expander {
|
||||
min-height: 200px;
|
||||
// max-height: 1000px;
|
||||
// overflow-y: auto;
|
||||
|
||||
margin-top: 30px;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.card__inner {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.is-inactive {
|
||||
.card__inner {
|
||||
pointer-events: none;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.card__inner {
|
||||
background-color: $gray;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Expander Widths
|
||||
|
||||
//when 3 cards in a row
|
||||
@media screen and (min-width: 992px) {
|
||||
|
||||
.card:nth-of-type(3n+2) .card__expander {
|
||||
margin-left: calc(-100% - 30px);
|
||||
}
|
||||
.card:nth-of-type(3n+3) .card__expander {
|
||||
margin-left: calc(-200% - 60px);
|
||||
}
|
||||
.card:nth-of-type(3n+4) {
|
||||
clear: left;
|
||||
}
|
||||
.card__expander {
|
||||
width: calc(300% + 60px);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//when 2 cards in a row
|
||||
@media screen and (min-width: 768px) and (max-width: 991px) {
|
||||
|
||||
.card:nth-of-type(2n+2) .card__expander {
|
||||
margin-left: calc(-100% - 30px);
|
||||
}
|
||||
.card:nth-of-type(2n+3) {
|
||||
clear: left;
|
||||
}
|
||||
.card__expander {
|
||||
width: calc(200% + 30px);
|
||||
}
|
||||
|
||||
}
|
||||
</style>
|
||||
101
src/presentation/Scripts/Cards/CardListItemScripts.vue
Normal file
101
src/presentation/Scripts/Cards/CardListItemScripts.vue
Normal file
@@ -0,0 +1,101 @@
|
||||
<template>
|
||||
<span>
|
||||
<span v-if="nodes != null && nodes.length > 0">
|
||||
<SelectableTree
|
||||
:nodes="nodes"
|
||||
:selectedNodeIds="selectedNodeIds"
|
||||
:filterPredicate="filterPredicate"
|
||||
:filterText="filterText"
|
||||
v-on:nodeSelected="checkNodeAsync($event)">
|
||||
</SelectableTree>
|
||||
</span>
|
||||
<span v-else>Nooo 😢</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
import { Category } from '@/domain/Category';
|
||||
import { IRepository } from '@/infrastructure/Repository/IRepository';
|
||||
import { IScript } from '@/domain/IScript';
|
||||
import { IApplicationState, IUserSelection } from '@/application/State/IApplicationState';
|
||||
import { IFilterMatches } from '@/application/State/Filter/IFilterMatches';
|
||||
import { ScriptNodeParser } from './ScriptNodeParser';
|
||||
import SelectableTree, { FilterPredicate } from './../SelectableTree/SelectableTree.vue';
|
||||
import { INode } from './../SelectableTree/INode';
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
SelectableTree,
|
||||
},
|
||||
})
|
||||
export default class CardListItemScripts extends StatefulVue {
|
||||
@Prop() public categoryId!: number;
|
||||
|
||||
public nodes?: INode[] = null;
|
||||
public selectedNodeIds?: string[] = null;
|
||||
public filterText?: string = null;
|
||||
|
||||
private matches?: IFilterMatches;
|
||||
|
||||
public async mounted() {
|
||||
// React to state changes
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.reactToChanges(state);
|
||||
// Update initial state
|
||||
await this.updateNodesAsync(this.categoryId);
|
||||
}
|
||||
|
||||
public async checkNodeAsync(node: INode) {
|
||||
if (node.children != null && node.children.length > 0) {
|
||||
return; // only interested in script nodes
|
||||
}
|
||||
const state = await this.getCurrentStateAsync();
|
||||
if (node.selected) {
|
||||
state.selection.addSelectedScript(node.id);
|
||||
} else {
|
||||
state.selection.removeSelectedScript(node.id);
|
||||
}
|
||||
}
|
||||
|
||||
@Watch('categoryId')
|
||||
public async updateNodesAsync(categoryId: |number) {
|
||||
this.nodes = categoryId ?
|
||||
await ScriptNodeParser.parseNodes(categoryId, await this.getCurrentStateAsync())
|
||||
: undefined;
|
||||
}
|
||||
|
||||
public filterPredicate(node: INode): boolean {
|
||||
return this.matches.scriptMatches.some((script: IScript) => script.id === node.id);
|
||||
}
|
||||
|
||||
private reactToChanges(state: IApplicationState) {
|
||||
// Update selection data
|
||||
const updateNodeSelection = (node: INode, selectedScripts: ReadonlyArray<IScript>): INode => {
|
||||
return {
|
||||
id: node.id,
|
||||
text: node.text,
|
||||
selected: selectedScripts.some((script) => script.id === node.id),
|
||||
children: node.children ? node.children.map((child) => updateNodeSelection(child, selectedScripts)) : [],
|
||||
documentationUrls: node.documentationUrls,
|
||||
};
|
||||
};
|
||||
state.selection.changed.on(
|
||||
(selectedScripts: ReadonlyArray<IScript>) =>
|
||||
this.nodes = this.nodes.map((node: INode) => updateNodeSelection(node, selectedScripts)),
|
||||
);
|
||||
// Update search / filter data
|
||||
state.filter.filterRemoved.on(() =>
|
||||
this.filterText = '');
|
||||
state.filter.filtered.on((matches: IFilterMatches) => {
|
||||
this.filterText = matches.query;
|
||||
this.matches = matches;
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
</style>
|
||||
43
src/presentation/Scripts/Cards/ScriptNodeParser.ts
Normal file
43
src/presentation/Scripts/Cards/ScriptNodeParser.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { ICategory } from './../../../domain/ICategory';
|
||||
import { IApplicationState, IUserSelection } from '@/application/State/IApplicationState';
|
||||
import { INode } from './../SelectableTree/INode';
|
||||
|
||||
export class ScriptNodeParser {
|
||||
public static parseNodes(categoryId: number, state: IApplicationState): INode[] | undefined {
|
||||
const category = state.getCategory(categoryId);
|
||||
if (!category) {
|
||||
throw new Error(`Category with id ${categoryId} does not exist`);
|
||||
}
|
||||
const tree = this.parseNodesRecursively(category, state.selection);
|
||||
return tree;
|
||||
}
|
||||
|
||||
private static parseNodesRecursively(parentCategory: ICategory, selection: IUserSelection): INode[] {
|
||||
const nodes = new Array<INode>();
|
||||
if (parentCategory.subCategories && parentCategory.subCategories.length > 0) {
|
||||
for (const subCategory of parentCategory.subCategories) {
|
||||
const subCategoryNodes = this.parseNodesRecursively(subCategory, selection);
|
||||
nodes.push(
|
||||
{
|
||||
id: `cat${subCategory.id}`,
|
||||
text: subCategory.name,
|
||||
selected: false,
|
||||
children: subCategoryNodes,
|
||||
documentationUrls: subCategory.documentationUrls,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (parentCategory.scripts && parentCategory.scripts.length > 0) {
|
||||
for (const script of parentCategory.scripts) {
|
||||
nodes.push( {
|
||||
id: script.id,
|
||||
text: script.name,
|
||||
selected: selection.isSelected(script),
|
||||
children: undefined,
|
||||
documentationUrls: script.documentationUrls,
|
||||
});
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
19
src/presentation/Scripts/CategoryTree.vue
Normal file
19
src/presentation/Scripts/CategoryTree.vue
Normal file
@@ -0,0 +1,19 @@
|
||||
<template>
|
||||
<div>
|
||||
<CardList v-if="isGrouped">
|
||||
</CardList>
|
||||
<SelectableTree></SelectableTree>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from 'vue-property-decorator';
|
||||
import { Category } from '@/domain/Category';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
|
||||
/** Shows content of single category or many categories */
|
||||
@Component
|
||||
export default class CategoryTree extends StatefulVue {
|
||||
@Prop() public data!: Category | Category[];
|
||||
}
|
||||
</script>
|
||||
7
src/presentation/Scripts/SelectableTree/INode.ts
Normal file
7
src/presentation/Scripts/SelectableTree/INode.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export interface INode {
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
readonly documentationUrls: ReadonlyArray<string>;
|
||||
readonly children?: ReadonlyArray<INode>;
|
||||
readonly selected: boolean;
|
||||
}
|
||||
46
src/presentation/Scripts/SelectableTree/Node.vue
Normal file
46
src/presentation/Scripts/SelectableTree/Node.vue
Normal file
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<div id="node">
|
||||
<div>{{ this.data.text }}</div>
|
||||
<div
|
||||
v-for="url of this.data.documentationUrls"
|
||||
v-bind:key="url">
|
||||
<a :href="url"
|
||||
:alt="url"
|
||||
target="_blank" class="docs"
|
||||
v-tooltip.top-center="url"
|
||||
v-on:click.stop>
|
||||
<font-awesome-icon :icon="['fas', 'info-circle']" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import { INode } from './INode';
|
||||
/** Wrapper for Liquor Tree, reveals only abstracted INode for communication */
|
||||
@Component
|
||||
export default class Node extends Vue {
|
||||
@Prop() public data: INode;
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
#node {
|
||||
display:flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
.docs {
|
||||
color: $gray;
|
||||
cursor: pointer;
|
||||
margin-left:5px;
|
||||
&:hover {
|
||||
color: $slate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
181
src/presentation/Scripts/SelectableTree/SelectableTree.vue
Normal file
181
src/presentation/Scripts/SelectableTree/SelectableTree.vue
Normal file
@@ -0,0 +1,181 @@
|
||||
<template>
|
||||
<span>
|
||||
<span v-if="initialNodes != null && initialNodes.length > 0">
|
||||
<tree :options="liquorTreeOptions"
|
||||
:data="this.initialNodes"
|
||||
v-on:node:checked="nodeSelected($event)"
|
||||
v-on:node:unchecked="nodeSelected($event)"
|
||||
ref="treeElement"
|
||||
>
|
||||
<span class="tree-text" slot-scope="{ node }">
|
||||
<Node :data="convertExistingToNode(node)"/>
|
||||
</span>
|
||||
</tree>
|
||||
</span>
|
||||
<span v-else>Nooo 😢</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator';
|
||||
import LiquorTree, { ILiquorTreeNewNode, ILiquorTreeExistingNode, ILiquorTree } from 'liquor-tree';
|
||||
import Node from './Node.vue';
|
||||
import { INode } from './INode';
|
||||
export type FilterPredicate = (node: INode) => boolean;
|
||||
|
||||
/** Wrapper for Liquor Tree, reveals only abstracted INode for communication */
|
||||
@Component({
|
||||
components: {
|
||||
LiquorTree,
|
||||
Node,
|
||||
},
|
||||
})
|
||||
export default class SelectableTree extends Vue {
|
||||
@Prop() public filterPredicate?: FilterPredicate;
|
||||
@Prop() public filterText?: string;
|
||||
@Prop() public nodes?: INode[];
|
||||
|
||||
public initialNodes?: ILiquorTreeNewNode[] = null;
|
||||
public liquorTreeOptions = this.getLiquorTreeOptions();
|
||||
|
||||
public mounted() {
|
||||
// console.log('Mounted', 'initial nodes', this.nodes);
|
||||
// console.log('Mounted', 'initial model', this.getLiquorTreeApi().model);
|
||||
|
||||
if (this.nodes) {
|
||||
this.initialNodes = this.nodes.map((node) => this.toLiquorTreeNode(node));
|
||||
} else {
|
||||
throw new Error('Initial nodes are null or empty');
|
||||
}
|
||||
|
||||
if (this.filterText) {
|
||||
this.updateFilterText(this.filterText);
|
||||
}
|
||||
}
|
||||
|
||||
public nodeSelected(node: ILiquorTreeExistingNode) {
|
||||
this.$emit('nodeSelected', this.convertExistingToNode(node));
|
||||
return;
|
||||
}
|
||||
|
||||
@Watch('filterText')
|
||||
public updateFilterText(filterText: |string) {
|
||||
const api = this.getLiquorTreeApi();
|
||||
if (!filterText) {
|
||||
api.clearFilter();
|
||||
} else {
|
||||
api.filter('filtered'); // text does not matter, it'll trigger the predicate
|
||||
}
|
||||
}
|
||||
|
||||
@Watch('nodes', {deep: true})
|
||||
public setSelectedStatus(nodes: |ReadonlyArray<INode>) {
|
||||
if (!nodes || nodes.length === 0) {
|
||||
throw new Error('Updated nodes are null or empty');
|
||||
}
|
||||
// Update old node properties, re-setting it changes expanded status etc.
|
||||
// It'll not be needed when this is merged: https://github.com/amsik/liquor-tree/pull/141
|
||||
const updateCheckedState = (
|
||||
oldNodes: ReadonlyArray<ILiquorTreeExistingNode>,
|
||||
updatedNodes: ReadonlyArray<INode>): ILiquorTreeNewNode[] => {
|
||||
const newNodes = new Array<ILiquorTreeNewNode>();
|
||||
for (const oldNode of oldNodes) {
|
||||
for (const updatedNode of updatedNodes) {
|
||||
if (oldNode.id === updatedNode.id) {
|
||||
const newState = oldNode.states;
|
||||
newState.checked = updatedNode.selected;
|
||||
newNodes.push({
|
||||
id: oldNode.id,
|
||||
text: updatedNode.text,
|
||||
children: oldNode.children == null ? [] :
|
||||
updateCheckedState(
|
||||
oldNode.children,
|
||||
updatedNode.children),
|
||||
state: newState,
|
||||
data: {
|
||||
documentationUrls: oldNode.data.documentationUrls,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return newNodes;
|
||||
};
|
||||
const newModel = updateCheckedState(
|
||||
this.getLiquorTreeApi().model, nodes);
|
||||
this.getLiquorTreeApi().setModel(newModel);
|
||||
}
|
||||
|
||||
private convertItem(liquorTreeNode: ILiquorTreeNewNode): INode {
|
||||
if (!liquorTreeNode) { throw new Error('liquorTreeNode is undefined'); }
|
||||
return {
|
||||
id: liquorTreeNode.id,
|
||||
text: liquorTreeNode.text,
|
||||
selected: liquorTreeNode.state && liquorTreeNode.state.checked,
|
||||
children: (!liquorTreeNode.children || liquorTreeNode.children.length === 0)
|
||||
? [] : liquorTreeNode.children.map((childNode) => this.convertItem(childNode)),
|
||||
documentationUrls: liquorTreeNode.data.documentationUrls,
|
||||
};
|
||||
}
|
||||
|
||||
private convertExistingToNode(liquorTreeNode: ILiquorTreeExistingNode): INode {
|
||||
if (!liquorTreeNode) { throw new Error('liquorTreeNode is undefined'); }
|
||||
return {
|
||||
id: liquorTreeNode.id,
|
||||
text: liquorTreeNode.data.text,
|
||||
selected: liquorTreeNode.states && liquorTreeNode.states.checked,
|
||||
children: (!liquorTreeNode.children || liquorTreeNode.children.length === 0)
|
||||
? [] : liquorTreeNode.children.map((childNode) => this.convertExistingToNode(childNode)),
|
||||
documentationUrls: liquorTreeNode.data.documentationUrls,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private toLiquorTreeNode(node: INode): ILiquorTreeNewNode {
|
||||
if (!node) { throw new Error('node is undefined'); }
|
||||
return {
|
||||
id: node.id,
|
||||
text: node.text,
|
||||
state: {
|
||||
checked: node.selected,
|
||||
},
|
||||
children: (!node.children || node.children.length === 0) ? [] :
|
||||
node.children.map((childNode) => this.toLiquorTreeNode(childNode)),
|
||||
data: {
|
||||
documentationUrls: node.documentationUrls,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private getLiquorTreeOptions(): any {
|
||||
return {
|
||||
checkbox: true,
|
||||
checkOnSelect: true,
|
||||
deletion: (node) => !node.children || node.children.length === 0,
|
||||
filter: {
|
||||
matcher: (query: string, node: ILiquorTreeExistingNode) => {
|
||||
if (!this.filterPredicate) {
|
||||
throw new Error('Cannot filter as predicate is null');
|
||||
}
|
||||
return this.filterPredicate(this.convertExistingToNode(node));
|
||||
},
|
||||
emptyText: '🕵️Hmm.. Can not see one 🧐',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private getLiquorTreeApi(): ILiquorTree {
|
||||
if (!this.$refs.treeElement) {
|
||||
throw new Error('Referenced tree element cannot be found. Probably it\'s not rendered?');
|
||||
}
|
||||
return (this.$refs.treeElement as any).tree;
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
|
||||
</style>
|
||||
32
src/presentation/Scripts/Selector/SelectableOption.vue
Normal file
32
src/presentation/Scripts/Selector/SelectableOption.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<span
|
||||
v-bind:class="{ 'disabled': enabled, 'enabled': !enabled}"
|
||||
@click="onClicked()">{{label}}</span>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from 'vue-property-decorator';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
|
||||
@Component
|
||||
export default class SelectableOption extends StatefulVue {
|
||||
@Prop() public enabled: boolean;
|
||||
@Prop() public label: string;
|
||||
@Emit('click') public onClicked() { return; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
|
||||
.enabled {
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
font-weight:bold;
|
||||
text-decoration:underline;
|
||||
}
|
||||
}
|
||||
.disabled {
|
||||
color:$gray;
|
||||
}
|
||||
</style>
|
||||
106
src/presentation/Scripts/Selector/TheSelector.vue
Normal file
106
src/presentation/Scripts/Selector/TheSelector.vue
Normal file
@@ -0,0 +1,106 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<div class="part">Select:</div>
|
||||
<div class="part">
|
||||
<SelectableOption
|
||||
label="Recommended"
|
||||
:enabled="isRecommendedSelected"
|
||||
@click="selectRecommendedAsync()" />
|
||||
</div>
|
||||
<div class="part"> | </div>
|
||||
<div class="part">
|
||||
<SelectableOption
|
||||
label="All"
|
||||
:enabled="isAllSelected"
|
||||
@click="selectAllAsync()" />
|
||||
</div>
|
||||
<div class="part"> | </div>
|
||||
<div class="part">
|
||||
<SelectableOption
|
||||
label="None"
|
||||
:enabled="isNoneSelected"
|
||||
@click="selectNoneAsync()">
|
||||
</SelectableOption>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
import SelectableOption from './SelectableOption.vue';
|
||||
import { IApplicationState } from '@/application/State/IApplicationState';
|
||||
import { IScript } from '@/domain/Script';
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
SelectableOption,
|
||||
},
|
||||
})
|
||||
export default class TheSelector extends StatefulVue {
|
||||
public isAllSelected = false;
|
||||
public isNoneSelected = false;
|
||||
public isRecommendedSelected = false;
|
||||
|
||||
public async mounted() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.updateSelections(state);
|
||||
state.selection.changed.on(() => {
|
||||
this.updateSelections(state);
|
||||
});
|
||||
}
|
||||
|
||||
public async selectAllAsync(): Promise<void> {
|
||||
if (this.isAllSelected) {
|
||||
return;
|
||||
}
|
||||
const state = await this.getCurrentStateAsync();
|
||||
state.selection.selectAll();
|
||||
}
|
||||
|
||||
public async selectRecommendedAsync(): Promise<void> {
|
||||
if (this.isRecommendedSelected) {
|
||||
return;
|
||||
}
|
||||
const state = await this.getCurrentStateAsync();
|
||||
state.selection.selectOnly(state.defaultScripts);
|
||||
}
|
||||
|
||||
public async selectNoneAsync(): Promise<void> {
|
||||
if (this.isNoneSelected) {
|
||||
return;
|
||||
}
|
||||
const state = await this.getCurrentStateAsync();
|
||||
state.selection.deselectAll();
|
||||
}
|
||||
|
||||
private updateSelections(state: IApplicationState) {
|
||||
this.isNoneSelected = state.selection.totalSelected === 0;
|
||||
this.isAllSelected = state.selection.totalSelected === state.appTotalScripts;
|
||||
this.isRecommendedSelected = this.areSame(state.defaultScripts, state.selection.selectedScripts);
|
||||
}
|
||||
|
||||
private areSame(scripts: ReadonlyArray<IScript>, other: ReadonlyArray<IScript>): boolean {
|
||||
return (scripts.length === other.length) &&
|
||||
scripts.every((script) => other.some((s) => s.id === script.id));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/fonts.scss";
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items:flex-start;
|
||||
|
||||
.part {
|
||||
display: flex;
|
||||
margin-right:5px;
|
||||
}
|
||||
font:16px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
|
||||
}
|
||||
|
||||
</style>
|
||||
48
src/presentation/Scripts/TheGrouper.vue
Normal file
48
src/presentation/Scripts/TheGrouper.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
Group by: <span
|
||||
v-bind:class="{ 'disabled': isGrouped, 'enabled': !isGrouped}"
|
||||
@click="changeGrouping()" >Cards</Span> |
|
||||
<span class="action"
|
||||
v-bind:class="{ 'disabled': !isGrouped, 'enabled': isGrouped}"
|
||||
@click="changeGrouping()">None</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import { StatefulVue } from '@/presentation/StatefulVue';
|
||||
import { IApplicationState } from '@/application/State/IApplicationState';
|
||||
|
||||
@Component
|
||||
export default class TheGrouper extends StatefulVue {
|
||||
public isGrouped = true;
|
||||
|
||||
public changeGrouping() {
|
||||
this.isGrouped = !this.isGrouped;
|
||||
}
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
@import "@/presentation/styles/fonts.scss";
|
||||
|
||||
.container {
|
||||
// text-align:left;
|
||||
font:16px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
|
||||
|
||||
}
|
||||
.enabled {
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
font-weight:bold;
|
||||
text-decoration:underline;
|
||||
}
|
||||
}
|
||||
.disabled {
|
||||
color:$gray;
|
||||
}
|
||||
|
||||
</style>
|
||||
11
src/presentation/StatefulVue.ts
Normal file
11
src/presentation/StatefulVue.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { ApplicationState, IApplicationState } from '../application/State/ApplicationState';
|
||||
import { Vue } from 'vue-property-decorator';
|
||||
export { IApplicationState };
|
||||
|
||||
export abstract class StatefulVue extends Vue {
|
||||
public isLoading = true;
|
||||
|
||||
protected getCurrentStateAsync(): Promise<IApplicationState> {
|
||||
return ApplicationState.GetAsync();
|
||||
}
|
||||
}
|
||||
53
src/presentation/TheCodeArea.vue
Normal file
53
src/presentation/TheCodeArea.vue
Normal file
@@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<div :id="editorId" class="code-area" ></div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Watch, Vue } from 'vue-property-decorator';
|
||||
import { StatefulVue, IApplicationState } from './StatefulVue';
|
||||
import ace from 'ace-builds';
|
||||
import 'ace-builds/webpack-resolver';
|
||||
|
||||
|
||||
@Component
|
||||
export default class TheCodeArea extends StatefulVue {
|
||||
public readonly editorId = 'codeEditor';
|
||||
private editor!: ace.Ace.Editor;
|
||||
|
||||
@Prop() private theme!: string;
|
||||
|
||||
public async mounted() {
|
||||
this.editor = this.initializeEditor();
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.updateCode(state.code.current);
|
||||
state.code.changed.on((code) => this.updateCode(code));
|
||||
}
|
||||
|
||||
private updateCode(code: string) {
|
||||
this.editor.setValue(code || 'Something is bad 😢', 1);
|
||||
}
|
||||
|
||||
private initializeEditor(): ace.Ace.Editor {
|
||||
const lang = 'batchfile';
|
||||
const theme = this.theme || 'github';
|
||||
const editor = ace.edit(this.editorId);
|
||||
editor.getSession().setMode(`ace/mode/${lang}`);
|
||||
editor.setTheme(`ace/theme/${theme}`);
|
||||
editor.setReadOnly(true);
|
||||
editor.setAutoScrollEditorIntoView(true);
|
||||
// this.editor.getSession().setUseWrapMode(true);
|
||||
// this.editor.setOption("indentedSoftWrap", false);
|
||||
return editor;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.code-area {
|
||||
/* ----- Fill its parent div ------ */
|
||||
width: 100%;
|
||||
/* height */
|
||||
max-height: 1000px;
|
||||
min-height: 200px;
|
||||
}
|
||||
</style>
|
||||
64
src/presentation/TheCodeButtons.vue
Normal file
64
src/presentation/TheCodeButtons.vue
Normal file
@@ -0,0 +1,64 @@
|
||||
<template>
|
||||
<div class="container" v-if="hasCode">
|
||||
<IconButton
|
||||
text="Copy"
|
||||
v-on:click="copyCodeAsync"
|
||||
icon-prefix="fas" icon-name="copy">
|
||||
</IconButton>
|
||||
<IconButton
|
||||
text="Download"
|
||||
v-on:click="saveCodeAsync"
|
||||
icon-prefix="fas" icon-name="file-download">
|
||||
</IconButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import { StatefulVue, IApplicationState } from './StatefulVue';
|
||||
import { SaveFileDialog } from './../infrastructure/SaveFileDialog';
|
||||
import { Clipboard } from './../infrastructure/Clipboard';
|
||||
import IconButton from './IconButton.vue';
|
||||
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
IconButton,
|
||||
},
|
||||
})
|
||||
export default class TheCodeButtons extends StatefulVue {
|
||||
public hasCode = false;
|
||||
|
||||
public async mounted() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.hasCode = state.code.current && state.code.current.length > 0;
|
||||
state.code.changed.on((code) => {
|
||||
this.hasCode = code && code.length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
public async copyCodeAsync() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
Clipboard.copyText(state.code.current);
|
||||
}
|
||||
|
||||
public async saveCodeAsync() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
SaveFileDialog.saveText(state.code.current, 'privacy-script.bat');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
}
|
||||
.container > * + * {
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
</style>
|
||||
66
src/presentation/TheHeader.vue
Normal file
66
src/presentation/TheHeader.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<template>
|
||||
<div id="container">
|
||||
<h1 class="child title" >{{ title }}</h1>
|
||||
<h2 class="child subtitle">{{ subtitle }}</h2>
|
||||
<a :href="githubUrl" target="_blank" class="child github" >
|
||||
<font-awesome-icon :icon="['fab', 'github']" size="3x" />
|
||||
</a>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from 'vue-property-decorator';
|
||||
import { StatefulVue } from './StatefulVue';
|
||||
|
||||
@Component
|
||||
export default class TheHeader extends StatefulVue {
|
||||
private title: string = '';
|
||||
private subtitle: string = '';
|
||||
@Prop() private githubUrl!: string;
|
||||
|
||||
public async mounted() {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
this.title = state.appName;
|
||||
this.subtitle = `Privacy generator tool for Windows v${state.appVersion}`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
#container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
|
||||
.child {
|
||||
display: flex;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
color: $black;
|
||||
text-transform: uppercase;
|
||||
font-size: 2.5em;
|
||||
font-weight: 500;
|
||||
line-height: 1.1;
|
||||
}
|
||||
.subtitle {
|
||||
margin: 0;
|
||||
font-size: 1.5em;
|
||||
color: $gray;
|
||||
font-family: 'Yesteryear', cursive;
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.github {
|
||||
color:inherit;
|
||||
cursor: pointer;
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
</style>
|
||||
78
src/presentation/TheSearchBar.vue
Normal file
78
src/presentation/TheSearchBar.vue
Normal file
@@ -0,0 +1,78 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<div class="search">
|
||||
<input type="text" class="searchTerm" placeholder="Search for configurations"
|
||||
@input="updateFilterAsync($event.target.value)" >
|
||||
<div class="iconWrapper">
|
||||
<font-awesome-icon :icon="['fas', 'search']" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
|
||||
import { StatefulVue } from './StatefulVue';
|
||||
|
||||
@Component
|
||||
export default class TheSearchBar extends StatefulVue {
|
||||
|
||||
|
||||
public async updateFilterAsync(filter: |string) {
|
||||
const state = await this.getCurrentStateAsync();
|
||||
if (!filter) {
|
||||
state.filter.removeFilter();
|
||||
} else {
|
||||
state.filter.setFilter(filter);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@import "@/presentation/styles/colors.scss";
|
||||
@import "@/presentation/styles/fonts.scss";
|
||||
|
||||
.container {
|
||||
padding-top: 30px;
|
||||
padding-right: 30%;
|
||||
padding-left: 30%;
|
||||
font: $default-font;
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.searchTerm {
|
||||
width: 100%;
|
||||
border: 1.5px solid $gray;
|
||||
border-right: none;
|
||||
height: 36px;
|
||||
border-radius: 3px 0 0 3px;
|
||||
padding-left:10px;
|
||||
padding-right:10px;
|
||||
outline: none;
|
||||
color: $gray;
|
||||
}
|
||||
|
||||
.searchTerm:focus{
|
||||
color: $slate;
|
||||
}
|
||||
|
||||
.iconWrapper {
|
||||
width: 40px;
|
||||
height: 36px;
|
||||
border: 1px solid $gray;
|
||||
background: $gray;
|
||||
text-align: center;
|
||||
color: $white;
|
||||
border-radius: 0 5px 5px 0;
|
||||
font-size: 20px;
|
||||
padding:5px;
|
||||
}
|
||||
|
||||
</style>
|
||||
8
src/presentation/styles/colors.scss
Normal file
8
src/presentation/styles/colors.scss
Normal file
@@ -0,0 +1,8 @@
|
||||
$white: #fff;
|
||||
$light-gray: #eceef1;
|
||||
$gray: darken(#eceef1, 30%);
|
||||
$dark-gray: #616f86;
|
||||
$slate: darken(#eceef1, 70%);
|
||||
$dark-slate: #2f3133;
|
||||
$accent: #1abc9c;
|
||||
$black: #000
|
||||
26
src/presentation/styles/fonts.scss
Normal file
26
src/presentation/styles/fonts.scss
Normal file
@@ -0,0 +1,26 @@
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Slabo 27px';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Slabo 27px'), local('Slabo27px-Regular'), url('~@/presentation/styles/fonts/Slabo27px-v6.woff2') format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Slabo 27px';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Slabo 27px'), local('Slabo27px-Regular'), url('~@/presentation/styles/fonts/Slabo27px-v6.woff2') format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Yesteryear';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Yesteryear'), local('Yesteryear-Regular'), url('~@/presentation/styles/fonts/yesteryear-v8.woff2') format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
||||
$default-font: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
|
||||
BIN
src/presentation/styles/fonts/Slabo27px-v6.woff2
Normal file
BIN
src/presentation/styles/fonts/Slabo27px-v6.woff2
Normal file
Binary file not shown.
BIN
src/presentation/styles/fonts/yesteryear-v8.woff2
Normal file
BIN
src/presentation/styles/fonts/yesteryear-v8.woff2
Normal file
Binary file not shown.
43
src/presentation/styles/tooltip.scss
Normal file
43
src/presentation/styles/tooltip.scss
Normal file
@@ -0,0 +1,43 @@
|
||||
// based on https://github.com/Akryum/v-tooltip/blob/83615e394c96ca491a4df04b892ae87e833beb97/demo-src/src/App.vue#L179-L303
|
||||
.tooltip {
|
||||
display: block !important;
|
||||
z-index: 10000;
|
||||
.tooltip-inner {
|
||||
background: $black;
|
||||
color: $white;
|
||||
border-radius: 16px;
|
||||
padding: 5px 10px 4px;
|
||||
}
|
||||
.tooltip-arrow {
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-style: solid;
|
||||
position: absolute;
|
||||
margin: 5px;
|
||||
border-color: $black;
|
||||
z-index: 1;
|
||||
}
|
||||
&[x-placement^="top"] {
|
||||
margin-bottom: 5px;
|
||||
.tooltip-arrow {
|
||||
border-width: 5px 5px 0 5px;
|
||||
border-left-color: transparent !important;
|
||||
border-right-color: transparent !important;
|
||||
border-bottom-color: transparent !important;
|
||||
bottom: -5px;
|
||||
left: calc(50% - 5px);
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
&[aria-hidden='true'] {
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
transition: opacity .15s, visibility .15s;
|
||||
}
|
||||
&[aria-hidden='false'] {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
transition: opacity .15s;
|
||||
}
|
||||
}
|
||||
35
src/presentation/styles/tree.scss
Normal file
35
src/presentation/styles/tree.scss
Normal file
@@ -0,0 +1,35 @@
|
||||
// Overrides base styling for LiquorTree
|
||||
|
||||
.tree-node > .tree-content > .tree-anchor > span {
|
||||
color: $white !important;
|
||||
}
|
||||
|
||||
.tree-node {
|
||||
white-space: normal !important;
|
||||
}
|
||||
|
||||
.tree-arrow.has-child {
|
||||
&.rtl:after, &:after {
|
||||
border-color: $white !important;
|
||||
}
|
||||
}
|
||||
|
||||
.tree-node.selected > .tree-content {
|
||||
> .tree-anchor > span {
|
||||
font-weight: bolder;
|
||||
}
|
||||
}
|
||||
|
||||
.tree-content:hover {
|
||||
background: $dark-gray !important;
|
||||
}
|
||||
|
||||
.tree-checkbox {
|
||||
&.checked {
|
||||
background: $accent !important;
|
||||
}
|
||||
&.indeterminate {
|
||||
border-color: $gray !important;
|
||||
}
|
||||
background: $dark-slate !important;
|
||||
}
|
||||
13
src/shims-tsx.d.ts
vendored
Normal file
13
src/shims-tsx.d.ts
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
import Vue, { VNode } from 'vue';
|
||||
|
||||
declare global {
|
||||
namespace JSX {
|
||||
// tslint:disable no-empty-interface
|
||||
interface Element extends VNode {}
|
||||
// tslint:disable no-empty-interface
|
||||
interface ElementClass extends Vue {}
|
||||
interface IntrinsicElements {
|
||||
[elem: string]: any;
|
||||
}
|
||||
}
|
||||
}
|
||||
4
src/shims-vue.d.ts
vendored
Normal file
4
src/shims-vue.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
declare module '*.vue' {
|
||||
import Vue from 'vue';
|
||||
export default Vue;
|
||||
}
|
||||
41
tests/unit/application/UserSelection.spec.ts
Normal file
41
tests/unit/application/UserSelection.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { CategoryStub } from './../stubs/CategoryStub';
|
||||
import { ApplicationStub } from './../stubs/ApplicationStub';
|
||||
import { ScriptStub } from './../stubs/ScriptStub';
|
||||
import { UserSelection } from '@/application/State/Selection/UserSelection';
|
||||
import 'mocha';
|
||||
import { expect } from 'chai';
|
||||
|
||||
|
||||
describe('UserSelection', () => {
|
||||
it('deselectAll removes all items', async () => {
|
||||
// arrange
|
||||
const app = new ApplicationStub()
|
||||
.withCategory(new CategoryStub(1)
|
||||
.withScripts('s1', 's2', 's3', 's4'));
|
||||
const selectedScripts = [new ScriptStub('s1'), new ScriptStub('s2'), new ScriptStub('s3')];
|
||||
const sut = new UserSelection(app, selectedScripts);
|
||||
|
||||
// act
|
||||
sut.deselectAll();
|
||||
const actual = sut.selectedScripts;
|
||||
|
||||
// assert
|
||||
expect(actual, JSON.stringify(sut.selectedScripts)).to.have.length(0);
|
||||
});
|
||||
it('selectOnly selects expected', async () => {
|
||||
// arrange
|
||||
const app = new ApplicationStub()
|
||||
.withCategory(new CategoryStub(1)
|
||||
.withScripts('s1', 's2', 's3', 's4'));
|
||||
const selectedScripts = [new ScriptStub('s1'), new ScriptStub('s2'), new ScriptStub('s3')];
|
||||
const sut = new UserSelection(app, selectedScripts);
|
||||
const expected = [new ScriptStub('s2'), new ScriptStub('s3'), new ScriptStub('s4')];
|
||||
|
||||
// act
|
||||
sut.selectOnly(expected);
|
||||
const actual = sut.selectedScripts;
|
||||
|
||||
// assert
|
||||
expect(actual).to.deep.equal(expected);
|
||||
});
|
||||
});
|
||||
55
tests/unit/infrastructure/AsyncLazy.spec.ts
Normal file
55
tests/unit/infrastructure/AsyncLazy.spec.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { AsyncLazy } from '@/infrastructure/Threading/AsyncLazy';
|
||||
import 'mocha';
|
||||
import { expect } from 'chai';
|
||||
|
||||
describe('AsyncLazy', () => {
|
||||
|
||||
it('returns value from lambda', async () => {
|
||||
// arrange
|
||||
const expected = 'test';
|
||||
const lambda = () => Promise.resolve(expected);
|
||||
const sut = new AsyncLazy(lambda);
|
||||
|
||||
// act
|
||||
const actual = await sut.getValueAsync();
|
||||
|
||||
// assert
|
||||
expect(actual).to.equal(expected);
|
||||
});
|
||||
|
||||
describe('when running multiple times', () => {
|
||||
let totalExecuted: number = 0;
|
||||
|
||||
beforeEach(() => totalExecuted = 0);
|
||||
|
||||
it('when running sync', async () => {
|
||||
const sut = new AsyncLazy(() => {
|
||||
totalExecuted++;
|
||||
return Promise.resolve(totalExecuted);
|
||||
});
|
||||
const results = new Array<number>();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
results.push(await sut.getValueAsync());
|
||||
}
|
||||
expect(totalExecuted).to.equal(1);
|
||||
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
|
||||
});
|
||||
|
||||
it('when running long-running task paralelly', async () => {
|
||||
const sleep = (time: number) => new Promise(((resolve) => setTimeout(resolve, time)));
|
||||
const sut = new AsyncLazy(async () => {
|
||||
await sleep(100);
|
||||
totalExecuted++;
|
||||
return Promise.resolve(totalExecuted);
|
||||
});
|
||||
const results = await Promise.all([
|
||||
sut.getValueAsync(),
|
||||
sut.getValueAsync(),
|
||||
sut.getValueAsync(),
|
||||
sut.getValueAsync(),
|
||||
sut.getValueAsync()]);
|
||||
expect(totalExecuted).to.equal(1);
|
||||
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user