initial commit
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled
Signed-off-by: Kamal Tufekcic <kamal@lo.sh>
This commit is contained in:
commit
1d99048c95
165830 changed files with 79062 additions and 0 deletions
23
soliton_wasm/Cargo.toml
Normal file
23
soliton_wasm/Cargo.toml
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
[package]
|
||||
name = "soliton-wasm"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
authors.workspace = true
|
||||
description = "WebAssembly bindings for libsoliton — post-quantum cryptographic library"
|
||||
# Not published to crates.io — distributed via npm as a wasm-pack package.
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
libsoliton = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
zeroize = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
661
soliton_wasm/LICENSE.md
Normal file
661
soliton_wasm/LICENSE.md
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
122
soliton_wasm/README.md
Normal file
122
soliton_wasm/README.md
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
# soliton-wasm
|
||||
|
||||
WebAssembly bindings for [libsoliton](https://git.lo.sh/lo/libsoliton) — a pure-Rust post-quantum cryptographic library.
|
||||
|
||||
## Install
|
||||
|
||||
Configure the registry once (per project or globally):
|
||||
|
||||
```bash
|
||||
npm config set registry https://git.lo.sh/api/packages/lo/npm/
|
||||
```
|
||||
|
||||
Then install:
|
||||
|
||||
```bash
|
||||
bun add soliton-wasm
|
||||
# or
|
||||
npm install soliton-wasm
|
||||
# or
|
||||
pnpm add soliton-wasm
|
||||
```
|
||||
|
||||
For Deno, configure in `deno.json`:
|
||||
```json
|
||||
{
|
||||
"npmRegistry": "https://git.lo.sh/api/packages/lo/npm/"
|
||||
}
|
||||
```
|
||||
```ts
|
||||
import * as soliton from "npm:soliton-wasm";
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```js
|
||||
import init, * as soliton from "soliton-wasm";
|
||||
|
||||
// Initialize the WASM module (required once).
|
||||
await init();
|
||||
|
||||
// Identity
|
||||
const alice = new soliton.Identity();
|
||||
const sig = alice.sign(new TextEncoder().encode("hello"));
|
||||
alice.verify(new TextEncoder().encode("hello"), sig);
|
||||
const pk = alice.publicKey();
|
||||
const fp = alice.fingerprint();
|
||||
alice.free(); // zeroize secret key
|
||||
|
||||
// Primitives
|
||||
const hash = soliton.sha3_256(data);
|
||||
const tag = soliton.hmacSha3_256(key, data);
|
||||
const okm = soliton.hkdfSha3_256(salt, ikm, info, 32);
|
||||
|
||||
// Auth (zero-knowledge)
|
||||
const { ciphertext, token } = soliton.authChallenge(clientPk);
|
||||
const proof = soliton.authRespond(clientSk, ciphertext);
|
||||
const valid = soliton.authVerify(token, proof);
|
||||
|
||||
// KEX
|
||||
const { publicKey: spkPub, secretKey: spkSk } = soliton.xwingKeygen();
|
||||
const spkSig = soliton.kexSignPrekey(bobSk, spkPub);
|
||||
const initiated = soliton.kexInitiate(
|
||||
alicePk, aliceSk, bobPk, spkPub, 1, spkSig, "lo-crypto-v1",
|
||||
);
|
||||
|
||||
// Ratchet
|
||||
const { encryptedPayload, ratchetInitKey } = soliton.Ratchet.encryptFirstMessage(
|
||||
chainKey, plaintext, aad,
|
||||
);
|
||||
const ratchet = soliton.Ratchet.initAlice(rootKey, rik, localFp, remoteFp, peerEk, ekSk);
|
||||
const { header, ciphertext: ct } = ratchet.encrypt(plaintext);
|
||||
ratchet.free();
|
||||
|
||||
// Streaming AEAD
|
||||
const enc = new soliton.StreamEncryptor(key);
|
||||
const hdr = enc.header();
|
||||
const chunk = enc.encryptChunk(data, true); // is_last
|
||||
enc.free();
|
||||
|
||||
// Storage
|
||||
const ring = new soliton.StorageKeyRing(1, key);
|
||||
const blob = ring.encryptBlob("channel", "segment", plaintext);
|
||||
const decrypted = ring.decryptBlob("channel", "segment", blob);
|
||||
ring.free();
|
||||
|
||||
// Verification phrase
|
||||
const phrase = soliton.verificationPhrase(pkA, pkB);
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
Full TypeScript types are included. All byte parameters accept `Uint8Array`. All byte returns are `Uint8Array`. Opaque types (`Identity`, `Ratchet`, `StorageKeyRing`, `StreamEncryptor`, `StreamDecryptor`, `CallKeys`) must be `free()`'d when no longer needed to zeroize secret material.
|
||||
|
||||
See [CHEATSHEET.md](https://git.lo.sh/lo/libsoliton/src/branch/main/CHEATSHEET.md) for the full API reference with sizes, error codes, and protocol details.
|
||||
|
||||
## CLI
|
||||
|
||||
The package includes a Node-based CLI for post-quantum operations without a Rust toolchain:
|
||||
|
||||
```bash
|
||||
bunx soliton-wasm keygen # Generate identity keypair
|
||||
bunx soliton-wasm fingerprint identity.pk # SHA3-256 fingerprint
|
||||
bunx soliton-wasm sign identity.sk message.txt # Hybrid sign
|
||||
bunx soliton-wasm verify identity.pk message.txt # Verify signature
|
||||
bunx soliton-wasm xwing-keygen # X-Wing keypair (SPK/OPK)
|
||||
bunx soliton-wasm phrase pk_a.bin pk_b.bin # Verification phrase
|
||||
bunx soliton-wasm encrypt --key key.bin < in > out # Streaming AEAD encrypt
|
||||
bunx soliton-wasm decrypt --key key.bin < in > out # Streaming AEAD decrypt
|
||||
bunx soliton-wasm version
|
||||
```
|
||||
|
||||
For better performance, use the native CLI: `cargo install soliton-cli` → `soliton keygen`.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Specification.md](https://git.lo.sh/lo/libsoliton/src/branch/main/Specification.md) — full cryptographic specification
|
||||
- [CHEATSHEET.md](https://git.lo.sh/lo/libsoliton/src/branch/main/CHEATSHEET.md) — API quick reference
|
||||
- [Abstract.md](https://git.lo.sh/lo/libsoliton/src/branch/main/Abstract.md) — formal security model
|
||||
|
||||
## License
|
||||
|
||||
[AGPL-3.0-only](https://git.lo.sh/lo/libsoliton/src/branch/main/LICENSE.md)
|
||||
438
soliton_wasm/bin/soliton.js
Normal file
438
soliton_wasm/bin/soliton.js
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* soliton — CLI for post-quantum cryptographic operations (WASM).
|
||||
*
|
||||
* Standalone CLI that requires no Rust toolchain — runs via WASM in Node.
|
||||
* For the native CLI (faster, no Node dependency), install soliton-cli via cargo.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, readSync, openSync, closeSync } from "node:fs";
|
||||
import { join, resolve, dirname } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import process from "node:process";
|
||||
|
||||
// Initialize WASM manually — the bundler target's entry point imports .wasm
|
||||
// as an ES module which Node doesn't support natively.
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const wasmBytes = readFileSync(join(__dirname, "..", "soliton_wasm_bg.wasm"));
|
||||
const bgModule = await import("../soliton_wasm_bg.js");
|
||||
const wasmModule = await WebAssembly.instantiate(wasmBytes, {
|
||||
"./soliton_wasm_bg.js": bgModule,
|
||||
});
|
||||
bgModule.__wbg_set_wasm(wasmModule.instance.exports);
|
||||
wasmModule.instance.exports.__wbindgen_start();
|
||||
const soliton = bgModule;
|
||||
|
||||
const STREAM_CHUNK_SIZE = 1_048_576; // 1 MiB
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const cmd = args[0];
|
||||
|
||||
function usage() {
|
||||
console.error(`soliton — post-quantum cryptographic toolkit (WASM)
|
||||
|
||||
Usage: soliton <command> [options]
|
||||
|
||||
Commands:
|
||||
keygen [--output <dir>] Generate identity keypair
|
||||
fingerprint <pk-file> Print SHA3-256 fingerprint
|
||||
sign <sk-file> [file] Hybrid sign (Ed25519 + ML-DSA-65)
|
||||
verify <pk-file> <file> [--sig <file>] Verify a hybrid signature
|
||||
xwing-keygen [--output <dir>] Generate X-Wing keypair (SPK/OPK)
|
||||
sign-prekey <sk-file> <spk-pub-file> Sign a pre-key
|
||||
phrase <pk-a-file> <pk-b-file> Verification phrase
|
||||
encrypt --key <key-file> [file] [-o out] Streaming AEAD encrypt
|
||||
encrypt --derive [--salt <hex>] [file] [-o out]
|
||||
decrypt --key <key-file> [file] [-o out] Streaming AEAD decrypt
|
||||
decrypt --derive --salt <hex> [file] [-o out]
|
||||
argon2id [--m <KiB>] [--t <passes>] [--p <lanes>]
|
||||
version Print library version`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function readFile(path) {
|
||||
return new Uint8Array(readFileSync(resolve(path)));
|
||||
}
|
||||
|
||||
function writeFileSafe(path, data, mode) {
|
||||
writeFileSync(resolve(path), Buffer.from(data), { mode: mode || 0o644 });
|
||||
}
|
||||
|
||||
function writeSecretFile(path, data) {
|
||||
writeFileSafe(path, data, 0o600);
|
||||
}
|
||||
|
||||
function readStdin() {
|
||||
const chunks = [];
|
||||
const fd = openSync("/dev/stdin", "r");
|
||||
const buf = Buffer.alloc(65536);
|
||||
let n;
|
||||
while (true) {
|
||||
try {
|
||||
n = readSync(fd, buf, 0, buf.length, null);
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
if (n === 0) break;
|
||||
chunks.push(Uint8Array.prototype.slice.call(buf, 0, n)); // copy — prevents overwrite
|
||||
}
|
||||
closeSync(fd);
|
||||
return new Uint8Array(Buffer.concat(chunks));
|
||||
}
|
||||
|
||||
function readInput(filePath) {
|
||||
return filePath ? readFile(filePath) : readStdin();
|
||||
}
|
||||
|
||||
function hexEncode(bytes) {
|
||||
return Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
function hexDecode(hex) {
|
||||
if (hex.length % 2 !== 0) throw new Error("invalid hex length");
|
||||
if (!/^[0-9a-fA-F]*$/.test(hex)) throw new Error("invalid hex character");
|
||||
const bytes = new Uint8Array(hex.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function getArg(flag) {
|
||||
const idx = args.indexOf(flag);
|
||||
if (idx === -1 || idx + 1 >= args.length) return null;
|
||||
return args[idx + 1];
|
||||
}
|
||||
|
||||
function hasFlag(flag) {
|
||||
return args.includes(flag);
|
||||
}
|
||||
|
||||
/** Get a positional arg, skipping known flag+value pairs. */
|
||||
function getPositionalAfter(startIdx) {
|
||||
const flags = new Set([
|
||||
"--output",
|
||||
"-o",
|
||||
"--key",
|
||||
"-k",
|
||||
"--sig",
|
||||
"--salt",
|
||||
"--m",
|
||||
"--t",
|
||||
"--p",
|
||||
"--length",
|
||||
]);
|
||||
for (let i = startIdx; i < args.length; i++) {
|
||||
if (flags.has(args[i])) {
|
||||
i++; // skip flag value
|
||||
continue;
|
||||
}
|
||||
if (args[i].startsWith("-")) continue; // skip boolean flags
|
||||
return args[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function readPassphrase(prompt) {
|
||||
// Suppress echo if possible.
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stderr,
|
||||
terminal: process.stderr.isTTY || false,
|
||||
});
|
||||
if (rl.terminal) {
|
||||
// Manually handle echo suppression via raw mode.
|
||||
process.stderr.write(prompt);
|
||||
return new Promise((res) => {
|
||||
let input = "";
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.resume();
|
||||
process.stdin.setEncoding("utf8");
|
||||
const onData = (ch) => {
|
||||
if (ch === "\r" || ch === "\n") {
|
||||
process.stdin.setRawMode(false);
|
||||
process.stdin.pause();
|
||||
process.stdin.removeListener("data", onData);
|
||||
process.stderr.write("\n");
|
||||
rl.close();
|
||||
res(input);
|
||||
} else if (ch === "\u007F" || ch === "\b") {
|
||||
input = input.slice(0, -1);
|
||||
} else if (ch === "\u0003") {
|
||||
process.exit(130);
|
||||
} else {
|
||||
input += ch;
|
||||
}
|
||||
};
|
||||
process.stdin.on("data", onData);
|
||||
});
|
||||
}
|
||||
return new Promise((res) => {
|
||||
rl.question(prompt, (answer) => {
|
||||
rl.close();
|
||||
res(answer);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (!cmd) usage();
|
||||
|
||||
try {
|
||||
switch (cmd) {
|
||||
case "keygen": {
|
||||
const dir = getArg("--output") || getArg("-o") || ".";
|
||||
const id = new soliton.Identity();
|
||||
const pk = id.publicKey();
|
||||
const sk = id.secretKey();
|
||||
const fp = id.fingerprintHex();
|
||||
writeFileSafe(join(dir, "identity.pk"), pk);
|
||||
writeSecretFile(join(dir, "identity.sk"), sk);
|
||||
console.error(`Public key: ${join(dir, "identity.pk")}`);
|
||||
console.error(`Secret key: ${join(dir, "identity.sk")}`);
|
||||
console.error(`Fingerprint: ${fp}`);
|
||||
id.free();
|
||||
break;
|
||||
}
|
||||
|
||||
case "fingerprint": {
|
||||
const pkBytes = readFile(args[1]);
|
||||
console.log(soliton.fingerprintHex(pkBytes));
|
||||
break;
|
||||
}
|
||||
|
||||
case "sign": {
|
||||
const skBytes = readFile(args[1]);
|
||||
const pkPath = args[1].replace(/\.sk$/, ".pk");
|
||||
const pkBytes = readFile(pkPath);
|
||||
const inputFile = getPositionalAfter(2);
|
||||
const message = readInput(inputFile);
|
||||
const id = soliton.Identity.fromBytes(pkBytes, skBytes);
|
||||
const sig = id.sign(message);
|
||||
const outPath = getArg("--output") || getArg("-o");
|
||||
if (outPath) {
|
||||
writeFileSafe(outPath, sig);
|
||||
} else if (inputFile) {
|
||||
writeFileSafe(`${inputFile}.sig`, sig);
|
||||
console.error(`Signature: ${inputFile}.sig`);
|
||||
} else {
|
||||
process.stdout.write(Buffer.from(sig));
|
||||
}
|
||||
id.free();
|
||||
break;
|
||||
}
|
||||
|
||||
case "verify": {
|
||||
const pkBytes = readFile(args[1]);
|
||||
const message = readFile(args[2]);
|
||||
const sigPath = getArg("--sig") || `${args[2]}.sig`;
|
||||
const sigBytes = readFile(sigPath);
|
||||
soliton.hybridVerify(pkBytes, message, sigBytes);
|
||||
console.error("Signature OK");
|
||||
break;
|
||||
}
|
||||
|
||||
case "xwing-keygen": {
|
||||
const dir = getArg("--output") || getArg("-o") || ".";
|
||||
const kp = soliton.xwingKeygen();
|
||||
writeFileSafe(join(dir, "xwing.pk"), kp.publicKey);
|
||||
writeSecretFile(join(dir, "xwing.sk"), kp.secretKey);
|
||||
console.error(`Public key: ${join(dir, "xwing.pk")}`);
|
||||
console.error(`Secret key: ${join(dir, "xwing.sk")}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case "sign-prekey": {
|
||||
const skBytes = readFile(args[1]);
|
||||
const spkBytes = readFile(args[2]);
|
||||
const sig = soliton.kexSignPrekey(skBytes, spkBytes);
|
||||
const out = getArg("--output") || getArg("-o") || "spk.sig";
|
||||
writeFileSafe(out, sig);
|
||||
console.error(`Pre-key signature: ${out}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case "phrase": {
|
||||
const pkA = readFile(args[1]);
|
||||
const pkB = readFile(args[2]);
|
||||
console.log(soliton.verificationPhrase(pkA, pkB));
|
||||
break;
|
||||
}
|
||||
|
||||
case "encrypt": {
|
||||
const keyPath = getArg("--key") || getArg("-k");
|
||||
const derive = hasFlag("--derive");
|
||||
const saltHex = getArg("--salt");
|
||||
let key;
|
||||
|
||||
if (derive) {
|
||||
const password = await readPassphrase("Passphrase: ");
|
||||
let salt;
|
||||
if (saltHex) {
|
||||
salt = hexDecode(saltHex);
|
||||
} else {
|
||||
salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
console.error(`Salt: ${hexEncode(salt)} (save this to decrypt later)`);
|
||||
}
|
||||
key = soliton.argon2id(new TextEncoder().encode(password), salt, 65536, 3, 4, 32);
|
||||
} else if (keyPath) {
|
||||
key = readFile(keyPath);
|
||||
} else {
|
||||
console.error("error: provide --key <file> or --derive");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const inputFile = getPositionalAfter(1);
|
||||
const plaintext = readInput(inputFile);
|
||||
const enc = new soliton.StreamEncryptor(key);
|
||||
const header = enc.header();
|
||||
|
||||
const chunks = [];
|
||||
chunks.push(header);
|
||||
|
||||
if (plaintext.length === 0) {
|
||||
chunks.push(enc.encryptChunk(new Uint8Array(0), true));
|
||||
} else {
|
||||
const totalChunks = Math.ceil(plaintext.length / STREAM_CHUNK_SIZE);
|
||||
for (let i = 0; i < totalChunks; i++) {
|
||||
const start = i * STREAM_CHUNK_SIZE;
|
||||
const end = Math.min(start + STREAM_CHUNK_SIZE, plaintext.length);
|
||||
const isLast = i === totalChunks - 1;
|
||||
chunks.push(enc.encryptChunk(plaintext.subarray(start, end), isLast));
|
||||
}
|
||||
}
|
||||
enc.free();
|
||||
|
||||
const totalLen = chunks.reduce((s, c) => s + c.length, 0);
|
||||
const combined = new Uint8Array(totalLen);
|
||||
let offset = 0;
|
||||
for (const c of chunks) {
|
||||
combined.set(c, offset);
|
||||
offset += c.length;
|
||||
}
|
||||
|
||||
const outPath = getArg("--output") || getArg("-o");
|
||||
if (outPath) {
|
||||
writeFileSafe(outPath, combined);
|
||||
} else {
|
||||
process.stdout.write(Buffer.from(combined));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "decrypt": {
|
||||
const keyPath = getArg("--key") || getArg("-k");
|
||||
const derive = hasFlag("--derive");
|
||||
const saltHex = getArg("--salt");
|
||||
let key;
|
||||
|
||||
if (derive) {
|
||||
if (!saltHex) {
|
||||
console.error("error: --derive requires --salt <hex> for decryption");
|
||||
process.exit(1);
|
||||
}
|
||||
const password = await readPassphrase("Passphrase: ");
|
||||
key = soliton.argon2id(
|
||||
new TextEncoder().encode(password),
|
||||
hexDecode(saltHex),
|
||||
65536,
|
||||
3,
|
||||
4,
|
||||
32,
|
||||
);
|
||||
} else if (keyPath) {
|
||||
key = readFile(keyPath);
|
||||
} else {
|
||||
console.error("error: provide --key <file> or --derive --salt <hex>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const inputFile = getPositionalAfter(1);
|
||||
const data = readInput(inputFile);
|
||||
if (data.length < 26) {
|
||||
console.error("error: input too short (missing stream header)");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const header = data.subarray(0, 26);
|
||||
const ciphertext = data.subarray(26);
|
||||
|
||||
const dec = new soliton.StreamDecryptor(key, header);
|
||||
const ptChunks = [];
|
||||
|
||||
// Each chunk: tag_byte (1) + ciphertext (variable) + AEAD tag (16).
|
||||
// Non-final uncompressed: 1 + 1,048,576 + 16 = 1,048,593 bytes.
|
||||
// Final: everything remaining.
|
||||
let pos = 0;
|
||||
while (pos < ciphertext.length) {
|
||||
const tagByte = ciphertext[pos];
|
||||
const isFinalChunk = tagByte === 0x01;
|
||||
const chunkSize = isFinalChunk
|
||||
? ciphertext.length - pos
|
||||
: 1 + STREAM_CHUNK_SIZE + 16;
|
||||
if (pos + chunkSize > ciphertext.length) {
|
||||
throw new Error("truncated chunk in stream");
|
||||
}
|
||||
const { plaintext: pt, isLast } = dec.decryptChunk(
|
||||
ciphertext.subarray(pos, pos + chunkSize),
|
||||
);
|
||||
ptChunks.push(pt);
|
||||
pos += chunkSize;
|
||||
if (isLast) break;
|
||||
}
|
||||
|
||||
// Truncation detection: an attacker who strips the final chunk leaves
|
||||
// the decryptor non-finalized with all prior chunks authentic.
|
||||
if (!dec.isFinalized()) {
|
||||
dec.free();
|
||||
throw new Error("stream truncated: final chunk missing");
|
||||
}
|
||||
dec.free();
|
||||
|
||||
const totalLen = ptChunks.reduce((s, c) => s + c.length, 0);
|
||||
const plaintext = new Uint8Array(totalLen);
|
||||
let off = 0;
|
||||
for (const c of ptChunks) {
|
||||
plaintext.set(c, off);
|
||||
off += c.length;
|
||||
}
|
||||
|
||||
const outPath = getArg("--output") || getArg("-o");
|
||||
if (outPath) {
|
||||
writeFileSafe(outPath, plaintext);
|
||||
} else {
|
||||
process.stdout.write(Buffer.from(plaintext));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "argon2id": {
|
||||
const m = Number.parseInt(getArg("--m") || "65536");
|
||||
const t = Number.parseInt(getArg("--t") || "3");
|
||||
const p = Number.parseInt(getArg("--p") || "4");
|
||||
const len = Number.parseInt(getArg("--length") || "32");
|
||||
|
||||
const password = await readPassphrase("Passphrase: ");
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
const key = soliton.argon2id(new TextEncoder().encode(password), salt, m, t, p, len);
|
||||
console.error(`Salt: ${hexEncode(salt)}`);
|
||||
console.log(hexEncode(key));
|
||||
break;
|
||||
}
|
||||
|
||||
case "version":
|
||||
console.log(`soliton ${soliton.version()} (wasm)`);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(`Unknown command: ${cmd}`);
|
||||
usage();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`error: ${e.message || e}`);
|
||||
process.exit(1);
|
||||
}
|
||||
16
soliton_wasm/package.json
Normal file
16
soliton_wasm/package.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "wasm-pack build --target bundler && node -e \"const p=JSON.parse(require('fs').readFileSync('pkg/package.json'));p.bin={soliton:'bin/soliton.js'};p.files.push('bin/soliton.js');p.publishConfig={registry:'https://git.lo.sh/api/packages/lo/npm/'};require('fs').writeFileSync('pkg/package.json',JSON.stringify(p,null,2))\" && rm -rf pkg/bin && cp -r bin pkg/bin",
|
||||
"test": "vitest run",
|
||||
"test:browser": "vitest run --config vitest.browser.config.js",
|
||||
"test:all": "vitest run && vitest run --config vitest.browser.config.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitest/browser": "^3.2.4",
|
||||
"playwright": "^1.59.0",
|
||||
"vite-plugin-wasm": "^3.6.0",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
46
soliton_wasm/src/auth.rs
Normal file
46
soliton_wasm/src/auth.rs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
//! LO-Auth: zero-knowledge authentication via KEM challenge-response.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Generate an auth challenge. Returns { ciphertext: Uint8Array, token: Uint8Array }.
|
||||
#[wasm_bindgen(js_name = "authChallenge")]
|
||||
pub fn auth_challenge(client_pk: &[u8]) -> Result<JsValue, JsValue> {
|
||||
let pk =
|
||||
soliton::identity::IdentityPublicKey::from_bytes(client_pk.to_vec()).map_err(to_js_err)?;
|
||||
let (ct, token) = soliton::auth::auth_challenge(&pk).map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"ciphertext".into(),
|
||||
&js_sys::Uint8Array::from(ct.as_bytes()),
|
||||
)?;
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"token".into(),
|
||||
&js_sys::Uint8Array::from(&*token as &[u8]),
|
||||
)?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Respond to an auth challenge. Returns 32-byte proof.
|
||||
#[wasm_bindgen(js_name = "authRespond")]
|
||||
pub fn auth_respond(client_sk: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, JsValue> {
|
||||
let sk =
|
||||
soliton::identity::IdentitySecretKey::from_bytes(client_sk.to_vec()).map_err(to_js_err)?;
|
||||
let ct = soliton::primitives::xwing::Ciphertext::from_bytes(ciphertext.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let proof = soliton::auth::auth_respond(&sk, &ct).map_err(to_js_err)?;
|
||||
Ok(proof.to_vec())
|
||||
}
|
||||
|
||||
/// Verify an auth proof (constant-time). Returns true if valid.
|
||||
#[wasm_bindgen(js_name = "authVerify")]
|
||||
pub fn auth_verify(expected_token: &[u8], proof: &[u8]) -> Result<bool, JsValue> {
|
||||
if expected_token.len() != 32 || proof.len() != 32 {
|
||||
return Err(crate::errors::js_error("both inputs must be 32 bytes"));
|
||||
}
|
||||
let a: &[u8; 32] = expected_token.try_into().unwrap();
|
||||
let b: &[u8; 32] = proof.try_into().unwrap();
|
||||
Ok(soliton::auth::auth_verify(a, b))
|
||||
}
|
||||
54
soliton_wasm/src/call.rs
Normal file
54
soliton_wasm/src/call.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
//! Call key derivation.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Call keys for encrypted voice/video media.
|
||||
///
|
||||
/// Call `free()` when done to zeroize key material.
|
||||
#[wasm_bindgen]
|
||||
pub struct CallKeys {
|
||||
inner: Option<soliton::call::CallKeys>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl CallKeys {
|
||||
/// Current send key (32 bytes).
|
||||
#[wasm_bindgen(js_name = "sendKey")]
|
||||
pub fn send_key(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("call keys consumed"))?;
|
||||
Ok(inner.send_key().to_vec())
|
||||
}
|
||||
|
||||
/// Current recv key (32 bytes).
|
||||
#[wasm_bindgen(js_name = "recvKey")]
|
||||
pub fn recv_key(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("call keys consumed"))?;
|
||||
Ok(inner.recv_key().to_vec())
|
||||
}
|
||||
|
||||
/// Advance the call chain — derives fresh keys, zeroizes old ones.
|
||||
pub fn advance(&mut self) -> Result<(), JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("call keys consumed"))?;
|
||||
inner.advance().map_err(to_js_err)
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl CallKeys {
|
||||
pub fn from_inner(inner: soliton::call::CallKeys) -> Self {
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
}
|
||||
16
soliton_wasm/src/errors.rs
Normal file
16
soliton_wasm/src/errors.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
//! Error mapping from soliton::error::Error to JsValue.
|
||||
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
/// Convert a soliton error to a JS `Error` object.
|
||||
pub fn to_js_err(e: soliton::error::Error) -> JsValue {
|
||||
js_sys::Error::new(&e.to_string()).into()
|
||||
}
|
||||
|
||||
/// Create a JS `Error` from a string message.
|
||||
/// Use this instead of `JsValue::from_str()` so that thrown values are
|
||||
/// proper `Error` instances — `instanceof Error`, `.message`, and `.stack`
|
||||
/// all work as JS callers expect.
|
||||
pub fn js_error(msg: &str) -> JsValue {
|
||||
js_sys::Error::new(msg).into()
|
||||
}
|
||||
102
soliton_wasm/src/identity.rs
Normal file
102
soliton_wasm/src/identity.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
//! Identity key management.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// An identity keypair (X-Wing + Ed25519 + ML-DSA-65).
|
||||
///
|
||||
/// Call `free()` when done to zeroize secret key material.
|
||||
#[wasm_bindgen]
|
||||
pub struct Identity {
|
||||
pk: soliton::identity::IdentityPublicKey,
|
||||
sk: Option<soliton::identity::IdentitySecretKey>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Identity {
|
||||
/// Generate a fresh identity keypair.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn generate() -> Result<Identity, JsValue> {
|
||||
let id = soliton::identity::generate_identity().map_err(to_js_err)?;
|
||||
Ok(Self {
|
||||
pk: id.public_key,
|
||||
sk: Some(id.secret_key),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reconstruct from serialized public + secret key bytes.
|
||||
#[wasm_bindgen(js_name = "fromBytes")]
|
||||
pub fn from_bytes(pk_bytes: &[u8], sk_bytes: &[u8]) -> Result<Identity, JsValue> {
|
||||
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let sk = soliton::identity::IdentitySecretKey::from_bytes(sk_bytes.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
Ok(Self { pk, sk: Some(sk) })
|
||||
}
|
||||
|
||||
/// Reconstruct a public-key-only identity (cannot sign).
|
||||
#[wasm_bindgen(js_name = "fromPublicBytes")]
|
||||
pub fn from_public_bytes(pk_bytes: &[u8]) -> Result<Identity, JsValue> {
|
||||
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
Ok(Self { pk, sk: None })
|
||||
}
|
||||
|
||||
/// Public key bytes (3200 bytes).
|
||||
#[wasm_bindgen(js_name = "publicKey")]
|
||||
pub fn public_key(&self) -> Vec<u8> {
|
||||
self.pk.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// Secret key bytes (2496 bytes). Throws if this is a public-key-only identity.
|
||||
#[wasm_bindgen(js_name = "secretKey")]
|
||||
pub fn secret_key(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let sk = self
|
||||
.sk
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("no secret key"))?;
|
||||
Ok(sk.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// SHA3-256 fingerprint of the public key (32 bytes).
|
||||
pub fn fingerprint(&self) -> Vec<u8> {
|
||||
soliton::primitives::sha3_256::hash(self.pk.as_bytes()).to_vec()
|
||||
}
|
||||
|
||||
/// Hex-encoded fingerprint (64 chars).
|
||||
#[wasm_bindgen(js_name = "fingerprintHex")]
|
||||
pub fn fingerprint_hex(&self) -> String {
|
||||
soliton::primitives::sha3_256::fingerprint_hex(self.pk.as_bytes())
|
||||
}
|
||||
|
||||
/// Hybrid sign (Ed25519 + ML-DSA-65). Returns signature bytes (3373 bytes).
|
||||
pub fn sign(&self, message: &[u8]) -> Result<Vec<u8>, JsValue> {
|
||||
let sk = self
|
||||
.sk
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("no secret key"))?;
|
||||
let sig = soliton::identity::hybrid_sign(sk, message).map_err(to_js_err)?;
|
||||
Ok(sig.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Verify a hybrid signature against this identity's public key.
|
||||
pub fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), JsValue> {
|
||||
let sig = soliton::identity::HybridSignature::from_bytes(signature.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
soliton::identity::hybrid_verify(&self.pk, message, &sig).map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Zeroize the secret key.
|
||||
pub fn free(&mut self) {
|
||||
self.sk = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify a hybrid signature against raw public key bytes.
|
||||
#[wasm_bindgen(js_name = "hybridVerify")]
|
||||
pub fn hybrid_verify(pk: &[u8], message: &[u8], signature: &[u8]) -> Result<(), JsValue> {
|
||||
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk.to_vec()).map_err(to_js_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(signature.to_vec()).map_err(to_js_err)?;
|
||||
soliton::identity::hybrid_verify(&pk, message, &sig).map_err(to_js_err)
|
||||
}
|
||||
311
soliton_wasm/src/kex.rs
Normal file
311
soliton_wasm/src/kex.rs
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
//! LO-KEX: asynchronous key exchange.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Sign a pre-key with the identity key. Returns signature bytes (3373 bytes).
|
||||
#[wasm_bindgen(js_name = "kexSignPrekey")]
|
||||
pub fn kex_sign_prekey(ik_sk: &[u8], spk_pub: &[u8]) -> Result<Vec<u8>, JsValue> {
|
||||
let sk = soliton::identity::IdentitySecretKey::from_bytes(ik_sk.to_vec()).map_err(to_js_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_js_err)?;
|
||||
let sig = soliton::kex::sign_prekey(&sk, &spk).map_err(to_js_err)?;
|
||||
Ok(sig.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Verify a pre-key bundle. Throws on failure.
|
||||
#[wasm_bindgen(js_name = "kexVerifyBundle")]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn kex_verify_bundle(
|
||||
bundle_ik_pk: &[u8],
|
||||
known_ik_pk: &[u8],
|
||||
spk_pub: &[u8],
|
||||
spk_id: u32,
|
||||
spk_sig: &[u8],
|
||||
crypto_version: &str,
|
||||
opk_pub: Option<Vec<u8>>,
|
||||
opk_id: Option<u32>,
|
||||
) -> Result<(), JsValue> {
|
||||
let bik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let kik = soliton::identity::IdentityPublicKey::from_bytes(known_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_js_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_js_err)?;
|
||||
let opk = match opk_pub {
|
||||
Some(data) => {
|
||||
Some(soliton::primitives::xwing::PublicKey::from_bytes(data).map_err(to_js_err)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let bundle = soliton::kex::PreKeyBundle {
|
||||
ik_pub: bik,
|
||||
crypto_version: crypto_version.to_string(),
|
||||
spk_pub: spk,
|
||||
spk_id,
|
||||
spk_sig: sig,
|
||||
opk_pub: opk,
|
||||
opk_id,
|
||||
};
|
||||
soliton::kex::verify_bundle(bundle, &kik).map_err(to_js_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Result of session initiation (Alice's side).
|
||||
#[wasm_bindgen]
|
||||
pub struct InitiatedSession {
|
||||
inner: Option<soliton::kex::InitiatedSession>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl InitiatedSession {
|
||||
/// Encoded session init message bytes.
|
||||
#[wasm_bindgen(js_name = "sessionInitEncoded")]
|
||||
pub fn session_init_encoded(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
soliton::kex::encode_session_init(&s.session_init).map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Extract root key (32 bytes). Destructive — zeroed after first call.
|
||||
#[wasm_bindgen(js_name = "takeRootKey")]
|
||||
pub fn take_root_key(&mut self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.take_root_key().to_vec())
|
||||
}
|
||||
|
||||
/// Extract initial chain key (32 bytes). Destructive.
|
||||
#[wasm_bindgen(js_name = "takeInitialChainKey")]
|
||||
pub fn take_initial_chain_key(&mut self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.take_initial_chain_key().to_vec())
|
||||
}
|
||||
|
||||
/// Alice's ephemeral public key (1216 bytes).
|
||||
#[wasm_bindgen(js_name = "ekPk")]
|
||||
pub fn ek_pk(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.ek_pk.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Alice's ephemeral secret key (2432 bytes).
|
||||
#[wasm_bindgen(js_name = "ekSk")]
|
||||
pub fn ek_sk(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.ek_sk().as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Sender hybrid signature (3373 bytes).
|
||||
#[wasm_bindgen(js_name = "senderSig")]
|
||||
pub fn sender_sig(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.sender_sig.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Whether an OPK was used.
|
||||
#[wasm_bindgen(js_name = "opkUsed")]
|
||||
pub fn opk_used(&self) -> Result<bool, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.opk_used)
|
||||
}
|
||||
|
||||
/// Sender fingerprint (32 bytes).
|
||||
#[wasm_bindgen(js_name = "senderFingerprint")]
|
||||
pub fn sender_fingerprint(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.session_init.sender_ik_fingerprint.to_vec())
|
||||
}
|
||||
|
||||
/// Recipient fingerprint (32 bytes).
|
||||
#[wasm_bindgen(js_name = "recipientFingerprint")]
|
||||
pub fn recipient_fingerprint(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.session_init.recipient_ik_fingerprint.to_vec())
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Initiate a session (Alice's side).
|
||||
#[wasm_bindgen(js_name = "kexInitiate")]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn kex_initiate(
|
||||
alice_ik_pk: &[u8],
|
||||
alice_ik_sk: &[u8],
|
||||
bundle_ik_pk: &[u8],
|
||||
spk_pub: &[u8],
|
||||
spk_id: u32,
|
||||
spk_sig: &[u8],
|
||||
crypto_version: &str,
|
||||
opk_pub: Option<Vec<u8>>,
|
||||
opk_id: Option<u32>,
|
||||
) -> Result<InitiatedSession, JsValue> {
|
||||
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let a_sk = soliton::identity::IdentitySecretKey::from_bytes(alice_ik_sk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let b_pk = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let known_ik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_js_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_js_err)?;
|
||||
let opk = match opk_pub {
|
||||
Some(data) => {
|
||||
Some(soliton::primitives::xwing::PublicKey::from_bytes(data).map_err(to_js_err)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let bundle = soliton::kex::PreKeyBundle {
|
||||
ik_pub: b_pk,
|
||||
crypto_version: crypto_version.to_string(),
|
||||
spk_pub: spk,
|
||||
spk_id,
|
||||
spk_sig: sig,
|
||||
opk_pub: opk,
|
||||
opk_id,
|
||||
};
|
||||
|
||||
let verified = soliton::kex::verify_bundle(bundle, &known_ik).map_err(to_js_err)?;
|
||||
let session = soliton::kex::initiate_session(&a_pk, &a_sk, &verified).map_err(to_js_err)?;
|
||||
Ok(InitiatedSession {
|
||||
inner: Some(session),
|
||||
})
|
||||
}
|
||||
|
||||
/// Result of session receipt (Bob's side).
|
||||
#[wasm_bindgen]
|
||||
pub struct ReceivedSession {
|
||||
inner: Option<soliton::kex::ReceivedSession>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl ReceivedSession {
|
||||
/// Extract root key (32 bytes). Destructive.
|
||||
#[wasm_bindgen(js_name = "takeRootKey")]
|
||||
pub fn take_root_key(&mut self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.take_root_key().to_vec())
|
||||
}
|
||||
|
||||
/// Extract initial chain key (32 bytes). Destructive.
|
||||
#[wasm_bindgen(js_name = "takeInitialChainKey")]
|
||||
pub fn take_initial_chain_key(&mut self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.take_initial_chain_key().to_vec())
|
||||
}
|
||||
|
||||
/// Peer's ephemeral public key (1216 bytes).
|
||||
#[wasm_bindgen(js_name = "peerEk")]
|
||||
pub fn peer_ek(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("session consumed"))?;
|
||||
Ok(s.peer_ek.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive a session (Bob's side).
|
||||
#[wasm_bindgen(js_name = "kexReceive")]
|
||||
pub fn kex_receive(
|
||||
bob_ik_pk: &[u8],
|
||||
bob_ik_sk: &[u8],
|
||||
alice_ik_pk: &[u8],
|
||||
session_init_encoded: &[u8],
|
||||
sender_sig: &[u8],
|
||||
spk_sk: &[u8],
|
||||
opk_sk: Option<Vec<u8>>,
|
||||
) -> Result<ReceivedSession, JsValue> {
|
||||
let b_pk =
|
||||
soliton::identity::IdentityPublicKey::from_bytes(bob_ik_pk.to_vec()).map_err(to_js_err)?;
|
||||
let b_sk =
|
||||
soliton::identity::IdentitySecretKey::from_bytes(bob_ik_sk.to_vec()).map_err(to_js_err)?;
|
||||
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let si = soliton::kex::decode_session_init(session_init_encoded).map_err(to_js_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(sender_sig.to_vec()).map_err(to_js_err)?;
|
||||
let spk_secret =
|
||||
soliton::primitives::xwing::SecretKey::from_bytes(spk_sk.to_vec()).map_err(to_js_err)?;
|
||||
let opk_secret = match opk_sk {
|
||||
Some(data) => {
|
||||
Some(soliton::primitives::xwing::SecretKey::from_bytes(data).map_err(to_js_err)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let session = soliton::kex::receive_session(
|
||||
&b_pk,
|
||||
&b_sk,
|
||||
&a_pk,
|
||||
&si,
|
||||
&sig,
|
||||
&spk_secret,
|
||||
opk_secret.as_ref(),
|
||||
)
|
||||
.map_err(to_js_err)?;
|
||||
Ok(ReceivedSession {
|
||||
inner: Some(session),
|
||||
})
|
||||
}
|
||||
|
||||
/// Build first-message AAD from fingerprints and encoded session init.
|
||||
#[wasm_bindgen(js_name = "kexBuildFirstMessageAad")]
|
||||
pub fn kex_build_first_message_aad(
|
||||
sender_fp: &[u8],
|
||||
recipient_fp: &[u8],
|
||||
session_init_encoded: &[u8],
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
if sender_fp.len() != 32 || recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::js_error("fingerprints must be 32 bytes"));
|
||||
}
|
||||
let sfp: &[u8; 32] = sender_fp.try_into().unwrap();
|
||||
let rfp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
soliton::kex::build_first_message_aad_from_encoded(sfp, rfp, session_init_encoded)
|
||||
.map_err(to_js_err)
|
||||
}
|
||||
24
soliton_wasm/src/lib.rs
Normal file
24
soliton_wasm/src/lib.rs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
//! WebAssembly bindings for libsoliton.
|
||||
//!
|
||||
//! Provides the full libsoliton API to JavaScript/TypeScript via wasm-bindgen.
|
||||
//! All byte arrays are exchanged as `Uint8Array` (via `Vec<u8>` / `&[u8]`).
|
||||
//! Errors are thrown as JavaScript `Error` objects with descriptive messages.
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
mod auth;
|
||||
mod call;
|
||||
mod errors;
|
||||
mod identity;
|
||||
mod kex;
|
||||
mod primitives;
|
||||
mod ratchet;
|
||||
mod storage;
|
||||
mod stream;
|
||||
mod verification;
|
||||
|
||||
/// Library version string.
|
||||
#[wasm_bindgen(js_name = "version")]
|
||||
pub fn version() -> String {
|
||||
soliton::VERSION.to_string()
|
||||
}
|
||||
84
soliton_wasm/src/primitives.rs
Normal file
84
soliton_wasm/src/primitives.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
//! Primitive cryptographic operations.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// SHA3-256 hash. Returns 32 bytes.
|
||||
#[wasm_bindgen(js_name = "sha3_256")]
|
||||
pub fn sha3_256(data: &[u8]) -> Vec<u8> {
|
||||
soliton::primitives::sha3_256::hash(data).to_vec()
|
||||
}
|
||||
|
||||
/// SHA3-256 hex fingerprint of arbitrary data. Returns 64-char hex string.
|
||||
#[wasm_bindgen(js_name = "fingerprintHex")]
|
||||
pub fn fingerprint_hex(data: &[u8]) -> String {
|
||||
soliton::primitives::sha3_256::fingerprint_hex(data)
|
||||
}
|
||||
|
||||
/// HMAC-SHA3-256. Returns 32 bytes.
|
||||
#[wasm_bindgen(js_name = "hmacSha3_256")]
|
||||
pub fn hmac_sha3_256(key: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
soliton::primitives::hmac::hmac_sha3_256(key, data).to_vec()
|
||||
}
|
||||
|
||||
/// Constant-time HMAC-SHA3-256 verification.
|
||||
#[wasm_bindgen(js_name = "hmacSha3_256Verify")]
|
||||
pub fn hmac_sha3_256_verify(a: &[u8], b: &[u8]) -> Result<bool, JsValue> {
|
||||
if a.len() != 32 || b.len() != 32 {
|
||||
return Err(crate::errors::js_error("both inputs must be 32 bytes"));
|
||||
}
|
||||
let a: &[u8; 32] = a.try_into().unwrap();
|
||||
let b: &[u8; 32] = b.try_into().unwrap();
|
||||
Ok(soliton::primitives::hmac::hmac_sha3_256_verify_raw(a, b))
|
||||
}
|
||||
|
||||
/// HKDF-SHA3-256 extract-and-expand. Returns `length` bytes.
|
||||
#[wasm_bindgen(js_name = "hkdfSha3_256")]
|
||||
pub fn hkdf_sha3_256(
|
||||
salt: &[u8],
|
||||
ikm: &[u8],
|
||||
info: &[u8],
|
||||
length: usize,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let mut out = vec![0u8; length];
|
||||
soliton::primitives::hkdf::hkdf_sha3_256(salt, ikm, info, &mut out).map_err(to_js_err)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Generate an X-Wing keypair. Returns { publicKey: Uint8Array, secretKey: Uint8Array }.
|
||||
#[wasm_bindgen(js_name = "xwingKeygen")]
|
||||
pub fn xwing_keygen() -> Result<JsValue, JsValue> {
|
||||
let (pk, sk) = soliton::primitives::xwing::keygen().map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"publicKey".into(),
|
||||
&js_sys::Uint8Array::from(pk.as_bytes()),
|
||||
)?;
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"secretKey".into(),
|
||||
&js_sys::Uint8Array::from(sk.as_bytes()),
|
||||
)?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Argon2id key derivation. Returns `outLength` bytes.
|
||||
#[wasm_bindgen(js_name = "argon2id")]
|
||||
pub fn argon2id(
|
||||
password: &[u8],
|
||||
salt: &[u8],
|
||||
m_cost: u32,
|
||||
t_cost: u32,
|
||||
p_cost: u32,
|
||||
out_length: usize,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let params = soliton::primitives::argon2::Argon2Params {
|
||||
m_cost,
|
||||
t_cost,
|
||||
p_cost,
|
||||
};
|
||||
let mut out = vec![0u8; out_length];
|
||||
soliton::primitives::argon2::argon2id(password, salt, params, &mut out).map_err(to_js_err)?;
|
||||
Ok(out)
|
||||
}
|
||||
308
soliton_wasm/src/ratchet.rs
Normal file
308
soliton_wasm/src/ratchet.rs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
//! Double ratchet session.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
/// Double ratchet session state.
|
||||
///
|
||||
/// Call `free()` when done to zeroize all key material.
|
||||
#[wasm_bindgen]
|
||||
pub struct Ratchet {
|
||||
inner: Option<soliton::ratchet::RatchetState>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Ratchet {
|
||||
/// Initialize Alice's side (initiator).
|
||||
#[wasm_bindgen(js_name = "initAlice")]
|
||||
pub fn init_alice(
|
||||
root_key: &[u8],
|
||||
chain_key: &[u8],
|
||||
local_fp: &[u8],
|
||||
remote_fp: &[u8],
|
||||
peer_ek: &[u8],
|
||||
ek_sk: &[u8],
|
||||
) -> Result<Ratchet, JsValue> {
|
||||
let mut rk = to_32("root_key", root_key)?;
|
||||
let mut ck = to_32("chain_key", chain_key)?;
|
||||
let lfp = to_32("local_fp", local_fp)?;
|
||||
let rfp = to_32("remote_fp", remote_fp)?;
|
||||
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let ek_secret =
|
||||
soliton::primitives::xwing::SecretKey::from_bytes(ek_sk.to_vec()).map_err(to_js_err)?;
|
||||
|
||||
let state = soliton::ratchet::RatchetState::init_alice(rk, ck, lfp, rfp, ek_pub, ek_secret)
|
||||
.map_err(to_js_err)?;
|
||||
rk.zeroize();
|
||||
ck.zeroize();
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Initialize Bob's side (responder).
|
||||
#[wasm_bindgen(js_name = "initBob")]
|
||||
pub fn init_bob(
|
||||
root_key: &[u8],
|
||||
chain_key: &[u8],
|
||||
local_fp: &[u8],
|
||||
remote_fp: &[u8],
|
||||
peer_ek: &[u8],
|
||||
) -> Result<Ratchet, JsValue> {
|
||||
let mut rk = to_32("root_key", root_key)?;
|
||||
let mut ck = to_32("chain_key", chain_key)?;
|
||||
let lfp = to_32("local_fp", local_fp)?;
|
||||
let rfp = to_32("remote_fp", remote_fp)?;
|
||||
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
|
||||
let state = soliton::ratchet::RatchetState::init_bob(rk, ck, lfp, rfp, ek_pub)
|
||||
.map_err(to_js_err)?;
|
||||
rk.zeroize();
|
||||
ck.zeroize();
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Encrypt a plaintext message. Returns { header: Uint8Array, ciphertext: Uint8Array }.
|
||||
pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<JsValue, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
let msg = state.encrypt(plaintext).map_err(to_js_err)?;
|
||||
let header_bytes = encode_header(&msg.header);
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"header".into(),
|
||||
&js_sys::Uint8Array::from(header_bytes.as_slice()),
|
||||
)?;
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"ciphertext".into(),
|
||||
&js_sys::Uint8Array::from(msg.ciphertext.as_slice()),
|
||||
)?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Decrypt a received message.
|
||||
pub fn decrypt(&mut self, header: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
let rh = decode_header(header)?;
|
||||
let pt = state.decrypt(&rh, ciphertext).map_err(to_js_err)?;
|
||||
Ok(pt.to_vec())
|
||||
}
|
||||
|
||||
/// Encrypt the first message (pre-ratchet).
|
||||
/// Returns { encryptedPayload: Uint8Array, ratchetInitKey: Uint8Array }.
|
||||
#[wasm_bindgen(js_name = "encryptFirstMessage")]
|
||||
pub fn encrypt_first_message(
|
||||
chain_key: &[u8],
|
||||
plaintext: &[u8],
|
||||
aad: &[u8],
|
||||
) -> Result<JsValue, JsValue> {
|
||||
let ck = zeroizing_32("chain_key", chain_key)?;
|
||||
let (ct, rik) = soliton::ratchet::RatchetState::encrypt_first_message(ck, plaintext, aad)
|
||||
.map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"encryptedPayload".into(),
|
||||
&js_sys::Uint8Array::from(ct.as_slice()),
|
||||
)?;
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"ratchetInitKey".into(),
|
||||
&js_sys::Uint8Array::from(&*rik as &[u8]),
|
||||
)?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Decrypt the first message (pre-ratchet).
|
||||
/// Returns { plaintext: Uint8Array, ratchetInitKey: Uint8Array }.
|
||||
#[wasm_bindgen(js_name = "decryptFirstMessage")]
|
||||
pub fn decrypt_first_message(
|
||||
chain_key: &[u8],
|
||||
encrypted_payload: &[u8],
|
||||
aad: &[u8],
|
||||
) -> Result<JsValue, JsValue> {
|
||||
let ck = zeroizing_32("chain_key", chain_key)?;
|
||||
let (pt, rik) =
|
||||
soliton::ratchet::RatchetState::decrypt_first_message(ck, encrypted_payload, aad)
|
||||
.map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"plaintext".into(),
|
||||
&js_sys::Uint8Array::from(&*pt as &[u8]),
|
||||
)?;
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"ratchetInitKey".into(),
|
||||
&js_sys::Uint8Array::from(&*rik as &[u8]),
|
||||
)?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Serialize the ratchet state. Consumes the ratchet.
|
||||
/// Returns { blob: Uint8Array, epoch: BigInt }.
|
||||
#[wasm_bindgen(js_name = "toBytes")]
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
pub fn to_bytes(&mut self) -> Result<JsValue, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.take()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet already consumed"))?;
|
||||
let (blob, epoch) = state.to_bytes().map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"blob".into(),
|
||||
&js_sys::Uint8Array::from(&*blob as &[u8]),
|
||||
)?;
|
||||
js_sys::Reflect::set(&obj, &"epoch".into(), &JsValue::from(epoch))?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Deserialize ratchet state with anti-rollback protection.
|
||||
#[wasm_bindgen(js_name = "fromBytes")]
|
||||
pub fn from_bytes(data: &[u8], min_epoch: u64) -> Result<Ratchet, JsValue> {
|
||||
let state = soliton::ratchet::RatchetState::from_bytes_with_min_epoch(data, min_epoch)
|
||||
.map_err(to_js_err)?;
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Whether the ratchet can be serialized.
|
||||
#[wasm_bindgen(js_name = "canSerialize")]
|
||||
pub fn can_serialize(&self) -> Result<bool, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
Ok(state.can_serialize())
|
||||
}
|
||||
|
||||
/// Current epoch number.
|
||||
pub fn epoch(&self) -> Result<u64, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
Ok(state.epoch())
|
||||
}
|
||||
|
||||
/// Reset the ratchet (zeroize all keys).
|
||||
pub fn reset(&mut self) -> Result<(), JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
state.reset();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Derive call keys for encrypted voice/video.
|
||||
#[wasm_bindgen(js_name = "deriveCallKeys")]
|
||||
pub fn derive_call_keys(
|
||||
&self,
|
||||
kem_ss: &[u8],
|
||||
call_id: &[u8],
|
||||
) -> Result<super::call::CallKeys, JsValue> {
|
||||
let state = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("ratchet consumed or closed"))?;
|
||||
if kem_ss.len() != 32 {
|
||||
return Err(crate::errors::js_error("kem_ss must be 32 bytes"));
|
||||
}
|
||||
if call_id.len() != 16 {
|
||||
return Err(crate::errors::js_error("call_id must be 16 bytes"));
|
||||
}
|
||||
let ss: &[u8; 32] = kem_ss.try_into().unwrap();
|
||||
let cid: &[u8; 16] = call_id.try_into().unwrap();
|
||||
let keys = state.derive_call_keys(ss, cid).map_err(to_js_err)?;
|
||||
Ok(super::call::CallKeys::from_inner(keys))
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
if let Some(mut state) = self.inner.take() {
|
||||
state.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Header serialization — same wire format as the Python binding.
|
||||
fn encode_header(h: &soliton::ratchet::RatchetHeader) -> Vec<u8> {
|
||||
let pk_bytes = h.ratchet_pk.as_bytes();
|
||||
let has_ct = h.kem_ct.is_some();
|
||||
let size = 1216 + 1 + if has_ct { 2 + 1120 } else { 0 } + 4 + 4;
|
||||
let mut buf = Vec::with_capacity(size);
|
||||
buf.extend_from_slice(pk_bytes);
|
||||
if let Some(ref ct) = h.kem_ct {
|
||||
buf.push(0x01);
|
||||
let ct_bytes = ct.as_bytes();
|
||||
buf.extend_from_slice(&(ct_bytes.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(ct_bytes);
|
||||
} else {
|
||||
buf.push(0x00);
|
||||
}
|
||||
buf.extend_from_slice(&h.n.to_be_bytes());
|
||||
buf.extend_from_slice(&h.pn.to_be_bytes());
|
||||
buf
|
||||
}
|
||||
|
||||
fn decode_header(data: &[u8]) -> Result<soliton::ratchet::RatchetHeader, JsValue> {
|
||||
if data.len() < 1216 + 1 + 4 + 4 {
|
||||
return Err(crate::errors::js_error("header too short"));
|
||||
}
|
||||
let ratchet_pk = soliton::primitives::xwing::PublicKey::from_bytes(data[..1216].to_vec())
|
||||
.map_err(to_js_err)?;
|
||||
let has_ct = data[1216];
|
||||
if has_ct != 0x00 && has_ct != 0x01 {
|
||||
return Err(crate::errors::js_error(
|
||||
"invalid has_kem_ct flag (expected 0x00 or 0x01)",
|
||||
));
|
||||
}
|
||||
let rest = if has_ct == 0x01 {
|
||||
if data.len() < 1216 + 1 + 2 + 1120 + 4 + 4 {
|
||||
return Err(crate::errors::js_error("header too short for kem_ct"));
|
||||
}
|
||||
&data[1216 + 1 + 2 + 1120..]
|
||||
} else {
|
||||
&data[1216 + 1..]
|
||||
};
|
||||
let kem_ct = if has_ct == 0x01 {
|
||||
Some(
|
||||
soliton::primitives::xwing::Ciphertext::from_bytes(
|
||||
data[1216 + 1 + 2..1216 + 1 + 2 + 1120].to_vec(),
|
||||
)
|
||||
.map_err(to_js_err)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if rest.len() < 8 {
|
||||
return Err(crate::errors::js_error("header missing counters"));
|
||||
}
|
||||
let n = u32::from_be_bytes(rest[..4].try_into().unwrap());
|
||||
let pn = u32::from_be_bytes(rest[4..8].try_into().unwrap());
|
||||
Ok(soliton::ratchet::RatchetHeader {
|
||||
ratchet_pk,
|
||||
kem_ct,
|
||||
n,
|
||||
pn,
|
||||
})
|
||||
}
|
||||
|
||||
fn to_32(name: &str, data: &[u8]) -> Result<[u8; 32], JsValue> {
|
||||
data.try_into()
|
||||
.map_err(|_| crate::errors::js_error(&format!("{name} must be 32 bytes")))
|
||||
}
|
||||
|
||||
fn zeroizing_32(name: &str, data: &[u8]) -> Result<zeroize::Zeroizing<[u8; 32]>, JsValue> {
|
||||
let arr = to_32(name, data)?;
|
||||
Ok(zeroize::Zeroizing::new(arr))
|
||||
}
|
||||
152
soliton_wasm/src/storage.rs
Normal file
152
soliton_wasm/src/storage.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
//! Encrypted storage.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Encrypted storage key ring.
|
||||
///
|
||||
/// Call `free()` when done to zeroize key material.
|
||||
#[wasm_bindgen]
|
||||
pub struct StorageKeyRing {
|
||||
inner: Option<soliton::storage::StorageKeyRing>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl StorageKeyRing {
|
||||
/// Create a keyring with an initial active key.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(version: u8, key: &[u8]) -> Result<StorageKeyRing, JsValue> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::js_error("key must be 32 bytes"));
|
||||
}
|
||||
let key_arr: [u8; 32] = key.try_into().unwrap();
|
||||
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_js_err)?;
|
||||
let ring = soliton::storage::StorageKeyRing::new(storage_key).map_err(to_js_err)?;
|
||||
Ok(Self { inner: Some(ring) })
|
||||
}
|
||||
|
||||
/// Add a key to the ring.
|
||||
#[wasm_bindgen(js_name = "addKey")]
|
||||
pub fn add_key(&mut self, version: u8, key: &[u8], make_active: bool) -> Result<(), JsValue> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::js_error("key must be 32 bytes"));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
let key_arr: [u8; 32] = key.try_into().unwrap();
|
||||
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_js_err)?;
|
||||
ring.add_key(storage_key, make_active).map_err(to_js_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a key version from the ring.
|
||||
#[wasm_bindgen(js_name = "removeKey")]
|
||||
pub fn remove_key(&mut self, version: u8) -> Result<(), JsValue> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
ring.remove_key(version).map_err(to_js_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encrypt a community storage blob.
|
||||
#[wasm_bindgen(js_name = "encryptBlob")]
|
||||
pub fn encrypt_blob(
|
||||
&self,
|
||||
channel_id: &str,
|
||||
segment_id: &str,
|
||||
plaintext: &[u8],
|
||||
compress: Option<bool>,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
let key = ring
|
||||
.active_key()
|
||||
.ok_or_else(|| crate::errors::js_error("no active key"))?;
|
||||
soliton::storage::encrypt_blob(
|
||||
key,
|
||||
plaintext,
|
||||
channel_id,
|
||||
segment_id,
|
||||
compress.unwrap_or(false),
|
||||
)
|
||||
.map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Decrypt a community storage blob.
|
||||
#[wasm_bindgen(js_name = "decryptBlob")]
|
||||
pub fn decrypt_blob(
|
||||
&self,
|
||||
channel_id: &str,
|
||||
segment_id: &str,
|
||||
blob: &[u8],
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
let pt = soliton::storage::decrypt_blob(ring, blob, channel_id, segment_id)
|
||||
.map_err(to_js_err)?;
|
||||
Ok(pt.to_vec())
|
||||
}
|
||||
|
||||
/// Encrypt a DM queue blob.
|
||||
#[wasm_bindgen(js_name = "encryptDmQueue")]
|
||||
pub fn encrypt_dm_queue(
|
||||
&self,
|
||||
recipient_fp: &[u8],
|
||||
batch_id: &str,
|
||||
plaintext: &[u8],
|
||||
compress: Option<bool>,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
if recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::js_error("recipient_fp must be 32 bytes"));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
let key = ring
|
||||
.active_key()
|
||||
.ok_or_else(|| crate::errors::js_error("no active key"))?;
|
||||
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
soliton::storage::encrypt_dm_queue_blob(
|
||||
key,
|
||||
plaintext,
|
||||
fp,
|
||||
batch_id,
|
||||
compress.unwrap_or(false),
|
||||
)
|
||||
.map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Decrypt a DM queue blob.
|
||||
#[wasm_bindgen(js_name = "decryptDmQueue")]
|
||||
pub fn decrypt_dm_queue(
|
||||
&self,
|
||||
recipient_fp: &[u8],
|
||||
batch_id: &str,
|
||||
blob: &[u8],
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
if recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::js_error("recipient_fp must be 32 bytes"));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("keyring closed"))?;
|
||||
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
let pt =
|
||||
soliton::storage::decrypt_dm_queue_blob(ring, blob, fp, batch_id).map_err(to_js_err)?;
|
||||
Ok(pt.to_vec())
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
182
soliton_wasm/src/stream.rs
Normal file
182
soliton_wasm/src/stream.rs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
//! Streaming AEAD.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Streaming encryptor.
|
||||
///
|
||||
/// Call `free()` when done.
|
||||
#[wasm_bindgen]
|
||||
pub struct StreamEncryptor {
|
||||
inner: Option<soliton::streaming::StreamEncryptor>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl StreamEncryptor {
|
||||
/// Create a streaming encryptor.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(
|
||||
key: &[u8],
|
||||
aad: Option<Vec<u8>>,
|
||||
compress: Option<bool>,
|
||||
) -> Result<StreamEncryptor, JsValue> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::js_error("key must be 32 bytes"));
|
||||
}
|
||||
let key_arr: &[u8; 32] = key.try_into().unwrap();
|
||||
let aad_bytes = aad.as_deref().unwrap_or(&[]);
|
||||
let enc =
|
||||
soliton::streaming::stream_encrypt_init(key_arr, aad_bytes, compress.unwrap_or(false))
|
||||
.map_err(to_js_err)?;
|
||||
Ok(Self { inner: Some(enc) })
|
||||
}
|
||||
|
||||
/// The 26-byte stream header. Send this before any chunks.
|
||||
pub fn header(&self) -> Result<Vec<u8>, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("encryptor closed"))?;
|
||||
Ok(inner.header().to_vec())
|
||||
}
|
||||
|
||||
/// Encrypt one chunk. Non-final chunks must be exactly 1,048,576 bytes.
|
||||
#[wasm_bindgen(js_name = "encryptChunk")]
|
||||
pub fn encrypt_chunk(
|
||||
&mut self,
|
||||
plaintext: &[u8],
|
||||
is_last: Option<bool>,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("encryptor closed"))?;
|
||||
inner
|
||||
.encrypt_chunk(plaintext, is_last.unwrap_or(false))
|
||||
.map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Encrypt a specific chunk by index (random access, stateless).
|
||||
#[wasm_bindgen(js_name = "encryptChunkAt")]
|
||||
pub fn encrypt_chunk_at(
|
||||
&self,
|
||||
index: u64,
|
||||
plaintext: &[u8],
|
||||
is_last: Option<bool>,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("encryptor closed"))?;
|
||||
inner
|
||||
.encrypt_chunk_at(index, is_last.unwrap_or(false), plaintext)
|
||||
.map_err(to_js_err)
|
||||
}
|
||||
|
||||
/// Whether the encryptor has been finalized.
|
||||
#[wasm_bindgen(js_name = "isFinalized")]
|
||||
pub fn is_finalized(&self) -> Result<bool, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("encryptor closed"))?;
|
||||
Ok(inner.is_finalized())
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming decryptor.
|
||||
///
|
||||
/// Call `free()` when done.
|
||||
#[wasm_bindgen]
|
||||
pub struct StreamDecryptor {
|
||||
inner: Option<soliton::streaming::StreamDecryptor>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl StreamDecryptor {
|
||||
/// Create a streaming decryptor.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(
|
||||
key: &[u8],
|
||||
header: &[u8],
|
||||
aad: Option<Vec<u8>>,
|
||||
) -> Result<StreamDecryptor, JsValue> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::js_error("key must be 32 bytes"));
|
||||
}
|
||||
if header.len() != 26 {
|
||||
return Err(crate::errors::js_error("header must be 26 bytes"));
|
||||
}
|
||||
let key_arr: &[u8; 32] = key.try_into().unwrap();
|
||||
let hdr_arr: &[u8; 26] = header.try_into().unwrap();
|
||||
let aad_bytes = aad.as_deref().unwrap_or(&[]);
|
||||
let dec = soliton::streaming::stream_decrypt_init(key_arr, hdr_arr, aad_bytes)
|
||||
.map_err(to_js_err)?;
|
||||
Ok(Self { inner: Some(dec) })
|
||||
}
|
||||
|
||||
/// Decrypt the next sequential chunk. Returns { plaintext: Uint8Array, isLast: boolean }.
|
||||
#[wasm_bindgen(js_name = "decryptChunk")]
|
||||
pub fn decrypt_chunk(&mut self, chunk: &[u8]) -> Result<JsValue, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::js_error("decryptor closed"))?;
|
||||
let (pt, is_last) = inner.decrypt_chunk(chunk).map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"plaintext".into(),
|
||||
&js_sys::Uint8Array::from(&*pt as &[u8]),
|
||||
)?;
|
||||
js_sys::Reflect::set(&obj, &"isLast".into(), &JsValue::from_bool(is_last))?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Decrypt a specific chunk by index (random access).
|
||||
/// Returns { plaintext: Uint8Array, isLast: boolean }.
|
||||
#[wasm_bindgen(js_name = "decryptChunkAt")]
|
||||
pub fn decrypt_chunk_at(&self, index: u64, chunk: &[u8]) -> Result<JsValue, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("decryptor closed"))?;
|
||||
let (pt, is_last) = inner.decrypt_chunk_at(index, chunk).map_err(to_js_err)?;
|
||||
let obj = js_sys::Object::new();
|
||||
js_sys::Reflect::set(
|
||||
&obj,
|
||||
&"plaintext".into(),
|
||||
&js_sys::Uint8Array::from(&*pt as &[u8]),
|
||||
)?;
|
||||
js_sys::Reflect::set(&obj, &"isLast".into(), &JsValue::from_bool(is_last))?;
|
||||
Ok(obj.into())
|
||||
}
|
||||
|
||||
/// Whether the decryptor has seen the final chunk.
|
||||
#[wasm_bindgen(js_name = "isFinalized")]
|
||||
pub fn is_finalized(&self) -> Result<bool, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("decryptor closed"))?;
|
||||
Ok(inner.is_finalized())
|
||||
}
|
||||
|
||||
/// Next expected sequential chunk index.
|
||||
#[wasm_bindgen(js_name = "expectedIndex")]
|
||||
pub fn expected_index(&self) -> Result<u64, JsValue> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::js_error("decryptor closed"))?;
|
||||
Ok(inner.expected_index())
|
||||
}
|
||||
|
||||
pub fn free(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
}
|
||||
12
soliton_wasm/src/verification.rs
Normal file
12
soliton_wasm/src/verification.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
//! Verification phrases for out-of-band identity verification.
|
||||
|
||||
use crate::errors::to_js_err;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Generate a verification phrase from two identity public keys.
|
||||
/// Each key must be 3200 bytes. Returns a human-readable phrase (6 EFF words).
|
||||
/// The phrase is symmetric — swapping the keys produces the same phrase.
|
||||
#[wasm_bindgen(js_name = "verificationPhrase")]
|
||||
pub fn verification_phrase(pk_a: &[u8], pk_b: &[u8]) -> Result<String, JsValue> {
|
||||
soliton::verification::verification_phrase(pk_a, pk_b).map_err(to_js_err)
|
||||
}
|
||||
529
soliton_wasm/tests/soliton.test.js
Normal file
529
soliton_wasm/tests/soliton.test.js
Normal file
|
|
@ -0,0 +1,529 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import * as soliton from "../pkg/soliton_wasm.js";
|
||||
|
||||
const utf8 = (s) => new TextEncoder().encode(s);
|
||||
const fromUtf8 = (buf) => new TextDecoder().decode(buf);
|
||||
const randomBytes = (n) => crypto.getRandomValues(new Uint8Array(n));
|
||||
const bytesEqual = (a, b) => {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// ── Version ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("version", () => {
|
||||
it("returns non-empty string", () => {
|
||||
const v = soliton.version();
|
||||
expect(v.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Primitives ──────────────────────────────────────────────────────────
|
||||
|
||||
describe("primitives", () => {
|
||||
it("sha3_256 known vector — empty", () => {
|
||||
const hash = soliton.sha3_256(new Uint8Array(0));
|
||||
expect(hash.length).toBe(32);
|
||||
expect(hash[0]).toBe(0xa7);
|
||||
expect(hash[1]).toBe(0xff);
|
||||
});
|
||||
|
||||
it("sha3_256 known vector — abc", () => {
|
||||
const hash = soliton.sha3_256(utf8("abc"));
|
||||
expect(hash.length).toBe(32);
|
||||
expect(hash[0]).toBe(0x3a);
|
||||
expect(hash[1]).toBe(0x98);
|
||||
});
|
||||
|
||||
it("fingerprintHex", () => {
|
||||
const hex = soliton.fingerprintHex(utf8("abc"));
|
||||
expect(hex.length).toBe(64);
|
||||
expect(typeof hex).toBe("string");
|
||||
});
|
||||
|
||||
it("hmacSha3_256 and verify", () => {
|
||||
const key = new Uint8Array(32).fill(0x0b);
|
||||
const tag = soliton.hmacSha3_256(key, utf8("Hi There"));
|
||||
expect(tag.length).toBe(32);
|
||||
expect(soliton.hmacSha3_256Verify(tag, tag)).toBe(true);
|
||||
|
||||
const bad = new Uint8Array(tag);
|
||||
bad[0] ^= 0xff;
|
||||
expect(soliton.hmacSha3_256Verify(tag, bad)).toBe(false);
|
||||
});
|
||||
|
||||
it("hkdfSha3_256", () => {
|
||||
const salt = new Uint8Array(32);
|
||||
const ikm = new Uint8Array(32).fill(0x0b);
|
||||
const okm = soliton.hkdfSha3_256(salt, ikm, utf8("test"), 64);
|
||||
expect(okm.length).toBe(64);
|
||||
});
|
||||
|
||||
it("xwingKeygen", () => {
|
||||
const kp = soliton.xwingKeygen();
|
||||
expect(kp.publicKey.length).toBe(1216);
|
||||
expect(kp.secretKey.length).toBe(2432);
|
||||
});
|
||||
|
||||
it("argon2id", () => {
|
||||
const salt = randomBytes(16);
|
||||
const key1 = soliton.argon2id(utf8("password"), salt, 19456, 2, 1, 32);
|
||||
const key2 = soliton.argon2id(utf8("password"), salt, 19456, 2, 1, 32);
|
||||
expect(key1.length).toBe(32);
|
||||
expect(bytesEqual(key1, key2)).toBe(true);
|
||||
|
||||
const key3 = soliton.argon2id(utf8("wrong"), salt, 19456, 2, 1, 32);
|
||||
expect(bytesEqual(key1, key3)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Identity ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("identity", () => {
|
||||
it("keygen", () => {
|
||||
const id = new soliton.Identity();
|
||||
expect(id.publicKey().length).toBe(3200);
|
||||
expect(id.secretKey().length).toBe(2496);
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("fingerprint", () => {
|
||||
const id = new soliton.Identity();
|
||||
const fp = id.fingerprint();
|
||||
expect(fp.length).toBe(32);
|
||||
|
||||
// Verify fingerprint matches sha3_256(pk).
|
||||
const expected = soliton.sha3_256(id.publicKey());
|
||||
expect(bytesEqual(fp, expected)).toBe(true);
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("sign and verify", () => {
|
||||
const id = new soliton.Identity();
|
||||
const msg = utf8("test message");
|
||||
const sig = id.sign(msg);
|
||||
expect(sig.length).toBe(3373);
|
||||
id.verify(msg, sig); // throws on failure
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("verify wrong message throws", () => {
|
||||
const id = new soliton.Identity();
|
||||
const sig = id.sign(utf8("correct"));
|
||||
expect(() => id.verify(utf8("wrong"), sig)).toThrow();
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("verify wrong key throws", () => {
|
||||
const alice = new soliton.Identity();
|
||||
const bob = new soliton.Identity();
|
||||
const sig = alice.sign(utf8("hello"));
|
||||
expect(() => bob.verify(utf8("hello"), sig)).toThrow();
|
||||
alice.free();
|
||||
bob.free();
|
||||
});
|
||||
|
||||
it("fromBytes round trip", () => {
|
||||
const id = new soliton.Identity();
|
||||
const pk = id.publicKey();
|
||||
const sk = id.secretKey();
|
||||
id.free();
|
||||
|
||||
const id2 = soliton.Identity.fromBytes(pk, sk);
|
||||
const sig = id2.sign(utf8("roundtrip"));
|
||||
id2.verify(utf8("roundtrip"), sig);
|
||||
id2.free();
|
||||
});
|
||||
|
||||
it("fromPublicBytes cannot sign", () => {
|
||||
const id = new soliton.Identity();
|
||||
const pk = id.publicKey();
|
||||
id.free();
|
||||
|
||||
const pub_only = soliton.Identity.fromPublicBytes(pk);
|
||||
expect(() => pub_only.sign(utf8("test"))).toThrow();
|
||||
pub_only.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Auth ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("auth", () => {
|
||||
it("challenge-respond-verify round trip", () => {
|
||||
const id = new soliton.Identity();
|
||||
const pk = id.publicKey();
|
||||
const sk = id.secretKey();
|
||||
|
||||
const { ciphertext, token } = soliton.authChallenge(pk);
|
||||
const proof = soliton.authRespond(sk, ciphertext);
|
||||
expect(soliton.authVerify(token, proof)).toBe(true);
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("wrong proof fails", () => {
|
||||
const id = new soliton.Identity();
|
||||
const { token } = soliton.authChallenge(id.publicKey());
|
||||
expect(soliton.authVerify(token, new Uint8Array(32))).toBe(false);
|
||||
id.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Verification ────────────────────────────────────────────────────────
|
||||
|
||||
describe("verification", () => {
|
||||
it("phrase is symmetric", () => {
|
||||
const alice = new soliton.Identity();
|
||||
const bob = new soliton.Identity();
|
||||
|
||||
const p1 = soliton.verificationPhrase(alice.publicKey(), bob.publicKey());
|
||||
const p2 = soliton.verificationPhrase(bob.publicKey(), alice.publicKey());
|
||||
expect(p1.length).toBeGreaterThan(0);
|
||||
expect(p1).toBe(p2);
|
||||
|
||||
alice.free();
|
||||
bob.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Storage ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe("storage", () => {
|
||||
it("encrypt/decrypt round trip", () => {
|
||||
const key = randomBytes(32);
|
||||
const ring = new soliton.StorageKeyRing(1, key);
|
||||
const pt = utf8("encrypted storage data");
|
||||
const blob = ring.encryptBlob("channel-1", "segment-0", pt);
|
||||
const result = ring.decryptBlob("channel-1", "segment-0", blob);
|
||||
expect(bytesEqual(result, pt)).toBe(true);
|
||||
ring.free();
|
||||
});
|
||||
|
||||
it("wrong channel fails", () => {
|
||||
const ring = new soliton.StorageKeyRing(1, randomBytes(32));
|
||||
const blob = ring.encryptBlob("ch-1", "seg", utf8("data"));
|
||||
expect(() => ring.decryptBlob("ch-2", "seg", blob)).toThrow();
|
||||
ring.free();
|
||||
});
|
||||
|
||||
it("key rotation", () => {
|
||||
const ring = new soliton.StorageKeyRing(1, randomBytes(32));
|
||||
const blob_v1 = ring.encryptBlob("ch", "seg", utf8("v1"));
|
||||
ring.addKey(2, randomBytes(32), true);
|
||||
const blob_v2 = ring.encryptBlob("ch", "seg", utf8("v2"));
|
||||
|
||||
expect(fromUtf8(ring.decryptBlob("ch", "seg", blob_v1))).toBe("v1");
|
||||
expect(fromUtf8(ring.decryptBlob("ch", "seg", blob_v2))).toBe("v2");
|
||||
ring.free();
|
||||
});
|
||||
|
||||
it("dm queue round trip", () => {
|
||||
const ring = new soliton.StorageKeyRing(1, randomBytes(32));
|
||||
const fp = randomBytes(32);
|
||||
const pt = utf8("queued DM");
|
||||
const blob = ring.encryptDmQueue(fp, "batch-1", pt);
|
||||
const result = ring.decryptDmQueue(fp, "batch-1", blob);
|
||||
expect(bytesEqual(result, pt)).toBe(true);
|
||||
ring.free();
|
||||
});
|
||||
|
||||
it("compress round trip", () => {
|
||||
const ring = new soliton.StorageKeyRing(1, randomBytes(32));
|
||||
const data = utf8("compressible ".repeat(100));
|
||||
const blob = ring.encryptBlob("ch", "seg", data, true);
|
||||
const result = ring.decryptBlob("ch", "seg", blob);
|
||||
expect(bytesEqual(result, data)).toBe(true);
|
||||
ring.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Streaming AEAD ──────────────────────────────────────────────────────
|
||||
|
||||
describe("streaming", () => {
|
||||
it("single chunk round trip", () => {
|
||||
const key = randomBytes(32);
|
||||
const enc = new soliton.StreamEncryptor(key);
|
||||
const header = enc.header();
|
||||
expect(header.length).toBe(26);
|
||||
const ct = enc.encryptChunk(utf8("hello stream"), true);
|
||||
enc.free();
|
||||
|
||||
const dec = new soliton.StreamDecryptor(key, header);
|
||||
const { plaintext, isLast } = dec.decryptChunk(ct);
|
||||
expect(fromUtf8(plaintext)).toBe("hello stream");
|
||||
expect(isLast).toBe(true);
|
||||
dec.free();
|
||||
});
|
||||
|
||||
it("encrypt_at/decrypt_at", () => {
|
||||
const key = randomBytes(32);
|
||||
const enc = new soliton.StreamEncryptor(key);
|
||||
const header = enc.header();
|
||||
const ct = enc.encryptChunkAt(5n, utf8("at index five"), true);
|
||||
enc.free();
|
||||
|
||||
const dec = new soliton.StreamDecryptor(key, header);
|
||||
const { plaintext } = dec.decryptChunkAt(5n, ct);
|
||||
expect(fromUtf8(plaintext)).toBe("at index five");
|
||||
dec.free();
|
||||
});
|
||||
|
||||
it("wrong key fails", () => {
|
||||
const enc = new soliton.StreamEncryptor(randomBytes(32));
|
||||
const header = enc.header();
|
||||
const ct = enc.encryptChunk(utf8("data"), true);
|
||||
enc.free();
|
||||
|
||||
const dec = new soliton.StreamDecryptor(randomBytes(32), header);
|
||||
expect(() => dec.decryptChunk(ct)).toThrow();
|
||||
dec.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── KEX + Ratchet ───────────────────────────────────────────────────────
|
||||
|
||||
describe("kex", () => {
|
||||
it("sign and verify bundle", () => {
|
||||
const bob = new soliton.Identity();
|
||||
const { publicKey: spkPub } = soliton.xwingKeygen();
|
||||
const sig = soliton.kexSignPrekey(bob.secretKey(), spkPub);
|
||||
expect(sig.length).toBe(3373);
|
||||
|
||||
soliton.kexVerifyBundle(
|
||||
bob.publicKey(), bob.publicKey(),
|
||||
spkPub, 1, sig, "lo-crypto-v1",
|
||||
);
|
||||
bob.free();
|
||||
});
|
||||
|
||||
it("verify bundle wrong key throws", () => {
|
||||
const bob = new soliton.Identity();
|
||||
const eve = new soliton.Identity();
|
||||
const { publicKey: spkPub } = soliton.xwingKeygen();
|
||||
const sig = soliton.kexSignPrekey(bob.secretKey(), spkPub);
|
||||
|
||||
expect(() => soliton.kexVerifyBundle(
|
||||
bob.publicKey(), eve.publicKey(),
|
||||
spkPub, 1, sig, "lo-crypto-v1",
|
||||
)).toThrow();
|
||||
bob.free();
|
||||
eve.free();
|
||||
});
|
||||
});
|
||||
|
||||
describe("first message", () => {
|
||||
it("encrypt/decrypt round trip", () => {
|
||||
const ck = randomBytes(32);
|
||||
const aad = utf8("test-aad");
|
||||
const pt = utf8("first application message");
|
||||
|
||||
const { encryptedPayload, ratchetInitKey: rikA } =
|
||||
soliton.Ratchet.encryptFirstMessage(ck, pt, aad);
|
||||
const { plaintext, ratchetInitKey: rikB } =
|
||||
soliton.Ratchet.decryptFirstMessage(ck, encryptedPayload, aad);
|
||||
|
||||
expect(fromUtf8(plaintext)).toBe("first application message");
|
||||
expect(bytesEqual(rikA, rikB)).toBe(true);
|
||||
});
|
||||
|
||||
it("wrong key throws", () => {
|
||||
const ck = randomBytes(32);
|
||||
const { encryptedPayload } = soliton.Ratchet.encryptFirstMessage(
|
||||
ck, utf8("hello"), utf8("aad"),
|
||||
);
|
||||
expect(() =>
|
||||
soliton.Ratchet.decryptFirstMessage(randomBytes(32), encryptedPayload, utf8("aad")),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("full kex + ratchet", () => {
|
||||
it("complete session lifecycle", () => {
|
||||
const alice = new soliton.Identity();
|
||||
const bob = new soliton.Identity();
|
||||
const { publicKey: spkPub, secretKey: spkSk } = soliton.xwingKeygen();
|
||||
const spkSig = soliton.kexSignPrekey(bob.secretKey(), spkPub);
|
||||
|
||||
// Alice initiates.
|
||||
const initiated = soliton.kexInitiate(
|
||||
alice.publicKey(), alice.secretKey(),
|
||||
bob.publicKey(), spkPub, 1, spkSig, "lo-crypto-v1",
|
||||
);
|
||||
|
||||
// Bob receives.
|
||||
const siEncoded = initiated.sessionInitEncoded();
|
||||
const received = soliton.kexReceive(
|
||||
bob.publicKey(), bob.secretKey(), alice.publicKey(),
|
||||
siEncoded, initiated.senderSig(), spkSk,
|
||||
);
|
||||
|
||||
// First message.
|
||||
const aad = soliton.kexBuildFirstMessageAad(
|
||||
initiated.senderFingerprint(),
|
||||
initiated.recipientFingerprint(),
|
||||
siEncoded,
|
||||
);
|
||||
const { encryptedPayload, ratchetInitKey: rikA } =
|
||||
soliton.Ratchet.encryptFirstMessage(initiated.takeInitialChainKey(), utf8("hello bob"), aad);
|
||||
const { plaintext: firstPt, ratchetInitKey: rikB } =
|
||||
soliton.Ratchet.decryptFirstMessage(received.takeInitialChainKey(), encryptedPayload, aad);
|
||||
|
||||
expect(fromUtf8(firstPt)).toBe("hello bob");
|
||||
|
||||
// Init ratchets.
|
||||
const aliceR = soliton.Ratchet.initAlice(
|
||||
initiated.takeRootKey(), rikA,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peerEk(), initiated.ekSk(),
|
||||
);
|
||||
const bobR = soliton.Ratchet.initBob(
|
||||
received.takeRootKey(), rikB,
|
||||
bob.fingerprint(), alice.fingerprint(),
|
||||
received.peerEk(),
|
||||
);
|
||||
|
||||
// Alice sends to Bob.
|
||||
const { header, ciphertext } = aliceR.encrypt(utf8("message 1"));
|
||||
const pt1 = bobR.decrypt(header, ciphertext);
|
||||
expect(fromUtf8(pt1)).toBe("message 1");
|
||||
|
||||
// Bob replies (direction change).
|
||||
const { header: hdr2, ciphertext: ct2 } = bobR.encrypt(utf8("reply 1"));
|
||||
const pt2 = aliceR.decrypt(hdr2, ct2);
|
||||
expect(fromUtf8(pt2)).toBe("reply 1");
|
||||
|
||||
// Cleanup.
|
||||
aliceR.free();
|
||||
bobR.free();
|
||||
initiated.free();
|
||||
received.free();
|
||||
alice.free();
|
||||
bob.free();
|
||||
});
|
||||
|
||||
it("ratchet serialize/deserialize", () => {
|
||||
const alice = new soliton.Identity();
|
||||
const bob = new soliton.Identity();
|
||||
const { publicKey: spkPub, secretKey: spkSk } = soliton.xwingKeygen();
|
||||
const spkSig = soliton.kexSignPrekey(bob.secretKey(), spkPub);
|
||||
|
||||
const initiated = soliton.kexInitiate(
|
||||
alice.publicKey(), alice.secretKey(),
|
||||
bob.publicKey(), spkPub, 1, spkSig, "lo-crypto-v1",
|
||||
);
|
||||
const siEncoded = initiated.sessionInitEncoded();
|
||||
const received = soliton.kexReceive(
|
||||
bob.publicKey(), bob.secretKey(), alice.publicKey(),
|
||||
siEncoded, initiated.senderSig(), spkSk,
|
||||
);
|
||||
|
||||
const aad = soliton.kexBuildFirstMessageAad(
|
||||
initiated.senderFingerprint(), initiated.recipientFingerprint(), siEncoded,
|
||||
);
|
||||
const { ratchetInitKey: rik } =
|
||||
soliton.Ratchet.encryptFirstMessage(initiated.takeInitialChainKey(), utf8("x"), aad);
|
||||
|
||||
const aliceR = soliton.Ratchet.initAlice(
|
||||
initiated.takeRootKey(), rik,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peerEk(), initiated.ekSk(),
|
||||
);
|
||||
|
||||
aliceR.encrypt(utf8("advance state"));
|
||||
const { blob, epoch } = aliceR.toBytes();
|
||||
expect(blob.length).toBeGreaterThan(0);
|
||||
expect(epoch).toBeGreaterThanOrEqual(1n);
|
||||
|
||||
const restored = soliton.Ratchet.fromBytes(blob, 0n);
|
||||
const { ciphertext } = restored.encrypt(utf8("after restore"));
|
||||
expect(ciphertext.length).toBeGreaterThan(0);
|
||||
|
||||
restored.free();
|
||||
initiated.free();
|
||||
received.free();
|
||||
alice.free();
|
||||
bob.free();
|
||||
});
|
||||
|
||||
it("derive call keys", () => {
|
||||
const alice = new soliton.Identity();
|
||||
const bob = new soliton.Identity();
|
||||
const { publicKey: spkPub, secretKey: spkSk } = soliton.xwingKeygen();
|
||||
const spkSig = soliton.kexSignPrekey(bob.secretKey(), spkPub);
|
||||
|
||||
const initiated = soliton.kexInitiate(
|
||||
alice.publicKey(), alice.secretKey(),
|
||||
bob.publicKey(), spkPub, 1, spkSig, "lo-crypto-v1",
|
||||
);
|
||||
const siEncoded = initiated.sessionInitEncoded();
|
||||
const received = soliton.kexReceive(
|
||||
bob.publicKey(), bob.secretKey(), alice.publicKey(),
|
||||
siEncoded, initiated.senderSig(), spkSk,
|
||||
);
|
||||
|
||||
const aad = soliton.kexBuildFirstMessageAad(
|
||||
initiated.senderFingerprint(), initiated.recipientFingerprint(), siEncoded,
|
||||
);
|
||||
const { ratchetInitKey: rik } =
|
||||
soliton.Ratchet.encryptFirstMessage(initiated.takeInitialChainKey(), utf8("x"), aad);
|
||||
|
||||
const aliceR = soliton.Ratchet.initAlice(
|
||||
initiated.takeRootKey(), rik,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peerEk(), initiated.ekSk(),
|
||||
);
|
||||
|
||||
const kemSs = randomBytes(32);
|
||||
const callId = randomBytes(16);
|
||||
const keys = aliceR.deriveCallKeys(kemSs, callId);
|
||||
const send = keys.sendKey();
|
||||
const recv = keys.recvKey();
|
||||
expect(send.length).toBe(32);
|
||||
expect(recv.length).toBe(32);
|
||||
expect(bytesEqual(send, recv)).toBe(false);
|
||||
|
||||
keys.advance();
|
||||
const send2 = keys.sendKey();
|
||||
expect(bytesEqual(send, send2)).toBe(false);
|
||||
|
||||
keys.free();
|
||||
aliceR.free();
|
||||
initiated.free();
|
||||
received.free();
|
||||
alice.free();
|
||||
bob.free();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Additional Coverage ─────────────────────────────────────────────────
|
||||
|
||||
describe("additional", () => {
|
||||
it("hybridVerify standalone", () => {
|
||||
const id = new soliton.Identity();
|
||||
const msg = utf8("test");
|
||||
const sig = id.sign(msg);
|
||||
soliton.hybridVerify(id.publicKey(), msg, sig);
|
||||
expect(() => soliton.hybridVerify(id.publicKey(), utf8("wrong"), sig)).toThrow();
|
||||
id.free();
|
||||
});
|
||||
|
||||
it("storage removeKey", () => {
|
||||
const ring = new soliton.StorageKeyRing(1, randomBytes(32));
|
||||
ring.addKey(2, randomBytes(32), true);
|
||||
ring.removeKey(1);
|
||||
const blob = ring.encryptBlob("ch", "seg", utf8("data"));
|
||||
expect(fromUtf8(ring.decryptBlob("ch", "seg", blob))).toBe("data");
|
||||
ring.free();
|
||||
});
|
||||
|
||||
it("errors are Error instances", () => {
|
||||
try {
|
||||
soliton.authVerify(new Uint8Array(10), new Uint8Array(32));
|
||||
} catch (e) {
|
||||
expect(e instanceof Error).toBe(true);
|
||||
expect(typeof e.message).toBe("string");
|
||||
return;
|
||||
}
|
||||
expect.unreachable("should have thrown");
|
||||
});
|
||||
});
|
||||
14
soliton_wasm/vitest.browser.config.js
Normal file
14
soliton_wasm/vitest.browser.config.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { defineConfig } from "vitest/config";
|
||||
import wasm from "vite-plugin-wasm";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [wasm()],
|
||||
test: {
|
||||
include: ["tests/**/*.test.js"],
|
||||
browser: {
|
||||
enabled: true,
|
||||
provider: "playwright",
|
||||
instances: [{ browser: "chromium" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
9
soliton_wasm/vitest.config.js
Normal file
9
soliton_wasm/vitest.config.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { defineConfig } from "vitest/config";
|
||||
import wasm from "vite-plugin-wasm";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [wasm()],
|
||||
test: {
|
||||
include: ["tests/**/*.test.js"],
|
||||
},
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue