feat: release OTP and Passkey Tools 0.1.0

This commit is contained in:
2026-08-19 12:19:35 +02:00
commit c435c6a626
67 changed files with 12802 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules/
dist/
release/*.zip
release/*.zip.sha256
coverage/
playwright-report/
test-results/
*.tsbuildinfo
.DS_Store
+2
View File
@@ -0,0 +1,2 @@
@add-ideas:registry=https://git.add-ideas.de/api/packages/lotobo/npm/
always-auth=false
+11
View File
@@ -0,0 +1,11 @@
# Changelog
All notable changes are documented here.
## 0.1.0 - 2026-08-19
- Initial HOTP, TOTP and OCRA credential laboratory with official RFC-vector coverage.
- Added strict provisioning URI handling, local QR generation/image detection, Google migration, CSV, URI-list and plain-secret PSKC workflows.
- Added bounded WebAuthn CBOR/client/authenticator/attestation inspection and layered assertion verification.
- Added origin-gated, memory-only WebAuthn registration/authentication lab and browser capability diagnostics.
- Added Toolbox SDK 0.2.3 integration, responsive light/dark/system UI, reproducible release packaging, source identity and security/licence documentation.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2009 Kazuhiko Arase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
# Licence inventory
OTP & Passkey Tools is `GPL-3.0-or-later`; the full project licence is at `../LICENSE`.
`THIRD_PARTY_NOTICES.md` identifies shipped packages and adapted algorithms. Release preparation collates the exact installed runtime package licence files into `npm-runtime-licenses.txt`. `QRCode-MIT.txt` preserves the licence for the QR construction algorithm rewritten in this project.
+71
View File
@@ -0,0 +1,71 @@
# OTP & Passkey Tools
A production-oriented, local-first browser workbench for OTP credentials and WebAuthn/passkey evidence. It is part of the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal), but its release ZIP also runs as a standalone static application.
Authentication material stays in the active tab. The application has no backend, telemetry, automatic network lookup, service worker, cookie, local-storage credential store, or IndexedDB database.
## Included in 0.1.0
- RFC 4226 HOTP and RFC 6238 TOTP generation and bounded diagnostic verification using SHA-1, SHA-256 or SHA-512, with exact 64-bit counters and preserved leading zeroes.
- Strict `otpauth://` parsing/serialization, random secret generation, masked values, interoperability findings, live period display and a project-owned QR encoder.
- RFC 6287 OCRA-1 suite parsing and computation for counter, numeric/alphanumeric/hex challenge, PIN/password hash, session and timestamp inputs. Official RFC interoperability vectors cover SHA-1, SHA-256 and SHA-512 paths.
- Import of line-delimited provisioning URIs, Google Authenticator migration QR payloads, the documented CSV shape and RFC 6030 PSKC files containing plain secrets. Encrypted PSKC is rejected rather than guessed.
- Explicit URI-list and CSV export with an unencrypted-secret warning.
- Bounded CBOR, `clientDataJSON`, authenticator-data and attestation-object inspection, including flags, RP ID hash, counter, AAGUID, credential ID, COSE key and extensions.
- Layered assertion verification for challenge, origin, cross-origin state, RP ID hash, user presence/verification, signature counter, and ES256, RS256, PS256 or Ed25519 signatures.
- Serializable registration/request option examples, browser capability diagnostics and an ephemeral in-memory live ceremony lab.
## Security boundary
The Toolbox app at `/apps/auth/` is deliberately **inspect-only for live WebAuthn ceremonies**. Every app under `toolbox.add-ideas.de` shares one browser origin and therefore one WebAuthn relying-party namespace. Credential creation/authentication is enabled only on localhost or the dedicated origin:
```text
https://auth.toolbox.add-ideas.de/
```
The same immutable release can be served there, top-level, with RP ID `auth.toolbox.add-ideas.de`. The RP ID is never widened to `add-ideas.de`, and arbitrary RP IDs can only be inspected offline.
Raw CTAP/token administration is not claimed: browsers expose ordinary WebAuthn but block the FIDO HID usage page from WebHID. Camera and USB permissions are not requested. QR images can be selected locally when the browser implements `BarcodeDetector`; provisioning text can always be pasted.
See [SECURITY.md](SECURITY.md) for the threat model and limitations.
## Develop and verify
Requirements: Node.js 22+, npm 11, and `zip` for deterministic release packaging.
```sh
npm ci
npm run check
npm run test:browser
npm run package:release
```
The Vite base is relative, so both `/` and nested paths work. `npm run toolbox:check` validates the built manifest and its assets.
## Static deployment
Serve `dist/` or the contents of `release/auth-tools-0.1.0.zip` over HTTPS. Recommended response headers:
```text
Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; worker-src 'self' blob:; manifest-src 'self'
Permissions-Policy: camera=(), microphone=(), geolocation=(), usb=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
```
For Portal integration, pin the immutable Gitea release ZIP and SHA-256 in `toolbox-portal/release/toolbox.lock.json` with target `auth`.
## Deliberate limits
- This is an engineering and interoperability workbench, not a certified authenticator, relying-party server, password manager, FIDO certification tool or recovery system.
- Live credentials are forgotten on reload and cannot be exported by WebAuthn design.
- Attestation structures are decoded, but 0.1.0 does not establish attestation trust or silently download FIDO Metadata Service data. Assertion signatures are verified only with the explicitly supplied/created credential key.
- Google multi-QR batches must all be supplied; the current UI reviews one payload at a time. Google migration export and encrypted PSKC decryption are not claimed.
- CSV and URI exports contain raw OTP seeds. There is no encrypted vault format in this app.
- QR generation supports byte-mode error-correction M through version 10. Larger provisioning records remain available as text exports.
## Licence
`GPL-3.0-or-later`. See [LICENSE](LICENSE), [SOURCE.md](SOURCE.md), and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+40
View File
@@ -0,0 +1,40 @@
# Security model
## Data flow
All inputs are processed in the browser tab. There are no application `fetch`, WebSocket, beacon, analytics, service-worker, credential-storage or remote-metadata paths. OTP secrets, OCRA PIN input, imported files, WebAuthn responses and live test credential metadata are React/session memory and disappear on reload or **Clear session**.
Downloads and clipboard writes require a user action. Exports are not encrypted. The UI masks OTP secrets and provisioning URIs by default, but masking is not memory protection.
## Trust boundaries
- The static release and its hosting origin are trusted code. A compromised host can alter JavaScript and steal subsequently entered material; verify the release SHA-256 when this matters.
- Imported URIs, CSV, XML, protobuf, JSON, Base64url and CBOR are untrusted. Size/depth/count limits are applied before or during decoding. Imported text is rendered by React, never as markup. The only generated markup insertion is the project-owned QR SVG serializer, which receives an already serialized provisioning URI and emits path coordinates only.
- WebAuthn client data is verified as exact strings/bytes. Origins and RP IDs are not suffix-matched. The expected challenge is caller-supplied ceremony state; the tool cannot prove that a server generated or consumed it once.
- Signature verification establishes consistency with the supplied COSE public key, not account ownership or attestation trust.
## Origin isolation
`toolbox.add-ideas.de/apps/auth/` shares an origin with every other Portal app. Live registration/assertion is therefore disabled there. It is enabled only for localhost development or exact host `auth.toolbox.add-ideas.de`. Deploy the dedicated host top-level with `frame-ancestors 'none'`; do not change its RP ID to the parent domain.
## Cryptography
HMAC, digest, random generation, public-key import and signature verification use the browser Web Cryptography API. No custom cryptographic primitive is implemented. OTP dynamic truncation and OCRA data-input assembly are project code covered by RFC vectors.
SHA-1 remains available only where HOTP/TOTP/OCRA interoperability standards require it; it is used inside HMAC or as an explicitly selected OCRA PIN digest, not as a collision-resistant document signature.
## Parser limits
- Provisioning URI: 16 KiB.
- Migration/CSV/PSKC input: 4 MiB.
- Google protobuf: bounded input, varints at most 10 bytes, supported wire types only.
- CBOR: 4 MiB, depth 32, 10,000 items, definite lengths only, duplicate map keys rejected.
- OTP secret: 1 KiB; random generation: 161,024 bytes.
- Verification windows: TOTP 100 steps maximum; HOTP 10,000 counters maximum.
- QR encoder: version 10 maximum.
## Not a vault or identity provider
Do not use this app as the only copy of a credential. It does not offer encrypted persistence, recovery codes, account recovery, server-side challenge state, rate limiting, audit logging, device attestation policy, FIDO certification, or phishing protection outside normal browser WebAuthn behavior.
Report vulnerabilities through the repository issue tracker without including real secrets or production assertions.
+31
View File
@@ -0,0 +1,31 @@
# Corresponding source and provenance
The corresponding source for OTP & Passkey Tools 0.1.0 will be published at:
https://git.add-ideas.de/lotobo/auth-tools/src/tag/v0.1.0
Build that tag with Node.js 22 and the exact `package-lock.json`:
```sh
npm ci
npm run release:artifact
```
No generated bundle is the preferred source form. No runtime code, metadata or cryptographic service is loaded from a CDN.
## Standards and revisions used
| Source | Revision | Use |
| -------------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------- |
| Toolbox SDK | `ef2dab4b46c61812c9a877d8a19fe497b4a4630a`, packages 0.2.3 | manifest, context, shell and build checks |
| Toolbox Portal | `5ed7134d42f0b563bc47a1572107ea94994dfe3c`, tag v0.10.0 | release and UX integration contract |
| RFC 4226 | December 2005 | HOTP semantics and vectors |
| RFC 6238 | May 2011 | TOTP semantics and vectors |
| RFC 6287 | June 2011 | OCRA suite grammar, semantics and vectors |
| RFC 6030 | October 2010 | bounded plain-secret PSKC import |
| Google Authenticator migration protobuf | observed public interchange schema | local import only; unknown fields are skipped safely |
| Web Authentication | W3C WebAuthn Level 3 Recommendation, 13 January 2026 | client/authenticator structures and ceremony expectations |
| RFC 8949 / RFC 9052 / RFC 8152 registrations | published versions | bounded CBOR and COSE key interpretation |
| QR Code for JavaScript | Kazuhiko Arase, 2009 | QR construction algorithm rewritten in TypeScript under MIT terms |
The OCRA implementation was authored from the normative RFC definition and tested with its published interoperability values; the RFC Java reference implementation is not included. The QR module is an acknowledged clean TypeScript rewrite of the MIT-licensed construction algorithm, with deliberately bounded version support.
+24
View File
@@ -0,0 +1,24 @@
# Third-party notices
The release preparation step collates licence files for the exact locked runtime packages into `LICENSES/npm-runtime-licenses.txt` inside the static artifact.
## Direct runtime packages
| Package | Version | Licence | Role | Source |
| -------------------------------- | ------- | ---------- | ------------------------------- | ------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | manifest and context contract | https://git.add-ideas.de/lotobo/toolbox-sdk |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | shared shell, theme and actions | https://git.add-ideas.de/lotobo/toolbox-sdk |
| `react` | 19.2.6 | MIT | application UI | https://github.com/facebook/react |
| `react-dom` | 19.2.6 | MIT | browser rendering | https://github.com/facebook/react |
`scheduler`, distributed by the React project under MIT, is the only transitive runtime package.
## QR construction
`src/qr/encoder.ts` is a bounded TypeScript rewrite following the QRCode for JavaScript construction algorithm by Kazuhiko Arase (copyright 2009), used under the MIT License. The licence text is in `LICENSES/QRCode-MIT.txt`. The rewrite supports byte mode, error correction M, versions 110, and contains no upstream branding or UI.
## Standards material
RFC interoperability values are facts used as tests. The OCRA implementation is project-authored from RFC 6287; its Java reference implementation is not shipped. W3C WebAuthn, IETF CBOR/COSE and OTP specifications are implementation references, not bundled runtime software.
Development-only packages listed in `package-lock.json` build and test the source but are not shipped as runtime modules.
+40
View File
@@ -0,0 +1,40 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
ignores: [
"dist",
"release",
"coverage",
"test-results",
"playwright-report",
],
},
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2023,
globals: { ...globals.browser, ...globals.worker },
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
},
{
files: ["scripts/**/*.mjs", "playwright.config.ts"],
languageOptions: { globals: globals.node },
},
);
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="Inspect and test OTP and WebAuthn authentication locally in your browser."
/>
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
<title>OTP &amp; Passkey Tools</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
+4084
View File
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
{
"name": "auth-tools",
"version": "0.1.0",
"description": "Inspect and test OTP and WebAuthn authentication locally in the browser.",
"license": "GPL-3.0-or-later",
"author": "Albrecht Degering",
"repository": {
"type": "git",
"url": "git+https://git.add-ideas.de/lotobo/auth-tools.git"
},
"homepage": "https://git.add-ideas.de/lotobo/auth-tools",
"bugs": {
"url": "https://git.add-ideas.de/lotobo/auth-tools/issues"
},
"private": true,
"type": "module",
"engines": {
"node": ">=22"
},
"scripts": {
"predev": "npm run manifest:generate",
"dev": "vite",
"prebuild": "npm run release:prepare && npm run manifest:generate",
"build": "tsc -b && vite build",
"preview": "vite preview",
"typecheck": "tsc -b --pretty false",
"lint": "eslint . --max-warnings=0",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "vitest run",
"test:watch": "vitest",
"test:browser": "playwright test",
"manifest:generate": "node scripts/generate-toolbox-manifest.mjs",
"manifest:check": "node scripts/generate-toolbox-manifest.mjs --check",
"release:prepare": "node scripts/prepare-release-files.mjs",
"toolbox:check": "toolbox-check dist",
"package:release": "node scripts/package-release.mjs",
"check": "npm run manifest:check && npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build && npm run toolbox:check",
"release:artifact": "npm run check && npm run test:browser && npm run package:release -- --force"
},
"dependencies": {
"@add-ideas/toolbox-contract": "0.2.3",
"@add-ideas/toolbox-shell-react": "0.2.3",
"react": "19.2.6",
"react-dom": "19.2.6"
},
"devDependencies": {
"@add-ideas/toolbox-testkit": "0.2.3",
"@eslint/js": "10.0.1",
"@playwright/test": "1.61.1",
"@testing-library/jest-dom": "6.9.1",
"@testing-library/react": "16.3.2",
"@testing-library/user-event": "14.6.1",
"@types/node": "25.8.0",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "6.0.2",
"eslint": "10.4.0",
"eslint-plugin-react-hooks": "7.1.1",
"eslint-plugin-react-refresh": "0.5.2",
"fast-check": "4.9.0",
"globals": "17.6.0",
"jsdom": "29.1.1",
"prettier": "3.8.3",
"typescript": "6.0.3",
"typescript-eslint": "8.59.3",
"vite": "8.2.0",
"vitest": "4.1.6"
},
"packageManager": "npm@11.17.0"
}
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/browser",
fullyParallel: false,
workers: 2,
timeout: 120_000,
expect: { timeout: 10_000 },
reporter: [["list"]],
use: {
baseURL: "http://127.0.0.1:4173",
trace: "retain-on-failure",
},
webServer: {
command: "npm run build && node scripts/serve-test.mjs",
url: "http://127.0.0.1:4173",
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
],
});
+11
View File
@@ -0,0 +1,11 @@
# Changelog
All notable changes are documented here.
## 0.1.0 - 2026-08-19
- Initial HOTP, TOTP and OCRA credential laboratory with official RFC-vector coverage.
- Added strict provisioning URI handling, local QR generation/image detection, Google migration, CSV, URI-list and plain-secret PSKC workflows.
- Added bounded WebAuthn CBOR/client/authenticator/attestation inspection and layered assertion verification.
- Added origin-gated, memory-only WebAuthn registration/authentication lab and browser capability diagnostics.
- Added Toolbox SDK 0.2.3 integration, responsive light/dark/system UI, reproducible release packaging, source identity and security/licence documentation.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2009 Kazuhiko Arase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
# Licence inventory
OTP & Passkey Tools is `GPL-3.0-or-later`; the full project licence is at `../LICENSE`.
`THIRD_PARTY_NOTICES.md` identifies shipped packages and adapted algorithms. Release preparation collates the exact installed runtime package licence files into `npm-runtime-licenses.txt`. `QRCode-MIT.txt` preserves the licence for the QR construction algorithm rewritten in this project.
+486
View File
@@ -0,0 +1,486 @@
==============================================================================
@add-ideas/toolbox-contract@0.2.3
Declared licence: Apache-2.0
Installed from: node_modules/@add-ideas/toolbox-contract
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
@add-ideas/toolbox-shell-react@0.2.3
Declared licence: Apache-2.0
Installed from: node_modules/@add-ideas/toolbox-shell-react
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
react@19.2.6
Declared licence: MIT
Installed from: node_modules/react
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
react-dom@19.2.6
Declared licence: MIT
Installed from: node_modules/react-dom
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
scheduler@0.27.0
Declared licence: MIT
Installed from: node_modules/scheduler
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+71
View File
@@ -0,0 +1,71 @@
# OTP & Passkey Tools
A production-oriented, local-first browser workbench for OTP credentials and WebAuthn/passkey evidence. It is part of the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal), but its release ZIP also runs as a standalone static application.
Authentication material stays in the active tab. The application has no backend, telemetry, automatic network lookup, service worker, cookie, local-storage credential store, or IndexedDB database.
## Included in 0.1.0
- RFC 4226 HOTP and RFC 6238 TOTP generation and bounded diagnostic verification using SHA-1, SHA-256 or SHA-512, with exact 64-bit counters and preserved leading zeroes.
- Strict `otpauth://` parsing/serialization, random secret generation, masked values, interoperability findings, live period display and a project-owned QR encoder.
- RFC 6287 OCRA-1 suite parsing and computation for counter, numeric/alphanumeric/hex challenge, PIN/password hash, session and timestamp inputs. Official RFC interoperability vectors cover SHA-1, SHA-256 and SHA-512 paths.
- Import of line-delimited provisioning URIs, Google Authenticator migration QR payloads, the documented CSV shape and RFC 6030 PSKC files containing plain secrets. Encrypted PSKC is rejected rather than guessed.
- Explicit URI-list and CSV export with an unencrypted-secret warning.
- Bounded CBOR, `clientDataJSON`, authenticator-data and attestation-object inspection, including flags, RP ID hash, counter, AAGUID, credential ID, COSE key and extensions.
- Layered assertion verification for challenge, origin, cross-origin state, RP ID hash, user presence/verification, signature counter, and ES256, RS256, PS256 or Ed25519 signatures.
- Serializable registration/request option examples, browser capability diagnostics and an ephemeral in-memory live ceremony lab.
## Security boundary
The Toolbox app at `/apps/auth/` is deliberately **inspect-only for live WebAuthn ceremonies**. Every app under `toolbox.add-ideas.de` shares one browser origin and therefore one WebAuthn relying-party namespace. Credential creation/authentication is enabled only on localhost or the dedicated origin:
```text
https://auth.toolbox.add-ideas.de/
```
The same immutable release can be served there, top-level, with RP ID `auth.toolbox.add-ideas.de`. The RP ID is never widened to `add-ideas.de`, and arbitrary RP IDs can only be inspected offline.
Raw CTAP/token administration is not claimed: browsers expose ordinary WebAuthn but block the FIDO HID usage page from WebHID. Camera and USB permissions are not requested. QR images can be selected locally when the browser implements `BarcodeDetector`; provisioning text can always be pasted.
See [SECURITY.md](SECURITY.md) for the threat model and limitations.
## Develop and verify
Requirements: Node.js 22+, npm 11, and `zip` for deterministic release packaging.
```sh
npm ci
npm run check
npm run test:browser
npm run package:release
```
The Vite base is relative, so both `/` and nested paths work. `npm run toolbox:check` validates the built manifest and its assets.
## Static deployment
Serve `dist/` or the contents of `release/auth-tools-0.1.0.zip` over HTTPS. Recommended response headers:
```text
Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; worker-src 'self' blob:; manifest-src 'self'
Permissions-Policy: camera=(), microphone=(), geolocation=(), usb=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
```
For Portal integration, pin the immutable Gitea release ZIP and SHA-256 in `toolbox-portal/release/toolbox.lock.json` with target `auth`.
## Deliberate limits
- This is an engineering and interoperability workbench, not a certified authenticator, relying-party server, password manager, FIDO certification tool or recovery system.
- Live credentials are forgotten on reload and cannot be exported by WebAuthn design.
- Attestation structures are decoded, but 0.1.0 does not establish attestation trust or silently download FIDO Metadata Service data. Assertion signatures are verified only with the explicitly supplied/created credential key.
- Google multi-QR batches must all be supplied; the current UI reviews one payload at a time. Google migration export and encrypted PSKC decryption are not claimed.
- CSV and URI exports contain raw OTP seeds. There is no encrypted vault format in this app.
- QR generation supports byte-mode error-correction M through version 10. Larger provisioning records remain available as text exports.
## Licence
`GPL-3.0-or-later`. See [LICENSE](LICENSE), [SOURCE.md](SOURCE.md), and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+40
View File
@@ -0,0 +1,40 @@
# Security model
## Data flow
All inputs are processed in the browser tab. There are no application `fetch`, WebSocket, beacon, analytics, service-worker, credential-storage or remote-metadata paths. OTP secrets, OCRA PIN input, imported files, WebAuthn responses and live test credential metadata are React/session memory and disappear on reload or **Clear session**.
Downloads and clipboard writes require a user action. Exports are not encrypted. The UI masks OTP secrets and provisioning URIs by default, but masking is not memory protection.
## Trust boundaries
- The static release and its hosting origin are trusted code. A compromised host can alter JavaScript and steal subsequently entered material; verify the release SHA-256 when this matters.
- Imported URIs, CSV, XML, protobuf, JSON, Base64url and CBOR are untrusted. Size/depth/count limits are applied before or during decoding. Imported text is rendered by React, never as markup. The only generated markup insertion is the project-owned QR SVG serializer, which receives an already serialized provisioning URI and emits path coordinates only.
- WebAuthn client data is verified as exact strings/bytes. Origins and RP IDs are not suffix-matched. The expected challenge is caller-supplied ceremony state; the tool cannot prove that a server generated or consumed it once.
- Signature verification establishes consistency with the supplied COSE public key, not account ownership or attestation trust.
## Origin isolation
`toolbox.add-ideas.de/apps/auth/` shares an origin with every other Portal app. Live registration/assertion is therefore disabled there. It is enabled only for localhost development or exact host `auth.toolbox.add-ideas.de`. Deploy the dedicated host top-level with `frame-ancestors 'none'`; do not change its RP ID to the parent domain.
## Cryptography
HMAC, digest, random generation, public-key import and signature verification use the browser Web Cryptography API. No custom cryptographic primitive is implemented. OTP dynamic truncation and OCRA data-input assembly are project code covered by RFC vectors.
SHA-1 remains available only where HOTP/TOTP/OCRA interoperability standards require it; it is used inside HMAC or as an explicitly selected OCRA PIN digest, not as a collision-resistant document signature.
## Parser limits
- Provisioning URI: 16 KiB.
- Migration/CSV/PSKC input: 4 MiB.
- Google protobuf: bounded input, varints at most 10 bytes, supported wire types only.
- CBOR: 4 MiB, depth 32, 10,000 items, definite lengths only, duplicate map keys rejected.
- OTP secret: 1 KiB; random generation: 161,024 bytes.
- Verification windows: TOTP 100 steps maximum; HOTP 10,000 counters maximum.
- QR encoder: version 10 maximum.
## Not a vault or identity provider
Do not use this app as the only copy of a credential. It does not offer encrypted persistence, recovery codes, account recovery, server-side challenge state, rate limiting, audit logging, device attestation policy, FIDO certification, or phishing protection outside normal browser WebAuthn behavior.
Report vulnerabilities through the repository issue tracker without including real secrets or production assertions.
+31
View File
@@ -0,0 +1,31 @@
# Corresponding source and provenance
The corresponding source for OTP & Passkey Tools 0.1.0 will be published at:
https://git.add-ideas.de/lotobo/auth-tools/src/tag/v0.1.0
Build that tag with Node.js 22 and the exact `package-lock.json`:
```sh
npm ci
npm run release:artifact
```
No generated bundle is the preferred source form. No runtime code, metadata or cryptographic service is loaded from a CDN.
## Standards and revisions used
| Source | Revision | Use |
| -------------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------- |
| Toolbox SDK | `ef2dab4b46c61812c9a877d8a19fe497b4a4630a`, packages 0.2.3 | manifest, context, shell and build checks |
| Toolbox Portal | `5ed7134d42f0b563bc47a1572107ea94994dfe3c`, tag v0.10.0 | release and UX integration contract |
| RFC 4226 | December 2005 | HOTP semantics and vectors |
| RFC 6238 | May 2011 | TOTP semantics and vectors |
| RFC 6287 | June 2011 | OCRA suite grammar, semantics and vectors |
| RFC 6030 | October 2010 | bounded plain-secret PSKC import |
| Google Authenticator migration protobuf | observed public interchange schema | local import only; unknown fields are skipped safely |
| Web Authentication | W3C WebAuthn Level 3 Recommendation, 13 January 2026 | client/authenticator structures and ceremony expectations |
| RFC 8949 / RFC 9052 / RFC 8152 registrations | published versions | bounded CBOR and COSE key interpretation |
| QR Code for JavaScript | Kazuhiko Arase, 2009 | QR construction algorithm rewritten in TypeScript under MIT terms |
The OCRA implementation was authored from the normative RFC definition and tested with its published interoperability values; the RFC Java reference implementation is not included. The QR module is an acknowledged clean TypeScript rewrite of the MIT-licensed construction algorithm, with deliberately bounded version support.
+24
View File
@@ -0,0 +1,24 @@
# Third-party notices
The release preparation step collates licence files for the exact locked runtime packages into `LICENSES/npm-runtime-licenses.txt` inside the static artifact.
## Direct runtime packages
| Package | Version | Licence | Role | Source |
| -------------------------------- | ------- | ---------- | ------------------------------- | ------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | manifest and context contract | https://git.add-ideas.de/lotobo/toolbox-sdk |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | shared shell, theme and actions | https://git.add-ideas.de/lotobo/toolbox-sdk |
| `react` | 19.2.6 | MIT | application UI | https://github.com/facebook/react |
| `react-dom` | 19.2.6 | MIT | browser rendering | https://github.com/facebook/react |
`scheduler`, distributed by the React project under MIT, is the only transitive runtime package.
## QR construction
`src/qr/encoder.ts` is a bounded TypeScript rewrite following the QRCode for JavaScript construction algorithm by Kazuhiko Arase (copyright 2009), used under the MIT License. The licence text is in `LICENSES/QRCode-MIT.txt`. The rewrite supports byte mode, error correction M, versions 110, and contains no upstream branding or UI.
## Standards material
RFC interoperability values are facts used as tests. The OCRA implementation is project-authored from RFC 6287; its Java reference implementation is not shipped. W3C WebAuthn, IETF CBOR/COSE and OTP specifications are implementation references, not bundled runtime software.
Development-only packages listed in `package-lock.json` build and test the source but are not shipped as runtime modules.
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-labelledby="title">
<title id="title">OTP and passkey tools</title>
<path fill="#f4f0e8" stroke="#272421" stroke-width="3" d="M12 3h29l11 11v47H12z"/>
<path fill="#ded7c9" stroke="#272421" stroke-width="3" d="M41 3v12h11"/>
<circle cx="28" cy="32" r="9" fill="#e65f3c" stroke="#272421" stroke-width="3"/>
<path fill="none" stroke="#272421" stroke-linecap="round" stroke-width="4" d="M35 39l12 12m-5-5 4-4m-8 1 4-4"/>
<circle cx="28" cy="32" r="2.5" fill="#f4f0e8"/>
</svg>

