commit 0be6e9f2a65240d2f94af29161a251fcb65aa403
parent 341bd8c5557820682667791f84796ea6fa248aeb
Author: triesap <triesap@radroots.dev>
Date: Mon, 22 Dec 2025 15:49:54 +0000
merge: import client
Diffstat:
60 files changed, 4353 insertions(+), 0 deletions(-)
diff --git a/client/.gitignore b/client/.gitignore
@@ -0,0 +1,42 @@
+node_modules
+dist
+.turbo
+
+# Logs
+logs/
+*.log
+
+# Env
+.env
+.env.*
+!.env.example
+!.env.test
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Secrets
+*.pem
+*.crt
+*.key
+
+# Testing
+test*.json
+
+# Editors
+.vscode/
+.idea/
+*.iml
+
+# Notes
+notes*.txt
+notes*.md
+notes*.json
+tree*.txt
+diff*.txt
+prompt*.txt
+
+# Dev
+.local*
+justfile
+\ No newline at end of file
diff --git a/client/LICENSE b/client/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+\ No newline at end of file
diff --git a/client/package.json b/client/package.json
@@ -0,0 +1,96 @@
+{
+ "name": "@radroots/client",
+ "version": "0.0.1",
+ "private": true,
+ "license": "GPLv3",
+ "type": "module",
+ "exports": {
+ ".": {
+ "types": "./dist/types/index.d.ts",
+ "import": "./dist/esm/index.js",
+ "require": "./dist/cjs/index.js"
+ },
+ "./cipher": {
+ "types": "./dist/types/cipher/index.d.ts",
+ "import": "./dist/esm/cipher/index.js",
+ "require": "./dist/cjs/cipher/index.js"
+ },
+ "./crypto": {
+ "types": "./dist/types/crypto/index.d.ts",
+ "import": "./dist/esm/crypto/index.js",
+ "require": "./dist/cjs/crypto/index.js"
+ },
+ "./backup": {
+ "types": "./dist/types/backup/index.d.ts",
+ "import": "./dist/esm/backup/index.js",
+ "require": "./dist/cjs/backup/index.js"
+ },
+ "./datastore": {
+ "types": "./dist/types/datastore/index.d.ts",
+ "import": "./dist/esm/datastore/index.js",
+ "require": "./dist/cjs/datastore/index.js"
+ },
+ "./fs": {
+ "types": "./dist/types/fs/index.d.ts",
+ "import": "./dist/esm/fs/index.js",
+ "require": "./dist/cjs/fs/index.js"
+ },
+ "./geolocation": {
+ "types": "./dist/types/geolocation/index.d.ts",
+ "import": "./dist/esm/geolocation/index.js",
+ "require": "./dist/cjs/geolocation/index.js"
+ },
+ "./keystore": {
+ "types": "./dist/types/keystore/index.d.ts",
+ "import": "./dist/esm/keystore/index.js",
+ "require": "./dist/cjs/keystore/index.js"
+ },
+ "./notifications": {
+ "types": "./dist/types/notifications/index.d.ts",
+ "import": "./dist/esm/notifications/index.js",
+ "require": "./dist/cjs/notifications/index.js"
+ },
+ "./radroots": {
+ "types": "./dist/types/radroots/index.d.ts",
+ "import": "./dist/esm/radroots/index.js",
+ "require": "./dist/cjs/radroots/index.js"
+ },
+ "./sql": {
+ "types": "./dist/types/sql/index.d.ts",
+ "import": "./dist/esm/sql/index.js",
+ "require": "./dist/cjs/sql/index.js"
+ },
+ "./tangle": {
+ "types": "./dist/types/tangle/index.d.ts",
+ "import": "./dist/esm/tangle/index.js",
+ "require": "./dist/cjs/tangle/index.js"
+ }
+ },
+ "scripts": {
+ "build:esm": "tsc -p tsconfig.esm.json",
+ "build:cjs": "tsc -p tsconfig.cjs.json",
+ "build": "npm run clean && npm run build:esm && npm run build:cjs",
+ "prebuild": "npm run clean",
+ "clean": "rimraf dist",
+ "dev": "npm run watch",
+ "watch": "tsc -w"
+ },
+ "dependencies": {
+ "@radroots/geo": "*",
+ "@radroots/http": "*",
+ "@radroots/tangle-schema-bindings": "*",
+ "@radroots/tangle-sql-wasm": "*",
+ "@radroots/utils": "*",
+ "@radroots/utils-nostr": "*",
+ "idb": "^8.0.3",
+ "idb-keyval": "^6.2.1",
+ "sql.js": "1.13.0"
+ },
+ "devDependencies": {
+ "@types/debug": "^4.1.12",
+ "typescript": "^5.3.3"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/client/src/backup/codec.ts b/client/src/backup/codec.ts
@@ -0,0 +1,110 @@
+import { as_array_buffer } from "@radroots/utils";
+import { cl_backup_error } from "./error.js";
+import { crypto_kdf_derive_kek, crypto_kdf_iterations_default, crypto_kdf_salt_create } from "../crypto/kdf.js";
+import type { BackupBundle, BackupBundleEnvelope } from "./types.js";
+import type { KeyMaterialProvider } from "../crypto/types.js";
+
+const ensure_crypto = (): void => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_backup_error.crypto_undefined);
+};
+
+export const backup_bytes_to_b64 = (bytes: Uint8Array): string => {
+ if (typeof btoa === "undefined") throw new Error(cl_backup_error.encode_failure);
+ const chars: string[] = new Array(bytes.length);
+ for (let i = 0; i < bytes.length; i++) chars[i] = String.fromCharCode(bytes[i]);
+ return btoa(chars.join(""));
+};
+
+export const backup_b64_to_bytes = (value: string): Uint8Array => {
+ if (typeof atob === "undefined") throw new Error(cl_backup_error.decode_failure);
+ const binary = atob(value);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+};
+
+const is_record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const is_backup_bundle_envelope = (value: unknown): value is BackupBundleEnvelope => {
+ if (!is_record(value)) return false;
+ return typeof value.version === "number"
+ && typeof value.created_at === "number"
+ && typeof value.kdf_salt_b64 === "string"
+ && typeof value.kdf_iterations === "number"
+ && typeof value.iv_b64 === "string"
+ && typeof value.ciphertext_b64 === "string";
+};
+
+const is_backup_bundle = (value: unknown): value is BackupBundle => {
+ if (!is_record(value)) return false;
+ if (!is_record(value.manifest)) return false;
+ if (!Array.isArray(value.payloads)) return false;
+ return typeof value.manifest.version === "number"
+ && typeof value.manifest.created_at === "number"
+ && Array.isArray(value.manifest.stores);
+};
+
+export const backup_bundle_encode = async (bundle: BackupBundle, provider: KeyMaterialProvider): Promise<Uint8Array> => {
+ ensure_crypto();
+ try {
+ const json = JSON.stringify(bundle);
+ const plaintext = new TextEncoder().encode(json);
+ const salt = crypto_kdf_salt_create();
+ const iterations = crypto_kdf_iterations_default();
+ const material = await provider.get_key_material();
+ const kek = await crypto_kdf_derive_kek(material, salt, iterations);
+ material.fill(0);
+ const iv = new Uint8Array(12);
+ crypto.getRandomValues(iv);
+ const cipher_buf = await crypto.subtle.encrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(iv)
+ },
+ kek,
+ as_array_buffer(plaintext)
+ );
+ const envelope: BackupBundleEnvelope = {
+ version: 1,
+ created_at: Date.now(),
+ kdf_salt_b64: backup_bytes_to_b64(salt),
+ kdf_iterations: iterations,
+ iv_b64: backup_bytes_to_b64(iv),
+ ciphertext_b64: backup_bytes_to_b64(new Uint8Array(cipher_buf))
+ };
+ const encoded = JSON.stringify(envelope);
+ return new TextEncoder().encode(encoded);
+ } catch {
+ throw new Error(cl_backup_error.encode_failure);
+ }
+};
+
+export const backup_bundle_decode = async (blob: Uint8Array, provider: KeyMaterialProvider): Promise<BackupBundle> => {
+ ensure_crypto();
+ try {
+ const json = new TextDecoder().decode(blob);
+ const parsed = JSON.parse(json);
+ if (!is_backup_bundle_envelope(parsed)) throw new Error(cl_backup_error.invalid_bundle);
+ const salt = backup_b64_to_bytes(parsed.kdf_salt_b64);
+ const iv = backup_b64_to_bytes(parsed.iv_b64);
+ const ciphertext = backup_b64_to_bytes(parsed.ciphertext_b64);
+ const material = await provider.get_key_material();
+ const kek = await crypto_kdf_derive_kek(material, salt, parsed.kdf_iterations);
+ material.fill(0);
+ const plain_buf = await crypto.subtle.decrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(iv)
+ },
+ kek,
+ as_array_buffer(ciphertext)
+ );
+ const plaintext = new TextDecoder().decode(new Uint8Array(plain_buf));
+ const bundle_parsed = JSON.parse(plaintext);
+ if (!is_backup_bundle(bundle_parsed)) throw new Error(cl_backup_error.invalid_bundle);
+ return bundle_parsed;
+ } catch {
+ throw new Error(cl_backup_error.decode_failure);
+ }
+};
diff --git a/client/src/backup/error.ts b/client/src/backup/error.ts
@@ -0,0 +1,10 @@
+export const cl_backup_error = {
+ crypto_undefined: "error.client.backup.crypto_undefined",
+ invalid_bundle: "error.client.backup.invalid_bundle",
+ decode_failure: "error.client.backup.decode_failure",
+ encode_failure: "error.client.backup.encode_failure",
+ provider_missing: "error.client.backup.provider_missing"
+} as const;
+
+export type ClientBackupError = keyof typeof cl_backup_error;
+export type ClientBackupErrorMessage = (typeof cl_backup_error)[ClientBackupError];
diff --git a/client/src/backup/index.ts b/client/src/backup/index.ts
@@ -0,0 +1,136 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./codec.js";
+
+import { backup_bundle_decode, backup_bundle_encode } from "./codec.js";
+import type {
+ BackupBundle,
+ BackupBundlePayload,
+ BackupDatastoreStore,
+ BackupKeystoreStore,
+ BackupSqlStore
+} from "./types.js";
+import type { IWebCryptoService, KeyMaterialProvider } from "../crypto/types.js";
+import { DeviceKeyMaterialProvider } from "../crypto/provider.js";
+import { handle_err, type ResolveError } from "@radroots/utils";
+import type { IError } from "@radroots/types-bindings";
+
+export type BackupBundleBuildOpts = {
+ sql_store?: BackupSqlStore;
+ keystore_store?: BackupKeystoreStore;
+ datastore_store?: BackupDatastoreStore;
+ app_version?: string;
+ crypto_service?: IWebCryptoService;
+ key_material_provider?: KeyMaterialProvider;
+};
+
+export type BackupBundleImportOpts = {
+ sql_store?: BackupSqlStore;
+ keystore_store?: BackupKeystoreStore;
+ datastore_store?: BackupDatastoreStore;
+ crypto_service?: IWebCryptoService;
+ key_material_provider?: KeyMaterialProvider;
+ import_registry?: boolean;
+};
+
+const is_error = <T>(value: ResolveError<T>): value is IError<string> => {
+ return typeof value === "object" && value !== null && "err" in value;
+};
+
+const collect_payloads = async (opts: BackupBundleBuildOpts): Promise<ResolveError<BackupBundlePayload[]>> => {
+ const payloads: BackupBundlePayload[] = [];
+ if (opts.sql_store) {
+ const data = await opts.sql_store.export_backup();
+ if (is_error(data)) return data;
+ payloads.push({
+ store_id: opts.sql_store.get_store_id(),
+ store_type: "sql",
+ data
+ });
+ }
+ if (opts.keystore_store) {
+ const data = await opts.keystore_store.export_backup();
+ if (is_error(data)) return data;
+ payloads.push({
+ store_id: opts.keystore_store.get_store_id(),
+ store_type: "keystore",
+ data
+ });
+ }
+ if (opts.datastore_store) {
+ const data = await opts.datastore_store.export_backup();
+ if (is_error(data)) return data;
+ payloads.push({
+ store_id: opts.datastore_store.get_store_id(),
+ store_type: "datastore",
+ data
+ });
+ }
+ return payloads;
+};
+
+export const backup_bundle_build = async (opts: BackupBundleBuildOpts): Promise<ResolveError<BackupBundle>> => {
+ const payloads = await collect_payloads(opts);
+ if (is_error(payloads)) return payloads;
+ const stores = payloads.map((payload) => ({
+ store_id: payload.store_id,
+ store_type: payload.store_type
+ }));
+ const crypto_registry = opts.crypto_service
+ ? await opts.crypto_service.export_registry()
+ : { stores: [], keys: [] };
+ return {
+ manifest: {
+ version: 1,
+ created_at: Date.now(),
+ app_version: opts.app_version,
+ stores,
+ crypto_registry
+ },
+ payloads
+ };
+};
+
+export const backup_bundle_export = async (opts: BackupBundleBuildOpts): Promise<ResolveError<Uint8Array>> => {
+ try {
+ const provider = opts.key_material_provider ?? new DeviceKeyMaterialProvider();
+ const bundle = await backup_bundle_build(opts);
+ if (is_error(bundle)) return bundle;
+ return await backup_bundle_encode(bundle, provider);
+ } catch (e) {
+ return handle_err(e);
+ }
+};
+
+export const backup_bundle_import = async (blob: Uint8Array, opts: BackupBundleImportOpts): Promise<ResolveError<BackupBundle>> => {
+ try {
+ const provider = opts.key_material_provider ?? new DeviceKeyMaterialProvider();
+ const bundle = await backup_bundle_decode(blob, provider);
+ if (opts.import_registry && opts.crypto_service) {
+ await opts.crypto_service.import_registry(bundle.manifest.crypto_registry);
+ }
+ for (const payload of bundle.payloads) {
+ if (payload.store_type === "sql" && opts.sql_store) {
+ if (opts.sql_store.get_store_id() === payload.store_id) {
+ const res = await opts.sql_store.import_backup(payload.data);
+ if (is_error(res)) return res;
+ }
+ }
+ if (payload.store_type === "keystore" && opts.keystore_store) {
+ if (opts.keystore_store.get_store_id() === payload.store_id) {
+ const res = await opts.keystore_store.import_backup(payload.data);
+ if (is_error(res)) return res;
+ }
+ }
+ if (payload.store_type === "datastore" && opts.datastore_store) {
+ if (opts.datastore_store.get_store_id() === payload.store_id) {
+ const res = await opts.datastore_store.import_backup(payload.data);
+ if (is_error(res)) return res;
+ }
+ }
+ }
+ return bundle;
+ } catch (e) {
+ return handle_err(e);
+ }
+};
diff --git a/client/src/backup/types.ts b/client/src/backup/types.ts
@@ -0,0 +1,85 @@
+import type { ResolveError } from "@radroots/utils";
+import type { CryptoRegistryExport } from "../crypto/types.js";
+
+export type BackupBundleVersion = 1;
+
+export type BackupBundleStoreType = "sql" | "keystore" | "datastore";
+
+export type BackupSqlPayload = {
+ bytes_b64: string;
+};
+
+export type BackupKeystoreEntry = {
+ key: string;
+ value: string;
+};
+
+export type BackupKeystorePayload = {
+ entries: BackupKeystoreEntry[];
+};
+
+export type BackupDatastoreEntry = {
+ key: string;
+ value: string;
+};
+
+export type BackupDatastorePayload = {
+ entries: BackupDatastoreEntry[];
+};
+
+export type BackupBundlePayload =
+ | {
+ store_id: string;
+ store_type: "sql";
+ data: BackupSqlPayload;
+ }
+ | {
+ store_id: string;
+ store_type: "keystore";
+ data: BackupKeystorePayload;
+ }
+ | {
+ store_id: string;
+ store_type: "datastore";
+ data: BackupDatastorePayload;
+ };
+
+export type BackupBundleManifest = {
+ version: BackupBundleVersion;
+ created_at: number;
+ app_version?: string;
+ stores: { store_id: string; store_type: BackupBundleStoreType; }[];
+ crypto_registry: CryptoRegistryExport;
+};
+
+export type BackupBundle = {
+ manifest: BackupBundleManifest;
+ payloads: BackupBundlePayload[];
+};
+
+export type BackupBundleEnvelope = {
+ version: number;
+ created_at: number;
+ kdf_salt_b64: string;
+ kdf_iterations: number;
+ iv_b64: string;
+ ciphertext_b64: string;
+};
+
+export interface BackupSqlStore {
+ export_backup(): Promise<ResolveError<BackupSqlPayload>>;
+ import_backup(payload: BackupSqlPayload): Promise<ResolveError<void>>;
+ get_store_id(): string;
+}
+
+export interface BackupKeystoreStore {
+ export_backup(): Promise<ResolveError<BackupKeystorePayload>>;
+ import_backup(payload: BackupKeystorePayload): Promise<ResolveError<void>>;
+ get_store_id(): string;
+}
+
+export interface BackupDatastoreStore {
+ export_backup(): Promise<ResolveError<BackupDatastorePayload>>;
+ import_backup(payload: BackupDatastorePayload): Promise<ResolveError<void>>;
+ get_store_id(): string;
+}
diff --git a/client/src/cipher/error.ts b/client/src/cipher/error.ts
@@ -0,0 +1,9 @@
+export const cl_cipher_error = {
+ idb_undefined: "error.client.cipher.idb_undefined",
+ crypto_undefined: "error.client.cipher.crypto_undefined",
+ invalid_ciphertext: "error.client.cipher.invalid_ciphertext",
+ decrypt_failure: "error.client.cipher.decrypt_failure"
+} as const;
+
+export type ClientCipherError = keyof typeof cl_cipher_error;
+export type ClientCipherErrorMessage = (typeof cl_cipher_error)[ClientCipherError];
+\ No newline at end of file
diff --git a/client/src/cipher/index.ts b/client/src/cipher/index.ts
@@ -0,0 +1,4 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
+
diff --git a/client/src/cipher/types.ts b/client/src/cipher/types.ts
@@ -0,0 +1,8 @@
+import { type IdbClientConfig } from "@radroots/utils";
+
+export interface IClientCipher {
+ get_config(): IdbClientConfig;
+ reset(): Promise<void>;
+ encrypt(data: Uint8Array): Promise<Uint8Array>;
+ decrypt(blob: Uint8Array): Promise<Uint8Array>;
+}
diff --git a/client/src/cipher/web.ts b/client/src/cipher/web.ts
@@ -0,0 +1,90 @@
+import { type IdbClientConfig } from "@radroots/utils";
+import { createStore, del as idb_del, type UseStore } from "idb-keyval";
+import type { WebAesGcmCipherConfig } from "../keystore/web.js";
+import { crypto_registry_clear_key_entry, crypto_registry_clear_store_index, crypto_registry_get_store_index } from "../crypto/registry.js";
+import { WebCryptoService } from "../crypto/service.js";
+import type { LegacyKeyConfig } from "../crypto/types.js";
+import { IDB_CONFIG_CIPHER_AES_GCM } from "../idb/config.js";
+import { cl_cipher_error } from "./error.js";
+import type { IClientCipher } from "./types.js";
+
+const DEFAULT_IDB_CONFIG: IdbClientConfig = IDB_CONFIG_CIPHER_AES_GCM;
+
+const DEFAULT_WEB_AES_GCM_CONFIG = {
+ key_name: "radroots.aes-gcm.key",
+ algorithm: "AES-GCM",
+ key_length: 256,
+ iv_length: 12
+} as const;
+
+export interface IWebAesGcmCipher extends IClientCipher { }
+
+export class WebAesGcmCipher implements IWebAesGcmCipher {
+ private readonly db_name: string;
+ private readonly store_name: string;
+ private readonly key_name: string;
+ private readonly algorithm_name: string;
+ private readonly iv_length: number;
+ private readonly legacy_store: UseStore;
+ private readonly store_id: string;
+ private readonly crypto: WebCryptoService;
+ private readonly legacy_key_config: LegacyKeyConfig;
+
+ constructor(config?: WebAesGcmCipherConfig) {
+ const idb_config = config?.idb_config ?? {};
+ this.db_name = idb_config.database ?? DEFAULT_IDB_CONFIG.database;
+ this.store_name = idb_config.store ?? DEFAULT_IDB_CONFIG.store;
+ this.key_name = config?.key_name ?? DEFAULT_WEB_AES_GCM_CONFIG.key_name;
+ this.algorithm_name = config?.algorithm ?? DEFAULT_WEB_AES_GCM_CONFIG.algorithm;
+ this.iv_length = Number.isInteger(config?.iv_length) && (config?.iv_length ?? 0) > 0
+ ? config?.iv_length ?? DEFAULT_WEB_AES_GCM_CONFIG.iv_length
+ : DEFAULT_WEB_AES_GCM_CONFIG.iv_length;
+
+ if (typeof indexedDB === "undefined") throw new Error(cl_cipher_error.idb_undefined);
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_cipher_error.crypto_undefined);
+
+ this.legacy_store = createStore(this.db_name, this.store_name);
+ this.store_id = this.key_name;
+ this.crypto = new WebCryptoService();
+ this.legacy_key_config = {
+ idb_config: {
+ database: this.db_name,
+ store: this.store_name
+ },
+ key_name: this.key_name,
+ iv_length: this.iv_length,
+ algorithm: this.algorithm_name
+ };
+ this.crypto.register_store_config({
+ store_id: this.store_id,
+ legacy_key: this.legacy_key_config,
+ iv_length: this.iv_length
+ });
+ }
+
+ public get_config(): IdbClientConfig {
+ return {
+ database: this.db_name,
+ store: this.store_name
+ };
+ }
+
+ public async reset(): Promise<void> {
+ const index = await crypto_registry_get_store_index(this.store_id);
+ if (index) {
+ await crypto_registry_clear_store_index(this.store_id);
+ for (const key_id of index.key_ids) await crypto_registry_clear_key_entry(key_id);
+ }
+ await idb_del(this.key_name, this.legacy_store);
+ }
+
+ public async encrypt(data: Uint8Array): Promise<Uint8Array> {
+ return await this.crypto.encrypt(this.store_id, data);
+ }
+
+ public async decrypt(blob: Uint8Array): Promise<Uint8Array> {
+ if (blob.byteLength <= this.iv_length) throw new Error(cl_cipher_error.invalid_ciphertext);
+ const outcome = await this.crypto.decrypt_record(this.store_id, blob);
+ return outcome.plaintext;
+ }
+}
diff --git a/client/src/crypto/envelope.ts b/client/src/crypto/envelope.ts
@@ -0,0 +1,72 @@
+import { cl_crypto_error } from "./error.js";
+import type { CryptoEnvelope } from "./types.js";
+
+const ENVELOPE_MAGIC = new Uint8Array([0x52, 0x52, 0x43, 0x45]);
+const ENVELOPE_VERSION = 1;
+const ENVELOPE_HEADER_LENGTH = 4 + 1 + 1 + 1 + 8;
+
+const bytes_equal = (left: Uint8Array, right: Uint8Array): boolean => {
+ if (left.length !== right.length) return false;
+ for (let i = 0; i < left.length; i++) if (left[i] !== right[i]) return false;
+ return true;
+};
+
+export const crypto_envelope_encode = (envelope: CryptoEnvelope): Uint8Array => {
+ const encoder = new TextEncoder();
+ const key_bytes = encoder.encode(envelope.key_id);
+ if (key_bytes.length > 255) throw new Error(cl_crypto_error.invalid_key_id);
+ const total_len = ENVELOPE_HEADER_LENGTH + key_bytes.length + envelope.iv.length + envelope.ciphertext.length;
+ const out = new Uint8Array(total_len);
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
+ let offset = 0;
+ out.set(ENVELOPE_MAGIC, offset);
+ offset += ENVELOPE_MAGIC.length;
+ out[offset] = ENVELOPE_VERSION;
+ offset += 1;
+ out[offset] = key_bytes.length;
+ offset += 1;
+ out[offset] = envelope.iv.length;
+ offset += 1;
+ view.setBigUint64(offset, BigInt(envelope.created_at), false);
+ offset += 8;
+ out.set(key_bytes, offset);
+ offset += key_bytes.length;
+ out.set(envelope.iv, offset);
+ offset += envelope.iv.length;
+ out.set(envelope.ciphertext, offset);
+ return out;
+};
+
+export const crypto_envelope_decode = (blob: Uint8Array): CryptoEnvelope | null => {
+ if (blob.byteLength < ENVELOPE_HEADER_LENGTH) return null;
+ const magic = blob.slice(0, ENVELOPE_MAGIC.length);
+ if (!bytes_equal(magic, ENVELOPE_MAGIC)) return null;
+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
+ let offset = ENVELOPE_MAGIC.length;
+ const version = view.getUint8(offset);
+ offset += 1;
+ if (version !== ENVELOPE_VERSION) throw new Error(cl_crypto_error.invalid_envelope);
+ const key_len = view.getUint8(offset);
+ offset += 1;
+ const iv_len = view.getUint8(offset);
+ offset += 1;
+ const created_at = Number(view.getBigUint64(offset, false));
+ offset += 8;
+ const remaining = blob.byteLength - offset;
+ if (remaining < key_len + iv_len + 1) throw new Error(cl_crypto_error.invalid_envelope);
+ const key_bytes = blob.slice(offset, offset + key_len);
+ offset += key_len;
+ const iv = blob.slice(offset, offset + iv_len);
+ offset += iv_len;
+ const ciphertext = blob.slice(offset);
+ const decoder = new TextDecoder();
+ const key_id = decoder.decode(key_bytes);
+ if (!key_id) throw new Error(cl_crypto_error.invalid_key_id);
+ return {
+ version,
+ key_id,
+ iv,
+ created_at,
+ ciphertext
+ };
+};
diff --git a/client/src/crypto/error.ts b/client/src/crypto/error.ts
@@ -0,0 +1,17 @@
+export const cl_crypto_error = {
+ idb_undefined: "error.client.crypto.idb_undefined",
+ crypto_undefined: "error.client.crypto.crypto_undefined",
+ invalid_envelope: "error.client.crypto.invalid_envelope",
+ invalid_key_id: "error.client.crypto.invalid_key_id",
+ key_not_found: "error.client.crypto.key_not_found",
+ unwrap_failure: "error.client.crypto.unwrap_failure",
+ wrap_failure: "error.client.crypto.wrap_failure",
+ legacy_key_missing: "error.client.crypto.legacy_key_missing",
+ encrypt_failure: "error.client.crypto.encrypt_failure",
+ decrypt_failure: "error.client.crypto.decrypt_failure",
+ kdf_failure: "error.client.crypto.kdf_failure",
+ registry_failure: "error.client.crypto.registry_failure"
+} as const;
+
+export type ClientCryptoError = keyof typeof cl_crypto_error;
+export type ClientCryptoErrorMessage = (typeof cl_crypto_error)[ClientCryptoError];
diff --git a/client/src/crypto/index.ts b/client/src/crypto/index.ts
@@ -0,0 +1,8 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./envelope.js";
+export * from "./kdf.js";
+export * from "./keys.js";
+export * from "./registry.js";
+export * from "./provider.js";
+export * from "./service.js";
diff --git a/client/src/crypto/kdf.ts b/client/src/crypto/kdf.ts
@@ -0,0 +1,43 @@
+import { cl_crypto_error } from "./error.js";
+
+const DEFAULT_KDF_ITERATIONS = 210000;
+const KDF_HASH = "SHA-256";
+
+export const crypto_kdf_iterations_default = (): number => DEFAULT_KDF_ITERATIONS;
+
+export const crypto_kdf_salt_create = (length: number = 16): Uint8Array => {
+ if (!globalThis.crypto) throw new Error(cl_crypto_error.crypto_undefined);
+ const salt = new Uint8Array(length);
+ crypto.getRandomValues(salt);
+ return salt;
+};
+
+export const crypto_kdf_derive_kek = async (
+ material: Uint8Array,
+ salt: Uint8Array,
+ iterations: number
+): Promise<CryptoKey> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ try {
+ const material_bytes = new Uint8Array(material);
+ const salt_bytes = new Uint8Array(salt);
+ const base_key = await crypto.subtle.importKey("raw", material_bytes, "PBKDF2", false, ["deriveKey"]);
+ return await crypto.subtle.deriveKey(
+ {
+ name: "PBKDF2",
+ salt: salt_bytes,
+ iterations,
+ hash: KDF_HASH
+ },
+ base_key,
+ {
+ name: "AES-GCM",
+ length: 256
+ },
+ false,
+ ["encrypt", "decrypt"]
+ );
+ } catch {
+ throw new Error(cl_crypto_error.kdf_failure);
+ }
+};
diff --git a/client/src/crypto/keys.ts b/client/src/crypto/keys.ts
@@ -0,0 +1,95 @@
+import { as_array_buffer } from "@radroots/utils";
+import { cl_crypto_error } from "./error.js";
+
+const KEY_ID_BYTES_LENGTH = 16;
+const WRAP_IV_LENGTH = 12;
+
+const bytes_to_hex = (bytes: Uint8Array): string => {
+ let out = "";
+ for (let i = 0; i < bytes.length; i++) {
+ const part = bytes[i].toString(16).padStart(2, "0");
+ out += part;
+ }
+ return out;
+};
+
+export const crypto_key_id_create = (): string => {
+ if (!globalThis.crypto) throw new Error(cl_crypto_error.crypto_undefined);
+ const bytes = new Uint8Array(KEY_ID_BYTES_LENGTH);
+ crypto.getRandomValues(bytes);
+ return bytes_to_hex(bytes);
+};
+
+export const crypto_key_generate = async (): Promise<CryptoKey> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ return await crypto.subtle.generateKey(
+ {
+ name: "AES-GCM",
+ length: 256
+ },
+ true,
+ ["encrypt", "decrypt"]
+ );
+};
+
+export const crypto_key_export_raw = async (key: CryptoKey): Promise<Uint8Array> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ const raw = await crypto.subtle.exportKey("raw", key);
+ return new Uint8Array(raw);
+};
+
+export const crypto_key_import_raw = async (raw: Uint8Array): Promise<CryptoKey> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ return await crypto.subtle.importKey(
+ "raw",
+ as_array_buffer(raw),
+ "AES-GCM",
+ false,
+ ["encrypt", "decrypt"]
+ );
+};
+
+export const crypto_key_wrap = async (
+ kek: CryptoKey,
+ raw_key: Uint8Array
+): Promise<{ wrapped_key: Uint8Array; wrap_iv: Uint8Array; }> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ try {
+ const wrap_iv = new Uint8Array(WRAP_IV_LENGTH);
+ crypto.getRandomValues(wrap_iv);
+ const cipher_buf = await crypto.subtle.encrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(wrap_iv)
+ },
+ kek,
+ as_array_buffer(raw_key)
+ );
+ const wrapped_key = new Uint8Array(cipher_buf);
+ raw_key.fill(0);
+ return { wrapped_key, wrap_iv };
+ } catch {
+ throw new Error(cl_crypto_error.wrap_failure);
+ }
+};
+
+export const crypto_key_unwrap = async (
+ kek: CryptoKey,
+ wrapped_key: Uint8Array,
+ wrap_iv: Uint8Array
+): Promise<CryptoKey> => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+ try {
+ const raw = await crypto.subtle.decrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(wrap_iv)
+ },
+ kek,
+ as_array_buffer(wrapped_key)
+ );
+ return await crypto_key_import_raw(new Uint8Array(raw));
+ } catch {
+ throw new Error(cl_crypto_error.unwrap_failure);
+ }
+};
diff --git a/client/src/crypto/provider.ts b/client/src/crypto/provider.ts
@@ -0,0 +1,24 @@
+import { cl_crypto_error } from "./error.js";
+import type { KeyMaterialProvider } from "./types.js";
+import { crypto_registry_get_device_material, crypto_registry_set_device_material } from "./registry.js";
+
+const DEVICE_PROVIDER_ID = "device";
+const DEVICE_MATERIAL_BYTES = 32;
+
+export interface IDeviceKeyMaterialProvider extends KeyMaterialProvider { }
+
+export class DeviceKeyMaterialProvider implements IDeviceKeyMaterialProvider {
+ public async get_key_material(): Promise<Uint8Array> {
+ if (!globalThis.crypto) throw new Error(cl_crypto_error.crypto_undefined);
+ const existing = await crypto_registry_get_device_material();
+ if (existing) return new Uint8Array(existing);
+ const material = new Uint8Array(DEVICE_MATERIAL_BYTES);
+ crypto.getRandomValues(material);
+ await crypto_registry_set_device_material(material);
+ return new Uint8Array(material);
+ }
+
+ public async get_provider_id(): Promise<string> {
+ return DEVICE_PROVIDER_ID;
+ }
+}
diff --git a/client/src/crypto/registry.ts b/client/src/crypto/registry.ts
@@ -0,0 +1,139 @@
+import { createStore, del as idb_del, get as idb_get, keys as idb_keys, set as idb_set } from "idb-keyval";
+import type { IdbClientConfig } from "@radroots/utils";
+import { IDB_CONFIG_CRYPTO_REGISTRY } from "../idb/config.js";
+import { cl_crypto_error } from "./error.js";
+import type { CryptoKeyEntry, CryptoRegistryExport, CryptoStoreIndex } from "./types.js";
+
+const CRYPTO_IDB_CONFIG: IdbClientConfig = IDB_CONFIG_CRYPTO_REGISTRY;
+
+const CRYPTO_STORE = createStore(CRYPTO_IDB_CONFIG.database, CRYPTO_IDB_CONFIG.store);
+const STORE_INDEX_PREFIX = "store:";
+const KEY_ENTRY_PREFIX = "key:";
+const DEVICE_MATERIAL_KEY = "device:material";
+
+const ensure_idb = (): void => {
+ if (typeof indexedDB === "undefined") throw new Error(cl_crypto_error.idb_undefined);
+};
+
+const store_index_key = (store_id: string): string => `${STORE_INDEX_PREFIX}${store_id}`;
+const key_entry_key = (key_id: string): string => `${KEY_ENTRY_PREFIX}${key_id}`;
+
+const is_string_array = (value: unknown): value is string[] =>
+ Array.isArray(value) && value.every((item) => typeof item === "string");
+
+const is_record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const is_crypto_store_index = (value: unknown): value is CryptoStoreIndex => {
+ if (!is_record(value)) return false;
+ return typeof value.store_id === "string"
+ && typeof value.active_key_id === "string"
+ && typeof value.created_at === "number"
+ && is_string_array(value.key_ids);
+};
+
+const is_crypto_key_entry = (value: unknown): value is CryptoKeyEntry => {
+ if (!is_record(value)) return false;
+ return typeof value.key_id === "string"
+ && typeof value.store_id === "string"
+ && typeof value.created_at === "number"
+ && typeof value.status === "string"
+ && value.wrapped_key instanceof Uint8Array
+ && value.wrap_iv instanceof Uint8Array
+ && value.kdf_salt instanceof Uint8Array
+ && typeof value.kdf_iterations === "number"
+ && typeof value.iv_length === "number"
+ && typeof value.algorithm === "string"
+ && typeof value.provider_id === "string";
+};
+
+export const crypto_registry_get_store_index = async (store_id: string): Promise<CryptoStoreIndex | null> => {
+ ensure_idb();
+ const record = await idb_get(store_index_key(store_id), CRYPTO_STORE);
+ if (!record) return null;
+ if (!is_crypto_store_index(record)) throw new Error(cl_crypto_error.registry_failure);
+ return record;
+};
+
+export const crypto_registry_set_store_index = async (index: CryptoStoreIndex): Promise<void> => {
+ ensure_idb();
+ await idb_set(store_index_key(index.store_id), index, CRYPTO_STORE);
+};
+
+export const crypto_registry_get_key_entry = async (key_id: string): Promise<CryptoKeyEntry | null> => {
+ ensure_idb();
+ const record = await idb_get(key_entry_key(key_id), CRYPTO_STORE);
+ if (!record) return null;
+ if (!is_crypto_key_entry(record)) throw new Error(cl_crypto_error.registry_failure);
+ return record;
+};
+
+export const crypto_registry_set_key_entry = async (entry: CryptoKeyEntry): Promise<void> => {
+ ensure_idb();
+ await idb_set(key_entry_key(entry.key_id), entry, CRYPTO_STORE);
+};
+
+export const crypto_registry_list_store_indices = async (): Promise<CryptoStoreIndex[]> => {
+ ensure_idb();
+ const keys = await idb_keys(CRYPTO_STORE);
+ const store_keys = keys.filter((key): key is string => typeof key === "string" && key.startsWith(STORE_INDEX_PREFIX));
+ const out: CryptoStoreIndex[] = [];
+ for (const key of store_keys) {
+ const record = await idb_get(key, CRYPTO_STORE);
+ if (!record) continue;
+ if (!is_crypto_store_index(record)) throw new Error(cl_crypto_error.registry_failure);
+ out.push(record);
+ }
+ return out;
+};
+
+export const crypto_registry_list_key_entries = async (): Promise<CryptoKeyEntry[]> => {
+ ensure_idb();
+ const keys = await idb_keys(CRYPTO_STORE);
+ const entry_keys = keys.filter((key): key is string => typeof key === "string" && key.startsWith(KEY_ENTRY_PREFIX));
+ const out: CryptoKeyEntry[] = [];
+ for (const key of entry_keys) {
+ const record = await idb_get(key, CRYPTO_STORE);
+ if (!record) continue;
+ if (!is_crypto_key_entry(record)) throw new Error(cl_crypto_error.registry_failure);
+ out.push(record);
+ }
+ return out;
+};
+
+export const crypto_registry_export = async (): Promise<CryptoRegistryExport> => {
+ const stores = await crypto_registry_list_store_indices();
+ const keys = await crypto_registry_list_key_entries();
+ return { stores, keys };
+};
+
+export const crypto_registry_import = async (registry: CryptoRegistryExport): Promise<void> => {
+ ensure_idb();
+ for (const store of registry.stores) await crypto_registry_set_store_index(store);
+ for (const entry of registry.keys) await crypto_registry_set_key_entry(entry);
+};
+
+export const crypto_registry_get_device_material = async (): Promise<Uint8Array | null> => {
+ ensure_idb();
+ const record = await idb_get(DEVICE_MATERIAL_KEY, CRYPTO_STORE);
+ if (!record) return null;
+ if (record instanceof Uint8Array) return record;
+ if (record instanceof ArrayBuffer) return new Uint8Array(record);
+ if (ArrayBuffer.isView(record)) return new Uint8Array(record.buffer, record.byteOffset, record.byteLength);
+ throw new Error(cl_crypto_error.registry_failure);
+};
+
+export const crypto_registry_set_device_material = async (material: Uint8Array): Promise<void> => {
+ ensure_idb();
+ await idb_set(DEVICE_MATERIAL_KEY, material, CRYPTO_STORE);
+};
+
+export const crypto_registry_clear_store_index = async (store_id: string): Promise<void> => {
+ ensure_idb();
+ await idb_del(store_index_key(store_id), CRYPTO_STORE);
+};
+
+export const crypto_registry_clear_key_entry = async (key_id: string): Promise<void> => {
+ ensure_idb();
+ await idb_del(key_entry_key(key_id), CRYPTO_STORE);
+};
diff --git a/client/src/crypto/service.ts b/client/src/crypto/service.ts
@@ -0,0 +1,279 @@
+import { createStore, get as idb_get } from "idb-keyval";
+import { as_array_buffer } from "@radroots/utils";
+import { cl_crypto_error } from "./error.js";
+import { crypto_envelope_decode, crypto_envelope_encode } from "./envelope.js";
+import { crypto_kdf_derive_kek, crypto_kdf_iterations_default, crypto_kdf_salt_create } from "./kdf.js";
+import { crypto_key_export_raw, crypto_key_generate, crypto_key_id_create, crypto_key_import_raw, crypto_key_unwrap, crypto_key_wrap } from "./keys.js";
+import { crypto_registry_export, crypto_registry_get_key_entry, crypto_registry_get_store_index, crypto_registry_import, crypto_registry_set_key_entry, crypto_registry_set_store_index } from "./registry.js";
+import { DeviceKeyMaterialProvider } from "./provider.js";
+import type { CryptoDecryptOutcome, CryptoKeyEntry, CryptoRegistryExport, CryptoStoreConfig, CryptoStoreIndex, IWebCryptoService, KeyMaterialProvider, LegacyKeyConfig } from "./types.js";
+
+const DEFAULT_IV_LENGTH = 12;
+
+const ensure_crypto = (): void => {
+ if (!globalThis.crypto || !globalThis.crypto.subtle) throw new Error(cl_crypto_error.crypto_undefined);
+};
+
+const merge_key_ids = (key_ids: string[], next_key_id: string): string[] => {
+ if (key_ids.includes(next_key_id)) return key_ids;
+ return [...key_ids, next_key_id];
+};
+
+const bytes_from_value = (value: ArrayBuffer | ArrayBufferView): Uint8Array => {
+ if (value instanceof Uint8Array) return value;
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ return new Uint8Array(value);
+};
+
+export class WebCryptoService implements IWebCryptoService {
+ private store_configs: Map<string, CryptoStoreConfig>;
+ private key_material_provider: KeyMaterialProvider;
+
+ constructor(config?: { key_material_provider?: KeyMaterialProvider }) {
+ this.store_configs = new Map();
+ this.key_material_provider = config?.key_material_provider ?? new DeviceKeyMaterialProvider();
+ ensure_crypto();
+ }
+
+ public register_store_config(config: CryptoStoreConfig): void {
+ const existing = this.store_configs.get(config.store_id);
+ if (existing) {
+ this.store_configs.set(config.store_id, {
+ store_id: config.store_id,
+ iv_length: config.iv_length ?? existing.iv_length,
+ legacy_key: config.legacy_key ?? existing.legacy_key
+ });
+ return;
+ }
+ this.store_configs.set(config.store_id, {
+ store_id: config.store_id,
+ iv_length: config.iv_length ?? DEFAULT_IV_LENGTH,
+ legacy_key: config.legacy_key
+ });
+ }
+
+ public async encrypt(store_id: string, plaintext: Uint8Array): Promise<Uint8Array> {
+ ensure_crypto();
+ const { key, entry } = await this.resolve_active_key(store_id);
+ const iv_length = entry.iv_length || DEFAULT_IV_LENGTH;
+ const iv = new Uint8Array(iv_length);
+ crypto.getRandomValues(iv);
+ try {
+ const cipher_buf = await crypto.subtle.encrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(iv)
+ },
+ key,
+ as_array_buffer(plaintext)
+ );
+ const envelope = {
+ version: 1,
+ key_id: entry.key_id,
+ iv,
+ created_at: Date.now(),
+ ciphertext: new Uint8Array(cipher_buf)
+ };
+ return crypto_envelope_encode(envelope);
+ } catch {
+ throw new Error(cl_crypto_error.encrypt_failure);
+ }
+ }
+
+ public async decrypt(store_id: string, blob: Uint8Array): Promise<Uint8Array> {
+ const outcome = await this.decrypt_record(store_id, blob);
+ return outcome.plaintext;
+ }
+
+ public async decrypt_record(store_id: string, blob: Uint8Array): Promise<CryptoDecryptOutcome> {
+ ensure_crypto();
+ const config = this.resolve_store_config(store_id);
+ const envelope = crypto_envelope_decode(blob);
+ if (envelope) return await this.decrypt_envelope(store_id, envelope);
+ return await this.decrypt_legacy(store_id, blob, config.legacy_key, config.iv_length ?? DEFAULT_IV_LENGTH);
+ }
+
+ public async rotate_store_key(store_id: string): Promise<string> {
+ const config = this.resolve_store_config(store_id);
+ const index = await crypto_registry_get_store_index(store_id);
+ if (!index) {
+ const created = await this.create_store_key(store_id, config);
+ return created.entry.key_id;
+ }
+ const prev_entry = await crypto_registry_get_key_entry(index.active_key_id);
+ if (prev_entry) {
+ const rotated_entry: CryptoKeyEntry = {
+ ...prev_entry,
+ status: "rotated"
+ };
+ await crypto_registry_set_key_entry(rotated_entry);
+ }
+ const created = await this.create_key_entry(store_id, config);
+ const next_index: CryptoStoreIndex = {
+ ...index,
+ active_key_id: created.entry.key_id,
+ key_ids: merge_key_ids(index.key_ids, created.entry.key_id)
+ };
+ await crypto_registry_set_store_index(next_index);
+ return created.entry.key_id;
+ }
+
+ public async export_registry(): Promise<CryptoRegistryExport> {
+ return await crypto_registry_export();
+ }
+
+ public async import_registry(registry: CryptoRegistryExport): Promise<void> {
+ await crypto_registry_import(registry);
+ }
+
+ private resolve_store_config(store_id: string): CryptoStoreConfig {
+ const existing = this.store_configs.get(store_id);
+ if (existing) return existing;
+ const config = {
+ store_id,
+ iv_length: DEFAULT_IV_LENGTH
+ };
+ this.store_configs.set(store_id, config);
+ return config;
+ }
+
+ private async resolve_active_key(store_id: string): Promise<{ key: CryptoKey; entry: CryptoKeyEntry; index: CryptoStoreIndex; }> {
+ const index = await crypto_registry_get_store_index(store_id);
+ if (!index) return await this.create_store_key(store_id, this.resolve_store_config(store_id));
+ const entry = await crypto_registry_get_key_entry(index.active_key_id);
+ if (!entry) return await this.create_store_key(store_id, this.resolve_store_config(store_id));
+ const key = await this.unwrap_key_entry(entry);
+ return { key, entry, index };
+ }
+
+ private async resolve_key_by_id(store_id: string, key_id: string): Promise<{ key: CryptoKey; entry: CryptoKeyEntry; index: CryptoStoreIndex; }> {
+ const entry = await crypto_registry_get_key_entry(key_id);
+ if (!entry) throw new Error(cl_crypto_error.key_not_found);
+ let index = await crypto_registry_get_store_index(store_id);
+ if (!index) {
+ index = {
+ store_id,
+ active_key_id: entry.key_id,
+ key_ids: [entry.key_id],
+ created_at: entry.created_at
+ };
+ await crypto_registry_set_store_index(index);
+ }
+ const key = await this.unwrap_key_entry(entry);
+ return { key, entry, index };
+ }
+
+ private async create_store_key(store_id: string, config: CryptoStoreConfig): Promise<{ key: CryptoKey; entry: CryptoKeyEntry; index: CryptoStoreIndex; }> {
+ const created = await this.create_key_entry(store_id, config);
+ const index: CryptoStoreIndex = {
+ store_id,
+ active_key_id: created.entry.key_id,
+ key_ids: [created.entry.key_id],
+ created_at: created.entry.created_at
+ };
+ await crypto_registry_set_store_index(index);
+ return {
+ key: created.key,
+ entry: created.entry,
+ index
+ };
+ }
+
+ private async create_key_entry(store_id: string, config: CryptoStoreConfig): Promise<{ key: CryptoKey; entry: CryptoKeyEntry; }> {
+ const key_id = crypto_key_id_create();
+ const created_at = Date.now();
+ const kdf_salt = crypto_kdf_salt_create();
+ const kdf_iterations = crypto_kdf_iterations_default();
+ const material = await this.key_material_provider.get_key_material();
+ const provider_id = await this.key_material_provider.get_provider_id();
+ const kek = await crypto_kdf_derive_kek(material, kdf_salt, kdf_iterations);
+ material.fill(0);
+ const data_key = await crypto_key_generate();
+ const raw_key = await crypto_key_export_raw(data_key);
+ const wrapped = await crypto_key_wrap(kek, raw_key);
+ const entry: CryptoKeyEntry = {
+ key_id,
+ store_id,
+ created_at,
+ status: "active",
+ wrapped_key: wrapped.wrapped_key,
+ wrap_iv: wrapped.wrap_iv,
+ kdf_salt,
+ kdf_iterations,
+ iv_length: config.iv_length ?? DEFAULT_IV_LENGTH,
+ algorithm: "AES-GCM",
+ provider_id
+ };
+ await crypto_registry_set_key_entry(entry);
+ return { key: data_key, entry };
+ }
+
+ private async unwrap_key_entry(entry: CryptoKeyEntry): Promise<CryptoKey> {
+ const material = await this.key_material_provider.get_key_material();
+ const kek = await crypto_kdf_derive_kek(material, entry.kdf_salt, entry.kdf_iterations);
+ material.fill(0);
+ return await crypto_key_unwrap(kek, entry.wrapped_key, entry.wrap_iv);
+ }
+
+ private async decrypt_envelope(store_id: string, envelope: { key_id: string; iv: Uint8Array; ciphertext: Uint8Array; }): Promise<CryptoDecryptOutcome> {
+ const resolved = await this.resolve_key_by_id(store_id, envelope.key_id);
+ try {
+ const plain_buf = await crypto.subtle.decrypt(
+ {
+ name: "AES-GCM",
+ iv: as_array_buffer(envelope.iv)
+ },
+ resolved.key,
+ as_array_buffer(envelope.ciphertext)
+ );
+ const plaintext = new Uint8Array(plain_buf);
+ const needs_reencrypt = resolved.index.active_key_id !== envelope.key_id;
+ if (!needs_reencrypt) return { plaintext, needs_reencrypt };
+ const reencrypted = await this.encrypt(store_id, plaintext);
+ return { plaintext, needs_reencrypt, reencrypted };
+ } catch {
+ throw new Error(cl_crypto_error.decrypt_failure);
+ }
+ }
+
+ private async decrypt_legacy(
+ store_id: string,
+ blob: Uint8Array,
+ legacy_key: LegacyKeyConfig | undefined,
+ iv_length: number
+ ): Promise<CryptoDecryptOutcome> {
+ if (!legacy_key) throw new Error(cl_crypto_error.legacy_key_missing);
+ const legacy_crypto_key = await this.load_legacy_key(legacy_key);
+ if (!legacy_crypto_key) throw new Error(cl_crypto_error.legacy_key_missing);
+ if (blob.byteLength <= iv_length) throw new Error(cl_crypto_error.invalid_envelope);
+ const iv = blob.slice(0, iv_length);
+ const ciphertext = blob.slice(iv_length);
+ try {
+ const plain_buf = await crypto.subtle.decrypt(
+ {
+ name: legacy_key.algorithm,
+ iv: as_array_buffer(iv)
+ },
+ legacy_crypto_key,
+ as_array_buffer(ciphertext)
+ );
+ const plaintext = new Uint8Array(plain_buf);
+ const reencrypted = await this.encrypt(store_id, plaintext);
+ return { plaintext, needs_reencrypt: true, reencrypted };
+ } catch {
+ throw new Error(cl_crypto_error.decrypt_failure);
+ }
+ }
+
+ private async load_legacy_key(legacy: LegacyKeyConfig): Promise<CryptoKey | null> {
+ if (typeof indexedDB === "undefined") return null;
+ const legacy_store = createStore(legacy.idb_config.database, legacy.idb_config.store);
+ const stored = await idb_get(legacy.key_name, legacy_store);
+ if (!stored) return null;
+ if (stored instanceof CryptoKey) return stored;
+ if (stored instanceof Uint8Array) return await crypto_key_import_raw(stored);
+ if (stored instanceof ArrayBuffer) return await crypto_key_import_raw(new Uint8Array(stored));
+ if (ArrayBuffer.isView(stored)) return await crypto_key_import_raw(bytes_from_value(stored));
+ return null;
+ }
+}
diff --git a/client/src/crypto/types.ts b/client/src/crypto/types.ts
@@ -0,0 +1,71 @@
+import type { IdbClientConfig } from "@radroots/utils";
+
+export type CryptoKeyStatus = "active" | "rotated";
+
+export type CryptoEnvelope = {
+ version: number;
+ key_id: string;
+ iv: Uint8Array;
+ created_at: number;
+ ciphertext: Uint8Array;
+};
+
+export type CryptoKeyEntry = {
+ key_id: string;
+ store_id: string;
+ created_at: number;
+ status: CryptoKeyStatus;
+ wrapped_key: Uint8Array;
+ wrap_iv: Uint8Array;
+ kdf_salt: Uint8Array;
+ kdf_iterations: number;
+ iv_length: number;
+ algorithm: "AES-GCM";
+ provider_id: string;
+};
+
+export type CryptoStoreIndex = {
+ store_id: string;
+ active_key_id: string;
+ key_ids: string[];
+ created_at: number;
+};
+
+export type CryptoRegistryExport = {
+ stores: CryptoStoreIndex[];
+ keys: CryptoKeyEntry[];
+};
+
+export type CryptoDecryptOutcome = {
+ plaintext: Uint8Array;
+ needs_reencrypt: boolean;
+ reencrypted?: Uint8Array;
+};
+
+export type LegacyKeyConfig = {
+ idb_config: IdbClientConfig;
+ key_name: string;
+ iv_length: number;
+ algorithm: string;
+};
+
+export type CryptoStoreConfig = {
+ store_id: string;
+ legacy_key?: LegacyKeyConfig;
+ iv_length?: number;
+};
+
+export interface KeyMaterialProvider {
+ get_key_material(): Promise<Uint8Array>;
+ get_provider_id(): Promise<string>;
+}
+
+export interface IWebCryptoService {
+ register_store_config(config: CryptoStoreConfig): void;
+ encrypt(store_id: string, plaintext: Uint8Array): Promise<Uint8Array>;
+ decrypt(store_id: string, blob: Uint8Array): Promise<Uint8Array>;
+ decrypt_record(store_id: string, blob: Uint8Array): Promise<CryptoDecryptOutcome>;
+ rotate_store_key(store_id: string): Promise<string>;
+ export_registry(): Promise<CryptoRegistryExport>;
+ import_registry(registry: CryptoRegistryExport): Promise<void>;
+}
diff --git a/client/src/datastore/error.ts b/client/src/datastore/error.ts
@@ -0,0 +1,7 @@
+export const cl_datastore_error = {
+ idb_undefined: "error.client.datastore.idb_undefined",
+ no_result: "error.client.datastore.no_result"
+} as const;
+
+export type ClientDatastoreError = keyof typeof cl_datastore_error;
+export type ClientDatastoreErrorMessage = (typeof cl_datastore_error)[ClientDatastoreError];
+\ No newline at end of file
diff --git a/client/src/datastore/index.ts b/client/src/datastore/index.ts
@@ -0,0 +1,3 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
diff --git a/client/src/datastore/types.ts b/client/src/datastore/types.ts
@@ -0,0 +1,40 @@
+import type { IdbClientConfig, ResolveError, ResultObj, ResultPass, ResultsList } from "@radroots/utils";
+import type { BackupDatastorePayload } from "../backup/types.js";
+
+export type IClientDatastoreValue = string | null;
+
+export type IClientDatastoreSetResolve = ResolveError<ResultPass>;
+export type IClientDatastoreGetResolve = ResolveError<ResultObj<string>>;
+export type IClientDatastoreSetPResolve = ResolveError<ResultPass>;
+export type IClientDatastoreGetPResolve = ResolveError<ResultObj<string>>;
+export type IClientDatastoreKeysResolve = ResolveError<ResultsList<string>>;
+export type IClientDatastoreDelResolve = ResolveError<ResultObj<string>>;
+export type IClientDatastoreDelPrefResolve = ResolveError<ResultsList<string>>;
+export type IClientDatastoreEntriesResolve = ResolveError<ResultsList<[string, IClientDatastoreValue]>>;
+
+export type IClientDatastoreKeyMap = Record<string, string>;
+export type IClientDatastoreKeyParamMap = Record<string, (...args: string[]) => string>;
+
+export interface IClientDatastore<
+ TKeyMap extends IClientDatastoreKeyMap,
+ TKeyParamMap extends IClientDatastoreKeyParamMap,
+ TKeyObjMap extends IClientDatastoreKeyMap,
+> {
+ init(): Promise<ResolveError<void>>;
+ get_config(): IdbClientConfig;
+ get_store_id(): string;
+ set(key: keyof TKeyMap, value: string): Promise<ResolveError<ResultObj<string>>>;
+ get(key: keyof TKeyMap): Promise<ResolveError<ResultObj<string>>>;
+ set_obj<T>(key: keyof TKeyObjMap, value: T): Promise<ResolveError<ResultObj<T>>>;
+ update_obj<T extends Record<string, unknown>>(key: keyof TKeyObjMap, value: Partial<T>): Promise<ResolveError<ResultObj<T>>>;
+ get_obj<T>(key: keyof TKeyObjMap): Promise<ResolveError<ResultObj<T>>>;
+ del_obj(key: keyof TKeyObjMap): Promise<ResolveError<ResultObj<string>>>;
+ del(key: keyof TKeyMap): Promise<IClientDatastoreDelResolve>;
+ del_pref(key_prefix: string): Promise<IClientDatastoreDelPrefResolve>;
+ setp<K extends keyof TKeyParamMap>(key: K, key_param: Parameters<TKeyParamMap[K]>[0], value: string): Promise<ResolveError<ResultObj<string>>>;
+ getp<K extends keyof TKeyParamMap>(key: K, key_param: Parameters<TKeyParamMap[K]>[0]): Promise<ResolveError<ResultObj<string>>>;
+ keys(): Promise<ResolveError<ResultsList<string>>>;
+ reset(): Promise<ResolveError<ResultPass>>;
+ export_backup(): Promise<ResolveError<BackupDatastorePayload>>;
+ import_backup(payload: BackupDatastorePayload): Promise<ResolveError<void>>;
+}
diff --git a/client/src/datastore/web.ts b/client/src/datastore/web.ts
@@ -0,0 +1,281 @@
+import { err_msg, handle_err, text_dec, text_enc, type IdbClientConfig, type ResolveError, type ResultObj, type ResultPass, type ResultsList } from "@radroots/utils";
+import { createStore, clear as idb_clear, del as idb_del, get as idb_get, keys as idb_keys, set as idb_set, type UseStore } from "idb-keyval";
+import type { BackupDatastorePayload } from "../backup/types.js";
+import { WebCryptoService } from "../crypto/service.js";
+import { crypto_registry_clear_key_entry, crypto_registry_clear_store_index, crypto_registry_get_store_index } from "../crypto/registry.js";
+import { IDB_CONFIG_DATASTORE } from "../idb/config.js";
+import { cl_datastore_error } from "./error.js";
+import type {
+ IClientDatastore,
+ IClientDatastoreDelPrefResolve,
+ IClientDatastoreDelResolve,
+ IClientDatastoreKeyMap,
+ IClientDatastoreKeyParamMap
+} from "./types.js";
+
+const DEFAULT_IDB_CONFIG: IdbClientConfig = IDB_CONFIG_DATASTORE;
+
+const is_record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+export interface IWebDatastore<
+ Tk extends IClientDatastoreKeyMap,
+ Tp extends IClientDatastoreKeyParamMap,
+ TkO extends IClientDatastoreKeyMap,
+> extends IClientDatastore<Tk, Tp, TkO> { }
+
+export class WebDatastore<
+ Tk extends IClientDatastoreKeyMap,
+ Tp extends IClientDatastoreKeyParamMap,
+ TkO extends IClientDatastoreKeyMap,
+> implements IWebDatastore<Tk, Tp, TkO> {
+ private db_name: string;
+ private store_name: string;
+ private store: UseStore | null = null;
+ private _key_map: Tk;
+ private _key_param_map: Tp;
+ private _key_obj_map: TkO;
+ private crypto: WebCryptoService;
+ private store_id: string;
+
+ constructor(key_map: Tk, key_param_map: Tp, key_obj_map: TkO, config?: Partial<IdbClientConfig>) {
+ this.db_name = config?.database ?? DEFAULT_IDB_CONFIG.database;
+ this.store_name = config?.store ?? DEFAULT_IDB_CONFIG.store;
+ this.store = null;
+ this._key_map = key_map;
+ this._key_param_map = key_param_map;
+ this._key_obj_map = key_obj_map;
+ this.store_id = `datastore:${this.db_name}:${this.store_name}`;
+ this.crypto = new WebCryptoService();
+ this.crypto.register_store_config({
+ store_id: this.store_id,
+ iv_length: 12
+ });
+ }
+
+ private get_store(): UseStore {
+ if (!this.store) {
+ if (typeof indexedDB === "undefined") throw new Error(cl_datastore_error.idb_undefined);
+ this.store = createStore(this.db_name, this.store_name);
+ }
+ return this.store;
+ }
+
+ private as_bytes(value: unknown): Uint8Array | null {
+ if (value instanceof Uint8Array) return value;
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ return null;
+ }
+
+ private async decrypt_value(store_key: string, stored: unknown): Promise<ResolveError<ResultObj<string>>> {
+ if (typeof stored === "string") {
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(stored));
+ await idb_set(store_key, encrypted, this.get_store());
+ return { result: stored };
+ }
+ const bytes = this.as_bytes(stored);
+ if (!bytes) return err_msg(cl_datastore_error.no_result);
+ const outcome = await this.crypto.decrypt_record(this.store_id, bytes);
+ if (outcome.reencrypted) await idb_set(store_key, outcome.reencrypted, this.get_store());
+ return { result: text_dec(outcome.plaintext) };
+ }
+
+ public get_config(): IdbClientConfig {
+ return {
+ database: this.db_name,
+ store: this.store_name,
+ };
+ }
+
+ public get_store_id(): string {
+ return this.store_id;
+ }
+
+ public async init(): Promise<ResolveError<void>> {
+ try {
+ this.get_store();
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async set(key: keyof Tk, value: string): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(value));
+ await idb_set(this._key_map[key], encrypted, this.get_store());
+ return { result: value };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async get(key: keyof Tk): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const store_key = this._key_map[key];
+ const value = await idb_get(store_key, this.get_store());
+ if (!value) return err_msg(cl_datastore_error.no_result);
+ return await this.decrypt_value(store_key, value);
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async del(key: keyof Tk): Promise<IClientDatastoreDelResolve> {
+ try {
+ await idb_del(this._key_map[key], this.get_store());
+ return { result: key.toString() };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async set_obj<T>(key: keyof TkO, value: T): Promise<ResolveError<ResultObj<T>>> {
+ try {
+ const serialized = JSON.stringify(value);
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(serialized));
+ await idb_set(this._key_obj_map[key], encrypted, this.get_store());
+ return { result: value };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async update_obj<T extends Record<string, unknown>>(key: keyof TkO, value: Partial<T>): Promise<ResolveError<ResultObj<T>>> {
+ try {
+ const k = this._key_obj_map[key];
+ const obj_curr: Record<string, unknown> = {};
+ const curr = await idb_get(k, this.get_store());
+ if (curr) {
+ const decrypted = await this.decrypt_value(k, curr);
+ if ("err" in decrypted) return decrypted;
+ const parsed: unknown = JSON.parse(decrypted.result);
+ if (is_record(parsed)) for (const [curr_key, curr_val] of Object.entries(parsed)) obj_curr[curr_key] = curr_val;
+ }
+ const obj: T = { ...obj_curr, ...value } as T;
+ const serialized = JSON.stringify(obj);
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(serialized));
+ await idb_set(k, encrypted, this.get_store());
+ return { result: obj };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async get_obj<T>(key: keyof TkO): Promise<ResolveError<ResultObj<T>>> {
+ try {
+ const store_key = this._key_obj_map[key];
+ const value = await idb_get(store_key, this.get_store());
+ if (!value) return err_msg(cl_datastore_error.no_result);
+ const decrypted = await this.decrypt_value(store_key, value);
+ if ("err" in decrypted) return decrypted;
+ return { result: JSON.parse(decrypted.result) };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async del_obj(key: keyof TkO): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ await idb_del(this._key_obj_map[key], this.get_store());
+ return { result: key.toString() };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async setp<K extends keyof Tp>(
+ key: K,
+ key_param: Parameters<Tp[K]>[0],
+ value: string
+ ): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const store_key = this._key_param_map[key](key_param);
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(value));
+ await idb_set(store_key, encrypted, this.get_store());
+ return { result: value };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async getp<K extends keyof Tp>(
+ key: K,
+ key_param: Parameters<Tp[K]>[0]
+ ): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const store_key = this._key_param_map[key](key_param);
+ const value = await idb_get(store_key, this.get_store());
+ if (!value) return err_msg(cl_datastore_error.no_result);
+ return await this.decrypt_value(store_key, value);
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async del_pref(key_prefix: string): Promise<IClientDatastoreDelPrefResolve> {
+ try {
+ const all_keys = await idb_keys(this.get_store());
+ const filtered_keys = all_keys.filter((k): k is string => (typeof k === "string" && k.startsWith(key_prefix)));
+ for (const key of filtered_keys) {
+ await idb_del(key, this.get_store());
+ }
+ return { results: filtered_keys };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async keys(): Promise<ResolveError<ResultsList<string>>> {
+ try {
+ const all_keys = await idb_keys(this.get_store());
+ return { results: all_keys.filter((k): k is string => typeof k === "string") };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async export_backup(): Promise<ResolveError<BackupDatastorePayload>> {
+ try {
+ const all_keys = await idb_keys(this.get_store());
+ const entries: BackupDatastorePayload["entries"] = [];
+ for (const key of all_keys) {
+ if (typeof key !== "string") continue;
+ const value = await idb_get(key, this.get_store());
+ if (!value) continue;
+ const decrypted = await this.decrypt_value(key, value);
+ if ("err" in decrypted) return decrypted;
+ entries.push({ key, value: decrypted.result });
+ }
+ return { entries };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async import_backup(payload: BackupDatastorePayload): Promise<ResolveError<void>> {
+ try {
+ for (const entry of payload.entries) {
+ const encrypted = await this.crypto.encrypt(this.store_id, text_enc(entry.value));
+ await idb_set(entry.key, encrypted, this.get_store());
+ }
+ return;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async reset(): Promise<ResolveError<ResultPass>> {
+ try {
+ await idb_clear(this.get_store());
+ const index = await crypto_registry_get_store_index(this.store_id);
+ if (index) {
+ await crypto_registry_clear_store_index(this.store_id);
+ for (const key_id of index.key_ids) await crypto_registry_clear_key_entry(key_id);
+ }
+ return { pass: true } as const;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+}
diff --git a/client/src/error.ts b/client/src/error.ts
@@ -0,0 +1,12 @@
+export * from "./cipher/error.js";
+export * from "./crypto/error.js";
+export * from "./backup/error.js";
+export * from "./datastore/error.js";
+export * from "./fs/error.js";
+export * from "./geolocation/error.js";
+export * from "./http/error.js";
+export * from "./keystore/error.js";
+export * from "./notifications/error.js";
+export * from "./radroots/error.js";
+export * from "./sql/error.js";
+export * from "./tangle/error.js";
diff --git a/client/src/fs/error.ts b/client/src/fs/error.ts
@@ -0,0 +1,7 @@
+export const cl_fs_error = {
+ not_found: "error.client.fs.not_found",
+ request_failure: "error.client.fs.request_failure"
+} as const;
+
+export type ClientFsError = keyof typeof cl_fs_error;
+export type ClientFsErrorMessage = (typeof cl_fs_error)[ClientFsError];
diff --git a/client/src/fs/index.ts b/client/src/fs/index.ts
@@ -0,0 +1,4 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
+
diff --git a/client/src/fs/types.ts b/client/src/fs/types.ts
@@ -0,0 +1,21 @@
+import { type ResolveError } from "@radroots/utils";
+
+export type IClientFsOpenResult = { path: string }
+
+export type IClientFsFileInfo = {
+ size: number
+ isFile: boolean
+ isDirectory: boolean
+ accessedAt?: number
+ modifiedAt?: number
+ createdAt?: number
+};
+
+export type IClientFsReadBinResolve = ResolveError<Uint8Array>
+
+export interface IClientFs {
+ exists(path: string): Promise<ResolveError<boolean>>;
+ open(path: string): Promise<ResolveError<IClientFsOpenResult>>;
+ info(path: string): Promise<ResolveError<IClientFsFileInfo>>;
+ read_bin(path: string): Promise<IClientFsReadBinResolve>;
+}
diff --git a/client/src/fs/web.ts b/client/src/fs/web.ts
@@ -0,0 +1,43 @@
+import { err_msg, handle_err, type ResolveError } from "@radroots/utils";
+import { cl_fs_error } from "./error.js";
+import type { IClientFs, IClientFsFileInfo, IClientFsOpenResult, IClientFsReadBinResolve } from "./types.js";
+
+export interface IWebFs extends IClientFs {}
+
+export class WebFs implements IWebFs {
+ public async exists(path: string): Promise<ResolveError<boolean>> {
+ try {
+ const res = await fetch(path, { method: 'HEAD' });
+ return res.ok;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async open(path: string): Promise<ResolveError<IClientFsOpenResult>> {
+ return { path };
+ }
+
+ public async info(path: string): Promise<ResolveError<IClientFsFileInfo>> {
+ try {
+ const res = await fetch(path, { method: 'HEAD' });
+ if (!res.ok) return err_msg(res.status === 404 ? cl_fs_error.not_found : cl_fs_error.request_failure);
+ const size_header = res.headers.get('Content-Length');
+ const size = size_header ? Number(size_header) : 0;
+ return { size, isFile: true, isDirectory: false };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async read_bin(path: string): Promise<IClientFsReadBinResolve> {
+ try {
+ const res = await fetch(path);
+ if (!res.ok) return err_msg(res.status === 404 ? cl_fs_error.not_found : cl_fs_error.request_failure);
+ const buf = await res.arrayBuffer();
+ return new Uint8Array(buf);
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+}
diff --git a/client/src/geolocation/error.ts b/client/src/geolocation/error.ts
@@ -0,0 +1,11 @@
+export const cl_geolocation_error = {
+ permission_denied: "error.client.geolocation.permission_denied",
+ location_unavailable: "error.client.geolocation.location_unavailable",
+ position_unavailable: "error.client.geolocation.position_unavailable",
+ timeout: "error.client.geolocation.timeout",
+ blocked_by_permissions_policy: "error.client.geolocation.blocked_by_permissions_policy",
+ unknown_error: "error.client.geolocation.unknown_error"
+} as const;
+
+export type ClientGeolocationError = keyof typeof cl_geolocation_error;
+export type ClientGeolocationErrorMessage = (typeof cl_geolocation_error)[ClientGeolocationError];
+\ No newline at end of file
diff --git a/client/src/geolocation/index.ts b/client/src/geolocation/index.ts
@@ -0,0 +1,4 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
+
diff --git a/client/src/geolocation/types.ts b/client/src/geolocation/types.ts
@@ -0,0 +1,7 @@
+import type { IClientGeolocationPosition } from "@radroots/geo";
+import type { ResolveErrorMsg } from "@radroots/utils";
+import { type ClientGeolocationErrorMessage } from "./error.js";
+
+export interface IClientGeolocation {
+ current(): Promise<ResolveErrorMsg<IClientGeolocationPosition, ClientGeolocationErrorMessage>>;
+}
diff --git a/client/src/geolocation/web.ts b/client/src/geolocation/web.ts
@@ -0,0 +1,150 @@
+import type { IClientGeolocationPosition } from "@radroots/geo";
+import { err_msg, type ResolveErrorMsg } from "@radroots/utils";
+import { cl_geolocation_error, type ClientGeolocationErrorMessage } from "./error.js";
+import type { IClientGeolocation } from "./types.js";
+
+type GeoPolicyAllows = boolean | "unknown";
+type GeoPermissionState = PermissionState | "unknown";
+
+interface PermissionsPolicyLike {
+ allowsFeature(feature: "geolocation"): boolean;
+}
+
+interface DocumentWithPermissionsPolicy extends Document {
+ permissionsPolicy: PermissionsPolicyLike;
+}
+
+interface NavigatorWithPermissions extends Navigator {
+ permissions: Permissions;
+}
+
+interface GeoDebug {
+ policy_allows: GeoPolicyAllows;
+ permission_state: GeoPermissionState;
+ error_code?: number;
+ error_message?: string;
+ user_agent: string;
+}
+
+const geo_debug_enabled = true;
+
+function has_permissions_policy(doc: Document): doc is DocumentWithPermissionsPolicy {
+ return "permissionsPolicy" in doc;
+}
+
+function has_permissions_api(nav: Navigator): nav is NavigatorWithPermissions {
+ return "permissions" in nav;
+}
+
+function read_policy_allows_geolocation(doc: Document): GeoPolicyAllows {
+ if (!has_permissions_policy(doc)) return "unknown";
+ try {
+ return doc.permissionsPolicy.allowsFeature("geolocation");
+ } catch {
+ return "unknown";
+ }
+}
+
+async function read_permission_state_geolocation(nav: Navigator): Promise<GeoPermissionState> {
+ if (!has_permissions_api(nav)) return "unknown";
+ try {
+ const status = await nav.permissions.query({ name: "geolocation" });
+ return status.state;
+ } catch {
+ return "unknown";
+ }
+}
+
+function create_debug(
+ policy_allows: GeoPolicyAllows,
+ permission_state: GeoPermissionState
+): GeoDebug {
+ return {
+ policy_allows,
+ permission_state,
+ user_agent: navigator.userAgent
+ };
+}
+
+function log_geo_debug(event: string, debug: GeoDebug): void {
+ if (!geo_debug_enabled) return;
+ console.debug(event, debug);
+}
+
+function get_current_position(): Promise<GeolocationPosition> {
+ return new Promise<GeolocationPosition>((resolve, reject) => {
+ navigator.geolocation.getCurrentPosition(resolve, reject, {
+ enableHighAccuracy: true,
+ timeout: 10000,
+ maximumAge: 30000
+ });
+ });
+}
+
+function map_error_key(
+ debug: GeoDebug,
+ error: GeolocationPositionError
+) {
+ if (error.code === 1) {
+ if (debug.policy_allows === false) {
+ return cl_geolocation_error.blocked_by_permissions_policy;
+ }
+ return cl_geolocation_error.permission_denied;
+ }
+
+ if (error.code === 2) {
+ return cl_geolocation_error.position_unavailable;
+ }
+
+ if (error.code === 3) {
+ return cl_geolocation_error.timeout;
+ }
+
+ return cl_geolocation_error.unknown_error;
+}
+
+export interface IWebGeolocation extends IClientGeolocation {}
+
+export class WebGeolocation implements IWebGeolocation {
+ public async current(): Promise<ResolveErrorMsg<IClientGeolocationPosition, ClientGeolocationErrorMessage>> {
+ if (typeof navigator === "undefined" || typeof document === "undefined") return err_msg(cl_geolocation_error.location_unavailable);
+ if (!navigator.geolocation) return err_msg(cl_geolocation_error.location_unavailable);
+
+ const policy_allows = read_policy_allows_geolocation(document);
+ const permission_state = await read_permission_state_geolocation(navigator);
+
+ const base_debug = create_debug(policy_allows, permission_state);
+ const has_geo_error = typeof GeolocationPositionError !== "undefined";
+
+ if (policy_allows === false) {
+ log_geo_debug("[geolocation] blocked_by_policy", base_debug);
+ return err_msg(cl_geolocation_error.blocked_by_permissions_policy);
+ }
+
+ try {
+ const position = await get_current_position();
+
+ return {
+ lat: position.coords.latitude,
+ lng: position.coords.longitude,
+ accuracy: position.coords.accuracy
+ };
+ } catch (e) {
+ if (has_geo_error && e instanceof GeolocationPositionError) {
+ const debug: GeoDebug = {
+ ...base_debug,
+ error_code: e.code,
+ error_message: e.message
+ };
+
+ const key = map_error_key(debug, e);
+ log_geo_debug("[geolocation] error", debug);
+
+ return err_msg(key);
+ }
+
+ log_geo_debug("[geolocation] unknown_exception", base_debug);
+ return err_msg(cl_geolocation_error.unknown_error);
+ }
+ }
+}
diff --git a/client/src/idb/config.ts b/client/src/idb/config.ts
@@ -0,0 +1,47 @@
+import type { IdbClientConfig } from "@radroots/utils";
+
+export const RADROOTS_IDB_DATABASE = "radroots-pwa-v1";
+
+export const IDB_STORE_DATASTORE = "radroots.app.datastore";
+export const IDB_STORE_KEYSTORE = "radroots.security.keystore";
+export const IDB_STORE_KEYSTORE_NOSTR = "radroots.security.keystore.nostr";
+export const IDB_STORE_CRYPTO_REGISTRY = "radroots.security.crypto.registry";
+export const IDB_STORE_CIPHER_AES_GCM = "radroots.security.cipher.aes-gcm";
+export const IDB_STORE_CIPHER_SQL = "radroots.security.cipher.sql";
+export const IDB_STORE_TANGLE = "radroots.storage.tangle.sql";
+export const IDB_STORE_CIPHER_SUFFIX = ".cipher";
+
+export const IDB_CONFIG_DATASTORE: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_DATASTORE
+};
+
+export const IDB_CONFIG_KEYSTORE: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_KEYSTORE
+};
+
+export const IDB_CONFIG_KEYSTORE_NOSTR: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_KEYSTORE_NOSTR
+};
+
+export const IDB_CONFIG_CRYPTO_REGISTRY: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_CRYPTO_REGISTRY
+};
+
+export const IDB_CONFIG_CIPHER_AES_GCM: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_CIPHER_AES_GCM
+};
+
+export const IDB_CONFIG_CIPHER_SQL: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_CIPHER_SQL
+};
+
+export const IDB_CONFIG_TANGLE: IdbClientConfig = {
+ database: RADROOTS_IDB_DATABASE,
+ store: IDB_STORE_TANGLE
+};
diff --git a/client/src/index.ts b/client/src/index.ts
@@ -0,0 +1,3 @@
+export * as error from "./error.js";
+export * as crypto from "./crypto/index.js";
+export * as backup from "./backup/index.js";
diff --git a/client/src/keystore/error.ts b/client/src/keystore/error.ts
@@ -0,0 +1,10 @@
+export const cl_keystore_error = {
+ idb_undefined: "error.client.keystore.idb_undefined",
+ missing_key: "error.client.keystore.missing_key",
+ corrupt_data: "error.client.keystore.corrupt_data",
+ nostr_invalid_secret_key: "error.client.keystore.nostr_invalid_secret_key",
+ nostr_no_results: "error.client.keystore.nostr_no_results"
+} as const;
+
+export type ClientKeystoreError = keyof typeof cl_keystore_error;
+export type ClientKeystoreErrorMessage = (typeof cl_keystore_error)[ClientKeystoreError];
diff --git a/client/src/keystore/index.ts b/client/src/keystore/index.ts
@@ -0,0 +1,6 @@
+export * from "../cipher/web.js";
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web-nostr.js";
+export * from "./web.js";
+
diff --git a/client/src/keystore/types.ts b/client/src/keystore/types.ts
@@ -0,0 +1,24 @@
+import type { ResolveError, ResultObj, ResultPass, ResultPublicKey, ResultSecretKey, ResultsList } from "@radroots/utils";
+import type { BackupKeystorePayload } from "../backup/types.js";
+
+export type IClientKeystoreValue = string | null;
+
+export interface IClientKeystore {
+ add(key: string, value: string): Promise<ResolveError<ResultObj<string>>>;
+ remove(key: string): Promise<ResolveError<ResultObj<string>>>;
+ read(key?: string | null): Promise<ResolveError<ResultObj<IClientKeystoreValue>>>;
+ keys(): Promise<ResolveError<ResultsList<string>>>;
+ reset(): Promise<ResolveError<ResultPass>>;
+ get_store_id(): string;
+ export_backup(): Promise<ResolveError<BackupKeystorePayload>>;
+ import_backup(payload: BackupKeystorePayload): Promise<ResolveError<void>>;
+}
+
+export interface IClientKeystoreNostr {
+ generate(): Promise<ResolveError<ResultPublicKey>>;
+ add(secret_key: string): Promise<ResolveError<ResultPublicKey>>;
+ read(public_key: string): Promise<ResolveError<ResultSecretKey>>;
+ keys(): Promise<ResolveError<ResultsList<string>>>;
+ remove(public_key: string): Promise<ResolveError<ResultObj<string>>>;
+ reset(): Promise<ResolveError<ResultPass>>;
+}
diff --git a/client/src/keystore/web-nostr.ts b/client/src/keystore/web-nostr.ts
@@ -0,0 +1,107 @@
+import {
+ err_msg,
+ handle_err,
+ IdbClientConfig,
+ type ResolveError,
+ type ResultObj,
+ type ResultPass,
+ type ResultPublicKey,
+ type ResultSecretKey,
+ type ResultsList
+} from '@radroots/utils';
+import { lib_nostr_key_generate, lib_nostr_public_key, lib_nostr_secret_key_validate } from '@radroots/utils-nostr';
+import { cl_keystore_error } from "./error.js";
+import type { IClientKeystoreNostr } from './types.js';
+import { IDB_CONFIG_KEYSTORE_NOSTR } from "../idb/config.js";
+import { WebKeystore } from './web.js';
+
+export interface IWebKeystoreNostr extends IClientKeystoreNostr {
+ get_config(): IdbClientConfig;
+}
+
+export class WebKeystoreNostr implements IWebKeystoreNostr {
+ private keystore_config: IdbClientConfig;
+ private _keystore: WebKeystore;
+
+ constructor(config?: Partial<IdbClientConfig>) {
+ const config_base = config ?? {};
+ this.keystore_config = {
+ database: config_base.database ?? IDB_CONFIG_KEYSTORE_NOSTR.database,
+ store: config_base.store ?? IDB_CONFIG_KEYSTORE_NOSTR.store
+ };
+ this._keystore = new WebKeystore(this.keystore_config);
+ }
+
+ private async add_secret_key(secret_key_raw: string): Promise<ResolveError<ResultObj<string>>> {
+ const secret_key = lib_nostr_secret_key_validate(secret_key_raw);
+ if (!secret_key) throw new Error(cl_keystore_error.nostr_invalid_secret_key);
+ const public_key = lib_nostr_public_key(secret_key);
+ return await this._keystore.add(public_key, secret_key);
+ }
+
+ public get_config(): IdbClientConfig {
+ return this._keystore.get_config();
+ }
+
+ public async generate(): Promise<ResolveError<ResultPublicKey>> {
+ try {
+ const secret_key = lib_nostr_key_generate();
+ const resolve = await this.add_secret_key(secret_key);
+ if ("err" in resolve) return resolve;
+ return { public_key: resolve.result };
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+
+ public async add(secret_key_raw: string): Promise<ResolveError<ResultPublicKey>> {
+ try {
+ const resolve = await this.add_secret_key(secret_key_raw);
+ if ("err" in resolve) return resolve;
+ return { public_key: resolve.result };
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+
+ public async read(public_key?: string): Promise<ResolveError<ResultSecretKey>> {
+ try {
+ const resolve = await this._keystore.read(public_key);
+ if ("err" in resolve) return resolve;
+ if (!resolve.result) return err_msg(cl_keystore_error.missing_key);
+ return { secret_key: resolve.result };
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+
+ public async keys(): Promise<ResolveError<ResultsList<string>>> {
+ try {
+ const resolve = await this._keystore.keys();
+ if ("err" in resolve) return resolve;
+ if (resolve.results.length) return resolve;
+ return err_msg(cl_keystore_error.nostr_no_results);
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+
+ public async remove(public_key: string): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const resolve = await this._keystore.remove(public_key);
+ if ("err" in resolve) return resolve;
+ return { result: public_key };
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+
+ public async reset(): Promise<ResolveError<ResultPass>> {
+ try {
+ const resolve = await this._keystore.reset();
+ return resolve;
+ } catch (e) {
+ return handle_err(e);
+ }
+ };
+}
diff --git a/client/src/keystore/web.ts b/client/src/keystore/web.ts
@@ -0,0 +1,183 @@
+import {
+ err_msg,
+ handle_err,
+ IdbClientConfig,
+ text_dec,
+ text_enc,
+ type ResolveError,
+ type ResultObj,
+ type ResultPass,
+ type ResultsList
+} from "@radroots/utils";
+import { createStore, clear as idb_clear, del as idb_del, get as idb_get, keys as idb_keys, set as idb_set, type UseStore } from "idb-keyval";
+import type { BackupKeystorePayload } from "../backup/types.js";
+import { WebCryptoService } from "../crypto/service.js";
+import type { LegacyKeyConfig } from "../crypto/types.js";
+import { crypto_registry_clear_key_entry, crypto_registry_clear_store_index, crypto_registry_get_store_index } from "../crypto/registry.js";
+import { IDB_CONFIG_KEYSTORE, IDB_STORE_CIPHER_SUFFIX } from "../idb/config.js";
+import { cl_keystore_error } from "./error.js";
+import type { IClientKeystore, IClientKeystoreValue } from "./types.js";
+
+export type WebAesGcmCipherConfig = {
+ idb_config?: Partial<IdbClientConfig>;
+ key_name?: string;
+ key_length?: number;
+ iv_length?: number;
+ algorithm?: string;
+};
+
+export interface IWebKeystore extends IClientKeystore {
+ get_config(): IdbClientConfig;
+ get_store_id(): string;
+ export_backup(): Promise<ResolveError<BackupKeystorePayload>>;
+ import_backup(payload: BackupKeystorePayload): Promise<ResolveError<void>>;
+}
+
+export class WebKeystore implements IWebKeystore {
+ private config: IdbClientConfig;
+ private store: UseStore | null;
+ private crypto: WebCryptoService;
+ private store_id: string;
+ private legacy_key_config: LegacyKeyConfig;
+
+ constructor(config?: IdbClientConfig) {
+ const config_base = config ?? {};
+ this.config = {
+ database: config_base.database ?? IDB_CONFIG_KEYSTORE.database,
+ store: config_base.store ?? IDB_CONFIG_KEYSTORE.store
+ };
+ this.store = null;
+ this.store_id = `keystore:${this.config.database}:${this.config.store}`;
+ this.crypto = new WebCryptoService();
+ const legacy_store = `${this.config.store}${IDB_STORE_CIPHER_SUFFIX}`;
+
+ this.legacy_key_config = {
+ idb_config: {
+ database: this.config.database,
+ store: legacy_store
+ },
+ key_name: `radroots.keystore.${this.config.store}.aes-gcm.key`,
+ iv_length: 12,
+ algorithm: "AES-GCM"
+ };
+
+ this.crypto.register_store_config({
+ store_id: this.store_id,
+ legacy_key: this.legacy_key_config,
+ iv_length: 12
+ });
+ }
+
+ private get_store(): UseStore {
+ if (!this.store) {
+ if (typeof indexedDB === "undefined") throw new Error(cl_keystore_error.idb_undefined);
+ this.store = createStore(this.config.database, this.config.store);
+ }
+ return this.store;
+ }
+
+ private as_bytes(value: unknown): Uint8Array | null {
+ if (value instanceof Uint8Array) return value;
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ return null;
+ }
+
+ public get_config(): IdbClientConfig {
+ return {
+ database: this.config.database,
+ store: this.config.store
+ };
+ }
+
+ public get_store_id(): string {
+ return this.store_id;
+ }
+
+ public async add(key: string, value: string): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ const bytes = text_enc(value);
+ const cipher_bytes = await this.crypto.encrypt(this.store_id, bytes);
+ await idb_set(key, cipher_bytes, this.get_store());
+ return { result: key };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async remove(key: string): Promise<ResolveError<ResultObj<string>>> {
+ try {
+ await idb_del(key, this.get_store());
+ return { result: key };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async read(key?: string | null): Promise<ResolveError<ResultObj<IClientKeystoreValue>>> {
+ try {
+ if (!key) return err_msg(cl_keystore_error.missing_key);
+ const cipher_value = await idb_get(key, this.get_store());
+ const cipher_bytes = this.as_bytes(cipher_value);
+ if (!cipher_bytes) return err_msg(cl_keystore_error.corrupt_data);
+ const outcome = await this.crypto.decrypt_record(this.store_id, cipher_bytes);
+ if (outcome.reencrypted) await idb_set(key, outcome.reencrypted, this.get_store());
+ const plain = text_dec(outcome.plaintext);
+ return { result: plain };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async keys(): Promise<ResolveError<ResultsList<string>>> {
+ try {
+ const all_keys = await idb_keys(this.get_store());
+ return { results: all_keys.filter((k): k is string => typeof k === "string") };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async export_backup(): Promise<ResolveError<BackupKeystorePayload>> {
+ try {
+ const all_keys = await idb_keys(this.get_store());
+ const entries: BackupKeystorePayload["entries"] = [];
+ for (const key of all_keys) {
+ if (typeof key !== "string") continue;
+ const value = await this.read(key);
+ if ("err" in value) return value;
+ if (typeof value.result !== "string") return err_msg(cl_keystore_error.corrupt_data);
+ entries.push({ key, value: value.result });
+ }
+ return { entries };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async import_backup(payload: BackupKeystorePayload): Promise<ResolveError<void>> {
+ try {
+ for (const entry of payload.entries) {
+ const res = await this.add(entry.key, entry.value);
+ if ("err" in res) return res;
+ }
+ return;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async reset(): Promise<ResolveError<ResultPass>> {
+ try {
+ await idb_clear(this.get_store());
+ const index = await crypto_registry_get_store_index(this.store_id);
+ if (index) {
+ await crypto_registry_clear_store_index(this.store_id);
+ for (const key_id of index.key_ids) await crypto_registry_clear_key_entry(key_id);
+ }
+ return { pass: true } as const;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+}
diff --git a/client/src/notifications/error.ts b/client/src/notifications/error.ts
@@ -0,0 +1,7 @@
+export const cl_notifications_error = {
+ unavailable: "error.client.notifications.unavailable",
+ read_failure: "error.client.notifications.read_failure"
+} as const;
+
+export type ClientNotificationsError = keyof typeof cl_notifications_error;
+export type ClientNotificationsErrorMessage = (typeof cl_notifications_error)[ClientNotificationsError];
diff --git a/client/src/notifications/index.ts b/client/src/notifications/index.ts
@@ -0,0 +1,3 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
diff --git a/client/src/notifications/types.ts b/client/src/notifications/types.ts
@@ -0,0 +1,38 @@
+import { type IResultList } from "@radroots/types-bindings";
+import { type ResolveError, type ResolveStatus } from "@radroots/utils";
+
+export type IClientNotificationsNotifyPermission = "granted" | "denied" | "default" | "unavailable";
+
+export type IClientNotificationsDialogConfirmOpts =
+ | string
+ | {
+ message: string;
+ title?: string;
+ status?: ResolveStatus;
+ cancel?: string;
+ ok?: string;
+ }
+
+export type IClientNotificationsNotifySendOptions = {
+ id?: string;
+ channel_id?: string;
+ title?: string;
+ body?: string;
+}
+
+export type IClientNotificationsConfig = {
+ app_name: string;
+};
+
+export type IClientNotificationsAlertResolve = boolean;
+export type IClientNotificationsConfirmResolve = boolean;
+export type IClientNotificationsNotifyInitResolve = ResolveError<IClientNotificationsNotifyPermission>;
+export type IClientNotificationsNotifySendResolve = ResolveError<Notification>
+
+export interface IClientNotifications {
+ alert(opts: string, title?: string, status?: ResolveStatus): Promise<IClientNotificationsAlertResolve>;
+ confirm(opts: IClientNotificationsDialogConfirmOpts): Promise<IClientNotificationsConfirmResolve>;
+ notify_init(): Promise<IClientNotificationsNotifyInitResolve>;
+ notify_send(opts: string | IClientNotificationsNotifySendOptions): Promise<IClientNotificationsNotifySendResolve>;
+ open_photos(): Promise<ResolveError<IResultList<string> | undefined>>;
+}
diff --git a/client/src/notifications/web.ts b/client/src/notifications/web.ts
@@ -0,0 +1,106 @@
+import { IResultList } from "@radroots/types-bindings";
+import { err_msg, handle_err, type ResolveError, type ResolveStatus } from "@radroots/utils";
+import { cl_notifications_error } from "./error.js";
+import type {
+ IClientNotifications,
+ IClientNotificationsAlertResolve,
+ IClientNotificationsConfig,
+ IClientNotificationsConfirmResolve,
+ IClientNotificationsDialogConfirmOpts,
+ IClientNotificationsNotifyInitResolve,
+ IClientNotificationsNotifySendOptions,
+ IClientNotificationsNotifySendResolve
+} from "./types.js";
+
+export interface IWebNotifications extends IClientNotifications { }
+
+export class WebNotifications implements IWebNotifications {
+ private _config: IClientNotificationsConfig;
+
+ constructor(config: IClientNotificationsConfig = { app_name: "Radroots" }) {
+ this._config = config;
+ }
+ public async alert(opts: string, title?: string, kind?: ResolveStatus): Promise<IClientNotificationsAlertResolve> {
+ try {
+ const msg = title ? `${title}\n\n${opts}` : opts;
+ window.alert(msg);
+ return true;
+ } catch (e) {
+ handle_err(e);
+ return false;
+ }
+ }
+
+ public async confirm(opts: IClientNotificationsDialogConfirmOpts): Promise<IClientNotificationsConfirmResolve> {
+ try {
+ const msg = typeof opts === 'string' ? opts : opts.message
+ return window.confirm(msg);
+ } catch (e) {
+ handle_err(e);
+ return false;
+ }
+ }
+
+ public async notify_init(): Promise<IClientNotificationsNotifyInitResolve> {
+ try {
+ if (!("Notification" in window)) return "unavailable";
+ if (Notification.permission === 'granted') return "granted";
+ return await Notification.requestPermission();
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async notify_send(opts: string | IClientNotificationsNotifySendOptions): Promise<IClientNotificationsNotifySendResolve> {
+ try {
+ if (!("Notification" in window)) return err_msg(cl_notifications_error.unavailable);
+ if (Notification.permission !== "granted") {
+ const permission = await this.notify_init();
+ if (permission !== "granted") return err_msg(cl_notifications_error.unavailable);
+ }
+ if (typeof opts === "string") return new Notification(this._config.app_name, { body: opts });
+ else return new Notification(opts.title || this._config.app_name, { body: opts.body });
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ private async read_photo_data(file: File): Promise<string> {
+ return await new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ if (typeof reader.result === "string") return resolve(reader.result);
+ return reject(new Error(cl_notifications_error.read_failure));
+ };
+ reader.onerror = () => {
+ if (reader.error) return reject(reader.error);
+ return reject(new Error(cl_notifications_error.read_failure));
+ };
+ reader.readAsDataURL(file);
+ });
+ }
+
+ public async open_photos(): Promise<ResolveError<IResultList<string> | undefined>> {
+ try {
+ const files = await new Promise<FileList | null>((resolve) => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.multiple = true;
+ input.accept = 'image/png,image/jpg';
+ input.onchange = () => resolve(input.files);
+ input.click();
+ });
+ if (!files) return;
+ const results: string[] = [];
+ for (let i = 0; i < files.length; i++) {
+ const file = files.item(i);
+ if (!file) continue;
+ const data_url = await this.read_photo_data(file);
+ results.push(data_url);
+ }
+ return { results };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+}
diff --git a/client/src/radroots/error.ts b/client/src/radroots/error.ts
@@ -0,0 +1,8 @@
+export const cl_radroots_error = {
+ missing_base_url: "error.client.radroots.missing_base_url",
+ account_registered: "error.client.radroots.account_registered",
+ request_failure: "error.client.radroots.request_failure"
+} as const;
+
+export type ClientRadrootsError = keyof typeof cl_radroots_error;
+export type ClientRadrootsErrorMessage = (typeof cl_radroots_error)[ClientRadrootsError];
diff --git a/client/src/radroots/index.ts b/client/src/radroots/index.ts
@@ -0,0 +1,3 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
diff --git a/client/src/radroots/types.ts b/client/src/radroots/types.ts
@@ -0,0 +1,22 @@
+import { MediaResource, ResolveErrorMsg, type ResultObj } from '@radroots/utils';
+
+export type IClientRadrootsAccountsRequestMessage =
+ | string
+ | `error.client.request_failure`
+ | `*-registered`;
+
+export type IClientRadrootsAccountsRequest = { profile_name: string; secret_key: string; };
+export type IClientRadrootsAccountsRequestResolve = ResolveErrorMsg<ResultObj<string>, IClientRadrootsAccountsRequestMessage>;
+export type IClientRadrootsAccountsCreate = { tok: string; secret_key: string; };
+export type IClientRadrootsAccountsCreateResolve = ResolveErrorMsg<ResultObj<string>, IClientRadrootsAccountsRequestMessage>;
+export type IClientRadrootsAccountsActivate = { id: string; secret_key: string; };
+export type IClientRadrootsAccountsActivateResolve = ResolveErrorMsg<ResultObj<string>, IClientRadrootsAccountsRequestMessage>;
+export type IClientRadrootsMediaImageUpload = { mime_type?: string; file_data: Uint8Array; secret_key: string; };
+export type IClientRadrootsMediaImageUploadResolve = ResolveErrorMsg<MediaResource, IClientRadrootsAccountsRequestMessage>;
+
+export interface IClientRadroots {
+ accounts_request(opts: IClientRadrootsAccountsRequest): Promise<IClientRadrootsAccountsRequestResolve>;
+ accounts_create(opts: IClientRadrootsAccountsCreate): Promise<IClientRadrootsAccountsCreateResolve>;
+ accounts_activate(opts: IClientRadrootsAccountsActivate): Promise<IClientRadrootsAccountsActivateResolve>;
+ media_image_upload(opts: IClientRadrootsMediaImageUpload): Promise<IClientRadrootsMediaImageUploadResolve>;
+}
diff --git a/client/src/radroots/web.ts b/client/src/radroots/web.ts
@@ -0,0 +1,122 @@
+import { err_msg, schema_media_resource } from '@radroots/utils';
+import { type IHttpResponse, is_err_response, is_error_response, is_pass_response, WebHttp } from '@radroots/http';
+import { lib_nostr_event_sign_attest } from '@radroots/utils-nostr';
+import { cl_radroots_error } from "./error.js";
+import type {
+ IClientRadroots,
+ IClientRadrootsAccountsActivate,
+ IClientRadrootsAccountsActivateResolve,
+ IClientRadrootsAccountsCreate,
+ IClientRadrootsAccountsCreateResolve,
+ IClientRadrootsAccountsRequest,
+ IClientRadrootsAccountsRequestResolve,
+ IClientRadrootsMediaImageUpload,
+ IClientRadrootsMediaImageUploadResolve
+} from "./types.js";
+
+export interface IWebClientRadroots extends IClientRadroots { }
+
+export class WebClientRadroots implements IWebClientRadroots {
+ private _base_url: string
+ private _http_client: WebHttp
+
+ constructor(base_url: string) {
+ if (!base_url) throw new Error(cl_radroots_error.missing_base_url);
+ const parsed_url = new URL(base_url);
+ const sanitized_base_url = `${parsed_url.origin}${parsed_url.pathname}`.replace(/\/+$/, ``);
+ this._base_url = sanitized_base_url;
+ this._http_client = new WebHttp();
+ }
+
+ private is_res_pass(res: IHttpResponse): boolean {
+ return is_pass_response(res.data);
+ }
+
+ private parse_res_field(field: unknown): string | undefined {
+ if (typeof field === `string` && field) return field;
+ }
+
+ private is_record(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+ }
+
+ private create_x_nostr_event(secret_key: string): string {
+ return JSON.stringify(lib_nostr_event_sign_attest(secret_key));
+ }
+
+ public async accounts_request(opts: IClientRadrootsAccountsRequest): Promise<IClientRadrootsAccountsRequestResolve> {
+ const { profile_name, secret_key } = opts
+ const res = await this._http_client.fetch({
+ url: `${this._base_url}/v1/accounts/request`,
+ method: "post",
+ headers: {
+ "X-Nostr-Event": this.create_x_nostr_event(secret_key),
+ },
+ data: { profile_name }
+ });
+ if (is_err_response(res)) return res;
+ if (is_error_response(res)) return err_msg(res.error);
+ else if (this.is_res_pass(res)) {
+ const res_data = this.is_record(res.data) ? res.data : null;
+ const tok = res_data ? this.parse_res_field(res_data["tok"]) : undefined;
+ if (tok) return { result: tok };
+ }
+ return err_msg(cl_radroots_error.account_registered);
+ }
+
+ public async accounts_create(opts: IClientRadrootsAccountsCreate): Promise<IClientRadrootsAccountsCreateResolve> {
+ const { tok, secret_key } = opts
+ const res = await this._http_client.fetch({
+ url: `${this._base_url}/v1/accounts/create`,
+ method: "post",
+ headers: {
+ "X-Nostr-Event": this.create_x_nostr_event(secret_key),
+ },
+ authorization: tok
+ });
+ if (is_err_response(res)) return res;
+ if (is_error_response(res)) return err_msg(res.error);
+ else if (this.is_res_pass(res)) {
+ const res_data = this.is_record(res.data) ? res.data : null;
+ const id = res_data ? this.parse_res_field(res_data["id"]) : undefined;
+ if (id) return { result: id };
+ }
+ return err_msg(cl_radroots_error.request_failure);
+ }
+
+ public async accounts_activate(opts: IClientRadrootsAccountsActivate): Promise<IClientRadrootsAccountsActivateResolve> {
+ const { id, secret_key } = opts
+ const res = await this._http_client.fetch({
+ url: `${this._base_url}/v1/accounts/activate`,
+ method: "post",
+ headers: {
+ "X-Nostr-Event": this.create_x_nostr_event(secret_key),
+ },
+ data: { id }
+ });
+ if (is_err_response(res)) return res;
+ if (is_error_response(res)) return err_msg(res.error);
+ else if (this.is_res_pass(res)) return { result: id };
+ return err_msg(cl_radroots_error.request_failure);
+ }
+
+ public async media_image_upload(opts: IClientRadrootsMediaImageUpload): Promise<IClientRadrootsMediaImageUploadResolve> {
+ const { mime_type, file_data, secret_key } = opts
+ const res = await this._http_client.fetch({
+ url: `${this._base_url}/v1/media/image/upload`,
+ method: "put",
+ headers: {
+ "Content-Type": mime_type || "image/png",
+ "X-Nostr-Event": this.create_x_nostr_event(secret_key),
+ },
+ data_bin: file_data
+ });
+ if (is_err_response(res)) return res;
+ if (is_error_response(res)) return err_msg(res.error);
+ else if (this.is_res_pass(res)) {
+ const res_data = schema_media_resource.safeParse(res.data);
+ if (res_data.success && res_data.data) return res_data.data;
+ }
+ return err_msg(cl_radroots_error.request_failure);
+ }
+}
diff --git a/client/src/sql/error.ts b/client/src/sql/error.ts
@@ -0,0 +1,5 @@
+export const cl_sql_error = {
+} as const;
+
+export type ClientSqlError = keyof typeof cl_sql_error;
+export type ClientSqlErrorMessage = (typeof cl_sql_error)[ClientSqlError];
diff --git a/client/src/sql/index.ts b/client/src/sql/index.ts
@@ -0,0 +1,3 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
diff --git a/client/src/sql/types.ts b/client/src/sql/types.ts
@@ -0,0 +1,49 @@
+import type { IdbClientConfig, ResolveError } from "@radroots/utils";
+import type { SqlValue } from "sql.js";
+import type { BackupSqlPayload } from "../backup/types.js";
+
+export type SqlJsExecOutcome = {
+ changes: number;
+ last_insert_id: number;
+};
+
+export type SqlJsResultRow = Record<string, unknown>;
+
+export type SqlJsMigrationRow = {
+ id: number;
+ name: string;
+ applied_at: string;
+};
+
+export type SqlJsMigrationState = {
+ applied_names: string[];
+ applied_count: number;
+};
+
+export type SqlJsValue = SqlValue;
+
+export type SqlJsParams = Readonly<Record<string, SqlJsValue>> | ReadonlyArray<SqlJsValue>;
+
+export type WebSqlEngineConfig = {
+ store_key: string;
+ idb_config: IdbClientConfig;
+ cipher_config?: IdbClientConfig | null;
+};
+
+export interface IClientSqlEncryptedStore {
+ load(): Promise<Uint8Array | null>;
+ save(bytes: Uint8Array): Promise<void>;
+ remove(): Promise<void>;
+}
+
+export interface IWebSqlEngine {
+ close(): Promise<void>;
+ purge_storage(): Promise<void>;
+ exec(sql: string, params: SqlJsParams): SqlJsExecOutcome;
+ query(sql: string, params: SqlJsParams): SqlJsResultRow[];
+ export_bytes(): Uint8Array;
+ import_bytes(bytes: Uint8Array): Promise<void>;
+ export_backup(): Promise<ResolveError<BackupSqlPayload>>;
+ import_backup(payload: BackupSqlPayload): Promise<ResolveError<void>>;
+ get_store_id(): string;
+}
diff --git a/client/src/sql/web.ts b/client/src/sql/web.ts
@@ -0,0 +1,231 @@
+import { handle_err, type IdbClientConfig, type ResolveError } from "@radroots/utils";
+import { createStore, del as idb_del, get as idb_get, set as idb_set, type UseStore } from "idb-keyval";
+import type { BindParams, Database, SqlJsStatic, SqlValue, Statement } from "sql.js";
+import init_sql_js from "sql.js/dist/sql-wasm.js";
+import { backup_b64_to_bytes, backup_bytes_to_b64 } from "../backup/codec.js";
+import type { BackupSqlPayload } from "../backup/types.js";
+import { WebCryptoService } from "../crypto/service.js";
+import type { LegacyKeyConfig } from "../crypto/types.js";
+import { IDB_CONFIG_CIPHER_SQL } from "../idb/config.js";
+import type { IClientSqlEncryptedStore, IWebSqlEngine, SqlJsExecOutcome, SqlJsParams, SqlJsResultRow, WebSqlEngineConfig } from "./types.js";
+
+const DEFAULT_SQL_CIPHER_CONFIG: IdbClientConfig = IDB_CONFIG_CIPHER_SQL;
+
+interface IWebSqlEngineEncryptedStore extends IClientSqlEncryptedStore {
+ get_store_id(): string;
+}
+
+class WebSqlEngineEncryptedStore implements IWebSqlEngineEncryptedStore {
+ private readonly store_key: string;
+ private readonly store_id: string;
+ private readonly crypto: WebCryptoService;
+ private readonly db_name: string;
+ private readonly store_name: string;
+ private store: UseStore | null;
+
+ constructor(config: WebSqlEngineConfig) {
+ this.store_key = config.store_key;
+ this.db_name = config.idb_config.database;
+ this.store_name = config.idb_config.store;
+ this.store = null;
+ this.store_id = `sql:${this.store_key}`;
+ this.crypto = new WebCryptoService();
+ const legacy_config: LegacyKeyConfig = {
+ idb_config: config.cipher_config ?? DEFAULT_SQL_CIPHER_CONFIG,
+ key_name: `radroots.sql.${this.store_key}.aes-gcm.key`,
+ iv_length: 12,
+ algorithm: "AES-GCM"
+ };
+ this.crypto.register_store_config({
+ store_id: this.store_id,
+ legacy_key: legacy_config,
+ iv_length: 12
+ });
+ }
+
+ public get_store_id(): string {
+ return this.store_id;
+ }
+
+ private as_bytes(value: unknown): Uint8Array | null {
+ if (value instanceof Uint8Array) return value;
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ return null;
+ }
+
+ private get_store(): UseStore {
+ if (!this.store) this.store = createStore(this.db_name, this.store_name);
+ return this.store;
+ }
+
+ async load(): Promise<Uint8Array | null> {
+ if (typeof indexedDB === "undefined") return null;
+ const data = await idb_get(this.store_key, this.get_store());
+ const bytes = this.as_bytes(data);
+ if (!bytes) return null;
+ const outcome = await this.crypto.decrypt_record(this.store_id, bytes);
+ if (outcome.reencrypted) await idb_set(this.store_key, outcome.reencrypted, this.get_store());
+ return outcome.plaintext;
+ }
+
+ async save(bytes: Uint8Array): Promise<void> {
+ if (typeof indexedDB === "undefined") return;
+ const enc = await this.crypto.encrypt(this.store_id, bytes);
+ await idb_set(this.store_key, enc, this.get_store());
+ }
+
+ async remove(): Promise<void> {
+ if (typeof indexedDB === "undefined") return;
+ await idb_del(this.store_key, this.get_store());
+ }
+}
+
+export class WebSqlEngine implements IWebSqlEngine {
+ private save_timer: number | undefined;
+ private db: Database;
+ private readonly store_id: string;
+
+ private constructor(
+ private readonly sqljs: SqlJsStatic,
+ db: Database,
+ private readonly store: WebSqlEngineEncryptedStore
+ ) {
+ this.db = db;
+ this.store_id = store.get_store_id();
+ }
+
+ static async create(config: WebSqlEngineConfig): Promise<WebSqlEngine> {
+ const sql = await init_sql_js({ locateFile: f => `/assets/${f}` });
+ const store = new WebSqlEngineEncryptedStore(config);
+ const existing = await store.load();
+ const db = existing ? new sql.Database(existing) : new sql.Database();
+ return new WebSqlEngine(sql, db, store);
+ }
+
+ async close(): Promise<void> {
+ if (this.save_timer) {
+ self.clearTimeout(this.save_timer);
+ this.save_timer = undefined;
+ const bytes = this.db.export();
+ await this.store.save(bytes);
+ }
+ this.db.close();
+ }
+
+ async purge_storage(): Promise<void> {
+ await this.store.remove();
+ }
+
+ public get_store_id(): string {
+ return this.store_id;
+ }
+
+ private schedule_persist(): void {
+ if (this.save_timer) return;
+ this.save_timer = self.setTimeout(async () => {
+ const bytes = this.db.export();
+ await this.store.save(bytes);
+ this.save_timer = undefined;
+ }, 200);
+ }
+
+ public exec(sql: string, params: SqlJsParams): SqlJsExecOutcome {
+ const st = this.prepare(sql);
+ this.bind(st, params);
+ const result = this.consume_exec(st);
+ st.free();
+ this.schedule_persist();
+ return result;
+ }
+
+ public query(sql: string, params: SqlJsParams): SqlJsResultRow[] {
+ const st = this.prepare(sql);
+ this.bind(st, params);
+ const rows = this.collect_rows(st);
+ st.free();
+ return rows;
+ }
+
+ public export_bytes(): Uint8Array {
+ return this.db.export();
+ }
+
+ public async import_bytes(bytes: Uint8Array): Promise<void> {
+ this.db.close();
+ this.db = new this.sqljs.Database(bytes);
+ await this.store.save(bytes);
+ }
+
+ public async export_backup(): Promise<ResolveError<BackupSqlPayload>> {
+ try {
+ const bytes = this.export_bytes();
+ return { bytes_b64: backup_bytes_to_b64(bytes) };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ public async import_backup(payload: BackupSqlPayload): Promise<ResolveError<void>> {
+ try {
+ const bytes = backup_b64_to_bytes(payload.bytes_b64);
+ await this.import_bytes(bytes);
+ return;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ private prepare(sql: string): Statement {
+ return this.db.prepare(sql);
+ }
+
+ private bind(st: Statement, params: SqlJsParams): void {
+ let bind_params: BindParams;
+ if (Array.isArray(params)) bind_params = [...params];
+ else bind_params = { ...(params as Readonly<Record<string, SqlValue>>) };
+ st.bind(bind_params);
+ }
+
+ private consume_exec(st: Statement): SqlJsExecOutcome {
+ const changes_before = this.db.getRowsModified();
+ let last_id = 0;
+
+ while (st.step()) {
+ const col_names = st.getColumnNames();
+ const idx = col_names.indexOf("last_insert_rowid()");
+ if (idx >= 0) {
+ const v = st.get()[idx];
+ if (typeof v === "number") last_id = v;
+ }
+ }
+
+ const changes = this.db.getRowsModified() - changes_before;
+
+ if (!last_id) {
+ const res = this.db.exec("select last_insert_rowid() as id");
+ if (res[0]?.values?.[0]?.[0]) {
+ const v = res[0].values[0][0];
+ if (typeof v === "number") {
+ last_id = v;
+ }
+ }
+ }
+
+ return { changes, last_insert_id: last_id };
+ }
+
+ private collect_rows(st: Statement): SqlJsResultRow[] {
+ const out: SqlJsResultRow[] = [];
+ const names = st.getColumnNames();
+
+ while (st.step()) {
+ const row = st.get();
+ const obj: SqlJsResultRow = {};
+ for (let i = 0; i < names.length; i++) obj[names[i]] = row[i];
+ out.push(obj);
+ }
+
+ return out;
+ }
+}
diff --git a/client/src/tangle/bridge.ts b/client/src/tangle/bridge.ts
@@ -0,0 +1,46 @@
+import type { SqlJsParams, SqlJsValue } from "../sql/types.js";
+import { WebSqlEngine } from "../sql/web.js";
+
+const is_record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const is_sql_value = (value: unknown): value is SqlJsValue => {
+ if (value === null) return true;
+ if (typeof value === "string") return true;
+ if (typeof value === "number") return Number.isFinite(value);
+ return value instanceof Uint8Array;
+};
+
+const is_sql_value_array = (value: unknown): value is ReadonlyArray<SqlJsValue> =>
+ Array.isArray(value) && value.every(is_sql_value);
+
+const is_sql_value_record = (value: unknown): value is Readonly<Record<string, SqlJsValue>> =>
+ is_record(value) && Object.values(value).every(is_sql_value);
+
+function parse_sql_params(params_json: string): SqlJsParams {
+ const trimmed = params_json.trim();
+ if (!trimmed) return [];
+ try {
+ const raw = JSON.parse(trimmed);
+ if (is_sql_value_array(raw)) return raw;
+ if (is_sql_value_record(raw)) return raw;
+ return [];
+ } catch {
+ return [];
+ }
+}
+
+export function radroots_sql_install_bridges(engine: WebSqlEngine): void {
+ Object.assign(globalThis, {
+ __radroots_sql_wasm_exec: (sql: string, params_json: string) => {
+ const params = parse_sql_params(params_json);
+ const res = engine.exec(sql, params);
+ return res;
+ },
+ __radroots_sql_wasm_query: (sql: string, params_json: string) => {
+ const params = parse_sql_params(params_json);
+ const res = engine.query(sql, params);
+ return res;
+ }
+ });
+}
diff --git a/client/src/tangle/error.ts b/client/src/tangle/error.ts
@@ -0,0 +1,7 @@
+export const cl_tangle_error = {
+ parse_failure: "error.client.tangle.parse_failure",
+ invalid_response: "error.client.tangle.invalid_response"
+} as const;
+
+export type ClientTangleError = keyof typeof cl_tangle_error;
+export type ClientTangleErrorMessage = (typeof cl_tangle_error)[ClientTangleError];
diff --git a/client/src/tangle/index.ts b/client/src/tangle/index.ts
@@ -0,0 +1,3 @@
+export * from "./error.js";
+export * from "./types.js";
+export * from "./web.js";
diff --git a/client/src/tangle/types.ts b/client/src/tangle/types.ts
@@ -0,0 +1,139 @@
+import type {
+ IFarmCreate,
+ IFarmCreateResolve,
+ IFarmDelete,
+ IFarmDeleteResolve,
+ IFarmFindMany,
+ IFarmFindManyResolve,
+ IFarmFindOne,
+ IFarmFindOneResolve,
+ IFarmUpdate,
+ IFarmUpdateResolve,
+ ILocationGcsCreate,
+ ILocationGcsCreateResolve,
+ ILocationGcsDelete,
+ ILocationGcsDeleteResolve,
+ ILocationGcsFindMany,
+ ILocationGcsFindManyResolve,
+ ILocationGcsFindOne,
+ ILocationGcsFindOneResolve,
+ ILocationGcsUpdate,
+ ILocationGcsUpdateResolve,
+ ILogErrorCreate,
+ ILogErrorCreateResolve,
+ ILogErrorDelete,
+ ILogErrorDeleteResolve,
+ ILogErrorFindMany,
+ ILogErrorFindManyResolve,
+ ILogErrorFindOne,
+ ILogErrorFindOneResolve,
+ ILogErrorUpdate,
+ ILogErrorUpdateResolve,
+ IMediaImageCreate,
+ IMediaImageCreateResolve,
+ IMediaImageDelete,
+ IMediaImageDeleteResolve,
+ IMediaImageFindMany,
+ IMediaImageFindManyResolve,
+ IMediaImageFindOne,
+ IMediaImageFindOneResolve,
+ IMediaImageUpdate,
+ IMediaImageUpdateResolve,
+ INostrProfileCreate,
+ INostrProfileCreateResolve,
+ INostrProfileDelete,
+ INostrProfileDeleteResolve,
+ INostrProfileFindMany,
+ INostrProfileFindManyResolve,
+ INostrProfileFindOne,
+ INostrProfileFindOneResolve,
+ INostrProfileUpdate,
+ INostrProfileUpdateResolve,
+ INostrRelayCreate,
+ INostrRelayCreateResolve,
+ INostrRelayDelete,
+ INostrRelayDeleteResolve,
+ INostrRelayFindMany,
+ INostrRelayFindManyResolve,
+ INostrRelayFindOne,
+ INostrRelayFindOneResolve,
+ INostrRelayUpdate,
+ INostrRelayUpdateResolve,
+ ITradeProductCreate,
+ ITradeProductCreateResolve,
+ ITradeProductDelete,
+ ITradeProductDeleteResolve,
+ ITradeProductFindMany,
+ ITradeProductFindManyResolve,
+ ITradeProductFindOne,
+ ITradeProductFindOneResolve,
+ ITradeProductUpdate,
+ ITradeProductUpdateResolve,
+ IFarmLocationRelation,
+ IFarmLocationResolve,
+ INostrProfileRelayRelation,
+ INostrProfileRelayResolve,
+ ITradeProductLocationRelation,
+ ITradeProductLocationResolve,
+ ITradeProductMediaRelation,
+ ITradeProductMediaResolve
+} from "@radroots/tangle-schema-bindings";
+import { type SqlJsMigrationState } from "../sql/types.js";
+import type { IError } from "@radroots/types-bindings";
+import type { TangleDatabaseBackup } from "./web.js";
+
+export interface IClientTangleDatabase {
+ init(): Promise<void>;
+ migration_state(): Promise<SqlJsMigrationState | IError<string>>;
+ reset(): Promise<SqlJsMigrationState | IError<string>>;
+ reinit(): Promise<SqlJsMigrationState | IError<string>>;
+ get_store_key(): string;
+ export_backup(): Promise<TangleDatabaseBackup | IError<string>>;
+ import_backup(backup: TangleDatabaseBackup): Promise<void | IError<string>>;
+ farm_create(opts: IFarmCreate): Promise<IFarmCreateResolve | IError<string>>;
+ farm_find_one(opts: IFarmFindOne): Promise<IFarmFindOneResolve | IError<string>>;
+ farm_find_many(opts?: IFarmFindMany): Promise<IFarmFindManyResolve | IError<string>>;
+ farm_delete(opts: IFarmDelete): Promise<IFarmDeleteResolve | IError<string>>;
+ farm_update(opts: IFarmUpdate): Promise<IFarmUpdateResolve | IError<string>>;
+ location_gcs_create(opts: ILocationGcsCreate): Promise<ILocationGcsCreateResolve | IError<string>>;
+ location_gcs_find_one(opts: ILocationGcsFindOne): Promise<ILocationGcsFindOneResolve | IError<string>>;
+ location_gcs_find_many(opts?: ILocationGcsFindMany): Promise<ILocationGcsFindManyResolve | IError<string>>;
+ location_gcs_delete(opts: ILocationGcsDelete): Promise<ILocationGcsDeleteResolve | IError<string>>;
+ location_gcs_update(opts: ILocationGcsUpdate): Promise<ILocationGcsUpdateResolve | IError<string>>;
+ log_error_create(opts: ILogErrorCreate): Promise<ILogErrorCreateResolve | IError<string>>;
+ log_error_find_one(opts: ILogErrorFindOne): Promise<ILogErrorFindOneResolve | IError<string>>;
+ log_error_find_many(opts?: ILogErrorFindMany): Promise<ILogErrorFindManyResolve | IError<string>>;
+ log_error_delete(opts: ILogErrorDelete): Promise<ILogErrorDeleteResolve | IError<string>>;
+ log_error_update(opts: ILogErrorUpdate): Promise<ILogErrorUpdateResolve | IError<string>>;
+ media_image_create(opts: IMediaImageCreate): Promise<IMediaImageCreateResolve | IError<string>>;
+ media_image_find_one(opts: IMediaImageFindOne): Promise<IMediaImageFindOneResolve | IError<string>>;
+ media_image_find_many(opts?: IMediaImageFindMany): Promise<IMediaImageFindManyResolve | IError<string>>;
+ media_image_delete(opts: IMediaImageDelete): Promise<IMediaImageDeleteResolve | IError<string>>;
+ media_image_update(opts: IMediaImageUpdate): Promise<IMediaImageUpdateResolve | IError<string>>;
+ nostr_profile_create(opts: INostrProfileCreate): Promise<INostrProfileCreateResolve | IError<string>>;
+ nostr_profile_find_one(opts: INostrProfileFindOne): Promise<INostrProfileFindOneResolve | IError<string>>;
+ nostr_profile_find_many(opts?: INostrProfileFindMany): Promise<INostrProfileFindManyResolve | IError<string>>;
+ nostr_profile_delete(opts: INostrProfileDelete): Promise<INostrProfileDeleteResolve | IError<string>>;
+ nostr_profile_update(opts: INostrProfileUpdate): Promise<INostrProfileUpdateResolve | IError<string>>;
+ nostr_relay_create(opts: INostrRelayCreate): Promise<INostrRelayCreateResolve | IError<string>>;
+ nostr_relay_find_one(opts: INostrRelayFindOne): Promise<INostrRelayFindOneResolve | IError<string>>;
+ nostr_relay_find_many(opts?: INostrRelayFindMany): Promise<INostrRelayFindManyResolve | IError<string>>;
+ nostr_relay_delete(opts: INostrRelayDelete): Promise<INostrRelayDeleteResolve | IError<string>>;
+ nostr_relay_update(opts: INostrRelayUpdate): Promise<INostrRelayUpdateResolve | IError<string>>;
+ trade_product_create(opts: ITradeProductCreate): Promise<ITradeProductCreateResolve | IError<string>>;
+ trade_product_find_one(opts: ITradeProductFindOne): Promise<ITradeProductFindOneResolve | IError<string>>;
+ trade_product_find_many(opts?: ITradeProductFindMany): Promise<ITradeProductFindManyResolve | IError<string>>;
+ trade_product_delete(opts: ITradeProductDelete): Promise<ITradeProductDeleteResolve | IError<string>>;
+ trade_product_update(opts: ITradeProductUpdate): Promise<ITradeProductUpdateResolve | IError<string>>;
+ farm_location_set(opts: IFarmLocationRelation): Promise<IFarmLocationResolve | IError<string>>;
+ farm_location_unset(opts: IFarmLocationRelation): Promise<IFarmLocationResolve | IError<string>>;
+ nostr_profile_relay_set(opts: INostrProfileRelayRelation): Promise<INostrProfileRelayResolve | IError<string>>;
+ nostr_profile_relay_unset(opts: INostrProfileRelayRelation): Promise<INostrProfileRelayResolve | IError<string>>;
+ trade_product_location_set(opts: ITradeProductLocationRelation): Promise<ITradeProductLocationResolve | IError<string>>;
+ trade_product_location_unset(opts: ITradeProductLocationRelation): Promise<ITradeProductLocationResolve | IError<string>>;
+ trade_product_media_set(opts: ITradeProductMediaRelation): Promise<ITradeProductMediaResolve | IError<string>>;
+ trade_product_media_unset(opts: ITradeProductMediaRelation): Promise<ITradeProductMediaResolve | IError<string>>;
+}
+
+export interface IWebTangleDatabase extends IClientTangleDatabase {
+}
diff --git a/client/src/tangle/web.ts b/client/src/tangle/web.ts
@@ -0,0 +1,541 @@
+import type {
+ IFarmCreate,
+ IFarmCreateResolve,
+ IFarmDelete,
+ IFarmDeleteResolve,
+ IFarmFindMany,
+ IFarmFindManyResolve,
+ IFarmFindOne,
+ IFarmFindOneResolve,
+ IFarmLocationRelation,
+ IFarmLocationResolve,
+ IFarmUpdate,
+ IFarmUpdateResolve,
+ ILocationGcsCreate,
+ ILocationGcsCreateResolve,
+ ILocationGcsDelete,
+ ILocationGcsDeleteResolve,
+ ILocationGcsFindMany,
+ ILocationGcsFindManyResolve,
+ ILocationGcsFindOne,
+ ILocationGcsFindOneResolve,
+ ILocationGcsUpdate,
+ ILocationGcsUpdateResolve,
+ ILogErrorCreate,
+ ILogErrorCreateResolve,
+ ILogErrorDelete,
+ ILogErrorDeleteResolve,
+ ILogErrorFindMany,
+ ILogErrorFindManyResolve,
+ ILogErrorFindOne,
+ ILogErrorFindOneResolve,
+ ILogErrorUpdate,
+ ILogErrorUpdateResolve,
+ IMediaImageCreate,
+ IMediaImageCreateResolve,
+ IMediaImageDelete,
+ IMediaImageDeleteResolve,
+ IMediaImageFindMany,
+ IMediaImageFindManyResolve,
+ IMediaImageFindOne,
+ IMediaImageFindOneResolve,
+ IMediaImageUpdate,
+ IMediaImageUpdateResolve,
+ INostrProfileCreate,
+ INostrProfileCreateResolve,
+ INostrProfileDelete,
+ INostrProfileDeleteResolve,
+ INostrProfileFindMany,
+ INostrProfileFindManyResolve,
+ INostrProfileFindOne,
+ INostrProfileFindOneResolve,
+ INostrProfileRelayRelation,
+ INostrProfileRelayResolve,
+ INostrProfileUpdate,
+ INostrProfileUpdateResolve,
+ INostrRelayCreate,
+ INostrRelayCreateResolve,
+ INostrRelayDelete,
+ INostrRelayDeleteResolve,
+ INostrRelayFindMany,
+ INostrRelayFindManyResolve,
+ INostrRelayFindOne,
+ INostrRelayFindOneResolve,
+ INostrRelayUpdate,
+ INostrRelayUpdateResolve,
+ ITradeProductCreate,
+ ITradeProductCreateResolve,
+ ITradeProductDelete,
+ ITradeProductDeleteResolve,
+ ITradeProductFindMany,
+ ITradeProductFindManyResolve,
+ ITradeProductFindOne,
+ ITradeProductFindOneResolve,
+ ITradeProductLocationRelation,
+ ITradeProductLocationResolve,
+ ITradeProductMediaRelation,
+ ITradeProductMediaResolve,
+ ITradeProductUpdate,
+ ITradeProductUpdateResolve
+} from "@radroots/tangle-schema-bindings";
+import init_wasm, {
+ query_sql,
+ tangle_db_export_backup,
+ tangle_db_farm_create,
+ tangle_db_farm_delete,
+ tangle_db_farm_find_many,
+ tangle_db_farm_find_one,
+ tangle_db_farm_location_set,
+ tangle_db_farm_location_unset,
+ tangle_db_farm_update,
+ tangle_db_import_backup,
+ tangle_db_location_gcs_create,
+ tangle_db_location_gcs_delete,
+ tangle_db_location_gcs_find_many,
+ tangle_db_location_gcs_find_one,
+ tangle_db_location_gcs_update,
+ tangle_db_log_error_create,
+ tangle_db_log_error_delete,
+ tangle_db_log_error_find_many,
+ tangle_db_log_error_find_one,
+ tangle_db_log_error_update,
+ tangle_db_media_image_create,
+ tangle_db_media_image_delete,
+ tangle_db_media_image_find_many,
+ tangle_db_media_image_find_one,
+ tangle_db_media_image_update,
+ tangle_db_nostr_profile_create,
+ tangle_db_nostr_profile_delete,
+ tangle_db_nostr_profile_find_many,
+ tangle_db_nostr_profile_find_one,
+ tangle_db_nostr_profile_relay_set,
+ tangle_db_nostr_profile_relay_unset,
+ tangle_db_nostr_profile_update,
+ tangle_db_nostr_relay_create,
+ tangle_db_nostr_relay_delete,
+ tangle_db_nostr_relay_find_many,
+ tangle_db_nostr_relay_find_one,
+ tangle_db_nostr_relay_update,
+ tangle_db_reset_database,
+ tangle_db_run_migrations,
+ tangle_db_trade_product_create,
+ tangle_db_trade_product_delete,
+ tangle_db_trade_product_find_many,
+ tangle_db_trade_product_find_one,
+ tangle_db_trade_product_location_set,
+ tangle_db_trade_product_location_unset,
+ tangle_db_trade_product_media_set,
+ tangle_db_trade_product_media_unset,
+ tangle_db_trade_product_update
+} from "@radroots/tangle-sql-wasm";
+import type { IError } from "@radroots/types-bindings";
+import { err_msg, handle_err, type IdbClientConfig } from "@radroots/utils";
+import { IDB_CONFIG_TANGLE } from "../idb/config.js";
+import type { SqlJsMigrationRow, SqlJsMigrationState, WebSqlEngineConfig } from "../sql/types.js";
+import { WebSqlEngine } from "../sql/web.js";
+import { radroots_sql_install_bridges } from "./bridge.js";
+import { cl_tangle_error } from "./error.js";
+import type { IWebTangleDatabase } from "./types.js";
+
+export type TangleDatabaseBackup = {
+ format_version: string;
+ tangle_sql_version: string;
+ schema: {
+ object_type: string;
+ name: string;
+ table_name?: string;
+ sql?: string;
+ }[];
+ data: {
+ name: string;
+ rows: Record<string, unknown>[];
+ }[];
+ migrations: {
+ name: string;
+ up_sql: string;
+ down_sql: string;
+ }[];
+};
+
+export type WebTangleDatabaseConfig = {
+ store_key?: string;
+ idb_config?: IdbClientConfig;
+ cipher_config?: IdbClientConfig | null;
+};
+
+const is_record = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const is_sql_migration_row = (value: unknown): value is SqlJsMigrationRow => {
+ if (!is_record(value)) return false;
+ return typeof value.id === "number"
+ && Number.isFinite(value.id)
+ && typeof value.name === "string"
+ && typeof value.applied_at === "string";
+};
+
+const is_sql_migration_row_list = (value: unknown): value is SqlJsMigrationRow[] =>
+ Array.isArray(value) && value.every(is_sql_migration_row);
+
+const is_backup_schema_entry = (value: unknown): value is TangleDatabaseBackup["schema"][number] => {
+ if (!is_record(value)) return false;
+ if (typeof value.object_type !== "string") return false;
+ if (typeof value.name !== "string") return false;
+ if ("table_name" in value && typeof value.table_name !== "undefined" && typeof value.table_name !== "string") return false;
+ if ("sql" in value && typeof value.sql !== "undefined" && typeof value.sql !== "string") return false;
+ return true;
+};
+
+const is_backup_data_entry = (value: unknown): value is TangleDatabaseBackup["data"][number] => {
+ if (!is_record(value)) return false;
+ if (typeof value.name !== "string") return false;
+ if (!Array.isArray(value.rows)) return false;
+ if (!value.rows.every(is_record)) return false;
+ return true;
+};
+
+const is_backup_migration_entry = (value: unknown): value is TangleDatabaseBackup["migrations"][number] => {
+ if (!is_record(value)) return false;
+ return typeof value.name === "string"
+ && typeof value.up_sql === "string"
+ && typeof value.down_sql === "string";
+};
+
+const is_tangle_database_backup = (value: unknown): value is TangleDatabaseBackup => {
+ if (!is_record(value)) return false;
+ if (typeof value.format_version !== "string") return false;
+ if (typeof value.tangle_sql_version !== "string") return false;
+ if (!Array.isArray(value.schema) || !value.schema.every(is_backup_schema_entry)) return false;
+ if (!Array.isArray(value.data) || !value.data.every(is_backup_data_entry)) return false;
+ if (!Array.isArray(value.migrations) || !value.migrations.every(is_backup_migration_entry)) return false;
+ return true;
+};
+
+const DEFAULT_TANGLE_STORE_KEY = "radroots-pwa-v1-tangle-db";
+const DEFAULT_TANGLE_IDB_CONFIG: IdbClientConfig = IDB_CONFIG_TANGLE;
+
+export class WebTangleDatabase implements IWebTangleDatabase {
+ private engine: WebSqlEngine | null = null;
+ private readonly store_key: string;
+ private readonly idb_config: IdbClientConfig;
+ private readonly cipher_config: IdbClientConfig | null;
+
+ constructor(config?: WebTangleDatabaseConfig) {
+ this.store_key = config?.store_key ?? DEFAULT_TANGLE_STORE_KEY;
+ this.idb_config = config?.idb_config ?? DEFAULT_TANGLE_IDB_CONFIG;
+ this.cipher_config = config?.cipher_config ?? null;
+ }
+
+ get_store_key(): string {
+ return this.store_key;
+ }
+
+ private serialize<T>(opts: T): string {
+ return JSON.stringify(opts);
+ }
+
+ private deserialize<T>(data: string): T | IError<string> {
+ try {
+ return JSON.parse(data);
+ } catch {
+ return err_msg(cl_tangle_error.parse_failure);
+ }
+ }
+
+ private get_engine_config(): WebSqlEngineConfig {
+ return {
+ store_key: this.store_key,
+ idb_config: this.idb_config,
+ cipher_config: this.cipher_config
+ };
+ }
+
+ async init(): Promise<void> {
+ if (this.engine) return;
+ await init_wasm();
+ this.engine = await WebSqlEngine.create(this.get_engine_config());
+ radroots_sql_install_bridges(this.engine);
+ tangle_db_run_migrations();
+ }
+
+ async migration_state(): Promise<SqlJsMigrationState | IError<string>> {
+ try {
+ const res = await query_sql("select id, name, applied_at from __migrations order by id asc", "[]");
+ let parsed: unknown = res;
+ if (typeof res === "string") {
+ try {
+ parsed = JSON.parse(res);
+ } catch {
+ return err_msg(cl_tangle_error.parse_failure);
+ }
+ }
+ if (!is_sql_migration_row_list(parsed)) return err_msg(cl_tangle_error.invalid_response);
+ const names = parsed.map((row) => row.name);
+ return { applied_names: names, applied_count: names.length };
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ async reset(): Promise<SqlJsMigrationState | IError<string>> {
+ tangle_db_reset_database();
+ tangle_db_run_migrations();
+ return this.migration_state();
+ }
+
+ async reinit(): Promise<SqlJsMigrationState | IError<string>> {
+ if (this.engine) {
+ await this.engine.purge_storage();
+ await this.engine.close();
+ }
+ this.engine = await WebSqlEngine.create(this.get_engine_config());
+ radroots_sql_install_bridges(this.engine);
+ tangle_db_run_migrations();
+ return this.migration_state();
+ }
+
+ async export_backup(): Promise<TangleDatabaseBackup | IError<string>> {
+ try {
+ await this.init();
+ const res = await tangle_db_export_backup();
+ let parsed: unknown = res;
+ if (typeof res === "string") {
+ try {
+ parsed = JSON.parse(res);
+ } catch {
+ return err_msg(cl_tangle_error.parse_failure);
+ }
+ }
+ if (!is_tangle_database_backup(parsed)) return err_msg(cl_tangle_error.invalid_response);
+ return parsed;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ async import_backup(backup: TangleDatabaseBackup): Promise<void | IError<string>> {
+ try {
+ await this.init();
+ tangle_db_import_backup(this.serialize(backup));
+ return;
+ } catch (e) {
+ return handle_err(e);
+ }
+ }
+
+ async farm_create(opts: IFarmCreate): Promise<IFarmCreateResolve | IError<string>> {
+ const res = await tangle_db_farm_create(this.serialize(opts));
+ return this.deserialize<IFarmCreateResolve>(res);
+ }
+
+ async farm_find_one(opts: IFarmFindOne): Promise<IFarmFindOneResolve | IError<string>> {
+ const res = await tangle_db_farm_find_one(this.serialize(opts));
+ return this.deserialize<IFarmFindOneResolve>(res);
+ }
+
+ async farm_find_many(opts?: IFarmFindMany): Promise<IFarmFindManyResolve | IError<string>> {
+ const res = await tangle_db_farm_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<IFarmFindManyResolve>(res);
+ }
+
+ async farm_delete(opts: IFarmDelete): Promise<IFarmDeleteResolve | IError<string>> {
+ const res = await tangle_db_farm_delete(this.serialize(opts));
+ return this.deserialize<IFarmDeleteResolve>(res);
+ }
+
+ async farm_update(opts: IFarmUpdate): Promise<IFarmUpdateResolve | IError<string>> {
+ const res = await tangle_db_farm_update(this.serialize(opts));
+ return this.deserialize<IFarmUpdateResolve>(res);
+ }
+
+ async location_gcs_create(opts: ILocationGcsCreate): Promise<ILocationGcsCreateResolve | IError<string>> {
+ const res = await tangle_db_location_gcs_create(this.serialize(opts));
+ return this.deserialize<ILocationGcsCreateResolve>(res);
+ }
+
+ async location_gcs_find_one(opts: ILocationGcsFindOne): Promise<ILocationGcsFindOneResolve | IError<string>> {
+ const res = await tangle_db_location_gcs_find_one(this.serialize(opts));
+ return this.deserialize<ILocationGcsFindOneResolve>(res);
+ }
+
+ async location_gcs_find_many(opts?: ILocationGcsFindMany): Promise<ILocationGcsFindManyResolve | IError<string>> {
+ const res = await tangle_db_location_gcs_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<ILocationGcsFindManyResolve>(res);
+ }
+
+ async location_gcs_delete(opts: ILocationGcsDelete): Promise<ILocationGcsDeleteResolve | IError<string>> {
+ const res = await tangle_db_location_gcs_delete(this.serialize(opts));
+ return this.deserialize<ILocationGcsDeleteResolve>(res);
+ }
+
+ async location_gcs_update(opts: ILocationGcsUpdate): Promise<ILocationGcsUpdateResolve | IError<string>> {
+ const res = await tangle_db_location_gcs_update(this.serialize(opts));
+ return this.deserialize<ILocationGcsUpdateResolve>(res);
+ }
+
+ async log_error_create(opts: ILogErrorCreate): Promise<ILogErrorCreateResolve | IError<string>> {
+ const res = await tangle_db_log_error_create(this.serialize(opts));
+ return this.deserialize<ILogErrorCreateResolve>(res);
+ }
+
+ async log_error_find_one(opts: ILogErrorFindOne): Promise<ILogErrorFindOneResolve | IError<string>> {
+ const res = await tangle_db_log_error_find_one(this.serialize(opts));
+ return this.deserialize<ILogErrorFindOneResolve>(res);
+ }
+
+ async log_error_find_many(opts?: ILogErrorFindMany): Promise<ILogErrorFindManyResolve | IError<string>> {
+ const res = await tangle_db_log_error_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<ILogErrorFindManyResolve>(res);
+ }
+
+ async log_error_delete(opts: ILogErrorDelete): Promise<ILogErrorDeleteResolve | IError<string>> {
+ const res = await tangle_db_log_error_delete(this.serialize(opts));
+ return this.deserialize<ILogErrorDeleteResolve>(res);
+ }
+
+ async log_error_update(opts: ILogErrorUpdate): Promise<ILogErrorUpdateResolve | IError<string>> {
+ const res = await tangle_db_log_error_update(this.serialize(opts));
+ return this.deserialize<ILogErrorUpdateResolve>(res);
+ }
+
+ async media_image_create(opts: IMediaImageCreate): Promise<IMediaImageCreateResolve | IError<string>> {
+ const res = await tangle_db_media_image_create(this.serialize(opts));
+ return this.deserialize<IMediaImageCreateResolve>(res);
+ }
+
+ async media_image_find_one(opts: IMediaImageFindOne): Promise<IMediaImageFindOneResolve | IError<string>> {
+ const res = await tangle_db_media_image_find_one(this.serialize(opts));
+ return this.deserialize<IMediaImageFindOneResolve>(res);
+ }
+
+ async media_image_find_many(opts?: IMediaImageFindMany): Promise<IMediaImageFindManyResolve | IError<string>> {
+ const res = await tangle_db_media_image_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<IMediaImageFindManyResolve>(res);
+ }
+
+ async media_image_delete(opts: IMediaImageDelete): Promise<IMediaImageDeleteResolve | IError<string>> {
+ const res = await tangle_db_media_image_delete(this.serialize(opts));
+ return this.deserialize<IMediaImageDeleteResolve>(res);
+ }
+
+ async media_image_update(opts: IMediaImageUpdate): Promise<IMediaImageUpdateResolve | IError<string>> {
+ const res = await tangle_db_media_image_update(this.serialize(opts));
+ return this.deserialize<IMediaImageUpdateResolve>(res);
+ }
+
+ async nostr_profile_create(opts: INostrProfileCreate): Promise<INostrProfileCreateResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_create(this.serialize(opts));
+ return this.deserialize<INostrProfileCreateResolve>(res);
+ }
+
+ async nostr_profile_find_one(opts: INostrProfileFindOne): Promise<INostrProfileFindOneResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_find_one(this.serialize(opts));
+ return this.deserialize<INostrProfileFindOneResolve>(res);
+ }
+
+ async nostr_profile_find_many(opts?: INostrProfileFindMany): Promise<INostrProfileFindManyResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<INostrProfileFindManyResolve>(res);
+ }
+
+ async nostr_profile_delete(opts: INostrProfileDelete): Promise<INostrProfileDeleteResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_delete(this.serialize(opts));
+ return this.deserialize<INostrProfileDeleteResolve>(res);
+ }
+
+ async nostr_profile_update(opts: INostrProfileUpdate): Promise<INostrProfileUpdateResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_update(this.serialize(opts));
+ return this.deserialize<INostrProfileUpdateResolve>(res);
+ }
+
+ async nostr_relay_create(opts: INostrRelayCreate): Promise<INostrRelayCreateResolve | IError<string>> {
+ const res = await tangle_db_nostr_relay_create(this.serialize(opts));
+ return this.deserialize<INostrRelayCreateResolve>(res);
+ }
+
+ async nostr_relay_find_one(opts: INostrRelayFindOne): Promise<INostrRelayFindOneResolve | IError<string>> {
+ const res = await tangle_db_nostr_relay_find_one(this.serialize(opts));
+ return this.deserialize<INostrRelayFindOneResolve>(res);
+ }
+
+ async nostr_relay_find_many(opts?: INostrRelayFindMany): Promise<INostrRelayFindManyResolve | IError<string>> {
+ const res = await tangle_db_nostr_relay_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<INostrRelayFindManyResolve>(res);
+ }
+
+ async nostr_relay_delete(opts: INostrRelayDelete): Promise<INostrRelayDeleteResolve | IError<string>> {
+ const res = await tangle_db_nostr_relay_delete(this.serialize(opts));
+ return this.deserialize<INostrRelayDeleteResolve>(res);
+ }
+
+ async nostr_relay_update(opts: INostrRelayUpdate): Promise<INostrRelayUpdateResolve | IError<string>> {
+ const res = await tangle_db_nostr_relay_update(this.serialize(opts));
+ return this.deserialize<INostrRelayUpdateResolve>(res);
+ }
+
+ async trade_product_create(opts: ITradeProductCreate): Promise<ITradeProductCreateResolve | IError<string>> {
+ const res = await tangle_db_trade_product_create(this.serialize(opts));
+ return this.deserialize<ITradeProductCreateResolve>(res);
+ }
+
+ async trade_product_find_one(opts: ITradeProductFindOne): Promise<ITradeProductFindOneResolve | IError<string>> {
+ const res = await tangle_db_trade_product_find_one(this.serialize(opts));
+ return this.deserialize<ITradeProductFindOneResolve>(res);
+ }
+
+ async trade_product_find_many(opts?: ITradeProductFindMany): Promise<ITradeProductFindManyResolve | IError<string>> {
+ const res = await tangle_db_trade_product_find_many(this.serialize(opts ?? {}));
+ return this.deserialize<ITradeProductFindManyResolve>(res);
+ }
+
+ async trade_product_delete(opts: ITradeProductDelete): Promise<ITradeProductDeleteResolve | IError<string>> {
+ const res = await tangle_db_trade_product_delete(this.serialize(opts));
+ return this.deserialize<ITradeProductDeleteResolve>(res);
+ }
+
+ async trade_product_update(opts: ITradeProductUpdate): Promise<ITradeProductUpdateResolve | IError<string>> {
+ const res = await tangle_db_trade_product_update(this.serialize(opts));
+ return this.deserialize<ITradeProductUpdateResolve>(res);
+ }
+
+ async farm_location_set(opts: IFarmLocationRelation): Promise<IFarmLocationResolve | IError<string>> {
+ const res = await tangle_db_farm_location_set(this.serialize(opts));
+ return this.deserialize<IFarmLocationResolve>(res);
+ }
+
+ async farm_location_unset(opts: IFarmLocationRelation): Promise<IFarmLocationResolve | IError<string>> {
+ const res = await tangle_db_farm_location_unset(this.serialize(opts));
+ return this.deserialize<IFarmLocationResolve>(res);
+ }
+
+ async nostr_profile_relay_set(opts: INostrProfileRelayRelation): Promise<INostrProfileRelayResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_relay_set(this.serialize(opts));
+ return this.deserialize<INostrProfileRelayResolve>(res);
+ }
+
+ async nostr_profile_relay_unset(opts: INostrProfileRelayRelation): Promise<INostrProfileRelayResolve | IError<string>> {
+ const res = await tangle_db_nostr_profile_relay_unset(this.serialize(opts));
+ return this.deserialize<INostrProfileRelayResolve>(res);
+ }
+
+ async trade_product_location_set(opts: ITradeProductLocationRelation): Promise<ITradeProductLocationResolve | IError<string>> {
+ const res = await tangle_db_trade_product_location_set(this.serialize(opts));
+ return this.deserialize<ITradeProductLocationResolve>(res);
+ }
+
+ async trade_product_location_unset(opts: ITradeProductLocationRelation): Promise<ITradeProductLocationResolve | IError<string>> {
+ const res = await tangle_db_trade_product_location_unset(this.serialize(opts));
+ return this.deserialize<ITradeProductLocationResolve>(res);
+ }
+
+ async trade_product_media_set(opts: ITradeProductMediaRelation): Promise<ITradeProductMediaResolve | IError<string>> {
+ const res = await tangle_db_trade_product_media_set(this.serialize(opts));
+ return this.deserialize<ITradeProductMediaResolve>(res);
+ }
+
+ async trade_product_media_unset(opts: ITradeProductMediaRelation): Promise<ITradeProductMediaResolve | IError<string>> {
+ const res = await tangle_db_trade_product_media_unset(this.serialize(opts));
+ return this.deserialize<ITradeProductMediaResolve>(res);
+ }
+
+}
diff --git a/client/tsconfig.cjs.json b/client/tsconfig.cjs.json
@@ -0,0 +1,16 @@
+{
+ "extends": "@radroots/tsconfig/tsconfig.esm.json",
+ "compilerOptions": {
+ "module": "CommonJS",
+ "moduleResolution": "Node",
+ "lib": ["dom", "ES2022"],
+ "rootDir": "./src",
+ "outDir": "dist/cjs",
+ "declaration": false,
+ "declarationMap": false,
+ "emitDeclarationOnly": false,
+ "tsBuildInfoFile": "node_modules/.cache/tsc.utils-nostr.cjs.tsbuildinfo"
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/client/tsconfig.esm.json b/client/tsconfig.esm.json
@@ -0,0 +1,14 @@
+{
+ "extends": "@radroots/tsconfig/tsconfig.esm.json",
+ "compilerOptions": {
+ "moduleResolution": "nodenext",
+ "lib": ["dom", "ES2022"],
+ "rootDir": "./src",
+ "outDir": "dist/esm",
+ "declaration": true,
+ "declarationMap": true,
+ "declarationDir": "dist/types"
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/client/tsconfig.json b/client/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "./tsconfig.esm.json"
+}