index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | petrpan-code/ProtonMail/WebClients/packages | petrpan-code/ProtonMail/WebClients/packages/shared/LICENSE | 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
| 8,200 |
0 | petrpan-code/ProtonMail/WebClients/packages | petrpan-code/ProtonMail/WebClients/packages/shared/babel.config.js | module.exports = {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-runtime'],
};
| 8,201 |
0 | petrpan-code/ProtonMail/WebClients/packages | petrpan-code/ProtonMail/WebClients/packages/shared/package.json | {
"name": "@proton/shared",
"description": "Proton shared",
"license": "GPL-3.0",
"author": "ProtonMail",
"sideEffects": false,
"scripts": {
"check-types": "tsc",
"i18n:validate": "proton-i18n validate lint-functions lib",
"i18n:validate:context": "proton-i18n extract shared && proton-i18n validate",
"lint": "eslint lib test --ext .js,.ts,tsx --quiet --cache",
"pretty": "prettier --write $(find lib -type f -name '*.js' -o -name '*.ts' -o -name '*.tsx')",
"test": "NODE_ENV=test karma start test/karma.conf.js",
"testwatch": "npm test -- --auto-watch --no-single-run"
},
"dependencies": {
"@mattiasbuelens/web-streams-adapter": "0.1.0",
"@proton/colors": "workspace:^",
"@proton/crypto": "workspace:packages/crypto",
"@proton/srp": "workspace:packages/srp",
"@proton/styles": "workspace:packages/styles",
"@protontech/bip39": "^1.0.2",
"@protontech/mimemessage": "~v1.1.4",
"@protontech/mutex-browser": "^1.0.5",
"@protontech/tidy-url": "^1.10.1",
"@protontech/timezone-support": "^3.0.0",
"@sentry/browser": "^7.81.0",
"@types/dompurify": "^3.0.5",
"@types/node": "^20.9.3",
"@types/papaparse": "^5.3.12",
"@types/ua-parser-js": "^0.7.39",
"@types/webpack-env": "^1.18.4",
"date-fns": "^2.30.0",
"dompurify": "^3.0.6",
"file-saver": "^2.0.5",
"hi-base32": "^0.5.1",
"ical.js": "^1.5.0",
"is-valid-domain": "0.1.6",
"jsbi": "^4.3.0",
"lodash": "^4.17.21",
"papaparse": "^5.4.1",
"push.js": "^1.0.12",
"ua-parser-js": "^1.0.37",
"web-streams-polyfill": "^3.2.1"
},
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.23.4",
"@proton/eslint-config-proton": "workspace:packages/eslint-config-proton",
"@proton/i18n": "workspace:packages/i18n",
"@types/jasmine": "^5.1.3",
"eslint": "^8.54.0",
"jasmine": "^5.1.0",
"jasmine-core": "^5.1.1",
"karma": "^6.4.2",
"karma-chrome-launcher": "^3.2.0",
"karma-jasmine": "^5.1.0",
"karma-spec-reporter": "^0.0.36",
"karma-webpack": "^5.0.0",
"playwright": "^1.40.0",
"prettier": "^3.1.0",
"ts-loader": "^9.5.1",
"ttag": "^1.7.29",
"typescript": "^5.3.2",
"webpack": "^5.89.0"
}
}
| 8,202 |
0 | petrpan-code/ProtonMail/WebClients/packages | petrpan-code/ProtonMail/WebClients/packages/shared/tsconfig.json | {
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["webpack-env", "jasmine"]
}
}
| 8,203 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api.js | import { getAppVersionHeaders, getUIDHeaders } from './fetch/headers';
const addClientSecret = ['core/v4/auth', 'core/v4/auth/info', 'auth/v4/sessions'];
/**
* Create a function that can call the API with the correct parameters.
* @param {function} xhr - Fetch function
* @param {String} [UID] - The UID of the authenticated user, or nothing
* @param {String} API_URL - The URL to the API
* @param {String} APP_VERSION - The app version
* @param {String} CLIENT_ID - The id of the client
* @param {String} [CLIENT_SECRET] - Optional client secret
* @return {function}
*/
export default ({ xhr, UID, API_URL, APP_VERSION, clientID, CLIENT_SECRET }) => {
const authHeaders = UID ? getUIDHeaders(UID) : undefined;
const appVersionHeaders = getAppVersionHeaders(clientID, APP_VERSION);
const defaultHeaders = {
accept: 'application/vnd.protonmail.v1+json',
...appVersionHeaders,
...authHeaders,
};
return ({ url, data, headers, ...rest }) => {
// Special case for the admin panel
const dataWithClientSecret =
CLIENT_SECRET && addClientSecret.includes(url) ? { ...data, ClientSecret: CLIENT_SECRET } : data;
return xhr({
url: /^https?:\/\//.test(url) ? url : `${API_URL}/${url}`,
data: dataWithClientSecret,
headers: {
...defaultHeaders,
...headers,
},
...rest,
});
};
};
| 8,204 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/apiHandlers.ts | export const createOnceHandler = <Argument extends any, ReturnValue extends any>(
createPromise: (...args: Argument[]) => Promise<ReturnValue>
) => {
let promise: Promise<ReturnValue> | undefined;
const clear = () => {
promise = undefined;
};
return (...args: Argument[]): Promise<ReturnValue> => {
if (promise) {
return promise;
}
promise = createPromise(...args)
.then((result: ReturnValue) => {
clear();
return result;
})
.catch((e: any) => {
clear();
throw e;
});
return promise;
};
};
| 8,205 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/colors.ts | import { c } from 'ttag';
import { SimpleMap } from '@proton/shared/lib/interfaces';
import randomIntFromInterval from '@proton/utils/randomIntFromInterval';
export const ACCENT_COLORS_MAP = {
purple: { color: '#8080FF', getName: () => c('color').t`purple` },
pink: { color: '#DB60D6', getName: () => c('color').t`pink` },
strawberry: { color: '#EC3E7C', getName: () => c('color').t`strawberry` },
carrot: { color: '#F78400', getName: () => c('color').t`carrot` },
sahara: { color: '#936D58', getName: () => c('color').t`sahara` },
enzian: { color: '#5252CC', getName: () => c('color').t`enzian` },
plum: { color: '#A839A4', getName: () => c('color').t`plum` },
cerise: { color: '#BA1E55', getName: () => c('color').t`cerise` },
copper: { color: '#C44800', getName: () => c('color').t`copper` },
soil: { color: '#54473F', getName: () => c('color').t`soil` },
slateblue: { color: '#415DF0', getName: () => c('color').t`slateblue` },
pacific: { color: '#179FD9', getName: () => c('color').t`pacific` },
reef: { color: '#1DA583', getName: () => c('color').t`reef` },
fern: { color: '#3CBB3A', getName: () => c('color').t`fern` },
olive: { color: '#B4A40E', getName: () => c('color').t`olive` },
cobalt: { color: '#273EB2', getName: () => c('color').t`cobalt` },
ocean: { color: '#0A77A6', getName: () => c('color').t`ocean` },
pine: { color: '#0F735A', getName: () => c('color').t`pine` },
forest: { color: '#258723', getName: () => c('color').t`forest` },
pickle: { color: '#807304', getName: () => c('color').t`pickle` },
};
export const ACCENT_COLORS = Object.values(ACCENT_COLORS_MAP).map(({ color }) => color);
const COLOR_NAME_MAP = Object.values(ACCENT_COLORS_MAP).reduce<SimpleMap<() => string>>((acc, { color, getName }) => {
acc[color] = getName;
return acc;
}, {});
export const getColorName = (color: string) => {
return COLOR_NAME_MAP[color.toUpperCase()]?.();
};
export const getRandomAccentColor = () => ACCENT_COLORS[randomIntFromInterval(0, ACCENT_COLORS.length - 1)];
| 8,206 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/constants.ts | import type { enums } from '@proton/crypto';
import { EncryptionConfig } from './interfaces';
export const DEFAULT_TIMEOUT = 30000; // default fetch timeout
export const RETRY_DELAY_MAX = 10; // seconds
export const RETRY_ATTEMPTS_MAX = 5; // how many times to try the same request
export const OFFLINE_RETRY_DELAY = 2000; // how much time in ms to wait before retrying an offline request
export const OFFLINE_RETRY_ATTEMPTS_MAX = 0; // how many times to try the same request when offline
export const SECOND = 1000;
export const MINUTE = 60 * SECOND;
export const HOUR = 60 * MINUTE;
export const DAY = 24 * HOUR;
export const WEEK = 7 * DAY;
export const MONTH = 4 * WEEK;
export const YEAR = 12 * MONTH;
export const MINUTE_IN_SECONDS = 60;
export const HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS;
export const DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS;
// Max quantity for all addons
export const MAX_VPN_ADDON = 2000;
export const MAX_MEMBER_ADDON = 5000;
export const MAX_DOMAIN_PRO_ADDON = 99;
export const MAX_DOMAIN_PLUS_ADDON = 10;
export const MAX_ADDRESS_ADDON = 10;
export const MAX_SPACE_ADDON = 20;
// VPN B2B limits
export const MAX_MEMBER_VPN_B2B_ADDON = 5000;
export const MAX_IPS_ADDON = 100;
export const DOMAIN_PLACEHOLDER = 'example.com';
export const EMAIL_PLACEHOLDER = '[email protected]';
export const USERNAME_PLACEHOLDER = 'john.doe';
export const NAME_PLACEHOLDER = 'Thomas A. Anderson';
export const BRAND_NAME = 'Proton';
export const MAIL_SHORT_APP_NAME = 'Mail';
export const MAIL_APP_NAME = `${BRAND_NAME} ${MAIL_SHORT_APP_NAME}`;
export const CONTACTS_SHORT_APP_NAME = 'Contacts';
export const CONTACTS_APP_NAME = `${BRAND_NAME} ${CONTACTS_SHORT_APP_NAME}`;
export const CALENDAR_SHORT_APP_NAME = 'Calendar';
export const CALENDAR_APP_NAME = `${BRAND_NAME} ${CALENDAR_SHORT_APP_NAME}`;
export const DRIVE_SHORT_APP_NAME = 'Drive';
export const DRIVE_APP_NAME = `${BRAND_NAME} ${DRIVE_SHORT_APP_NAME}`;
export const PASS_SHORT_APP_NAME = 'Pass';
export const PASS_APP_NAME = `${BRAND_NAME} ${PASS_SHORT_APP_NAME}`;
export const VPN_SHORT_APP_NAME = 'VPN';
export const VPN_APP_NAME = `${BRAND_NAME} ${VPN_SHORT_APP_NAME}`;
export const VERIFY_APP_NAME = 'Proton Verify';
export const REFERRER_CODE_MAIL_TRIAL = 'MAILPLUSTRIAL';
export const PROTON_SENTINEL_NAME = 'Proton Sentinel';
export const APPS = {
PROTONACCOUNT: 'proton-account',
PROTONACCOUNTLITE: 'proton-account-lite',
PROTONVPNBROWSEREXTENSION: 'proton-vpn-browser-extension',
PROTONMAIL: 'proton-mail',
PROTONCONTACTS: 'proton-contacts',
PROTONDRIVE: 'proton-drive',
PROTONCALENDAR: 'proton-calendar',
PROTONPASS: 'proton-pass',
PROTONVPN_SETTINGS: 'proton-vpn-settings',
PROTONADMIN: 'proton-admin',
PROTONVERIFICATION: 'proton-verify',
PROTONEXTENSION: 'proton-extension',
PROTONPASSBROWSEREXTENSION: 'proton-pass-extension',
} as const;
interface AppConfiguration {
publicPath: string;
subdomain: string;
name: string;
bareName: string;
clientID?: string;
webClientID?: string;
windowsClientID?: string;
macosClientID?: string;
icon: string;
settingsSlug: string;
}
export const APPS_CONFIGURATION: { [key in APP_NAMES]: AppConfiguration } = {
[APPS.PROTONACCOUNT]: {
publicPath: '',
subdomain: 'account',
name: 'Proton Account',
bareName: 'Account',
webClientID: 'web-account',
windowsClientID: 'windows-mail',
macosClientID: 'macos-mail',
icon: 'brand-proton',
settingsSlug: 'account',
},
[APPS.PROTONACCOUNTLITE]: {
publicPath: '',
subdomain: 'account',
name: 'Proton Account',
bareName: 'Account',
webClientID: 'web-account-lite',
windowsClientID: 'windows-mail',
macosClientID: 'macos-mail',
icon: 'brand-proton',
settingsSlug: 'account',
},
[APPS.PROTONVPNBROWSEREXTENSION]: {
publicPath: '',
subdomain: '',
name: 'Proton VPN Browser Extension',
bareName: 'Browser VPN Extension',
webClientID: 'browser-vpn',
icon: 'brand-proton-vpn',
settingsSlug: '',
},
[APPS.PROTONMAIL]: {
publicPath: '',
subdomain: 'mail',
name: MAIL_APP_NAME,
bareName: MAIL_SHORT_APP_NAME,
webClientID: 'web-mail',
windowsClientID: 'windows-mail',
macosClientID: 'macos-mail',
icon: 'brand-proton-mail',
settingsSlug: 'mail',
},
[APPS.PROTONCONTACTS]: {
publicPath: '/contacts',
subdomain: 'contacts',
name: 'ProtonContacts',
bareName: 'Contacts',
webClientID: 'web-contacts',
icon: 'brand-proton',
settingsSlug: 'contacts',
},
[APPS.PROTONDRIVE]: {
publicPath: '/drive',
subdomain: 'drive',
name: DRIVE_APP_NAME,
bareName: DRIVE_SHORT_APP_NAME,
webClientID: 'web-drive',
icon: 'brand-proton-drive',
settingsSlug: 'drive',
},
[APPS.PROTONCALENDAR]: {
publicPath: '/calendar',
subdomain: 'calendar',
name: CALENDAR_APP_NAME,
bareName: CALENDAR_SHORT_APP_NAME,
webClientID: 'web-calendar',
windowsClientID: 'windows-mail',
macosClientID: 'macos-mail',
icon: 'brand-proton-calendar',
settingsSlug: 'calendar',
},
[APPS.PROTONPASS]: {
publicPath: '/pass',
subdomain: 'pass',
name: PASS_APP_NAME,
bareName: PASS_SHORT_APP_NAME,
webClientID: 'web-pass',
icon: 'brand-proton-pass',
settingsSlug: 'pass',
},
[APPS.PROTONEXTENSION]: {
publicPath: '',
subdomain: '',
name: PASS_APP_NAME,
bareName: PASS_SHORT_APP_NAME,
clientID: 'browser-pass',
icon: '',
settingsSlug: '',
},
[APPS.PROTONPASSBROWSEREXTENSION]: {
publicPath: '',
subdomain: '',
name: PASS_APP_NAME,
bareName: PASS_SHORT_APP_NAME,
clientID: 'browser-pass',
icon: '',
settingsSlug: '',
},
[APPS.PROTONVPN_SETTINGS]: {
publicPath: '',
subdomain: '',
name: VPN_APP_NAME,
bareName: VPN_SHORT_APP_NAME,
webClientID: 'web-vpn-settings',
icon: 'brand-proton-vpn',
settingsSlug: 'vpn',
},
[APPS.PROTONADMIN]: {
publicPath: '',
subdomain: '',
name: '',
bareName: 'Admin',
webClientID: 'web-admin',
icon: 'brand-proton',
settingsSlug: '',
},
[APPS.PROTONVERIFICATION]: {
publicPath: '',
subdomain: 'verify',
name: VERIFY_APP_NAME,
bareName: 'Verify',
webClientID: 'web-verify',
icon: 'brand-proton',
settingsSlug: '',
},
};
export enum PRODUCT_BIT {
Mail = 1,
Drive = 2,
VPN = 4,
PASS = 8,
}
export type APP_KEYS = keyof typeof APPS;
export type APP_NAMES = (typeof APPS)[APP_KEYS];
export type APP_CLIENT_IDS =
| (typeof APPS_CONFIGURATION)[keyof typeof APPS_CONFIGURATION]['webClientID']
| 'android_tv-vpn';
export const SSO_PATHS = {
EXTERNAL_SSO_LOGIN: '/sso/login',
OAUTH_AUTHORIZE: '/oauth/authorize',
OAUTH_CONFIRM_FORK: '/oauth/confirm',
AUTHORIZE: '/authorize',
FORK: '/login',
SWITCH: '/switch',
LOGIN: '/login',
RESET_PASSWORD: '/reset-password',
FORGOT_USERNAME: '/forgot-username',
MAIL_SIGNUP: '/mail/signup',
MAIL_SIGN_IN: '/mail',
CALENDAR_SIGNUP: '/calendar/signup',
CALENDAR_SIGN_IN: '/calendar',
DRIVE_SIGNUP: '/drive/signup',
DRIVE_SIGN_IN: '/drive',
BUSINESS_SIGNUP: '/business/signup',
VPN_SIGNUP: '/vpn/signup',
VPN_PRICING: '/vpn/pricing',
VPN_SIGN_IN: '/vpn',
PASS_SIGNUP: '/pass/signup',
PASS_SIGN_IN: '/pass',
SIGNUP: '/signup',
INVITE: '/pre-invite',
REFER: '/refer-a-friend',
TRIAL: '/trial',
} as const;
export const SETUP_ADDRESS_PATH = '/setup-address';
export const VPN_HOSTNAME = 'account.protonvpn.com';
export enum HTTP_STATUS_CODE {
OK = 200,
BAD_REQUEST = 400,
FORBIDDEN = 403,
NOT_FOUND = 404,
UNPROCESSABLE_ENTITY = 422,
TOO_MANY_REQUESTS = 429,
INTERNAL_SERVER_ERROR = 500,
}
export enum API_CODES {
GLOBAL_SUCCESS = 1001,
SINGLE_SUCCESS = 1000,
NOT_ALLOWED_ERROR = 2011,
INVALID_REQUIREMENT_ERROR = 2000,
INVALID_LINK_TYPE_ERROR = 2001,
ALREADY_EXISTS_ERROR = 2500,
NOT_FOUND_ERROR = 2501,
INVALID_ID_ERROR = 2061,
}
export const GET_VTIMEZONES_API_LIMIT = 10;
export const GET_CANONICAL_EMAILS_API_LIMIT = 100;
export enum ACCOUNT_DELETION_REASONS {
DIFFERENT_ACCOUNT = 'DIFFERENT_ACCOUNT',
TOO_EXPENSIVE = 'TOO_EXPENSIVE',
MISSING_FEATURE = 'MISSING_FEATURE',
USE_OTHER_SERVICE = 'USE_OTHER_SERVICE',
OTHER = 'OTHER',
}
export const FORBIDDEN_LABEL_NAMES = ['inbox', 'drafts', 'sent', 'starred', 'archive', 'spam', 'trash', 'outbox'];
export enum SUBSCRIPTION_CANCELLATION_REASONS {
DIFFERENT_ACCOUNT = 'DIFFERENT_ACCOUNT',
TOO_EXPENSIVE = 'TOO_EXPENSIVE',
MISSING_FEATURE = 'MISSING_FEATURE',
QUALITY_ISSUE = 'QUALITY_ISSUE',
STREAMING_SERVICE_UNSUPPORTED = 'STREAMING_SERVICE_UNSUPPORTED',
SWITCHING_TO_DIFFERENT_SERVICE = 'SWITCHING_TO_DIFFERENT_SERVICE',
TEMPORARY = 'TEMPORARY',
OTHER = 'OTHER',
}
export const MAIN_USER_KEY = 'USER_KEYS';
export const SECURE_SESSION_STORAGE_KEY = 'SECURE';
export const MAILBOX_PASSWORD_KEY = 'proton:mailbox_pwd';
export const UID_KEY = 'proton:oauth:UID';
export const USER_ID_KEY = 'proton:userID';
export const LOCAL_ID_KEY = 'proton:localID';
export const PERSIST_SESSION_KEY = 'proton:persistSession';
export const TRUST_SESSION_KEY = 'proton:trustSession';
export const INTERVAL_EVENT_TIMER = 30 * 1000;
export const MAX_SIZE_SCREENSHOT = 500 * 1000;
export enum EVENT_ACTIONS {
DELETE = 0,
CREATE = 1,
UPDATE = 2,
UPDATE_DRAFT = 2,
UPDATE_FLAGS = 3,
}
export enum USER_ROLES {
FREE_ROLE = 0,
MEMBER_ROLE = 1,
ADMIN_ROLE = 2,
}
export const ELEMENTS_PER_PAGE = 10;
export enum INVOICE_OWNER {
USER = 0,
ORGANIZATION = 1,
}
export const DEFAULT_CURRENCY = 'EUR';
export const CURRENCIES = ['EUR', 'USD', 'CHF'] as const;
export const MIN_DONATION_AMOUNT = 100;
export const MIN_CREDIT_AMOUNT = 500;
export const MAX_CREDIT_AMOUNT = 4000000;
export const MIN_BITCOIN_AMOUNT = MIN_CREDIT_AMOUNT;
export const MAX_BITCOIN_AMOUNT = MAX_CREDIT_AMOUNT;
export const DEFAULT_CREDITS_AMOUNT = 5000;
export enum INVOICE_TYPE {
OTHER = 0,
SUBSCRIPTION = 1,
CANCELLATION = 2,
CREDIT = 3,
DONATION = 4,
CHARGEBACK = 5,
RENEWAL = 6,
REFUND = 7,
MODIFICATION = 8,
ADDITION = 9,
}
export enum INVOICE_STATE {
UNPAID = 0,
PAID = 1,
VOID = 2,
BILLED = 3,
WRITEOFF = 4,
}
export enum UNPAID_STATE {
NOT_UNPAID = 0,
AVAILABLE = 1,
OVERDUE = 2,
DELINQUENT = 3,
NO_RECEIVE = 4,
}
export const BASE_SIZE = 1024;
export const GIGA = BASE_SIZE ** 3;
export enum MEMBER_TYPE {
PROTON = 0,
MANAGED = 1,
}
export enum ADDRESS_STATUS {
STATUS_DISABLED = 0,
STATUS_ENABLED = 1,
STATUS_DELETING = 2, // not used by clients yet; coming in the future
}
export enum ADDRESS_TYPE {
TYPE_ORIGINAL = 1,
TYPE_ALIAS = 2,
TYPE_CUSTOM_DOMAIN = 3,
TYPE_PREMIUM = 4,
TYPE_EXTERNAL = 5,
}
export enum ADDRESS_RECEIVE {
RECEIVE_YES = 1,
RECEIVE_NO = 0,
}
export enum ADDRESS_SEND {
SEND_YES = 1,
SEND_NO = 0,
}
export enum ADDRESS_FLAGS {
FLAG_DISABLE_E2EE = 16,
FLAG_DISABLE_EXPECTED_SIGNED = 32,
}
export enum MEMBER_PERMISSIONS {
MANAGE_FORWARDING = 1,
}
export enum MEMBER_PRIVATE {
READABLE = 0,
UNREADABLE = 1,
}
export enum MEMBER_ROLE {
ORGANIZATION_NONE = 0,
ORGANIZATION_MEMBER = 1,
ORGANIZATION_ADMIN = 2,
}
export enum MEMBER_SUBSCRIBER {
NON_PAYER = 0,
PAYER = 1,
}
export enum PACKAGE_SIGNATURES_MODE {
SIGNATURES_NONE = 0,
SIGNATURES_ATTACHMENTS = 1,
SIGNATURES_BODY = 2,
}
export enum PGP_SCHEMES {
PGP_INLINE = 'pgp-inline',
PGP_MIME = 'pgp-mime',
}
export enum PGP_SCHEMES_MORE {
GLOBAL_DEFAULT = '',
}
export type CONTACT_PGP_SCHEMES = PGP_SCHEMES | PGP_SCHEMES_MORE;
export enum MIME_TYPES {
MIME = 'multipart/mixed',
PLAINTEXT = 'text/plain',
DEFAULT = 'text/html',
ICS = 'text/calendar',
APPLICATION_ICS = 'application/ics', // Google's special one that doesn't have standard newlines
PGP_KEYS = 'application/pgp-keys',
}
export enum MIME_TYPES_MORE {
AUTOMATIC = '',
}
export type CONTACT_MIME_TYPES = MIME_TYPES.PLAINTEXT | MIME_TYPES.DEFAULT | MIME_TYPES_MORE.AUTOMATIC;
export enum RECIPIENT_TYPES {
TYPE_INTERNAL = 1,
TYPE_EXTERNAL = 2,
}
/**
* Returned by legacy GET /keys endpoint
*/
export enum IGNORE_KT {
VALID = 0,
EXTERNAL_ADDRESS = 1,
CATCH_ALL = 2,
}
export enum DRAFT_TYPE {
NORMAL = 'text/html',
PLAIN_TEXT = 'text/plain',
}
export enum ORGANIZATION_FLAGS {
LOYAL = 1,
COVID = 2,
SMTP_SUBMISSION = 4,
NO_CYCLE_SCHEDULED = 8,
DISSIDENT = 64,
PROTON = 128,
}
export enum ORGANIZATION_TWOFA_SETTING {
NOT_REQUIRED = 0,
REQUIRED_ADMIN_ONLY = 1,
REQUIRED_ALL = 2,
}
export enum APP_UPSELL_REF_PATH {
MAIL_UPSELL_REF_PATH = 'upsell_mail-',
CALENDAR_UPSELL_REF_PATH = 'upsell_calendar-',
DRIVE_UPSELL_REF_PATH = 'upsell_drive-',
PASS_UPSELL_REF_PATH = 'upsell_pass-',
VPN_UPSELL_REF_PATH = 'upsell_vpn-',
}
export enum UPSELL_COMPONENT {
BANNER = 'banner-',
MODAL = 'modal-',
BUTTON = 'button-',
}
export enum MAIL_UPSELL_PATHS {
AUTO_REPLY = 'auto-reply',
DOMAIN_NAMES = 'domain-names',
CATCH_ALL = 'catch-all',
BRIDGE = 'bridge',
PM_ME = 'pm-me',
SHORT_ADDRESS = 'short-address',
AUTO_DELETE = 'auto-delete',
SCHEDULE_SEND = 'schedule-send',
STORAGE_FULL = 'storage-full',
GET_STARTED_CHECKLIST = 'get-started-checklist',
MAIL_FOOTER = 'mail-footer',
UNLIMITED_FOLDERS = 'unlimited-folders',
UNLIMITED_LABELS = 'unlimited-labels',
UNLIMITED_FILTERS = 'unlimited-filters',
UNLIMITED_ADDRESSES = 'unlimited-addresses',
FORWARD_EMAILS = 'forward-emails',
SMTP_SUBMISSION = 'smtp-submission',
SNOOZE_MESSAGE = 'snooze-message',
}
export enum CALENDAR_UPSELL_PATHS {
MULTI_CAL = 'multi-cal',
SHARE_CAL = 'share-cal',
MAX_CAL = 'max-cal',
}
export enum DRIVE_UPSELL_PATHS {
SIDEBAR = 'sidebar',
}
export enum SHARED_UPSELL_PATHS {
MULTI_USER = 'multi-user',
CONTACT_GROUP = 'contact-groups',
STORAGE = 'storage',
STORAGE_PERCENTAGE = 'storage-percentage',
ORGANIZATION_CAPACITY = 'organization-capacity',
SENTINEL = 'sentinel',
}
export enum DASHBOARD_UPSELL_PATHS {
MAILPLUS = 'mailplus-dashboard',
UNLIMITED = 'unlimited-dashboard',
DRIVE = 'drive-dashboard',
PASS = 'pass-dashboard',
VPN = 'vpn-dashboard',
FAMILY = 'family-dashboard',
BUSINESS = 'business-dashboard',
}
export const LOYAL_BONUS_STORAGE = 5 * GIGA;
export const LOYAL_BONUS_CONNECTION = 2;
export const COVID_PLUS_BONUS_STORAGE = 5 * GIGA;
export const COVID_PROFESSIONAL_BONUS_STORAGE = 5 * GIGA;
export const COVID_VISIONARY_BONUS_STORAGE = 10 * GIGA;
export const FREE_VPN_CONNECTIONS = 1;
export const VPN_CONNECTIONS = 10;
export enum CYCLE {
MONTHLY = 1,
YEARLY = 12,
TWO_YEARS = 24,
THIRTY = 30,
FIFTEEN = 15,
}
export const DEFAULT_CYCLE = CYCLE.TWO_YEARS;
export const BLACK_FRIDAY = {
COUPON_CODE: 'BF2022',
START: new Date(Date.UTC(2021, 10, 1, 5)), // 6 AM CET
END: new Date(Date.UTC(2022, 0, 1, 17)), // 6 PM CET
CYBER_START: new Date(Date.UTC(2020, 10, 30, 6)),
CYBER_END: new Date(Date.UTC(2020, 11, 1, 6)),
};
export const PRODUCT_PAYER = {
START: new Date(Date.UTC(2020, 9, 28, 6)),
END: new Date(Date.UTC(2020, 11, 15, 6)),
};
export const MIN_PAYPAL_AMOUNT = 499;
export const MAX_PAYPAL_AMOUNT = 99999900;
export enum NEWSLETTER_SUBSCRIPTIONS {
ANNOUNCEMENTS = 'Announcements',
/** not displayed anymore, turning on one product news should turn it on as well */
FEATURES = 'Features',
NEWSLETTER = 'Newsletter',
BETA = 'Beta',
BUSINESS = 'Business',
OFFERS = 'Offers',
/** used in `Messages & Composing` */
NEW_EMAIL_NOTIF = 'NewEmailNotif',
ONBOARDING = 'Onboarding',
USER_SURVEY = 'UserSurveys',
INBOX_NEWS = 'InboxNews',
VPN_NEWS = 'VpnNews',
DRIVE_NEWS = 'DriveNews',
PASS_NEWS = 'PassNews',
}
export enum NEWSLETTER_SUBSCRIPTIONS_BITS {
ANNOUNCEMENTS = 1 << 0,
FEATURES = 1 << 1,
NEWSLETTER = 1 << 2,
BETA = 1 << 3,
BUSINESS = 1 << 4,
OFFERS = 1 << 5,
/** used in `Messages & Composing` */
NEW_EMAIL_NOTIF = 1 << 6,
ONBOARDING = 1 << 7,
USER_SURVEY = 1 << 8,
INBOX_NEWS = 1 << 9,
VPN_NEWS = 1 << 10,
DRIVE_NEWS = 1 << 11,
PASS_NEWS = 1 << 12,
}
export const NEWSLETTER_SUBSCRIPTIONS_BY_BITS: Record<NEWSLETTER_SUBSCRIPTIONS_BITS, NEWSLETTER_SUBSCRIPTIONS> = {
[NEWSLETTER_SUBSCRIPTIONS_BITS.ANNOUNCEMENTS]: NEWSLETTER_SUBSCRIPTIONS.ANNOUNCEMENTS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.FEATURES]: NEWSLETTER_SUBSCRIPTIONS.FEATURES,
[NEWSLETTER_SUBSCRIPTIONS_BITS.NEWSLETTER]: NEWSLETTER_SUBSCRIPTIONS.NEWSLETTER,
[NEWSLETTER_SUBSCRIPTIONS_BITS.BETA]: NEWSLETTER_SUBSCRIPTIONS.BETA,
[NEWSLETTER_SUBSCRIPTIONS_BITS.BUSINESS]: NEWSLETTER_SUBSCRIPTIONS.BUSINESS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.OFFERS]: NEWSLETTER_SUBSCRIPTIONS.OFFERS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.NEW_EMAIL_NOTIF]: NEWSLETTER_SUBSCRIPTIONS.NEW_EMAIL_NOTIF,
[NEWSLETTER_SUBSCRIPTIONS_BITS.ONBOARDING]: NEWSLETTER_SUBSCRIPTIONS.ONBOARDING,
[NEWSLETTER_SUBSCRIPTIONS_BITS.USER_SURVEY]: NEWSLETTER_SUBSCRIPTIONS.USER_SURVEY,
[NEWSLETTER_SUBSCRIPTIONS_BITS.INBOX_NEWS]: NEWSLETTER_SUBSCRIPTIONS.INBOX_NEWS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.VPN_NEWS]: NEWSLETTER_SUBSCRIPTIONS.VPN_NEWS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.DRIVE_NEWS]: NEWSLETTER_SUBSCRIPTIONS.DRIVE_NEWS,
[NEWSLETTER_SUBSCRIPTIONS_BITS.PASS_NEWS]: NEWSLETTER_SUBSCRIPTIONS.PASS_NEWS,
};
export const CONTACT_EMAILS_LIMIT = 1000;
export const CONTACTS_LIMIT = 1000;
export const EXPORT_CONTACTS_LIMIT = 50; // Maximum page size for export is 50 from API
export const CONTACTS_REQUESTS_PER_SECOND = 10;
export const ALL_MEMBERS_ID = -100;
export enum LABEL_EXCLUSIVE {
FOLDER = 1,
LABEL = 0,
}
export const REGEX_IMAGE_EXTENSION = /\.(gif|jpe?g|tiff|png)$/i;
export const DARK_MODE_CLASS = 'isDarkMode';
export enum LINK_WARNING {
KEY = 'link_warning',
VALUE = 'dontAsk',
}
export const MEMBER_ADDON_PREFIX = '1member';
export const DOMAIN_ADDON_PREFIX = '1domain';
export const IP_ADDON_PREFIX = '1ip';
export enum ADDON_NAMES {
ADDRESS = '5address',
MEMBER = '1member',
DOMAIN = '1domain',
SPACE = '1gb',
VPN = '1vpn',
MEMBER_DRIVE_PRO = `${MEMBER_ADDON_PREFIX}-drivepro2022`,
MEMBER_MAIL_PRO = `${MEMBER_ADDON_PREFIX}-mailpro2022`,
MEMBER_BUNDLE_PRO = `${MEMBER_ADDON_PREFIX}-bundlepro2022`,
DOMAIN_BUNDLE_PRO = `${DOMAIN_ADDON_PREFIX}-bundlepro2022`,
MEMBER_ENTERPRISE = `${MEMBER_ADDON_PREFIX}-enterprise2022`,
DOMAIN_ENTERPRISE = `${DOMAIN_ADDON_PREFIX}-enterprise2022`,
MEMBER_VPN_PRO = `${MEMBER_ADDON_PREFIX}-vpnpro2023`,
MEMBER_VPN_BUSINESS = `${MEMBER_ADDON_PREFIX}-vpnbiz2023`,
IP_VPN_BUSINESS = `${IP_ADDON_PREFIX}-vpnbiz2023`,
}
export enum PLAN_TYPES {
PLAN = 1,
ADDON = 0,
}
export enum PLAN_SERVICES {
MAIL = 1,
DRIVE = 2,
VPN = 4,
PASS = 8,
}
// You don't need more, use `user.isPaid`
export const FREE_SUBSCRIPTION = {
isFreeSubscription: true,
};
export type FreeSubscription = typeof FREE_SUBSCRIPTION;
export function isFreeSubscription(obj: any): obj is FreeSubscription {
return !!obj && obj.isFreeSubscription && Object.keys(obj).length === 1;
}
export const FREE_ORGANIZATION = {}; // You don't need more, use `user.isPaid`
export enum PLANS {
FREE = 'free',
// Old plans
PLUS = 'plus',
PROFESSIONAL = 'professional',
VISIONARY = 'visionary',
VPNBASIC = 'vpnbasic',
VPNPLUS = 'vpnplus',
// New plans
DRIVE = 'drive2022',
DRIVE_PRO = 'drivepro2022',
PASS_PLUS = 'pass2023',
MAIL = 'mail2022',
MAIL_PRO = 'mailpro2022',
VPN = 'vpn2022',
BUNDLE = 'bundle2022',
BUNDLE_PRO = 'bundlepro2022',
ENTERPRISE = 'enterprise2022',
FAMILY = 'family2022',
NEW_VISIONARY = 'visionary2022',
VPN_PRO = 'vpnpro2023',
VPN_BUSINESS = 'vpnbiz2023',
VPN_PASS_BUNDLE = 'vpnpass2023',
}
export const PLAN_NAMES = {
[PLANS.FREE]: 'Free',
[PLANS.PLUS]: 'Plus',
[PLANS.PROFESSIONAL]: 'Professional',
[PLANS.VISIONARY]: 'Visionary',
[PLANS.VPNBASIC]: 'Basic',
[PLANS.VPNPLUS]: 'Plus',
[PLANS.DRIVE]: 'Drive Plus',
[PLANS.DRIVE_PRO]: 'Drive Essentials',
[PLANS.PASS_PLUS]: 'Pass Plus',
[PLANS.MAIL]: 'Mail Plus',
[PLANS.MAIL_PRO]: 'Mail Essentials',
[PLANS.VPN]: 'VPN Plus',
[PLANS.BUNDLE]: 'Proton Unlimited',
[PLANS.BUNDLE_PRO]: 'Business',
[PLANS.ENTERPRISE]: 'Enterprise',
[PLANS.FAMILY]: 'Proton Family',
[PLANS.NEW_VISIONARY]: 'Visionary',
[PLANS.VPN_PRO]: 'VPN Essentials',
[PLANS.VPN_BUSINESS]: 'VPN Business',
[PLANS.VPN_PASS_BUNDLE]: 'VPN and Pass bundle',
};
export const MEMBER_PLAN_MAPPING = {
[ADDON_NAMES.MEMBER_BUNDLE_PRO]: PLANS.BUNDLE_PRO,
[ADDON_NAMES.MEMBER_MAIL_PRO]: PLANS.MAIL_PRO,
[ADDON_NAMES.MEMBER_DRIVE_PRO]: PLANS.DRIVE_PRO,
[ADDON_NAMES.MEMBER_ENTERPRISE]: PLANS.ENTERPRISE,
[ADDON_NAMES.MEMBER_VPN_PRO]: PLANS.VPN_PRO,
[ADDON_NAMES.MEMBER_VPN_BUSINESS]: PLANS.VPN_BUSINESS,
};
export enum COUPON_CODES {
BUNDLE = 'BUNDLE',
PROTONTEAM = 'PROTONTEAM',
BLACK_FRIDAY_2018 = 'TWO4ONE2018',
BLACK_FRIDAY_2019 = 'BF2019',
BLACK_FRIDAY_2020 = 'BF2020',
BLACK_FRIDAY_2022 = 'BF2022',
BLACK_FRIDAY_2023 = 'BF2023',
MAIL_BLACK_FRIDAY_2022 = 'MAILBF2022',
VPN_BLACK_FRIDAY_2022 = 'VPNBF2022',
LIFETIME = 'LIFETIME',
VISIONARYFOREVER = 'VISIONARYFOREVER',
REFERRAL = 'REFERRAL',
ANNIVERSARY23 = 'ANNIVERSARY23',
}
export const GIFT_CODE_LENGTH = 16;
export const KEY_EXTENSION = 'asc';
export const KEY_FILE_EXTENSION = `.${KEY_EXTENSION}`;
export enum ENCRYPTION_TYPES {
CURVE25519 = 'CURVE25519',
RSA4096 = 'RSA4096',
}
export const DEFAULT_ENCRYPTION_CONFIG = ENCRYPTION_TYPES.CURVE25519;
export const ENCRYPTION_CONFIGS: { [key: string]: EncryptionConfig } = {
[ENCRYPTION_TYPES.CURVE25519]: {
type: 'ecc',
curve: 'ed25519' as enums.curve,
}, // casting is just informational
[ENCRYPTION_TYPES.RSA4096]: { type: 'rsa', rsaBits: 4096 },
};
export enum KEY_FLAG {
FLAG_EMAIL_NO_SIGN = 8,
/**
* Key can't be used to encrypt email. There are multiple scenarios where this can happen
* - the key is associated to a product without Mail, like Drive or VPN
* - the key is associated to an external address
* - the key is associated to an internal address e2e encryption disabled (e.g. because of forwarding)
*/
FLAG_EMAIL_NO_ENCRYPT = 4,
// Key can be used to encrypt
FLAG_NOT_OBSOLETE = 2,
// Key can be used to verify signatures
FLAG_NOT_COMPROMISED = 1,
}
export enum USER_STATUS {
DELETED = 0,
DISABLED = 1,
USER = 2,
VPN_ADMIN = 3,
ADMIN = 4,
SUPER_ADMIN = 5,
}
export enum MAILBOX_IDENTIFIERS {
inbox = '0',
allDrafts = '1',
allSent = '2',
trash = '3',
spam = '4',
allmail = '5',
starred = '10',
archive = '6',
sent = '7',
drafts = '8',
outbox = '9',
search = 'search',
label = 'label',
}
export enum INCOMING_DEFAULTS_LOCATION {
INBOX = Number(MAILBOX_IDENTIFIERS.inbox),
SPAM = Number(MAILBOX_IDENTIFIERS.spam),
BLOCKED = 14,
}
/* eslint no-useless-escape: "off" */
export const REGEX_EMAIL =
/(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/i;
export enum FILTER_STATUS {
ENABLED = 1,
DISABLED = 0,
}
export const FREE_USER_ACTIVE_FILTERS_LIMIT = 1;
export const FREE_USER_FOLDERS_LIMIT = 3;
export const FREE_USER_LABELS_LIMIT = 3;
export const VCARD_VERSION = '4.0';
export enum CONTACT_CARD_TYPE {
ENCRYPTED_AND_SIGNED = 3,
SIGNED = 2,
ENCRYPTED = 1,
CLEAR_TEXT = 0,
}
export enum LABEL_TYPE {
MESSAGE_LABEL = 1,
CONTACT_GROUP = 2,
MESSAGE_FOLDER = 3,
SYSTEM_FOLDER = 4,
}
export const DEFAULT_LOCALE = 'en_US';
export enum PASSWORD_MODE {
SINGLE = 1,
TWO_PASSWORD = 2,
}
export enum SORT_DIRECTION {
ASC = 'ASC',
DESC = 'DESC',
}
export enum SERVER_FEATURES {
SECURE_CORE = 1,
TOR = 2,
P2P = 4,
XOR = 8,
IPV6 = 16,
RESTRICTED = 32,
PARTNER = 64,
DOUBLE_RESTRICTION = 128,
}
export enum CLIENT_TYPES {
MAIL = 1,
VPN = 2,
PASS = 5,
}
export enum TOKEN_TYPES {
EMAIL = 'email',
SMS = 'sms',
INVITE = 'invite',
COUPON = 'coupon',
CAPTCHA = 'captcha',
}
export enum MAILBOX_LABEL_IDS {
INBOX = '0',
ALL_DRAFTS = '1',
ALL_SENT = '2',
TRASH = '3',
SPAM = '4',
ALL_MAIL = '5',
STARRED = '10',
ARCHIVE = '6',
SENT = '7',
DRAFTS = '8',
OUTBOX = '9',
SCHEDULED = '12',
ALMOST_ALL_MAIL = '15',
SNOOZED = '16',
}
export const LINKED_LABEL_IDS: {
[key in MAILBOX_LABEL_IDS]?: MAILBOX_LABEL_IDS;
} = {
[MAILBOX_LABEL_IDS.ALL_DRAFTS]: MAILBOX_LABEL_IDS.DRAFTS,
[MAILBOX_LABEL_IDS.ALL_SENT]: MAILBOX_LABEL_IDS.SENT,
[MAILBOX_LABEL_IDS.ALL_MAIL]: MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL,
[MAILBOX_LABEL_IDS.DRAFTS]: MAILBOX_LABEL_IDS.ALL_DRAFTS,
[MAILBOX_LABEL_IDS.SENT]: MAILBOX_LABEL_IDS.ALL_SENT,
[MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL]: MAILBOX_LABEL_IDS.ALL_MAIL,
};
export enum AutoReplyDuration {
FIXED = 0,
DAILY = 1,
WEEKLY = 2,
MONTHLY = 3,
PERMANENT = 4,
}
export const DKIM_RSA_1024 = 0;
export const DKIM_RSA_2048 = 1;
export enum DKIM_KEY_STATUS {
ACTIVE = 0,
PENDING = 1,
RETIRED = 2,
DECEASED = 3,
}
export enum DKIM_KEY_DNS_STATUS {
NOT_SET = 0,
GOOD = 1,
INVALID = 2,
}
export enum DENSITY {
COMFORTABLE = 0,
COMPACT = 1,
}
export enum SPAM_SCORE {
PM_SPOOFED = 100,
DMARC_FAILED = 101,
PHISHING = 102,
}
export const COLLAPSE_MENU_KEY = 'collapse-menu';
export const ROOT_FOLDER = 0;
export const USER_SCOPES = {
DRIVE: 68719476736,
};
export const DOH_DOMAINS = ['.compute.amazonaws.com'];
export const PROTON_DOMAINS = [
'protonmail.com',
'protonmail.ch',
'protonvpn.com',
'protonstatus.com',
'gdpr.eu',
'protonvpn.net',
'pm.me',
'protonmailrmez3lotccipshtkleegetolb73fuirgj7r4o4vfu7ozyd.onion',
'proton.me',
];
export enum LINK_TYPES {
WEB = 'web',
EMAIL = 'email',
PHONE = 'phone',
}
declare const WEBPACK_FEATURE_FLAGS: string;
// This is a definition coming from webpack. Hide behind typeof for the test env.
export const FEATURE_FLAGS = typeof WEBPACK_FEATURE_FLAGS === 'undefined' ? '' : WEBPACK_FEATURE_FLAGS;
declare const WEBPACK_APP_MODE: string;
export const APP_MODE = typeof WEBPACK_APP_MODE === 'undefined' ? '' : WEBPACK_APP_MODE;
export const isSSOMode = APP_MODE === 'sso';
export const isStandaloneMode = APP_MODE === 'standalone';
declare const WEBPACK_PUBLIC_PATH: string;
export const PUBLIC_PATH = typeof WEBPACK_PUBLIC_PATH === 'undefined' ? '' : WEBPACK_PUBLIC_PATH;
interface OpenPGPFile {
filepath: string;
integrity?: string;
}
const DUMMY_FILE = {
filepath: '/',
};
declare const WEBPACK_OPENPGP: {
main: OpenPGPFile;
compat: OpenPGPFile;
elliptic: OpenPGPFile;
worker: OpenPGPFile;
};
export const OPENPGP =
typeof WEBPACK_OPENPGP === 'undefined'
? {
main: DUMMY_FILE,
compat: DUMMY_FILE,
elliptic: DUMMY_FILE,
worker: DUMMY_FILE,
}
: WEBPACK_OPENPGP;
export const FORKABLE_APPS = new Set(
[
APPS.PROTONMAIL,
APPS.PROTONCONTACTS,
APPS.PROTONDRIVE,
APPS.PROTONCALENDAR,
APPS.PROTONPASS,
APPS.PROTONEXTENSION,
APPS.PROTONPASSBROWSEREXTENSION,
APPS.PROTONVPNBROWSEREXTENSION,
].filter(Boolean)
);
export const EXTENSIONS = {
[APPS.PROTONEXTENSION]: { ID: 'ghmbeldphafepmbegfdlkpapadhbakde' },
[APPS.PROTONPASSBROWSEREXTENSION]: {
ID: 'ghmbeldphafepmbegfdlkpapadhbakde',
},
[APPS.PROTONVPNBROWSEREXTENSION]: {
ID: 'jplgfhpmjnbigmhklmmbgecoobifkmpa',
},
} as const;
export const AES256 = 'aes256';
export const REFERRAL_PROGRAM_MAX_AMOUNT = 9000;
export const FIBONACCI_LIST = [1, 1, 2, 3, 5, 8, 13];
/* Here is a list of product not to be translated */
//TODO should this be moved in the easy-switch package
export const PRODUCT_NAMES = {
EASY_SWITCH: 'Easy Switch',
};
// Allowed Log parameters of the /metrics route
export enum METRICS_LOG {
SIGNUP = 'signup',
ENCRYPTED_SEARCH = 'encrypted_search',
DARK_STYLES = 'dark_styles',
}
/** SimpleLogin constants **/
// SimpleLogin tags used to communicate with the web extension
export enum SIMPLE_LOGIN_TAGS {
EXTENSION_INSTALLED_QUERY = 'EXTENSION_INSTALLED_QUERY',
EXTENSION_INSTALLED_RESPONSE = 'EXTENSION_INSTALLED_RESPONSE',
}
export enum SIMPLE_LOGIN_EXTENSION_LINKS {
MAIN_PAGE = 'https://simplelogin.io',
DASHBOARD = 'https://app.simplelogin.io/dashboard/',
}
export const OPEN_OFFER_MODAL_EVENT = 'openoffermodal';
export const FAMILY_MAX_USERS = 6;
export enum DESKTOP_APP_NAMES {
DRIVE = 'drive',
}
export enum DESKTOP_PLATFORMS {
LINUX = 'linux',
MACOS = 'macos',
WINDOWS = 'windows',
}
export enum RELEASE_CATEGORIES {
STABLE = 'Stable',
ALPHA = 'Alpha',
EARLY_ACCESS = 'EarlyAccess',
}
export enum PROTON_WEBSITES {
PROTON_STATUS_PAGE = 'https://status.proton.me',
}
export const IPS_INCLUDED_IN_PLAN: Partial<Record<PLANS, number>> = {
[PLANS.VPN_BUSINESS]: 1,
} as const;
/**
* Mail Composer toolbar
*/
export const COMPOSER_TOOLBAR_ICON_SIZE = 14;
| 8,207 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/errors.ts | export const HTTP_ERROR_CODES = {
ABORTED: -1,
TIMEOUT: 0,
UNPROCESSABLE_ENTITY: 422,
UNAUTHORIZED: 401,
UNLOCK: 403,
TOO_MANY_REQUESTS: 429,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
};
export const API_CUSTOM_ERROR_CODES = {
APP_VERSION_BAD: 5003,
ALREADY_USED: 2001,
USERNAME_ALREADY_USED: 12106,
EMAIL_FORMAT: 2050,
NOT_ALLOWED: 2011,
CARD_DECLINED: 2902,
TOO_MANY_CHILDREN: 8003,
AUTH_SWITCH_TO_SSO: 8100,
AUTH_SWITCH_TO_SRP: 8101,
HUMAN_VERIFICATION_REQUIRED: 9001,
DEVICE_VERIFICATION_REQUIRED: 9002,
AUTH_ACCOUNT_DISABLED: 10003,
USER_UPDATE_EMAIL_SELF: 12007,
TOKEN_INVALID: 12087,
KEY_GET_INPUT_INVALID: 33101,
KEY_GET_ADDRESS_MISSING: 33102,
KEY_GET_DOMAIN_MISSING_MX: 33103,
KEY_GET_INVALID_KT: 33104,
INCOMING_DEFAULT_UPDATE_NOT_EXIST: 35023,
USER_EXISTS_USERNAME_ALREADY_USED: 12106,
NO_RESET_METHODS: 2029,
JWT_EXPIRED: 8005,
PAYMENTS_SUBSCRIPTION_AMOUNT_MISMATCH: 22101,
USER_CREATE_TOKEN_INVALID: 12087,
USER_RESTRICTED_STATE: 12100,
};
export const EVENT_ERRORS = {
MAIL: 1,
CONTACTS: 2,
};
| 8,208 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/password.ts | export const alphabeticChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
export const digits = '0123456789';
export const specialChars = '!#$%&()*+.:;<=>?@[]^';
export const generatePassword = (options: { useSpecialChars: boolean; length: number }) => {
const chars = Array.from(alphabeticChars + digits + (options.useSpecialChars ? specialChars : ''));
const randomValues = crypto.getRandomValues(new Uint8Array(options.length));
const passwordChars = Array.from(randomValues).map((n) => {
const rangeBoundMaxIndex = n % chars.length;
return chars[rangeBoundMaxIndex];
});
return passwordChars.join('');
};
| 8,209 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared | petrpan-code/ProtonMail/WebClients/packages/shared/lib/srp.ts | import { getRandomSrpVerifier, getSrp } from '@proton/srp';
import { getInfo, getModulus } from './api/auth';
import { Fido2Data, InfoResponse, ModulusResponse } from './authentication/interface';
import { Api } from './interfaces';
export interface AuthCredentials {
username?: string;
password: string;
}
export type Credentials =
| AuthCredentials
| (AuthCredentials & { totp: string })
| (AuthCredentials & { fido2: Fido2Data });
interface SrpAuthData {
ClientProof: string;
ClientEphemeral: string;
TwoFactorCode?: string;
SRPSession: string;
}
export interface SrpConfig {
[key: string]: any;
}
/**
* Call the API with the SRP parameters and validate the server proof.
*/
interface CallAndValidateArguments {
api: Api;
config: SrpConfig;
authData: SrpAuthData;
expectedServerProof: string;
}
const callAndValidate = async ({
api,
config: { data, ...restConfig },
authData,
expectedServerProof,
}: CallAndValidateArguments) => {
const response: Response = await api({
...restConfig,
output: 'raw',
data: {
...authData,
...data,
},
});
const clonedResponse = response.clone();
const result = await clonedResponse.json();
const { ServerProof } = result;
if (ServerProof !== expectedServerProof) {
throw new Error('Unexpected server proof');
}
return response;
};
/**
* Perform an API call with SRP auth.
*/
interface SrpAuthArguments {
api: Api;
credentials: Credentials;
config: SrpConfig;
info?: InfoResponse;
version?: number;
}
export const srpAuth = async ({ api, credentials, config, info, version }: SrpAuthArguments) => {
const actualInfo = info || (await api<InfoResponse>(getInfo(credentials.username)));
const { expectedServerProof, clientProof, clientEphemeral } = await getSrp(actualInfo, credentials, version);
const authData = {
ClientProof: clientProof,
ClientEphemeral: clientEphemeral,
SRPSession: actualInfo.SRPSession,
...('totp' in credentials ? { TwoFactorCode: credentials.totp } : undefined),
...('fido2' in credentials ? { FIDO2: credentials.fido2 } : undefined),
};
return callAndValidate({
api,
config,
authData,
expectedServerProof,
});
};
/**
* Get initialization parameters for SRP.
*/
export const srpGetVerify = async ({ api, credentials }: { api: Api; credentials: Credentials }) => {
const data = await api<ModulusResponse>(getModulus());
const { version, salt, verifier } = await getRandomSrpVerifier(data, credentials);
const authData = {
ModulusID: data.ModulusID,
Version: version,
Salt: salt,
Verifier: verifier,
};
return {
Auth: authData,
};
};
/**
* Perform an SRP call with the random verifier.
*/
export const srpVerify = async <T = any>({
api,
credentials,
config: { data, ...restConfig },
}: {
api: Api;
credentials: Credentials;
config: SrpConfig;
}) => {
const authData = await srpGetVerify({ api, credentials });
return api<T>({
...restConfig,
data: {
...data,
...authData,
},
});
};
| 8,210 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/addresses.ts | import { Address, Api, SignedKeyList } from '../interfaces';
import queryPages from './helpers/queryPages';
import { PaginationParams } from './interface';
export const queryAddresses = (params?: PaginationParams) => ({
url: 'core/v4/addresses',
method: 'get',
params,
});
export const getAllAddresses = (api: Api): Promise<Address[]> => {
return queryPages((page, pageSize) => {
return api<{ Addresses: Address[]; Total: number }>(
queryAddresses({
Page: page,
PageSize: pageSize,
})
);
}).then((pages) => {
return pages.flatMap(({ Addresses }) => Addresses);
});
};
interface CreateAddressArgs {
MemberID?: string;
Local: string;
Domain: string;
DisplayName?: string;
Signature?: string;
}
export const createAddress = ({ MemberID, Local, Domain, DisplayName, Signature }: CreateAddressArgs) => ({
url: 'core/v4/addresses',
method: 'post',
data: { MemberID, Local, Domain, DisplayName, Signature },
});
export const orderAddress = (AddressIDs: string[]) => ({
url: 'core/v4/addresses/order',
method: 'put',
data: { AddressIDs },
});
interface SetupAddressArgs {
Domain: string;
DisplayName: string;
Signature?: string;
}
export const setupAddress = ({ Domain, DisplayName, Signature }: SetupAddressArgs) => ({
url: 'core/v4/addresses/setup',
method: 'post',
data: { Domain, DisplayName, Signature },
});
export const getAddress = (addressID: string) => ({
url: `core/v4/addresses/${addressID}`,
method: 'get',
});
export const getCanonicalAddresses = (Emails: string[]) => ({
// params doesn't work correctly so
url: `core/v4/addresses/canonical?${Emails.map((email) => `Emails[]=${email}`).join('&')}`,
method: 'get',
// params: { Emails },
});
export const updateAddress = (
addressID: string,
{ DisplayName, Signature }: { DisplayName?: string; Signature?: string }
) => ({
url: `core/v4/addresses/${addressID}`,
method: 'put',
data: { DisplayName, Signature },
});
export const enableAddress = (addressID: string) => ({
url: `core/v4/addresses/${addressID}/enable`,
method: 'put',
});
export const disableAddress = (addressID: string) => ({
url: `core/v4/addresses/${addressID}/disable`,
method: 'put',
});
export const deleteAddress = (addressID: string) => ({
url: `core/v4/addresses/${addressID}`,
method: 'delete',
});
interface RenamedAddressKey {
ID: string;
PrivateKey: string;
}
interface RenameInternalAddressData {
Local: string;
AddressKeys: RenamedAddressKey[];
}
export const renameInternalAddress = (addressID: string, data: RenameInternalAddressData) => ({
url: `core/v4/addresses/${addressID}/rename/internal`,
method: 'put',
data,
});
interface RenameExternalAddressData {
Local: string;
Domain: string;
AddressKeys: RenamedAddressKey[];
}
export const renameExternalAddress = (addressID: string, data: RenameExternalAddressData) => ({
url: `core/v4/addresses/${addressID}/rename/external`,
method: 'put',
data,
});
export const addressType = (addressID: string, data: { Type: number; SignedKeyList: SignedKeyList }) => ({
url: `core/v4/addresses/${addressID}/type`,
method: 'put',
data,
});
| 8,211 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/apiEnvironmentConfig.ts | export const getApiEnvConfig = () => ({
url: 'core/v4/system/config',
method: 'get',
});
| 8,212 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/attachments.ts | export const getAttachment = (attachmentID: string) => ({
method: 'get',
url: `mail/v4/attachments/${attachmentID}`,
output: 'arrayBuffer',
});
export const getAttachmentsMetadata = (attachmentID: string) => ({
method: 'get',
url: `mail/v4/attachments/${attachmentID}/metadata`,
});
export const uploadAttachment = (data: {
Filename: string;
MessageID: string;
ContentID: string;
MIMEType: string;
KeyPackets: Blob;
DataPacket: Blob;
Signature?: Blob;
}) => ({
method: 'post',
url: 'mail/v4/attachments',
input: 'form',
data,
});
export const removeAttachment = (attachmentID: string, messageID: string) => ({
method: 'delete',
url: `mail/v4/attachments/${attachmentID}`,
params: { MessageID: messageID },
});
| 8,213 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/auth.ts | import { ChallengePayload } from '../authentication/interface';
import { APP_CLIENT_IDS } from '../constants';
import { HTTP_ERROR_CODES } from '../errors';
import { AuthenticationCredentialsPayload } from '../webauthn/interface';
export const PASSWORD_WRONG_ERROR = 8002;
export const auth = (
data:
| {
Username: string;
Payload?: ChallengePayload;
}
| {
SSOResponseToken: string;
},
persistent: boolean
) => ({
method: 'post',
url: 'core/v4/auth',
data: {
...data,
PersistentCookies: Number(persistent),
},
ignoreHandler: [HTTP_ERROR_CODES.TOO_MANY_REQUESTS],
});
export const auth2FA = (data: { TwoFactorCode: string } | { FIDO2: AuthenticationCredentialsPayload }) => ({
method: 'post',
url: 'core/v4/auth/2fa',
data: data,
});
export const authJwt = (data: { Token: String; ClientSecret?: String }) => ({
method: 'post',
url: 'core/v4/auth/jwt',
data,
});
export const revoke = (params?: { Child?: 1 }) => ({
method: 'delete',
url: 'core/v4/auth',
params,
});
interface RefreshArgs {
RefreshToken: string;
RedirectURI?: string;
}
export const setRefreshCookies = (data?: RefreshArgs) => {
const config = {
method: 'post',
// WARNING: The refresh cookie is set with `path=/api/auth/refresh;`
url: 'auth/refresh',
};
if (!data) {
return config;
}
return {
...config,
data: {
ResponseType: 'token',
GrantType: 'refresh_token',
RefreshToken: data.RefreshToken,
RedirectURI: data.RedirectURI || 'https://protonmail.com',
},
};
};
interface CookiesArgs {
UID: string;
RefreshToken: string;
State: string;
RedirectURI?: string;
Persistent?: boolean;
}
export const setCookies = ({
UID,
RefreshToken,
State,
RedirectURI = 'https://protonmail.com',
Persistent = false,
}: CookiesArgs) => ({
method: 'post',
url: 'core/v4/auth/cookies',
data: {
UID,
ResponseType: 'token',
GrantType: 'refresh_token',
RefreshToken,
RedirectURI,
Persistent: Number(Persistent),
State,
},
});
export const getLocalKey = () => ({
method: 'get',
url: 'auth/v4/sessions/local/key',
});
export const setLocalKey = (Key: string) => ({
method: 'put',
url: 'auth/v4/sessions/local/key',
data: {
Key,
},
});
export const pushForkSession = (data: {
Payload?: string;
ChildClientID: APP_CLIENT_IDS;
Independent: 0 | 1;
Selector?: string;
UserCode?: string;
}) => ({
method: 'post',
url: 'auth/v4/sessions/forks',
data,
});
export const pullForkSession = (selector: string) => ({
method: 'get',
url: `auth/v4/sessions/forks/${selector}`,
});
export const getLocalSessions = () => ({
method: 'get',
url: `auth/v4/sessions/local`,
});
export const getInfo = (Username?: string, intent: 'Proton' | 'Auto' | 'SSO' = 'Proton') => ({
method: 'post',
url: 'core/v4/auth/info',
data: { ...(Username ? { Username } : undefined), Intent: intent },
});
export const getModulus = () => ({
method: 'get',
url: 'core/v4/auth/modulus',
});
export const createSession = (data?: { ClientSecret?: string; Payload?: ChallengePayload }) => ({
method: 'post',
url: 'auth/v4/sessions',
data,
});
export const querySessions = () => ({
method: 'get',
url: 'auth/v4/sessions',
});
export const revokeOtherSessions = () => ({
method: 'delete',
url: 'auth/v4/sessions',
});
export const revokeSession = (UID: string | number) => ({
method: 'delete',
url: `auth/v4/sessions/${UID}`,
});
export const queryScopes = () => ({
method: 'get',
url: 'core/v4/auth/scopes',
});
export const getMnemonicAuthInfo = (Username?: string) => ({
method: 'post',
url: 'auth/v4/mnemonic/info',
data: Username ? { Username } : undefined,
});
export const authMnemonic = (Username: string, persistent: boolean) => ({
method: 'post',
url: 'auth/v4/mnemonic',
data: { Username, PersistentCookies: Number(persistent) },
ignoreHandler: [HTTP_ERROR_CODES.TOO_MANY_REQUESTS],
});
export const payload = (data: ChallengePayload) => ({
method: 'post',
url: `auth/v4/sessions/payload`,
data: {
Payload: data,
},
});
| 8,214 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/calendars.ts | import { CALENDAR_VALIDATION_MODE } from '../calendar/constants';
import { Attendee, CalendarNotificationSettings, CalendarSettings, CalendarUserSettings } from '../interfaces/calendar';
import {
CalendarCreateArguments,
CalendarCreateOrUpdateEventBlobData,
CalendarEventsIDsQuery,
CalendarEventsQuery,
CalendarExportEventsQuery,
CalendarKeysResetData,
CalendarSetupData,
CreateCalendarMemberData,
CreatePublicLinks,
CreateSinglePersonalEventData,
GetEventByUIDArguments,
QueryCalendarAlarms,
SyncMultipleEventsData,
UpdateCalendarInviteData,
UpdateCalendarMemberData,
} from '../interfaces/calendar/Api';
import { Nullable, RequireOnly } from '../interfaces/utils';
import { PaginationParams } from './interface';
const CALENDAR_V1 = 'calendar/v1';
export const queryLatestModelEventID = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/modelevents/latest`,
method: 'get',
});
export const queryModelEvents = (calendarID: string, eventID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/modelevents/${eventID}`,
method: 'get',
});
export const queryCalendars = () => ({
url: `${CALENDAR_V1}`,
method: 'get',
});
export const createCalendar = (data: CalendarCreateArguments) => ({
url: `${CALENDAR_V1}`,
method: 'post',
data,
});
export const setupCalendar = (calendarID: string, data: CalendarSetupData) => ({
url: `${CALENDAR_V1}/${calendarID}/keys`,
method: 'post',
data,
});
export const getCalendar = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}`,
method: 'get',
});
export const getFullCalendar = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/bootstrap`,
method: 'get',
});
export const getCalendarKeys = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/keys`,
method: 'get',
});
export const getAllCalendarKeys = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/keys/all`,
method: 'get',
});
export const getPassphrases = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/passphrases`,
method: 'get',
});
export const getPassphrase = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/passphrase`,
method: 'get',
});
export const reactivateCalendarKey = (calendarID: string, keyID: string, data: { PrivateKey: string }) => ({
url: `${CALENDAR_V1}/${calendarID}/keys/${keyID}`,
method: 'put',
data,
});
export const getCalendarGroupReset = () => ({
url: `${CALENDAR_V1}/keys/reset`,
method: 'get',
});
export const resetCalendars = (data: { CalendarKeys: CalendarKeysResetData }) => ({
url: `${CALENDAR_V1}/keys/reset`,
method: 'post',
data,
});
export const removeCalendar = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}`,
method: 'delete',
});
export const queryMembers = (calendarID: string, params?: PaginationParams) => ({
url: `${CALENDAR_V1}/${calendarID}/members`,
method: 'get',
params,
});
export const getAllMembers = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/members/all`,
method: 'get',
});
export const getCalendarInvitations = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations`,
method: 'get',
});
export const getAllInvitations = () => ({
url: `${CALENDAR_V1}/invitations`,
method: 'get',
});
export const addMember = (
calendarID: string,
data: { AddressID: string; Signature: string; Members: CreateCalendarMemberData[] }
) => ({
url: `${CALENDAR_V1}/${calendarID}/members`,
method: 'post',
data,
});
export const updateMember = (calendarID: string, memberID: string, data: Partial<UpdateCalendarMemberData>) => ({
url: `${CALENDAR_V1}/${calendarID}/members/${memberID}`,
method: 'put',
data,
});
export const updateMemberPermission = (
calendarID: string,
memberID: string,
data: RequireOnly<Pick<UpdateCalendarMemberData, 'Permissions' | 'PassphraseKeyPacket'>, 'Permissions'>
) => ({
url: `${CALENDAR_V1}/${calendarID}/members/${memberID}/permission`,
method: 'put',
data,
});
export const updateInvitation = (
calendarID: string,
invitationID: string,
data: Partial<UpdateCalendarInviteData>
) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${invitationID}`,
method: 'put',
data,
});
export const removeMember = (calendarID: string, memberID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/members/${memberID}`,
method: 'delete',
});
export const getInvitation = (calendarID: string, invitationID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${invitationID}`,
method: 'get',
});
export const removeInvitation = (calendarID: string, invitationID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${invitationID}`,
method: 'delete',
});
export const acceptInvitation = (calendarID: string, addressID: string, data: { Signature: string }) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${addressID}/accept`,
method: 'put',
data,
});
export const rejectInvitation = (calendarID: string, addressID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${addressID}/reject`,
method: 'put',
});
export const getEventsCount = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/events/count`,
method: 'get',
});
export const queryEvents = (
calendarID: string,
params: CalendarEventsQuery | CalendarExportEventsQuery | GetEventByUIDArguments
) => ({
url: `${CALENDAR_V1}/${calendarID}/events`,
method: 'get',
params,
});
export const queryEventsIDs = (calendarID: string, params: CalendarEventsIDsQuery) => ({
url: `${CALENDAR_V1}/${calendarID}/events/ids`,
method: 'get',
params,
});
export const getEvent = (calendarID: string, eventID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/events/${eventID}`,
method: 'get',
});
export const getEventByUID = (params: GetEventByUIDArguments) => ({
url: `${CALENDAR_V1}/events`,
method: 'get',
params,
});
export const deleteEvent = (calendarID: string, eventID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/events/${eventID}`,
method: 'delete',
});
export const updatePersonalEventPart = (calendarID: string, eventID: string, data: CreateSinglePersonalEventData) => ({
url: `${CALENDAR_V1}/${calendarID}/events/${eventID}/personal`,
method: 'put',
data,
});
export const updateAttendeePartstat = (
calendarID: string,
eventID: string,
attendeeID: string,
data: Pick<Attendee, 'Status' | 'UpdateTime'>
) => ({
url: `${CALENDAR_V1}/${calendarID}/events/${eventID}/attendees/${attendeeID}`,
method: 'put',
data,
});
export const upgradeP2PInvite = (
calendarID: string,
eventID: string,
data: Pick<CalendarCreateOrUpdateEventBlobData, 'SharedKeyPacket'>
) => ({
url: `${CALENDAR_V1}/${calendarID}/events/${eventID}/upgrade`,
method: 'put',
data,
});
export const acceptInvite = (uid: string, data: { Signature: string }) => ({
url: `${CALENDAR_V1}/events/${uid}/accept`,
method: 'put',
data,
});
export const getCalendarSettings = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/settings`,
method: 'get',
});
export const updateCalendarSettings = (calendarID: string, data: Partial<CalendarSettings>) => ({
url: `${CALENDAR_V1}/${calendarID}/settings`,
method: 'put',
data,
});
export const getCalendarUserSettings = () => ({
url: 'settings/calendar',
method: 'get',
});
export const updateCalendarUserSettings = (data: Partial<CalendarUserSettings>) => ({
url: 'settings/calendar',
method: 'put',
data,
});
export const getAllowedTimeZones = () => ({
url: `${CALENDAR_V1}/timezones`,
method: 'get',
});
export const getVtimezones = (Timezones: string[]) => ({
// params doesn't work correctly so
url: `${CALENDAR_V1}/vtimezones?${Timezones.map((tzid) => `Timezones[]=${tzid}`).join('&')}`,
method: 'get',
// params: { Timezones }
});
export const queryCalendarAlarms = (calendarID: string, params: QueryCalendarAlarms) => ({
url: `${CALENDAR_V1}/${calendarID}/alarms`,
method: 'get',
params,
});
export const getCalendarAlarm = (calendarID: string, alarmID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/alarms/${alarmID}`,
method: 'get',
});
export const syncMultipleEvents = (calendarID: string, data: SyncMultipleEventsData) => ({
url: `${CALENDAR_V1}/${calendarID}/events/sync`,
method: 'put',
data,
});
export const createPublicLink = (calendarID: string, data: CreatePublicLinks) => ({
url: `${CALENDAR_V1}/${calendarID}/urls`,
method: 'post',
data,
});
export const getPublicLinks = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/urls`,
method: 'get',
});
export const deletePublicLink = ({ calendarID, urlID }: { calendarID: string; urlID: string }) => ({
url: `${CALENDAR_V1}/${calendarID}/urls/${urlID}`,
method: 'delete',
});
export const editPublicLink = ({
calendarID,
urlID,
encryptedPurpose,
}: {
calendarID: string;
urlID: string;
encryptedPurpose: Nullable<string>;
}) => ({
url: `${CALENDAR_V1}/${calendarID}/urls/${urlID}`,
method: 'put',
data: { EncryptedPurpose: encryptedPurpose },
});
export const getSubscriptionParameters = (calendarID: string) => ({
url: `${CALENDAR_V1}/${calendarID}/subscription`,
method: 'get',
});
export const validateSubscription = ({
url: URL,
mode: Mode = CALENDAR_VALIDATION_MODE.DOWNLOAD_AND_PARSE,
}: {
url: string;
mode?: CALENDAR_VALIDATION_MODE;
}) => ({
url: `${CALENDAR_V1}/subscription/validate`,
method: 'post',
data: { URL, Mode },
});
export const getDirectoryCalendars = (type: number) => ({
url: `${CALENDAR_V1}/directory?Type=${type}`,
method: 'get',
});
export const joinHolidaysCalendar = (
calendarID: string,
addressID: string,
data: {
PassphraseKeyPacket: string;
Signature: string;
Color: string;
DefaultFullDayNotifications: CalendarNotificationSettings[];
}
) => ({
url: `${CALENDAR_V1}/${calendarID}/invitations/${addressID}/join`,
method: 'post',
data,
});
| 8,215 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/checklist.ts | import { CHECKLIST_DISPLAY_TYPE, ChecklistId, ChecklistKeyType } from '../interfaces';
export const getChecklist = (checklistId: ChecklistId) => ({
method: 'get',
url: `core/v4/checklist/${checklistId}`,
});
export const seenCompletedChecklist = (checklistId: ChecklistId) => ({
method: 'post',
url: `core/v4/checklist/${checklistId}/seen-completed-list`,
});
export const getDriveChecklist = (checklistId: ChecklistId) => ({
method: 'get',
url: `drive/v2/checklist/${checklistId}`,
});
export const seenCompletedDriveChecklist = (checklistId: ChecklistId) => ({
method: 'post',
url: `drive/v2/checklist/${checklistId}/seen-completed-list`,
});
export const hidePaidUserChecklist = () => ({
method: 'post',
url: `core/v4/checklist/paying-user/hide`,
});
export const updateChecklistItem = (Item: ChecklistKeyType) => ({
method: 'put',
url: `core/v4/checklist/check-item`,
data: {
Item,
},
});
export const updateChecklistDisplay = (Display: Omit<CHECKLIST_DISPLAY_TYPE, CHECKLIST_DISPLAY_TYPE.FULL>) => ({
method: 'put',
url: `core/v4/checklist/update-display`,
data: {
Display,
},
});
| 8,216 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/contacts.ts | export const queryContacts = ({
Page = 0,
PageSize = 1000,
LabelID,
}: {
Page?: number;
PageSize?: number;
LabelID?: string;
} = {}) => ({
url: 'contacts/v4/contacts',
method: 'get',
params: { Page, PageSize, LabelID },
});
export const queryContactExport = ({
Page = 0,
PageSize = 50,
LabelID,
}: {
Page?: number;
PageSize?: number;
LabelID?: string;
} = {}) => ({
url: 'contacts/v4/contacts/export',
method: 'get',
params: { Page, PageSize, LabelID },
});
export const getContact = (contactID: string) => ({
url: `contacts/v4/contacts/${contactID}`,
method: 'get',
});
interface Card {
Type: number;
Data: string;
Signature: string | null;
}
export const addContacts = ({
Contacts,
Overwrite,
Labels,
Import,
}: {
Contacts: {
Cards: Card[];
}[];
Overwrite: 0 | 1;
Import?: 0 | 1;
Labels?: number;
timeout?: number;
}) => ({
url: 'contacts/v4/contacts',
method: 'post',
data: { Contacts, Overwrite, Labels, Import },
});
export const updateContact = (contactID: string, { Cards }: { Cards: Card[] }) => ({
url: `contacts/v4/contacts/${contactID}`,
method: 'put',
data: { Cards },
});
export const labelContacts = ({ LabelID, ContactIDs }: { LabelID: string; ContactIDs: string[] }) => ({
url: 'contacts/v4/contacts/label',
method: 'put',
data: { LabelID, ContactIDs },
});
export const unLabelContacts = ({ LabelID, ContactIDs }: { LabelID: string; ContactIDs: string[] }) => ({
url: 'contacts/v4/contacts/unlabel',
method: 'put',
data: { LabelID, ContactIDs },
});
export const deleteContacts = (IDs: string[]) => ({
url: 'contacts/v4/contacts/delete',
method: 'put',
data: { IDs },
});
export const clearContacts = () => ({
url: 'contacts/v4/contacts',
method: 'delete',
});
export const queryContactEmails = ({
Page,
PageSize,
Email,
LabelID,
}: {
Page?: number;
PageSize?: number;
} & (
| {
Email?: string;
LabelID?: never;
}
| {
Email?: never;
LabelID?: string;
}
) = {}) => ({
url: 'contacts/v4/contacts/emails',
method: 'get',
params: { Page, PageSize, Email, LabelID },
});
export const labelContactEmails = ({ LabelID, ContactEmailIDs }: { LabelID: string; ContactEmailIDs: string[] }) => ({
url: 'contacts/v4/contacts/emails/label',
method: 'put',
data: { LabelID, ContactEmailIDs },
});
export const unLabelContactEmails = ({ LabelID, ContactEmailIDs }: { LabelID: string; ContactEmailIDs: string[] }) => ({
url: 'contacts/v4/contacts/emails/unlabel',
method: 'put',
data: { LabelID, ContactEmailIDs },
});
| 8,217 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/conversations.ts | import { SPAM_ACTION } from '../mail/mailSettings';
import { getAppropriateSort } from './helpers/snoozeSort';
interface QueryConversationProps {
Location: any;
To: any;
Starred: any;
Page: number;
PageSize: number;
Limit: Number;
LabelID: string;
Sort?: string;
Desc: number;
Begin: string;
End: string;
BeginID: string;
EndID: string;
Keyword: string;
From: string;
Subject: string;
Attachments: number;
Unread: number;
AddressID: string;
ID: string;
AutoWildcard: number;
}
export const queryConversations = ({
Location,
Page = 0,
PageSize = 50,
Limit = 50,
LabelID,
Sort = 'Time',
Desc = 1,
Begin,
End,
BeginID,
EndID,
Keyword,
To,
From,
Subject,
Attachments,
Starred,
Unread,
AddressID,
ID,
AutoWildcard,
}: QueryConversationProps) => ({
method: 'get',
url: 'mail/v4/conversations',
params: {
Location,
Page,
PageSize,
Limit,
LabelID,
Sort: getAppropriateSort(LabelID, Sort),
Desc,
Begin,
End,
BeginID,
EndID,
Keyword,
Recipients: To,
From,
Subject,
Attachments,
Starred,
Unread,
AddressID,
ID,
AutoWildcard,
},
});
export const getConversation = (conversationID: string, MessageID?: string) => ({
method: 'get',
url: `mail/v4/conversations/${conversationID}`,
params: { MessageID },
});
export const queryConversationCount = (AddressID: string) => ({
method: 'get',
url: 'mail/v4/conversations/count',
params: { AddressID },
});
export const markConversationsAsRead = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/conversations/read',
data: { IDs },
});
export const markConversationsAsUnread = (IDs: string[], LabelID: string) => ({
method: 'put',
url: 'mail/v4/conversations/unread',
data: { IDs, LabelID },
});
export const deleteConversations = (IDs: string[], LabelID: string) => ({
method: 'put',
url: 'mail/v4/conversations/delete',
data: { IDs, LabelID },
});
interface LabelConversationsProps {
LabelID: string;
IDs: string[];
SpamAction?: SPAM_ACTION;
}
export const labelConversations = ({ LabelID, IDs, SpamAction }: LabelConversationsProps) => ({
method: 'put',
url: 'mail/v4/conversations/label',
data: { LabelID, IDs, SpamAction },
});
export const unlabelConversations = ({ LabelID, IDs }: LabelConversationsProps) => ({
method: 'put',
url: 'mail/v4/conversations/unlabel',
data: { LabelID, IDs },
});
export const setExpiration = (IDs: string[], ExpirationTime: number | null) => ({
method: 'put',
url: 'mail/v4/conversations/expire',
data: { IDs, ExpirationTime },
});
export const snoozeConversations = (IDs: string[], SnoozeTime: number) => ({
method: 'put',
url: 'mail/v4/conversations/snooze',
data: { IDs, SnoozeTime },
});
export const unsnoozeConversations = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/conversations/unsnooze',
data: { IDs },
});
| 8,218 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/domains.js | export const queryDomains = (params) => ({
url: 'domains',
method: 'get',
params,
});
export const getDomain = (domainID) => ({
url: `domains/${domainID}`,
method: 'get',
});
export const queryDomainAddresses = (domainID, params) => ({
url: `domains/${domainID}/addresses`,
method: 'get',
params,
});
export const queryAvailableDomains = (Type) => ({
url: 'domains/available',
method: 'get',
params: { Type },
});
export const queryPremiumDomains = () => ({
url: 'domains/premium',
method: 'get',
});
export const addDomain = (Name) => ({
url: 'domains',
method: 'post',
data: { Name },
});
export const updateCatchAll = (domainID, AddressID) => ({
url: `domains/${domainID}/catchall`,
method: 'put',
data: { AddressID },
});
export const deleteDomain = (domainID) => ({
url: `domains/${domainID}`,
method: 'delete',
});
| 8,219 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/eo.ts | export const getEOToken = (id: string) => ({
method: 'get',
url: `mail/v4/eo/token/${id}`,
});
export const getEOMessage = (decryptedToken: string, id: string) => ({
method: 'get',
url: `mail/v4/eo/message`,
headers: {
Authorization: decryptedToken,
'x-eo-uid': id,
},
});
export const getEOAttachment = (attachmentId: string, decryptedToken: string, id: string) => ({
method: 'get',
url: `mail/v4/eo/attachment/${attachmentId}`,
headers: {
Authorization: decryptedToken,
'x-eo-uid': id,
},
output: 'arrayBuffer',
});
export const EOReply = (
decryptedToken: string,
id: string,
data: {
Body: string;
ReplyBody: string;
'Filename[]': string[];
'MIMEType[]': string[];
'ContentID[]': string[];
'KeyPackets[]': Blob[];
'DataPacket[]': Blob[];
}
) => ({
method: 'post',
url: 'mail/v4/eo/reply',
input: 'form',
headers: {
Authorization: decryptedToken,
'x-eo-uid': id,
},
data,
});
| 8,220 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/events.ts | export const getLatestID = () => ({
url: 'core/v4/events/latest',
method: 'get',
});
export const getEvents = (eventID: string, params?: { ConversationCounts: 1 | 0; MessageCounts: 1 | 0 }) => ({
url: `core/v4/events/${eventID}`,
method: 'get',
params,
});
| 8,221 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/experiments.ts | export const getExperiment = (experimentCode: string) => ({
url: `core/v4/experiments/${experimentCode}`,
method: 'get',
});
/**
* Get all experiment flags of experimentCodes
* API route is a lot more powerfull with sorts, filters
* It's just not needed at this point
*/
export const getExperiments = () => {
return {
url: `core/v4/experiments`,
method: 'get',
};
};
| 8,222 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/features.ts | export const getFeature = (featureCode: string) => ({
url: `core/v4/features/${featureCode}`,
method: 'get',
});
/**
* Get all feature flags of featureCodes
* API route is a lot more powerfull with sorts, filters
* It's just not needed at this point
*/
export const getFeatures = (featureCodes: string[]) => {
if (featureCodes?.length < 1) {
throw new Error(`Provide a list of feature code, getting them all at once is not recommended at this point`);
}
if (featureCodes.length > 150) {
throw new Error(`You can't ask for more than 150 features at a time, use pagination instead`);
}
return {
url: `core/v4/features`,
method: 'get',
params: {
Code: featureCodes.join(','),
Limit: featureCodes.length,
},
};
};
export const updateFeatureValue = (featureCode: string, Value: any) => ({
url: `core/v4/features/${featureCode}/value`,
method: 'put',
data: { Value },
});
| 8,223 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/feedback.ts | export const sendFeedback = ({
Score,
Feedback,
FeedbackType,
}: {
Score: number;
Feedback: string;
FeedbackType: string;
}) => ({
url: `core/v4/feedback`,
method: 'post',
data: { Score, Feedback, FeedbackType },
});
| 8,224 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/filters.ts | import { Filter } from '@proton/components/containers/filters/interfaces';
type AddSieveFilterParams = Required<Pick<Filter, 'Name' | 'Sieve' | 'Version'>>;
export const addSieveFilter = ({ Name, Sieve, Version }: AddSieveFilterParams) => ({
method: 'post',
url: 'mail/v4/filters',
data: { Name, Sieve, Version },
});
export const addTreeFilter = (
{ ID, Name, Status, Version, Simple, Tree, Sieve }: Filter,
Source?: 'AutoLabel' | 'AutoFolder'
) => ({
method: 'post',
url: 'mail/v4/filters',
data: { ID, Name, Status, Version, Simple, Tree, Sieve },
params: { Source },
});
export const queryFilters = () => ({
method: 'get',
url: 'mail/v4/filters',
});
export const clearFilters = () => ({
method: 'delete',
url: 'mail/v4/filters',
});
export const updateFilter = (filterID: string, { Name, Status, Version, Sieve, Simple, Tree }: Omit<Filter, 'ID'>) => ({
method: 'put',
url: `mail/v4/filters/${filterID}`,
data: { Name, Status, Version, Simple, Tree, Sieve },
});
export const checkSieveFilter = (
{ Sieve, Version }: Partial<Pick<Filter, 'Sieve' | 'Version'>> = { Sieve: undefined, Version: undefined }
) => ({
method: 'put',
url: 'mail/v4/filters/check',
data: { Sieve, Version },
});
export const enableFilter = (filterID: string) => ({
method: 'put',
url: `mail/v4/filters/${filterID}/enable`,
});
export const disableFilter = (filterID: string) => ({
method: 'put',
url: `mail/v4/filters/${filterID}/disable`,
});
export const toggleEnable = (ID: string, enable = true) => (enable ? enableFilter : disableFilter)(ID);
export const deleteFilter = (filterID: string) => ({
method: 'delete',
url: `mail/v4/filters/${filterID}`,
});
export const updateFilterOrder = (FilterIDs: string[]) => ({
method: 'put',
url: 'mail/v4/filters/order',
data: { FilterIDs },
});
interface ApplyFiltersParams {
AllowList?: 0 | 1;
BlockList?: 0 | 1;
}
export const applyAllFilters = ({ AllowList = 0, BlockList = 0 }: ApplyFiltersParams = {}) => ({
method: 'post',
url: 'mail/v4/messages/apply-filters',
data: { AllFilters: 1, AllowList, BlockList },
});
export const applyFilters = (FilterIDs: string[], { AllowList = 0, BlockList = 0 }: ApplyFiltersParams = {}) => ({
method: 'post',
url: 'mail/v4/messages/apply-filters',
data: { AllFilters: 0, FilterIDs, AllowList, BlockList },
});
| 8,225 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/forwardings.ts | import { SIEVE_VERSION, SieveBranch } from '@proton/sieve/src/interface';
import {
Api,
ForwardingState,
ForwardingType,
IncomingAddressForwarding,
OutgoingAddressForwarding,
} from '../interfaces';
import queryPages from './helpers/queryPages';
interface ProxyInstance {
PgpVersion: number;
ForwarderKeyFingerprint: string;
ForwardeeKeyFingerprint: string;
ProxyParam: string;
}
interface QueryProps {
AddressID?: string;
Page?: number;
PageSize?: number;
}
export const queryOutgoingForwardings = ({ AddressID, Page, PageSize }: QueryProps) => ({
method: 'get',
url: 'mail/v4/forwardings/outgoing',
params: { Page, PageSize, AddressID },
});
export const queryAllOutgoingForwardings = (api: Api) => {
return queryPages((Page, PageSize) => {
return api<{ OutgoingAddressForwardings: OutgoingAddressForwarding[]; Total: number }>(
queryOutgoingForwardings({
Page,
PageSize,
})
);
}).then((pages) => {
return pages.flatMap(({ OutgoingAddressForwardings }) => OutgoingAddressForwardings);
});
};
export const queryIncomingForwardings = ({ AddressID, Page, PageSize }: QueryProps) => ({
method: 'get',
url: 'mail/v4/forwardings/incoming',
params: { Page, PageSize, AddressID },
});
export const queryAllIncomingForwardings = (api: Api) => {
return queryPages((Page, PageSize) => {
return api<{ IncomingAddressForwardings: IncomingAddressForwarding[]; Total: number }>(
queryIncomingForwardings({
Page,
PageSize,
})
);
}).then((pages) => {
return pages.flatMap(({ IncomingAddressForwardings }) => IncomingAddressForwardings);
});
};
export interface SetupForwardingParameters {
Type: ForwardingType;
ForwarderAddressID: string;
ForwardeeEmail: string;
ForwardeePrivateKey?: string; // Only for internal E2EE forwarding
ActivationToken?: string; // Only for internal E2EE forwarding
ProxyInstances?: ProxyInstance[]; // Only for E2EE forwarding
Tree: SieveBranch[] | null;
Version: SIEVE_VERSION;
}
export const setupForwarding = ({
Type,
ForwarderAddressID,
ForwardeeEmail,
ForwardeePrivateKey,
ActivationToken,
ProxyInstances,
Tree,
Version,
}: SetupForwardingParameters) => ({
method: 'post',
url: 'mail/v4/forwardings',
data: {
Type,
ForwarderAddressID,
ForwardeeEmail,
ForwardeePrivateKey,
ActivationToken,
ProxyInstances,
Tree,
Version,
},
});
interface UpdateForwardingParameters {
ID: string;
ForwardeePrivateKey: string;
ActivationToken: string;
ProxyInstances: ProxyInstance[];
}
export const updateForwarding = ({
ID,
ForwardeePrivateKey,
ActivationToken,
ProxyInstances,
}: UpdateForwardingParameters) => ({
method: 'put',
url: `mail/v4/forwardings/${ID}`,
data: {
ForwardeePrivateKey,
ActivationToken,
ProxyInstances,
},
});
export const deleteForwarding = (ID: string) => ({
method: 'delete',
url: `mail/v4/forwardings/${ID}`,
});
export const rejectForwarding = (ID: string) => ({
method: 'delete',
url: `mail/v4/forwardings/${ID}`,
});
export const acceptExternalForwarding = (jwt: string) => ({
method: 'put',
url: `mail/v4/forwardings/external/${jwt}`,
});
export const rejectExternalForwarding = (jwt: string) => ({
method: 'delete',
url: `mail/v4/forwardings/external/${jwt}`,
});
export interface ExternalForwardingResult {
Code: number;
Type: ForwardingType;
State: ForwardingState;
ForwarderEmail: string;
ForwardeeEmail: string;
}
export const getExternalForwarding = (jwt: string) => ({
method: 'get',
url: `mail/v4/forwardings/external/${jwt}`,
});
export const pauseForwarding = (ID: string) => ({
method: 'put',
url: `mail/v4/forwardings/${ID}/pause`,
});
export const resumeForwarding = (ID: string) => ({
method: 'put',
url: `mail/v4/forwardings/${ID}/resume`,
});
export const resendForwardingInvitation = (ID: string) => ({
method: 'put',
url: `mail/v4/forwardings/${ID}/reinvite`,
});
export const updateForwardingFilter = (ID: string, Tree: SieveBranch[] | null, Version: SIEVE_VERSION) => ({
method: 'put',
url: `mail/v4/forwardings/${ID}/filter`,
data: { Tree, Version },
});
| 8,226 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/images.ts | export const getImage = (Url: string, DryRun = 0, UID?: string) => ({
method: 'get',
url: 'core/v4/images',
params: { Url, DryRun, UID },
});
export type SenderImageMode = 'light' | 'dark';
/**
* Get logo corresponding to address
* @param Address encoded email address
* @param Size The size of the logo to be returned, default 48
* @returns
*/
export const getLogo = (
Address: string,
Size?: number,
BimiSelector?: string,
Mode?: SenderImageMode,
UID?: string
) => ({
method: 'get',
url: 'core/v4/images/logo',
params: { UID, Address, Size, BimiSelector, Mode },
});
| 8,227 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/incomingDefaults.ts | export const getIncomingDefaults = ({
Location,
Page,
PageSize,
Keyword,
}: {
Location?: number;
Page?: number;
PageSize?: number;
Keyword?: string;
} = {}) => ({
method: 'get',
url: 'mail/v4/incomingdefaults',
params: { Location, Page, PageSize, Keyword },
});
interface IncomingDefaultConfig {
Email?: string;
Domain?: string;
Location: number;
}
interface AddIncomingDefaultConfig extends IncomingDefaultConfig {
/**
* If email is already registered in incomingDefaults we overwrite the location
* Avoids to find the already exiting item ID
*/
Overwrite?: boolean;
}
export const addIncomingDefault = ({ Email, Domain, Location, Overwrite }: AddIncomingDefaultConfig) => {
let url = 'mail/v4/incomingdefaults';
if (Overwrite) {
url = `${url}?Overwrite=1`;
}
return {
method: 'post',
url,
data: { Email, Domain, Location },
};
};
export const updateIncomingDefault = (
incomingDefaultID: string,
{ Email, Domain, Location }: IncomingDefaultConfig
) => ({
method: 'put',
url: `mail/v4/incomingdefaults/${incomingDefaultID}`,
data: { Email, Domain, Location },
});
export const deleteIncomingDefaults = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/incomingdefaults/delete',
data: { IDs },
});
export const clearIncomingDefaults = () => ({
method: 'delete',
url: 'mail/v4/incomingdefaults',
});
| 8,228 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/interface.ts | export interface PaginationParams {
Page?: number;
PageSize?: number;
}
| 8,229 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/invites.ts | import { CLIENT_TYPES } from '../constants';
export const createInvitation = ({ Email, Type }: { Email: string; Type: CLIENT_TYPES }) => ({
method: 'post',
url: 'core/v4/invites',
data: { Email, Type },
});
export const checkInvitation = (data: { Selector: string; Token: string; Type: CLIENT_TYPES }) => ({
method: 'post',
url: 'core/v4/invites/check',
data,
});
| 8,230 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/keys.ts | import { AddressKeyPayload, AddressKeyPayloadV2, SignedKeyList } from '../interfaces';
interface GetPublicKeysForInboxParams {
Email: string;
Fingerprint?: string;
}
/** @deprecated in favor of `getAllPublicKeys` */
export const getPublicKeys = (params: GetPublicKeysForInboxParams) => ({
url: 'core/v4/keys',
method: 'get',
params,
});
interface GetAllPublicKeysParams {
Email: string;
InternalOnly?: 0 | 1;
}
export const getAllPublicKeys = (params: GetAllPublicKeysParams) => ({
url: 'core/v4/keys/all',
method: 'get',
params,
});
export const getKeySalts = () => ({
url: 'core/v4/keys/salts',
method: 'get',
});
interface CreateUserKeyPayload {
Primary: number;
PrivateKey: string;
}
export const createUserKeyRoute = (data: CreateUserKeyPayload) => ({
url: 'core/v4/keys/user',
method: 'post',
data,
});
interface AddressKeyToken {
AddressKeyID: string;
KeyPacket: string;
Signature: string;
}
interface AddressTokensPayload {
AddressKeyTokens: AddressKeyToken[];
}
export const replaceAddressTokens = (data: AddressTokensPayload) => ({
url: 'core/v4/keys/tokens',
method: 'put',
data,
});
interface CreateAddressKeyPayload {
AddressID: string;
Primary: number;
PrivateKey: string;
SignedKeyList: SignedKeyList;
AddressForwardingID?: string;
}
export const createAddressKeyRoute = (data: CreateAddressKeyPayload) => ({
url: 'core/v4/keys',
method: 'post',
data,
});
interface CreateAddressKeyPayloadV2 extends CreateAddressKeyPayload {
Token: string;
Signature: string;
}
export const createAddressKeyRouteV2 = (data: CreateAddressKeyPayloadV2) => ({
url: 'core/v4/keys/address',
method: 'post',
data,
});
interface SetupKeysPayload {
PrimaryKey: string;
KeySalt: string;
AddressKeys: (AddressKeyPayload | AddressKeyPayloadV2)[];
}
export const setupKeys = (data: SetupKeysPayload) => ({
url: 'core/v4/keys/setup',
method: 'post',
data,
});
interface ActivateKeyPayload {
ID: string;
PrivateKey: string;
SignedKeyList: SignedKeyList;
}
export const activateKeyRoute = ({ ID, ...data }: ActivateKeyPayload) => ({
url: `core/v4/keys/${ID}/activate`,
method: 'put',
data,
});
interface ActivateKeyPayloadV2 extends ActivateKeyPayload {
Signature: string;
Token: string;
}
export const activateKeyRouteV2 = ({ ID, ...data }: ActivateKeyPayloadV2) => ({
url: `core/v4/keys/address/${ID}`,
method: 'put',
data,
});
export const reactiveLegacyAddressKeyRouteV2 = ({ ID, ...data }: ActivateKeyPayloadV2) => ({
url: `core/v4/keys/address/${ID}`,
method: 'put',
data,
});
interface ReactivateKeyPayload {
ID: string;
PrivateKey: string;
SignedKeyList?: SignedKeyList;
}
export const reactivateKeyRoute = ({ ID, PrivateKey, SignedKeyList }: ReactivateKeyPayload) => ({
url: `core/v4/keys/${ID}`,
method: 'put',
data: {
PrivateKey,
SignedKeyList,
},
});
interface ReactivateUserKeyPayloadV2 {
ID: string;
PrivateKey: string;
AddressKeyFingerprints: string[];
SignedKeyLists: {
[key: string]: SignedKeyList;
};
}
export const reactivateUserKeyRouteV2 = ({ ID, ...data }: ReactivateUserKeyPayloadV2) => ({
url: `core/v4/keys/user/${ID}`,
method: 'put',
data,
});
interface SetKeyPrimaryPayload {
ID: string;
SignedKeyList: SignedKeyList;
}
export const setKeyPrimaryRoute = ({ ID, ...data }: SetKeyPrimaryPayload) => ({
url: `core/v4/keys/${ID}/primary`,
method: 'put',
data,
});
interface SetKeyFlagsPayload {
ID: string;
Flags: number;
SignedKeyList: SignedKeyList;
}
export const setKeyFlagsRoute = ({ ID, ...data }: SetKeyFlagsPayload) => ({
url: `core/v4/keys/${ID}/flags`,
method: 'put',
data,
});
interface RemoveKeyPayload {
ID: string;
SignedKeyList: SignedKeyList;
}
export const removeKeyRoute = ({ ID, ...data }: RemoveKeyPayload) => ({
url: `core/v4/keys/${ID}/delete`,
method: 'put',
data,
});
export interface UpdatePrivateKeyPayload {
KeySalt: string;
Keys: { ID: string; PrivateKey: string }[];
OrganizationKey?: string;
}
export interface UpdatePrivateKeyPayloadV2 {
KeySalt: string;
UserKeys: { ID: string; PrivateKey: string }[];
OrganizationKey?: string;
}
export const updatePrivateKeyRoute = (data: UpdatePrivateKeyPayload | UpdatePrivateKeyPayloadV2) => ({
url: 'core/v4/keys/private',
method: 'put',
data,
});
export interface ResetKeysPayload {
Username: string;
Token: string;
KeySalt: string;
}
export interface ResetKeysPayloadWithKeys extends ResetKeysPayload {
PrimaryKey: string;
AddressKeys: AddressKeyPayload[];
}
export interface ResetKeysPayloadV2 extends ResetKeysPayload {
PrimaryKey: string;
AddressKeys: AddressKeyPayloadV2[];
}
export const resetKeysRoute = (data: ResetKeysPayloadWithKeys | ResetKeysPayloadV2 | ResetKeysPayload) => ({
url: 'core/v4/keys/reset',
method: 'post',
data,
});
interface UpgradeKeyPayload {
ID: string;
PrivateKey: string;
}
interface UpgradeKeysPayload {
KeySalt: string;
Keys: UpgradeKeyPayload[];
OrganizationKey?: string;
}
export interface UpgradeAddressKeyPayload {
ID: string;
PrivateKey: string;
Token: string;
Signature: string;
}
interface UpgradeKeysPayloadV2 {
KeySalt: string;
UserKeys: UpgradeKeyPayload[];
AddressKeys: UpgradeAddressKeyPayload[];
OrganizationKey?: string;
SignedKeyLists: {
[key: string]: SignedKeyList;
};
}
export const upgradeKeysRoute = (data: UpgradeKeysPayload | UpgradeKeysPayloadV2) => ({
url: 'core/v4/keys/private/upgrade',
method: 'post',
data,
});
export interface MigrateAddressKeyPayload {
ID: string;
Token: string;
Signature: string;
PrivateKey: string;
}
export interface MigrateAddressKeysPayload {
AddressKeys: MigrateAddressKeyPayload[];
SignedKeyLists: { [key: string]: SignedKeyList };
}
export const migrateAddressKeysRoute = (data: MigrateAddressKeysPayload) => ({
url: 'core/v4/keys/migrate',
method: 'post',
data,
});
export interface GetSignedKeyListsParams {
AfterRevision?: number;
Identifier: string;
}
export const getSignedKeyListsRoute = (params: GetSignedKeyListsParams) => ({
url: 'core/v4/keys/signedkeylists',
method: 'get',
params,
});
export interface GetSignedKeyListParams {
Revision: number;
Identifier: string;
}
export const getSignedKeyListRoute = (params: GetSignedKeyListParams) => ({
url: 'keys/signedkeylist',
method: 'get',
params,
});
export interface UpdateSignedKeyListPayload {
AddressID: string;
SignedKeyList: SignedKeyList;
}
export const updateSignedKeyListRoute = (data: UpdateSignedKeyListPayload) => ({
url: 'core/v4/keys/signedkeylists',
method: 'post',
data,
});
export interface UpdateSignedKeyListSignatureData {
AddressID: string;
Revision: number;
Signature: string;
}
export const updateSignedKeyListSignatureRoute = (data: UpdateSignedKeyListSignatureData) => ({
url: 'core/v4/keys/signedkeylists/signature',
method: 'put',
data,
});
| 8,231 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/labels.ts | import { LABEL_TYPE } from '../constants';
const { MESSAGE_LABEL, MESSAGE_FOLDER, CONTACT_GROUP, SYSTEM_FOLDER } = LABEL_TYPE;
export const get = (Type: number) => ({
url: 'core/v4/labels',
method: 'get',
params: { Type },
});
interface PartialLabelOrderArgument {
LabelIDs: string[];
ParentID?: string | number;
}
interface LabelOrderArgument extends PartialLabelOrderArgument {
Type: number;
}
export const order = ({ LabelIDs, ParentID, Type }: LabelOrderArgument) => ({
method: 'put',
url: 'core/v4/labels/order',
data: { LabelIDs, ParentID, Type },
});
interface PartialCreateLabelArgument {
Name: string;
Color: string;
ParentID?: string | number;
Notify?: number;
Expanded?: number;
Sticky?: number;
}
interface CreateLabelArgument extends PartialCreateLabelArgument {
Type: number;
}
export const create = ({ Name, Color, Type, Notify, ParentID, Expanded }: CreateLabelArgument) => ({
method: 'post',
url: 'core/v4/labels',
data: { Name, Color, Type, Notify, ParentID, Expanded },
});
interface UpdateLabelArguments {
Name: string;
Color: string;
Notify?: number;
ParentID?: string | number;
Sticky?: number;
Expanded?: number;
Display?: number;
}
export const updateLabel = (
labelID: string,
{ Name, Color, Notify, ParentID, Sticky, Expanded, Display }: UpdateLabelArguments
) => ({
method: 'put',
url: `core/v4/labels/${labelID}`,
data: { Name, Color, Notify, ParentID, Sticky, Expanded, Display },
});
export const deleteLabel = (labelID: string) => ({
method: 'delete',
url: `core/v4/labels/${labelID}`,
});
export const deleteLabels = (labelIDs: string[]) => ({
method: 'delete',
url: 'core/v4/labels',
data: { LabelIDs: labelIDs },
});
export const checkLabelAvailability = (params: { Name: string; Type: LABEL_TYPE; ParentID?: string | number }) => ({
method: 'get',
url: 'core/v4/labels/available',
params,
});
export const getLabels = () => get(MESSAGE_LABEL);
export const getFolders = () => get(MESSAGE_FOLDER);
export const getSystemFolders = () => get(SYSTEM_FOLDER);
export const getContactGroup = () => get(CONTACT_GROUP);
export const orderFolders = (opt: PartialLabelOrderArgument) => order({ ...opt, Type: MESSAGE_FOLDER });
export const orderLabels = (opt: PartialLabelOrderArgument) => order({ ...opt, Type: MESSAGE_LABEL });
export const orderSystemFolders = (opt: Pick<PartialLabelOrderArgument, 'LabelIDs'>) =>
order({ ...opt, ParentID: undefined, Type: SYSTEM_FOLDER });
export const orderContactGroup = (opt: PartialLabelOrderArgument) => order({ ...opt, Type: CONTACT_GROUP });
export const createLabel = (opt: PartialCreateLabelArgument) => create({ ...opt, Type: MESSAGE_LABEL });
export const createContactGroup = (opt: PartialCreateLabelArgument) => create({ ...opt, Type: CONTACT_GROUP });
export const updateSystemFolders = (labelId: string, opt: Pick<UpdateLabelArguments, 'Color' | 'Name' | 'Display'>) =>
updateLabel(labelId, { ...opt });
| 8,232 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/logs.js | export const queryLogs = (params) => ({
method: 'get',
url: 'core/v4/logs/auth',
params,
});
export const clearLogs = () => ({
method: 'delete',
url: 'core/v4/logs/auth',
});
| 8,233 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/mailSettings.ts | import { AutoResponder as tsAutoResponder } from '../interfaces/AutoResponder';
import { BLOCK_SENDER_CONFIRMATION } from '../mail/constants';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS, DIRECTION, PM_SIGNATURE_REFERRAL, SPAM_ACTION } from '../mail/mailSettings';
export const getMailSettings = () => ({
url: 'mail/v4/settings',
method: 'get',
});
export const updateShowMoved = (ShowMoved: number) => ({
url: 'mail/v4/settings/moved',
method: 'put',
data: { ShowMoved },
});
export const updateHideRemoteImages = (HideRemoteImages: number) => ({
url: 'mail/v4/settings/hide-remote-images',
method: 'put',
data: { HideRemoteImages },
});
export const updateShowAlmostAllMail = (AlmostAllMail: number) => ({
url: 'mail/v4/settings/almost-all-mail',
method: 'put',
data: { AlmostAllMail },
});
export const updateHideEmbeddedImages = (HideEmbeddedImages: number) => ({
url: 'mail/v4/settings/hide-embedded-images',
method: 'put',
data: { HideEmbeddedImages },
});
export const updateAutoSaveContacts = (AutoSaveContacts: number) => ({
url: 'mail/v4/settings/autocontacts',
method: 'put',
data: { AutoSaveContacts },
});
export const updateTheme = (Theme: string | number) => ({
url: 'mail/v4/settings/theme',
method: 'put',
data: { Theme },
});
export const updateDisplayName = (DisplayName: string) => ({
url: 'mail/v4/settings/display',
method: 'put',
data: { DisplayName },
});
export const updateSignature = (Signature: string) => ({
url: 'mail/v4/settings/signature',
method: 'put',
data: { Signature },
});
export const updatePMSignature = (PMSignature: number) => ({
url: 'mail/v4/settings/pmsignature',
method: 'put',
data: { PMSignature },
});
export const updatePMSignatureReferralLink = (PMSignatureReferralLink: PM_SIGNATURE_REFERRAL) => ({
url: 'mail/v4/settings/pmsignature-referral',
method: 'put',
data: { PMSignatureReferralLink },
});
export const updateComposerMode = (ComposerMode: number) => ({
url: 'mail/v4/settings/composermode',
method: 'put',
data: { ComposerMode },
});
export const updateMessageButtons = (MessageButtons: number) => ({
url: 'mail/v4/settings/messagebuttons',
method: 'put',
data: { MessageButtons },
});
export const updateViewMode = (ViewMode: number) => ({
url: 'mail/v4/settings/viewmode',
method: 'put',
data: { ViewMode },
});
export const updateStickyLabels = (StickyLabels: number) => ({
url: 'mail/v4/settings/stickylabels',
method: 'put',
data: { StickyLabels },
});
export const updateDraftType = (MIMEType: string) => ({
url: 'mail/v4/settings/drafttype',
method: 'put',
data: { MIMEType },
});
export const updateRightToLeft = (RightToLeft: DIRECTION) => ({
url: 'mail/v4/settings/righttoleft',
method: 'put',
data: { RightToLeft },
});
export const updateViewLayout = (ViewLayout: number) => ({
url: 'mail/v4/settings/viewlayout',
method: 'put',
data: { ViewLayout },
});
export const updatePromptPin = (PromptPin: number) => ({
url: 'mail/v4/settings/promptpin',
method: 'put',
data: { PromptPin },
});
export const updateKT = (KT: number) => ({
url: 'mail/v4/settings/kt',
method: 'put',
data: { KT },
});
export const updatePGPScheme = (PGPScheme: number) => ({
url: 'mail/v4/settings/pgpscheme',
method: 'put',
data: { PGPScheme },
});
export const updateSign = (Sign: number) => ({
url: 'mail/v4/settings/sign',
method: 'put',
data: { Sign },
});
export const updateAttachPublicKey = (AttachPublicKey: number) => ({
url: 'mail/v4/settings/attachpublic',
method: 'put',
data: { AttachPublicKey },
});
export const updateShortcuts = (Shortcuts: number) => ({
url: 'mail/v4/settings/shortcuts',
method: 'put',
data: { Shortcuts },
});
export const updateAutoresponder = (AutoResponder: tsAutoResponder) => ({
url: 'mail/v4/settings/autoresponder',
method: 'put',
data: { AutoResponder },
});
export const updateConfirmLink = (ConfirmLink: number) => ({
url: 'mail/v4/settings/confirmlink',
method: 'put',
data: { ConfirmLink },
});
export const updateDelaySend = (DelaySendSeconds: number) => ({
url: 'mail/v4/settings/delaysend',
method: 'put',
data: { DelaySendSeconds },
});
export const updateEnableFolderColor = (EnableFolderColor: number) => ({
url: 'mail/v4/settings/enablefoldercolor',
method: 'put',
data: { EnableFolderColor },
});
export const updateInheritParentFolderColor = (InheritParentFolderColor: number) => ({
url: 'mail/v4/settings/inheritparentfoldercolor',
method: 'put',
data: { InheritParentFolderColor },
});
export const updateFontFace = (FontFace: string) => ({
url: 'mail/v4/settings/fontface',
method: 'put',
data: { FontFace },
});
export const updateFontSize = (FontSize: number) => ({
url: 'mail/v4/settings/fontsize',
method: 'put',
data: { FontSize },
});
export const updateImageProxy = (ImageProxy: number, Action: 'add' | 'remove') => ({
url: 'mail/v4/settings/imageproxy',
method: 'put',
data: { ImageProxy, Action: Action === 'add' ? 1 : 0 },
});
export const updateSpamAction = (SpamAction: SPAM_ACTION | null) => ({
url: 'mail/v4/settings/spam-action',
method: 'put',
data: { SpamAction },
});
export const updateBlockSenderConfirmation = (BlockSenderConfirmation: BLOCK_SENDER_CONFIRMATION | null) => ({
url: 'mail/v4/settings/block-sender-confirmation',
method: 'put',
data: { BlockSenderConfirmation },
});
export const updateHideSenderImages = (HideSenderImages: number) => ({
url: 'mail/v4/settings/hide-sender-images',
method: 'put',
data: { HideSenderImages },
});
export const updateDisplayUnreadFavicon = (UnreadFavicon: number) => ({
url: 'mail/v4/settings/unread-favicon',
method: 'put',
data: { UnreadFavicon },
});
export const updateAutoDelete = (AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS) => ({
url: 'mail/v4/settings/auto-delete-spam-and-trash-days',
method: 'put',
data: { Days: AutoDeleteSpamAndTrashDays },
});
| 8,234 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/mailUndoActions.ts | export const undoActions = (Token: string) => ({
url: 'mail/v4/undoactions',
method: 'post',
data: { Token },
});
| 8,235 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/memberKeys.ts | import { SignedKeyList } from '../interfaces';
interface SetupMemberKeyAddressKeyPayload {
AddressID: string;
SignedKeyList: SignedKeyList;
UserKey: string;
MemberKey: string;
Token: string;
}
interface SetupMemberKeyUserKeyPayload {
UserKey: string;
MemberKey: string;
Token: string;
}
interface SetupMemberKeyPayload {
MemberID: string;
AddressKeys: SetupMemberKeyAddressKeyPayload[];
KeySalt: string;
PrimaryKey: SetupMemberKeyUserKeyPayload;
}
interface SetupMemberKeyUserKeyPayloadV2 {
PrivateKey: string;
OrgPrivateKey: string;
OrgToken: string;
}
interface SetupMemberKeyAddressKeyPayloadV2 {
AddressID: string;
PrivateKey: string;
Token: string;
Signature: string;
OrgSignature: string;
SignedKeyList: SignedKeyList;
}
interface SetupMemberKeyPayloadV2 {
MemberID: string;
AddressKeys: SetupMemberKeyAddressKeyPayloadV2[];
KeySalt: string;
UserKey: SetupMemberKeyUserKeyPayloadV2;
}
export const setupMemberKeyRoute = ({ MemberID, ...data }: SetupMemberKeyPayload | SetupMemberKeyPayloadV2) => ({
url: `members/${MemberID}/keys/setup`,
method: 'post',
data,
});
interface CreateMemberKeyPayload {
MemberID: string;
Activation: string;
Token: string;
AddressID: string;
UserKey: string;
MemberKey: string;
Primary: number;
SignedKeyList: SignedKeyList;
}
interface CreateMemberKeyPayloadV2 extends Omit<CreateMemberKeyPayload, 'UserKey' | 'MemberKey' | 'Activation'> {
Signature: string;
OrgSignature: string;
PrivateKey: string;
}
export const createMemberKeyRoute = ({ MemberID, ...data }: CreateMemberKeyPayload | CreateMemberKeyPayloadV2) => ({
url: `members/${MemberID}/keys`,
method: 'post',
data,
});
export interface MigrateMemberAddressKeyPayload {
ID: string;
Token: string;
Signature: string;
OrgSignature: string;
PrivateKey: string;
}
interface MigrateMemberAddressKeysPayload {
MemberID: string;
AddressKeys: MigrateMemberAddressKeyPayload[];
SignedKeyLists: { [key: string]: SignedKeyList };
}
export const migrateMembersAddressKeysRoute = ({ MemberID, ...data }: MigrateMemberAddressKeysPayload) => ({
url: `members/${MemberID}/keys/migrate`,
method: 'post',
data,
});
| 8,236 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/memberSessions.js | export const createSession = (memberID, data) => ({
method: 'post',
url: `members/${memberID}/sessions`,
data,
});
export const getSessions = (memberID) => ({
method: 'get',
url: `members/${memberID}/sessions`,
});
export const revokeSession = (memberID, uid) => ({
method: 'delete',
url: `members/${memberID}/sessions/${uid}`,
});
export const revokeSessions = (memberID) => ({
method: 'delete',
url: `members/${memberID}/sessions`,
});
| 8,237 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/members.ts | import { Address, Api, Member, SignedKeyList } from '../interfaces';
import queryPages from './helpers/queryPages';
import { PaginationParams } from './interface';
export const queryMembers = (params?: PaginationParams) => ({
method: 'get',
url: 'core/v4/members',
params: {
...params,
IncludeAddresses: 1,
},
});
export const getAllMembers = (api: Api) => {
return queryPages((Page, PageSize) => {
return api<{ Members: Member[]; Total: number }>(
queryMembers({
Page,
PageSize,
})
);
}).then((pages) => {
return pages.flatMap(({ Members }) => Members);
});
};
export const getMember = (memberID: string) => ({
method: 'get',
url: `core/v4/members/${memberID}`,
});
export const queryAddresses = (memberID: string, params?: PaginationParams) => ({
method: 'get',
url: `core/v4/members/${memberID}/addresses`,
params,
});
export const getAllMemberAddresses = (api: Api, memberID: string) => {
return queryPages((page, pageSize) => {
return api<{ Addresses: Address[]; Total: number }>(
queryAddresses(memberID, {
Page: page,
PageSize: pageSize,
})
);
}).then((pages) => {
return pages.flatMap(({ Addresses = [] }) => Addresses);
});
};
export const createMember = (data: { Name: string; Private: number; MaxSpace: number; MaxVPN: number }) => ({
method: 'post',
url: 'core/v4/members',
data,
});
export const checkMemberAddressAvailability = (data: { Local: string; Domain: string }) => ({
method: 'post',
url: `core/v4/members/addresses/available`,
data,
});
export const createMemberAddress = (memberID: string, data: { Local: string; Domain: string }) => ({
method: 'post',
url: `core/v4/members/${memberID}/addresses`,
data,
});
export const updateName = (memberID: string, Name: string) => ({
method: 'put',
url: `core/v4/members/${memberID}/name`,
data: { Name },
});
export const updateQuota = (memberID: string, MaxSpace: number) => ({
method: 'put',
url: `core/v4/members/${memberID}/quota`,
data: { MaxSpace },
});
export const updateRole = (memberID: string, Role: number) => ({
method: 'put',
url: `core/v4/members/${memberID}/role`,
data: { Role },
});
export const updateVPN = (memberID: string, MaxVPN: number) => ({
method: 'put',
url: `core/v4/members/${memberID}/vpn`,
data: { MaxVPN },
});
export const removeMember = (memberID: string) => ({
method: 'delete',
url: `core/v4/members/${memberID}`,
});
export const privatizeMember = (memberID: string) => ({
method: 'put',
url: `core/v4/members/${memberID}/privatize`,
});
export const authMember = (memberID: string, data: { Unlock?: boolean } = {}) => ({
method: 'post',
url: `core/v4/members/${memberID}/auth`,
data,
});
export const inviteMember = (email: string, maxSpace: number) => ({
url: `core/v4/members/invitations`,
method: 'post',
data: {
Email: email,
MaxSpace: maxSpace,
},
});
export const deleteMember = (memberId: string) => ({
url: `core/v4/members/${memberId}`,
method: 'delete',
});
export const editMemberInvitation = (memberID: string, maxSpace: number) => ({
method: 'put',
url: `core/v4/members/invitations/${memberID}`,
data: {
MaxSpace: maxSpace,
},
});
export const updateAddressFlags = (
addressID: string,
Encrypt: boolean,
Sign: boolean,
SignedKeyList: SignedKeyList
) => ({
method: 'put',
url: `core/v4/addresses/${addressID}/encryption`,
data: {
Encrypt: Encrypt ? 1 : 0,
Sign: Sign ? 1 : 0,
SignedKeyList,
},
});
| 8,238 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/messages.ts | import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings';
import { SimpleMap } from '../interfaces';
import { Message } from '../interfaces/mail/Message';
import { PackageDirect } from '../interfaces/mail/crypto';
import { CREATE_DRAFT_MESSAGE_ACTION, SEND_MESSAGE_DIRECT_ACTION } from '../interfaces/message';
import { getAppropriateSort } from './helpers/snoozeSort';
type BaseMessage = Pick<
Message,
'ToList' | 'CCList' | 'BCCList' | 'Subject' | 'Sender' | 'Body' | 'MIMEType' | 'Attachments' | 'Flags'
>;
interface QueryMessageMetadataParams {
Location?: string;
Page?: number;
PageSize?: number;
Limit?: number;
LabelID?: string | string[];
Sort?: string;
Desc?: number;
Begin?: number;
End?: number;
BeginID?: string;
EndID?: string;
Keyword?: string;
To?: string;
From?: string;
Subject?: string;
Attachments?: number;
Starred?: number;
Unread?: number;
AddressID?: string;
ID?: string;
AutoWildcard?: number;
}
export const queryMessageMetadata = ({
Location,
Page,
PageSize,
Limit,
LabelID,
Sort = 'Time',
Desc = 1,
Begin,
End,
BeginID,
EndID,
Keyword,
To,
From,
Subject,
Attachments,
Starred,
Unread,
AddressID,
ID,
AutoWildcard,
}: QueryMessageMetadataParams) => ({
method: 'get',
url: 'mail/v4/messages',
params: {
Location,
Page,
PageSize,
Limit,
LabelID,
Sort: getAppropriateSort(LabelID, Sort),
Desc,
Begin,
End,
BeginID,
EndID,
Keyword,
Recipients: To,
From,
Subject,
Attachments,
Starred,
Unread,
AddressID,
ID,
AutoWildcard,
},
});
export const queryMessageCount = (AddressID: string) => ({
method: 'get',
url: 'mail/v4/messages/count',
params: { AddressID },
});
export const getMessage = (messageID: string) => ({
method: 'get',
url: `mail/v4/messages/${messageID}`,
});
interface SendMessageData {
AutoSaveContacts: number;
DelaySeconds?: number;
DeliveryTime?: number;
ExpirationTime?: number;
ExpiresIn?: number;
Packages: PackageDirect[];
}
export const sendMessage = (
messageID: string,
{ ExpirationTime, ExpiresIn, AutoSaveContacts, Packages, DelaySeconds = 0, DeliveryTime }: SendMessageData
) => ({
method: 'post',
url: `mail/v4/messages/${messageID}`,
data: { ExpirationTime, ExpiresIn, AutoSaveContacts, Packages, DelaySeconds, DeliveryTime },
});
export const sendMessageForm = (messageID: string, data: any, sendingFrom?: string) => ({
method: 'post',
url: `mail/v4/messages/${messageID}`,
input: 'form',
data,
params: {
Source: sendingFrom,
},
});
interface SendMessageDirectData {
Message: BaseMessage;
ParentID?: number;
Action?: SEND_MESSAGE_DIRECT_ACTION;
AttachmentKeys: SimpleMap<string>;
ExpirationTime?: number;
ExpiresIn?: number;
AutoSaveContacts: number;
Packages: PackageDirect[];
}
export const sendMessageDirect = ({
Message,
ParentID,
Action,
AttachmentKeys,
ExpirationTime,
ExpiresIn,
AutoSaveContacts,
Packages,
}: SendMessageDirectData) => ({
method: 'post',
url: `mail/v4/messages/send/direct`,
data: { Message, ParentID, Action, AttachmentKeys, ExpirationTime, ExpiresIn, AutoSaveContacts, Packages },
});
interface UpdateDraftData {
Message: BaseMessage;
AttachmentKeyPackets: SimpleMap<string>;
}
interface CreateDraftData extends UpdateDraftData {
ParentID?: string;
Action?: CREATE_DRAFT_MESSAGE_ACTION;
}
export const createDraft = ({ Message, ParentID, Action, AttachmentKeyPackets }: CreateDraftData) => ({
method: 'post',
url: 'mail/v4/messages',
data: { Message, ParentID, Action, AttachmentKeyPackets },
});
export const updateDraft = (messageID: string, { Message, AttachmentKeyPackets }: UpdateDraftData) => ({
method: 'put',
url: `mail/v4/messages/${messageID}`,
data: { Message, AttachmentKeyPackets },
});
export const updateBody = (messageID: string, data: { Body: string }) => ({
method: 'post',
url: `mail/v4/messages/${messageID}/body`,
data,
});
export const markAsBroken = (messageID: string) => ({
method: 'put',
url: `mail/v4/messages/${messageID}/mark/broken`,
});
export const readReceipt = (messageID: string) => ({
method: 'post',
url: `mail/v4/messages/${messageID}/receipt`,
});
export const markAsHam = (messageID: string) => ({
method: 'put',
url: `mail/v4/messages/${messageID}/mark/ham`,
});
export const oneClickUnsubscribe = (ID: string) => ({
method: 'post',
url: `mail/v4/messages/${ID}/unsubscribe`,
});
export const markAsUnsubscribed = (IDs: string[]) => ({
method: 'put',
url: `mail/v4/messages/mark/unsubscribed`,
data: { IDs },
});
export const markMessageAsRead = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/messages/read',
data: { IDs },
});
export const markMessageAsUnread = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/messages/unread',
data: { IDs },
});
export const deleteMessages = (IDs: string[], CurrentLabelID?: string) => ({
method: 'put',
url: 'mail/v4/messages/delete',
data: { IDs, CurrentLabelID },
});
export const undeleteMessages = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/messages/undelete',
data: { IDs },
});
export const labelMessages = ({
LabelID,
IDs,
SpamAction,
}: {
LabelID: string;
IDs: string[];
SpamAction?: SPAM_ACTION;
}) => ({
method: 'put',
url: 'mail/v4/messages/label',
data: { LabelID, IDs, SpamAction },
});
export const unlabelMessages = ({ LabelID, IDs }: { LabelID: string; IDs: string[] }) => ({
method: 'put',
url: 'mail/v4/messages/unlabel',
data: { LabelID, IDs },
});
export const emptyLabel = ({ LabelID, AddressID }: { LabelID: string; AddressID: string | undefined }) => ({
method: 'delete',
url: 'mail/v4/messages/empty',
params: { LabelID, AddressID },
});
export const moveAll = ({
SourceLabelID,
DestinationLabelID,
KeepSourceLabel = 1,
}: {
SourceLabelID: string;
DestinationLabelID: string;
KeepSourceLabel?: number;
}) => ({
method: 'put',
url: 'mail/v4/messages/move',
data: { SourceLabelID, DestinationLabelID, KeepSourceLabel },
});
export const cancelSend = (messageID: string) => ({
method: 'post',
url: `mail/v4/messages/${messageID}/cancel_send`,
});
export const forceSend = (messageID: string) => ({
method: 'post',
url: `mail/v4/messages/${messageID}/force_send`,
});
export const unsubscribeMessages = (IDs: string[]) => ({
method: 'post',
url: 'mail/v4/messages/unsubscribe',
data: { IDs },
});
export const setExpiration = (IDs: string[], ExpirationTime: number | null) => ({
method: 'put',
url: 'mail/v4/messages/expire',
data: { IDs, ExpirationTime },
});
| 8,239 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/metrics.ts | import { METRICS_LOG } from '../constants';
interface SendMetricsReportPayload {
Log: METRICS_LOG;
Title?: string;
Data?: any;
}
export const metrics = ({ Log, Title, Data }: SendMetricsReportPayload) => ({
method: 'post',
url: 'metrics',
data: { Log, Title, Data },
});
| 8,240 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/oauth.ts | export const getOAuthLastAccess = (ClientID: string) => ({
method: 'get',
url: `oauth/v1/last_access`,
params: {
ClientID,
},
});
export interface OAuthLastAccess {
Accepted: boolean;
LastAccess: number | null;
AcceptanceTime: number | null;
}
export const getOAuthClientInfo = (clientID: string) => ({
method: 'get',
url: `oauth/v1/client/${clientID}`,
});
export interface OAuthClientInfo {
ClientID: string;
Name: string;
Logo: string;
ModifyTime: number;
CreateTime: number;
}
export interface OAuthForkResponse {
Code: string;
RedirectUri: string;
}
export const postOAuthFork = (data: { ClientID: string; OaSession: string }) => ({
method: 'post',
url: 'oauth/v1/fork',
data,
});
| 8,241 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/orgIncomingDefaults.ts | export const getOrgIncomingDefaults = ({
Location,
Page,
PageSize,
Keyword,
}: {
Location?: number;
Page?: number;
PageSize?: number;
Keyword?: string;
} = {}) => ({
method: 'get',
url: 'mail/v4/orgincomingdefaults',
params: { Location, Page, PageSize, Keyword },
});
interface OrgIncomingDefaultConfig {
Email?: string;
Domain?: string;
Location: number;
}
interface AddOrgIncomingDefaultConfig extends OrgIncomingDefaultConfig {
/**
* If email is already registered in orgIncomingDefaults we overwrite the location
* Avoids to find the already exiting item ID
*/
Overwrite?: boolean;
}
export const addOrgIncomingDefault = ({ Email, Domain, Location, Overwrite }: AddOrgIncomingDefaultConfig) => {
let url = 'mail/v4/orgincomingdefaults';
if (Overwrite) {
url = `${url}?Overwrite=1`;
}
return {
method: 'post',
url,
data: { Email, Domain, Location },
};
};
export const updateOrgIncomingDefault = (
orgIncomingDefaultID: string,
{ Email, Domain, Location }: OrgIncomingDefaultConfig
) => ({
method: 'put',
url: `mail/v4/orgincomingdefaults/${orgIncomingDefaultID}`,
data: { Email, Domain, Location },
});
export const deleteOrgIncomingDefaults = (IDs: string[]) => ({
method: 'put',
url: 'mail/v4/orgincomingdefaults/delete',
data: { IDs },
});
export const clearOrgIncomingDefaults = () => ({
method: 'delete',
url: 'mail/v4/orgincomingdefaults',
});
| 8,242 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/organization.ts | export const getOrganization = () => ({
url: 'core/v4/organizations',
method: 'get',
});
export const getOrganizationKeys = () => ({
url: 'core/v4/organizations/keys',
method: 'get',
});
export const getOrganizationBackupKeys = () => ({
url: 'core/v4/organizations/keys/backup',
method: 'get',
});
export const updateOrganizationName = (Name: string) => ({
url: 'core/v4/organizations/name',
method: 'put',
data: { Name },
});
export const updateOrganizationEmail = (Email: string) => ({
url: 'core/v4/organizations/email',
method: 'put',
data: { Email },
});
export const updateOrganizationTheme = (Theme: string) => ({
url: 'core/v4/organizations/theme',
method: 'put',
data: { Theme },
});
export const updateTwoFactor = (GracePeriod: number) => ({
url: 'core/v4/organizations/2fa',
method: 'put',
data: { GracePeriod },
});
export interface UpdateOrganizationKeysPayloadLegacy {
PrivateKey: string;
BackupPrivateKey: string;
BackupKeySalt: string;
Tokens: { ID: string; Token: string }[];
}
export const updateOrganizationKeysLegacy = ({
PrivateKey,
BackupPrivateKey,
BackupKeySalt,
Tokens,
}: UpdateOrganizationKeysPayloadLegacy) => ({
url: 'core/v4/organizations/keys',
method: 'post',
data: { PrivateKey, BackupPrivateKey, BackupKeySalt, Tokens },
});
export interface UpdateOrganizationKeysPayloadV2 {
PrivateKey: string;
BackupPrivateKey: string;
BackupKeySalt: string;
Members: {
ID: string;
UserKeyTokens: {
ID: string;
Token: string;
}[];
AddressKeyTokens: {
ID: string;
Token: string;
Signature: string;
OrgSignature: string;
}[];
}[];
}
export const updateOrganizationKeysV2 = ({
PrivateKey,
BackupPrivateKey,
BackupKeySalt,
Members,
}: UpdateOrganizationKeysPayloadV2) => ({
url: 'core/v4/organizations/keys',
method: 'post',
data: { PrivateKey, BackupPrivateKey, BackupKeySalt, Members },
});
export const updateBackupKey = ({ PrivateKey, KeySalt }: { PrivateKey: string; KeySalt: string }) => ({
url: 'core/v4/organizations/keys/backup',
method: 'post',
data: { PrivateKey, KeySalt },
});
export const activateOrganizationKey = (PrivateKey: string) => ({
url: 'core/v4/organizations/keys/activate',
method: 'put',
data: { PrivateKey },
});
export const leaveOrganisation = () => ({
url: 'core/v4/organizations/membership',
method: 'delete',
});
export const queryEnforceTwoFA = (Require: number) => ({
url: `core/v4/organizations/require2fa`,
method: 'put',
data: { Require },
});
export const queryRemoveTwoFA = () => ({
url: `core/v4/organizations/require2fa`,
method: 'delete',
});
export const sendEmailReminderTwoFA = () => ({
url: 'core/v4/organizations/2fa/remind',
method: 'post',
});
| 8,243 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/payments.ts | import { PlanIDs } from 'proton-account/src/app/signup/interfaces';
import { Autopay, WrappedCryptoPayment } from '@proton/components/payments/core';
import {
AmountAndCurrency,
ChargeablePaymentParameters,
ExistingPayment,
TokenPayment,
TokenPaymentMethod,
WrappedCardPayment,
WrappedPaypalPayment,
} from '@proton/components/payments/core/interface';
import { INVOICE_OWNER, INVOICE_STATE, INVOICE_TYPE } from '@proton/shared/lib/constants';
import { ProductParam, getProductHeaders } from '../apps/product';
import { Currency, Cycle, Renew } from '../interfaces';
export const getSubscription = () => ({
url: 'payments/v4/subscription',
method: 'get',
});
export interface FeedbackDowngradeData {
Reason?: string;
Feedback?: string;
ReasonDetails?: string;
Context?: 'vpn' | 'mail';
}
export const deleteSubscription = (data: FeedbackDowngradeData) => ({
url: 'payments/v4/subscription',
method: 'delete',
data,
});
export type CheckSubscriptionData = {
Plans: PlanIDs;
Currency: Currency;
Cycle: Cycle;
CouponCode?: string;
Codes?: string[];
};
export const checkSubscription = (data: CheckSubscriptionData) => ({
url: 'payments/v4/subscription/check',
method: 'post',
data,
});
export type SubscribeData = {
Plans: PlanIDs;
Currency: Currency;
Cycle: Cycle;
Codes?: string[];
} & (TokenPaymentMethod | WrappedCardPayment | ExistingPayment | {}) &
AmountAndCurrency;
export const subscribe = (data: SubscribeData, product: ProductParam) => ({
url: 'payments/v4/subscription',
method: 'post',
data,
headers: getProductHeaders(product, {
endpoint: 'payments/v4/subscription',
product,
}),
});
export interface QueryInvoicesParams {
/**
* Starts with 0
*/
Page: number;
PageSize: number;
Owner: INVOICE_OWNER;
State?: INVOICE_STATE;
Type?: INVOICE_TYPE;
}
/**
* Query list of invoices for the current user. The response is {@link InvoiceResponse}
*/
export const queryInvoices = ({ Page, PageSize, Owner, State, Type }: QueryInvoicesParams) => ({
url: 'payments/v4/invoices',
method: 'get',
params: { Page, PageSize, Owner, State, Type },
});
export interface QueryPlansParams {
Currency?: Currency;
}
export const queryPlans = (params?: QueryPlansParams) => ({
url: 'payments/v4/plans',
method: 'get',
params,
});
export const getInvoice = (invoiceID: string) => ({
url: `payments/v4/invoices/${invoiceID}`,
method: 'get',
output: 'arrayBuffer',
});
export const checkInvoice = (invoiceID: string, GiftCode?: string) => ({
url: `payments/v4/invoices/${invoiceID}/check`,
method: 'put',
data: { GiftCode },
});
export const queryPaymentMethods = () => ({
url: 'payments/v4/methods',
method: 'get',
});
export type SetPaymentMethodData = TokenPayment & { Autopay?: Autopay };
export const setPaymentMethod = (data: SetPaymentMethodData) => ({
url: 'payments/v4/methods',
method: 'post',
data,
});
export interface UpdatePaymentMethodsData {
Autopay: Autopay;
}
export const updatePaymentMethod = (methodId: string, data: UpdatePaymentMethodsData) => ({
url: `payments/v4/methods/${methodId}`,
method: 'put',
data,
});
export const deletePaymentMethod = (methodID: string) => ({
url: `payments/v4/methods/${methodID}`,
method: 'delete',
});
export const createBitcoinPayment = (Amount: number, Currency: Currency) => ({
url: 'payments/bitcoin', // blocked by PAY-963
method: 'post',
data: { Amount, Currency },
});
export const createBitcoinDonation = (Amount: number, Currency: Currency) => ({
url: 'payments/bitcoin/donate', // blocked by PAY-963
method: 'post',
data: { Amount, Currency },
});
/**
* @param invoiceID
* @param data – does not have to include the payment token if user pays from the credits balance. In this case Amount
* must be set to 0 and payment token must not be supplied.
*/
export const payInvoice = (invoiceID: string, data: (TokenPaymentMethod & AmountAndCurrency) | AmountAndCurrency) => ({
url: `payments/v4/invoices/${invoiceID}`,
method: 'post',
data,
});
export const queryPaymentMethodStatus = () => ({
url: 'payments/v4/status',
method: 'get',
});
export const orderPaymentMethods = (PaymentMethodIDs: string[]) => ({
url: 'payments/v4/methods/order',
method: 'put',
data: { PaymentMethodIDs },
});
export interface GiftCodeData {
GiftCode: string;
Amount: number;
}
export const buyCredit = (
data: (TokenPaymentMethod & AmountAndCurrency) | GiftCodeData | ChargeablePaymentParameters
) => ({
url: 'payments/v4/credit',
method: 'post',
data,
});
export interface ValidateCreditData {
GiftCode: string;
}
export const validateCredit = (data: ValidateCreditData) => ({
url: 'payments/v4/credit/check',
method: 'post',
data,
});
export type CreateBitcoinTokenData = AmountAndCurrency & WrappedCryptoPayment;
export type CreateTokenData =
| ((AmountAndCurrency | {}) & (WrappedPaypalPayment | WrappedCardPayment | ExistingPayment))
| CreateBitcoinTokenData;
export const createToken = (data: CreateTokenData) => ({
url: 'payments/v4/tokens',
method: 'post',
data,
});
export const getTokenStatus = (paymentToken: string) => ({
url: `payments/v4/tokens/${paymentToken}`,
method: 'get',
});
export const getLastCancelledSubscription = () => ({
url: 'payments/v4/subscription/latest',
method: 'get',
});
export type RenewalStateData =
| {
RenewalState: Renew.Enabled;
}
| {
RenewalState: Renew.Disabled;
CancellationFeedback: FeedbackDowngradeData;
};
export const changeRenewState = (data: RenewalStateData) => ({
url: 'payments/v4/subscription/renew',
method: 'put',
data,
});
| 8,244 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/reports.ts | import { CLIENT_TYPES } from '@proton/shared/lib/constants';
export interface BugPayload {
ClientType: CLIENT_TYPES;
Client: string;
ClientVersion: string;
Title: string;
Description: string;
Email: string;
Username: string;
OS: string;
OSVersion: string;
Browser: string | undefined;
BrowserVersion: string | undefined;
Resolution: string;
DeviceName: string | undefined;
DeviceModel: string | undefined;
}
export const reportBug = (data: BugPayload, input?: 'form') => ({
method: 'post',
url: 'reports/bug',
input,
data,
});
interface PhishingPayload {
MessageID?: string;
MIMEType: 'text/plain' | 'text/html';
Body?: string;
}
export const reportPhishing = ({ MessageID, MIMEType, Body }: PhishingPayload) => ({
method: 'post',
url: 'reports/phishing',
data: { MessageID, MIMEType, Body },
});
interface CancelPlanPayload {
Reason: string;
Message: string;
Email: string;
OS: string;
OSVersion: string;
Browser: string | undefined;
BrowserVersion: string | undefined;
Client: string;
ClientVersion: string;
ClientType: CLIENT_TYPES;
Tags: string[];
}
export const reportCancelPlan = (data: CancelPlanPayload) => ({
method: 'post',
url: 'core/v4/reports/cancel-plan',
data,
});
| 8,245 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/reset.ts | type RequestUsernamePayload =
| {
Email: string;
}
| {
Phone: string;
};
export const requestUsername = (data: RequestUsernamePayload) => ({
url: 'core/v4/reset/username',
method: 'post',
data,
});
export const validateResetToken = (username: string, token: string) => ({
url: `core/v4/reset/${username}/${token}`,
method: 'get',
});
export const requestLoginResetToken = (data: { Username: string; Email?: string; Phone?: string }) => ({
url: 'core/v4/reset',
method: 'post',
data,
});
| 8,246 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/sessionRecovery.ts | export const initiateSessionRecovery = () => ({
url: 'account/v1/recovery/session',
method: 'POST',
});
export const abortSessionRecovery = () => ({
url: 'account/v1/recovery/session/abort',
method: 'POST',
});
export const consumeSessionRecovery = (data: {
UserKeys: {
ID: string;
PrivateKey: string;
}[];
KeySalt: string;
OrganizationKey?: string;
}) => ({
url: 'account/v1/recovery/session/consume',
method: 'POST',
data,
});
export const updateSessionAccountRecovery = (data: { SessionAccountRecovery: 0 | 1 }) => ({
url: 'core/v4/settings/sessionaccountrecovery',
method: 'PUT',
data,
});
| 8,247 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/settings.ts | import { DENSITY, NEWSLETTER_SUBSCRIPTIONS } from '@proton/shared/lib/constants';
import {
DRAWER_VISIBILITY,
SETTINGS_DATE_FORMAT,
SETTINGS_LOG_AUTH_STATE,
SETTINGS_TIME_FORMAT,
SETTINGS_WEEK_START,
} from '@proton/shared/lib/interfaces';
import { ThemeSetting, ThemeTypes } from '@proton/shared/lib/themes/themes';
import { RegistrationOptions } from '../../lib/webauthn/interface';
export const TOTP_WRONG_ERROR = 12060;
export const getSettings = () => ({
url: 'core/v4/settings',
method: 'get',
});
export const updateUsername = (data: { Username: string }) => ({
url: 'core/v4/settings/username',
method: 'put',
data,
});
export const updatePassword = () => ({
url: 'core/v4/settings/password',
method: 'put',
});
export const upgradePassword = () => ({
url: 'core/v4/settings/password/upgrade',
method: 'put',
});
export const updateLocale = (Locale: string) => ({
url: 'core/v4/settings/locale',
method: 'put',
data: { Locale },
});
export const getNews = () => ({
url: 'core/v4/settings/news',
method: 'get',
});
export const patchNews = (data: Partial<Record<NEWSLETTER_SUBSCRIPTIONS, boolean>>) => ({
url: 'core/v4/settings/news',
method: 'PATCH',
data,
});
export const getNewsExternal = () => ({
url: 'core/v4/settings/news/external',
method: 'get',
});
export const patchNewsExternal = (data: Partial<Record<NEWSLETTER_SUBSCRIPTIONS, boolean>>) => ({
url: 'core/v4/settings/news/external',
method: 'PATCH',
data,
});
export const updateInvoiceText = (InvoiceText: string) => ({
url: 'core/v4/settings/invoicetext',
method: 'put',
data: { InvoiceText },
});
export const updateLogAuth = (LogAuth: SETTINGS_LOG_AUTH_STATE) => ({
url: 'core/v4/settings/logauth',
method: 'put',
data: { LogAuth },
});
export const enableHighSecurity = () => ({
url: 'core/v4/settings/highsecurity',
method: 'post',
data: {},
});
export const disableHighSecurity = () => ({
url: 'core/v4/settings/highsecurity',
method: 'delete',
data: {},
});
export const updateDensity = (Density: DENSITY) => ({
url: 'core/v4/settings/density',
method: 'put',
data: { Density },
});
export const updateEmail = (data: { Email: string }) => ({
url: 'core/v4/settings/email',
method: 'put',
data,
});
export const updateNotifyEmail = (Notify: number) => ({
url: 'core/v4/settings/email/notify',
method: 'put',
data: { Notify },
});
export const updateResetEmail = (Reset: number) => ({
url: 'core/v4/settings/email/reset',
method: 'put',
data: { Reset },
});
export const verifyEmail = (Token: string) => ({
url: 'core/v4/settings/email/verify',
method: 'post',
data: { Token },
});
export const updatePhone = (data: { Phone: string }) => ({
url: 'core/v4/settings/phone',
method: 'put',
data,
});
export const updateNotifyPhone = (Notify: string) => ({
url: 'core/v4/settings/phone/notify',
method: 'put',
data: { Notify },
});
export const updateResetPhone = (data: { Reset: number }) => ({
url: 'core/v4/settings/phone/reset',
method: 'put',
data,
});
export const verifyPhone = (Token: string) => ({
url: 'core/v4/settings/phone/verify',
method: 'post',
data: { Token },
});
export const registerSecurityKey = (data: {
RegistrationOptions: RegistrationOptions;
ClientData: string;
AttestationObject: string;
Transports: string[];
Name: string;
}) => ({
url: 'core/v4/settings/2fa/register',
method: 'post',
data,
});
export const getSecurityKeyChallenge = (crossPlatform: boolean) => ({
url: 'core/v4/settings/2fa/register',
method: 'get',
params: {
CrossPlatform: +crossPlatform,
},
});
export const removeSecurityKey = (credentialID: string) => ({
url: `core/v4/settings/2fa/${credentialID}/remove`,
method: 'post',
});
export const renameSecurityKey = (credentialID: string, data: { Name: string }) => ({
url: `core/v4/settings/2fa/${credentialID}/rename`,
method: 'put',
data,
});
export const setupTotp = (TOTPSharedSecret: string, TOTPConfirmation: string) => ({
url: 'core/v4/settings/2fa/totp',
method: 'post',
data: { TOTPSharedSecret, TOTPConfirmation },
});
export const disableTotp = () => ({
url: 'core/v4/settings/2fa/totp',
method: 'put',
});
export const disable2FA = () => ({
url: 'core/v4/settings/2fa',
method: 'put',
});
export const updateHideDrawer = (HideSidePanel: DRAWER_VISIBILITY) => ({
url: 'core/v4/settings/hide-side-panel',
method: 'put',
data: { HideSidePanel },
});
export const updateTheme = (data: ThemeSetting) => ({
url: 'core/v4/settings/theme',
method: 'put',
data,
});
export const updateThemeType = (ThemeType: ThemeTypes) => ({
url: 'core/v4/settings/themetype',
method: 'put',
data: { ThemeType },
});
export const updateWeekStart = (WeekStart: SETTINGS_WEEK_START) => ({
url: 'core/v4/settings/weekstart',
method: 'put',
data: { WeekStart },
});
export const updateDateFormat = (DateFormat: SETTINGS_DATE_FORMAT) => ({
url: 'core/v4/settings/dateformat',
method: 'put',
data: { DateFormat },
});
export const updateTimeFormat = (TimeFormat: SETTINGS_TIME_FORMAT) => ({
url: 'core/v4/settings/timeformat',
method: 'put',
data: { TimeFormat },
});
export const updateWelcomeFlags = () => ({
url: 'core/v4/settings/welcome',
method: 'put',
});
export const updateEarlyAccess = (data: { EarlyAccess: number }) => ({
url: 'core/v4/settings/earlyaccess',
method: 'put',
data,
});
export const updateFlags = (data: { Welcomed: number }) => ({
url: 'core/v4/settings/flags',
method: 'put',
data,
});
export const updateTelemetry = (data: { Telemetry: number }) => ({
url: 'core/v4/settings/telemetry',
method: 'put',
data,
});
export const updateCrashReports = (data: { CrashReports: number }) => ({
url: 'core/v4/settings/crashreports',
method: 'put',
data,
});
| 8,248 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/settingsMnemonic.ts | import { MNEMONIC_STATUS } from '../interfaces';
export interface MnemonicKeyResponse {
ID: string;
PrivateKey: string;
Salt: string;
}
export const getMnemonicUserKeys = () => ({
url: 'core/v4/settings/mnemonic',
method: 'get',
});
interface UpdateMnemonicPhrasePayload {
MnemonicUserKeys: {
ID: string;
PrivateKey: string;
}[];
MnemonicSalt: string;
MnemonicAuth: {
Version: number;
ModulusID: string;
Salt: string;
Verifier: string;
};
}
export const updateMnemonicPhrase = (data: UpdateMnemonicPhrasePayload) => ({
url: 'core/v4/settings/mnemonic',
method: 'put',
data,
});
export const reactivateMnemonicPhrase = (data: UpdateMnemonicPhrasePayload) => ({
url: 'core/v4/settings/mnemonic/reactivate',
method: 'put',
data,
});
export const disableMnemonicPhrase = () => ({
url: 'core/v4/settings/mnemonic/disable',
method: 'post',
});
export interface GetMnemonicResetData {
MnemonicStatus: MNEMONIC_STATUS;
MnemonicUserKeys: {
ID: string;
PrivateKey: string;
Salt: string;
}[];
}
export const getMnemonicReset = () => ({
url: 'core/v4/settings/mnemonic/reset',
method: 'get',
});
interface MnemonicResetPayload {
UserKeys: {
ID: string;
PrivateKey: string;
}[];
KeysSalt: string;
}
export const mnemonicReset = (data: MnemonicResetPayload) => ({
url: 'core/v4/settings/mnemonic/reset',
method: 'post',
data,
});
| 8,249 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/settingsRecovery.ts | interface NewRecoverySecretPayload {
RecoverySecret: string;
Signature: string;
}
export const setNewRecoverySecret = (data: NewRecoverySecretPayload) => ({
url: 'core/v4/settings/recovery/secret',
method: 'post',
data,
});
export const deleteRecoverySecrets = () => ({
url: 'core/v4/settings/recovery/secret',
method: 'delete',
});
export const updateDeviceRecovery = (data: { DeviceRecovery: number }) => ({
url: 'core/v4/settings/devicerecovery',
method: 'PUT',
data,
});
| 8,250 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/simpleLogin.ts | export const getSLAccountLinked = () => ({
method: 'get',
url: 'simple_login/v1/user',
});
export const getSLSubscription = () => ({
method: 'get',
url: 'simple_login/v1/subscription',
});
export const createSLUser = (Redirect?: 'browser_extension' | 'home') => ({
method: 'post',
url: 'simple_login/v1/user',
data: { Redirect },
});
| 8,251 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/smtptokens.ts | export const createToken = (AddressID: string, Name: string) => ({
method: 'post',
url: 'mail/v4/smtptokens',
data: {
AddressID,
Name,
},
});
export const deleteToken = (tokenID: string) => ({
method: 'delete',
url: `mail/v4/smtptokens/${tokenID}`,
});
export const getTokens = () => ({
method: 'get',
url: 'mail/v4/smtptokens',
});
export const isTokenEligible = () => ({
method: 'get',
url: 'mail/v4/smtptokens/eligible',
});
| 8,252 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/telemetry.ts | import { SimpleMap } from '@proton/shared/lib/interfaces';
export enum TelemetryMeasurementGroups {
mailSimpleLogin = 'mail.web.simplelogin_popups',
calendarTimeZoneSelector = 'calendar.web.timezone_selector',
calendarEncryptedSearch = 'calendar.web.encrypted_search',
accountSignupBasic = 'account.any.signup_basic',
accountSignup = 'account.any.signup',
keyTransparency = 'any.web.key_transparency',
mailPrivacyDropdown = 'mail.web.privacy_dropdown',
mailSelectAll = 'mail.web.select_all',
}
export enum TelemetrySimpleLoginEvents {
spam_view = 'spam_view',
newsletter_unsubscribe = 'newsletter_unsubscribe',
simplelogin_modal_view = 'simplelogin_modal_view',
go_to_simplelogin = 'go_to_simplelogin',
}
export enum TelemetryCalendarEvents {
change_temporary_time_zone = 'change_temporary_time_zone',
enable_encrypted_search = 'enable_encrypted_search',
}
export enum TelemetryAccountSignupBasicEvents {
flow_started = 'flow_started',
account_created = 'account_created',
}
export enum TelemetryAccountSignupEvents {
pageLoad = 'fe.page_load',
planSelect = 'user.plan_select',
cycleSelect = 'user.cycle_select',
currencySelect = 'user.currency_select',
paymentSelect = 'user.payment_select',
userCheckout = 'user.checkout',
userSignIn = 'user.sign_in',
interactAccountCreate = 'user.interact.account_create',
interactUpsell = 'user.interact.upsell',
interactCreditCard = 'user.interact.credit_card',
interactPassword = 'user.interact.password',
interactRecoveryKit = 'user.interact.recovery',
interactDownload = 'user.interact.download',
beAvailableExternal = 'be.available_external',
beSignInSuccess = 'be.sign_in_success',
beSignOutSuccess = 'be.sign_out_success',
bePaymentMethods = 'be.payments_available',
checkoutError = 'be.checkout_error',
hvNeeded = 'be.hv_needed',
loadPaymentBtc = 'fe.load_payment_btc',
onboardingStart = 'fe.onboarding_start',
onboardShown = 'fe.onboarding_shown',
onboardFinish = 'fe.onboarding_finish',
signupFinish = 'fe.signup_finish',
}
export enum TelemetryKeyTransparencyErrorEvents {
self_audit_error = 'self_audit_error',
key_verification_failure = 'key_verification_failure',
}
export enum TelemetryMailEvents {
privacy_dropdown_opened = 'privacy_dropdown_opened',
}
export enum TelemetryMailSelectAllEvents {
notification_move_to = 'notification_move_to',
// The rest will be used soon with the new Select all feature
banner_move_to = 'banner_move_to',
banner_label_as = 'banner_label_as',
banner_mark_as_read = 'banner_mark_as_read',
banner_mark_as_unread = 'banner_mark_as_unread',
}
export type TelemetryEvents =
| TelemetrySimpleLoginEvents
| TelemetryCalendarEvents
| TelemetryAccountSignupBasicEvents
| TelemetryAccountSignupEvents
| TelemetryKeyTransparencyErrorEvents
| TelemetryMailEvents
| TelemetryMailSelectAllEvents;
export interface TelemetryReport {
measurementGroup: TelemetryMeasurementGroups;
event: TelemetryEvents;
values?: SimpleMap<number>;
dimensions?: SimpleMap<string>;
}
export const sendTelemetryData = (data: {
MeasurementGroup: TelemetryMeasurementGroups;
Event: TelemetryEvents;
Values?: SimpleMap<number>;
Dimensions?: SimpleMap<string>;
}) => ({
method: 'post',
url: 'data/v1/stats',
data: {
...data,
Values: data.Values || {},
Dimensions: data.Dimensions || {},
},
});
export const sendMultipleTelemetryData = (data: { reports: TelemetryReport[] }) => {
const EventInfo = data.reports.map(({ measurementGroup, event, values, dimensions }) => ({
MeasurementGroup: measurementGroup,
Event: event,
Values: values || {},
Dimensions: dimensions || {},
}));
return {
method: 'post',
url: 'data/v1/stats/multiple',
data: { EventInfo },
};
};
| 8,253 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/tests.js | export const ping = () => ({
url: 'tests/ping',
method: 'get',
});
export const testHumanVerification = () => ({
url: 'tests/humanverification',
method: 'get',
});
| 8,254 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/user.ts | import { ProductParam, getProductHeaders } from '../apps/product';
import { CLIENT_TYPES } from '../constants';
import { HumanVerificationMethodType } from '../interfaces';
export const getUser = () => ({
url: 'core/v4/users',
method: 'get',
});
export const queryCreateUser = (
data: {
Username: string;
Domain?: string;
Email?: string;
Phone?: string;
Type: CLIENT_TYPES; // 1 = mail, 2 = VPN
Referrer?: string;
ReferralIdentifier?: string;
ReferralID?: string; // Invite
TokenPayment?: string;
Payload?: {
[key: string]: string;
};
Salt?: string;
},
product: ProductParam
) => ({
url: 'core/v4/users',
method: 'post',
data,
headers: getProductHeaders(product, {
endpoint: 'core/v4/users',
product,
}),
});
export const getRecoveryMethods = (Username: string) => ({
url: 'core/v4/users/reset',
method: 'get',
params: { Username },
});
export const queryCreateUserExternal = (
data: {
Email: string;
Token?: string;
TokenType?: HumanVerificationMethodType;
Type: CLIENT_TYPES; // 1 = mail, 2 = VPN
Referrer?: string;
TokenPayment?: string;
Payload?: {
[key: string]: string;
};
Salt?: string;
},
product: ProductParam
) => ({
url: 'core/v4/users/external',
method: 'post',
data,
headers: getProductHeaders(product, {
endpoint: 'core/v4/users/external',
product,
}),
});
export const queryUnlock = () => ({
url: 'core/v4/users/unlock',
method: 'put',
});
export const canDelete = () => ({
url: 'core/v4/users/delete',
method: 'get',
});
export const deleteUser = (data: { Reason?: string; Feedback?: string; Email?: string }) => ({
url: 'core/v4/users/delete',
method: 'put',
data,
});
export const unlockPasswordChanges = () => ({
url: 'core/v4/users/password',
method: 'put',
});
export const lockSensitiveSettings = () => ({
url: 'core/v4/users/lock',
method: 'put',
});
export const getHumanVerificationMethods = () => ({
url: 'core/v4/users/human',
method: 'get',
});
export const queryVerificationCode = (
Type: 'email' | 'sms',
Destination:
| {
Address: string;
Phone?: never;
}
| {
Address?: never;
Phone: string;
}
) => ({
url: 'core/v4/users/code',
method: 'post',
data: { Type, Destination },
});
export const queryCheckUsernameAvailability = (Name: string, ParseDomain?: boolean) => ({
url: 'core/v4/users/available',
method: 'get',
params: { Name, ParseDomain: ParseDomain ? 1 : 0 },
});
export const queryCheckEmailAvailability = (Name: string) => ({
url: 'core/v4/users/availableExternal',
method: 'get',
params: { Name },
});
export const queryDirectSignupStatus = (
Type: CLIENT_TYPES // 1 = mail, 2 = VPN
) => ({
url: 'core/v4/users/direct',
method: 'get',
params: { Type },
});
export const queryCheckVerificationCode = (
Token: string,
TokenType: 'email' | 'sms' | 'invite' | 'coupon' | 'payment',
Type: CLIENT_TYPES // 1 = mail, 2 = VPN
) => ({
url: 'core/v4/users/check',
method: 'put',
data: { Token, TokenType, Type },
});
export const getInvitations = () => ({
url: 'core/v4/users/invitations',
method: 'get',
});
export const acceptInvitation = (invitationID: string) => ({
url: `core/v4/users/invitations/${invitationID}/accept`,
method: 'post',
});
export const rejectInvitation = (invitationID: string) => ({
url: `core/v4/users/invitations/${invitationID}/reject`,
method: 'post',
});
export const disableUser = (data: { JWT: string }) => ({
url: `core/v4/users/disable/${data.JWT}`,
method: 'get',
});
| 8,255 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/verification.ts | export const getVerificationDataRoute = (token: string, method: string) => ({
url: `core/v4/verification/${method}/${token}`,
method: 'get',
});
export const sendVerificationCode = (token: string, method: string) => ({
url: `core/v4/verification/${method}/${token}`,
method: 'post',
});
export const verifyVerificationCode = (token: string, method: string, code: string) => ({
url: `core/v4/verification/${method}/${token}/${code}`,
method: 'post',
});
| 8,256 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/verify.ts | export const postVerifySend = (data: {
Type: 'recovery_email' | 'external_email';
/* required if type is external_email, optional & not used if type is recovery_email */
Destination?: string;
}) => ({
url: 'core/v4/verify/send',
method: 'post',
data,
});
export const postVerifyValidate = (data: { JWT: string }) => ({
url: 'core/v4/verify/validate',
method: 'post',
data,
});
export const postVerifyUnvalidate = (data: { JWT: string }) => ({
url: 'core/v4/verify/validate',
method: 'delete',
data,
});
export const postVerifyPhone = () => ({
url: 'core/v4/verify/phone',
method: 'post',
});
| 8,257 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/vpn.js | import { HTTP_ERROR_CODES } from '../errors';
export const getClientVPNInfo = () => ({
method: 'get',
url: 'vpn',
});
export const queryVPNLogicalServerLoads = () => ({
method: 'get',
url: 'vpn/loads',
});
export const queryVPNCountriesCount = () => ({
method: 'get',
url: 'vpn/countries/count',
});
export const queryVPNLogicalServerInfo = () => ({
method: 'get',
url: 'vpn/logicals',
});
export const queryVPNLogicalServerInfoCount = () => ({
method: 'get',
url: 'vpn/logicals/count',
params: {
GroupBy: 'Tier',
},
});
export const queryVPNServerInfo = () => ({
method: 'get',
url: 'vpn/servers',
});
export const queryVPNServersCount = () => ({
method: 'get',
url: 'vpn/v1/servers-count',
});
export const getLocation = () => ({
method: 'get',
url: 'vpn/location',
ignoreHandler: [HTTP_ERROR_CODES.TOO_MANY_REQUESTS],
});
export const getVPNServerConfig = ({ LogicalID, ServerID, Country, Category, Tier, Platform, Protocol }) => ({
method: 'get',
url: 'vpn/config',
output: 'arrayBuffer',
params: { LogicalID, ServerID, Country, Category, Tier, Platform, Protocol },
});
export const getAuthServerVPNInfo = ({ Username, ServerIP, Secret }) => ({
method: 'post',
url: 'vpn/auth',
data: { Username, ServerIP, Secret },
});
export const getAccountingServerVPNInfo = ({ Username, ServerIP, Secret }) => ({
method: 'post',
url: 'vpn/accounting',
data: { Username, ServerIP, Secret },
});
export const updateServerLoad = (encryptedID, { Secret, Bytes }) => ({
method: 'post',
url: `vpn/servers/${encryptedID}/load`,
data: { Secret, Bytes },
});
export const updateServerStatus = (encryptedID, { Secret, Status, Services }) => ({
method: 'post',
url: `vpn/servers/${encryptedID}/status`,
data: { Secret, Status, Services },
});
export const getVPNActiveSessionCount = () => ({
method: 'get',
url: 'vpn/sessioncount',
});
export const queryVPNActiveSessionInfo = () => ({
method: 'get',
url: 'vpn/sessions',
});
export const resetVPNSettings = () => ({
method: 'put',
url: 'vpn/settings/reset',
});
| 8,258 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/core/load.ts | export const load = (page: string) => ({
method: 'get',
url: 'core/v4/load',
params: { page },
});
| 8,259 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/core/referrals.ts | interface GetReferralsProps {
Offset?: number;
Limit?: number;
}
export const getReferrals = (params?: GetReferralsProps) => ({
method: 'get',
url: 'core/v4/referrals',
params: params,
});
/**
* Get current user referral status
*/
export const getReferralsStatus = () => ({
method: 'get',
url: 'core/v4/referrals/status',
});
interface SendEmailInvationProps {
emails: string[];
}
export const sendEmailInvitation = ({ emails }: SendEmailInvationProps) => ({
method: 'post',
url: 'core/v4/referrals',
data: { Recipients: emails },
});
interface ResendInvitationURLParams {
id: string;
}
export const resendEmailInvitation = ({ id }: ResendInvitationURLParams) => ({
method: 'get',
url: `core/v4/referrals/${id}`,
});
interface DeleteInvitationURLParams {
id: string;
}
/** delete an invitation or outdated referral */
export const deleteInvitation = ({ id }: DeleteInvitationURLParams) => ({
method: 'delete',
url: `core/v4/referrals/${id}`,
});
export const checkReferrer = (identifier: string) => ({
method: 'get',
url: `core/v4/referrals/identifiers/${identifier}`,
});
| 8,260 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/core/update.ts | export const update = (params: any) => ({
method: 'get',
url: 'core/v4/update',
params,
});
| 8,261 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/core/validate.ts | export const validateEmail = (Email: string) => ({
method: 'post',
url: 'core/v4/validate/email',
data: { Email },
});
export const validatePhone = (Phone: string) => ({
method: 'post',
url: 'core/v4/validate/phone',
data: { Phone },
});
| 8,262 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/devices.ts | import { CreateDeviceVolume } from '../../interfaces/drive/device';
export const queryDevices = () => ({
method: 'get',
url: 'drive/devices',
});
export const queryDeviceDeletion = (deviceId: string) => ({
method: 'delete',
url: `drive/devices/${deviceId}`,
});
export const queryDeviceRename = (
deviceId: string,
data: {
Name: string;
}
) => ({
method: 'put',
url: `drive/devices/${deviceId}`,
data: {
Device: {
SyncState: 1,
},
Share: {
Name: data.Name,
},
},
});
export const queryCreateDriveDevice = (data: CreateDeviceVolume) => ({
method: 'post',
url: 'drive/devices',
data,
});
| 8,263 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/files.ts | import { UPLOAD_TIMEOUT } from '../../drive/constants';
import { CreateDriveFile, Thumbnail, UpdateFileRevision } from '../../interfaces/drive/file';
export const queryCreateFile = (shareId: string, data: CreateDriveFile) => {
return {
method: 'post',
timeout: UPLOAD_TIMEOUT,
url: `drive/shares/${shareId}/files`,
silence: true,
data,
};
};
export const queryFileRevisions = (shareId: string, linkId: string) => {
return {
method: 'get',
url: `drive/shares/${shareId}/files/${linkId}/revisions`,
silence: true,
};
};
export const queryFileRevision = (
shareId: string,
linkId: string,
revisionId: string,
pagination?: { FromBlockIndex: number; PageSize: number }
) => {
const query = {
method: 'get',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}`,
silence: true,
};
if (pagination) {
return {
...query,
params: pagination,
};
}
return query;
};
export const queryFileRevisionThumbnail = (
shareId: string,
linkId: string,
revisionId: string,
thumbnailType: 1 | 2 | 3 = 1
) => {
return {
method: 'get',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}/thumbnail?Type=${thumbnailType}`,
silence: true,
};
};
/**
* This route should never be called without also instanciating a verifier.
* See the file uploader in the Drive app.
*/
export const queryVerificationData = (shareId: string, linkId: string, revisionId: string) => {
return {
method: 'get',
url: `drive/shares/${shareId}/links/${linkId}/revisions/${revisionId}/verification`,
silence: true,
};
};
export const queryRequestUpload = (data: {
BlockList: {
Hash: string;
EncSignature: string;
Size: number;
Index: number;
Verifier: {
Token: string;
};
}[];
ThumbnailList?: Thumbnail[];
AddressID: string;
ShareID: string;
LinkID: string;
RevisionID: string;
Thumbnail?: number;
ThumbnailHash?: string;
ThumbnailSize?: number;
}) => {
return {
method: 'post',
url: 'drive/blocks',
data,
};
};
export const queryFileBlock = (url: string) => {
return {
method: 'get',
output: 'stream',
credentials: 'omit',
url,
};
};
export const queryUploadFileBlock = (url: string, chunk: Uint8Array) => {
return {
method: 'put',
input: 'binary',
data: new Blob([chunk]),
url,
};
};
export const queryCreateFileRevision = (
shareId: string,
linkId: string,
currentRevisionId: string,
clientUID?: string
) => {
return {
method: 'post',
timeout: UPLOAD_TIMEOUT,
url: `drive/shares/${shareId}/files/${linkId}/revisions`,
silence: true,
data: {
CurrentRevisionID: currentRevisionId,
ClientUID: clientUID,
},
};
};
export const queryUpdateFileRevision = (
shareID: string,
linkID: string,
revisionId: string,
data: UpdateFileRevision
) => {
return {
method: 'put',
timeout: UPLOAD_TIMEOUT,
url: `drive/shares/${shareID}/files/${linkID}/revisions/${revisionId}`,
data,
};
};
export const queryDeleteFileRevision = (shareId: string, linkId: string, revisionId: string) => {
return {
method: 'delete',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}`,
};
};
export const queryRestoreFileRevision = (shareId: string, linkId: string, revisionId: string) => {
return {
method: 'post',
url: `drive/shares/${shareId}/files/${linkId}/revisions/${revisionId}/restore`,
};
};
| 8,264 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/folder.ts | import { SORT_DIRECTION } from '../../constants';
import { DEFAULT_SORT_FIELD, DEFAULT_SORT_ORDER, FOLDER_PAGE_SIZE } from '../../drive/constants';
import { CreateNewFolder } from '../../interfaces/drive/folder';
export const queryFolderChildren = (
shareID: string,
linkID: string,
{
Page,
PageSize = FOLDER_PAGE_SIZE,
FoldersOnly = 0,
Sort = DEFAULT_SORT_FIELD,
Desc = DEFAULT_SORT_ORDER === SORT_DIRECTION.ASC ? 0 : 1,
}: { Page: number; PageSize?: number; FoldersOnly?: number; Sort?: string; Desc?: 0 | 1 }
) => ({
method: 'get',
url: `drive/shares/${shareID}/folders/${linkID}/children`,
params: { Page, PageSize, FoldersOnly, Sort, Desc, Thumbnails: 1 },
});
export const queryCreateFolder = (shareID: string, data: CreateNewFolder) => ({
method: 'post',
url: `drive/shares/${shareID}/folders`,
data,
});
| 8,265 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/link.ts | import { EXPENSIVE_REQUEST_TIMEOUT } from '../../drive/constants';
export const queryCheckAvailableHashes = (
shareId: string,
linkId: string,
data: { Hashes: string[] },
suppressErrors = false
) => {
return {
method: 'post',
timeout: EXPENSIVE_REQUEST_TIMEOUT,
url: `drive/shares/${shareId}/links/${linkId}/checkAvailableHashes`,
suppress: suppressErrors,
data,
};
};
export const queryGetLink = (ShareID: string, LinkID: string) => ({
method: 'get',
url: `drive/shares/${ShareID}/links/${LinkID}`,
});
export const queryTrashLinks = (ShareID: string, ParentLinkID: string, LinkIDs: string[]) => ({
method: 'post',
url: `drive/shares/${ShareID}/folders/${ParentLinkID}/trash_multiple`,
data: { LinkIDs },
});
export const queryDeleteTrashedLinks = (ShareID: string, LinkIDs: string[]) => ({
method: 'post',
url: `drive/shares/${ShareID}/trash/delete_multiple`,
data: { LinkIDs },
});
export const queryDeleteChildrenLinks = (ShareID: string, ParentLinkID: string, LinkIDs: string[]) => ({
method: 'post',
url: `drive/shares/${ShareID}/folders/${ParentLinkID}/delete_multiple`,
data: { LinkIDs },
});
export const queryRestoreLinks = (ShareID: string, LinkIDs: string[]) => ({
method: 'put',
url: `drive/shares/${ShareID}/trash/restore_multiple`,
data: { LinkIDs },
});
export const queryEmptyTrashOfShare = (ShareID: string) => ({
method: 'delete',
url: `drive/shares/${ShareID}/trash`,
});
export const queryLinkMetaBatch = (shareId: string, linksIds: string[], loadThumbnails: boolean = false) => ({
method: 'post',
url: `drive/shares/${shareId}/links/fetch_metadata`,
data: { LinkIDs: linksIds, Thumbnails: loadThumbnails ? 1 : 0 },
});
export const queryShareMap = (shareID: string, lastIndex?: number, sessionName?: string, pageSize?: number) => ({
url: `drive/shares/${shareID}/map`,
method: 'get',
params: {
LastIndex: lastIndex,
SessionName: sessionName,
PageSize: pageSize,
},
});
| 8,266 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/photos.ts | import { PHOTOS_PAGE_SIZE } from '../../drive/constants';
export const queryPhotos = (
volumeId: string,
params?: {
Desc?: 0 | 1;
PreviousPageLastLinkID?: string;
MinimumCaptureTime?: number;
}
) => ({
method: 'get',
url: `drive/volumes/${volumeId}/photos`,
params: {
PageSize: PHOTOS_PAGE_SIZE,
...params,
},
});
export const queryDeletePhotosShare = (volumeId: string, shareId: string) => ({
method: 'delete',
url: `drive/volumes/${volumeId}/photos/share/${shareId}`,
});
| 8,267 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/share.ts | import { EXPENSIVE_REQUEST_TIMEOUT } from '../../drive/constants';
import { MoveLink } from '../../interfaces/drive/link';
import { CreateDrivePhotosShare, CreateDriveShare } from '../../interfaces/drive/share';
export const queryCreateShare = (volumeID: string, data: CreateDriveShare) => ({
method: 'post',
url: `drive/volumes/${volumeID}/shares`,
data,
});
export const queryCreatePhotosShare = (volumeID: string, data: CreateDrivePhotosShare) => ({
method: 'post',
url: `drive/volumes/${volumeID}/photos/share`,
data,
});
export const queryUserShares = (ShowAll = 1) => ({
method: 'get',
url: 'drive/shares',
silence: true,
params: { ShowAll },
});
export const queryShareMeta = (shareID: string) => ({
method: `get`,
url: `drive/shares/${shareID}`,
});
export const queryRenameLink = (
shareID: string,
linkID: string,
data: { Name: string; MIMEType?: string; Hash: string; SignatureAddress: string; OriginalHash: string }
) => ({
method: `put`,
url: `drive/shares/${shareID}/links/${linkID}/rename`,
data,
});
export const queryMoveLink = (shareID: string, linkID: string, data: MoveLink) => ({
method: 'put',
url: `drive/shares/${shareID}/links/${linkID}/move`,
data,
});
export const queryEvents = (shareID: string, eventID: string) => ({
timeout: EXPENSIVE_REQUEST_TIMEOUT,
url: `drive/shares/${shareID}/events/${eventID}`,
method: 'get',
});
export const queryLatestEvents = (shareID: string) => ({
url: `drive/shares/${shareID}/events/latest`,
method: 'get',
});
export const queryDeleteShare = (shareID: string) => ({
url: `drive/shares/${shareID}`,
method: 'delete',
});
| 8,268 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/sharing.ts | import { HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { SORT_DIRECTION } from '../../constants';
import { DEFAULT_SORT_FIELD, DEFAULT_SORT_ORDER, FOLDER_PAGE_SIZE } from '../../drive/constants';
import { AbuseReportPayload, CreateSharedURL, UpdateSharedURL } from '../../interfaces/drive/sharing';
export const queryInitSRPHandshake = (token: string) => {
return {
method: 'get',
url: `drive/urls/${token}/info`,
silence: true,
};
};
export const querySharedURLInformation = (token: string) => {
return {
method: 'get',
url: `drive/urls/${token}`,
silence: true,
};
};
export const queryShareURLAuth = (token: string) => {
return {
method: 'post',
url: `drive/urls/${token}/auth`,
silence: true,
};
};
export const querySharedURLFileRevision = (
token: string,
linkID: string,
pagination?: {
FromBlockIndex: number;
PageSize: number;
}
) => {
const query = {
method: 'get',
url: `drive/urls/${token}/files/${linkID}`,
};
if (pagination) {
return {
...query,
params: pagination,
silence: [HTTP_ERROR_CODES.UNAUTHORIZED],
};
}
return query;
};
export const querySharedURLChildren = (
token: string,
linkId: string,
{
Page,
PageSize = FOLDER_PAGE_SIZE,
Sort = DEFAULT_SORT_FIELD,
Desc = DEFAULT_SORT_ORDER === SORT_DIRECTION.ASC ? 0 : 1,
}: { Page: number; PageSize?: number; FoldersOnly?: number; Sort?: string; Desc?: 0 | 1 }
) => {
return {
method: 'get',
url: `drive/urls/${token}/folders/${linkId}/children`,
params: { Page, PageSize, Sort, Desc, Thumbnails: 1 },
silence: [HTTP_ERROR_CODES.UNAUTHORIZED],
};
};
export const queryCreateSharedLink = (shareId: string, data: CreateSharedURL) => {
return {
method: 'post',
url: `drive/shares/${shareId}/urls`,
data,
};
};
export const querySharedLinks = (shareId: string, params: { Page: number; PageSize?: number; Recursive?: 1 | 0 }) => {
return {
method: 'get',
url: `drive/shares/${shareId}/urls`,
params,
};
};
export const queryUpdateSharedLink = (shareId: string, shareUrlId: string, data: Partial<UpdateSharedURL>) => {
return {
method: 'put',
url: `drive/shares/${shareId}/urls/${shareUrlId}`,
data,
};
};
export const queryDeleteSharedLink = (shareId: string, shareUrlId: string) => {
return {
method: 'delete',
url: `drive/shares/${shareId}/urls/${shareUrlId}`,
};
};
export const queryDeleteMultipleSharedLinks = (shareId: string, shareUrlIds: string[]) => {
return {
method: 'post',
url: `drive/shares/${shareId}/urls/delete_multiple`,
data: {
ShareURLIDs: shareUrlIds,
},
};
};
export const querySubmitAbuseReport = (data: AbuseReportPayload) => {
return {
method: 'post',
url: 'drive/report/url',
data,
};
};
| 8,269 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/userSettings.ts | import { UserSettings } from '../../interfaces/drive/userSettings';
export const queryUserSettings = () => {
return {
method: 'get',
url: `drive/me/settings`,
};
};
export const queryUpdateUserSettings = (data: Partial<UserSettings>) => {
return {
method: 'put',
url: `drive/me/settings`,
data,
};
};
| 8,270 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/drive/volume.ts | import { FOLDER_PAGE_SIZE } from '../../drive/constants';
import { CreateDriveVolume, RestoreDriveVolume } from '../../interfaces/drive/volume';
export const queryCreateDriveVolume = (data: CreateDriveVolume) => ({
method: 'post',
url: 'drive/volumes',
data,
});
export const queryRestoreDriveVolume = (encryptedVolumeId: string, data: RestoreDriveVolume) => ({
method: 'put',
url: `drive/volumes/${encryptedVolumeId}/restore`,
data,
});
export const queryDeleteLockedVolumes = (volumeId: string) => {
return {
method: 'put',
url: `drive/volumes/${volumeId}/delete_locked`,
};
};
export const queryVolumeTrash = (
volumeId: string,
{ Page = 0, PageSize = FOLDER_PAGE_SIZE }: { Page?: number; PageSize?: number }
) => {
return {
method: 'get',
url: `drive/volumes/${volumeId}/trash`,
params: {
Page,
PageSize,
},
};
};
export const queryVolumeEmptyTrash = (volumeId: string) => ({
method: 'delete',
url: `drive/volumes/${volumeId}/trash`,
});
export const queryVolumeSharedLinks = (
volumeId: string,
params: { Page: number; PageSize?: number; Recursive?: 1 | 0 }
) => {
return {
method: 'get',
url: `drive/volumes/${volumeId}/urls`,
params,
};
};
export const queryLatestVolumeEvent = (volumeId: string) => ({
url: `drive/volumes/${volumeId}/events/latest`,
method: 'get',
});
export const queryVolumeEvents = (volumeId: string, eventId: string) => ({
url: `drive/volumes/${volumeId}/events/${eventId}`,
method: 'get',
});
| 8,271 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/apiErrorHelper.ts | import { c } from 'ttag';
import { API_CODES } from '../../constants';
import { HTTP_ERROR_CODES } from '../../errors';
export const isNotExistError = (error: any) => {
const notExistErrorCodes = [
API_CODES.INVALID_ID_ERROR,
API_CODES.NOT_FOUND_ERROR,
/**
* Mail Specific: Conversation does not exists
*/
20052,
];
return Boolean(notExistErrorCodes.includes(error.data?.Code));
};
export const getApiError = (e?: any) => {
if (!e) {
return {};
}
const { data, status } = e;
if (!data) {
return {
status,
};
}
const { Error: errorMessage, Code: errorCode, Details: errorDetails } = data;
if (!errorMessage) {
return {
status,
};
}
return {
status,
code: errorCode,
message: errorMessage,
details: errorDetails,
};
};
export const getIs401Error = (e: any) => {
if (!e) {
return false;
}
return e.name === 'InactiveSession' || e.status === 401;
};
export const getIsOfflineError = (e: any) => {
return e.name === 'OfflineError';
};
export const getIsUnreachableError = (e: any) => {
if (!e) {
return false;
}
// On 503, even if there's response, it's an unreachable error
if (e.status === HTTP_ERROR_CODES.SERVICE_UNAVAILABLE) {
return true;
}
// On 502 or 504, we verify that the API did not actually give a response. It can return these codes when acting as a proxy (e.g. email-list unsubscribe).
return (
[HTTP_ERROR_CODES.BAD_GATEWAY, HTTP_ERROR_CODES.GATEWAY_TIMEOUT].includes(e.status) &&
e.data?.Code === undefined
);
};
export const getIsNetworkError = (e: any) => {
if (!e) {
return false;
}
return e.name === 'NetworkError' || e.message?.toLowerCase() === 'network error';
};
export const getIsTimeoutError = (e: any) => {
if (!e) {
return false;
}
return e.name === 'TimeoutError';
};
export const getIsConnectionIssue = (e: any) => {
return getIsOfflineError(e) || getIsUnreachableError(e) || getIsNetworkError(e) || getIsTimeoutError(e);
};
export const getApiErrorMessage = (e: Error): string | undefined => {
const { message } = getApiError(e);
if (getIs401Error(e)) {
return message || c('Info').t`Session timed out`;
}
if (getIsOfflineError(e)) {
return message || c('Info').t`Internet connection lost`;
}
if (getIsUnreachableError(e)) {
return message || c('Info').t`Servers are unreachable. Please try again in a few minutes`;
}
if (getIsTimeoutError(e)) {
return message || c('Error').t`Request timed out`;
}
if (message) {
return `${message}`;
}
};
| 8,272 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/canonicalEmailMap.ts | import { API_CODES } from '../../constants';
import { Api } from '../../interfaces';
import { GetCanonicalAddressesApiResponse } from '../../interfaces/calendar';
import { SimpleMap } from '../../interfaces/utils';
import { getCanonicalAddresses } from '../addresses';
export const getCanonicalEmailMap = async (emails: string[] = [], api: Api) => {
const map: SimpleMap<string> = {};
if (emails.length) {
const encodedEmails = emails.map((email) => encodeURIComponent(email));
const { Responses, Code } = await api<GetCanonicalAddressesApiResponse>(getCanonicalAddresses(encodedEmails));
if (Code !== API_CODES.GLOBAL_SUCCESS) {
throw new Error('Canonicalize operation failed');
}
Responses.forEach(({ Email, Response: { Code, CanonicalEmail } }) => {
if (Code !== API_CODES.SINGLE_SUCCESS) {
throw new Error('Canonicalize operation failed');
}
map[Email] = CanonicalEmail;
});
}
return map;
};
| 8,273 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/customConfig.ts | import { withAuthHeaders, withUIDHeaders } from '@proton/shared/lib/fetch/headers';
import { Api } from '../../interfaces';
export const getSilentApi = (api: Api) => {
return <T>(config: any) => api<T>({ ...config, silence: true });
};
export const getApiWithAbort = (api: Api, signal: AbortSignal) => {
return <T>(config: any) => api<T>({ ...config, signal });
};
export const getSilentApiWithAbort = (api: Api, signal: AbortSignal) => {
return <T>(config: any) => api<T>({ ...config, signal, silence: true });
};
export const getUIDApi = (UID: string, api: Api) => {
return <T>(config: any) => api<T>(withUIDHeaders(UID, config));
};
export const getAuthAPI = (UID: string, AccessToken: string, api: Api) => {
return <T>(config: any) => api<T>(withAuthHeaders(UID, AccessToken, config));
};
| 8,274 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/deviceVerificationHandler.ts | import { create as createMutex } from '@protontech/mutex-browser';
import { createOnceHandler } from '@proton/shared/lib/apiHandlers';
import { wait } from '@proton/shared/lib/helpers/promise';
import pbkdfWorkerWrapper from '@proton/shared/lib/pow/pbkdfWorkerWrapper';
import noop from '@proton/utils/noop';
import randomIntFromInterval from '@proton/utils/randomIntFromInterval';
import localStorageWithExpiry from './localStorageWithExpiry';
const onSolve = (b64Source: string): Promise<string> => {
return new Promise((resolve, reject) => {
try {
const pbkdfWorker = pbkdfWorkerWrapper();
pbkdfWorker.postMessage({ b64Source });
pbkdfWorker.onmessage = (event) => {
resolve(event.data);
};
pbkdfWorker.onerror = (error) => {
reject(error);
};
} catch (error) {
reject(error);
}
});
};
export const createDeviceHandlers = () => {
const deviceVerificationHandlers: { [key: string]: ReturnType<typeof createOnceHandler<string, string>> } = {};
const deviceVerificationHandler = (
UID: string,
challengeType: number,
challengePayload: string
): Promise<string> => {
if (!deviceVerificationHandlers[UID]) {
const mutex = createMutex({ expiry: 15000 });
const getMutexLock = async (UID: string) => {
try {
await mutex.lock(UID);
return () => {
return mutex.unlock(UID).catch(noop);
};
} catch (e) {
// If getting the mutex fails, fall back to a random wait
await wait(randomIntFromInterval(100, 2000));
return () => {
return Promise.resolve();
};
}
};
deviceVerificationHandlers[UID] = createOnceHandler(async (challengePayload: string): Promise<string> => {
const unlockMutex = await getMutexLock(UID);
let token = '';
try {
const lastCachedDate = localStorageWithExpiry.getData(challengePayload);
if (!lastCachedDate) {
token = await onSolve(challengePayload);
localStorageWithExpiry.storeData(challengePayload, token, 1 * 60 * 1000);
await wait(50);
} else {
token = lastCachedDate;
}
} catch (e) {
throw e;
} finally {
await unlockMutex();
}
return token;
});
}
return deviceVerificationHandlers[UID](challengePayload);
};
return deviceVerificationHandler;
};
| 8,275 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/getAndVerifyApiKeys.ts | import { CryptoProxy } from '@proton/crypto';
import {
Api,
ApiAddressKey,
ApiAddressKeySource,
FetchedSignedKeyList,
KeyTransparencyVerificationResult,
ProcessedApiAddressKey,
VerifyOutboundPublicKeys,
} from '../../interfaces';
import { getAllPublicKeys } from '../keys';
export interface ApiKeysWithKTStatus {
addressKeys: ProcessedApiAddressKey[];
addressKTResult?: KeyTransparencyVerificationResult;
catchAllKeys?: ProcessedApiAddressKey[];
catchAllKTResult?: KeyTransparencyVerificationResult;
unverifiedKeys?: ProcessedApiAddressKey[];
hasValidProtonMX?: boolean;
Code?: number;
Warnings?: string[];
}
const getApiKeySource = (source: number): ApiAddressKeySource => {
switch (source) {
case 0:
return ApiAddressKeySource.PROTON;
case 1:
return ApiAddressKeySource.WKD;
default:
return ApiAddressKeySource.UNKNOWN;
}
};
const importKeys = (keys: ApiAddressKey[]): Promise<ProcessedApiAddressKey[]> => {
return Promise.all(
keys.map(async ({ PublicKey, Flags, Source }) => {
return {
armoredPublicKey: PublicKey,
flags: Flags,
publicKeyRef: await CryptoProxy.importPublicKey({ armoredKey: PublicKey }),
source: getApiKeySource(Source),
};
})
);
};
export const getAndVerifyApiKeys = async ({
api,
email,
internalKeysOnly,
verifyOutboundPublicKeys,
skipVerificationOfExternalDomains = false,
silence = false,
noCache = false,
}: {
api: Api;
email: string;
internalKeysOnly: boolean;
/** KT verification function, or `null` for legacy use-case where KT is disabled */
verifyOutboundPublicKeys: VerifyOutboundPublicKeys | null;
/** Optimisations _only_ for apps where users with external domains do not have valid keys (e.g. Mail) */
skipVerificationOfExternalDomains?: boolean;
silence?: boolean;
noCache?: boolean;
}): Promise<ApiKeysWithKTStatus> => {
const config: any = { ...getAllPublicKeys({ Email: email, InternalOnly: internalKeysOnly ? 1 : 0 }), silence };
if (noCache) {
config.cache = 'no-cache';
}
const { Address, CatchAll, Unverified, ProtonMX, ...rest } = await api<{
Address: {
Keys: ApiAddressKey[];
SignedKeyList: FetchedSignedKeyList | null;
};
CatchAll:
| {
Keys: ApiAddressKey[];
SignedKeyList: FetchedSignedKeyList | null;
}
| undefined;
Unverified: {
Keys: ApiAddressKey[];
};
ProtonMX: boolean;
Warnings: string[];
}>(config);
const addressKeys = await importKeys(Address.Keys);
const unverifiedKeys = Unverified ? await importKeys(Unverified.Keys) : undefined;
const catchAllKeys = CatchAll ? await importKeys(CatchAll.Keys) : undefined;
const ktResult = verifyOutboundPublicKeys
? await verifyOutboundPublicKeys(
email,
skipVerificationOfExternalDomains,
{ keyList: addressKeys, signedKeyList: Address.SignedKeyList },
CatchAll ? { keyList: catchAllKeys!, signedKeyList: CatchAll.SignedKeyList } : undefined
)
: {};
return {
addressKeys,
catchAllKeys,
unverifiedKeys,
hasValidProtonMX: ProtonMX,
...rest,
...ktResult,
};
};
| 8,276 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/getPublicKeysEmailHelper.ts | import { c } from 'ttag';
import { ktKeyVerificationFailureTelemetry, ktSentryReport } from '@proton/key-transparency/lib';
import {
Api,
ApiKeysConfig,
KT_VERIFICATION_STATUS,
KeyTransparencyActivation,
VerifyOutboundPublicKeys,
} from '../../interfaces';
import getPublicKeysEmailHelperWithKT from './getPublicKeysEmailHelperWithKT';
export const KEY_VERIFICATION_ERROR_MESSAGE = c('loc_nightly: Key verification error')
.t`Unable to verify this address at this time`;
/**
* Ask the API for public keys for a given email address. The response will contain keys both
* for internal users and for external users with WKD keys
*/
const getPublicKeysEmailHelper = async ({
email,
internalKeysOnly = false,
includeInternalKeysWithE2EEDisabledForMail = false,
api,
ktActivation,
verifyOutboundPublicKeys,
silence,
noCache,
}: {
email: string;
internalKeysOnly?: boolean;
api: Api;
ktActivation: KeyTransparencyActivation;
verifyOutboundPublicKeys: VerifyOutboundPublicKeys;
/**
* Whether to return internal keys which cannot be used for email encryption, as the owner has disabled E2EE.
* These keys may still be used for e.g. calendar sharing or message verification.
**/
includeInternalKeysWithE2EEDisabledForMail?: boolean;
silence?: boolean;
noCache?: boolean;
}): Promise<ApiKeysConfig> => {
if (ktActivation === KeyTransparencyActivation.DISABLED) {
const { ktVerificationResult, ...resultWithoutKT } = await getPublicKeysEmailHelperWithKT({
email,
internalKeysOnly,
includeInternalKeysWithE2EEDisabledForMail,
api,
verifyOutboundPublicKeys: null, // skip KT verification
silence,
noCache,
});
return resultWithoutKT;
}
const result = await getPublicKeysEmailHelperWithKT({
email,
internalKeysOnly,
includeInternalKeysWithE2EEDisabledForMail,
api,
verifyOutboundPublicKeys,
silence,
noCache,
});
if (result.ktVerificationResult?.status === KT_VERIFICATION_STATUS.VERIFICATION_FAILED) {
const visible = ktActivation === KeyTransparencyActivation.SHOW_UI;
ktSentryReport('Key verification error', { email });
await ktKeyVerificationFailureTelemetry(api, visible);
if (visible) {
return {
publicKeys: [],
ktVerificationResult: result.ktVerificationResult,
Errors: [KEY_VERIFICATION_ERROR_MESSAGE],
};
}
}
if (ktActivation === KeyTransparencyActivation.LOG_ONLY) {
return {
...result,
ktVerificationResult: undefined,
};
}
return result;
};
export default getPublicKeysEmailHelper;
| 8,277 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/getPublicKeysEmailHelperWithKT.ts | import { RECIPIENT_TYPES } from '../../constants';
import { API_CUSTOM_ERROR_CODES } from '../../errors';
import {
Api,
ApiKeysConfig,
KT_VERIFICATION_STATUS,
ProcessedApiAddressKey,
ProcessedApiKey,
VerifyOutboundPublicKeys,
} from '../../interfaces';
import { getExternalKeys, getInternalKeys, getMailCapableKeys, supportsMail } from '../../keys';
import { getAndVerifyApiKeys } from './getAndVerifyApiKeys';
const { KEY_GET_ADDRESS_MISSING, KEY_GET_DOMAIN_MISSING_MX, KEY_GET_INPUT_INVALID, KEY_GET_INVALID_KT } =
API_CUSTOM_ERROR_CODES;
const EMAIL_ERRORS = [KEY_GET_ADDRESS_MISSING, KEY_GET_DOMAIN_MISSING_MX, KEY_GET_INPUT_INVALID, KEY_GET_INVALID_KT];
export const castKeys = (keys: ProcessedApiAddressKey[]): ProcessedApiKey[] => {
return keys.map(({ armoredPublicKey, flags, publicKeyRef }) => {
return { armoredKey: armoredPublicKey, flags, publicKey: publicKeyRef };
});
};
const getFailedOrUnVerified = (failed: boolean) =>
failed ? KT_VERIFICATION_STATUS.VERIFICATION_FAILED : KT_VERIFICATION_STATUS.UNVERIFIED_KEYS;
/**
* This is an Inbox-specific helper, as it discards address keys from external addresses, which are not used by Inbox at the moment.
* If support for returning such keys is added, it's important to provide a way to distinguish them from Unverified keys (e.g. from WKD)
* which can also be present for external accounts.
*/
const getPublicKeysEmailHelperWithKT = async ({
email,
internalKeysOnly,
includeInternalKeysWithE2EEDisabledForMail,
api,
verifyOutboundPublicKeys,
silence,
noCache,
}: {
email: string;
internalKeysOnly: boolean;
includeInternalKeysWithE2EEDisabledForMail: boolean;
api: Api;
verifyOutboundPublicKeys: VerifyOutboundPublicKeys | null;
silence?: boolean;
noCache?: boolean;
}): Promise<ApiKeysConfig> => {
try {
const {
addressKeys,
catchAllKeys,
unverifiedKeys,
addressKTResult,
catchAllKTResult,
hasValidProtonMX,
...rest
} = await getAndVerifyApiKeys({
api,
email,
internalKeysOnly,
verifyOutboundPublicKeys,
skipVerificationOfExternalDomains: !includeInternalKeysWithE2EEDisabledForMail, // as we know we are in a Mail context
silence,
noCache,
});
// First we use verified internal address keys from internal recipients.
// Users with internal custom domains but with bad MX setup will not be properly identifiable if they also don't have address keys
// valid for mail encryption. For the current uses of this helper, this was deemed ok.
if (addressKeys.length > 0) {
const intendedForMailEncryption = !includeInternalKeysWithE2EEDisabledForMail;
// E2EE is disabled with external forwarding, as well as in some setups with custom addresses.
// unclear when/if it can happen that some keys have e2ee-disabled and some are not, but for now we cover the case.
const addressKeysForMailEncryption = addressKeys.filter((key) => supportsMail(key.flags));
const hasDisabledE2EEForMail = addressKeysForMailEncryption.length === 0;
if (intendedForMailEncryption && addressKeysForMailEncryption.length > 0) {
return {
publicKeys: castKeys(addressKeysForMailEncryption),
ktVerificationResult: addressKTResult,
RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL,
isCatchAll: false,
isInternalWithDisabledE2EEForMail: false,
...rest,
};
} else if (intendedForMailEncryption && hasDisabledE2EEForMail && hasValidProtonMX) {
// All keys are disabled for E2EE in mail, hence the recipient may be treated as external
return {
publicKeys: [],
RecipientType: RECIPIENT_TYPES.TYPE_EXTERNAL,
isCatchAll: false,
isInternalWithDisabledE2EEForMail: true,
ktVerificationResult: {
status: getFailedOrUnVerified(
addressKTResult?.status === KT_VERIFICATION_STATUS.VERIFICATION_FAILED
),
},
...rest,
};
} else if (!intendedForMailEncryption && (addressKeysForMailEncryption.length > 0 || hasValidProtonMX)) {
return {
publicKeys: castKeys(addressKeys), // we checked `addressKeysForMailEncryption` to determine if the recipient is internal, but we return all keys as that's requested by the caller
ktVerificationResult: addressKTResult,
RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL, // as e2ee-disabled flags are ignored, then from the perspective of the caller, this is an internal recipient
isCatchAll: false,
isInternalWithDisabledE2EEForMail: hasDisabledE2EEForMail, // unused, could also be set to undefined
...rest,
};
} // else, the recipient is believed external, and no address keys are returned
}
const keysChangedRecently = !!addressKTResult?.keysChangedRecently || !!catchAllKTResult?.keysChangedRecently;
const verificationFailed =
addressKTResult?.status === KT_VERIFICATION_STATUS.VERIFICATION_FAILED ||
catchAllKTResult?.status === KT_VERIFICATION_STATUS.VERIFICATION_FAILED;
// Then we check if there are unverified internal address keys
if (unverifiedKeys) {
const mailCapableUnverifiedInternalKeys = getMailCapableKeys(getInternalKeys(unverifiedKeys));
if (mailCapableUnverifiedInternalKeys.length != 0) {
const status = getFailedOrUnVerified(verificationFailed);
return {
publicKeys: castKeys(mailCapableUnverifiedInternalKeys),
ktVerificationResult: { status, keysChangedRecently },
RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL,
isCatchAll: false,
isInternalWithDisabledE2EEForMail: false,
...rest,
};
}
}
// Then we check if there are internal catchall keys
if (catchAllKeys) {
const mailCapableCatchAllKeys = getMailCapableKeys(catchAllKeys);
if (mailCapableCatchAllKeys.length != 0) {
const status = verificationFailed
? KT_VERIFICATION_STATUS.VERIFICATION_FAILED
: catchAllKTResult?.status;
const ktVerificationResult = catchAllKTResult ? { status: status!, keysChangedRecently } : undefined;
return {
publicKeys: castKeys(mailCapableCatchAllKeys),
ktVerificationResult,
RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL,
isCatchAll: true,
isInternalWithDisabledE2EEForMail: false,
...rest,
};
}
}
const ktVerificationResult = {
status: getFailedOrUnVerified(verificationFailed),
keysChangedRecently,
};
// Finally we check if there are external unverified keys
if (unverifiedKeys) {
const mailCapableUnverifiedExternalKeys = getMailCapableKeys(getExternalKeys(unverifiedKeys));
if (mailCapableUnverifiedExternalKeys.length != 0) {
const firstUnverifiedKey = mailCapableUnverifiedExternalKeys[0];
return {
publicKeys: castKeys([firstUnverifiedKey]),
ktVerificationResult,
RecipientType: RECIPIENT_TYPES.TYPE_EXTERNAL,
isCatchAll: false,
isInternalWithDisabledE2EEForMail: false,
...rest,
};
}
}
return {
publicKeys: [],
RecipientType: RECIPIENT_TYPES.TYPE_EXTERNAL,
ktVerificationResult,
isCatchAll: false,
isInternalWithDisabledE2EEForMail: false,
...rest,
};
} catch (error: any) {
const { data = {} } = error;
if (EMAIL_ERRORS.includes(data.Code)) {
return {
publicKeys: [],
Errors: [data.Error],
};
}
throw error;
}
};
export default getPublicKeysEmailHelperWithKT;
| 8,278 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/getPublicKeysVcardHelper.ts | import { PublicKeyReference } from '@proton/crypto';
import { CONTACT_CARD_TYPE } from '../../constants';
import { CRYPTO_PROCESSING_TYPES } from '../../contacts/constants';
import { readSigned } from '../../contacts/decrypt';
import { getKeyInfoFromProperties } from '../../contacts/keyProperties';
import { parseToVCard } from '../../contacts/vcard';
import { CANONICALIZE_SCHEME, canonicalizeEmail } from '../../helpers/email';
import { Api, PinnedKeysConfig } from '../../interfaces';
import { ContactEmail, Contact as tsContact } from '../../interfaces/contacts';
import { getContact, queryContactEmails } from '../contacts';
const getContactEmail = async (
emailAddress: string,
contactEmailsMap: { [email: string]: ContactEmail | undefined } = {},
api: Api
) => {
// Simple normalize here, internal version is to aggressive relative to contacts emails
const canonicalEmail = canonicalizeEmail(emailAddress);
if (contactEmailsMap[canonicalEmail]) {
return contactEmailsMap[canonicalEmail];
}
const { ContactEmails = [] } = await api<{ ContactEmails: ContactEmail[] }>(
queryContactEmails({ Email: canonicalEmail })
);
return ContactEmails[0];
};
/**
* Get the public keys stored in the vcard of a contact associated to a certain email address.
* Verify the signature on the contact in the process with the public keys provided
*/
const getPublicKeysVcardHelper = async (
api: Api,
emailAddress: string,
publicKeys: PublicKeyReference[],
isInternal?: boolean,
contactEmailsMap: { [email: string]: ContactEmail | undefined } = {}
): Promise<PinnedKeysConfig> => {
let isContact = false;
let isContactSignatureVerified;
let contactSignatureTimestamp;
try {
const ContactEmail = await getContactEmail(emailAddress, contactEmailsMap, api);
if (ContactEmail === undefined) {
return { pinnedKeys: [], isContact };
}
isContact = true;
// ContactEmail.Defaults flag informs if there is specific configuration in the contact for this email
if (ContactEmail.Defaults === 1) {
return { pinnedKeys: [], isContact };
}
// pick the first contact with the desired email. The API returns them ordered by decreasing priority already
const { Contact } = await api<{ Contact: tsContact }>(getContact(ContactEmail.ContactID));
// all the info we need is in the signed part
const signedCard = Contact.Cards.find(({ Type }) => Type === CONTACT_CARD_TYPE.SIGNED);
if (!signedCard) {
// contacts created by the server are not signed
return { pinnedKeys: [], isContact: !!Contact.Cards.length };
}
const { type, data: signedVcard, signatureTimestamp } = await readSigned(signedCard, { publicKeys });
isContactSignatureVerified = type === CRYPTO_PROCESSING_TYPES.SUCCESS;
contactSignatureTimestamp = signatureTimestamp;
const vCardContact = parseToVCard(signedVcard);
const emailProperty = (vCardContact.email || []).find(({ field, value }) => {
const scheme = isInternal ? CANONICALIZE_SCHEME.PROTON : CANONICALIZE_SCHEME.DEFAULT;
return (
field === 'email' &&
canonicalizeEmail(value as string, scheme) === canonicalizeEmail(emailAddress, scheme)
);
});
if (!emailProperty || !emailProperty.group) {
throw new Error('Invalid vcard');
}
return {
...(await getKeyInfoFromProperties(vCardContact, emailProperty.group)),
isContact,
isContactSignatureVerified,
contactSignatureTimestamp,
};
} catch (error: any) {
return { pinnedKeys: [], isContact, isContactSignatureVerified, contactSignatureTimestamp, error };
}
};
export default getPublicKeysVcardHelper;
| 8,279 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/localStorageWithExpiry.ts | // localStorageWithExpiry.ts
interface StoredItem {
value: string;
expiresAt: number;
}
const localStorageWithExpiry = {
storeData: (key: string, value: string, expirationInMs: number = 10 * 60 * 1000): void => {
const item: StoredItem = {
value,
expiresAt: Date.now() + expirationInMs,
};
window.localStorage.setItem(key, JSON.stringify(item));
},
getData: (key: string): string | null => {
const storedValue = window.localStorage.getItem(key);
if (storedValue) {
const { value, expiresAt }: StoredItem = JSON.parse(storedValue);
if (expiresAt > Date.now()) {
return value;
}
window.localStorage.removeItem(key);
}
return null;
},
deleteData: (key: string): void => {
window.localStorage.removeItem(key);
},
};
export default localStorageWithExpiry;
| 8,280 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/mailSettings.ts | import { CONTACT_MIME_TYPES, MIME_TYPES, PGP_SCHEMES } from '../../constants';
import { ContactPublicKeyModel, MailSettings } from '../../interfaces';
import { PACKAGE_TYPE, SIGN } from '../../mail/mailSettings';
/**
* Extract sign flag from the contact public key model and mail settings
*/
export const extractSign = (model: ContactPublicKeyModel, mailSettings: MailSettings): boolean => {
const { sign } = model;
return sign !== undefined ? sign : mailSettings.Sign === SIGN.ENABLED;
};
/**
* Extract PGP scheme from the contact public key model and mail settings
*/
export const extractScheme = (model: ContactPublicKeyModel, mailSettings: MailSettings): PGP_SCHEMES => {
const { scheme } = model;
if (scheme === PGP_SCHEMES.PGP_INLINE || scheme === PGP_SCHEMES.PGP_MIME) {
return scheme;
}
if (mailSettings.PGPScheme === PACKAGE_TYPE.SEND_PGP_INLINE) {
return PGP_SCHEMES.PGP_INLINE;
}
return PGP_SCHEMES.PGP_MIME;
};
/**
* Extract MIME type (for the composer) from the contact public key model and mail settings
*/
export const extractDraftMIMEType = (model: ContactPublicKeyModel, mailSettings: MailSettings): CONTACT_MIME_TYPES => {
const { mimeType } = model;
const sign = extractSign(model, mailSettings);
const scheme = extractScheme(model, mailSettings);
if (sign && scheme === PGP_SCHEMES.PGP_INLINE) {
return MIME_TYPES.PLAINTEXT;
}
return mimeType;
};
| 8,281 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/paginatedFetch.ts | import { Api } from '../../interfaces';
const MAX_ITERATIONS = 100;
const paginatedFetch = async <T>(
api: Api,
cb: (pageNumber: number, pageSize: number) => Promise<T[]>,
max = MAX_ITERATIONS
) => {
const pageSize = 100;
let pageNumber = 0;
let result: T[] = [];
while (pageNumber < max) {
const page = await cb(pageNumber, pageSize);
result = result.concat(page);
if (page.length !== pageSize) {
break;
}
pageNumber++;
}
return result;
};
export default paginatedFetch;
| 8,282 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/queryPages.ts | import chunk from '@proton/utils/chunk';
import { runChunksDelayed } from '../../helpers/promise';
interface Arguments {
pageSize: number;
pagesPerChunk: number;
delayPerChunk: number;
}
const queryPages = async <T extends { Total: number }>(
requestPage: (page: number, pageSize: number) => Promise<T>,
{ pageSize = 50, pagesPerChunk = 10, delayPerChunk = 100 }: Partial<Arguments> = {}
) => {
const firstPage = await requestPage(0, pageSize);
const n = Math.ceil((firstPage?.Total || 0) / pageSize) - 1; // First page already loaded
if (n <= 0) {
return [firstPage];
}
const pages = Array.from({ length: n }, (a, i) => i + 1);
const chunks = chunk(pages, pagesPerChunk);
const restPages =
chunks.length > 0 ? await runChunksDelayed(chunks, (idx) => requestPage(idx, pageSize), delayPerChunk) : [];
return [firstPage].concat(restPages);
};
export default queryPages;
| 8,283 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/refreshHandlers.ts | import { create as createMutex } from '@protontech/mutex-browser';
import { getLastRefreshDate, setLastRefreshDate } from '@proton/shared/lib/api/helpers/refreshStorage';
import { retryHandler } from '@proton/shared/lib/api/helpers/retryHandler';
import { createOnceHandler } from '@proton/shared/lib/apiHandlers';
import { OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY, RETRY_ATTEMPTS_MAX } from '@proton/shared/lib/constants';
import { HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { ApiError } from '@proton/shared/lib/fetch/ApiError';
import { getDateHeader } from '@proton/shared/lib/fetch/helpers';
import { wait } from '@proton/shared/lib/helpers/promise';
import noop from '@proton/utils/noop';
import randomIntFromInterval from '@proton/utils/randomIntFromInterval';
export const createRefreshHandlers = (refresh: (UID: string) => Promise<Response>) => {
const refreshHandlers: { [key: string]: (date: Date | undefined) => Promise<void> } = {};
const refreshHandler = (UID: string, responseDate: Date | undefined) => {
if (!refreshHandlers[UID]) {
const mutex = createMutex({ expiry: 15000 });
const getMutexLock = async (UID: string) => {
try {
await mutex.lock(UID);
return () => {
return mutex.unlock(UID).catch(noop);
};
} catch (e) {
// If getting the mutex fails, fall back to a random wait
await wait(randomIntFromInterval(100, 2000));
return () => {
return Promise.resolve();
};
}
};
/**
* Refreshing the session needs to handle multiple race conditions.
* 1) Race conditions within the context (tab). Solved by the once handler.
* 2) Race conditions within multiple contexts (tabs). Solved by the shared mutex.
*/
refreshHandlers[UID] = createOnceHandler(async (responseDate: Date = new Date()) => {
const unlockMutex = await getMutexLock(UID);
try {
const lastRefreshDate = getLastRefreshDate(UID);
if (lastRefreshDate === undefined || responseDate > lastRefreshDate) {
const result = await refresh(UID);
setLastRefreshDate(UID, getDateHeader(result.headers) || new Date());
// Add an artificial delay to ensure cookies are properly updated to avoid race conditions
await wait(50);
}
} finally {
await unlockMutex();
}
});
}
return refreshHandlers[UID](responseDate);
};
return refreshHandler;
};
export const getIsRefreshFailure = (error: ApiError) => {
// Any 4xx from the refresh call and the session is no longer valid, 429 is already handled in the refreshHandler
return error.status >= 400 && error.status <= 499;
};
/**
* Handle refresh token. Happens when the access token has expired.
* Multiple calls can fail, so this ensures the refresh route is called once.
* Needs to re-handle errors here for that reason.
*/
export const refresh = (call: () => Promise<Response>, attempts: number, maxAttempts: number): Promise<Response> => {
return call().catch((e) => {
if (attempts >= maxAttempts) {
throw e;
}
const { status, name } = e;
if (name === 'OfflineError') {
if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
throw e;
}
return wait(OFFLINE_RETRY_DELAY).then(() => refresh(call, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX));
}
if (name === 'TimeoutError') {
if (attempts > OFFLINE_RETRY_ATTEMPTS_MAX) {
throw e;
}
return refresh(call, attempts + 1, OFFLINE_RETRY_ATTEMPTS_MAX);
}
if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
return retryHandler(e).then(() => refresh(call, attempts + 1, RETRY_ATTEMPTS_MAX));
}
throw e;
});
};
| 8,284 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/refreshStorage.ts | import { encodeBase64URL } from '../../helpers/encoding';
import { getItem, removeItem, setItem } from '../../helpers/storage';
const getKey = (UID: string) => {
return encodeBase64URL(`r-${UID}`);
};
export const setLastRefreshDate = (UID: string, now: Date) => {
setItem(getKey(UID), `${+now}`);
};
export const getLastRefreshDate = (UID: string) => {
const oldString = getItem(getKey(UID));
const parsed = Number.parseInt(oldString || '', 10);
const date = new Date(parsed);
return Number.isNaN(+date) ? undefined : date;
};
export const removeLastRefreshDate = (UID: string) => {
removeItem(getKey(UID));
};
| 8,285 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/response.ts | import { API_CODES } from '../../constants';
const { GLOBAL_SUCCESS, SINGLE_SUCCESS } = API_CODES;
interface Response {
Response: { Code: number };
}
interface Responses {
Code: number;
Responses?: Response[];
}
export const allSucceded = ({ Code, Responses = [] }: Responses): boolean => {
if (Code !== GLOBAL_SUCCESS) {
return false;
}
return !Responses.some(({ Response: { Code } }) => Code !== SINGLE_SUCCESS);
};
| 8,286 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/retryHandler.ts | import { RETRY_DELAY_MAX } from '@proton/shared/lib/constants';
import { ApiError } from '@proton/shared/lib/fetch/ApiError';
import { wait } from '@proton/shared/lib/helpers/promise';
export const retryHandler = (e: ApiError, maxDelay = RETRY_DELAY_MAX) => {
const headers = e?.response?.headers;
const retryAfterSeconds = parseInt(headers?.get('retry-after') || '0', 10);
if (retryAfterSeconds < 0 || retryAfterSeconds >= maxDelay) {
return Promise.reject(e);
}
return wait(retryAfterSeconds * 1000);
};
| 8,287 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/safeApiRequests.ts | /**
* Process multiple requests involving API calls safely to avoid getting jailed
*/
export const processApiRequestsSafe = <T>(
promisesGenerators: (() => Promise<T>)[],
maxConcurrentPerInterval = 10,
intervalInMilliseconds = 1000
): Promise<T[]> => {
const queue = [...promisesGenerators];
let results: Promise<T>[] = [];
return new Promise((resolve) => {
const run = () => {
const callbacks = queue.splice(0, maxConcurrentPerInterval);
const promises = callbacks.map((cb) => cb());
results = results.concat(promises);
if (queue.length) {
setTimeout(run, intervalInMilliseconds);
} else {
resolve(Promise.all(results));
}
};
run();
});
};
| 8,288 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/snoozeSort.ts | import { MAILBOX_LABEL_IDS } from '../../constants';
// The sort order needs to be changed if the user is in the snoozed or inbox folder
export const getAppropriateSort = (LabelID?: string | string[], Sort?: string) => {
return LabelID &&
!Array.isArray(LabelID) &&
[MAILBOX_LABEL_IDS.SNOOZED.toString(), MAILBOX_LABEL_IDS.INBOX.toString()].includes(LabelID)
? 'SnoozeTime'
: Sort ?? 'Time';
};
| 8,289 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api | petrpan-code/ProtonMail/WebClients/packages/shared/lib/api/helpers/withApiHandlers.js | import { setRefreshCookies } from '@proton/shared/lib/api/auth';
import { OFFLINE_RETRY_ATTEMPTS_MAX, OFFLINE_RETRY_DELAY, RETRY_ATTEMPTS_MAX } from '../../constants';
import { API_CUSTOM_ERROR_CODES, HTTP_ERROR_CODES } from '../../errors';
import {
getDeviceVerificationHeaders,
getUIDHeaderValue,
getVerificationHeaders,
withUIDHeaders,
} from '../../fetch/headers';
import { getDateHeader } from '../../fetch/helpers';
import { wait } from '../../helpers/promise';
import { getApiError } from './apiErrorHelper';
import { createDeviceHandlers } from './deviceVerificationHandler';
import { createRefreshHandlers, getIsRefreshFailure, refresh } from './refreshHandlers';
import { retryHandler } from './retryHandler';
export const InactiveSessionError = () => {
const error = new Error('Inactive session');
error.name = 'InactiveSession';
return error;
};
export const AppVersionBadError = () => {
const error = new Error('App version outdated');
error.name = 'AppVersionBadError';
return error;
};
/**
* Attach a catch handler to every API call to handle 401, 403, and other errors.
* @param {function} call
* @param {string} UID
* @param {function} onMissingScopes
* @param {function} onVerification
* @return {function}
*/
export default ({ call, UID, onMissingScopes, onVerification }) => {
let loggedOut = false;
let appVersionBad = false;
const refreshHandler = createRefreshHandlers((UID) => {
return refresh(() => call(withUIDHeaders(UID, setRefreshCookies())), 1, RETRY_ATTEMPTS_MAX);
});
const deviceVerificationHandler = createDeviceHandlers();
return (options) => {
const perform = (attempts, maxAttempts) => {
if (loggedOut) {
return Promise.reject(InactiveSessionError());
}
if (appVersionBad) {
return Promise.reject(AppVersionBadError());
}
return call(options).catch((e) => {
if (loggedOut) {
throw InactiveSessionError();
}
if (maxAttempts && attempts >= maxAttempts) {
throw e;
}
const { status, name, response } = e;
const {
ignoreHandler,
silence = [],
headers,
retriesOnOffline = OFFLINE_RETRY_ATTEMPTS_MAX,
retriesOnTimeout = OFFLINE_RETRY_ATTEMPTS_MAX,
} = options || {};
if (name === 'OfflineError') {
if (attempts > retriesOnOffline) {
throw e;
}
return wait(OFFLINE_RETRY_DELAY).then(() => perform(attempts + 1, retriesOnOffline));
}
if (name === 'TimeoutError') {
if (attempts > retriesOnTimeout) {
throw e;
}
return perform(attempts + 1, retriesOnTimeout);
}
const ignoreUnauthorized =
Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNAUTHORIZED);
const requestUID = getUIDHeaderValue(headers) ?? UID;
// Sending a request with a UID but without an authorization header is when the public app makes
// authenticated requests (mostly for persisted sessions), and ignoring "login" or "signup" requests.
if (
status === HTTP_ERROR_CODES.UNAUTHORIZED &&
!ignoreUnauthorized &&
(UID || (requestUID && !headers?.Authorization))
) {
return refreshHandler(requestUID, getDateHeader(response && response.headers)).then(
() => perform(attempts + 1, RETRY_ATTEMPTS_MAX),
(error) => {
if (getIsRefreshFailure(error)) {
// Disable any further requests on this session if it was created with a UID and the request was done with the failing UID
if (UID && requestUID === UID) {
loggedOut = true;
// Inactive session error is only thrown when this error was caused by a logged in session requesting through the same UID
// to have a specific error consumers can use
throw InactiveSessionError();
}
// The original 401 error is thrown to make it more clear that this auth & refresh failure
// was caused by an original auth failure and consumers can just check for 401 instead of 4xx
throw e;
}
// Otherwise, this is not actually an authentication error, it might have failed because the API responds with 5xx, or because the client is offline etc
// and as such the error from the refresh call is thrown
throw error;
}
);
}
const ignoreUnlock = Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.UNLOCK);
if (status === HTTP_ERROR_CODES.UNLOCK && !ignoreUnlock) {
const { Details: { MissingScopes: missingScopes = [] } = {} } = e.data || {};
return onMissingScopes({
scopes: missingScopes,
error: e,
options,
});
}
const ignoreTooManyRequests =
Array.isArray(ignoreHandler) && ignoreHandler.includes(HTTP_ERROR_CODES.TOO_MANY_REQUESTS);
if (status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS && !ignoreTooManyRequests) {
return retryHandler(e).then(() => perform(attempts + 1, RETRY_ATTEMPTS_MAX));
}
const { code } = getApiError(e);
if (code === API_CUSTOM_ERROR_CODES.APP_VERSION_BAD) {
appVersionBad = true;
throw AppVersionBadError();
}
const ignoreHumanVerification =
Array.isArray(ignoreHandler) &&
ignoreHandler.includes(API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED);
if (code === API_CUSTOM_ERROR_CODES.HUMAN_VERIFICATION_REQUIRED && !ignoreHumanVerification) {
const {
Details: {
HumanVerificationToken: captchaToken,
HumanVerificationMethods: methods = [],
Title: title,
} = {},
} = e.data || {};
const onVerify = (token, tokenType) => {
return call({
...options,
silence:
silence === true
? true
: [
...(Array.isArray(silence) ? silence : []),
API_CUSTOM_ERROR_CODES.TOKEN_INVALID,
],
headers: {
...options.headers,
...getVerificationHeaders(token, tokenType),
},
});
};
return onVerification({ token: captchaToken, methods, onVerify, title }, e);
}
const ignoreDeviceVerification =
Array.isArray(ignoreHandler) &&
ignoreHandler.includes(API_CUSTOM_ERROR_CODES.DEVICE_VERIFICATION_REQUIRED);
if (code === API_CUSTOM_ERROR_CODES.DEVICE_VERIFICATION_REQUIRED && !ignoreDeviceVerification) {
const { Details: { ChallengeType: challengType, ChallengePayload: challengePayload } = {} } =
e.data || {};
const requestUID = getUIDHeaderValue(headers) ?? UID;
return deviceVerificationHandler(requestUID, challengType, challengePayload)
.then((result) => {
return call({
...options,
headers: {
...options.headers,
...getDeviceVerificationHeaders(result),
},
});
})
.catch((error) => {
throw error;
});
}
throw e;
});
};
return perform(1);
};
};
| 8,290 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/apps/desktopVersions.ts | import { DESKTOP_APP_NAMES, DESKTOP_PLATFORMS, RELEASE_CATEGORIES } from '@proton/shared/lib/constants';
import { getDownloadUrl } from '@proton/shared/lib/helpers/url';
export interface Props {
appName: DESKTOP_APP_NAMES;
platform: DESKTOP_PLATFORMS;
version: 'latest' | string;
category: RELEASE_CATEGORIES;
}
interface RELEASE {
CategoryName: RELEASE_CATEGORIES;
Version: string;
ReleaseDate: string;
File: {
Url: string;
Sha512CheckSum: 'string';
Args: string;
};
ReleaseNotes: {
Type: string;
Notes: string[];
}[];
}
/*
* This helper will help to fetch specific or latest version of a desktop app
* It currently only support Drive apps.
*/
export const fetchDesktopVersion = async ({
appName,
platform,
category,
version,
}: Props): Promise<
| {
url: string;
version: string;
}
| undefined
> => {
try {
const response = await fetch(getDownloadUrl(`/${appName}/${platform}/version.json`));
if (!response.ok) {
throw new Error(response.statusText);
}
const { Releases: releases }: { Releases: RELEASE[] } = await response.json();
const filteredReleases = releases.filter((release) => release.CategoryName === category);
if (!filteredReleases.length) {
return undefined;
}
if (version === 'latest') {
// We assume that latest release is always the first one
const latestRelease = filteredReleases[0];
return { url: latestRelease.File.Url, version: latestRelease.Version };
} else {
const release = filteredReleases.find((release) => release.Version === version);
if (!release) {
return undefined;
}
return { url: release.File.Url, version: release.Version };
}
} catch (e: any) {
throw Error(`Failed to fetch ${appName} ${platform}@${version} app's url`, {
cause: e,
});
}
};
| 8,291 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/apps/helper.ts | import window from '@proton/shared/lib/window';
import isTruthy from '@proton/utils/isTruthy';
import { getLocalIDPath, stripLocalBasenameFromPathname } from '../authentication/pathnameHelper';
import { APPS, APPS_CONFIGURATION, APP_NAMES, EXTENSIONS, VPN_HOSTNAME } from '../constants';
import { isMac, isWindows } from '../helpers/browser';
import { isElectronApp } from '../helpers/desktop';
import { stripLeadingAndTrailingSlash } from '../helpers/string';
interface TargetLocation {
hostname: string;
protocol: string;
port: string;
}
const getSSOAppTargetLocation = (location: TargetLocation = window.location): TargetLocation => {
if (location.hostname === VPN_HOSTNAME) {
return {
hostname: 'proton.me',
protocol: 'https:',
port: '',
};
}
return location;
};
export const getAppHref = (
to: string,
toApp: APP_NAMES,
localID?: number,
targetLocation: TargetLocation = window.location
) => {
const { subdomain: targetSubdomain } = APPS_CONFIGURATION[toApp];
const { hostname, protocol, port } = getSSOAppTargetLocation(targetLocation);
const lastIndex = hostname.lastIndexOf('.');
const secondLevelIndex = hostname.indexOf('.');
// If there's no second level, just use the original hostname. NOTE: Does not work for tlds as .co.uk
const secondLevelDomain = lastIndex !== secondLevelIndex ? hostname.substr(secondLevelIndex + 1) : hostname;
const targetDomain = [targetSubdomain, secondLevelDomain].filter(isTruthy).join('.');
const targetPort = port.length > 0 ? `:${port}` : '';
const path = [
targetDomain + targetPort,
stripLeadingAndTrailingSlash(''),
getLocalIDPath(localID),
stripLeadingAndTrailingSlash(stripLocalBasenameFromPathname(to)),
]
.filter(isTruthy)
.join('/');
return `${protocol}//${path}`;
};
export const getAppHrefBundle = (to: string, toApp: APP_NAMES) => {
const path = [APPS_CONFIGURATION[toApp].publicPath, to]
.map(stripLeadingAndTrailingSlash)
.filter(isTruthy)
.join('/');
return `/${path}`;
};
export const getAccountSettingsApp = () => APPS.PROTONACCOUNT;
export const getClientID = (appName: APP_NAMES) => {
const config = APPS_CONFIGURATION[appName];
const isElectron = isElectronApp();
let apiClientID = config.webClientID ?? config.clientID ?? '';
if (isElectron) {
if (isWindows()) {
apiClientID = config.windowsClientID ?? apiClientID;
} else if (isMac()) {
apiClientID = config.macosClientID ?? apiClientID;
}
}
return apiClientID;
};
export const getExtension = (appName: APP_NAMES) => {
return EXTENSIONS[appName as keyof typeof EXTENSIONS];
};
export const getAppName = (appName: APP_NAMES) => {
return APPS_CONFIGURATION[appName].name;
};
export const getAppShortName = (appName: APP_NAMES) => {
return APPS_CONFIGURATION[appName].bareName;
};
export const getInvoicesPathname = () => {
return '/dashboard#invoices';
};
| 8,292 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/apps/product.ts | import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { captureMessage } from '../helpers/sentry';
export const otherProductParamValues = ['generic', 'business'] as const;
export type OtherProductParam = (typeof otherProductParamValues)[number];
export type ProductParam = APP_NAMES | OtherProductParam | undefined;
export const normalizeProduct = (product: ProductParam) => {
if (!product) {
return;
}
// Converts:
// proton-mail -> mail
// proton-vpn-settings -> vpn
if (product === APPS.PROTONVPN_SETTINGS) {
return 'vpn';
}
return product.replace('proton-', '');
};
export interface ProductHeaderContext {
endpoint?: string;
product?: any;
emptyProduct?: boolean;
}
function notifySentry(normalizedProduct: string | undefined, context?: ProductHeaderContext) {
const isAllowed = ['generic', 'mail', 'drive', 'calendar', 'vpn', 'business', 'pass'].includes(
'' + normalizedProduct
);
if (!isAllowed) {
captureMessage('Wrong product header', { level: 'error', extra: { normalizedProduct, context } });
}
}
export const getProductHeaders = (product: ProductParam, context?: ProductHeaderContext) => {
if (!product) {
notifySentry(undefined, {
...context,
emptyProduct: true,
});
return;
}
const normalizedProduct = normalizeProduct(product);
notifySentry(normalizedProduct, context);
return { 'x-pm-product': normalizedProduct };
};
| 8,293 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/apps/slugHelper.ts | import { stripLocalBasenameFromPathname } from '../authentication/pathnameHelper';
import { APPS, APPS_CONFIGURATION, APP_NAMES } from '../constants';
import { stripLeadingAndTrailingSlash } from '../helpers/string';
export const DEFAULT_APP = APPS.PROTONMAIL;
export const ALLOWED_APPS = [
APPS.PROTONMAIL,
APPS.PROTONCALENDAR,
APPS.PROTONCONTACTS,
APPS.PROTONVPN_SETTINGS,
APPS.PROTONDRIVE,
APPS.PROTONPASS,
];
export const getSlugFromApp = (app: APP_NAMES) => APPS_CONFIGURATION[app].settingsSlug;
export const getAppFromPathname = (pathname: string): APP_NAMES | undefined => {
return ALLOWED_APPS.find((appName) => {
const slug = getSlugFromApp(appName);
// Expects a trimmed string
return pathname.match(`^${slug}(/|$)`);
});
};
export const getAppFromHostname = (hostname: string): APP_NAMES | undefined => {
return ALLOWED_APPS.find((appName) => {
const slug = getSlugFromApp(appName);
return hostname.match(`^${slug}\.`);
});
};
export const getAppFromPathnameSafe = (pathname: string) => {
const trimmedPathname = stripLeadingAndTrailingSlash(stripLocalBasenameFromPathname(pathname));
return getAppFromPathname(trimmedPathname);
};
export const ALLOWED_SLUGS = ALLOWED_APPS.map((app) => APPS_CONFIGURATION[app].settingsSlug);
export type AppSlug = (typeof ALLOWED_SLUGS)[number];
export const stripSlugFromPathname = (pathname: string) => {
return pathname.replace(new RegExp(`/(${ALLOWED_SLUGS.join('|')})`), '');
};
| 8,294 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/ForkInterface.ts | export enum FORK_TYPE {
SWITCH = '1',
// Used in VPN extension
SIGNUP = '2',
}
export interface Extension {
ID: string;
}
| 8,295 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/SessionInterface.ts | export interface PersistedSessionBlob {
keyPassword: string;
}
export interface PersistedSession {
UserID: string;
UID: string;
blob?: string;
isSubUser: boolean;
persistent: boolean;
trusted: boolean;
}
export interface PersistedSessionWithLocalID extends PersistedSession {
localID: number;
}
| 8,296 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/apps.ts | import { DEFAULT_APP } from '@proton/shared/lib/apps/slugHelper';
import { User } from '@proton/shared/lib/interfaces';
import { getIsExternalAccount, getIsVPNOnlyAccount } from '@proton/shared/lib/keys';
import { APPS, APPS_CONFIGURATION, APP_NAMES, CLIENT_TYPES, PRODUCT_BIT } from '../constants';
export const getToAppName = (toApp?: APP_NAMES) => {
if (!toApp || toApp === APPS.PROTONACCOUNT) {
return '';
}
return APPS_CONFIGURATION[toApp]?.name || '';
};
export const vpnApps = [APPS.PROTONVPN_SETTINGS, APPS.PROTONVPNBROWSEREXTENSION];
export const passApps = [APPS.PROTONPASS, APPS.PROTONEXTENSION, APPS.PROTONPASSBROWSEREXTENSION];
export const externalApps = [...vpnApps, APPS.PROTONDRIVE, ...passApps];
export const requiresProtonAddress: APP_NAMES[] = [APPS.PROTONMAIL, APPS.PROTONCALENDAR];
export const requiresAddress: APP_NAMES[] = [...requiresProtonAddress, APPS.PROTONDRIVE, ...passApps];
export const requiresNonDelinquent: APP_NAMES[] = [
APPS.PROTONMAIL,
APPS.PROTONCONTACTS,
APPS.PROTONCALENDAR,
APPS.PROTONDRIVE,
];
export const getHasAppExternalSignup = (toApp?: APP_NAMES) => {
return externalApps.includes(toApp as any);
};
export const getIsPassApp = (toApp?: APP_NAMES) => {
return passApps.includes(toApp as any);
};
export const getIsVPNApp = (toApp?: APP_NAMES, clientType?: CLIENT_TYPES) => {
return vpnApps.includes(toApp as any) || clientType === CLIENT_TYPES.VPN;
};
export const getIsMailApp = (toApp?: APP_NAMES) => {
return toApp === APPS.PROTONMAIL;
};
export const getIsCalendarApp = (toApp?: APP_NAMES) => {
return toApp === APPS.PROTONCALENDAR;
};
export const getIsDriveApp = (toApp?: APP_NAMES) => {
return toApp === APPS.PROTONDRIVE;
};
export const getRequiresAddress = (toApp: APP_NAMES) => {
return requiresAddress.includes(toApp);
};
export const getRequiresProtonAddress = (toApp: APP_NAMES) => {
return requiresProtonAddress.includes(toApp);
};
export const getToApp = (toApp: APP_NAMES | undefined, user: User) => {
if (toApp) {
return toApp;
}
if (user.Flags.sso || getIsVPNOnlyAccount(user)) {
return APPS.PROTONVPN_SETTINGS;
}
if (getIsExternalAccount(user)) {
const { Subscribed } = user;
if (Subscribed === PRODUCT_BIT.VPN) {
return APPS.PROTONVPN_SETTINGS;
}
if (Subscribed === PRODUCT_BIT.PASS) {
return APPS.PROTONPASS;
}
// VPN and Pass bundle
if (Subscribed === (PRODUCT_BIT.VPN | PRODUCT_BIT.PASS)) {
return APPS.PROTONVPN_SETTINGS;
}
return APPS.PROTONDRIVE;
}
return DEFAULT_APP;
};
| 8,297 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/authentication.ts | import createAuthentication from './createAuthenticationStore';
import createSecureSessionStorage from './createSecureSessionStorage';
const authentication = createAuthentication(createSecureSessionStorage());
export default authentication;
| 8,298 |
0 | petrpan-code/ProtonMail/WebClients/packages/shared/lib | petrpan-code/ProtonMail/WebClients/packages/shared/lib/authentication/createAuthenticationStore.ts | import { decodeUtf8Base64, encodeUtf8Base64 } from '@proton/crypto/lib/utils';
import { LOCAL_ID_KEY, MAILBOX_PASSWORD_KEY, PERSIST_SESSION_KEY, TRUST_SESSION_KEY, UID_KEY } from '../constants';
interface Arguments {
set: (key: string, value: any) => void;
get: (key: string) => any;
}
const createAuthenticationStore = ({ set, get }: Arguments) => {
const setUID = (UID: string | undefined) => set(UID_KEY, UID);
const getUID = (): string => get(UID_KEY);
const setPassword = (password: string | undefined) => {
if (password === undefined) {
set(MAILBOX_PASSWORD_KEY, password);
return;
}
set(MAILBOX_PASSWORD_KEY, encodeUtf8Base64(password));
};
const getPassword = () => {
const value: string | undefined = get(MAILBOX_PASSWORD_KEY);
if (value === undefined) {
return '';
}
return decodeUtf8Base64(value);
};
const setLocalID = (LocalID: number | undefined) => set(LOCAL_ID_KEY, LocalID);
const getLocalID = () => get(LOCAL_ID_KEY);
const hasSession = () => !!getUID();
const setPersistent = (persist: boolean | undefined) => set(PERSIST_SESSION_KEY, persist);
// Keep old default behavior
const getPersistent = () => get(PERSIST_SESSION_KEY) ?? true;
const setTrusted = (trusted: boolean | undefined) => set(TRUST_SESSION_KEY, trusted);
const getTrusted = () => get(TRUST_SESSION_KEY) ?? false;
return {
getUID,
setUID,
setLocalID,
getLocalID,
hasSession,
setPassword,
getPassword,
setPersistent,
getPersistent,
setTrusted,
getTrusted,
};
};
export type AuthenticationStore = ReturnType<typeof createAuthenticationStore>;
export default createAuthenticationStore;
| 8,299 |
Subsets and Splits