After

Width:  |  Height:  |  Size: 561 B

+52
View File
@@ -0,0 +1,52 @@
{
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
"schemaVersion": 1,
"id": "de.add-ideas.auth-tools",
"name": "OTP & Passkey Tools",
"version": "0.1.0",
"description": "Generate, inspect and verify OTP credentials and test WebAuthn/passkey ceremonies locally in the browser.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["security", "authentication", "developer"],
"tags": [
"otp",
"hotp",
"totp",
"ocra",
"oath",
"webauthn",
"fido2",
"passkey",
"attestation",
"assertion"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": true,
"workers": false,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": true
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Authentication material stays in this tab; nothing is uploaded or saved unless you explicitly export it."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/auth-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/auth-tools"
}
]
}
+55
View File
@@ -0,0 +1,55 @@
import { lstat, readFile, writeFile } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { format } from "prettier";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const sourcePath = join(root, "src", "toolbox", "manifest.source.json");
const outputPath = join(root, "public", "toolbox-app.json");
const source = JSON.parse(await readFile(sourcePath, "utf8"));
const packageJson = JSON.parse(
await readFile(join(root, "package.json"), "utf8"),
);
const versionSource = await readFile(join(root, "src", "version.ts"), "utf8");
const applicationVersion =
/^export const APPLICATION_VERSION = "([^"]+)";$/mu.exec(versionSource)?.[1];
if (
source.version !== packageJson.version ||
applicationVersion !== packageJson.version
)
throw new Error(
`Version drift: manifest ${source.version}, application ${String(applicationVersion)}, package ${packageJson.version}`,
);
if (
source.id !== "de.add-ideas.auth-tools" ||
source.source?.repository !== "https://git.add-ideas.de/lotobo/auth-tools" ||
source.source?.license !== "GPL-3.0-or-later"
)
throw new Error("Manifest source identity is incomplete or inconsistent");
for (const asset of source.assets ?? []) {
if (
typeof asset !== "string" ||
!asset.startsWith("./") ||
asset.includes("\\") ||
asset.split("/").includes("..")
)
throw new Error(`Unsafe manifest asset path: ${JSON.stringify(asset)}`);
const details = await lstat(join(root, "public", asset.slice(2))).catch(
() => null,
);
if (!details?.isFile() || details.isSymbolicLink())
throw new Error(`Manifest asset is missing or unsafe: ${asset}`);
}
const serialized = await format(JSON.stringify(source), {
filepath: outputPath,
});
if (process.argv.includes("--check")) {
if ((await readFile(outputPath, "utf8").catch(() => "")) !== serialized)
throw new Error(
`${relative(root, outputPath)} is stale; run npm run manifest:generate`,
);
console.log("Toolbox manifest is synchronized");
} else {
await writeFile(outputPath, serialized);
console.log(`Generated ${relative(root, outputPath)}`);
}
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import {
access,
cp,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rename,
rm,
utimes,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
const execute = promisify(execFile);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageJson = JSON.parse(
await readFile(path.join(root, "package.json"), "utf8"),
);
const argument = (name, fallback) => {
const index = process.argv.indexOf(name);
return index >= 0 ? process.argv[index + 1] : fallback;
};
const output = path.resolve(
root,
argument("--output", `release/auth-tools-${packageJson.version}.zip`),
);
const checksumOutput = `${output}.sha256`;
const force = process.argv.includes("--force");
if (
path.extname(output).toLowerCase() !== ".zip" ||
output === root ||
output === path.parse(output).root
)
throw new Error("Release output is not a safe ZIP target");
const exists = (file) =>
access(file).then(
() => true,
() => false,
);
if (!force && ((await exists(output)) || (await exists(checksumOutput))))
throw new Error("Release output already exists; use --force to replace it");
const input = path.join(root, "dist");
for (const name of [
"index.html",
"toolbox-app.json",
"favicon.svg",
"README.md",
"CHANGELOG.md",
"LICENSE",
"SOURCE.md",
"SECURITY.md",
"THIRD_PARTY_NOTICES.md",
"LICENSES/README.md",
"LICENSES/npm-runtime-licenses.txt",
]) {
const details = await lstat(path.join(input, name)).catch(() => null);
if (!details?.isFile() || details.isSymbolicLink())
throw new Error(`Release is missing a regular file: ${name}`);
}
const manifest = JSON.parse(
await readFile(path.join(input, "toolbox-app.json"), "utf8"),
);
if (
manifest.id !== "de.add-ideas.auth-tools" ||
manifest.version !== packageJson.version ||
manifest.entry !== "./" ||
manifest.icon !== "./favicon.svg"
)
throw new Error("Packaged Toolbox manifest identity is invalid");
const html = await readFile(path.join(input, "index.html"), "utf8");
if (/\b(?:src|href)=["']\//iu.test(html))
throw new Error("index.html contains a root-absolute asset reference");
async function collect(directory, prefix = "") {
const files = [];
for (const entry of (await readdir(directory, { withFileTypes: true })).sort(
(left, right) => left.name.localeCompare(right.name),
)) {
const absolute = path.join(directory, entry.name);
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isSymbolicLink())
throw new Error(`Release contains a symbolic link: ${relative}`);
if (entry.isDirectory()) files.push(...(await collect(absolute, relative)));
else if (entry.isFile()) files.push({ absolute, relative });
else throw new Error(`Unsupported release entry: ${relative}`);
}
return files;
}
const sourceFiles = await collect(input);
for (const file of sourceFiles)
if (
file.relative.endsWith(".map") ||
/(?:^|\/)(?:\.env(?:\.|$)|id_rsa|id_ed25519|.*\.pem$|.*\.key$)/iu.test(
file.relative,
) ||
file.relative.startsWith("/") ||
file.relative.split("/").includes("..")
)
throw new Error(`Forbidden release entry: ${file.relative}`);
await mkdir(path.dirname(output), { recursive: true });
const stagingRoot = await mkdtemp(
path.join(path.dirname(output), ".auth-release-"),
);
const stagedTree = path.join(stagingRoot, "tree");
const stagedArchive = path.join(stagingRoot, path.basename(output));
try {
await cp(input, stagedTree, { recursive: true });
const timestamp = new Date("1980-01-01T00:00:00.000Z");
for (const file of await collect(stagedTree))
await utimes(file.absolute, timestamp, timestamp);
await execute(
"zip",
[
"-X",
"-q",
"-9",
stagedArchive,
...sourceFiles.map((file) => file.relative),
],
{ cwd: stagedTree, maxBuffer: 1024 * 1024 },
);
const archive = await readFile(stagedArchive);
const digest = createHash("sha256").update(archive).digest("hex");
const stagedChecksum = `${stagedArchive}.sha256`;
await writeFile(stagedChecksum, `${digest} ${path.basename(output)}\n`, {
mode: 0o644,
});
if (force) {
await rm(output, { force: true });
await rm(checksumOutput, { force: true });
}
await rename(stagedArchive, output);
await rename(stagedChecksum, checksumOutput);
console.log(
`Created ${path.relative(root, output)} (${archive.byteLength} bytes, ${sourceFiles.length} files)\nSHA-256 ${digest}`,
);
} finally {
await rm(stagingRoot, { recursive: true, force: true });
}
+65
View File
@@ -0,0 +1,65 @@
import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const destination = path.join(root, "public");
const required = [
"LICENSE",
"README.md",
"CHANGELOG.md",
"SOURCE.md",
"SECURITY.md",
"THIRD_PARTY_NOTICES.md",
];
await mkdir(destination, { recursive: true });
for (const name of required) {
await readFile(path.join(root, name));
await cp(path.join(root, name), path.join(destination, name));
}
const publicLicenses = path.join(destination, "LICENSES");
await rm(publicLicenses, { recursive: true, force: true });
await cp(path.join(root, "LICENSES"), publicLicenses, { recursive: true });
const lock = JSON.parse(
await readFile(path.join(root, "package-lock.json"), "utf8"),
);
const sections = [];
for (const [location, locked] of Object.entries(lock.packages ?? {}).sort(
([left], [right]) => left.localeCompare(right),
)) {
if (!location.includes("node_modules/") || locked.dev === true) continue;
const packageDirectory = path.join(root, location);
const details = JSON.parse(
await readFile(path.join(packageDirectory, "package.json"), "utf8"),
);
const candidates = (await readdir(packageDirectory))
.filter((name) => /^(?:licen[cs]e|copying|notice)(?:\.|$)/iu.test(name))
.sort();
const texts = [];
for (const candidate of candidates) {
try {
texts.push(
`--- ${candidate} ---\n${await readFile(path.join(packageDirectory, candidate), "utf8")}`,
);
} catch {
/* Ignore directories and non-text aliases. */
}
}
sections.push(
[
"=".repeat(78),
`${details.name}@${details.version}`,
`Declared licence: ${details.license ?? locked.license ?? "See upstream"}`,
`Installed from: ${location}`,
"=".repeat(78),
texts.join("\n\n") ||
"No package-local licence file was present; see THIRD_PARTY_NOTICES.md.",
].join("\n"),
);
}
await writeFile(
path.join(publicLicenses, "npm-runtime-licenses.txt"),
`${sections.join("\n\n")}\n`,
);
console.log("Prepared static release notices");
+74
View File
@@ -0,0 +1,74 @@
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"dist",
);
const nestedPrefix = "/deep/nested/auth/";
const mediaTypes = new Map([
[".css", "text/css; charset=utf-8"],
[".html", "text/html; charset=utf-8"],
[".js", "text/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".svg", "image/svg+xml"],
[".md", "text/markdown; charset=utf-8"],
[".txt", "text/plain; charset=utf-8"],
]);
const headers = {
"Content-Security-Policy":
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; worker-src 'self' blob:; manifest-src 'self'",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), usb=()",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
};
function safeFile(requestPath) {
const decoded = decodeURIComponent(requestPath);
const relative = decoded.startsWith(nestedPrefix)
? decoded.slice(nestedPrefix.length)
: decoded.replace(/^\/+/, "");
const normalized = path.posix.normalize(relative || "index.html");
if (
normalized === ".." ||
normalized.startsWith("../") ||
path.isAbsolute(normalized)
)
return null;
return path.join(root, normalized);
}
const server = createServer(async (request, response) => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
let file = safeFile(url.pathname);
if (!file) {
response.writeHead(400).end("Bad request");
return;
}
if ((await stat(file).catch(() => null))?.isDirectory())
file = path.join(file, "index.html");
const content = await readFile(file);
response.writeHead(200, {
"Content-Type":
mediaTypes.get(path.extname(file)) ?? "application/octet-stream",
"Cache-Control": "no-cache",
...headers,
});
response.end(content);
} catch {
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
response.end("Not found");
}
});
server.listen(4173, "127.0.0.1", () =>
console.log(
"Authentication Tools test server listening on http://127.0.0.1:4173",
),
);
+41
View File
@@ -0,0 +1,41 @@
import { lazy, Suspense, useState } from "react";
import { AppShell } from "@add-ideas/toolbox-shell-react";
import "@add-ideas/toolbox-shell-react/styles.css";
import "./styles.css";
import { AppErrorBoundary } from "./components/AppErrorBoundary";
import { HelpDialog } from "./components/HelpDialog";
import { manifest } from "./toolbox/manifest";
const Workbench = lazy(async () => ({
default: (await import("./components/Workbench")).Workbench,
}));
export function App() {
const [helpOpen, setHelpOpen] = useState(false);
return (
<AppErrorBoundary>
<AppShell
app={manifest}
manifestUrl="./toolbox-app.json"
helpAction={{ onClick: () => setHelpOpen(true) }}
onContextError={(error) =>
console.warn(
"Toolbox context unavailable; continuing standalone.",
error,
)
}
>
<Suspense
fallback={
<p className="workbench-loading" role="status">
Preparing the local authentication workbench
</p>
}
>
<Workbench />
</Suspense>
</AppShell>
<HelpDialog open={helpOpen} onClose={() => setHelpOpen(false)} />
</AppErrorBoundary>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface Props {
children: ReactNode;
}
interface State {
error: Error | null;
}
export class AppErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.error(
"OTP & Passkey Tools encountered an unrecoverable interface error",
error,
info,
);
}
render(): ReactNode {
if (!this.state.error) return this.props.children;
return (
<main className="fatal-error" role="alert">
<h1>Authentication tools could not continue</h1>
<p>{this.state.error.message}</p>
<button
type="button"
className="primary-button"
onClick={() => globalThis.location.reload()}
>
Reload application
</button>
</main>
);
}
}
+81
View File
@@ -0,0 +1,81 @@
import { useEffect, useRef } from "react";
export function HelpDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
return (
<dialog ref={ref} className="tool-dialog" onClose={onClose}>
<div className="dialog-heading">
<div>
<p className="eyebrow">Local authentication laboratory</p>
<h2>OTP & Passkey Tools help</h2>
</div>
<button
className="icon-button"
type="button"
aria-label="Close help"
onClick={onClose}
>
×
</button>
</div>
<div className="dialog-body prose">
<h3>Handle secrets deliberately</h3>
<p>
OTP seeds are equivalent to a second-factor credential. This app keeps
them in memory only, masks them by default and clears them on reload.
Exports are explicit and unencrypted; move them only through a secure
channel.
</p>
<h3>OTP clock and counters</h3>
<p>
TOTP is computed from this devices clock. A rejected valid-looking
value commonly means clock drift, a different period, or the wrong
hash/digit profile. HOTP counters must remain synchronized.
</p>
<h3>Passkey inspection</h3>
<p>
Inspection is offline. Verification is layered: client-data
expectations, RP ID hash, authenticator flags, counter and
cryptographic signature are reported separately. Metadata is never
fetched silently.
</p>
<h3>Live ceremonies</h3>
<p>
WebAuthn credentials belong to an exact RP ID. Live tests are enabled
only on localhost or the dedicated authentication hostname. The shared
Toolbox origin remains inspect-only so unrelated apps do not share its
credential namespace.
</p>
<p>
No authentication material, file, telemetry or request leaves this
tab.
</p>
</div>
<div className="dialog-actions">
<a
className="secondary-button"
href="https://git.add-ideas.de/lotobo/auth-tools"
target="_blank"
rel="noreferrer"
>
Source and issues
</a>
<button className="primary-button" type="button" onClick={onClose}>
Done
</button>
</div>
</dialog>
);
}
+56
View File
@@ -0,0 +1,56 @@
import { useCallback, useState } from "react";
import { OtpWorkspace } from "./otp/OtpWorkspace";
import { WebAuthnWorkspace } from "./webauthn/WebAuthnWorkspace";
type Workspace = "otp" | "passkeys";
export function Workbench() {
const [workspace, setWorkspace] = useState<Workspace>("otp");
const [session, setSession] = useState(0);
const clear = useCallback(() => setSession((value) => value + 1), []);
return (
<main className="auth-application">
<section className="privacy-strip" aria-label="Privacy status">
<span className="status-dot" aria-hidden="true" />
<div>
<strong>Sensitive session · memory only</strong>
<span> Nothing is uploaded or saved automatically.</span>
</div>
<button
type="button"
className="secondary-button compact-button"
onClick={clear}
>
Clear session
</button>
</section>
<nav className="workspace-tabs" aria-label="Authentication tool family">
<button
type="button"
className={workspace === "otp" ? "active" : ""}
aria-current={workspace === "otp" ? "page" : undefined}
onClick={() => setWorkspace("otp")}
>
<span aria-hidden="true">123</span>
<strong>OTP</strong>
<small>HOTP, TOTP and migrations</small>
</button>
<button
type="button"
className={workspace === "passkeys" ? "active" : ""}
aria-current={workspace === "passkeys" ? "page" : undefined}
onClick={() => setWorkspace("passkeys")}
>
<span aria-hidden="true"></span>
<strong>WebAuthn / Passkeys</strong>
<small>Inspect, verify and test</small>
</button>
</nav>
{workspace === "otp" ? (
<OtpWorkspace key={`otp-${session}`} />
) : (
<WebAuthnWorkspace key={`passkeys-${session}`} />
)}
</main>
);
}
+854
View File
@@ -0,0 +1,854 @@
import { useEffect, useMemo, useState } from "react";
import {
base32ToBytes,
bytesToBase32,
randomBytes,
} from "../../crypto/encoding";
import {
exportCsv,
exportOtpAuthList,
importCsv,
importGoogleMigration,
importOtpAuthList,
importPlainPskc,
type ImportResult,
} from "../../otp/migration";
import {
hotp,
totp,
verifyHotp,
verifyTotp,
type OtpHashAlgorithm,
type OtpKind,
} from "../../otp/otp";
import { hashOcraPassword, ocra, parseOcraSuite } from "../../otp/ocra";
import {
profileStrength,
serializeOtpAuth,
type OtpProfile,
} from "../../otp/profile";
import { qrSvg } from "../../qr/encoder";
function downloadText(
name: string,
content: string,
type = "text/plain;charset=utf-8",
): void {
const url = URL.createObjectURL(new Blob([content], { type }));
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
function initialProfile(): OtpProfile {
return {
kind: "totp",
secret: randomBytes(20),
issuer: "",
account: "",
algorithm: "SHA-1",
digits: 6,
period: 30,
counter: 0n,
extensions: new Map(),
};
}
function detectImport(input: string): ImportResult {
const trimmed = input.trim();
if (trimmed.startsWith("otpauth-migration://"))
return importGoogleMigration(trimmed);
if (trimmed.startsWith("<")) return importPlainPskc(trimmed);
if (/^otpauth:\/\//imu.test(trimmed)) return importOtpAuthList(trimmed);
return importCsv(trimmed);
}
interface BarcodeResult {
rawValue: string;
}
interface BarcodeDetectorLike {
detect(source: ImageBitmap): Promise<BarcodeResult[]>;
}
interface BarcodeDetectorConstructor {
new (options: { formats: string[] }): BarcodeDetectorLike;
}
export function OtpWorkspace() {
const [profile, setProfile] = useState<OtpProfile>(initialProfile);
const [secretText, setSecretText] = useState(() =>
bytesToBase32(profile.secret),
);
const [secretVisible, setSecretVisible] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [code, setCode] = useState("······");
const [verifyCode, setVerifyCode] = useState("");
const [verification, setVerification] = useState("");
const [error, setError] = useState("");
const [mode, setMode] = useState<"credential" | "ocra" | "migration">(
"credential",
);
const [migrationText, setMigrationText] = useState("");
const [imported, setImported] = useState<OtpProfile[]>([]);
const [warnings, setWarnings] = useState<string[]>([]);
useEffect(() => {
const timer = window.setInterval(() => setNow(Date.now()), 500);
return () => window.clearInterval(timer);
}, []);
useEffect(() => {
let active = true;
const generate =
profile.kind === "totp"
? totp({
secret: profile.secret,
algorithm: profile.algorithm,
digits: profile.digits,
period: profile.period,
timestamp: now / 1000,
})
: hotp({
secret: profile.secret,
algorithm: profile.algorithm,
digits: profile.digits,
counter: profile.counter,
});
void generate
.then((value) => {
if (active) setCode(value);
})
.catch((reason: unknown) => {
if (active)
setError(
reason instanceof Error ? reason.message : "OTP generation failed.",
);
});
return () => {
active = false;
};
}, [profile, now]);
const uri = useMemo(() => {
try {
return serializeOtpAuth(profile);
} catch {
return "";
}
}, [profile]);
const qr = useMemo(() => {
try {
return uri ? qrSvg(uri) : "";
} catch {
return "";
}
}, [uri]);
const strength = useMemo(() => profileStrength(profile), [profile]);
const remaining =
profile.kind === "totp"
? profile.period - (Math.floor(now / 1000) % profile.period)
: null;
const update = <Key extends keyof OtpProfile>(
key: Key,
value: OtpProfile[Key],
) => setProfile((current) => ({ ...current, [key]: value }));
const updateSecret = (value: string) => {
setSecretText(value);
try {
const secret = base32ToBytes(value, {
allowPadding: true,
allowSeparators: true,
});
if (!secret.length) throw new Error("Secret is empty.");
update("secret", secret);
setError("");
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Invalid Base32 secret.",
);
}
};
const regenerate = () => {
const secret = randomBytes(
profile.algorithm === "SHA-512"
? 64
: profile.algorithm === "SHA-256"
? 32
: 20,
);
setSecretText(bytesToBase32(secret));
update("secret", secret);
setError("");
};
const verify = async () => {
try {
const match =
profile.kind === "totp"
? await verifyTotp(verifyCode, {
secret: profile.secret,
algorithm: profile.algorithm,
digits: profile.digits,
period: profile.period,
timestamp: now / 1000,
window: 2,
})
: await verifyHotp(verifyCode, {
secret: profile.secret,
algorithm: profile.algorithm,
digits: profile.digits,
counter: profile.counter,
lookAhead: 20,
});
setVerification(
match
? `Valid · ${match.delta === 0 ? "current moving factor" : `offset ${match.delta > 0 ? "+" : ""}${match.delta}`}`
: "No match in the diagnostic window.",
);
} catch (reason) {
setVerification(
reason instanceof Error ? reason.message : "Verification failed.",
);
}
};
const performImport = (text = migrationText) => {
try {
const result = detectImport(text);
setImported(result.profiles);
setWarnings(result.warnings);
setError("");
if (result.profiles[0]) {
setProfile(result.profiles[0]);
setSecretText(bytesToBase32(result.profiles[0].secret));
}
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Import failed.");
setImported([]);
}
};
const scanQr = async (file: File) => {
try {
if (file.size > 16 * 1024 * 1024)
throw new Error("QR image is larger than the 16 MiB safety limit.");
const Constructor = (
globalThis as typeof globalThis & {
BarcodeDetector?: BarcodeDetectorConstructor;
}
).BarcodeDetector;
if (!Constructor)
throw new Error(
"This browser has no BarcodeDetector. Paste the provisioning URI instead.",
);
const bitmap = await createImageBitmap(file);
try {
if (
bitmap.width > 4096 ||
bitmap.height > 4096 ||
bitmap.width * bitmap.height > 16_777_216
)
throw new Error(
"QR image dimensions exceed the 4096 px / 16-megapixel safety limit.",
);
const results = await new Constructor({ formats: ["qr_code"] }).detect(
bitmap,
);
if (!results[0]?.rawValue)
throw new Error("No QR code was found in the image.");
setMigrationText(results[0].rawValue);
performImport(results[0].rawValue);
} finally {
bitmap.close();
}
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "QR decoding failed.",
);
}
};
return (
<section className="workspace">
<div className="subtabs" role="tablist" aria-label="OTP tasks">
<button
type="button"
className={mode === "credential" ? "active" : ""}
onClick={() => setMode("credential")}
>
Credential lab
</button>
<button
type="button"
className={mode === "ocra" ? "active" : ""}
onClick={() => setMode("ocra")}
>
OCRA challenge
</button>
<button
type="button"
className={mode === "migration" ? "active" : ""}
onClick={() => setMode("migration")}
>
Import & migration
</button>
</div>
{error && (
<div className="notice error" role="alert">
{error}
<button
type="button"
aria-label="Dismiss error"
onClick={() => setError("")}
>
×
</button>
</div>
)}
{mode === "credential" ? (
<div className="otp-grid">
<article className="panel editor-panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Provisioning profile</p>
<h2>Credential parameters</h2>
</div>
<span className="badge">{strength.secretBits} bit secret</span>
</div>
<div className="panel-body form-grid">
<label>
<span>Type</span>
<select
value={profile.kind}
onChange={(event) =>
update("kind", event.target.value as OtpKind)
}
>
<option value="totp">TOTP · time based</option>
<option value="hotp">HOTP · counter based</option>
</select>
</label>
<label>
<span>Hash</span>
<select
value={profile.algorithm}
onChange={(event) =>
update("algorithm", event.target.value as OtpHashAlgorithm)
}
>
<option>SHA-1</option>
<option>SHA-256</option>
<option>SHA-512</option>
</select>
</label>
<label>
<span>Issuer</span>
<input
value={profile.issuer}
maxLength={256}
placeholder="Example service"
onChange={(event) => update("issuer", event.target.value)}
/>
</label>
<label>
<span>Account</span>
<input
value={profile.account}
maxLength={512}
placeholder="name@example.org"
onChange={(event) => update("account", event.target.value)}
/>
</label>
<label className="wide">
<span>Base32 secret</span>
<div className="input-actions">
<input
type={secretVisible ? "text" : "password"}
spellCheck={false}
autoComplete="off"
value={secretText}
onChange={(event) => updateSecret(event.target.value)}
/>
<button
type="button"
className="icon-button"
aria-label={secretVisible ? "Hide secret" : "Show secret"}
onClick={() => setSecretVisible((value) => !value)}
>
{secretVisible ? "Hide" : "Show"}
</button>
<button
type="button"
className="secondary-button"
onClick={regenerate}
>
Generate
</button>
</div>
</label>
<label>
<span>Digits</span>
<select
value={profile.digits}
onChange={(event) =>
update("digits", Number(event.target.value))
}
>
<option value="6">6</option>
<option value="8">8</option>
<option value="10">10</option>
</select>
</label>
{profile.kind === "totp" ? (
<label>
<span>Period (seconds)</span>
<input
type="number"
min="1"
max="86400"
value={profile.period}
onChange={(event) =>
update("period", Number(event.target.value))
}
/>
</label>
) : (
<label>
<span>Counter</span>
<input
inputMode="numeric"
value={profile.counter.toString()}
onChange={(event) => {
if (/^\d+$/u.test(event.target.value))
update("counter", BigInt(event.target.value));
}}
/>
</label>
)}
</div>
<details className="findings">
<summary>Interoperability analysis</summary>
<ul>
{strength.findings.map((finding) => (
<li key={finding}>{finding}</li>
))}
</ul>
</details>
</article>
<article className="panel code-panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Live value</p>
<h2>{profile.kind.toUpperCase()} code</h2>
</div>
{remaining !== null && (
<span className="countdown">{remaining}s</span>
)}
</div>
<div className="code-display" aria-live="polite">
{code.match(/.{1,3}/gu)?.join(" ")}
</div>
<div className="progress" aria-hidden="true">
{remaining !== null && (
<span
style={{ width: `${(remaining / profile.period) * 100}%` }}
/>
)}
</div>
<div className="verify-row">
<input
aria-label="Code to verify"
inputMode="numeric"
placeholder={`${profile.digits}-digit code`}
value={verifyCode}
onChange={(event) => setVerifyCode(event.target.value)}
/>
<button
type="button"
className="primary-button"
onClick={() => void verify()}
>
Verify
</button>
</div>
{verification && (
<p className="verification" role="status">
{verification}
</p>
)}
{uri ? (
<>
<div className="qr" dangerouslySetInnerHTML={{ __html: qr }} />
<label className="wide">
<span>Provisioning URI</span>
<textarea
readOnly
rows={4}
value={
secretVisible
? uri
: uri.replace(/([?&]secret=)[^&]+/u, "$1")
}
/>
</label>
<div className="button-row">
<button
type="button"
className="secondary-button"
onClick={() => void navigator.clipboard.writeText(uri)}
>
Copy URI
</button>
<button
type="button"
className="secondary-button"
onClick={() =>
downloadText("otp-provisioning.svg", qr, "image/svg+xml")
}
>
Download QR
</button>
</div>
</>
) : (
<p className="empty-state">
Add an account label to create a provisioning URI and QR.
</p>
)}
</article>
</div>
) : mode === "ocra" ? (
<OcraLab />
) : (
<div className="migration-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Import locally</p>
<h2>Provisioning and migration data</h2>
</div>
</div>
<div className="panel-body">
<p className="hint">
Paste one or more <code>otpauth://</code> URIs, a Google
Authenticator migration URI, the apps CSV format, or
plain-secret PSKC XML.
</p>
<textarea
className="migration-input"
rows={12}
value={migrationText}
onChange={(event) => setMigrationText(event.target.value)}
placeholder="Paste migration data. It never leaves this tab."
/>
<div className="button-row">
<button
type="button"
className="primary-button"
onClick={() => performImport()}
>
Inspect import
</button>
<label className="secondary-button file-button">
Read QR image
<input
type="file"
accept="image/*"
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void scanQr(file);
}}
/>
</label>
</div>
</div>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Review before export</p>
<h2>
{imported.length
? `${imported.length} credential${imported.length === 1 ? "" : "s"}`
: "No imported credentials"}
</h2>
</div>
</div>
<div className="credential-list">
{imported.map((item, index) => (
<button
type="button"
key={`${item.issuer}-${item.account}-${index}`}
onClick={() => {
setProfile(item);
setSecretText(bytesToBase32(item.secret));
setMode("credential");
}}
>
<strong>{item.issuer || "No issuer"}</strong>
<span>{item.account}</span>
<small>
{item.kind.toUpperCase()} · {item.algorithm} · {item.digits}{" "}
digits
</small>
</button>
))}
</div>
{warnings.length > 0 && (
<div className="warnings">
<strong>Import notes</strong>
<ul>
{warnings.map((warning) => (
<li key={warning}>{warning}</li>
))}
</ul>
</div>
)}
{imported.length > 0 && (
<div className="panel-footer">
<p>Exports contain unencrypted secrets.</p>
<div className="button-row">
<button
type="button"
className="secondary-button"
onClick={() =>
downloadText(
"otp-credentials.txt",
exportOtpAuthList(imported),
)
}
>
Export URI list
</button>
<button
type="button"
className="secondary-button"
onClick={() =>
downloadText(
"otp-credentials.csv",
exportCsv(imported),
"text/csv;charset=utf-8",
)
}
>
Export CSV
</button>
</div>
</div>
)}
</article>
</div>
)}
</section>
);
}
function OcraLab() {
const [suiteText, setSuiteText] = useState("OCRA-1:HOTP-SHA1-6:QN08");
const [secretText, setSecretText] = useState(() =>
bytesToBase32(randomBytes(20)),
);
const [secretVisible, setSecretVisible] = useState(false);
const [question, setQuestion] = useState("00000000");
const [counter, setCounter] = useState("0");
const [password, setPassword] = useState("");
const [session, setSession] = useState("");
const [response, setResponse] = useState("");
const [error, setError] = useState("");
const suite = useMemo(() => {
try {
return parseOcraSuite(suiteText);
} catch {
return null;
}
}, [suiteText]);
const compute = async () => {
try {
const parsed = parseOcraSuite(suiteText);
const passwordHash = parsed.passwordAlgorithm
? await hashOcraPassword(password, parsed.passwordAlgorithm)
: undefined;
const value = await ocra({
suite: parsed,
secret: base32ToBytes(secretText, {
allowPadding: true,
allowSeparators: true,
}),
question,
...(parsed.counter ? { counter: BigInt(counter) } : {}),
...(passwordHash ? { passwordHash } : {}),
...(parsed.sessionLength !== undefined
? { session: new TextEncoder().encode(session) }
: {}),
});
setResponse(value);
setError("");
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "OCRA computation failed.",
);
setResponse("");
}
};
return (
<div className="split-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">RFC 6287</p>
<h2>OCRA suite and key</h2>
</div>
<span className="badge">Challenge-response</span>
</div>
<div className="panel-body compact-form">
<label>
<span>OCRASuite</span>
<input
spellCheck={false}
value={suiteText}
onChange={(event) => setSuiteText(event.target.value)}
/>
</label>
<label>
<span>Base32 shared secret</span>
<div className="input-actions">
<input
type={secretVisible ? "text" : "password"}
spellCheck={false}
autoComplete="off"
value={secretText}
onChange={(event) => setSecretText(event.target.value)}
/>
<button
type="button"
className="icon-button"
onClick={() => setSecretVisible((value) => !value)}
>
{secretVisible ? "Hide" : "Show"}
</button>
</div>
</label>
{suite ? (
<dl className="suite-summary">
<div>
<dt>HMAC / output</dt>
<dd>
{suite.algorithm} ·{" "}
{suite.digits === 0
? "full digest"
: `${suite.digits} digits`}
</dd>
</div>
<div>
<dt>Question</dt>
<dd>
{suite.questionFormat} · up to {suite.questionLength}
</dd>
</div>
<div>
<dt>Additional inputs</dt>
<dd>
{[
suite.counter && "counter",
suite.passwordAlgorithm &&
`${suite.passwordAlgorithm} PIN hash`,
suite.sessionLength &&
`${suite.sessionLength}-byte session`,
suite.timeStepSeconds &&
`${suite.timeStepSeconds}s time step`,
]
.filter(Boolean)
.join(", ") || "none"}
</dd>
</div>
</dl>
) : (
<p className="hint">
Enter a valid OCRA-1 suite to inspect its inputs.
</p>
)}
</div>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Explicit data input</p>
<h2>Compute response</h2>
</div>
</div>
<div className="panel-body compact-form">
<label>
<span>Challenge question</span>
<input
spellCheck={false}
value={question}
onChange={(event) => setQuestion(event.target.value)}
/>
</label>
{suite?.counter && (
<label>
<span>Counter</span>
<input
inputMode="numeric"
value={counter}
onChange={(event) => setCounter(event.target.value)}
/>
</label>
)}
{suite?.passwordAlgorithm && (
<label>
<span>
PIN / password · hashed locally with {suite.passwordAlgorithm}
</span>
<input
type="password"
autoComplete="off"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</label>
)}
{suite?.sessionLength !== undefined && (
<label>
<span>
UTF-8 session data · padded to {suite.sessionLength} bytes
</span>
<textarea
rows={3}
value={session}
onChange={(event) => setSession(event.target.value)}
/>
</label>
)}
{suite?.timeStepSeconds !== undefined && (
<p className="hint">
Timestamp input uses the current Unix time and the suites{" "}
{suite.timeStepSeconds}-second step.
</p>
)}
<button
type="button"
className="primary-button"
onClick={() => void compute()}
>
Compute OCRA response
</button>
{error && (
<p className="inline-error" role="alert">
{error}
</p>
)}
{response && (
<div className="ocra-response" aria-live="polite">
<span>Response</span>
<strong>{response}</strong>
</div>
)}
<p className="hint">
OCRA responses are meaningful only inside a protocol that validates
challenges once, synchronizes counters when used, and protects the
channel.
</p>
</div>
</article>
</div>
);
}
@@ -0,0 +1,596 @@
import { useEffect, useMemo, useState } from "react";
import {
base64UrlToBytes,
bytesToBase64Url,
randomBytes,
} from "../../crypto/encoding";
import {
detectCapabilities,
createMemoryCredential,
exerciseMemoryCredential,
liveLabAvailability,
LIVE_HOST,
type BrowserCapabilities,
type MemoryCredential,
} from "../../webauthn/live";
import {
cborDiagnostic,
parseAttestationObject,
parseAuthenticatorData,
parseClientData,
} from "../../webauthn/parser";
import {
coseKeyToJson,
verifyAssertion,
type AssertionVerificationResult,
} from "../../webauthn/verify";
type InspectKind = "client" | "attestation" | "authenticator";
function diagnostic(kind: InspectKind, input: string): unknown {
if (kind === "client") return parseClientData(input.trim());
if (kind === "authenticator")
return parseAuthenticatorData(base64UrlToBytes(input.trim()));
const result = parseAttestationObject(input.trim());
return {
format: result.format,
statement: cborDiagnostic(result.statement),
authenticator: {
...result.authenticator,
raw: bytesToBase64Url(result.authenticator.raw),
...(result.authenticator.attestedCredential
? {
attestedCredential: {
...result.authenticator.attestedCredential,
credentialPublicKey: coseKeyToJson(
result.authenticator.attestedCredential.credentialPublicKey,
),
},
}
: {}),
...(result.authenticator.extensions
? { extensions: cborDiagnostic(result.authenticator.extensions) }
: {}),
},
};
}
function capabilityLabel(value: boolean | null): string {
return value === null ? "Not exposed" : value ? "Available" : "Unavailable";
}
const EMPTY_ASSERTION = {
clientDataJSON: "",
authenticatorData: "",
signature: "",
credentialPublicKey: "",
expectedChallenge: "",
expectedOrigin: typeof location === "undefined" ? "" : location.origin,
expectedRpId: typeof location === "undefined" ? "" : location.hostname,
};
export function WebAuthnWorkspace() {
const [mode, setMode] = useState<"inspect" | "verify" | "options" | "live">(
"inspect",
);
const [inspectKind, setInspectKind] = useState<InspectKind>("client");
const [inspectInput, setInspectInput] = useState("");
const [inspectOutput, setInspectOutput] = useState("");
const [error, setError] = useState("");
const [assertion, setAssertion] = useState(EMPTY_ASSERTION);
const [verification, setVerification] =
useState<AssertionVerificationResult | null>(null);
const [capabilities, setCapabilities] = useState<BrowserCapabilities | null>(
null,
);
const [credential, setCredential] = useState<MemoryCredential | null>(null);
const [liveResult, setLiveResult] =
useState<AssertionVerificationResult | null>(null);
const [busy, setBusy] = useState(false);
const [userName, setUserName] = useState("local-user");
const [requireUv, setRequireUv] = useState(true);
const availability = useMemo(() => liveLabAvailability(window.location), []);
useEffect(() => {
void detectCapabilities().then(setCapabilities);
}, []);
const inspect = () => {
try {
setInspectOutput(
JSON.stringify(diagnostic(inspectKind, inspectInput), null, 2),
);
setError("");
} catch (reason) {
setError(
reason instanceof Error
? reason.message
: "Input could not be decoded.",
);
}
};
const verify = async () => {
try {
setVerification(
await verifyAssertion({
...assertion,
requireUserVerification: requireUv,
}),
);
setError("");
} catch (reason) {
setError(
reason instanceof Error
? reason.message
: "Assertion verification failed.",
);
setVerification(null);
}
};
const create = async () => {
setBusy(true);
setError("");
setLiveResult(null);
try {
setCredential(
await createMemoryCredential({
userName,
userDisplayName: userName,
attestation: "none",
}),
);
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Registration failed.",
);
} finally {
setBusy(false);
}
};
const exercise = async () => {
if (!credential) return;
setBusy(true);
setError("");
try {
const result = await exerciseMemoryCredential(credential, requireUv);
setLiveResult(result);
if (result.verified)
setCredential((current) =>
current ? { ...current, signCount: result.signCount } : current,
);
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Authentication failed.",
);
} finally {
setBusy(false);
}
};
const optionExample = useMemo(
() => ({
registration: {
challenge: bytesToBase64Url(randomBytes(32)),
rp: { id: location.hostname, name: "Example relying party" },
user: {
id: bytesToBase64Url(randomBytes(32)),
name: "user@example.org",
displayName: "Example user",
},
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
],
authenticatorSelection: {
residentKey: "preferred",
userVerification: "preferred",
},
timeout: 120000,
attestation: "none",
},
authentication: {
challenge: bytesToBase64Url(randomBytes(32)),
rpId: location.hostname,
userVerification: "preferred",
timeout: 120000,
},
}),
[],
);
return (
<section className="workspace">
<div className="subtabs" role="tablist" aria-label="WebAuthn tasks">
<button
type="button"
className={mode === "inspect" ? "active" : ""}
onClick={() => setMode("inspect")}
>
Inspector
</button>
<button
type="button"
className={mode === "verify" ? "active" : ""}
onClick={() => setMode("verify")}
>
Assertion verifier
</button>
<button
type="button"
className={mode === "options" ? "active" : ""}
onClick={() => setMode("options")}
>
Options builder
</button>
<button
type="button"
className={mode === "live" ? "active" : ""}
onClick={() => setMode("live")}
>
Live ceremony
</button>
</div>
{error && (
<div className="notice error" role="alert">
{error}
<button
type="button"
aria-label="Dismiss error"
onClick={() => setError("")}
>
×
</button>
</div>
)}
{mode === "inspect" && (
<div className="split-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Offline decoder</p>
<h2>WebAuthn structure</h2>
</div>
</div>
<div className="panel-body">
<label>
<span>Input type</span>
<select
value={inspectKind}
onChange={(event) =>
setInspectKind(event.target.value as InspectKind)
}
>
<option value="client">clientDataJSON · Base64url</option>
<option value="attestation">
attestationObject · Base64url CBOR
</option>
<option value="authenticator">
authenticatorData · Base64url
</option>
</select>
</label>
<label>
<span>Encoded input</span>
<textarea
className="mono-input"
rows={16}
spellCheck={false}
value={inspectInput}
onChange={(event) => setInspectInput(event.target.value)}
placeholder="Paste Base64url without a data: prefix"
/>
</label>
<button
type="button"
className="primary-button"
onClick={inspect}
>
Decode locally
</button>
</div>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Bounded parser output</p>
<h2>Decoded fields</h2>
</div>
</div>
{inspectOutput ? (
<pre className="diagnostic-output">{inspectOutput}</pre>
) : (
<div className="empty-state">
<strong>No decoded structure yet</strong>
<span>
CBOR depth, item count and byte size are limited before
parsing.
</span>
</div>
)}
</article>
</div>
)}
{mode === "verify" && (
<div className="split-grid verifier-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Authentication response</p>
<h2>Assertion evidence</h2>
</div>
</div>
<div className="panel-body compact-form">
{(
[
"clientDataJSON",
"authenticatorData",
"signature",
"credentialPublicKey",
] as const
).map((name) => (
<label key={name}>
<span>
{name === "credentialPublicKey"
? "Credential COSE key · JSON labels"
: `${name} · Base64url`}
</span>
<textarea
rows={name === "credentialPublicKey" ? 5 : 3}
spellCheck={false}
value={assertion[name]}
onChange={(event) =>
setAssertion((current) => ({
...current,
[name]: event.target.value,
}))
}
/>
</label>
))}
</div>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Expected ceremony state</p>
<h2>Verification policy</h2>
</div>
</div>
<div className="panel-body compact-form">
{(
["expectedChallenge", "expectedOrigin", "expectedRpId"] as const
).map((name) => (
<label key={name}>
<span>{name.replace("expected", "Expected ")}</span>
<input
value={assertion[name]}
onChange={(event) =>
setAssertion((current) => ({
...current,
[name]: event.target.value,
}))
}
/>
</label>
))}
<label className="check-row">
<input
type="checkbox"
checked={requireUv}
onChange={(event) => setRequireUv(event.target.checked)}
/>
<span>Require the user-verification flag</span>
</label>
<button
type="button"
className="primary-button"
onClick={() => void verify()}
>
Verify all layers
</button>
{verification && <VerificationReport result={verification} />}
</div>
</article>
</div>
)}
{mode === "options" && (
<div className="split-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Serializable hand-off</p>
<h2>Creation options</h2>
</div>
</div>
<pre className="diagnostic-output">
{JSON.stringify(optionExample.registration, null, 2)}
</pre>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Serializable hand-off</p>
<h2>Request options</h2>
</div>
</div>
<pre className="diagnostic-output">
{JSON.stringify(optionExample.authentication, null, 2)}
</pre>
</article>
<p className="wide-note">
Challenges and user handles above are generated locally on each
load. In production, a relying-party server must generate, store and
consume challenges exactly once. This builder never claims that a
JSON shape alone completes a secure ceremony.
</p>
</div>
)}
{mode === "live" && (
<div className="split-grid">
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Browser diagnostics</p>
<h2>Runtime and origin</h2>
</div>
<span
className={`badge ${availability.available ? "success" : "warning"}`}
>
{availability.available ? "Live enabled" : "Inspect only"}
</span>
</div>
<div className="panel-body">
<dl className="capability-list">
<div>
<dt>Effective origin</dt>
<dd>{location.origin}</dd>
</div>
<div>
<dt>RP ID</dt>
<dd>{location.hostname}</dd>
</div>
<div>
<dt>Secure context</dt>
<dd>
{capabilityLabel(capabilities?.secureContext ?? false)}
</dd>
</div>
<div>
<dt>WebAuthn API</dt>
<dd>
{capabilityLabel(
capabilities?.publicKeyCredential ?? false,
)}
</dd>
</div>
<div>
<dt>Platform authenticator</dt>
<dd>
{capabilityLabel(
capabilities?.platformAuthenticator ?? null,
)}
</dd>
</div>
<div>
<dt>Conditional mediation</dt>
<dd>
{capabilityLabel(
capabilities?.conditionalMediation ?? null,
)}
</dd>
</div>
</dl>
<p className="origin-explanation">{availability.reason}</p>
{!availability.available && (
<a
className="primary-button centered-link"
href={`https://${LIVE_HOST}/`}
>
Open isolated ceremony lab
</a>
)}
</div>
</article>
<article className="panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Ephemeral relying party</p>
<h2>Registration and authentication</h2>
</div>
</div>
<div className="panel-body compact-form">
<label>
<span>Local username</span>
<input
value={userName}
maxLength={128}
onChange={(event) => setUserName(event.target.value)}
/>
</label>
<label className="check-row">
<input
type="checkbox"
checked={requireUv}
onChange={(event) => setRequireUv(event.target.checked)}
/>
<span>Require user verification during authentication</span>
</label>
<div className="button-row">
<button
type="button"
className="primary-button"
disabled={!availability.available || busy}
onClick={() => void create()}
>
{busy
? "Waiting for browser…"
: credential
? "Replace test credential"
: "Create test credential"}
</button>
<button
type="button"
className="secondary-button"
disabled={!credential || busy}
onClick={() => void exercise()}
>
Authenticate
</button>
</div>
{credential && (
<div className="credential-card">
<strong>Credential held in this tab</strong>
<code>{credential.id}</code>
<span>
{credential.format} attestation · AAGUID {credential.aaguid}{" "}
· counter {credential.signCount}
</span>
<button
type="button"
className="link-button"
onClick={() => {
setCredential(null);
setLiveResult(null);
}}
>
Forget now
</button>
</div>
)}
{liveResult && <VerificationReport result={liveResult} />}
</div>
</article>
</div>
)}
</section>
);
}
function VerificationReport({
result,
}: {
result: AssertionVerificationResult;
}) {
return (
<div className="verification-report" aria-live="polite">
<strong>
{result.verified ? "Assertion verified" : "Assertion rejected"}
</strong>
<ul>
{result.checks.map((check) => (
<li key={check.name} className={check.status}>
<span>
{check.status === "pass"
? "✓"
: check.status === "fail"
? "×"
: "i"}
</span>
<div>
<b>{check.name}</b>
<small>{check.detail}</small>
</div>
</li>
))}
</ul>
</div>
);
}
+132
View File
@@ -0,0 +1,132 @@
export class EncodingError extends Error {
constructor(message: string) {
super(message);
this.name = "EncodingError";
}
}
const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
export function bytesToHex(bytes: Uint8Array): string {
return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
export function bytesToArrayBuffer(bytes: Uint8Array): ArrayBuffer {
return Uint8Array.from(bytes).buffer;
}
export function hexToBytes(input: string): Uint8Array {
const normalized = input.replace(/[\s:-]/gu, "");
if (normalized.length === 0) return new Uint8Array();
if (normalized.length % 2 !== 0 || !/^[0-9a-f]+$/iu.test(normalized)) {
throw new EncodingError(
"Hexadecimal input must contain complete byte pairs.",
);
}
const output = new Uint8Array(normalized.length / 2);
for (let index = 0; index < output.length; index += 1) {
output[index] = Number.parseInt(
normalized.slice(index * 2, index * 2 + 2),
16,
);
}
return output;
}
export function bytesToBase32(bytes: Uint8Array): string {
let buffer = 0;
let bits = 0;
let output = "";
for (const byte of bytes) {
buffer = (buffer << 8) | byte;
bits += 8;
while (bits >= 5) {
bits -= 5;
output += BASE32_ALPHABET[(buffer >>> bits) & 31];
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) output += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];
return output;
}
export interface Base32DecodeOptions {
allowPadding?: boolean;
allowSeparators?: boolean;
}
export function base32ToBytes(
input: string,
options: Base32DecodeOptions = {},
): Uint8Array {
let normalized = input.trim().toUpperCase();
if (options.allowSeparators) normalized = normalized.replace(/[\s-]/gu, "");
if (options.allowPadding) normalized = normalized.replace(/=+$/u, "");
if (normalized.length === 0) return new Uint8Array();
if (!/^[A-Z2-7]+$/u.test(normalized)) {
throw new EncodingError("Base32 uses only AZ and 27.");
}
const output: number[] = [];
let buffer = 0;
let bits = 0;
for (const character of normalized) {
buffer = (buffer << 5) | BASE32_ALPHABET.indexOf(character);
bits += 5;
if (bits >= 8) {
bits -= 8;
output.push((buffer >>> bits) & 0xff);
buffer &= (1 << bits) - 1;
}
}
if (bits > 0 && buffer !== 0) {
throw new EncodingError("Base32 has non-zero trailing bits.");
}
return Uint8Array.from(output);
}
export function bytesToBase64Url(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replace(/=+$/u, "");
}
export function base64UrlToBytes(input: string): Uint8Array {
const normalized = input.trim();
if (!/^[A-Za-z0-9_-]*={0,2}$/u.test(normalized)) {
throw new EncodingError("Input is not valid unpadded Base64url.");
}
const raw = normalized.replaceAll("-", "+").replaceAll("_", "/");
const padded = raw.padEnd(Math.ceil(raw.length / 4) * 4, "=");
try {
const binary = atob(padded);
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
} catch {
throw new EncodingError("Input is not valid Base64url.");
}
}
export function utf8ToBytes(input: string): Uint8Array {
return new TextEncoder().encode(input);
}
export function bytesToUtf8(input: Uint8Array): string {
try {
return new TextDecoder("utf-8", { fatal: true }).decode(input);
} catch {
throw new EncodingError("Bytes are not valid UTF-8.");
}
}
export function randomBytes(length: number): Uint8Array {
if (!Number.isInteger(length) || length < 16 || length > 1024) {
throw new RangeError(
"Random secret length must be between 16 and 1024 bytes.",
);
}
const output = new Uint8Array(length);
crypto.getRandomValues(output);
return output;
}
+9
View File
@@ -0,0 +1,9 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
+423
View File
@@ -0,0 +1,423 @@
import { base32ToBytes, bytesToBase32 } from "../crypto/encoding";
import type { OtpHashAlgorithm } from "./otp";
import { parseOtpAuth, serializeOtpAuth, type OtpProfile } from "./profile";
export interface ImportResult {
profiles: OtpProfile[];
warnings: string[];
}
const MAX_IMPORT_BYTES = 4 * 1024 * 1024;
function utf8(bytes: Uint8Array): string {
try {
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
throw new Error("Migration payload contains invalid UTF-8.");
}
}
function readVarint(bytes: Uint8Array, state: { offset: number }): bigint {
let value = 0n;
for (let shift = 0n; shift < 70n; shift += 7n) {
if (state.offset >= bytes.length)
throw new Error("Protocol Buffer value is truncated.");
const byte = bytes[state.offset++]!;
value |= BigInt(byte & 0x7f) << shift;
if (!(byte & 0x80)) return value;
}
throw new Error("Protocol Buffer integer is too large.");
}
function readProto(bytes: Uint8Array): Map<number, Array<bigint | Uint8Array>> {
const fields = new Map<number, Array<bigint | Uint8Array>>();
const state = { offset: 0 };
while (state.offset < bytes.length) {
const tag = readVarint(bytes, state);
const field = Number(tag >> 3n);
const wire = Number(tag & 7n);
if (field <= 0)
throw new Error("Protocol Buffer contains an invalid field number.");
let value: bigint | Uint8Array;
if (wire === 0) value = readVarint(bytes, state);
else if (wire === 2) {
const length = Number(readVarint(bytes, state));
if (
!Number.isSafeInteger(length) ||
length < 0 ||
state.offset + length > bytes.length
)
throw new Error("Protocol Buffer field length is invalid.");
value = bytes.slice(state.offset, state.offset + length);
state.offset += length;
} else if (wire === 1) {
if (state.offset + 8 > bytes.length)
throw new Error("Protocol Buffer field is truncated.");
value = bytes.slice(state.offset, state.offset + 8);
state.offset += 8;
} else if (wire === 5) {
if (state.offset + 4 > bytes.length)
throw new Error("Protocol Buffer field is truncated.");
value = bytes.slice(state.offset, state.offset + 4);
state.offset += 4;
} else throw new Error(`Unsupported Protocol Buffer wire type ${wire}.`);
const list = fields.get(field) ?? [];
list.push(value);
fields.set(field, list);
}
return fields;
}
function firstBytes(
fields: Map<number, Array<bigint | Uint8Array>>,
number: number,
): Uint8Array | undefined {
const value = fields.get(number)?.[0];
return value instanceof Uint8Array ? value : undefined;
}
function firstInt(
fields: Map<number, Array<bigint | Uint8Array>>,
number: number,
fallback = 0n,
): bigint {
const value = fields.get(number)?.[0];
return typeof value === "bigint" ? value : fallback;
}
function parseMigrationParameter(
bytes: Uint8Array,
warnings: string[],
): OtpProfile {
const fields = readProto(bytes);
const secret = firstBytes(fields, 1);
if (!secret?.length)
throw new Error("Google migration credential has no secret.");
const name = firstBytes(fields, 2)
? utf8(firstBytes(fields, 2)!)
: "Imported account";
const issuer = firstBytes(fields, 3) ? utf8(firstBytes(fields, 3)!) : "";
const algorithms: Record<string, OtpHashAlgorithm> = {
"0": "SHA-1",
"1": "SHA-1",
"2": "SHA-256",
"3": "SHA-512",
};
const algorithmCode = firstInt(fields, 4).toString();
const algorithm = algorithms[algorithmCode];
if (!algorithm)
throw new Error(`Unsupported Google migration hash code ${algorithmCode}.`);
const digitCode = Number(firstInt(fields, 5, 1n));
const digits = digitCode === 2 ? 8 : 6;
if (digitCode !== 0 && digitCode !== 1 && digitCode !== 2)
warnings.push(`Unknown digit code ${digitCode}; interpreted as 6 digits.`);
const typeCode = Number(firstInt(fields, 6, 2n));
if (typeCode !== 1 && typeCode !== 2)
throw new Error(`Unsupported Google migration OTP type ${typeCode}.`);
return {
kind: typeCode === 1 ? "hotp" : "totp",
secret,
issuer,
account: name,
algorithm,
digits,
period: 30,
counter: firstInt(fields, 7),
extensions: new Map(),
};
}
function decodeStandardBase64(input: string): Uint8Array {
const normalized = input
.replaceAll(" ", "+")
.replaceAll("-", "+")
.replaceAll("_", "/");
if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized))
throw new Error("Migration data is not valid Base64.");
try {
return Uint8Array.from(
atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=")),
(value) => value.charCodeAt(0),
);
} catch {
throw new Error("Migration data is not valid Base64.");
}
}
export function importGoogleMigration(input: string): ImportResult {
if (input.length > MAX_IMPORT_BYTES * 2)
throw new Error("Migration URI is too large.");
const url = new URL(input);
if (url.protocol !== "otpauth-migration:" || url.hostname !== "offline")
throw new Error("Expected an otpauth-migration://offline URI.");
const data = url.searchParams.get("data");
if (!data) throw new Error("Migration URI has no data parameter.");
const payload = decodeStandardBase64(data);
if (payload.byteLength > MAX_IMPORT_BYTES)
throw new Error("Migration payload is too large.");
const fields = readProto(payload);
const warnings: string[] = [];
const version = firstInt(fields, 2, 1n);
if (version !== 1n)
warnings.push(
`Migration payload version ${version.toString()} is not documented by this importer.`,
);
const batchSize = firstInt(fields, 3, 1n);
if (batchSize > 1n)
warnings.push(
`This is one part of a ${batchSize.toString()}-QR migration batch; import all parts.`,
);
const parameters = fields.get(1) ?? [];
const profiles = parameters.map((value) => {
if (!(value instanceof Uint8Array))
throw new Error("Migration credential has an invalid wire type.");
return parseMigrationParameter(value, warnings);
});
if (!profiles.length)
throw new Error("Migration payload contains no OTP credentials.");
return { profiles, warnings };
}
function csvRows(input: string): string[][] {
if (input.length > MAX_IMPORT_BYTES)
throw new Error("CSV input is too large.");
const rows: string[][] = [];
let row: string[] = [];
let field = "";
let quoted = false;
for (let index = 0; index < input.length; index += 1) {
const character = input[index]!;
if (quoted) {
if (character === '"' && input[index + 1] === '"') {
field += '"';
index += 1;
} else if (character === '"') quoted = false;
else field += character;
} else if (character === '"' && field === "") quoted = true;
else if (character === ",") {
row.push(field);
field = "";
} else if (character === "\n") {
row.push(field.replace(/\r$/u, ""));
rows.push(row);
row = [];
field = "";
} else field += character;
}
if (quoted) throw new Error("CSV contains an unterminated quoted field.");
if (field || row.length) {
row.push(field);
rows.push(row);
}
return rows.filter((item) => item.some(Boolean));
}
export function importCsv(input: string): ImportResult {
const rows = csvRows(input);
const header = rows.shift()?.map((value) => value.trim().toLowerCase());
if (!header) throw new Error("CSV is empty.");
const find = (name: string): number => header.indexOf(name);
for (const required of ["type", "account", "secret"])
if (find(required) < 0)
throw new Error(`CSV requires a ${required} column.`);
const warnings: string[] = [];
const profiles = rows.map((row, rowIndex): OtpProfile => {
const get = (name: string): string => row[find(name)]?.trim() ?? "";
const unprotect = (value: string): string =>
/^'[=+\-@\t\r]/u.test(value) ? value.slice(1) : value;
const kind = get("type").toLowerCase();
if (kind !== "totp" && kind !== "hotp")
throw new Error(`CSV row ${rowIndex + 2} has an invalid type.`);
const algorithmText =
get("algorithm").toUpperCase().replace("-", "") || "SHA1";
const algorithm = (
{ SHA1: "SHA-1", SHA256: "SHA-256", SHA512: "SHA-512" } as Record<
string,
OtpHashAlgorithm | undefined
>
)[algorithmText];
if (!algorithm)
throw new Error(`CSV row ${rowIndex + 2} has an unsupported algorithm.`);
const digits = Number(get("digits") || 6);
const period = Number(get("period") || 30);
const counterText = get("counter") || "0";
if (
!Number.isInteger(digits) ||
digits < 6 ||
digits > 10 ||
!Number.isInteger(period) ||
period < 1 ||
!/^\d+$/u.test(counterText)
)
throw new Error(
`CSV row ${rowIndex + 2} contains an invalid numeric field.`,
);
const account = unprotect(get("account"));
const issuer = unprotect(get("issuer"));
const secret = base32ToBytes(get("secret"), {
allowPadding: true,
allowSeparators: true,
});
if (!account || !secret.byteLength)
throw new Error(
`CSV row ${rowIndex + 2} requires an account and non-empty secret.`,
);
if (secret.byteLength > 1024)
throw new Error(`CSV row ${rowIndex + 2} secret is too large.`);
return {
kind,
account,
issuer,
secret,
algorithm,
digits,
period,
counter: BigInt(counterText),
extensions: new Map(),
};
});
if (!profiles.length)
warnings.push("CSV contains a header but no credentials.");
return { profiles, warnings };
}
function csvField(value: string): string {
const protectedValue = /^[=+\-@\t\r]/u.test(value) ? `'${value}` : value;
return /[",\r\n]/u.test(protectedValue)
? `"${protectedValue.replaceAll('"', '""')}"`
: protectedValue;
}
export function exportCsv(profiles: readonly OtpProfile[]): string {
const rows = [
[
"type",
"account",
"issuer",
"secret",
"algorithm",
"digits",
"period",
"counter",
],
];
for (const profile of profiles)
rows.push([
profile.kind,
profile.account,
profile.issuer,
bytesToBase32(profile.secret),
profile.algorithm,
String(profile.digits),
String(profile.period),
String(profile.counter),
]);
return `${rows.map((row) => row.map(csvField).join(",")).join("\r\n")}\r\n`;
}
export function importOtpAuthList(input: string): ImportResult {
if (input.length > MAX_IMPORT_BYTES)
throw new Error("Provisioning list is too large.");
const warnings: string[] = [];
const profiles = input
.split(/\r?\n/gu)
.map((line) => line.trim())
.filter(Boolean)
.map((line, index) => {
try {
const parsed = parseOtpAuth(line);
warnings.push(
...parsed.warnings.map(
(warning) => `Line ${index + 1}: ${warning.message}`,
),
);
return parsed.profile;
} catch (error) {
throw new Error(
`Line ${index + 1}: ${error instanceof Error ? error.message : "Invalid provisioning URI."}`,
{ cause: error },
);
}
});
return { profiles, warnings };
}
export function exportOtpAuthList(profiles: readonly OtpProfile[]): string {
return `${profiles.map(serializeOtpAuth).join("\n")}\n`;
}
function localName(element: Element, name: string): Element | undefined {
return [...element.getElementsByTagNameNS("*", name)][0];
}
export function importPlainPskc(input: string): ImportResult {
if (input.length > MAX_IMPORT_BYTES)
throw new Error("PSKC input is too large.");
const document = new DOMParser().parseFromString(input, "application/xml");
if (document.querySelector("parsererror"))
throw new Error("PSKC is not well-formed XML.");
const packages = [...document.getElementsByTagNameNS("*", "KeyPackage")];
const warnings: string[] = [];
const profiles = packages.map((keyPackage, index): OtpProfile => {
if (localName(keyPackage, "EncryptedValue"))
throw new Error(
`PSKC key ${index + 1} is encrypted; decrypt it in its source system first.`,
);
const plain = localName(keyPackage, "PlainValue")?.textContent?.trim();
if (!plain) throw new Error(`PSKC key ${index + 1} has no plain secret.`);
const secret = decodeStandardBase64(plain);
if (!secret.byteLength || secret.byteLength > 1024)
throw new Error(`PSKC key ${index + 1} secret length is invalid.`);
const key = localName(keyPackage, "Key");
const algorithmUri = key?.getAttribute("Algorithm") ?? "";
const kind = /hotp/iu.test(algorithmUri)
? "hotp"
: /totp/iu.test(algorithmUri)
? "totp"
: null;
if (!kind)
throw new Error(
`PSKC key ${index + 1} does not declare a supported HOTP/TOTP algorithm.`,
);
const responseFormat = localName(keyPackage, "ResponseFormat");
const digits = Number(responseFormat?.getAttribute("Length") ?? 6);
const account =
localName(keyPackage, "FriendlyName")?.textContent?.trim() ||
key?.getAttribute("Id") ||
`PSKC key ${index + 1}`;
const issuer = localName(keyPackage, "Issuer")?.textContent?.trim() ?? "";
const counterText =
localName(keyPackage, "Counter")?.textContent?.trim() ?? "0";
const periodText =
localName(keyPackage, "TimeInterval")?.textContent?.trim() ?? "30";
if (
!/^\d+$/u.test(counterText) ||
!/^\d+$/u.test(periodText) ||
!Number.isInteger(digits) ||
digits < 6 ||
digits > 10 ||
Number(periodText) < 1 ||
Number(periodText) > 86_400 ||
BigInt(counterText) > (1n << 64n) - 1n
)
throw new Error(`PSKC key ${index + 1} has invalid moving-factor data.`);
if (!/sha1/iu.test(algorithmUri) && algorithmUri)
warnings.push(
`PSKC key ${index + 1}: algorithm URI is not a recognized HOTP/TOTP SHA-1 profile.`,
);
return {
kind,
secret,
issuer,
account,
algorithm: "SHA-1",
digits,
period: Number(periodText),
counter: BigInt(counterText),
extensions: new Map(),
};
});
if (!profiles.length)
throw new Error("PSKC contains no KeyPackage elements.");
return { profiles, warnings };
}
+249
View File
@@ -0,0 +1,249 @@
import {
bytesToArrayBuffer,
bytesToHex,
hexToBytes,
utf8ToBytes,
} from "../crypto/encoding";
import type { OtpHashAlgorithm } from "./otp";
export interface OcraSuite {
source: string;
algorithm: OtpHashAlgorithm;
digits: number;
counter: boolean;
questionFormat: "numeric" | "alphanumeric" | "hexadecimal";
questionLength: number;
passwordAlgorithm?: OtpHashAlgorithm;
sessionLength?: number;
timeStepSeconds?: number;
}
export interface OcraInput {
suite: string | OcraSuite;
secret: Uint8Array;
question: string;
counter?: bigint;
passwordHash?: Uint8Array;
session?: Uint8Array;
timestamp?: number;
timeStep?: bigint;
}
const HASH_NAMES: Record<string, OtpHashAlgorithm | undefined> = {
SHA1: "SHA-1",
SHA256: "SHA-256",
SHA512: "SHA-512",
};
const HASH_LENGTHS: Record<OtpHashAlgorithm, number> = {
"SHA-1": 20,
"SHA-256": 32,
"SHA-512": 64,
};
function parseQuestion(
token: string,
): Pick<OcraSuite, "questionFormat" | "questionLength"> {
const match = /^Q([ANH])(\d{1,2})$/u.exec(token);
if (!match)
throw new Error("OCRA DataInput must contain a QFxx challenge descriptor.");
const length = Number(match[2]);
if (length < 4 || length > 64)
throw new Error("OCRA challenge length must be between 4 and 64.");
const format = (
{ A: "alphanumeric", N: "numeric", H: "hexadecimal" } as const
)[match[1] as "A" | "N" | "H"];
return { questionFormat: format, questionLength: length };
}
export function parseOcraSuite(input: string): OcraSuite {
if (input.length > 256 || input.trim() !== input)
throw new Error("OCRA suite is malformed or too long.");
const parts = input.split(":");
if (parts.length !== 3 || parts[0] !== "OCRA-1")
throw new Error("Only the OCRA-1 suite version is supported.");
const cryptoMatch = /^HOTP-(SHA1|SHA256|SHA512)-(0|[4-9]|10)$/u.exec(
parts[1]!,
);
if (!cryptoMatch)
throw new Error(
"OCRA CryptoFunction must be HOTP-SHA1/SHA256/SHA512 with 0 or 410 digits.",
);
const algorithm = HASH_NAMES[cryptoMatch[1]!]!;
const digits = Number(cryptoMatch[2]);
const tokens = parts[2]!.split("-");
let index = 0;
const counter = tokens[index] === "C";
if (counter) index += 1;
const question = parseQuestion(tokens[index] ?? "");
index += 1;
let passwordAlgorithm: OtpHashAlgorithm | undefined;
let sessionLength: number | undefined;
let timeStepSeconds: number | undefined;
for (; index < tokens.length; index += 1) {
const token = tokens[index]!;
if (token.startsWith("P")) {
if (
passwordAlgorithm ||
sessionLength !== undefined ||
timeStepSeconds !== undefined
)
throw new Error("OCRA password input is duplicated or out of order.");
passwordAlgorithm = HASH_NAMES[token.slice(1)];
if (!passwordAlgorithm)
throw new Error("OCRA password hash must be SHA1, SHA256 or SHA512.");
} else if (token.startsWith("S")) {
if (
sessionLength !== undefined ||
timeStepSeconds !== undefined ||
!/^S\d{3}$/u.test(token)
)
throw new Error("OCRA session input is duplicated or out of order.");
sessionLength = Number(token.slice(1));
if (sessionLength < 1 || sessionLength > 512)
throw new Error("OCRA session length must be between 1 and 512 bytes.");
} else if (token.startsWith("T")) {
if (timeStepSeconds !== undefined)
throw new Error("OCRA timestamp input is duplicated.");
const timeMatch = /^T(\d{1,2})([SMH])$/u.exec(token);
if (!timeMatch)
throw new Error("OCRA timestamp must use seconds, minutes or hours.");
const amount = Number(timeMatch[1]);
const unit = timeMatch[2]!;
if ((unit === "S" || unit === "M") && (amount < 1 || amount > 59))
throw new Error("OCRA second/minute steps must be between 1 and 59.");
if (unit === "H" && (amount < 1 || amount > 48))
throw new Error("OCRA hour steps must be between 1 and 48.");
timeStepSeconds = amount * (unit === "S" ? 1 : unit === "M" ? 60 : 3600);
} else throw new Error(`Unsupported OCRA DataInput token ${token}.`);
}
return {
source: input,
algorithm,
digits,
counter,
...question,
...(passwordAlgorithm ? { passwordAlgorithm } : {}),
...(sessionLength !== undefined ? { sessionLength } : {}),
...(timeStepSeconds !== undefined ? { timeStepSeconds } : {}),
};
}
function unsigned64(value: bigint, name: string): Uint8Array {
if (value < 0n || value > (1n << 64n) - 1n)
throw new Error(`${name} must be an unsigned 64-bit integer.`);
const bytes = new Uint8Array(8);
for (let index = 7; index >= 0; index -= 1) {
bytes[index] = Number(value & 0xffn);
value >>= 8n;
}
return bytes;
}
function questionBytes(suite: OcraSuite, question: string): Uint8Array {
if (question.length === 0 || question.length > suite.questionLength)
throw new Error(
`OCRA question must contain 1${suite.questionLength} ${suite.questionFormat} characters.`,
);
if (suite.questionFormat === "numeric") {
if (!/^\d+$/u.test(question))
throw new Error("OCRA numeric question contains a non-digit.");
return hexToBytes(BigInt(question).toString(16).padEnd(256, "0"));
}
if (suite.questionFormat === "hexadecimal") {
if (!/^[0-9a-f]+$/iu.test(question))
throw new Error(
"OCRA hexadecimal question contains an invalid character.",
);
return hexToBytes(question.padEnd(256, "0"));
}
if (!/^[A-Za-z0-9]+$/u.test(question))
throw new Error("OCRA alphanumeric questions use only AZ, az and 09.");
return utf8ToBytes(question);
}
export async function hashOcraPassword(
password: string,
algorithm: OtpHashAlgorithm,
): Promise<Uint8Array> {
if (password.length > 4096)
throw new Error("OCRA password input is too large.");
return new Uint8Array(
await crypto.subtle.digest(
algorithm,
bytesToArrayBuffer(utf8ToBytes(password)),
),
);
}
export async function ocra(input: OcraInput): Promise<string> {
const suite =
typeof input.suite === "string" ? parseOcraSuite(input.suite) : input.suite;
if (!input.secret.byteLength || input.secret.byteLength > 1024)
throw new Error("An OCRA secret is required.");
const pieces: Uint8Array[] = [utf8ToBytes(suite.source), Uint8Array.of(0)];
if (suite.counter) {
if (input.counter === undefined)
throw new Error("This OCRA suite requires a counter.");
pieces.push(unsigned64(input.counter, "OCRA counter"));
}
const question = questionBytes(suite, input.question);
if (question.byteLength > 128)
throw new Error("OCRA question encoding exceeds 128 bytes.");
const paddedQuestion = new Uint8Array(128);
paddedQuestion.set(question);
pieces.push(paddedQuestion);
if (suite.passwordAlgorithm) {
if (!input.passwordHash)
throw new Error("This OCRA suite requires a pre-hashed password/PIN.");
if (input.passwordHash.byteLength !== HASH_LENGTHS[suite.passwordAlgorithm])
throw new Error(
`OCRA ${suite.passwordAlgorithm} password hash has the wrong length.`,
);
pieces.push(input.passwordHash);
}
if (suite.sessionLength !== undefined) {
if (!input.session)
throw new Error("This OCRA suite requires session data.");
if (input.session.byteLength > suite.sessionLength)
throw new Error("OCRA session data exceeds the suite length.");
const session = new Uint8Array(suite.sessionLength);
session.set(input.session, suite.sessionLength - input.session.byteLength);
pieces.push(session);
}
if (suite.timeStepSeconds !== undefined) {
const timeStep =
input.timeStep ??
BigInt(
Math.floor(
(input.timestamp ?? Date.now() / 1000) / suite.timeStepSeconds,
),
);
pieces.push(unsigned64(timeStep, "OCRA time step"));
}
const length = pieces.reduce((sum, piece) => sum + piece.byteLength, 0);
const data = new Uint8Array(length);
let offset = 0;
for (const piece of pieces) {
data.set(piece, offset);
offset += piece.byteLength;
}
const key = await crypto.subtle.importKey(
"raw",
bytesToArrayBuffer(input.secret),
{ name: "HMAC", hash: suite.algorithm },
false,
["sign"],
);
const digest = new Uint8Array(
await crypto.subtle.sign("HMAC", key, bytesToArrayBuffer(data)),
);
if (suite.digits === 0) return bytesToHex(digest);
const truncationOffset = digest.at(-1)! & 0x0f;
const binary =
((digest[truncationOffset]! & 0x7f) << 24) |
((digest[truncationOffset + 1]! & 0xff) << 16) |
((digest[truncationOffset + 2]! & 0xff) << 8) |
(digest[truncationOffset + 3]! & 0xff);
return (binary % 10 ** suite.digits).toString().padStart(suite.digits, "0");
}
+165
View File
@@ -0,0 +1,165 @@
import { bytesToArrayBuffer } from "../crypto/encoding";
export type OtpHashAlgorithm = "SHA-1" | "SHA-256" | "SHA-512";
export type OtpKind = "hotp" | "totp";
export interface HotpOptions {
secret: Uint8Array;
counter: bigint;
digits?: number;
algorithm?: OtpHashAlgorithm;
}
export interface TotpOptions extends Omit<HotpOptions, "counter"> {
timestamp?: number;
period?: number;
epoch?: number;
}
export interface OtpMatch {
code: string;
counter: bigint;
delta: number;
}
export const MAX_HOTP_COUNTER = (1n << 64n) - 1n;
function validateSecret(secret: Uint8Array): void {
if (
!ArrayBuffer.isView(secret) ||
secret.BYTES_PER_ELEMENT !== 1 ||
secret.byteLength === 0
) {
throw new TypeError("An OTP secret is required.");
}
if (secret.byteLength > 1024)
throw new RangeError("OTP secret is too large.");
}
function validateDigits(digits: number): void {
if (!Number.isInteger(digits) || digits < 6 || digits > 10) {
throw new RangeError("OTP digits must be an integer between 6 and 10.");
}
}
function counterBytes(counter: bigint): Uint8Array {
if (counter < 0n || counter > MAX_HOTP_COUNTER) {
throw new RangeError("HOTP counter must be an unsigned 64-bit value.");
}
const output = new Uint8Array(8);
let remaining = counter;
for (let index = 7; index >= 0; index -= 1) {
output[index] = Number(remaining & 0xffn);
remaining >>= 8n;
}
return output;
}
export async function hotp(options: HotpOptions): Promise<string> {
validateSecret(options.secret);
const digits = options.digits ?? 6;
const algorithm = options.algorithm ?? "SHA-1";
validateDigits(digits);
const key = await crypto.subtle.importKey(
"raw",
bytesToArrayBuffer(options.secret),
{ name: "HMAC", hash: algorithm },
false,
["sign"],
);
const digest = new Uint8Array(
await crypto.subtle.sign(
"HMAC",
key,
bytesToArrayBuffer(counterBytes(options.counter)),
),
);
const offset = (digest.at(-1) ?? 0) & 0x0f;
if (offset + 3 >= digest.length) throw new Error("HMAC result is too short.");
const binary =
((digest[offset]! & 0x7f) << 24) |
((digest[offset + 1]! & 0xff) << 16) |
((digest[offset + 2]! & 0xff) << 8) |
(digest[offset + 3]! & 0xff);
return (binary % 10 ** digits).toString().padStart(digits, "0");
}
export function totpCounter(timestamp: number, period = 30, epoch = 0): bigint {
if (!Number.isFinite(timestamp) || timestamp < 0) {
throw new RangeError("TOTP timestamp must be a non-negative Unix time.");
}
if (!Number.isInteger(period) || period < 1 || period > 86_400) {
throw new RangeError("TOTP period must be between 1 and 86400 seconds.");
}
if (!Number.isFinite(epoch) || epoch < 0 || epoch > timestamp) {
throw new RangeError("TOTP epoch must not exceed the timestamp.");
}
return BigInt(Math.floor((timestamp - epoch) / period));
}
export async function totp(options: TotpOptions): Promise<string> {
const timestamp = options.timestamp ?? Date.now() / 1000;
return hotp({
secret: options.secret,
counter: totpCounter(timestamp, options.period, options.epoch),
digits: options.digits,
algorithm: options.algorithm,
});
}
function normalizeCode(code: string, digits: number): string | null {
const normalized = code.replace(/[\s-]/gu, "");
return new RegExp(`^[0-9]{${digits}}$`, "u").test(normalized)
? normalized
: null;
}
export async function verifyTotp(
code: string,
options: TotpOptions & { window?: number },
): Promise<OtpMatch | null> {
const digits = options.digits ?? 6;
validateDigits(digits);
const normalized = normalizeCode(code, digits);
if (!normalized) return null;
const window = options.window ?? 1;
if (!Number.isInteger(window) || window < 0 || window > 100) {
throw new RangeError("Diagnostic TOTP window must be between 0 and 100.");
}
const baseCounter = totpCounter(
options.timestamp ?? Date.now() / 1000,
options.period,
options.epoch,
);
for (let distance = 0; distance <= window; distance += 1) {
const deltas = distance === 0 ? [0] : [-distance, distance];
for (const delta of deltas) {
const counter = baseCounter + BigInt(delta);
if (counter < 0n) continue;
const candidate = await hotp({ ...options, counter, digits });
if (candidate === normalized) return { code: candidate, counter, delta };
}
}
return null;
}
export async function verifyHotp(
code: string,
options: HotpOptions & { lookAhead?: number },
): Promise<OtpMatch | null> {
const digits = options.digits ?? 6;
validateDigits(digits);
const normalized = normalizeCode(code, digits);
if (!normalized) return null;
const lookAhead = options.lookAhead ?? 10;
if (!Number.isInteger(lookAhead) || lookAhead < 0 || lookAhead > 10_000) {
throw new RangeError("HOTP look-ahead must be between 0 and 10000.");
}
for (let delta = 0; delta <= lookAhead; delta += 1) {
const counter = options.counter + BigInt(delta);
if (counter > MAX_HOTP_COUNTER) break;
const candidate = await hotp({ ...options, counter, digits });
if (candidate === normalized) return { code: candidate, counter, delta };
}
return null;
}
+262
View File
@@ -0,0 +1,262 @@
import { base32ToBytes, bytesToBase32 } from "../crypto/encoding";
import type { OtpHashAlgorithm, OtpKind } from "./otp";
export interface OtpProfile {
kind: OtpKind;
secret: Uint8Array;
issuer: string;
account: string;
algorithm: OtpHashAlgorithm;
digits: number;
period: number;
counter: bigint;
extensions: ReadonlyMap<string, string>;
}
export interface OtpProfileWarning {
code:
| "issuer-mismatch"
| "short-secret"
| "nonstandard-digits"
| "nonstandard-period"
| "extension";
message: string;
}
const HASH_FROM_URI: Record<string, OtpHashAlgorithm> = {
SHA1: "SHA-1",
SHA256: "SHA-256",
SHA512: "SHA-512",
};
export interface ParsedOtpAuth {
profile: OtpProfile;
warnings: OtpProfileWarning[];
}
function decodeComponent(value: string, field: string): string {
try {
return decodeURIComponent(value);
} catch {
throw new Error(`${field} contains invalid percent encoding.`);
}
}
function integerParameter(
value: string | undefined,
fallback: string,
name: string,
): number {
const text = value ?? fallback;
if (!/^\d+$/u.test(text))
throw new Error(`${name} must be an unsigned integer.`);
return Number(text);
}
function hasUnsafeLabelCharacter(value: string): boolean {
return [...value].some((character) => {
const code = character.codePointAt(0)!;
return character === ":" || code <= 31 || code === 127;
});
}
export function parseOtpAuth(input: string): ParsedOtpAuth {
if (input.length > 16_384) throw new Error("Provisioning URI is too large.");
let url: URL;
try {
url = new URL(input);
} catch {
throw new Error("Provisioning input is not a valid URI.");
}
if (url.protocol.toLowerCase() !== "otpauth:") {
throw new Error("Expected an otpauth:// provisioning URI.");
}
const kind = url.hostname.toLowerCase();
if (kind !== "hotp" && kind !== "totp") {
throw new Error("OTP type must be HOTP or TOTP.");
}
const parameters = new Map<string, string>();
for (const [rawName, value] of url.searchParams) {
const name = rawName.toLowerCase();
if (parameters.has(name)) throw new Error(`Duplicate ${name} parameter.`);
parameters.set(name, value);
}
const secretText = parameters.get("secret");
if (!secretText)
throw new Error("Provisioning URI does not contain a secret.");
const secret = base32ToBytes(secretText, {
allowPadding: true,
allowSeparators: false,
});
if (secret.byteLength === 0) throw new Error("OTP secret is empty.");
const rawLabel = url.pathname.replace(/^\//u, "");
if (!rawLabel)
throw new Error("Provisioning URI does not contain an account label.");
const separator = /:|%3a/iu.exec(rawLabel);
const issuerLabel = separator
? decodeComponent(rawLabel.slice(0, separator.index), "Issuer label")
: "";
const account = decodeComponent(
separator
? rawLabel
.slice(separator.index + separator[0].length)
.replace(/^(?:%20)+/iu, "")
: rawLabel,
"Account label",
);
if (!account) throw new Error("Provisioning account label is empty.");
if (issuerLabel.includes(":") || account.includes(":")) {
throw new Error("Issuer and account labels must not contain a colon.");
}
const issuer = parameters.get("issuer") ?? issuerLabel;
const algorithmText = (parameters.get("algorithm") ?? "SHA1").toUpperCase();
const algorithm = HASH_FROM_URI[algorithmText];
if (!algorithm)
throw new Error(`Unsupported OTP algorithm: ${algorithmText}.`);
const digits = integerParameter(parameters.get("digits"), "6", "OTP digits");
if (!Number.isInteger(digits) || digits < 6 || digits > 10) {
throw new Error("OTP digits must be between 6 and 10.");
}
const period = integerParameter(
parameters.get("period"),
"30",
"TOTP period",
);
if (!Number.isInteger(period) || period < 1 || period > 86_400) {
throw new Error("TOTP period is outside the supported range.");
}
const counterText = parameters.get("counter");
if (kind === "hotp" && counterText === undefined) {
throw new Error("HOTP provisioning requires a counter.");
}
if (counterText !== undefined && !/^\d+$/u.test(counterText)) {
throw new Error("HOTP counter must be an unsigned integer.");
}
const counter = BigInt(counterText ?? "0");
if (counter > (1n << 64n) - 1n)
throw new Error("HOTP counter exceeds 64 bits.");
const known = new Set([
"secret",
"issuer",
"algorithm",
"digits",
"period",
"counter",
]);
const extensions = new Map(
[...parameters].filter(([name]) => !known.has(name)),
);
const warnings: OtpProfileWarning[] = [];
if (
issuerLabel &&
parameters.get("issuer") &&
issuerLabel !== parameters.get("issuer")
) {
warnings.push({
code: "issuer-mismatch",
message:
"The display issuer and issuer parameter differ; verify the intended service.",
});
}
if (secret.byteLength < 16) {
warnings.push({
code: "short-secret",
message: "The secret is shorter than the 128-bit HOTP minimum.",
});
}
if (digits !== 6 && digits !== 8) {
warnings.push({
code: "nonstandard-digits",
message: "Many authenticator applications support only 6 or 8 digits.",
});
}
if (kind === "totp" && period !== 30) {
warnings.push({
code: "nonstandard-period",
message: "Some authenticator applications ignore non-default periods.",
});
}
for (const name of extensions.keys()) {
warnings.push({
code: "extension",
message: `Unknown parameter preserved: ${name}.`,
});
}
return {
profile: {
kind,
secret,
issuer,
account,
algorithm,
digits,
period,
counter,
extensions,
},
warnings,
};
}
function uriHash(algorithm: OtpHashAlgorithm): string {
return algorithm.replace("-", "");
}
export function serializeOtpAuth(profile: OtpProfile): string {
if (!profile.account.trim()) throw new Error("An account label is required.");
const issuer = profile.issuer.trim();
if (
hasUnsafeLabelCharacter(issuer) ||
hasUnsafeLabelCharacter(profile.account)
) {
throw new Error(
"Issuer and account labels must not contain colons or control characters.",
);
}
const label = issuer
? `${issuer}:${profile.account.trim()}`
: profile.account.trim();
const parameters = new URLSearchParams();
parameters.set("secret", bytesToBase32(profile.secret));
if (issuer) parameters.set("issuer", issuer);
parameters.set("algorithm", uriHash(profile.algorithm));
parameters.set("digits", profile.digits.toString());
if (profile.kind === "totp")
parameters.set("period", profile.period.toString());
else parameters.set("counter", profile.counter.toString());
for (const [name, value] of profile.extensions) {
if (!parameters.has(name)) parameters.set(name, value);
}
const encodedLabel = label
.split(":")
.map((part) => encodeURIComponent(part))
.join(":");
return `otpauth://${profile.kind}/${encodedLabel}?${parameters.toString()}`;
}
export function profileStrength(profile: OtpProfile): {
secretBits: number;
findings: string[];
} {
const secretBits = profile.secret.byteLength * 8;
const findings: string[] = [];
if (secretBits < 128)
findings.push("Secret is below the HOTP 128-bit minimum.");
else if (secretBits < 160)
findings.push(
"Secret meets the minimum but not the 160-bit recommendation.",
);
if (profile.kind === "hotp" && profile.algorithm !== "SHA-1") {
findings.push(
"HOTP RFC 4226 specifies HMAC-SHA-1; other hashes may not interoperate.",
);
}
if (profile.kind === "totp" && profile.period !== 30) {
findings.push("Non-default periods are frequently ignored by importers.");
}
if (findings.length === 0)
findings.push("No structural interoperability issue detected.");
return { secretBits, findings };
}
+378
View File
@@ -0,0 +1,378 @@
/*
* QR construction follows Kazuhiko Arase's QRCode for JavaScript algorithm
* (MIT License, copyright 2009 Kazuhiko Arase), rewritten in TypeScript for
* a bounded browser-only byte-mode encoder. See THIRD_PARTY_NOTICES.md.
*/
interface RsBlock {
total: number;
data: number;
}
// Error correction M, versions 110. Each group is count,total,data.
const RS_M = [
[1, 26, 16],
[1, 44, 28],
[1, 70, 44],
[2, 50, 32],
[2, 67, 43],
[4, 43, 27],
[4, 49, 31],
[2, 60, 38, 2, 61, 39],
[3, 58, 36, 2, 59, 37],
[4, 69, 43, 1, 70, 44],
] as const;
const PATTERNS = [
[],
[6, 18],
[6, 22],
[6, 26],
[6, 30],
[6, 34],
[6, 22, 38],
[6, 24, 42],
[6, 26, 46],
[6, 28, 50],
] as const;
class Bits {
readonly bytes: number[] = [];
length = 0;
put(value: number, length: number): void {
for (let shift = length - 1; shift >= 0; shift -= 1)
this.bit(Boolean((value >>> shift) & 1));
}
bit(value: boolean): void {
const index = Math.floor(this.length / 8);
if (this.bytes.length <= index) this.bytes.push(0);
if (value)
this.bytes[index] = this.bytes[index]! | (0x80 >>> (this.length % 8));
this.length += 1;
}
}
const EXP = new Uint8Array(512);
const LOG = new Uint8Array(256);
for (let index = 0, value = 1; index < 255; index += 1) {
EXP[index] = value;
LOG[value] = index;
value <<= 1;
if (value & 0x100) value ^= 0x11d;
}
for (let index = 255; index < EXP.length; index += 1)
EXP[index] = EXP[index - 255]!;
function multiplyPoly(left: number[], right: number[]): number[] {
const output = Array.from(
{ length: left.length + right.length - 1 },
() => 0,
);
for (let leftIndex = 0; leftIndex < left.length; leftIndex += 1) {
for (let rightIndex = 0; rightIndex < right.length; rightIndex += 1) {
const a = left[leftIndex]!;
const b = right[rightIndex]!;
if (a && b)
output[leftIndex + rightIndex] =
output[leftIndex + rightIndex]! ^ EXP[LOG[a]! + LOG[b]!]!;
}
}
return output;
}
function errorCorrection(data: number[], count: number): number[] {
let divisor = [1];
for (let index = 0; index < count; index += 1)
divisor = multiplyPoly(divisor, [1, EXP[index]!]);
const working = [...data, ...Array.from({ length: count }, () => 0)];
for (let index = 0; index < data.length; index += 1) {
const lead = working[index]!;
if (!lead) continue;
const ratio = LOG[lead]!;
for (let coefficient = 0; coefficient < divisor.length; coefficient += 1) {
const value = divisor[coefficient]!;
if (value)
working[index + coefficient] =
working[index + coefficient]! ^ EXP[LOG[value]! + ratio]!;
}
}
return working.slice(data.length);
}
function blocks(version: number): RsBlock[] {
const row = RS_M[version - 1];
if (!row)
throw new Error(
"QR payload requires a version above the supported version 10 limit.",
);
const output: RsBlock[] = [];
for (let index = 0; index < row.length; index += 3) {
for (let count = 0; count < row[index]!; count += 1)
output.push({ total: row[index + 1]!, data: row[index + 2]! });
}
return output;
}
function dataCodewords(payload: Uint8Array, version: number): number[] {
const structure = blocks(version);
const capacity = structure.reduce((sum, block) => sum + block.data, 0);
const bits = new Bits();
bits.put(4, 4);
bits.put(payload.byteLength, version < 10 ? 8 : 16);
for (const byte of payload) bits.put(byte, 8);
if (bits.length > capacity * 8)
throw new Error("QR payload does not fit this version.");
if (bits.length + 4 <= capacity * 8) bits.put(0, 4);
while (bits.length % 8) bits.bit(false);
let pad = 0xec;
while (bits.bytes.length < capacity) {
bits.put(pad, 8);
pad = pad === 0xec ? 0x11 : 0xec;
}
const dataBlocks: number[][] = [];
const eccBlocks: number[][] = [];
let offset = 0;
for (const block of structure) {
const data = bits.bytes.slice(offset, offset + block.data);
offset += block.data;
dataBlocks.push(data);
eccBlocks.push(errorCorrection(data, block.total - block.data));
}
const output: number[] = [];
const maxData = Math.max(...dataBlocks.map((block) => block.length));
const maxEcc = Math.max(...eccBlocks.map((block) => block.length));
for (let index = 0; index < maxData; index += 1)
for (const block of dataBlocks)
if (index < block.length) output.push(block[index]!);
for (let index = 0; index < maxEcc; index += 1)
for (const block of eccBlocks)
if (index < block.length) output.push(block[index]!);
return output;
}
function bchDigit(value: number): number {
let digits = 0;
while (value) {
digits += 1;
value >>>= 1;
}
return digits;
}
function bch(value: number, generator: number, shift: number): number {
let remainder = value << shift;
while (bchDigit(remainder) >= bchDigit(generator))
remainder ^= generator << (bchDigit(remainder) - bchDigit(generator));
return (value << shift) | remainder;
}
function mask(pattern: number, row: number, column: number): boolean {
if (pattern === 0) return (row + column) % 2 === 0;
if (pattern === 1) return row % 2 === 0;
if (pattern === 2) return column % 3 === 0;
if (pattern === 3) return (row + column) % 3 === 0;
if (pattern === 4)
return (Math.floor(row / 2) + Math.floor(column / 3)) % 2 === 0;
if (pattern === 5) return ((row * column) % 2) + ((row * column) % 3) === 0;
if (pattern === 6)
return (((row * column) % 2) + ((row * column) % 3)) % 2 === 0;
return (((row * column) % 3) + ((row + column) % 2)) % 2 === 0;
}
type Matrix = Array<Array<boolean | null>>;
function finder(matrix: Matrix, top: number, left: number): void {
const size = matrix.length;
for (let row = -1; row <= 7; row += 1)
for (let column = -1; column <= 7; column += 1) {
if (
top + row < 0 ||
left + column < 0 ||
top + row >= size ||
left + column >= size
)
continue;
matrix[top + row]![left + column] =
(row >= 0 && row <= 6 && (column === 0 || column === 6)) ||
(column >= 0 && column <= 6 && (row === 0 || row === 6)) ||
(row >= 2 && row <= 4 && column >= 2 && column <= 4);
}
}
function setup(version: number, pattern: number, test: boolean): Matrix {
const size = version * 4 + 17;
const matrix: Matrix = Array.from({ length: size }, () =>
Array.from({ length: size }, () => null),
);
finder(matrix, 0, 0);
finder(matrix, size - 7, 0);
finder(matrix, 0, size - 7);
const positions = PATTERNS[version - 1]!;
for (const row of positions)
for (const column of positions) {
if (matrix[row]![column] !== null) continue;
for (let y = -2; y <= 2; y += 1)
for (let x = -2; x <= 2; x += 1)
matrix[row + y]![column + x] =
Math.abs(y) === 2 || Math.abs(x) === 2 || (y === 0 && x === 0);
}
for (let index = 8; index < size - 8; index += 1) {
if (matrix[index]![6] === null) matrix[index]![6] = index % 2 === 0;
if (matrix[6]![index] === null) matrix[6]![index] = index % 2 === 0;
}
const format = bch(pattern, 0x537, 10) ^ 0x5412; // M has format level bits 00.
for (let index = 0; index < 15; index += 1) {
const value = !test && Boolean((format >>> index) & 1);
const verticalRow =
index < 6 ? index : index < 8 ? index + 1 : size - 15 + index;
matrix[verticalRow]![8] = value;
const horizontalColumn =
index < 8 ? size - index - 1 : index < 9 ? 7 : 15 - index - 1;
matrix[8]![horizontalColumn] = value;
}
matrix[size - 8]![8] = !test;
if (version >= 7) {
const versionBits = bch(version, 0x1f25, 12);
for (let index = 0; index < 18; index += 1) {
const value = !test && Boolean((versionBits >>> index) & 1);
matrix[Math.floor(index / 3)]![(index % 3) + size - 11] = value;
matrix[(index % 3) + size - 11]![Math.floor(index / 3)] = value;
}
}
return matrix;
}
function place(
matrix: Matrix,
codewords: number[],
pattern: number,
): boolean[][] {
const size = matrix.length;
let row = size - 1;
let direction = -1;
let byteIndex = 0;
let bitIndex = 7;
for (let column = size - 1; column > 0; column -= 2) {
if (column === 6) column -= 1;
for (;;) {
for (let offset = 0; offset < 2; offset += 1)
if (matrix[row]![column - offset] === null) {
let dark =
byteIndex < codewords.length &&
Boolean((codewords[byteIndex]! >>> bitIndex) & 1);
if (mask(pattern, row, column - offset)) dark = !dark;
matrix[row]![column - offset] = dark;
bitIndex -= 1;
if (bitIndex < 0) {
bitIndex = 7;
byteIndex += 1;
}
}
row += direction;
if (row < 0 || row >= size) {
row -= direction;
direction = -direction;
break;
}
}
}
return matrix as boolean[][];
}
function penalty(matrix: boolean[][]): number {
const size = matrix.length;
let score = 0;
for (let row = 0; row < size; row += 1)
for (let column = 0; column < size; column += 1) {
let same = 0;
for (let y = -1; y <= 1; y += 1)
for (let x = -1; x <= 1; x += 1)
if (
(x || y) &&
row + y >= 0 &&
column + x >= 0 &&
row + y < size &&
column + x < size &&
matrix[row + y]![column + x] === matrix[row]![column]
)
same += 1;
if (same > 5) score += 3 + same - 5;
}
for (let row = 0; row < size - 1; row += 1)
for (let column = 0; column < size - 1; column += 1) {
const count =
Number(matrix[row]![column]) +
Number(matrix[row + 1]![column]) +
Number(matrix[row]![column + 1]) +
Number(matrix[row + 1]![column + 1]);
if (count === 0 || count === 4) score += 3;
}
const finderLike = (values: boolean[]): boolean =>
values[0] === true &&
values[1] === false &&
values[2] === true &&
values[3] === true &&
values[4] === true &&
values[5] === false &&
values[6] === true;
for (let index = 0; index < size; index += 1)
for (let offset = 0; offset < size - 6; offset += 1) {
if (finderLike(matrix[index]!.slice(offset, offset + 7))) score += 40;
if (
finderLike(
Array.from(
{ length: 7 },
(_, step) => matrix[offset + step]![index]!,
),
)
)
score += 40;
}
const dark = matrix.flat().filter(Boolean).length;
return score + (Math.abs((dark * 100) / (size * size) - 50) / 5) * 10;
}
export function encodeQr(text: string): boolean[][] {
const payload = new TextEncoder().encode(text);
let version = 1;
for (; version <= 10; version += 1) {
const capacity =
blocks(version).reduce((sum, block) => sum + block.data, 0) * 8;
const required = 4 + (version < 10 ? 8 : 16) + payload.byteLength * 8;
if (required <= capacity) break;
}
if (version > 10)
throw new Error(
"Provisioning URI is too large for the built-in QR encoder (maximum version 10). ",
);
const codewords = dataCodewords(payload, version);
let best: boolean[][] | undefined;
let bestScore = Number.POSITIVE_INFINITY;
for (let pattern = 0; pattern < 8; pattern += 1) {
const score = penalty(
place(setup(version, pattern, true), codewords, pattern),
);
if (score < bestScore) {
best = place(setup(version, pattern, false), codewords, pattern);
bestScore = score;
}
}
return best!;
}
export function qrSvg(text: string, moduleSize = 6): string {
const matrix = encodeQr(text);
const quiet = 4;
const dimension = (matrix.length + quiet * 2) * moduleSize;
const path: string[] = [];
for (let row = 0; row < matrix.length; row += 1)
for (let column = 0; column < matrix.length; column += 1)
if (matrix[row]![column])
path.push(
`M${(column + quiet) * moduleSize} ${(row + quiet) * moduleSize}h${moduleSize}v${moduleSize}h-${moduleSize}z`,
);
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${dimension} ${dimension}" role="img" aria-label="OTP provisioning QR code"><rect width="100%" height="100%" fill="white"/><path d="${path.join("")}" fill="black"/></svg>`;
}
+777
View File
@@ -0,0 +1,777 @@
:root {
--auth-blue: #315dc7;
--auth-teal: #16806f;
--auth-success: #19744d;
--auth-warning: #9a6505;
}
[data-toolbox-theme="dark"] {
--auth-blue: #8dacff;
--auth-teal: #65d7c4;
--auth-success: #67d99f;
--auth-warning: #e8bc62;
}
@media (prefers-color-scheme: dark) {
[data-toolbox-theme="system"] {
--auth-blue: #8dacff;
--auth-teal: #65d7c4;
--auth-success: #67d99f;
--auth-warning: #e8bc62;
}
}
* {
box-sizing: border-box;
}
html {
min-width: 320px;
min-height: 100%;
background: var(--toolbox-background);
}
body {
min-width: 320px;
min-height: 100vh;
margin: 0;
}
button,
input,
select,
textarea {
font: inherit;
}
button,
select,
input[type="checkbox"] {
cursor: pointer;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible,
summary:focus-visible,
a:focus-visible {
outline: 3px solid color-mix(in srgb, var(--toolbox-focus) 62%, transparent);
outline-offset: 2px;
}
.auth-application,
.workbench-loading,
.fatal-error {
width: min(100%, 90rem);
margin-inline: auto;
}
.auth-application {
padding: 1rem 0 3rem;
color: var(--toolbox-text);
}
.workbench-loading,
.fatal-error {
padding: 3rem 1rem;
text-align: center;
color: var(--toolbox-muted);
}
.privacy-strip {
display: flex;
align-items: center;
gap: 0.65rem;
min-height: 3rem;
margin-bottom: 1rem;
padding: 0.55rem 0.7rem 0.55rem 1rem;
border: 1px solid
color-mix(in srgb, var(--auth-teal) 45%, var(--toolbox-border));
border-radius: var(--toolbox-radius);
background: color-mix(in srgb, var(--auth-teal) 7%, var(--toolbox-surface));
font-size: 0.82rem;
}
.privacy-strip > div {
flex: 1;
}
.privacy-strip span:not(.status-dot) {
color: var(--toolbox-muted);
}
.status-dot {
width: 0.6rem;
height: 0.6rem;
border-radius: 50%;
background: var(--auth-teal);
box-shadow: 0 0 0 0.25rem
color-mix(in srgb, var(--auth-teal) 13%, transparent);
}
.workspace-tabs {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.7rem;
margin-bottom: 1rem;
}
.workspace-tabs button {
display: grid;
grid-template-columns: 2.4rem 1fr;
grid-template-rows: auto auto;
column-gap: 0.7rem;
align-items: center;
min-height: 4.4rem;
padding: 0.65rem 0.9rem;
border: 1px solid var(--toolbox-border);
border-radius: var(--toolbox-radius);
background: var(--toolbox-surface);
color: var(--toolbox-text);
text-align: left;
}
.workspace-tabs button > span {
grid-row: 1 / 3;
display: grid;
place-items: center;
width: 2.4rem;
aspect-ratio: 1;
border-radius: 0.7rem;
background: var(--toolbox-accent-soft);
color: var(--auth-blue);
font-size: 0.8rem;
font-weight: 850;
}
.workspace-tabs strong {
align-self: end;
}
.workspace-tabs small {
align-self: start;
color: var(--toolbox-muted);
}
.workspace-tabs button:hover,
.workspace-tabs button.active {
border-color: color-mix(in srgb, var(--auth-blue) 65%, var(--toolbox-border));
background: color-mix(in srgb, var(--auth-blue) 5%, var(--toolbox-surface));
}
.workspace-tabs button.active {
box-shadow: inset 0 -3px var(--auth-blue);
}
.workspace {
min-width: 0;
}
.subtabs {
display: flex;
gap: 0.25rem;
margin: 0 0 1rem;
padding: 0.25rem;
overflow-x: auto;
border: 1px solid var(--toolbox-border);
border-radius: calc(var(--toolbox-radius) * 0.85);
background: var(--toolbox-surface-soft);
}
.subtabs button {
flex: 0 0 auto;
padding: 0.55rem 0.8rem;
border: 0;
border-radius: calc(var(--toolbox-radius) * 0.65);
background: transparent;
color: var(--toolbox-muted);
font-weight: 700;
}
.subtabs button.active {
background: var(--toolbox-surface);
color: var(--toolbox-text);
box-shadow: 0 2px 8px rgb(20 30 60 / 8%);
}
.otp-grid,
.migration-grid,
.split-grid {
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(20rem, 0.85fr);
gap: 1rem;
align-items: start;
}
.migration-grid,
.split-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.panel {
min-width: 0;
overflow: hidden;
border: 1px solid var(--toolbox-border);
border-radius: var(--toolbox-radius);
background: var(--toolbox-surface);
box-shadow: 0 8px 28px rgb(20 30 60 / 5%);
}
.panel-heading {
display: flex;
min-height: 4rem;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.8rem 1rem;
border-bottom: 1px solid var(--toolbox-border);
}
.panel-heading h2,
.panel-heading p {
margin: 0;
}
.panel-heading h2 {
font-size: 1rem;
}
.eyebrow {
color: var(--toolbox-muted);
font-size: 0.67rem;
font-weight: 780;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.panel-body {
display: grid;
gap: 0.85rem;
padding: 1rem;
}
.panel-footer {
padding: 1rem;
border-top: 1px solid var(--toolbox-border);
}
.panel-footer p {
margin: 0 0 0.7rem;
color: var(--toolbox-muted);
font-size: 0.8rem;
}
.form-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
label {
display: grid;
gap: 0.35rem;
min-width: 0;
color: var(--toolbox-muted);
font-size: 0.76rem;
font-weight: 700;
}
label.wide,
.wide-note {
grid-column: 1 / -1;
}
input,
select,
textarea {
width: 100%;
min-width: 0;
border: 1px solid var(--toolbox-border);
border-radius: calc(var(--toolbox-radius) * 0.66);
padding: 0.58rem 0.65rem;
background: var(--toolbox-background);
color: var(--toolbox-text);
}
textarea {
resize: vertical;
line-height: 1.45;
}
.input-actions,
.button-row,
.verify-row {
display: flex;
align-items: stretch;
gap: 0.45rem;
}
.input-actions input,
.verify-row input {
flex: 1;
}
.primary-button,
.secondary-button,
.icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid transparent;
border-radius: calc(var(--toolbox-radius) * 0.7);
padding: 0.55rem 0.75rem;
font-weight: 720;
text-decoration: none;
}
.primary-button {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent);
color: var(--toolbox-accent-contrast);
}
.primary-button:hover:not(:disabled) {
background: var(--toolbox-accent-hover);
}
.secondary-button,
.icon-button {
border-color: var(--toolbox-border);
background: var(--toolbox-surface);
color: var(--toolbox-text);
}
.secondary-button:hover:not(:disabled),
.icon-button:hover:not(:disabled) {
border-color: var(--toolbox-accent);
}
button:disabled {
cursor: not-allowed;
opacity: 0.52;
}
.compact-button {
padding: 0.4rem 0.6rem;
font-size: 0.75rem;
}
.badge {
display: inline-flex;
align-items: center;
border: 1px solid var(--toolbox-border);
border-radius: 99rem;
padding: 0.28rem 0.55rem;
background: var(--toolbox-surface-soft);
color: var(--toolbox-muted);
font-size: 0.68rem;
font-weight: 750;
}
.badge.success {
color: var(--auth-success);
border-color: color-mix(
in srgb,
var(--auth-success) 45%,
var(--toolbox-border)
);
}
.badge.warning {
color: var(--auth-warning);
border-color: color-mix(
in srgb,
var(--auth-warning) 45%,
var(--toolbox-border)
);
}
.findings {
padding: 0.7rem 1rem;
border-top: 1px solid var(--toolbox-border);
color: var(--toolbox-muted);
font-size: 0.78rem;
}
.findings summary {
cursor: pointer;
font-weight: 700;
}
.findings ul,
.warnings ul {
margin-bottom: 0;
padding-left: 1.2rem;
}
.code-display {
padding: 2rem 1rem 1rem;
color: var(--toolbox-text);
font:
800 clamp(2rem, 6vw, 3.5rem)/1 ui-monospace,
SFMono-Regular,
Consolas,
monospace;
letter-spacing: 0.04em;
text-align: center;
}
.countdown {
color: var(--auth-blue);
font-size: 0.78rem;
font-weight: 800;
}
.progress {
height: 0.28rem;
margin: 0 1rem 1rem;
overflow: hidden;
border-radius: 99rem;
background: var(--toolbox-surface-soft);
}
.progress span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--auth-blue);
transition: width 0.4s linear;
}
.verify-row {
padding: 0 1rem;
}
.verification {
margin: 0.6rem 1rem 0;
color: var(--auth-teal);
font-size: 0.8rem;
font-weight: 700;
}
.qr {
display: grid;
place-items: center;
margin: 1rem auto;
}
.qr svg {
width: min(100%, 16rem);
height: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.7rem;
}
.code-panel > label,
.code-panel > .button-row {
margin: 0 1rem 1rem;
}
.notice {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
padding: 0.7rem 0.9rem;
border: 1px solid;
border-radius: var(--toolbox-radius);
}
.notice.error {
border-color: color-mix(
in srgb,
var(--toolbox-danger) 55%,
var(--toolbox-border)
);
background: color-mix(
in srgb,
var(--toolbox-danger) 7%,
var(--toolbox-surface)
);
color: var(--toolbox-danger);
}
.notice button {
border: 0;
background: transparent;
color: inherit;
font-size: 1.2rem;
}
.hint,
.origin-explanation,
.wide-note {
margin: 0;
color: var(--toolbox-muted);
font-size: 0.82rem;
line-height: 1.55;
}
.migration-input,
.mono-input,
.diagnostic-output,
.credential-card code {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
}
.file-button {
position: relative;
cursor: pointer;
}
.file-button input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
}
.credential-list {
display: grid;
max-height: 28rem;
overflow: auto;
}
.credential-list button {
display: grid;
gap: 0.15rem;
padding: 0.8rem 1rem;
border: 0;
border-bottom: 1px solid var(--toolbox-border);
background: transparent;
color: var(--toolbox-text);
text-align: left;
}
.credential-list button:hover {
background: var(--toolbox-surface-soft);
}
.credential-list span,
.credential-list small {
color: var(--toolbox-muted);
}
.warnings {
padding: 1rem;
color: var(--auth-warning);
font-size: 0.8rem;
}
.empty-state {
display: grid;
place-items: center;
gap: 0.4rem;
min-height: 15rem;
padding: 2rem;
color: var(--toolbox-muted);
text-align: center;
}
.diagnostic-output {
min-height: 25rem;
max-height: 42rem;
margin: 0;
padding: 1rem;
overflow: auto;
background: var(--toolbox-background);
color: var(--toolbox-text);
font-size: 0.75rem;
line-height: 1.5;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.compact-form {
gap: 0.75rem;
}
.check-row {
display: flex;
align-items: center;
gap: 0.55rem;
color: var(--toolbox-text);
}
.check-row input {
width: 1rem;
height: 1rem;
}
.wide-note {
padding: 1rem;
border: 1px solid var(--toolbox-border);
border-radius: var(--toolbox-radius);
background: var(--toolbox-surface-soft);
}
.capability-list {
display: grid;
gap: 0;
margin: 0;
}
.suite-summary {
display: grid;
gap: 0;
margin: 0;
}
.suite-summary div {
display: grid;
grid-template-columns: minmax(8rem, 0.7fr) 1.3fr;
gap: 1rem;
padding: 0.55rem 0;
border-bottom: 1px solid var(--toolbox-border);
}
.suite-summary dt {
color: var(--toolbox-muted);
}
.suite-summary dd {
margin: 0;
font-weight: 700;
}
.inline-error {
margin: 0;
color: var(--toolbox-danger);
font-size: 0.8rem;
font-weight: 700;
}
.ocra-response {
display: grid;
gap: 0.25rem;
padding: 1rem;
border: 1px solid
color-mix(in srgb, var(--auth-teal) 50%, var(--toolbox-border));
border-radius: calc(var(--toolbox-radius) * 0.7);
background: color-mix(in srgb, var(--auth-teal) 7%, var(--toolbox-surface));
text-align: center;
}
.ocra-response span {
color: var(--toolbox-muted);
font-size: 0.7rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.ocra-response strong {
font:
800 2rem/1.2 ui-monospace,
SFMono-Regular,
Consolas,
monospace;
letter-spacing: 0.08em;
}
.capability-list div {
display: grid;
grid-template-columns: minmax(8rem, 0.7fr) 1.3fr;
gap: 1rem;
padding: 0.55rem 0;
border-bottom: 1px solid var(--toolbox-border);
}
.capability-list dt {
color: var(--toolbox-muted);
}
.capability-list dd {
margin: 0;
overflow-wrap: anywhere;
font-weight: 700;
}
.centered-link {
margin-inline: auto;
}
.credential-card {
display: grid;
gap: 0.45rem;
padding: 0.8rem;
border: 1px solid
color-mix(in srgb, var(--auth-teal) 45%, var(--toolbox-border));
border-radius: calc(var(--toolbox-radius) * 0.7);
background: color-mix(in srgb, var(--auth-teal) 6%, var(--toolbox-surface));
}
.credential-card code {
overflow: hidden;
text-overflow: ellipsis;
}
.credential-card span {
color: var(--toolbox-muted);
font-size: 0.74rem;
}
.link-button {
justify-self: start;
border: 0;
padding: 0;
background: transparent;
color: var(--toolbox-accent);
font-weight: 700;
}
.verification-report {
display: grid;
gap: 0.6rem;
margin-top: 0.5rem;
}
.verification-report > strong {
font-size: 1rem;
}
.verification-report ul {
display: grid;
gap: 0.35rem;
margin: 0;
padding: 0;
list-style: none;
}
.verification-report li {
display: flex;
gap: 0.55rem;
padding: 0.5rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.5rem;
}
.verification-report li > span {
display: grid;
flex: 0 0 1.4rem;
place-items: center;
height: 1.4rem;
border-radius: 50%;
background: var(--toolbox-surface-soft);
font-weight: 850;
}
.verification-report li.pass > span {
color: var(--auth-success);
}
.verification-report li.fail > span {
color: var(--toolbox-danger);
}
.verification-report li div {
display: grid;
gap: 0.12rem;
}
.verification-report li small {
color: var(--toolbox-muted);
}
.tool-dialog {
width: min(calc(100% - 2rem), 42rem);
max-height: min(46rem, calc(100vh - 2rem));
padding: 0;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: var(--toolbox-radius);
background: var(--toolbox-surface);
color: var(--toolbox-text);
box-shadow: var(--toolbox-shadow);
}
.tool-dialog::backdrop {
background: rgb(10 15 30 / 55%);
backdrop-filter: blur(3px);
}
.dialog-heading,
.dialog-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.9rem 1rem;
}
.dialog-heading {
border-bottom: 1px solid var(--toolbox-border);
}
.dialog-heading h2,
.dialog-heading p {
margin: 0;
}
.dialog-body {
padding: 1rem;
}
.dialog-actions {
border-top: 1px solid var(--toolbox-border);
}
.prose {
line-height: 1.6;
}
.prose h3 {
margin-bottom: 0.25rem;
font-size: 1rem;
}
.prose p {
margin-top: 0.25rem;
color: var(--toolbox-muted);
}
@media (max-width: 820px) {
.auth-application {
padding-inline: 0.65rem;
}
.otp-grid,
.migration-grid,
.split-grid {
grid-template-columns: 1fr;
}
.workspace-tabs button {
grid-template-columns: 2rem 1fr;
}
.workspace-tabs button > span {
width: 2rem;
}
.privacy-strip > div span {
display: none;
}
}
@media (max-width: 540px) {
.form-grid {
grid-template-columns: 1fr;
}
label.wide {
grid-column: auto;
}
.input-actions {
flex-wrap: wrap;
}
.input-actions input {
flex-basis: 100%;
}
.workspace-tabs small {
display: none;
}
.workspace-tabs button {
grid-template-rows: 1fr;
min-height: 3.5rem;
}
.workspace-tabs button > span {
grid-row: auto;
}
.privacy-strip {
align-items: flex-start;
flex-wrap: wrap;
}
.privacy-strip .compact-button {
margin-left: 1.2rem;
}
}
+42
View File
@@ -0,0 +1,42 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
if (
!(
HTMLDialogElement.prototype as HTMLDialogElement & {
showModal?: () => void;
}
).showModal
) {
HTMLDialogElement.prototype.showModal = function showModal() {
this.setAttribute("open", "");
};
}
const nativeDialogClose = HTMLDialogElement.prototype.close;
HTMLDialogElement.prototype.close = function close(returnValue?: string) {
if (nativeDialogClose) {
try {
nativeDialogClose.call(this, returnValue);
return;
} catch {
// jsdom fallback.
}
}
this.removeAttribute("open");
};
Object.defineProperty(URL, "createObjectURL", {
configurable: true,
value: vi.fn(() => "blob:auth-tools-test"),
});
Object.defineProperty(URL, "revokeObjectURL", {
configurable: true,
value: vi.fn(),
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
+52
View File
@@ -0,0 +1,52 @@
{
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
"schemaVersion": 1,
"id": "de.add-ideas.auth-tools",
"name": "OTP & Passkey Tools",
"version": "0.1.0",
"description": "Generate, inspect and verify OTP credentials and test WebAuthn/passkey ceremonies locally in the browser.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["security", "authentication", "developer"],
"tags": [
"otp",
"hotp",
"totp",
"ocra",
"oath",
"webauthn",
"fido2",
"passkey",
"attestation",
"assertion"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": true,
"workers": false,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": true
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Authentication material stays in this tab; nothing is uploaded or saved unless you explicitly export it."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/auth-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/auth-tools"
}
]
}
+4
View File
@@ -0,0 +1,4 @@
import { defineToolboxApp, parseToolboxApp } from "@add-ideas/toolbox-contract";
import manifestSource from "./manifest.source.json";
export const manifest = defineToolboxApp(parseToolboxApp(manifestSource));
+1
View File
@@ -0,0 +1 @@
export const APPLICATION_VERSION = "0.1.0";
+204
View File
@@ -0,0 +1,204 @@
export type CborScalar = null | boolean | number | bigint | string | Uint8Array;
export type CborValue = CborScalar | CborValue[] | Map<CborValue, CborValue>;
export interface DecodedCbor {
value: CborValue;
bytesRead: number;
}
export class CborDecodeError extends Error {
constructor(message: string) {
super(message);
this.name = "CborDecodeError";
}
}
interface Limits {
maxDepth: number;
maxItems: number;
maxByteLength: number;
}
const DEFAULT_LIMITS: Limits = {
maxDepth: 32,
maxItems: 10_000,
maxByteLength: 4 * 1024 * 1024,
};
class Decoder {
private offset = 0;
private items = 0;
private readonly bytes: Uint8Array;
private readonly limits: Limits;
constructor(bytes: Uint8Array, limits: Limits) {
this.bytes = bytes;
this.limits = limits;
}
decode(): DecodedCbor {
const value = this.readValue(0);
return { value, bytesRead: this.offset };
}
private require(length: number): void {
if (length < 0 || this.offset + length > this.bytes.byteLength) {
throw new CborDecodeError("CBOR data ends unexpectedly.");
}
}
private readByte(): number {
this.require(1);
return this.bytes[this.offset++]!;
}
private readUnsigned(length: number): bigint {
this.require(length);
let value = 0n;
for (let index = 0; index < length; index += 1) {
value = (value << 8n) | BigInt(this.bytes[this.offset++]!);
}
return value;
}
private readArgument(additional: number): bigint {
if (additional < 24) return BigInt(additional);
if (additional === 24) return this.readUnsigned(1);
if (additional === 25) return this.readUnsigned(2);
if (additional === 26) return this.readUnsigned(4);
if (additional === 27) return this.readUnsigned(8);
if (additional === 31) {
throw new CborDecodeError("Indefinite-length CBOR is not accepted.");
}
throw new CborDecodeError(
"CBOR uses a reserved additional-information value.",
);
}
private safeLength(value: bigint): number {
if (
value > BigInt(this.limits.maxByteLength) ||
value > BigInt(Number.MAX_SAFE_INTEGER)
) {
throw new CborDecodeError("CBOR item exceeds the configured size limit.");
}
return Number(value);
}
private readValue(depth: number): CborValue {
if (depth > this.limits.maxDepth)
throw new CborDecodeError("CBOR nesting is too deep.");
this.items += 1;
if (this.items > this.limits.maxItems)
throw new CborDecodeError("CBOR has too many items.");
const initial = this.readByte();
const major = initial >>> 5;
const additional = initial & 31;
const argument = this.readArgument(additional);
if (major === 0)
return argument <= BigInt(Number.MAX_SAFE_INTEGER)
? Number(argument)
: argument;
if (major === 1) {
const negative = -1n - argument;
return negative >= BigInt(Number.MIN_SAFE_INTEGER)
? Number(negative)
: negative;
}
if (major === 2) {
const length = this.safeLength(argument);
this.require(length);
const value = this.bytes.slice(this.offset, this.offset + length);
this.offset += length;
return value;
}
if (major === 3) {
const length = this.safeLength(argument);
this.require(length);
const value = this.bytes.slice(this.offset, this.offset + length);
this.offset += length;
try {
return new TextDecoder("utf-8", { fatal: true }).decode(value);
} catch {
throw new CborDecodeError("CBOR text contains invalid UTF-8.");
}
}
if (major === 4) {
const length = this.safeLength(argument);
const output: CborValue[] = [];
for (let index = 0; index < length; index += 1)
output.push(this.readValue(depth + 1));
return output;
}
if (major === 5) {
const length = this.safeLength(argument);
const output = new Map<CborValue, CborValue>();
const keys = new Set<string>();
for (let index = 0; index < length; index += 1) {
const key = this.readValue(depth + 1);
const fingerprint = this.keyFingerprint(key);
if (keys.has(fingerprint))
throw new CborDecodeError("CBOR map contains a duplicate key.");
keys.add(fingerprint);
output.set(key, this.readValue(depth + 1));
}
return output;
}
if (major === 6) {
if (argument === 24n || argument === 55799n)
return this.readValue(depth + 1);
throw new CborDecodeError(
`Unsupported CBOR semantic tag ${argument.toString()}.`,
);
}
if (major === 7) {
if (additional === 20) return false;
if (additional === 21) return true;
if (additional === 22) return null;
throw new CborDecodeError(
"Floating-point and undefined CBOR values are not accepted.",
);
}
throw new CborDecodeError("Unsupported CBOR major type.");
}
private keyFingerprint(key: CborValue): string {
if (key instanceof Uint8Array)
return `b:${[...key]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("")}`;
if (Array.isArray(key) || key instanceof Map)
throw new CborDecodeError("Compound CBOR map keys are not accepted.");
return `${typeof key}:${String(key)}`;
}
}
export function decodeCbor(
bytes: Uint8Array,
limits: Partial<Limits> = {},
): DecodedCbor {
const configured = { ...DEFAULT_LIMITS, ...limits };
if (bytes.byteLength > configured.maxByteLength) {
throw new CborDecodeError("CBOR input exceeds the configured size limit.");
}
return new Decoder(bytes, configured).decode();
}
export function decodeCompleteCbor(bytes: Uint8Array): CborValue {
const decoded = decodeCbor(bytes);
if (decoded.bytesRead !== bytes.byteLength) {
throw new CborDecodeError("CBOR contains trailing data.");
}
return decoded.value;
}
export function cborMap(
value: CborValue,
label = "CBOR value",
): Map<CborValue, CborValue> {
if (!(value instanceof Map))
throw new CborDecodeError(`${label} must be a map.`);
return value;
}
+196
View File
@@ -0,0 +1,196 @@
import {
base64UrlToBytes,
bytesToArrayBuffer,
bytesToBase64Url,
randomBytes,
} from "../crypto/encoding";
import {
coseKeyToJson,
verifyAssertion,
type AssertionVerificationResult,
} from "./verify";
import { parseAttestationObject } from "./parser";
export const LIVE_HOST = "auth.toolbox.add-ideas.de";
export interface BrowserCapabilities {
secureContext: boolean;
credentialsApi: boolean;
publicKeyCredential: boolean;
conditionalMediation: boolean | null;
platformAuthenticator: boolean | null;
}
export interface MemoryCredential {
id: string;
publicKey: Record<string, string | number>;
signCount: number;
transports: AuthenticatorTransport[];
createdAt: string;
aaguid: string;
format: string;
}
export function liveLabAvailability(
location: Pick<Location, "hostname" | "origin">,
): {
available: boolean;
reason: string;
rpId: string;
} {
const local =
location.hostname === "localhost" ||
location.hostname === "127.0.0.1" ||
location.hostname === "::1";
const dedicated = location.hostname === LIVE_HOST;
return {
available: Boolean(globalThis.isSecureContext && (local || dedicated)),
rpId: location.hostname,
reason: !globalThis.isSecureContext
? "WebAuthn requires a secure context."
: local || dedicated
? `Ceremonies are bound to ${location.origin}.`
: `Live ceremonies are isolated at https://${LIVE_HOST}; this shared Portal origin is inspect-only.`,
};
}
export async function detectCapabilities(): Promise<BrowserCapabilities> {
const credential =
typeof PublicKeyCredential === "undefined"
? undefined
: PublicKeyCredential;
const conditional =
credential && "isConditionalMediationAvailable" in credential
? await PublicKeyCredential.isConditionalMediationAvailable().catch(
() => false,
)
: null;
const platform =
credential && "isUserVerifyingPlatformAuthenticatorAvailable" in credential
? await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable().catch(
() => false,
)
: null;
return {
secureContext: globalThis.isSecureContext,
credentialsApi: typeof navigator.credentials !== "undefined",
publicKeyCredential: Boolean(credential),
conditionalMediation: conditional,
platformAuthenticator: platform,
};
}
export async function createMemoryCredential(input: {
userName: string;
userDisplayName: string;
attestation: AttestationConveyancePreference;
authenticatorAttachment?: AuthenticatorAttachment;
}): Promise<MemoryCredential> {
const availability = liveLabAvailability(window.location);
if (!availability.available) throw new Error(availability.reason);
const challenge = randomBytes(32);
const userId = randomBytes(32);
const publicKey: PublicKeyCredentialCreationOptions = {
challenge: bytesToArrayBuffer(challenge),
rp: { id: availability.rpId, name: "add·ideas Authentication Lab" },
user: {
id: bytesToArrayBuffer(userId),
name: input.userName.trim() || "local-user",
displayName:
input.userDisplayName.trim() || input.userName.trim() || "Local user",
},
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
{ type: "public-key", alg: -8 },
],
timeout: 120_000,
attestation: input.attestation,
authenticatorSelection: {
residentKey: "preferred",
userVerification: "preferred",
...(input.authenticatorAttachment
? { authenticatorAttachment: input.authenticatorAttachment }
: {}),
},
};
const credential = await navigator.credentials.create({ publicKey });
if (
!(credential instanceof PublicKeyCredential) ||
!(credential.response instanceof AuthenticatorAttestationResponse)
) {
throw new Error("Browser did not return a WebAuthn registration response.");
}
const parsed = parseAttestationObject(
new Uint8Array(credential.response.attestationObject),
);
const attested = parsed.authenticator.attestedCredential;
if (!attested)
throw new Error(
"Registration response does not contain a credential public key.",
);
return {
id: credential.id,
publicKey: coseKeyToJson(attested.credentialPublicKey),
signCount: parsed.authenticator.signCount,
transports: (credential.response.getTransports?.() ?? []).filter(
(value): value is AuthenticatorTransport =>
[
"ble",
"cable",
"hybrid",
"internal",
"nfc",
"smart-card",
"usb",
].includes(value),
),
createdAt: new Date().toISOString(),
aaguid: attested.aaguid,
format: parsed.format,
};
}
export async function exerciseMemoryCredential(
credential: MemoryCredential,
requireUserVerification: boolean,
): Promise<AssertionVerificationResult> {
const availability = liveLabAvailability(window.location);
if (!availability.available) throw new Error(availability.reason);
const challenge = randomBytes(32);
const publicKey: PublicKeyCredentialRequestOptions = {
challenge: bytesToArrayBuffer(challenge),
rpId: availability.rpId,
timeout: 120_000,
userVerification: requireUserVerification ? "required" : "preferred",
allowCredentials: [
{
type: "public-key",
id: bytesToArrayBuffer(base64UrlToBytes(credential.id)),
transports: credential.transports,
},
],
};
const result = await navigator.credentials.get({ publicKey });
if (
!(result instanceof PublicKeyCredential) ||
!(result.response instanceof AuthenticatorAssertionResponse)
) {
throw new Error("Browser did not return a WebAuthn assertion response.");
}
return verifyAssertion({
clientDataJSON: bytesToBase64Url(
new Uint8Array(result.response.clientDataJSON),
),
authenticatorData: bytesToBase64Url(
new Uint8Array(result.response.authenticatorData),
),
signature: bytesToBase64Url(new Uint8Array(result.response.signature)),
credentialPublicKey: JSON.stringify(credential.publicKey),
expectedChallenge: bytesToBase64Url(challenge),
expectedOrigin: window.location.origin,
expectedRpId: availability.rpId,
requireUserVerification,
previousSignCount: credential.signCount,
});
}
+202
View File
@@ -0,0 +1,202 @@
import {
base64UrlToBytes,
bytesToBase64Url,
bytesToHex,
bytesToUtf8,
} from "../crypto/encoding";
import {
cborMap,
decodeCbor,
decodeCompleteCbor,
type CborValue,
} from "./cbor";
export interface AuthenticatorFlags {
userPresent: boolean;
userVerified: boolean;
backupEligible: boolean;
backupState: boolean;
attestedCredentialData: boolean;
extensionData: boolean;
raw: number;
}
export interface AttestedCredentialData {
aaguid: string;
credentialId: string;
credentialPublicKey: Map<CborValue, CborValue>;
}
export interface ParsedAuthenticatorData {
rpIdHash: string;
flags: AuthenticatorFlags;
signCount: number;
attestedCredential?: AttestedCredentialData;
extensions?: CborValue;
bytesRead: number;
raw: Uint8Array;
}
export interface ParsedAttestation {
format: string;
statement: Map<CborValue, CborValue>;
authenticator: ParsedAuthenticatorData;
}
export interface CollectedClientData {
type: string;
challenge: string;
origin: string;
crossOrigin?: boolean;
tokenBinding?: unknown;
[key: string]: unknown;
}
function readU16(bytes: Uint8Array, offset: number): number {
if (offset + 2 > bytes.byteLength)
throw new Error("Authenticator data ends unexpectedly.");
return (bytes[offset]! << 8) | bytes[offset + 1]!;
}
function readU32(bytes: Uint8Array, offset: number): number {
if (offset + 4 > bytes.byteLength)
throw new Error("Authenticator data ends unexpectedly.");
return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(
0,
false,
);
}
export function parseAuthenticatorData(
bytes: Uint8Array,
): ParsedAuthenticatorData {
if (bytes.byteLength < 37)
throw new Error("Authenticator data must contain at least 37 bytes.");
const flagByte = bytes[32]!;
const flags: AuthenticatorFlags = {
userPresent: Boolean(flagByte & 0x01),
userVerified: Boolean(flagByte & 0x04),
backupEligible: Boolean(flagByte & 0x08),
backupState: Boolean(flagByte & 0x10),
attestedCredentialData: Boolean(flagByte & 0x40),
extensionData: Boolean(flagByte & 0x80),
raw: flagByte,
};
if (flags.backupState && !flags.backupEligible) {
throw new Error(
"Authenticator flags set backup state without backup eligibility.",
);
}
let offset = 37;
let attestedCredential: AttestedCredentialData | undefined;
if (flags.attestedCredentialData) {
if (offset + 18 > bytes.byteLength)
throw new Error("Attested credential data is truncated.");
const aaguidBytes = bytes.slice(offset, offset + 16);
offset += 16;
const credentialLength = readU16(bytes, offset);
offset += 2;
if (
credentialLength === 0 ||
offset + credentialLength > bytes.byteLength
) {
throw new Error("Attested credential ID length is invalid.");
}
const credentialId = bytes.slice(offset, offset + credentialLength);
offset += credentialLength;
const decodedKey = decodeCbor(bytes.slice(offset));
const credentialPublicKey = cborMap(
decodedKey.value,
"Credential public key",
);
offset += decodedKey.bytesRead;
const hex = bytesToHex(aaguidBytes);
attestedCredential = {
aaguid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,
credentialId: bytesToBase64Url(credentialId),
credentialPublicKey,
};
}
let extensions: CborValue | undefined;
if (flags.extensionData) {
const decoded = decodeCbor(bytes.slice(offset));
extensions = decoded.value;
offset += decoded.bytesRead;
}
if (offset !== bytes.byteLength) {
throw new Error(
"Authenticator data contains bytes not described by its flags.",
);
}
return {
rpIdHash: bytesToHex(bytes.slice(0, 32)),
flags,
signCount: readU32(bytes, 33),
...(attestedCredential ? { attestedCredential } : {}),
...(extensions !== undefined ? { extensions } : {}),
bytesRead: offset,
raw: bytes,
};
}
export function parseAttestationObject(
input: string | Uint8Array,
): ParsedAttestation {
const bytes = typeof input === "string" ? base64UrlToBytes(input) : input;
const map = cborMap(decodeCompleteCbor(bytes), "Attestation object");
const format = map.get("fmt");
const authData = map.get("authData");
const statement = map.get("attStmt");
if (typeof format !== "string")
throw new Error("Attestation format is missing.");
if (!(authData instanceof Uint8Array))
throw new Error("Attestation authData is missing.");
return {
format,
statement: cborMap(statement ?? null, "Attestation statement"),
authenticator: parseAuthenticatorData(authData),
};
}
export function parseClientData(
input: string | Uint8Array,
): CollectedClientData {
const bytes = typeof input === "string" ? base64UrlToBytes(input) : input;
let value: unknown;
try {
value = JSON.parse(bytesToUtf8(bytes));
} catch {
throw new Error("Client data is not valid UTF-8 JSON.");
}
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("Client data must be a JSON object.");
}
const object = value as Record<string, unknown>;
if (
typeof object.type !== "string" ||
typeof object.challenge !== "string" ||
typeof object.origin !== "string"
) {
throw new Error("Client data requires type, challenge and origin strings.");
}
if (
object.crossOrigin !== undefined &&
typeof object.crossOrigin !== "boolean"
) {
throw new Error("Client data crossOrigin must be boolean when present.");
}
return object as CollectedClientData;
}
export function cborDiagnostic(value: CborValue): unknown {
if (value instanceof Uint8Array) {
return { base64url: bytesToBase64Url(value), bytes: value.byteLength };
}
if (Array.isArray(value)) return value.map(cborDiagnostic);
if (value instanceof Map) {
return Object.fromEntries(
[...value].map(([key, item]) => [String(key), cborDiagnostic(item)]),
);
}
return typeof value === "bigint" ? `${value.toString()}n` : value;
}
+386
View File
@@ -0,0 +1,386 @@
import {
base64UrlToBytes,
bytesToArrayBuffer,
bytesToBase64Url,
bytesToHex,
utf8ToBytes,
} from "../crypto/encoding";
import type { CborValue } from "./cbor";
import { parseAuthenticatorData, parseClientData } from "./parser";
export type CheckStatus = "pass" | "fail" | "warning" | "information";
export interface VerificationCheck {
name: string;
status: CheckStatus;
detail: string;
}
export interface AssertionVerificationInput {
clientDataJSON: string;
authenticatorData: string;
signature: string;
credentialPublicKey: string | Map<CborValue, CborValue>;
expectedChallenge: string;
expectedOrigin: string;
expectedRpId: string;
requireUserVerification?: boolean;
previousSignCount?: number;
}
export interface AssertionVerificationResult {
verified: boolean;
checks: VerificationCheck[];
signCount: number;
}
function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {
if (left.byteLength !== right.byteLength) return false;
let difference = 0;
for (let index = 0; index < left.byteLength; index += 1)
difference |= left[index]! ^ right[index]!;
return difference === 0;
}
async function digest(bytes: Uint8Array): Promise<Uint8Array> {
return new Uint8Array(
await crypto.subtle.digest("SHA-256", bytesToArrayBuffer(bytes)),
);
}
function coseNumber(map: Map<CborValue, CborValue>, key: number): number {
const value = map.get(key);
if (typeof value !== "number")
throw new Error(`COSE key parameter ${key} is missing.`);
return value;
}
function coseBytes(map: Map<CborValue, CborValue>, key: number): Uint8Array {
const value = map.get(key);
if (!(value instanceof Uint8Array))
throw new Error(`COSE key parameter ${key} is missing.`);
return value;
}
function decodeCoseJson(input: string): Map<CborValue, CborValue> {
let value: unknown;
try {
value = JSON.parse(input);
} catch {
throw new Error("Credential public key JSON is invalid.");
}
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("Credential public key must be a JSON object.");
}
const result = new Map<CborValue, CborValue>();
for (const [rawKey, item] of Object.entries(value)) {
const key = Number(rawKey);
if (!Number.isInteger(key))
throw new Error("COSE key labels must be integers.");
if (typeof item === "string" && /^[-_A-Za-z0-9]+=*$/u.test(item)) {
result.set(key, base64UrlToBytes(item));
} else if (typeof item === "number") result.set(key, item);
else throw new Error(`Unsupported COSE value for label ${rawKey}.`);
}
return result;
}
export function coseKeyToJson(
map: Map<CborValue, CborValue>,
): Record<string, string | number> {
const result: Record<string, string | number> = {};
for (const [key, value] of map) {
if (typeof key !== "number") continue;
if (typeof value === "number") result[String(key)] = value;
else if (value instanceof Uint8Array)
result[String(key)] = bytesToBase64Url(value);
}
return result;
}
function derEcdsaToRaw(signature: Uint8Array, size = 32): Uint8Array {
if (signature[0] !== 0x30)
throw new Error("ECDSA signature is not a DER sequence.");
let offset = 1;
let sequenceLength = signature[offset++]!;
if (sequenceLength & 0x80) {
const lengthBytes = sequenceLength & 0x7f;
if (
lengthBytes === 0 ||
lengthBytes > 2 ||
offset + lengthBytes > signature.length
)
throw new Error("ECDSA DER length is invalid.");
sequenceLength = 0;
for (let index = 0; index < lengthBytes; index += 1)
sequenceLength = sequenceLength * 256 + signature[offset++]!;
}
if (
offset + sequenceLength !== signature.length ||
signature[offset++] !== 0x02
)
throw new Error("ECDSA DER sequence is malformed.");
const rLength = signature[offset++]!;
const r = signature.slice(offset, offset + rLength);
offset += rLength;
if (signature[offset++] !== 0x02)
throw new Error("ECDSA DER sequence lacks s.");
const sLength = signature[offset++]!;
const s = signature.slice(offset, offset + sLength);
if (offset + sLength !== signature.length)
throw new Error("ECDSA DER signature has trailing data.");
const normalize = (integer: Uint8Array): Uint8Array => {
if (!integer.length || (integer[0]! & 0x80) !== 0)
throw new Error("ECDSA DER integer is negative or empty.");
if (integer.length > 1 && integer[0] === 0 && (integer[1]! & 0x80) === 0)
throw new Error("ECDSA DER integer is not minimally encoded.");
let start = 0;
while (start < integer.length - 1 && integer[start] === 0) start += 1;
const stripped = integer.slice(start);
if (stripped.length > size) throw new Error("ECDSA integer is too large.");
const output = new Uint8Array(size);
output.set(stripped, size - stripped.length);
return output;
};
const output = new Uint8Array(size * 2);
output.set(normalize(r));
output.set(normalize(s), size);
return output;
}
async function importCoseKey(map: Map<CborValue, CborValue>): Promise<{
key: CryptoKey;
algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams;
normalizeSignature: (signature: Uint8Array) => Uint8Array;
}> {
const kty = coseNumber(map, 1);
const alg = coseNumber(map, 3);
if (kty === 2 && alg === -7 && coseNumber(map, -1) === 1) {
const jwk: JsonWebKey = {
kty: "EC",
crv: "P-256",
x: bytesToBase64Url(coseBytes(map, -2)),
y: bytesToBase64Url(coseBytes(map, -3)),
ext: true,
};
return {
key: await crypto.subtle.importKey(
"jwk",
jwk,
{ name: "ECDSA", namedCurve: "P-256" },
false,
["verify"],
),
algorithm: { name: "ECDSA", hash: "SHA-256" },
normalizeSignature: derEcdsaToRaw,
};
}
if (kty === 3 && (alg === -257 || alg === -37)) {
const jwk: JsonWebKey = {
kty: "RSA",
n: bytesToBase64Url(coseBytes(map, -1)),
e: bytesToBase64Url(coseBytes(map, -2)),
ext: true,
};
const name = alg === -37 ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
return {
key: await crypto.subtle.importKey(
"jwk",
jwk,
{ name, hash: "SHA-256" },
false,
["verify"],
),
algorithm: alg === -37 ? { name, saltLength: 32 } : name,
normalizeSignature: (signature) => signature,
};
}
if (kty === 1 && alg === -8 && coseNumber(map, -1) === 6) {
const jwk: JsonWebKey = {
kty: "OKP",
crv: "Ed25519",
x: bytesToBase64Url(coseBytes(map, -2)),
ext: true,
};
return {
key: await crypto.subtle.importKey("jwk", jwk, "Ed25519", false, [
"verify",
]),
algorithm: "Ed25519",
normalizeSignature: (signature) => signature,
};
}
throw new Error(
`Unsupported COSE key type/algorithm combination: kty ${kty}, alg ${alg}.`,
);
}
function addCheck(
checks: VerificationCheck[],
name: string,
pass: boolean,
detail: string,
): void {
checks.push({ name, status: pass ? "pass" : "fail", detail });
}
export async function verifyAssertion(
input: AssertionVerificationInput,
): Promise<AssertionVerificationResult> {
const checks: VerificationCheck[] = [];
const clientBytes = base64UrlToBytes(input.clientDataJSON);
const authBytes = base64UrlToBytes(input.authenticatorData);
const client = parseClientData(clientBytes);
const authenticator = parseAuthenticatorData(authBytes);
addCheck(
checks,
"Ceremony type",
client.type === "webauthn.get",
`Received ${client.type}.`,
);
const challengeMatches = (() => {
try {
return bytesEqual(
base64UrlToBytes(client.challenge),
base64UrlToBytes(input.expectedChallenge),
);
} catch {
return false;
}
})();
addCheck(
checks,
"Challenge",
challengeMatches,
challengeMatches
? "Challenge matches exactly."
: "Challenge does not match.",
);
let receivedOriginValid = false;
let expectedOriginValid = false;
try {
receivedOriginValid = new URL(client.origin).origin === client.origin;
} catch {
// Reported as a failed syntax check below.
}
try {
expectedOriginValid =
new URL(input.expectedOrigin).origin === input.expectedOrigin;
} catch {
// Reported as a failed syntax check below.
}
addCheck(
checks,
"Origin syntax",
receivedOriginValid && expectedOriginValid,
"Origins must be serialized, absolute URL origins without a path.",
);
addCheck(
checks,
"Origin",
receivedOriginValid &&
expectedOriginValid &&
client.origin === input.expectedOrigin,
`Received ${client.origin}.`,
);
addCheck(
checks,
"Cross-origin",
client.crossOrigin !== true,
client.crossOrigin === true
? "Client data marks this ceremony cross-origin."
: "Ceremony is not marked cross-origin.",
);
const expectedRpHash = await digest(utf8ToBytes(input.expectedRpId));
addCheck(
checks,
"RP ID hash",
bytesToHex(expectedRpHash) === authenticator.rpIdHash,
`Expected SHA-256(${input.expectedRpId}).`,
);
addCheck(
checks,
"User presence",
authenticator.flags.userPresent,
"Authenticator UP flag must be set.",
);
if (input.requireUserVerification)
addCheck(
checks,
"User verification",
authenticator.flags.userVerified,
"User verification was required.",
);
else
checks.push({
name: "User verification",
status: "information",
detail: authenticator.flags.userVerified
? "UV flag is set."
: "UV was not required and is not set.",
});
if (
input.previousSignCount !== undefined &&
input.previousSignCount > 0 &&
authenticator.signCount > 0
) {
addCheck(
checks,
"Signature counter",
authenticator.signCount > input.previousSignCount,
`Previous ${input.previousSignCount}; received ${authenticator.signCount}.`,
);
} else {
checks.push({
name: "Signature counter",
status: "information",
detail: `Received ${authenticator.signCount}; zero/non-incrementing counters can be valid for multi-device credentials.`,
});
}
try {
const cose =
typeof input.credentialPublicKey === "string"
? decodeCoseJson(input.credentialPublicKey)
: input.credentialPublicKey;
const imported = await importCoseKey(cose);
const clientHash = await digest(clientBytes);
const signed = new Uint8Array(authBytes.byteLength + clientHash.byteLength);
signed.set(authBytes);
signed.set(clientHash, authBytes.byteLength);
const signature = imported.normalizeSignature(
base64UrlToBytes(input.signature),
);
const valid = await crypto.subtle.verify(
imported.algorithm,
imported.key,
bytesToArrayBuffer(signature),
bytesToArrayBuffer(signed),
);
addCheck(
checks,
"Cryptographic signature",
valid,
valid
? "Signature verifies with the supplied credential key."
: "Signature verification failed.",
);
} catch (error) {
checks.push({
name: "Cryptographic signature",
status: "fail",
detail:
error instanceof Error
? error.message
: "Signature verification failed.",
});
}
return {
verified: checks.every((check) => check.status !== "fail"),
checks,
signCount: authenticator.signCount,
};
}
+61
View File
@@ -0,0 +1,61 @@
import { expect, test } from "@playwright/test";
test("runs from a nested path and keeps authentication material local", async ({
page,
}) => {
const requests: string[] = [];
page.on("request", (request) => requests.push(request.url()));
await page.goto("/deep/nested/auth/");
await expect(page.getByText("Sensitive session · memory only")).toBeVisible();
await expect(
page.getByRole("heading", { name: "Credential parameters" }),
).toBeVisible();
await page.getByLabel("Issuer").fill("Example");
await page.getByLabel("Account").fill("alice@example.test");
await expect(page.getByText("TOTP code")).toBeVisible();
await expect(page.locator(".qr svg")).toBeVisible();
expect(
requests.every((url) => new URL(url).origin === "http://127.0.0.1:4173"),
).toBe(true);
});
test("computes an RFC OCRA vector and decodes client data", async ({
page,
}) => {
await page.goto("/deep/nested/auth/");
await page.getByRole("button", { name: "OCRA challenge" }).click();
await page
.getByLabel("Base32 shared secret")
.fill("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
await page.getByRole("button", { name: "Compute OCRA response" }).click();
await expect(page.getByText("237653")).toBeVisible();
await page.getByRole("button", { name: /WebAuthn \/ Passkeys/ }).click();
const client = btoa(
JSON.stringify({
type: "webauthn.get",
challenge: "YQ",
origin: "https://example.test",
}),
)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replace(/=+$/u, "");
await page.getByLabel("Encoded input").fill(client);
await page.getByRole("button", { name: "Decode locally" }).click();
await expect(page.locator(".diagnostic-output")).toContainText(
"webauthn.get",
);
});
test("shared origin exposes inspection but not live credential creation", async ({
page,
}) => {
await page.goto("/deep/nested/auth/");
await page.getByRole("button", { name: /WebAuthn \/ Passkeys/ }).click();
await page.getByRole("button", { name: "Live ceremony" }).click();
await expect(page.getByText("Inspect only")).toBeVisible();
await expect(
page.getByRole("button", { name: "Create test credential" }),
).toBeDisabled();
});
+41
View File
@@ -0,0 +1,41 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { Workbench } from "../../src/components/Workbench";
describe("authentication workbench", () => {
it("switches independent workspaces and clears sensitive session state", async () => {
const user = userEvent.setup();
render(<Workbench />);
expect(
screen.getByRole("heading", { name: "Credential parameters" }),
).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /OCRA challenge/iu }));
expect(
screen.getByRole("heading", { name: "OCRA suite and key" }),
).toBeInTheDocument();
await user.click(
screen.getByRole("button", { name: /WebAuthn \/ Passkeys/iu }),
);
expect(
screen.getByRole("heading", { name: "WebAuthn structure" }),
).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Clear session" }));
expect(
screen.getByRole("heading", { name: "WebAuthn structure" }),
).toBeInTheDocument();
});
it("keeps live ceremonies disabled on the shared/non-dedicated origin", async () => {
const user = userEvent.setup();
render(<Workbench />);
await user.click(
screen.getByRole("button", { name: /WebAuthn \/ Passkeys/iu }),
);
await user.click(screen.getByRole("button", { name: "Live ceremony" }));
expect(screen.getByText("Inspect only")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Create test credential" }),
).toBeDisabled();
});
});
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import {
base32ToBytes,
base64UrlToBytes,
bytesToBase32,
bytesToBase64Url,
bytesToHex,
hexToBytes,
utf8ToBytes,
} from "../../src/crypto/encoding";
describe("encoding", () => {
it("round-trips RFC 4648-style encodings", () => {
const bytes = utf8ToBytes("Hello!\u{1f512}");
expect([...base32ToBytes(bytesToBase32(bytes))]).toEqual([...bytes]);
expect([...base64UrlToBytes(bytesToBase64Url(bytes))]).toEqual([...bytes]);
expect([...hexToBytes(bytesToHex(bytes))]).toEqual([...bytes]);
});
it("rejects non-zero trailing Base32 bits", () => {
expect(() => base32ToBytes("AB")).toThrow(/trailing bits/iu);
});
it("accepts deliberate manual separators only when enabled", () => {
expect(() => base32ToBytes("JBSW Y3DP")).toThrow();
expect([...base32ToBytes("JBSW-Y3DP", { allowSeparators: true })]).toEqual([
...utf8ToBytes("Hello"),
]);
});
});
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import {
exportCsv,
importCsv,
importOtpAuthList,
importPlainPskc,
} from "../../src/otp/migration";
import { utf8ToBytes } from "../../src/crypto/encoding";
import type { OtpProfile } from "../../src/otp/profile";
const profile: OtpProfile = {
kind: "totp",
account: 'alice,"admin"',
issuer: "Example",
secret: utf8ToBytes("12345678901234567890"),
algorithm: "SHA-256",
digits: 8,
period: 45,
counter: 0n,
extensions: new Map(),
};
describe("OTP migrations", () => {
it("round-trips the documented CSV including quoting", () => {
const result = importCsv(exportCsv([profile]));
expect(result.profiles[0]).toMatchObject({
account: profile.account,
issuer: "Example",
algorithm: "SHA-256",
digits: 8,
period: 45,
});
expect([...result.profiles[0]!.secret]).toEqual([...profile.secret]);
});
it("neutralizes spreadsheet formulas without changing a round trip", () => {
const dangerous = { ...profile, account: '=HYPERLINK("https://bad")' };
const csv = exportCsv([dangerous]);
expect(csv).toContain("'=HYPERLINK");
expect(importCsv(csv).profiles[0]!.account).toBe(dangerous.account);
});
it("reports the failing line in URI lists", () => {
expect(() =>
importOtpAuthList("otpauth://totp/Good?secret=JBSWY3DPEHPK3PXP\nnope"),
).toThrow(/Line 2/iu);
});
it("imports plain-secret PSKC and refuses encrypted keys", () => {
const xml = `<KeyContainer xmlns="urn:ietf:params:xml:ns:keyprov:pskc"><KeyPackage><Key Id="alice" Algorithm="urn:ietf:params:xml:ns:keyprov:pskc:totp"><Issuer>Example</Issuer><Data><Secret><PlainValue>MTIzNDU2Nzg5MDEyMzQ1Njc4OTA=</PlainValue></Secret><TimeInterval><PlainValue>30</PlainValue></TimeInterval></Data><Policy><KeyUsage>OTP</KeyUsage></Policy><ResponseFormat Length="6" Encoding="DECIMAL"/></Key></KeyPackage></KeyContainer>`;
expect(importPlainPskc(xml).profiles[0]).toMatchObject({
kind: "totp",
account: "alice",
issuer: "Example",
digits: 6,
});
expect(() =>
importPlainPskc(
xml.replace(
"<PlainValue>MTIzNDU2Nzg5MDEyMzQ1Njc4OTA=</PlainValue>",
"<EncryptedValue/>",
),
),
).toThrow(/encrypted/iu);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from "vitest";
import { hexToBytes, utf8ToBytes } from "../../src/crypto/encoding";
import { hashOcraPassword, ocra, parseOcraSuite } from "../../src/otp/ocra";
describe("OCRA", () => {
it("parses complete suites and rejects reordered inputs", () => {
expect(
parseOcraSuite("OCRA-1:HOTP-SHA512-8:C-QN08-PSHA1-S064-T1M"),
).toMatchObject({
algorithm: "SHA-512",
digits: 8,
counter: true,
questionFormat: "numeric",
passwordAlgorithm: "SHA-1",
sessionLength: 64,
timeStepSeconds: 60,
});
expect(() => parseOcraSuite("OCRA-1:HOTP-SHA1-6:QN08-T1M-PSHA1")).toThrow(
/order/iu,
);
});
it("matches RFC 6287 one-way challenge vectors", async () => {
const secret = utf8ToBytes("12345678901234567890");
const expected = [
"237653",
"243178",
"653583",
"740991",
"608993",
"388898",
"816933",
"224598",
"750600",
"294470",
];
for (let index = 0; index < expected.length; index += 1) {
await expect(
ocra({
suite: "OCRA-1:HOTP-SHA1-6:QN08",
secret,
question: String(index).repeat(8),
}),
).resolves.toBe(expected[index]);
}
});
it("matches RFC 6287 counter/PIN and timestamp vectors", async () => {
const secret32 = utf8ToBytes("12345678901234567890123456789012");
const pinHash = await hashOcraPassword("1234", "SHA-1");
expect([...pinHash]).toEqual([
...hexToBytes("7110eda4d09e062aa5e4a390b0a572ac0d2c0220"),
]);
await expect(
ocra({
suite: "OCRA-1:HOTP-SHA256-8:C-QN08-PSHA1",
secret: secret32,
counter: 0n,
question: "12345678",
passwordHash: pinHash,
}),
).resolves.toBe("65347737");
const secret64 = utf8ToBytes(
"1234567890123456789012345678901234567890123456789012345678901234",
);
await expect(
ocra({
suite: "OCRA-1:HOTP-SHA512-8:QN08-T1M",
secret: secret64,
question: "00000000",
timeStep: 0x132d0b6n,
}),
).resolves.toBe("95209754");
});
});
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import { utf8ToBytes } from "../../src/crypto/encoding";
import {
hotp,
totp,
totpCounter,
verifyHotp,
verifyTotp,
} from "../../src/otp/otp";
describe("HOTP", () => {
it("matches every RFC 4226 test value", async () => {
const secret = utf8ToBytes("12345678901234567890");
const expected = [
"755224",
"287082",
"359152",
"969429",
"338314",
"254676",
"287922",
"162583",
"399871",
"520489",
];
await expect(
Promise.all(
expected.map((_, counter) =>
hotp({ secret, counter: BigInt(counter) }),
),
),
).resolves.toEqual(expected);
});
it("searches forward without losing leading zeroes", async () => {
const secret = utf8ToBytes("12345678901234567890");
const match = await verifyHotp("338314", {
secret,
counter: 1n,
lookAhead: 5,
});
expect(match).toMatchObject({ counter: 4n, delta: 3 });
});
});
describe("TOTP", () => {
const cases = [
[59, "94287082", "46119246", "90693936"],
[1_111_111_109, "07081804", "68084774", "25091201"],
[1_111_111_111, "14050471", "67062674", "99943326"],
[1_234_567_890, "89005924", "91819424", "93441116"],
[2_000_000_000, "69279037", "90698825", "38618901"],
[20_000_000_000, "65353130", "77737706", "47863826"],
] as const;
it("matches RFC 6238 SHA-1, SHA-256 and SHA-512 vectors", async () => {
const secrets = {
"SHA-1": utf8ToBytes("12345678901234567890"),
"SHA-256": utf8ToBytes("12345678901234567890123456789012"),
"SHA-512": utf8ToBytes(
"1234567890123456789012345678901234567890123456789012345678901234",
),
} as const;
for (const [timestamp, sha1, sha256, sha512] of cases) {
await expect(
totp({
secret: secrets["SHA-1"],
timestamp,
digits: 8,
algorithm: "SHA-1",
}),
).resolves.toBe(sha1);
await expect(
totp({
secret: secrets["SHA-256"],
timestamp,
digits: 8,
algorithm: "SHA-256",
}),
).resolves.toBe(sha256);
await expect(
totp({
secret: secrets["SHA-512"],
timestamp,
digits: 8,
algorithm: "SHA-512",
}),
).resolves.toBe(sha512);
}
});
it("uses integer counters beyond 2038", () => {
expect(totpCounter(20_000_000_000)).toBe(666_666_666n);
});
it("diagnoses a bounded clock delta", async () => {
const secret = utf8ToBytes("12345678901234567890");
const code = await totp({ secret, timestamp: 1_111_111_109 });
const match = await verifyTotp(code, {
secret,
timestamp: 1_111_111_109 + 60,
window: 3,
});
expect(match?.delta).toBe(-2);
});
});
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import { parseOtpAuth, serializeOtpAuth } from "../../src/otp/profile";
describe("otpauth profiles", () => {
it("parses and serializes a TOTP profile without losing extensions", () => {
const parsed = parseOtpAuth(
"otpauth://totp/Example:alice%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=SHA256&digits=8&period=45&image=ignored",
);
expect(parsed.profile).toMatchObject({
kind: "totp",
issuer: "Example",
account: "alice@example.com",
algorithm: "SHA-256",
digits: 8,
period: 45,
});
expect(parsed.profile.extensions.get("image")).toBe("ignored");
expect(serializeOtpAuth(parsed.profile)).toContain("image=ignored");
});
it("requires an HOTP counter and preserves 64-bit values", () => {
expect(() =>
parseOtpAuth("otpauth://hotp/Example?secret=JBSWY3DPEHPK3PXP"),
).toThrow(/counter/iu);
const parsed = parseOtpAuth(
"otpauth://hotp/Example?secret=JBSWY3DPEHPK3PXP&counter=18446744073709551615",
);
expect(parsed.profile.counter).toBe((1n << 64n) - 1n);
});
it("rejects duplicate known parameters", () => {
expect(() =>
parseOtpAuth(
"otpauth://totp/Example?secret=JBSWY3DPEHPK3PXP&secret=JBSWY3DPEHPK3PXP",
),
).toThrow(/duplicate/iu);
});
it("rejects partially numeric parameters and unsafe labels", () => {
expect(() =>
parseOtpAuth(
"otpauth://totp/Example?secret=JBSWY3DPEHPK3PXP&digits=6oops",
),
).toThrow(/integer/iu);
const parsed = parseOtpAuth(
"otpauth://totp/Example?secret=JBSWY3DPEHPK3PXP",
);
parsed.profile.account = "unsafe:label";
expect(() => serializeOtpAuth(parsed.profile)).toThrow(/colon/iu);
});
it("warns without silently reconciling issuer mismatch", () => {
const result = parseOtpAuth(
"otpauth://totp/Display:alice?secret=JBSWY3DPEHPK3PXP&issuer=canonical.example",
);
expect(result.profile.issuer).toBe("canonical.example");
expect(result.warnings.some(({ code }) => code === "issuer-mismatch")).toBe(
true,
);
});
});
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import {
bytesToArrayBuffer,
bytesToHex,
utf8ToBytes,
} from "../../src/crypto/encoding";
import { encodeQr, qrSvg } from "../../src/qr/encoder";
async function matrixHash(text: string): Promise<string> {
const bits = encodeQr(text)
.map((row) => row.map((value) => (value ? "1" : "0")).join(""))
.join("");
return bytesToHex(
new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
bytesToArrayBuffer(utf8ToBytes(bits)),
),
),
);
}
describe("QR encoder", () => {
it("matches the reviewed reference matrices", async () => {
await expect(matrixHash("Hello")).resolves.toBe(
"ac69828947e29c188c38459b3eab69d0071aeedc825c41277d82ca3141033afe",
);
await expect(
matrixHash(
"otpauth://totp/Example:alice?secret=JBSWY3DPEHPK3PXP&issuer=Example",
),
).resolves.toBe(
"d39d6eed126c0bc3ca92a851a062613e8cfa178adf9a8e2b3c399ba77cbb0187",
);
});
it("emits a self-contained SVG with a quiet zone", () => {
const svg = qrSvg("Hello");
expect(svg).toMatch(/^<svg xmlns=/u);
expect(svg).toContain("<rect");
expect(svg).not.toContain("script");
});
it("rejects oversized values instead of allocating unbounded matrices", () => {
expect(() => encodeQr("x".repeat(500))).toThrow(/version 10/iu);
});
});
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { decodeCompleteCbor } from "../../src/webauthn/cbor";
describe("bounded CBOR decoder", () => {
it("decodes deterministic maps and byte strings", () => {
const value = decodeCompleteCbor(
Uint8Array.from([
0xa2, 0x01, 0x42, 0xaa, 0xbb, 0x63, 0x66, 0x6d, 0x74, 0x64, 0x6e, 0x6f,
0x6e, 0x65,
]),
);
expect(value).toBeInstanceOf(Map);
expect((value as Map<unknown, unknown>).get("fmt")).toBe("none");
});
it("rejects indefinite, duplicate and trailing encodings", () => {
expect(() => decodeCompleteCbor(Uint8Array.from([0x9f, 0xff]))).toThrow(
/Indefinite/iu,
);
expect(() =>
decodeCompleteCbor(Uint8Array.from([0xa2, 0x01, 0x01, 0x01, 0x02])),
).toThrow(/duplicate/iu);
expect(() =>
decodeCompleteCbor(
Uint8Array.from([0xa2, 0x41, 0xaa, 0x01, 0x41, 0xaa, 0x02]),
),
).toThrow(/duplicate/iu);
expect(() => decodeCompleteCbor(Uint8Array.from([0x01, 0x02]))).toThrow(
/trailing/iu,
);
});
it("enforces depth and item limits", () => {
expect(() =>
decodeCompleteCbor(
Uint8Array.from([...Array.from({ length: 34 }, () => 0x81), 0x00]),
),
).toThrow(/deep/iu);
});
});
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import {
bytesToArrayBuffer,
bytesToBase64Url,
utf8ToBytes,
} from "../../src/crypto/encoding";
import {
parseAuthenticatorData,
parseClientData,
} from "../../src/webauthn/parser";
describe("WebAuthn parsers", () => {
it("parses collected client data without normalizing security fields", () => {
const json = utf8ToBytes(
JSON.stringify({
type: "webauthn.get",
challenge: "YWJj",
origin: "https://example.test",
crossOrigin: false,
}),
);
expect(parseClientData(bytesToBase64Url(json))).toMatchObject({
type: "webauthn.get",
origin: "https://example.test",
});
});
it("extracts flags and the unsigned signature counter", async () => {
const rpHash = new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
bytesToArrayBuffer(utf8ToBytes("example.test")),
),
);
const bytes = Uint8Array.from([...rpHash, 0x05, 0x00, 0x00, 0x00, 0x09]);
const parsed = parseAuthenticatorData(bytes);
expect(parsed.flags).toMatchObject({
userPresent: true,
userVerified: true,
});
expect(parsed.signCount).toBe(9);
});
it("rejects inconsistent backup flags and undeclared trailing data", () => {
expect(() =>
parseAuthenticatorData(
Uint8Array.from([...new Uint8Array(32), 0x10, 0, 0, 0, 0]),
),
).toThrow(/backup/iu);
expect(() =>
parseAuthenticatorData(
Uint8Array.from([...new Uint8Array(32), 0x01, 0, 0, 0, 0, 0]),
),
).toThrow(/not described/iu);
});
});
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, it } from "vitest";
import {
base64UrlToBytes,
bytesToArrayBuffer,
bytesToBase64Url,
utf8ToBytes,
} from "../../src/crypto/encoding";
import { verifyAssertion } from "../../src/webauthn/verify";
import type { CborValue } from "../../src/webauthn/cbor";
function rawEcdsaToDer(raw: Uint8Array): Uint8Array {
const integer = (part: Uint8Array): number[] => {
let offset = 0;
while (offset < part.length - 1 && part[offset] === 0) offset += 1;
const value = [...part.slice(offset)];
if (value[0]! & 0x80) value.unshift(0);
return [0x02, value.length, ...value];
};
const r = integer(raw.slice(0, 32));
const s = integer(raw.slice(32));
return Uint8Array.from([0x30, r.length + s.length, ...r, ...s]);
}
describe("assertion verification", () => {
it("checks ceremony bindings and a WebAuthn DER ECDSA signature", async () => {
const pair = await crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" },
true,
["sign", "verify"],
);
const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
const challenge = bytesToBase64Url(
crypto.getRandomValues(new Uint8Array(32)),
);
const origin = "https://auth.example.test";
const rpId = "auth.example.test";
const clientBytes = utf8ToBytes(
JSON.stringify({
type: "webauthn.get",
challenge,
origin,
crossOrigin: false,
}),
);
const rpHash = new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
bytesToArrayBuffer(utf8ToBytes(rpId)),
),
);
const authenticator = Uint8Array.from([...rpHash, 0x05, 0, 0, 0, 7]);
const clientHash = new Uint8Array(
await crypto.subtle.digest("SHA-256", bytesToArrayBuffer(clientBytes)),
);
const signed = Uint8Array.from([...authenticator, ...clientHash]);
const rawSignature = new Uint8Array(
await crypto.subtle.sign(
{ name: "ECDSA", hash: "SHA-256" },
pair.privateKey,
bytesToArrayBuffer(signed),
),
);
const cose = new Map<CborValue, CborValue>([
[1, 2],
[3, -7],
[-1, 1],
[-2, base64UrlToBytes(jwk.x!)],
[-3, base64UrlToBytes(jwk.y!)],
]);
const result = await verifyAssertion({
clientDataJSON: bytesToBase64Url(clientBytes),
authenticatorData: bytesToBase64Url(authenticator),
signature: bytesToBase64Url(rawEcdsaToDer(rawSignature)),
credentialPublicKey: cose,
expectedChallenge: challenge,
expectedOrigin: origin,
expectedRpId: rpId,
requireUserVerification: true,
previousSignCount: 6,
});
expect(result.verified).toBe(true);
expect(result.checks.every((check) => check.status !== "fail")).toBe(true);
});
it("fails expected origin independently", async () => {
await expect(
verifyAssertion({
clientDataJSON: bytesToBase64Url(
utf8ToBytes(
JSON.stringify({
type: "webauthn.get",
challenge: "YQ",
origin: "https://wrong.test",
}),
),
),
authenticatorData: bytesToBase64Url(
Uint8Array.from([...new Uint8Array(32), 1, 0, 0, 0, 0]),
),
signature: "",
credentialPublicKey: "{}",
expectedChallenge: "YQ",
expectedOrigin: "https://right.test",
expectedRpId: "right.test",
}),
).resolves.toMatchObject({ verified: false });
});
});
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023", "DOM", "DOM.Iterable", "WebWorker"],
"module": "ESNext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"useDefineForClassFields": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["src", "tests"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": [
"vite.config.ts",
"playwright.config.ts",
"eslint.config.mjs",
"scripts/**/*.mjs"
]
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
base: "./",
plugins: [react()],
worker: { format: "es" },
test: {
environment: "jsdom",
setupFiles: "./src/test/setup.ts",
css: true,
restoreMocks: true,
exclude: ["tests/browser/**", "node_modules/**", "dist/**"],
},
});