Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
217dc5f92b | ||
|
|
0b43530651 | ||
|
|
e0f6d7c72c | ||
|
|
9e78daeeba | ||
|
|
60aaf0cd96 | ||
|
|
90ab322332 | ||
|
|
eff782847d | ||
|
|
ed0458633b | ||
|
|
3edea4bdff | ||
|
|
2ac0afa691 | ||
|
|
cbe12bcd49 | ||
|
|
f21146e2f2 | ||
|
|
7972123887 | ||
|
|
630c451688 | ||
|
|
8559e023be | ||
|
|
75cb978fba | ||
|
|
8d318d5da4 | ||
|
|
d567655645 | ||
|
|
4fb4022188 | ||
|
|
256f12023e | ||
|
|
2840ddfc58 | ||
|
|
4b27a342d1 | ||
|
|
851d3b4876 | ||
|
|
ac57752ec2 | ||
|
|
ebfbbf9901 | ||
|
|
b866471825 | ||
|
|
f95b3c0d4a |
No files matched your search
@@ -0,0 +1,128 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
E-mail .
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
Generated
+732
-13
File diff suppressed because it is too large.
Load diff
@@ -6,3 +6,6 @@ members = [
|
||||
"server",
|
||||
"wasm"
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
license = "MIT OR Apache-2.0"
|
||||
+7
-3
@@ -4,7 +4,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN cargo build -p server --release
|
||||
RUN cargo build -p chronoseal-server --bin chronoseal --release
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
@@ -14,10 +14,14 @@ RUN apt-get update && apt-get install -y \
|
||||
|
||||
WORKDIR /opt/chronoseal
|
||||
|
||||
COPY --from=builder /app/target/release/server /usr/local/bin/chronoseal
|
||||
COPY --from=builder /app/target/release/chronoseal /usr/local/bin/chronoseal
|
||||
COPY frontend /usr/share/chronoseal/frontend
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
ENV RUST_LOG=info
|
||||
ENV CHRONOSEAL_DB_PATH=/var/lib/chronoseal/chronoseal.sqlite
|
||||
ENV CHRONOSEAL_FRONTEND_DIR=/usr/share/chronoseal/frontend
|
||||
ENV CHRONOSEAL_PID_FILE=/run/chronoseal.pid
|
||||
|
||||
CMD ["chronoseal"]
|
||||
CMD ["chronoseal", "run"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Sunil Purushottam Thakare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship made available under
|
||||
the License, as indicated by a copyright notice that is included in
|
||||
or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other transformations
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
||||
in the Work by the copyright owner or by an individual or Legal Entity
|
||||
authorized to submit on behalf of the copyright owner. For the purposes
|
||||
of this definition, "submit" means any form of electronic, verbal, or
|
||||
written communication sent to the Licensor or its representatives,
|
||||
including but not limited to communication on electronic mailing lists,
|
||||
source code control systems, and issue tracking systems that are managed
|
||||
by, or on behalf of, the Licensor for the purpose of submitting and
|
||||
discussing improvements to the Work, but excluding communication that is
|
||||
conspicuously marked or designated in writing by the copyright owner as
|
||||
"Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
||||
whom a Contribution has been received by the Licensor and included
|
||||
within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a cross-claim
|
||||
or counterclaim in a lawsuit) alleging that the Work or any
|
||||
Contribution embodied within the Work constitutes direct or
|
||||
contributory patent infringement, then any patent licenses granted to
|
||||
You under this License for that Work shall terminate as of the date
|
||||
such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works
|
||||
a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, You must include a readable copy of the attribution
|
||||
notices contained within such NOTICE file, in at least one of the
|
||||
following places: within a NOTICE text provided as part of the
|
||||
Derivative Works; within the Source form or documentation, if
|
||||
provided along with the Derivative Works; or, within a display
|
||||
generated by the Derivative Works, if and wherever such third-party
|
||||
notices normally appear. The contents of the NOTICE file are for
|
||||
informational purposes only and do not modify the License. You may
|
||||
add Your own attribution notices within Derivative Works that You
|
||||
distribute, alongside or as an addendum to the NOTICE text from
|
||||
the Work, provided that such additional attribution notices cannot
|
||||
be construed as modifying the License.
|
||||
|
||||
You may add Your own license statement for Your modifications and
|
||||
may provide additional grant of rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Work.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed
|
||||
to in writing, Licensor provides the Work (and each Contributor
|
||||
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
|
||||
OR CONDITIONS OF ANY KIND, either express or implied, including,
|
||||
without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
You are solely responsible for determining the appropriateness of using
|
||||
or redistributing the Work and assume any risks associated with Your
|
||||
exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or exemplary damages of any character arising as a result
|
||||
of this License or out of the use or inability to use the Work
|
||||
(including but not limited to damages for loss of goodwill, work
|
||||
stoppage, computer failure or malfunction, or all other commercial
|
||||
damages or losses), even if such Contributor has been advised of the
|
||||
possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Liability. While redistributing the Work or
|
||||
Derivative Works thereof, You may choose to offer, and charge a fee
|
||||
for, acceptance of support, warranty, indemnity, or other liability
|
||||
obligations and/or rights consistent with this License. However, in
|
||||
accepting such obligations, You may offer such obligations only on
|
||||
Your own behalf and on Your sole responsibility, not on behalf of
|
||||
any other Contributor, and only if You agree to indemnify, defend,
|
||||
and hold each Contributor harmless for any liability incurred by, or
|
||||
claims asserted against, such Contributor by reason of your accepting
|
||||
any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright (c) 2026 Sunil Thakare
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Sunil Purushottam Thakare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
-674
@@ -1,674 +0,0 @@
|
||||
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>.
|
||||
@@ -1,127 +1,332 @@
|
||||
# ChronoSeal
|
||||
|
||||
**Cryptographic anti-automation and browser attestation framework built with Rust, WASM, and behavioral continuity verification.**
|
||||
<p align="center">
|
||||
<img src="logo/chronoseal.svg" width="220" alt="ChronoSeal Logo">
|
||||
</p>
|
||||
|
||||
ChronoSeal makes it computationally expensive and operationally complex for AI scrapers, headless browsers, and automation tools to impersonate real users — while remaining completely invisible and frictionless to legitimate human visitors.
|
||||
<p align="center">
|
||||
<strong>Cryptographic attestation daemon and anti-automation framework.</strong>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Privacy-preserving • Unix-native • Lightweight • WASM-powered
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
ChronoSeal is a lightweight cryptographic attestation daemon designed to raise the operational cost of browser automation, scraping, replay attacks, and synthetic interaction.
|
||||
|
||||
ChronoSeal establishes a continuous, cryptographically verifiable proof-of-presence for every browser session. It is inspired by the heartbeat model used in IoT firmware (ESP32-class devices): the client must keep emitting signed, chained attestations, or the session is silently invalidated.
|
||||
Instead of relying on:
|
||||
|
||||
* CAPTCHA systems
|
||||
* invasive browser fingerprinting
|
||||
* telemetry-heavy tracking
|
||||
* persistent identifiers
|
||||
|
||||
ChronoSeal establishes a continuous cryptographic proof-of-runtime continuity using:
|
||||
|
||||
* WASM execution
|
||||
* chained cryptographic heartbeats
|
||||
* behavioral entropy validation
|
||||
* ephemeral attestation state
|
||||
|
||||
while remaining completely invisible and frictionless to legitimate human users.
|
||||
|
||||
---
|
||||
|
||||
# Features
|
||||
|
||||
* CLI-first Unix-native architecture
|
||||
* Rich operational subcommands
|
||||
* Machine-readable JSON/YAML outputs
|
||||
* Hardened systemd integration
|
||||
* Graceful shutdown and signal handling
|
||||
* One-line installation workflow
|
||||
* Prometheus-compatible metrics
|
||||
* WASM-based client runtime
|
||||
* Ed25519 + Blake3 cryptographic chaining
|
||||
* Behavioral entropy validation
|
||||
* Randomized stack-machine verification
|
||||
* Silent rejection model
|
||||
* SQLite-backed ephemeral sessions
|
||||
* Connection-pooled runtime architecture
|
||||
* Lightweight deployment footprint
|
||||
* Docker and native deployment support
|
||||
|
||||
---
|
||||
|
||||
# Quick Start
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
sudo bash scripts/install.sh
|
||||
```
|
||||
|
||||
## Check Status
|
||||
|
||||
```bash
|
||||
chronoseal status --format json
|
||||
```
|
||||
|
||||
## Health Probe
|
||||
|
||||
```bash
|
||||
chronoseal health
|
||||
```
|
||||
|
||||
## View Metrics
|
||||
|
||||
```bash
|
||||
chronoseal metrics
|
||||
```
|
||||
|
||||
## View Logs
|
||||
|
||||
```bash
|
||||
sudo journalctl -u chronoseal -f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# CLI
|
||||
|
||||
```bash
|
||||
chronoseal --help
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
| Command | Description |
|
||||
| ------------ | ------------------------------------------ |
|
||||
| `run` | Run the ChronoSeal daemon |
|
||||
| `status` | Report daemon status |
|
||||
| `health` | Perform daemon health probe |
|
||||
| `config` | Validate and print effective configuration |
|
||||
| `generate` | Generate operational material |
|
||||
| `metrics` | Output Prometheus metrics |
|
||||
| `stats` | Print runtime statistics |
|
||||
| `completion` | Generate shell completions |
|
||||
| `version` | Print version/build information |
|
||||
|
||||
---
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
chronoseal status --format json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"running": true,
|
||||
"healthy": true,
|
||||
"bind": "0.0.0.0:3000",
|
||||
"pid_file": "/run/chronoseal.pid",
|
||||
"pid": 79459
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# How It Works
|
||||
|
||||
ChronoSeal establishes a continuous cryptographic proof-of-presence for browser sessions.
|
||||
|
||||
The system is inspired by heartbeat validation models used in embedded and distributed systems.
|
||||
|
||||
## Session Flow
|
||||
|
||||
```text
|
||||
Browser Server
|
||||
│ │
|
||||
│ WASM loads, generates Ed25519 keypair │
|
||||
│ Private key never leaves WASM memory │
|
||||
│ │
|
||||
├──── POST /init { public_key } ──────────►│ Store session, salt, initial hash
|
||||
├──── POST /init { public_key } ──────────►│
|
||||
│◄─── { session_id, salt, opcodes, H0 } ────┤
|
||||
│ │
|
||||
│ Every 12–25s (jittered): │
|
||||
│ ┌─ Collect mouse entropy │
|
||||
│ ├─ Execute VM opcodes → stack state │
|
||||
│ ├─ Compute H(n) = Blake3(H(n-1) ║ …) │
|
||||
│ └─ Sign payload with Ed25519 │
|
||||
│ Every 12–25s (randomized): │
|
||||
│ ┌─ Collect behavioral entropy │
|
||||
│ ├─ Execute VM opcode program │
|
||||
│ ├─ Advance Blake3 hash chain │
|
||||
│ └─ Sign payload using Ed25519 │
|
||||
│ │
|
||||
├──── POST /hb { session_id, sig, … } ────►│ Verify sig → chain → behavior → fingerprint
|
||||
│◄─── { status, next_salt } ────────────────┤ Rotate salt, advance chain
|
||||
├──── POST /heartbeat { signed_payload } ─►│
|
||||
│◄─── { status, next_salt } ────────────────┤
|
||||
│ │
|
||||
│ On failure: server returns {"status":"ok"}│ Silent rejection — indistinguishable
|
||||
│ Invalid sessions silently rejected │
|
||||
```
|
||||
|
||||
The server validates:
|
||||
|
||||
* signature authenticity
|
||||
* heartbeat continuity
|
||||
* replay resistance
|
||||
* behavioral entropy
|
||||
* timestamp validity
|
||||
* fingerprint sanity
|
||||
|
||||
---
|
||||
|
||||
## Security Model
|
||||
# Security Model
|
||||
|
||||
### What ChronoSeal protects against
|
||||
## What ChronoSeal Protects Against
|
||||
|
||||
| Threat | Mechanism |
|
||||
|---|---|
|
||||
| Playwright / Puppeteer Stealth | Mouse entropy validation rejects synthetic or absent movement |
|
||||
| Replay attacks | Hash chain — each heartbeat references the previous hash; old payloads are invalid |
|
||||
| Signature forgery | Ed25519 private key generated inside WASM, never serialised or exposed to JS |
|
||||
| Clock manipulation | Server enforces ±30s timestamp window |
|
||||
| Credential sharing | Session is bound to a keypair generated fresh on every page load |
|
||||
| Flooding with fake sessions | Per-session rate limiting (5 req / 10s); stale entries evicted every 60s |
|
||||
| Passive analysis of traffic | Server always returns `{"status":"ok"}` — rejections are silent |
|
||||
|
||||
### What ChronoSeal does not claim
|
||||
|
||||
ChronoSeal is a cost-raising mechanism, not an impenetrable barrier. A sufficiently motivated adversary with a real browser, real input devices, and the patience to reverse the WASM can bypass it. The goal is to make scraping expensive and operationally complex enough to be impractical at scale.
|
||||
| Threat | Mechanism |
|
||||
| ------------------------ | ------------------------------------- |
|
||||
| Replay attacks | Blake3 chained heartbeat continuity |
|
||||
| Signature forgery | Ed25519 keypair generated inside WASM |
|
||||
| Session cloning | Ephemeral session-bound keypairs |
|
||||
| Static scraping | Runtime participation requirements |
|
||||
| Naive browser automation | Behavioral continuity validation |
|
||||
| Timestamp replay | Drift-window enforcement |
|
||||
| Session flooding | Per-session rate limiting |
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
## Silent Rejection Model
|
||||
|
||||
```
|
||||
chronoseal-rs/
|
||||
├── shared/ Shared types, Blake3 hash-chain logic, constants
|
||||
├── server/ Axum HTTP server
|
||||
│ ├── routes/ /init and /hb handlers
|
||||
│ ├── session.rs Session lifecycle: create, verify, advance chain
|
||||
│ ├── crypto.rs Ed25519 signature verification (BTreeMap canonical JSON)
|
||||
│ ├── trust.rs Behavioral signal validation (mouse speed, pauses)
|
||||
│ ├── fingerprint Browser fingerprint sanity checks
|
||||
│ ├── vm.rs Random opcode program generator
|
||||
│ ├── ratelimit.rs Token-bucket rate limiter with periodic eviction
|
||||
│ └── cleanup.rs Background task: expire sessions + evict rate limiter
|
||||
├── wasm/ Rust → WASM client module
|
||||
│ ├── crypto.rs Ed25519 keypair, signing, hash computation
|
||||
│ └── vm.rs Stack machine executor (PUSH/ADD/SUB/MUL/XOR/AND/OR/ROT/NOT/HASH)
|
||||
└── frontend/ Vanilla JS glue
|
||||
├── heartbeat.js Session init, heartbeat scheduling, chain advancement
|
||||
└── entropy.js Mouse event collection
|
||||
```
|
||||
ChronoSeal intentionally avoids explicit rejection semantics.
|
||||
|
||||
### Stack Machine
|
||||
|
||||
The server generates a random program (8–16 opcodes) on session init. The client executes it on every heartbeat and includes the resulting stack state in the signed payload. This makes each heartbeat structurally unique without requiring any server round-trip.
|
||||
|
||||
| Opcode | Mnemonic | Effect |
|
||||
|--------|----------|--------|
|
||||
| `0x00` | PUSH u32 | Push 4-byte little-endian literal |
|
||||
| `0x01` | ADD | Pop 2, push `a + b` (wrapping) |
|
||||
| `0x02` | SUB | Pop 2, push `a - b` (wrapping) |
|
||||
| `0x03` | MUL | Pop 2, push `a * b` (wrapping) |
|
||||
| `0x04` | XOR | Pop 2, push `a ^ b` |
|
||||
| `0x05` | AND | Pop 2, push `a & b` |
|
||||
| `0x06` | OR | Pop 2, push `a \| b` |
|
||||
| `0x07` | ROT | Pop 2, push `a.rotate_left(b % 32)` |
|
||||
| `0x08` | NOT | Pop 1, push `!a` (unary) |
|
||||
| `0x09` | HASH | Blake3 of entire stack → single u32 |
|
||||
|
||||
### Hash Chain
|
||||
|
||||
```
|
||||
H(0) = Blake3( session_id ║ pub_key ║ salt₀ )
|
||||
|
||||
H(n) = Blake3( saltₙ₋₁ ║ H(n-1) ║ timestamp ║ Blake3(entropy_json) ║ Blake3(stack_json) )
|
||||
```
|
||||
|
||||
Each heartbeat must present `H(n-1)` matching what the server stored. Forging a valid `H(n)` requires knowing the private key (for the signature), the salt (server-side only), and all prior state.
|
||||
|
||||
### Signature Canonical Form
|
||||
|
||||
The client signs a JSON object with keys sorted alphabetically (matching `JSON.stringify(obj, Object.keys(obj).sort())`):
|
||||
Invalid sessions may still receive:
|
||||
|
||||
```json
|
||||
{
|
||||
"entropyData": { "events": [ { "x": …, "y": …, "t": … } ] },
|
||||
"fingerprint": { "aspectRatio": "…", "devicePixelRatio": "…", "hardwareConcurrency": … },
|
||||
"prevHash": "hex…",
|
||||
"sessionId": "hex…",
|
||||
"stackState": { "stack": […], "ip": … },
|
||||
"timestamp": 1234567890123
|
||||
}
|
||||
{ "status": "ok" }
|
||||
```
|
||||
|
||||
The server reconstructs this using `BTreeMap` (alphabetical key order) before calling `VerifyingKey::verify_strict`.
|
||||
This prevents:
|
||||
|
||||
* oracle-style probing
|
||||
* protocol learning
|
||||
* easy automation tuning
|
||||
* behavioral enumeration
|
||||
|
||||
---
|
||||
|
||||
## SQLite Schema
|
||||
## What ChronoSeal Does Not Claim
|
||||
|
||||
ChronoSeal is a cost-raising mechanism, not an impenetrable barrier.
|
||||
|
||||
A sufficiently motivated adversary with:
|
||||
|
||||
* real browsers
|
||||
* genuine input devices
|
||||
* enough reverse engineering effort
|
||||
|
||||
can eventually bypass the system.
|
||||
|
||||
The goal is to make automation:
|
||||
|
||||
* expensive
|
||||
* operationally complex
|
||||
* difficult to scale
|
||||
* harder to replay deterministically
|
||||
|
||||
---
|
||||
|
||||
# Architecture
|
||||
|
||||
```text
|
||||
chronoseal-rs/
|
||||
├── shared/ Shared types, constants, hash-chain logic
|
||||
├── server/ Axum HTTP daemon
|
||||
│ ├── routes/ API routes
|
||||
│ ├── session.rs Session lifecycle management
|
||||
│ ├── crypto.rs Ed25519 verification
|
||||
│ ├── trust.rs Behavioral validation
|
||||
│ ├── fingerprint/ Browser sanity validation
|
||||
│ ├── vm.rs Random opcode generator
|
||||
│ ├── ratelimit.rs Token bucket limiter
|
||||
│ ├── cleanup.rs Session expiration lifecycle
|
||||
│ └── metrics.rs Prometheus metrics
|
||||
├── wasm/ Rust → WASM runtime
|
||||
│ ├── crypto.rs Signing + hash chaining
|
||||
│ └── vm.rs Stack-machine executor
|
||||
├── frontend/ Lightweight JS integration
|
||||
├── scripts/ Build/install/dev scripts
|
||||
└── docs/ Project documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Stack Machine
|
||||
|
||||
ChronoSeal includes a lightweight randomized stack-machine execution engine.
|
||||
|
||||
The server generates a randomized opcode program during session initialization.
|
||||
|
||||
The client executes this program on every heartbeat and includes the resulting stack state in the signed payload.
|
||||
|
||||
This makes heartbeat payloads structurally dynamic.
|
||||
|
||||
## Supported Opcodes
|
||||
|
||||
| Opcode | Mnemonic | Effect |
|
||||
| ------ | -------- | ----------------------- |
|
||||
| `0x00` | PUSH | Push literal |
|
||||
| `0x01` | ADD | Wrapping addition |
|
||||
| `0x02` | SUB | Wrapping subtraction |
|
||||
| `0x03` | MUL | Wrapping multiplication |
|
||||
| `0x04` | XOR | Bitwise XOR |
|
||||
| `0x05` | AND | Bitwise AND |
|
||||
| `0x06` | OR | Bitwise OR |
|
||||
| `0x07` | ROT | Rotate left |
|
||||
| `0x08` | NOT | Unary inversion |
|
||||
| `0x09` | HASH | Blake3 stack hash |
|
||||
|
||||
---
|
||||
|
||||
# Hash Chain
|
||||
|
||||
ChronoSeal uses Blake3 chained continuity validation.
|
||||
|
||||
## Initial Hash
|
||||
|
||||
```text
|
||||
H(0) = Blake3( session_id ║ public_key ║ salt₀ )
|
||||
```
|
||||
|
||||
## Heartbeat Progression
|
||||
|
||||
```text
|
||||
H(n) = Blake3(
|
||||
saltₙ₋₁ ║
|
||||
H(n-1) ║
|
||||
timestamp ║
|
||||
Blake3(entropy_json) ║
|
||||
Blake3(stack_json)
|
||||
)
|
||||
```
|
||||
|
||||
Each heartbeat depends on:
|
||||
|
||||
* prior continuity
|
||||
* prior server-issued salt
|
||||
* behavioral entropy
|
||||
* VM execution result
|
||||
* timestamp progression
|
||||
|
||||
---
|
||||
|
||||
# Signature Canonicalization
|
||||
|
||||
Heartbeat payloads are serialized into canonical key order before signing.
|
||||
|
||||
The server reconstructs payloads identically before:
|
||||
|
||||
* Ed25519 verification
|
||||
* hash progression validation
|
||||
|
||||
This prevents:
|
||||
|
||||
* serialization inconsistencies
|
||||
* ambiguous signing layouts
|
||||
* malformed payload tricks
|
||||
|
||||
---
|
||||
|
||||
# SQLite Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
@@ -136,101 +341,196 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
);
|
||||
```
|
||||
|
||||
Sessions are stored in an in-memory SQLite database. All session state is lost on server restart by design — clients re-initialise transparently.
|
||||
ChronoSeal intentionally uses ephemeral session persistence.
|
||||
|
||||
Session continuity is designed to reset transparently.
|
||||
|
||||
---
|
||||
|
||||
## Build
|
||||
# Runtime Architecture
|
||||
|
||||
### Prerequisites
|
||||
## Server Runtime
|
||||
|
||||
- Rust stable (≥ 1.87)
|
||||
- [`wasm-pack`](https://rustwasm.github.io/wasm-pack/installer/)
|
||||
* Rust
|
||||
* Axum
|
||||
* Tokio
|
||||
* SQLite
|
||||
* `r2d2`
|
||||
* `thiserror`
|
||||
|
||||
### WASM
|
||||
## Browser Runtime
|
||||
|
||||
```bash
|
||||
wasm-pack build wasm --target web --release
|
||||
mv wasm/pkg frontend/pkg
|
||||
```
|
||||
|
||||
### Server
|
||||
|
||||
```bash
|
||||
cargo build -p server --release
|
||||
```
|
||||
|
||||
### Dev (all-in-one)
|
||||
|
||||
```bash
|
||||
bash scripts/dev.sh
|
||||
```
|
||||
|
||||
The server serves the `frontend/` directory statically at `/` and the API at `/init` and `/hb`.
|
||||
* Rust → WASM
|
||||
* Ed25519 signing
|
||||
* Blake3 chaining
|
||||
* stack-machine execution
|
||||
|
||||
---
|
||||
|
||||
## Deployment
|
||||
# Deployment
|
||||
|
||||
### Native + systemd
|
||||
## Recommended Installation
|
||||
|
||||
```bash
|
||||
cargo build -p server --release
|
||||
sudo cp target/release/server /usr/local/bin/chronoseal
|
||||
sudo bash scripts/install.sh
|
||||
```
|
||||
|
||||
The installer:
|
||||
|
||||
* creates `chronoseal` service user
|
||||
* builds release artifacts
|
||||
* installs frontend assets
|
||||
* deploys hardened systemd service
|
||||
* enables and starts daemon
|
||||
|
||||
---
|
||||
|
||||
## Manual Installation
|
||||
|
||||
```bash
|
||||
bash scripts/build.sh
|
||||
|
||||
sudo cp target/release/chronoseal /usr/local/bin/
|
||||
sudo cp chronoseal.service /etc/systemd/system/
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chronoseal
|
||||
```
|
||||
|
||||
### Docker
|
||||
---
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### Reverse Proxy
|
||||
|
||||
Place ChronoSeal behind nginx, Nginx Proxy Manager, or HAProxy. Enable:
|
||||
|
||||
- TLS 1.3
|
||||
- HTTP/2
|
||||
- Aggressive upstream timeouts (the heartbeat interval is 12–25s)
|
||||
|
||||
---
|
||||
|
||||
## Integration
|
||||
# Development
|
||||
|
||||
Drop two lines into any protected page:
|
||||
## Full Build
|
||||
|
||||
```html
|
||||
<script type="module" src="/pkg/antibot_wasm.js"></script>
|
||||
<script type="module" src="/main.js"></script>
|
||||
```bash
|
||||
bash scripts/build.sh
|
||||
```
|
||||
|
||||
`main.js` calls `initHeartbeat()` which handles WASM loading, session init, and schedules all subsequent heartbeats automatically. There is no visible UI, no CAPTCHA, no user interaction required.
|
||||
## Development Mode
|
||||
|
||||
```bash
|
||||
bash scripts/dev.sh
|
||||
```
|
||||
|
||||
## Direct Execution
|
||||
|
||||
```bash
|
||||
cargo run -p server -- run --bind 127.0.0.1:3000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
# Prerequisites
|
||||
|
||||
All tunable constants are in `shared/src/constants.rs`:
|
||||
* Rust stable ≥ 1.87
|
||||
* `wasm-pack`
|
||||
|
||||
| Constant | Default | Description |
|
||||
|---|---|---|
|
||||
| `SESSION_ID_LEN` | 32 bytes | Session ID entropy |
|
||||
| `SALT_LEN` | 16 bytes | Per-heartbeat salt size |
|
||||
| `HEARTBEAT_MIN_INTERVAL_MS` | 12 000 ms | Minimum heartbeat interval |
|
||||
| `HEARTBEAT_MAX_INTERVAL_MS` | 25 000 ms | Maximum heartbeat interval (uniform jitter) |
|
||||
| `EXPIRATION_MINUTES` | 30 min | Session lifetime after last heartbeat |
|
||||
| `RATE_LIMIT_COUNT` | 5 | Max heartbeats per window |
|
||||
| `RATE_LIMIT_WINDOW_SECS` | 10 s | Rate limit window |
|
||||
| `MAX_TIMESTAMP_DRIFT_MS` | 30 000 ms | Anti-replay timestamp window |
|
||||
| `MIN_MOUSE_TOTAL_DIST` | 10.0 px | Minimum cumulative mouse travel |
|
||||
| `MAX_MOUSE_AVG_SPEED` | 2.0 px/ms | Maximum average mouse speed |
|
||||
| `MIN_PAUSE_COUNT` | 1 | Minimum mouse pause events |
|
||||
Install:
|
||||
|
||||
```bash
|
||||
cargo install wasm-pack
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
# Configuration
|
||||
|
||||
[GPL-3.0](LICENSE.md)
|
||||
## Precedence
|
||||
|
||||
```text
|
||||
CLI flags > CHRONOSEAL_* environment variables > config file > defaults
|
||||
```
|
||||
|
||||
## Default Config Locations
|
||||
|
||||
```text
|
||||
/etc/chronoseal/config.toml
|
||||
$XDG_CONFIG_HOME/chronoseal/config.toml
|
||||
~/.config/chronoseal/config.toml
|
||||
```
|
||||
|
||||
## Runtime State
|
||||
|
||||
```text
|
||||
~/.local/state/chronoseal/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Observability
|
||||
|
||||
ChronoSeal exposes:
|
||||
|
||||
* health probes
|
||||
* runtime statistics
|
||||
* Prometheus metrics
|
||||
|
||||
## Metrics Example
|
||||
|
||||
```bash
|
||||
chronoseal metrics
|
||||
```
|
||||
|
||||
```text
|
||||
# HELP chronoseal_sessions Active ChronoSeal sessions
|
||||
# TYPE chronoseal_sessions gauge
|
||||
chronoseal_sessions 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Lightweight Runtime
|
||||
|
||||
Current release artifacts:
|
||||
|
||||
```text
|
||||
chronoseal ~8.5 MB
|
||||
chronoseal_wasm.wasm ~719 KB
|
||||
```
|
||||
|
||||
ChronoSeal intentionally avoids:
|
||||
|
||||
* heavyweight frontend frameworks
|
||||
* Electron-style packaging
|
||||
* telemetry-heavy dependencies
|
||||
* oversized runtime models
|
||||
|
||||
---
|
||||
|
||||
# Philosophy
|
||||
|
||||
ChronoSeal is intentionally not:
|
||||
|
||||
* a surveillance framework
|
||||
* invasive browser fingerprinting
|
||||
* a CAPTCHA replacement
|
||||
* a telemetry ecosystem
|
||||
|
||||
ChronoSeal is:
|
||||
|
||||
* a cryptographic attestation runtime
|
||||
* a behavioral continuity engine
|
||||
* a proof-of-runtime framework
|
||||
* a lightweight Unix-native daemon
|
||||
|
||||
---
|
||||
|
||||
# License
|
||||
|
||||
[MIT OR Apache-2.0](LICENSE)
|
||||
|
||||
---
|
||||
|
||||
# Project
|
||||
|
||||
GitHub:
|
||||
https://github.com/thakares/chronoseal-rs
|
||||
+20
-19
@@ -1,35 +1,36 @@
|
||||
[Unit]
|
||||
Description=ChronoSeal Anti-Bot Service
|
||||
Description=ChronoSeal Cryptographic Attestation Daemon
|
||||
After=network.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
|
||||
User=chronoseal
|
||||
Group=chronoseal
|
||||
|
||||
ExecStart=/usr/local/bin/chronoseal run
|
||||
WorkingDirectory=/opt/chronoseal
|
||||
|
||||
ExecStart=/usr/local/bin/chronoseal
|
||||
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
Environment=RUST_LOG=info
|
||||
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
# Hardening (production-grade)
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
|
||||
MemoryDenyWriteExecute=true
|
||||
RestrictRealtime=true
|
||||
RestrictSUIDSGID=true
|
||||
|
||||
LockPersonality=true
|
||||
|
||||
ProtectHome=yes
|
||||
NoNewPrivileges=yes
|
||||
PrivateTmp=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
MemoryDenyWriteExecute=yes
|
||||
RestrictRealtime=yes
|
||||
RestrictSUIDSGID=yes
|
||||
LockPersonality=yes
|
||||
SystemCallArchitectures=native
|
||||
ReadWritePaths=/run/chronoseal.pid
|
||||
|
||||
# Logging
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
# ChronoSeal — API Reference
|
||||
|
||||
## Base URL
|
||||
|
||||
All endpoints are relative to the server root. In development: `http://localhost:3000`.
|
||||
In production: your HTTPS domain via reverse proxy.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `POST /init`
|
||||
|
||||
Initialise a new session. Called once per page load, immediately after the
|
||||
WASM module generates an Ed25519 keypair.
|
||||
|
||||
#### Request
|
||||
|
||||
```http
|
||||
POST /init
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"public_key": "hex-encoded 32-byte Ed25519 verifying key"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|---|---|---|
|
||||
| `public_key` | `string` | Hex-encoded 32-byte Ed25519 verifying key generated by the WASM module |
|
||||
|
||||
#### Response `200 OK`
|
||||
|
||||
```json
|
||||
{
|
||||
"session_id": "64-char hex string (32 bytes)",
|
||||
"salt": "32-char hex string (16 bytes)",
|
||||
"opcodes_b64": "base64-encoded VM program (8–16 opcodes)",
|
||||
"initial_hash": "64-char hex string (32 bytes Blake3)",
|
||||
"expires_at": 1234567890123
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|---|---|---|
|
||||
| `session_id` | `string` | Opaque session identifier; include in every heartbeat |
|
||||
| `salt` | `string` | Initial salt; used to compute `H(0)` and first `H(1)` |
|
||||
| `opcodes_b64` | `string` | Base64 VM program; execute with `run_program()` on every heartbeat |
|
||||
| `initial_hash` | `string` | `H(0) = Blake3(session_id ║ pub_key ║ salt)`; the first `prev_hash` |
|
||||
| `expires_at` | `number` | Unix timestamp in milliseconds; session expires after 30 minutes of inactivity |
|
||||
|
||||
#### Error
|
||||
|
||||
Returns `500 Internal Server Error` only on server-side failures (DB errors,
|
||||
invalid public key length). No meaningful error body is returned.
|
||||
|
||||
---
|
||||
|
||||
### `POST /hb`
|
||||
|
||||
Submit a heartbeat. Called every 12–25 seconds with uniform random jitter.
|
||||
|
||||
#### Request
|
||||
|
||||
```http
|
||||
POST /hb
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"session_id": "64-char hex",
|
||||
"prev_hash": "64-char hex",
|
||||
"timestamp": 1234567890123,
|
||||
"entropy_data": {
|
||||
"events": [
|
||||
{ "x": 412.0, "y": 308.5, "t": 1234.567 },
|
||||
{ "x": 415.2, "y": 310.1, "t": 1285.123 }
|
||||
]
|
||||
},
|
||||
"stack_state": {
|
||||
"stack": [2971406957, 1234567890],
|
||||
"ip": 42
|
||||
},
|
||||
"fingerprint": {
|
||||
"aspectRatio": "1.7777777778",
|
||||
"devicePixelRatio": "2",
|
||||
"hardwareConcurrency": 8
|
||||
},
|
||||
"signature": "128-char hex Ed25519 signature"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|---|---|---|
|
||||
| `session_id` | `string` | Session ID from `/init` |
|
||||
| `prev_hash` | `string` | Hash chain head from previous heartbeat (or `initial_hash` for the first) |
|
||||
| `timestamp` | `number` | `Date.now()` in milliseconds; must be within ±30s of server time |
|
||||
| `entropy_data.events` | `array` | Mouse events since previous heartbeat; each has `x`, `y` (px), `t` (performance.now ms) |
|
||||
| `stack_state.stack` | `array` | `u32[]` result of executing the VM program |
|
||||
| `stack_state.ip` | `number` | Instruction pointer after execution |
|
||||
| `fingerprint.aspectRatio` | `string` | `(screen.width / screen.height).toFixed(10)` |
|
||||
| `fingerprint.devicePixelRatio` | `string` | `String(window.devicePixelRatio)` |
|
||||
| `fingerprint.hardwareConcurrency` | `number` | `navigator.hardwareConcurrency \|\| 1` |
|
||||
| `signature` | `string` | Hex-encoded 64-byte Ed25519 signature over the canonical payload |
|
||||
|
||||
#### Canonical Signing Payload
|
||||
|
||||
The client signs the following JSON object. Top-level keys must be sorted
|
||||
alphabetically. Nested object keys follow their natural serialisation order.
|
||||
|
||||
```json
|
||||
{
|
||||
"entropyData": { "events": [{ "t": …, "x": …, "y": … }] },
|
||||
"fingerprint": { "aspectRatio": "…", "devicePixelRatio": "…", "hardwareConcurrency": … },
|
||||
"prevHash": "…",
|
||||
"sessionId": "…",
|
||||
"stackState": { "ip": …, "stack": […] },
|
||||
"timestamp": …
|
||||
}
|
||||
```
|
||||
|
||||
Note: field names in the signing payload use camelCase (`sessionId`,
|
||||
`prevHash`, `entropyData`, `stackState`) while the request body uses
|
||||
snake_case (`session_id`, `prev_hash`, `entropy_data`, `stack_state`).
|
||||
|
||||
#### Response `200 OK` — Accepted
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"next_salt": "32-char hex string (16 bytes)"
|
||||
}
|
||||
```
|
||||
|
||||
The client must:
|
||||
1. Capture `sentSalt = currentSalt` before updating.
|
||||
2. Set `currentSalt = next_salt`.
|
||||
3. Compute `prevHash = compute_next_hash(prevHash, timestamp, entropyJson, stackStateJson, sentSalt)`.
|
||||
|
||||
#### Response `200 OK` — Rejected
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok"
|
||||
}
|
||||
```
|
||||
|
||||
`next_salt` is absent. The response body is intentionally identical in
|
||||
structure. Rejections are silent — the caller cannot distinguish a validation
|
||||
failure from a rate limit hit or an expired session.
|
||||
|
||||
The client should log a warning and continue scheduling heartbeats (they will
|
||||
continue to fail until the page is reloaded and a new session is established).
|
||||
|
||||
---
|
||||
|
||||
## Validation Rules (Server-Side)
|
||||
|
||||
Heartbeats are rejected (silently) if any of the following checks fail:
|
||||
|
||||
| Check | Condition for rejection |
|
||||
|---|---|
|
||||
| Rate limit | > 5 requests per 10-second window for this `session_id` |
|
||||
| Session not found | `session_id` not in SQLite |
|
||||
| Session expired | `current_time_ms > expires_at` |
|
||||
| Signature invalid | Ed25519 verification fails against stored public key |
|
||||
| Hash chain broken | `hex(prev_hash) ≠ stored last_hash` |
|
||||
| Timestamp drift | `\|server_now_ms - timestamp\| > 30 000` |
|
||||
| Insufficient mouse events | `events.len() < 3` |
|
||||
| Insufficient mouse distance | `total_dist < 10.0 px` |
|
||||
| Mouse speed too high | `total_dist / total_time_ms > 2.0 px/ms` |
|
||||
| No mouse pauses | `pause_count < 1` |
|
||||
| Invalid aspect ratio | `ar < 0.5` or `ar > 3.0` |
|
||||
| Invalid devicePixelRatio | `dpr ≤ 0.0` or `dpr > 5.0` |
|
||||
| Zero hardwareConcurrency | `hardware_concurrency == 0` |
|
||||
|
||||
---
|
||||
|
||||
## Hash Chain Specification
|
||||
|
||||
```
|
||||
H(0) = Blake3( session_id_bytes ║ pub_key_bytes ║ salt₀_bytes )
|
||||
|
||||
H(n) = Blake3(
|
||||
saltₙ₋₁_bytes
|
||||
║ H(n-1)_bytes
|
||||
║ timestamp_u64_le_bytes
|
||||
║ Blake3( UTF-8( JSON(entropy_data) ) )
|
||||
║ Blake3( UTF-8( JSON(stack_state) ) )
|
||||
)
|
||||
```
|
||||
|
||||
All inputs are concatenated in the order shown. `timestamp` is encoded as a
|
||||
64-bit unsigned integer in little-endian byte order. JSON serialisation of
|
||||
`entropy_data` and `stack_state` uses the field order defined by the shared
|
||||
Rust types (serde derive, no custom ordering).
|
||||
|
||||
---
|
||||
|
||||
## WASM API
|
||||
|
||||
The WASM module (`antibot_wasm`) exports the following functions to JavaScript:
|
||||
|
||||
| Function | Signature | Description |
|
||||
|---|---|---|
|
||||
| `generate_keypair()` | `() → string` | Generate Ed25519 keypair; return hex public key. Private key stored in WASM memory. |
|
||||
| `get_public_key()` | `() → string` | Return hex public key, or `""` if not initialised. |
|
||||
| `sign_message(msg)` | `(string) → string` | Sign UTF-8 string; return hex signature, or `""` if not initialised. |
|
||||
| `compute_next_hash(prev, ts, entropy, stack, salt)` | `(string, u64, string, string, string) → string` | Compute next Blake3 chain hash; all inputs/output hex or JSON strings. |
|
||||
| `run_program(b64)` | `(string) → JsValue` | Execute base64 VM program; return `{ stack: u32[], ip: number }`. |
|
||||
|
||||
All functions return empty strings on error rather than panicking.
|
||||
Callers must check for empty return values before using the result.
|
||||
+370
-25
@@ -1,36 +1,381 @@
|
||||
# ChronoSeal Architecture
|
||||
# ChronoSeal — Architecture
|
||||
|
||||
## Core Principles
|
||||
## Overview
|
||||
|
||||
- Continuous browser attestation
|
||||
- Cryptographic heartbeat chains
|
||||
- WASM-isolated secrets
|
||||
- Behavioral entropy verification
|
||||
- Silent mitigation
|
||||
ChronoSeal is a stateless, cryptographic browser attestation framework. Its
|
||||
purpose is to make automated clients (headless browsers, AI scrapers, API
|
||||
harvesters) computationally expensive and operationally complex to operate,
|
||||
while remaining completely invisible to real human users.
|
||||
|
||||
## Components
|
||||
The design is inspired by the heartbeat model used in embedded IoT firmware:
|
||||
a device that stops sending signed, chained attestations is assumed to be
|
||||
offline or compromised. ChronoSeal applies the same principle to browser
|
||||
sessions.
|
||||
|
||||
### WASM Runtime
|
||||
---
|
||||
|
||||
Responsible for:
|
||||
- heartbeat generation
|
||||
- signature generation
|
||||
- entropy collection
|
||||
- VM execution
|
||||
## Design Principles
|
||||
|
||||
### Server
|
||||
**Stateless per request.** The server carries no per-request state beyond what
|
||||
is stored in SQLite keyed on `session_id`. Every HTTP request is independently
|
||||
verifiable.
|
||||
|
||||
Responsible for:
|
||||
- session verification
|
||||
- trust scoring
|
||||
- chain validation
|
||||
- mitigation
|
||||
**Silent failure.** Validation failures never return an error status or an
|
||||
error body. The server always responds `{"status":"ok"}` and simply omits
|
||||
`next_salt`. The client degrades gracefully. Attackers cannot enumerate
|
||||
validation rules by probing error responses.
|
||||
|
||||
**Private key isolation.** The Ed25519 signing key is generated inside the
|
||||
WASM module and never serialised, never exposed to the JavaScript environment,
|
||||
and never transmitted. It exists only in WASM linear memory for the lifetime
|
||||
of the page.
|
||||
|
||||
**Layered validation.** A heartbeat must pass five independent checks: session
|
||||
existence, expiry, signature, hash chain, and behavioral signals. Bypassing
|
||||
one layer is not sufficient.
|
||||
|
||||
**Cost asymmetry.** Each heartbeat requires a real browser environment, mouse
|
||||
activity, correct WASM execution, chain state synchronisation, and a valid
|
||||
Ed25519 signature over a time-windowed payload. For an automated client, the
|
||||
synchronisation burden alone makes scaled operation expensive.
|
||||
|
||||
### High-Level Design
|
||||
|
||||
- **Core**: Rust + Axum (async web framework)
|
||||
- **Storage**: In-memory SQLite (fast, ephemeral per process — restarts are clean)
|
||||
- **Client**: WASM + Rust (runs in browser for proof generation)
|
||||
- **Security Model**: Behavioral analysis + hash chaining + entropy scoring
|
||||
- **Deployment**: Static musl binary, systemd service, optional Docker
|
||||
|
||||
### Key Components
|
||||
|
||||
- `shared/` — Types, constants, crypto primitives used by server and WASM
|
||||
- `server/` — Axum routes, session management, trust engine, rate limiting, cleanup tasks
|
||||
- `wasm/` — Client-side proof generation
|
||||
- `frontend/` — Static assets served by the application
|
||||
|
||||
### Unix-Native Design Decisions
|
||||
|
||||
- Runs as a proper systemd service with strict sandboxing
|
||||
- All state is either in-memory or in standard locations (`/run/`, `/var/log/`, `/etc/`)
|
||||
- Graceful shutdown and reload support via signals
|
||||
- Logging designed for `journalctl` and structured parsing
|
||||
- Configuration will be fully runtime (no recompile needed)
|
||||
|
||||
### Design Goal
|
||||
|
||||
ChronoSeal should feel as natural to use as `nginx` or `redis-server` on a Linux system.
|
||||
---
|
||||
|
||||
## Component Map
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Browser │
|
||||
│ │
|
||||
│ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │
|
||||
│ │ entropy.js │ │ heartbeat.js │ │ transport.js│ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ mousemove │──►│ orchestrates │──►│ fetch POST │ │
|
||||
│ │ event ring │ │ init + HB │ │ /init /hb │ │
|
||||
│ └─────────────┘ └──────┬───────┘ └─────────────┘ │
|
||||
│ │ │
|
||||
│ ┌──────▼───────────────────────┐ │
|
||||
│ │ WASM Module (antibot_wasm) │ │
|
||||
│ │ │ │
|
||||
│ │ crypto.rs vm.rs │ │
|
||||
│ │ ├ generate_keypair() │ │
|
||||
│ │ ├ sign_message() │ │
|
||||
│ │ ├ compute_next_hash() │ │
|
||||
│ │ └ run_program() │ │
|
||||
│ └──────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
│ HTTPS
|
||||
┌─────────────────────────▼───────────────────────────────┐
|
||||
│ Server (Axum) │
|
||||
│ │
|
||||
│ routes/init.rs routes/heartbeat.rs │
|
||||
│ │ │ │
|
||||
│ └──────────┬───────────────┘ │
|
||||
│ ▼ │
|
||||
│ session.rs │
|
||||
│ ├ create_session() │
|
||||
│ └ verify_heartbeat() │
|
||||
│ │ │
|
||||
│ ┌──────────┼──────────────┐ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ crypto.rs trust.rs fingerprint.rs │
|
||||
│ (sig verify) (mouse (aspect ratio, │
|
||||
│ speed) DPR, HW conc.) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ shared::hashing (Blake3 hash chain) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ storage.rs (in-memory SQLite) │
|
||||
│ │
|
||||
│ ratelimit.rs cleanup.rs vm.rs middleware.rs │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Session Lifecycle
|
||||
|
||||
### 1. Initialisation — `POST /init`
|
||||
|
||||
```
|
||||
Client Server
|
||||
│ │
|
||||
│ generate Ed25519 keypair (in WASM) │
|
||||
│ pub_key = verifying_key.to_bytes() │
|
||||
│ │
|
||||
├─── { public_key: hex(pub_key) } ──────►│
|
||||
│ │ session_id = rand::random::<[u8;32]>()
|
||||
│ │ salt₀ = rand::random::<[u8;16]>()
|
||||
│ │ H(0) = Blake3(session_id║pub_key║salt₀)
|
||||
│ │ opcodes = generate_random_program(8..=16)
|
||||
│ │ INSERT INTO sessions …
|
||||
│ │
|
||||
│◄── { session_id, salt, opcodes_b64, │
|
||||
│ initial_hash, expires_at } ───────┤
|
||||
│ │
|
||||
│ prevHash = initial_hash │
|
||||
│ currentSalt = salt │
|
||||
│ opcodesB64 = opcodes_b64 │
|
||||
```
|
||||
|
||||
### 2. Heartbeat — `POST /hb`
|
||||
|
||||
Fired every 12–25 seconds with uniform random jitter.
|
||||
|
||||
```
|
||||
Client Server
|
||||
│ │
|
||||
│ stackState = run_program(opcodesB64) │
|
||||
│ events = collectEntropy(lastTime) │
|
||||
│ ts = Date.now() │
|
||||
│ │
|
||||
│ signable = { │
|
||||
│ entropyData, fingerprint, │ ← keys sorted alphabetically
|
||||
│ prevHash, sessionId, │
|
||||
│ stackState, timestamp │
|
||||
│ } │
|
||||
│ sig = sign_message( │
|
||||
│ JSON.stringify(signable, keys.sort))│
|
||||
│ │
|
||||
├─── { session_id, prev_hash, timestamp, │
|
||||
│ entropy_data, stack_state, │
|
||||
│ fingerprint, signature } ────────►│
|
||||
│ │ 1. Rate limit check
|
||||
│ │ 2. Lookup session, check expiry
|
||||
│ │ 3. Verify Ed25519 signature
|
||||
│ │ 4. Verify hash chain continuity
|
||||
│ │ 5. Validate timestamp window ±30s
|
||||
│ │ 6. Validate mouse behavior
|
||||
│ │ 7. Validate fingerprint signals
|
||||
│ │ 8. Compute H(n), rotate salt
|
||||
│ │ 9. UPDATE sessions …
|
||||
│ │
|
||||
│◄── { status: "ok", next_salt } ────────┤
|
||||
│ │
|
||||
│ sentSalt = currentSalt ◄── captured BEFORE rotation
|
||||
│ currentSalt = next_salt │
|
||||
│ prevHash = compute_next_hash( │
|
||||
│ prevHash, ts, entropy, │
|
||||
│ stackState, sentSalt) │
|
||||
```
|
||||
|
||||
### 3. Failure Path
|
||||
|
||||
On any validation failure the server returns `{"status":"ok"}` with no
|
||||
`next_salt`. The client logs a warning and continues scheduling heartbeats.
|
||||
The chain is broken — subsequent heartbeats will also fail silently.
|
||||
No error is surfaced to the page or its visitors.
|
||||
|
||||
---
|
||||
|
||||
## Cryptographic Protocol
|
||||
|
||||
### Key Generation
|
||||
|
||||
```
|
||||
Ed25519 keypair generated via ed25519-dalek + rand::thread_rng (OS-seeded)
|
||||
Private key: stored in WASM thread_local, never leaves WASM memory
|
||||
Public key: 32 bytes, hex-encoded, sent to server at init
|
||||
```
|
||||
|
||||
### Hash Chain
|
||||
|
||||
```
|
||||
H(0) = Blake3( session_id ║ pub_key ║ salt₀ )
|
||||
|
||||
H(n) = Blake3(
|
||||
saltₙ₋₁ ← server-side only, rotated each heartbeat
|
||||
║ H(n-1) ← must match stored last_hash
|
||||
║ timestamp_u64_le
|
||||
║ Blake3( JSON(entropy_data) )
|
||||
║ Blake3( JSON(stack_state) )
|
||||
)
|
||||
```
|
||||
|
||||
Salt rotation means an attacker who intercepts a heartbeat cannot compute
|
||||
future chain links without also intercepting every subsequent server response.
|
||||
|
||||
### Canonical Signing Payload
|
||||
|
||||
The signed message is a JSON object with top-level keys sorted alphabetically,
|
||||
serialised with no extra whitespace:
|
||||
|
||||
```json
|
||||
{
|
||||
"entropyData": { "events": [{"t":…,"x":…,"y":…}] },
|
||||
"fingerprint": { "aspectRatio":"…","devicePixelRatio":"…","hardwareConcurrency":… },
|
||||
"prevHash": "hex…",
|
||||
"sessionId": "hex…",
|
||||
"stackState": { "ip":…,"stack":[…] },
|
||||
"timestamp": 1234567890123
|
||||
}
|
||||
```
|
||||
|
||||
The server reconstructs this using `std::collections::BTreeMap` (alphabetical
|
||||
key order) before calling `VerifyingKey::verify_strict`. Any field mismatch,
|
||||
key order difference, or whitespace difference causes a signature failure.
|
||||
|
||||
### Hashing Algorithm
|
||||
|
||||
Blake3 is used throughout: hash chain links, entropy data digest, stack state
|
||||
digest, and the VM HASH opcode. Blake3 is chosen for speed in WASM,
|
||||
resistance to length-extension attacks, and a clean Rust API.
|
||||
|
||||
---
|
||||
|
||||
## Stack Machine
|
||||
|
||||
The server generates a random program on session init. The client executes it
|
||||
on every heartbeat and includes the resulting `StackState { stack, ip }` in
|
||||
the signed payload. This ensures each heartbeat carries unique, verifiable
|
||||
computation without additional round-trips.
|
||||
|
||||
### Instruction Set
|
||||
|
||||
| Opcode | Mnemonic | Operand | Stack effect | Description |
|
||||
|--------|----------|---------------|--------------|-------------|
|
||||
| `0x00` | PUSH | u32 (4B LE) | +1 | Push literal |
|
||||
| `0x01` | ADD | — | −1 | `a + b` wrapping |
|
||||
| `0x02` | SUB | — | −1 | `a - b` wrapping |
|
||||
| `0x03` | MUL | — | −1 | `a * b` wrapping |
|
||||
| `0x04` | XOR | — | −1 | `a ^ b` |
|
||||
| `0x05` | AND | — | −1 | `a & b` |
|
||||
| `0x06` | OR | — | −1 | `a \| b` |
|
||||
| `0x07` | ROT | — | −1 | `a.rotate_left(b % 32)` |
|
||||
| `0x08` | NOT | — | 0 | `!a` (unary) |
|
||||
| `0x09` | HASH | — | -(depth-1) | Blake3 of all stack items → single u32 |
|
||||
|
||||
The generator ensures ≥ 2 items on the stack before any binary opcode.
|
||||
NOT (0x08) does not change depth. HASH resets depth to 1.
|
||||
|
||||
---
|
||||
|
||||
## Behavioral Validation
|
||||
|
||||
### Mouse Entropy
|
||||
|
||||
Every heartbeat includes the mouse events collected since the previous
|
||||
heartbeat. Server checks:
|
||||
|
||||
| Check | Threshold |
|
||||
|---|---|
|
||||
| Minimum event count | ≥ 3 |
|
||||
| Minimum cumulative distance | ≥ 10 px |
|
||||
| Maximum average speed | ≤ 2.0 px/ms (distance / elapsed ms) |
|
||||
| Minimum pause count | ≥ 1 (movement < 0.2 px over > 50 ms) |
|
||||
|
||||
### Browser Fingerprint
|
||||
|
||||
| Signal | Valid range |
|
||||
|---|---|
|
||||
| `aspectRatio` (width / height) | 0.5 – 3.0 |
|
||||
| `devicePixelRatio` | 0 < dpr ≤ 5.0 |
|
||||
| `hardwareConcurrency` | ≥ 1 |
|
||||
|
||||
---
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
Token bucket per `session_id`: 5 requests / 10-second window.
|
||||
Stale entries evicted every 60 seconds by the cleanup task.
|
||||
Rate-limited responses are indistinguishable from validation failures.
|
||||
|
||||
---
|
||||
|
||||
## SQLite Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
public_key BLOB NOT NULL, -- 32-byte Ed25519 verifying key
|
||||
salt BLOB NOT NULL, -- 16-byte current salt
|
||||
last_hash BLOB NOT NULL, -- 32-byte Blake3 chain head
|
||||
chain_length INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL, -- Unix ms
|
||||
last_seen INTEGER NOT NULL, -- Unix ms
|
||||
expires_at INTEGER NOT NULL -- Unix ms
|
||||
);
|
||||
```
|
||||
|
||||
In-memory SQLite — all sessions lost on server restart by design.
|
||||
Clients re-initialise transparently on the next page load.
|
||||
|
||||
---
|
||||
|
||||
## Threat Model
|
||||
|
||||
Designed to increase:
|
||||
- scraping cost
|
||||
- operational complexity
|
||||
- synchronization burden
|
||||
### In Scope
|
||||
|
||||
ChronoSeal does not attempt impossible perfect prevention.
|
||||
| Threat | Mitigation |
|
||||
|---|---|
|
||||
| Playwright / Puppeteer / Selenium | Mouse entropy + behavioral validation |
|
||||
| Puppeteer Stealth, undetected-chromedriver | Signature over VM execution state |
|
||||
| Heartbeat replay | Hash chain + ±30s timestamp window |
|
||||
| Signature forgery | Private key isolated in WASM memory |
|
||||
| Parallel session sharing | Each session bound to a unique keypair |
|
||||
| Brute-forced session IDs | 256-bit random entropy |
|
||||
| Flooding with fake session IDs | Rate limiter + periodic HashMap eviction |
|
||||
| Traffic analysis | Uniform `{"status":"ok"}` on all failure paths |
|
||||
|
||||
### Out of Scope
|
||||
|
||||
| Threat | Reason |
|
||||
|---|---|
|
||||
| Real browser with real human input | Indistinguishable from a legitimate user |
|
||||
| WASM reverse engineering | Obfuscation is not a security primitive |
|
||||
| Server-side compromise | Outside the scope of client attestation |
|
||||
|
||||
ChronoSeal raises cost and complexity of automated access. It is not a
|
||||
cryptographic proof of humanity and does not claim to be.
|
||||
|
||||
---
|
||||
|
||||
## Module Reference
|
||||
|
||||
| Path | Purpose |
|
||||
|---|---|
|
||||
| `shared/src/protocol.rs` | Shared types: `InitRequest`, `HeartbeatRequest`, `StackState`, … |
|
||||
| `shared/src/hashing.rs` | `initial_hash`, `next_chain_hash`, `hash_stack` |
|
||||
| `shared/src/constants.rs` | All tunable parameters |
|
||||
| `server/src/routes/init.rs` | `POST /init` handler |
|
||||
| `server/src/routes/heartbeat.rs` | `POST /hb` handler |
|
||||
| `server/src/session.rs` | `create_session`, `verify_heartbeat` |
|
||||
| `server/src/crypto.rs` | `verify_signature` — BTreeMap canonical JSON |
|
||||
| `server/src/trust.rs` | `validate_mouse` — speed, distance, pauses |
|
||||
| `server/src/fingerprint.rs` | `validate` — aspect ratio, DPR, HW concurrency |
|
||||
| `server/src/vm.rs` | `generate_random_program` |
|
||||
| `server/src/ratelimit.rs` | `RateLimiter::check`, `evict_stale` |
|
||||
| `server/src/cleanup.rs` | Background loop: expire sessions + evict rate limiter |
|
||||
| `server/src/storage.rs` | SQLite init, `current_time_ms` |
|
||||
| `wasm/src/crypto.rs` | `generate_keypair`, `sign_message`, `compute_next_hash` |
|
||||
| `wasm/src/vm.rs` | `run_program` — stack machine executor |
|
||||
| `frontend/heartbeat.js` | Session init, heartbeat loop, chain advancement |
|
||||
| `frontend/entropy.js` | Mouse event ring buffer, `collectEntropy` |
|
||||
| `frontend/transport.js` | `sendRequest` fetch wrapper |
|
||||
+326
-16
@@ -1,36 +1,346 @@
|
||||
# Deployment
|
||||
# ChronoSeal — Deployment Guide
|
||||
|
||||
## Native
|
||||
## Prerequisites
|
||||
|
||||
| Tool | Minimum version | Purpose |
|
||||
|---|---|---|
|
||||
| Rust | 1.87 stable | Server + WASM compilation |
|
||||
| wasm-pack | 0.13 | WASM build and packaging |
|
||||
| Docker + Compose | 24 / 2.x | Container deployment |
|
||||
| nginx / NPM / HAProxy | any | TLS termination, reverse proxy |
|
||||
|
||||
Install Rust: https://rustup.rs
|
||||
Install wasm-pack: `cargo install wasm-pack`
|
||||
|
||||
---
|
||||
|
||||
## Build
|
||||
|
||||
### 1. Build the WASM module
|
||||
|
||||
```bash
|
||||
wasm-pack build wasm --target web --release
|
||||
mv wasm/pkg frontend/pkg
|
||||
```
|
||||
|
||||
This produces `frontend/pkg/antibot_wasm.js` and `frontend/pkg/antibot_wasm_bg.wasm`,
|
||||
which are loaded by `frontend/main.js` at runtime.
|
||||
|
||||
### 2. Build the server
|
||||
|
||||
```bash
|
||||
cargo build -p server --release
|
||||
```
|
||||
|
||||
Binary output: `target/release/server`
|
||||
|
||||
### 3. Build both (convenience script)
|
||||
|
||||
```bash
|
||||
bash scripts/build.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Running
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
bash scripts/dev.sh
|
||||
```
|
||||
|
||||
Runs the server with `cargo run --release`. The server serves the `frontend/`
|
||||
directory statically at `/` via tower-http `ServeDir`.
|
||||
|
||||
Open `http://localhost:3000` in a browser. Open DevTools console — heartbeats
|
||||
should appear every 12–25 seconds. No visible UI is rendered; the protection
|
||||
is entirely silent.
|
||||
|
||||
### Production (native binary)
|
||||
|
||||
```bash
|
||||
cargo build -p server --release
|
||||
sudo cp target/release/server /usr/local/bin/chronoseal
|
||||
```
|
||||
|
||||
## systemd
|
||||
Set environment variables before running:
|
||||
|
||||
```bash
|
||||
sudo cp chronoseal.service /etc/systemd/system/
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable chronoseal
|
||||
sudo systemctl start chronoseal
|
||||
export RUST_LOG=info # or warn for quieter output
|
||||
chronoseal
|
||||
```
|
||||
|
||||
The server binds to `0.0.0.0:3000` by default. Place behind a reverse proxy
|
||||
for TLS — do not expose port 3000 directly.
|
||||
|
||||
---
|
||||
|
||||
## systemd
|
||||
|
||||
### Service file
|
||||
|
||||
The provided `chronoseal.service` includes hardened systemd sandboxing:
|
||||
|
||||
```
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
MemoryDenyWriteExecute=true
|
||||
RestrictRealtime=true
|
||||
RestrictSUIDSGID=true
|
||||
LockPersonality=true
|
||||
SystemCallArchitectures=native
|
||||
```
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
# Create a dedicated system user
|
||||
sudo useradd --system --no-create-home --shell /usr/sbin/nologin chronoseal
|
||||
|
||||
# Install binary and frontend
|
||||
sudo cp target/release/server /usr/local/bin/chronoseal
|
||||
sudo mkdir -p /opt/chronoseal/frontend
|
||||
sudo cp -r frontend/ /opt/chronoseal/frontend/
|
||||
sudo chown -R chronoseal:chronoseal /opt/chronoseal
|
||||
|
||||
# Install and enable service
|
||||
sudo cp chronoseal.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chronoseal
|
||||
```
|
||||
|
||||
### Verify
|
||||
|
||||
```bash
|
||||
sudo systemctl status chronoseal
|
||||
journalctl -u chronoseal -f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Docker
|
||||
|
||||
### Build and run
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### docker-compose.yml overview
|
||||
|
||||
```yaml
|
||||
services:
|
||||
chronoseal:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
RUST_LOG: info
|
||||
tmpfs:
|
||||
- /tmp
|
||||
```
|
||||
|
||||
The `tmpfs` mount ensures the in-memory SQLite database is never written to
|
||||
disk, even if Docker's storage driver were to flush the container filesystem.
|
||||
|
||||
### Dockerfile stages
|
||||
|
||||
The Dockerfile uses a two-stage build:
|
||||
|
||||
1. `rust:1.87-bookworm` — compiles the server binary
|
||||
2. `debian:bookworm-slim` — minimal runtime image with only `ca-certificates`
|
||||
|
||||
The WASM module and frontend must be built separately (wasm-pack requires a
|
||||
browser toolchain not present in the server image) and mounted or copied into
|
||||
the container at `/opt/chronoseal/frontend/`.
|
||||
|
||||
```bash
|
||||
# Build WASM first
|
||||
wasm-pack build wasm --target web --release
|
||||
mv wasm/pkg frontend/pkg
|
||||
|
||||
# Then build and run the container
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Or mount the pre-built frontend as a volume:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ./frontend:/opt/chronoseal/frontend:ro
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reverse Proxy
|
||||
|
||||
Recommended:
|
||||
- nginx
|
||||
- Nginx Proxy Manager
|
||||
- HAProxy
|
||||
ChronoSeal must be served over HTTPS. The heartbeat payload contains a
|
||||
timestamp; if traffic is observable in plaintext, timing attacks become
|
||||
easier. TLS 1.3 is strongly recommended.
|
||||
|
||||
Enable:
|
||||
- HTTP/2
|
||||
- TLS 1.3
|
||||
- aggressive timeout policies
|
||||
### nginx
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name your.domain.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/your.domain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/your.domain.com/privkey.pem;
|
||||
ssl_protocols TLSv1.3;
|
||||
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
|
||||
|
||||
# Tight timeouts — heartbeat interval is 12–25s
|
||||
proxy_read_timeout 35s;
|
||||
proxy_send_timeout 10s;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name your.domain.com;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
```
|
||||
|
||||
### Nginx Proxy Manager
|
||||
|
||||
1. Add a new Proxy Host pointing to `http://chronoseal:3000`
|
||||
2. Enable SSL, Request Let's Encrypt certificate
|
||||
3. Enable HTTP/2, Force SSL
|
||||
4. Under Advanced, add:
|
||||
```
|
||||
proxy_read_timeout 35s;
|
||||
proxy_send_timeout 10s;
|
||||
```
|
||||
|
||||
### HAProxy
|
||||
|
||||
```haproxy
|
||||
frontend https_front
|
||||
bind *:443 ssl crt /etc/haproxy/certs/your.domain.pem alpn h2,http/1.1
|
||||
default_backend chronoseal_back
|
||||
|
||||
backend chronoseal_back
|
||||
server chronoseal 127.0.0.1:3000 check
|
||||
timeout connect 5s
|
||||
timeout server 35s
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration into an Existing Site
|
||||
|
||||
ChronoSeal is designed to run as a sidecar — its `/init` and `/hb` endpoints
|
||||
can be proxied from any existing web server. The frontend assets (`pkg/`) need
|
||||
to be served from the same origin as the protected page (or CORS must be
|
||||
configured).
|
||||
|
||||
### Option A — Serve everything from ChronoSeal
|
||||
|
||||
ChronoSeal serves `frontend/` statically. Put your protected HTML inside
|
||||
`frontend/` and let ChronoSeal serve it directly.
|
||||
|
||||
### Option B — Proxy only the API endpoints
|
||||
|
||||
Keep your existing server. Proxy `/init` and `/hb` to ChronoSeal, and serve
|
||||
the WASM and JS assets from your CDN or existing static file server.
|
||||
|
||||
```nginx
|
||||
# On your existing server:
|
||||
location ~ ^/(init|hb)$ {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
}
|
||||
```
|
||||
|
||||
Add to your protected pages:
|
||||
|
||||
```html
|
||||
<script type="module" src="/pkg/antibot_wasm.js"></script>
|
||||
<script type="module" src="/main.js"></script>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
All parameters are in `shared/src/constants.rs`. Recompile after changes.
|
||||
|
||||
| Constant | Default | Notes |
|
||||
|---|---|---|
|
||||
| `SESSION_ID_LEN` | 32 bytes | 256-bit entropy — do not reduce |
|
||||
| `SALT_LEN` | 16 bytes | Per-heartbeat salt |
|
||||
| `HEARTBEAT_MIN_INTERVAL_MS` | 12 000 ms | Increase to reduce server load |
|
||||
| `HEARTBEAT_MAX_INTERVAL_MS` | 25 000 ms | Jitter upper bound |
|
||||
| `EXPIRATION_MINUTES` | 30 min | Session TTL after last heartbeat |
|
||||
| `RATE_LIMIT_COUNT` | 5 | Max heartbeats per window per session |
|
||||
| `RATE_LIMIT_WINDOW_SECS` | 10 s | Rate limit window |
|
||||
| `MAX_TIMESTAMP_DRIFT_MS` | 30 000 ms | Anti-replay window; account for NTP skew |
|
||||
| `MIN_MOUSE_TOTAL_DIST` | 10.0 px | Lower for low-activity pages |
|
||||
| `MAX_MOUSE_AVG_SPEED` | 2.0 px/ms | Raise if legitimate users are rejected |
|
||||
| `MIN_PAUSE_COUNT` | 1 | Minimum natural pause events |
|
||||
|
||||
---
|
||||
|
||||
## Observability
|
||||
|
||||
ChronoSeal uses `tracing` with `tracing-subscriber`. Log levels:
|
||||
|
||||
| Level | Events |
|
||||
|---|---|
|
||||
| `INFO` | Server start, request method + path + status |
|
||||
| `WARN` | Heartbeat validation failures (with session ID and reason) |
|
||||
| `DEBUG` | Rate limit hits |
|
||||
|
||||
```bash
|
||||
RUST_LOG=info chronoseal # production
|
||||
RUST_LOG=debug chronoseal # development
|
||||
RUST_LOG=warn chronoseal # minimal output
|
||||
```
|
||||
|
||||
Log format is plain text to stdout. Pipe to `journald`, `fluentd`, or any
|
||||
log aggregator via stdout capture.
|
||||
|
||||
---
|
||||
|
||||
## Health Check
|
||||
|
||||
The server has no dedicated `/health` endpoint. Use a TCP check on port 3000,
|
||||
or a lightweight HTTP check on `GET /` (which serves `index.html`).
|
||||
|
||||
```bash
|
||||
# Docker health check (add to docker-compose.yml if needed)
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-sf", "http://localhost:3000/"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- [ ] TLS 1.3 enabled, TLS 1.0/1.1 disabled
|
||||
- [ ] HTTP/2 enabled
|
||||
- [ ] Port 3000 not exposed to the public internet (only via reverse proxy)
|
||||
- [ ] `RUST_LOG=warn` or `info` in production (not `debug` — session IDs appear in logs)
|
||||
- [ ] systemd service running as `chronoseal` user with hardened sandbox
|
||||
- [ ] `MemoryDenyWriteExecute=true` in service file (prevents JIT in process)
|
||||
- [ ] CORS `CorsLayer::permissive()` replaced with origin-restricted policy for production
|
||||
- [ ] Frontend assets served over the same HTTPS origin as protected pages
|
||||
@@ -0,0 +1,41 @@
|
||||
# ChronoSeal Design Philosophy
|
||||
|
||||
**"Everything is a File" — Unix-Native Software Design**
|
||||
|
||||
ChronoSeal is intentionally built as a **first-class citizen of Linux**. The entire application is designed to behave like a well-engineered native file within the Unix filesystem.
|
||||
|
||||
### Why This Philosophy Matters
|
||||
|
||||
ChronoSeal is designed so that administrators can operate, monitor, configure, and integrate it using the same reliable, transparent, and trusted tools and patterns they already use on Linux systems — without fighting the operating environment.
|
||||
|
||||
### Core Principles
|
||||
|
||||
- **Everything is a File**: The application must be controllable, inspectable, and composable through standard Unix interfaces (CLI, files, signals, pipes, and environment).
|
||||
- **CLI as Source of Truth**: All operations — starting, stopping, configuring, monitoring, and debugging — must be possible from the command line with excellent discoverability.
|
||||
- **Behave Like a Native File**: Predictable lifecycle management through commands, signals (`SIGHUP`, `SIGTERM`, `SIGUSR1`), logs, configuration files, and standard process semantics.
|
||||
- **Composability**: Must work naturally with pipes, redirection, scripts, systemd, Ansible, Docker, and orchestration tools.
|
||||
- **Observability by Default**: All important state and metrics should be accessible as text or structured data.
|
||||
- **Minimal Friction, Maximum Durability**: One-line installer, world-class `--help`, proper man pages, and decades-long maintainability are non-negotiable.
|
||||
- **Respect for the OS**: Follows Linux Filesystem Hierarchy Standard (FHS), XDG Base Directory specification, and hardened systemd practices.
|
||||
|
||||
### Non-Goals
|
||||
|
||||
ChronoSeal is **not** designed to be:
|
||||
- Cloud-first or vendor-specific
|
||||
- Browser-first or JavaScript-heavy
|
||||
- Dependency-heavy or framework-driven
|
||||
- GUI-centric (any graphical interface must be a thin wrapper)
|
||||
- Telemetry-oriented or privacy-invasive
|
||||
- Optimized for rapid prototyping at the cost of long-term reliability
|
||||
|
||||
These non-goals help keep the project focused on stability, simplicity, security, and deep Unix integration.
|
||||
|
||||
### Development Mindset
|
||||
|
||||
- Production robustness, security, and long-term sustainability take clear precedence over development speed.
|
||||
- Every design decision is evaluated against one question:
|
||||
**“Does this make ChronoSeal feel like it naturally belongs in `/usr/bin/`?”**
|
||||
|
||||
This philosophy guided the complete refactoring of ChronoSeal and continues to drive all future development.
|
||||
|
||||
**Status**: Core architecture and systemd integration completed. Rich CLI, runtime configuration system, and one-line installer are in active development.
|
||||
@@ -0,0 +1,278 @@
|
||||
# ChronoSeal Privacy & Design Principles
|
||||
|
||||
## Privacy-First Browser Attestation Framework
|
||||
|
||||
ChronoSeal is a lightweight, privacy-first browser attestation framework designed to resist:
|
||||
|
||||
- automated bots
|
||||
- AI-driven browser automation
|
||||
- scripted abuse
|
||||
- browser surveillance ecosystems
|
||||
|
||||
Unlike conventional anti-bot systems, ChronoSeal is intentionally designed to operate **without collecting or storing client identity data**.
|
||||
|
||||
---
|
||||
|
||||
# Core Philosophy
|
||||
|
||||
ChronoSeal verifies:
|
||||
|
||||
- session continuity
|
||||
- runtime coherence
|
||||
- cryptographic synchronization
|
||||
|
||||
It does **not** verify:
|
||||
|
||||
- personal identity
|
||||
- browsing history
|
||||
- behavioral profiles
|
||||
- long-term reputation
|
||||
|
||||
The framework is built around one principle:
|
||||
|
||||
> Verify live browser participation without turning users into telemetry.
|
||||
|
||||
---
|
||||
|
||||
# Privacy-First By Architecture
|
||||
|
||||
ChronoSeal is intentionally engineered to avoid becoming:
|
||||
|
||||
- a tracking platform
|
||||
- a fingerprinting database
|
||||
- a telemetry pipeline
|
||||
- a surveillance system
|
||||
|
||||
## ChronoSeal Does NOT Store
|
||||
|
||||
- IP addresses
|
||||
- Browser history
|
||||
- Persistent fingerprints
|
||||
- User profiles
|
||||
- Behavioral telemetry
|
||||
- Tracking identifiers
|
||||
- Device databases
|
||||
- Long-term session history
|
||||
- Cross-site correlation data
|
||||
|
||||
No client-side personal information is persisted.
|
||||
|
||||
---
|
||||
|
||||
# Stateless Trust Model
|
||||
|
||||
ChronoSeal focuses on:
|
||||
|
||||
- ephemeral runtime verification
|
||||
- cryptographic continuity
|
||||
- synchronized challenge progression
|
||||
- live execution integrity
|
||||
|
||||
The server only validates:
|
||||
|
||||
- whether the current browser session behaves like a coherent participant *right now*
|
||||
|
||||
ChronoSeal does not maintain:
|
||||
|
||||
- user identity databases
|
||||
- reputation systems
|
||||
- persistent surveillance records
|
||||
|
||||
---
|
||||
|
||||
# Anti-Bot Without Surveillance
|
||||
|
||||
Most modern anti-bot systems rely heavily on:
|
||||
|
||||
- fingerprinting
|
||||
- behavioral tracking
|
||||
- telemetry aggregation
|
||||
- centralized analytics
|
||||
|
||||
ChronoSeal deliberately rejects this model.
|
||||
|
||||
Instead, ChronoSeal uses:
|
||||
|
||||
- synchronized cryptographic chains
|
||||
- WASM-isolated signing
|
||||
- protocol continuity
|
||||
- transient verification state
|
||||
|
||||
This provides bot resistance while preserving user privacy.
|
||||
|
||||
---
|
||||
|
||||
# Lightweight By Design
|
||||
|
||||
ChronoSeal is intentionally engineered to remain:
|
||||
|
||||
- compact
|
||||
- dependency-light
|
||||
- operationally simple
|
||||
- Unix-native
|
||||
|
||||
## Current Footprint
|
||||
|
||||
### Server Binary
|
||||
|
||||
Compiled x86_64 Linux server binary:
|
||||
|
||||
- ~8.4 MB
|
||||
|
||||
### WASM Runtime
|
||||
|
||||
`chronoseal_wasm_bg.wasm`
|
||||
|
||||
- ~218 KB
|
||||
|
||||
### Full WASM Package
|
||||
|
||||
Entire generated WASM package:
|
||||
|
||||
- ~720 KB
|
||||
|
||||
Includes:
|
||||
|
||||
- WASM runtime
|
||||
- JavaScript glue code
|
||||
- Type definitions
|
||||
|
||||
---
|
||||
|
||||
# No Frontend Framework Dependency
|
||||
|
||||
ChronoSeal does not depend on:
|
||||
|
||||
- React
|
||||
- Angular
|
||||
- Vue
|
||||
- Electron
|
||||
- Node.js runtime
|
||||
- Browser bundler ecosystems
|
||||
|
||||
The browser runtime uses:
|
||||
|
||||
- native ES modules
|
||||
- direct WebAssembly loading
|
||||
- lightweight JavaScript glue
|
||||
|
||||
This minimizes:
|
||||
|
||||
- dependency complexity
|
||||
- supply-chain risk
|
||||
- build fragility
|
||||
- browser overhead
|
||||
|
||||
---
|
||||
|
||||
# Clean Repository Philosophy
|
||||
|
||||
ChronoSeal keeps generated artefacts out of version control.
|
||||
|
||||
## What Is NOT Stored In The Repository
|
||||
|
||||
| Path | Reason |
|
||||
|---|---|
|
||||
| `wasm/pkg/` | Generated build output |
|
||||
| `frontend/pkg/` | Generated serve-time artefacts |
|
||||
| `target/` | Standard Rust build artefacts |
|
||||
|
||||
Generated binaries change frequently and are reproducible from source.
|
||||
|
||||
The repository intentionally stores:
|
||||
|
||||
- source code
|
||||
- architecture
|
||||
- reproducible build logic only
|
||||
|
||||
---
|
||||
|
||||
# Unix-Native Operational Model
|
||||
|
||||
ChronoSeal is designed as:
|
||||
|
||||
- infrastructure software
|
||||
- not browser-centric SaaS
|
||||
|
||||
Core operational principles:
|
||||
|
||||
- CLI-first operation
|
||||
- systemd-native deployment
|
||||
- structured logs
|
||||
- explicit configuration
|
||||
- inspectable runtime behavior
|
||||
- minimal hidden state
|
||||
|
||||
ChronoSeal should feel natural on Linux systems:
|
||||
|
||||
- simple to deploy
|
||||
- easy to audit
|
||||
- understandable years later
|
||||
|
||||
---
|
||||
|
||||
# Security Through Operational Asymmetry
|
||||
|
||||
ChronoSeal increases attacker cost through:
|
||||
|
||||
- synchronization burden
|
||||
- runtime continuity requirements
|
||||
- WASM-isolated cryptographic execution
|
||||
- chained session progression
|
||||
|
||||
It does not attempt:
|
||||
|
||||
- invasive tracking
|
||||
- permanent identification
|
||||
- surveillance-driven scoring
|
||||
|
||||
---
|
||||
|
||||
# Design Goals
|
||||
|
||||
ChronoSeal prioritizes:
|
||||
|
||||
- Privacy
|
||||
- Simplicity
|
||||
- Transparency
|
||||
- Operational clarity
|
||||
- Long-term maintainability
|
||||
- Minimalism
|
||||
- Unix-native behavior
|
||||
- Low deployment friction
|
||||
|
||||
---
|
||||
|
||||
# Non-Goals
|
||||
|
||||
ChronoSeal is intentionally NOT:
|
||||
|
||||
- A surveillance platform
|
||||
- A telemetry collection system
|
||||
- A browser fingerprinting database
|
||||
- An analytics engine
|
||||
- A cloud lock-in service
|
||||
- A JavaScript-heavy frontend platform
|
||||
- An advertising or tracking framework
|
||||
|
||||
---
|
||||
|
||||
# Summary
|
||||
|
||||
ChronoSeal is designed to prove:
|
||||
|
||||
> “A live browser session is coherently participating right now.”
|
||||
|
||||
without storing:
|
||||
|
||||
- who the user is
|
||||
- where they came from
|
||||
- what they previously did
|
||||
|
||||
It is a lightweight, privacy-preserving, Unix-native browser attestation framework focused on:
|
||||
|
||||
- anti-bot resistance
|
||||
- anti-automation
|
||||
- operational simplicity
|
||||
|
||||
without compromising user privacy.
|
||||
@@ -0,0 +1,205 @@
|
||||
# ChronoSeal — Threat Model
|
||||
|
||||
## Purpose
|
||||
|
||||
This document defines what ChronoSeal is designed to protect against, what
|
||||
it explicitly does not protect against, and the reasoning behind each
|
||||
design decision in security terms.
|
||||
|
||||
ChronoSeal is a **cost-raising mechanism**. It does not claim to make
|
||||
automated access impossible. It makes automated access expensive, complex
|
||||
to maintain, and operationally fragile at scale.
|
||||
|
||||
---
|
||||
|
||||
## Assets Being Protected
|
||||
|
||||
| Asset | Description |
|
||||
|---|---|
|
||||
| Web page content | HTML, rendered data, scraped text |
|
||||
| API responses | JSON endpoints that serve structured data |
|
||||
| Server compute | CPU and bandwidth consumed by automated clients |
|
||||
| Rate-limited resources | Endpoints with per-user quotas |
|
||||
| Behavioral analytics | Metrics polluted by bot traffic |
|
||||
|
||||
---
|
||||
|
||||
## Attacker Profiles
|
||||
|
||||
### Level 1 — Script Kiddie / Commodity Scraper
|
||||
|
||||
**Tools:** `curl`, `requests`, `scrapy`, simple HTTP clients.
|
||||
**Capability:** No browser environment. Cannot execute JavaScript or WASM.
|
||||
**ChronoSeal response:** Session never initialises. No `session_id` is ever
|
||||
presented to `/hb`. Content gated behind session validation is never served.
|
||||
|
||||
### Level 2 — Headless Browser Operator
|
||||
|
||||
**Tools:** Playwright, Puppeteer, Selenium, undetected-chromedriver.
|
||||
**Capability:** Full browser environment. Can execute JavaScript and WASM.
|
||||
Cannot easily synthesise realistic mouse entropy or maintain hash chain state
|
||||
across concurrent sessions.
|
||||
**ChronoSeal response:** Mouse entropy validation rejects absent or synthetic
|
||||
movement. Hash chain requires per-session state synchronisation. Scaling to
|
||||
hundreds of concurrent sessions requires proportional infrastructure.
|
||||
|
||||
### Level 3 — Stealth Automation
|
||||
|
||||
**Tools:** Puppeteer Stealth, rebrowser-patches, custom CDP clients with
|
||||
evasion patches.
|
||||
**Capability:** Patches `navigator.webdriver`, spoofs browser fingerprints,
|
||||
can inject synthetic mouse events. May partially pass behavioral checks.
|
||||
**ChronoSeal response:** Ed25519 signature over the full payload (including
|
||||
behavioral state and VM execution result) means the attacker must also
|
||||
correctly execute the WASM program and maintain chain continuity. The private
|
||||
key is generated fresh per page load and never exposed — it cannot be
|
||||
extracted from a legitimate session and reused.
|
||||
|
||||
### Level 4 — Sophisticated Adversary
|
||||
|
||||
**Tools:** Full browser farm with real input devices, WASM reverse engineering,
|
||||
custom chain maintenance infrastructure.
|
||||
**Capability:** Can pass all current ChronoSeal checks given sufficient
|
||||
engineering effort.
|
||||
**ChronoSeal response:** Significantly increases operational cost. A browser
|
||||
farm with real input devices costs orders of magnitude more than a commodity
|
||||
scraper fleet. ChronoSeal is not designed to stop this attacker — no client-
|
||||
side protection can.
|
||||
|
||||
---
|
||||
|
||||
## Attack Vectors and Mitigations
|
||||
|
||||
### Replay Attack
|
||||
|
||||
**Attack:** Capture a valid heartbeat payload and retransmit it.
|
||||
**Mitigation:**
|
||||
- Timestamp window (±30 seconds): replayed payloads are rejected after 30s.
|
||||
- Hash chain: each heartbeat must present `H(n-1)` matching the server's
|
||||
stored state. A replayed heartbeat presents a stale hash that no longer
|
||||
matches after one successful heartbeat has advanced the chain.
|
||||
|
||||
### Signature Forgery
|
||||
|
||||
**Attack:** Construct a valid-looking heartbeat payload without the private key.
|
||||
**Mitigation:** Ed25519 with 128-bit security. The private key is generated
|
||||
inside WASM `thread_local` memory, never serialised, never passed to
|
||||
JavaScript, never transmitted. Forgery requires breaking Ed25519 or
|
||||
extracting the key from WASM memory — neither is practical.
|
||||
|
||||
### Key Extraction
|
||||
|
||||
**Attack:** Inspect WASM linear memory to extract the private signing key.
|
||||
**Mitigation:** The key is stored in a Rust `thread_local! { RefCell<Option<SigningKey>> }`.
|
||||
It has no exported symbol and is not referenced by any exported WASM function
|
||||
that returns raw memory. An attacker with full DevTools access to the WASM
|
||||
memory can extract it from one session, but it is useless for other sessions
|
||||
(fresh keypair per page load) and expires with the session.
|
||||
|
||||
### Hash Chain Forgery
|
||||
|
||||
**Attack:** Compute a valid `H(n)` without the server-side salt.
|
||||
**Mitigation:** Each chain link incorporates `saltₙ₋₁`, which is a 16-byte
|
||||
random value known only to the server and returned (once) in the heartbeat
|
||||
response. An attacker cannot compute `H(n+1)` without first receiving
|
||||
`saltₙ` from a successful heartbeat response, which requires a valid signature
|
||||
and all other checks to pass.
|
||||
|
||||
### Session Hijacking
|
||||
|
||||
**Attack:** Steal a `session_id` and use it from a different client.
|
||||
**Mitigation:** `session_id` alone is insufficient — the attacker also needs
|
||||
the private key (to produce valid signatures) and the current chain state
|
||||
(to present the correct `prev_hash`). All three are required simultaneously.
|
||||
|
||||
### Enumeration of Validation Rules
|
||||
|
||||
**Attack:** Send malformed heartbeats and analyse error responses to map
|
||||
validation logic.
|
||||
**Mitigation:** All failure paths return `{"status":"ok"}` with no `next_salt`.
|
||||
There is no error code, no error message, and no status difference between
|
||||
a rate limit hit, an invalid signature, a broken chain, and a behavioral
|
||||
rejection.
|
||||
|
||||
### DoS via Session Flooding
|
||||
|
||||
**Attack:** Open thousands of sessions to exhaust the rate limiter's HashMap
|
||||
memory.
|
||||
**Mitigation:** Rate limiter entries are evicted every 60 seconds by the
|
||||
cleanup task. Each entry is a small `(u32, Instant)` tuple; even at 100,000
|
||||
concurrent fake sessions, the HashMap occupies roughly 10–15 MB, which is
|
||||
well within normal server memory budgets. Sessions themselves expire after 30
|
||||
minutes of inactivity and are purged from SQLite.
|
||||
|
||||
### Clock Manipulation
|
||||
|
||||
**Attack:** Manipulate the client's `Date.now()` to bypass the timestamp
|
||||
window.
|
||||
**Mitigation:** The timestamp is included in the signed payload. Manipulating
|
||||
it requires also forging the signature. The server validates against its own
|
||||
clock — client-side clock manipulation cannot help without the private key.
|
||||
|
||||
### Synthetic Mouse Events
|
||||
|
||||
**Attack:** Inject programmatic `mousemove` events via `dispatchEvent` or
|
||||
CDP input simulation.
|
||||
**Mitigation:** Synthetic events often fail the pause check (no natural dwell
|
||||
periods), produce unrealistically uniform speed profiles, or fail the minimum
|
||||
distance threshold. Generating convincingly human mouse traces at scale
|
||||
requires either real input devices or sophisticated probabilistic models —
|
||||
both significantly increase operational cost.
|
||||
|
||||
---
|
||||
|
||||
## What ChronoSeal Does Not Protect Against
|
||||
|
||||
| Limitation | Explanation |
|
||||
|---|---|
|
||||
| Real browsers with real users acting as bots | A human operating a browser manually is indistinguishable from a legitimate visitor. ChronoSeal cannot address this. |
|
||||
| Server-side vulnerabilities | ChronoSeal is a client attestation layer. It does not protect the server from injection, authentication bypass, or other backend vulnerabilities. |
|
||||
| Highly resourced nation-state actors | Out of scope for a client-side protection layer. |
|
||||
| Content visible before session establishment | If the protected content is rendered before the first heartbeat, it can be scraped without a session. Gate content on session validity server-side. |
|
||||
| Perfect bot prevention | No client-side mechanism can be. WASM can be reverse engineered. ChronoSeal raises cost, not an impenetrable barrier. |
|
||||
|
||||
---
|
||||
|
||||
## Operational Security Notes
|
||||
|
||||
### Log Level
|
||||
|
||||
Do not run with `RUST_LOG=debug` in production. The debug log includes
|
||||
`session_id` values, which are sensitive identifiers. Use `warn` or `info`.
|
||||
|
||||
### CORS Policy
|
||||
|
||||
The default `CorsLayer::permissive()` is suitable for development only.
|
||||
In production, restrict allowed origins to your own domain:
|
||||
|
||||
```rust
|
||||
CorsLayer::new()
|
||||
.allow_origin("https://your.domain.com".parse::<HeaderValue>().unwrap())
|
||||
.allow_methods([Method::POST])
|
||||
.allow_headers([header::CONTENT_TYPE])
|
||||
```
|
||||
|
||||
### TLS
|
||||
|
||||
Serve exclusively over TLS 1.3. The heartbeat payload contains timestamps
|
||||
and behavioral signals. While each payload is signed and cannot be forged,
|
||||
plaintext transmission leaks behavioral patterns and timing information that
|
||||
could assist a sophisticated attacker.
|
||||
|
||||
### In-Memory SQLite
|
||||
|
||||
All session state is lost on server restart. This is intentional — there is
|
||||
no persistent state to steal. Clients transparently re-initialise. If your
|
||||
deployment restarts frequently (e.g. rolling deploys), sessions will be lost
|
||||
more often; tune `HEARTBEAT_MIN_INTERVAL_MS` and `EXPIRATION_MINUTES`
|
||||
accordingly so clients recover quickly.
|
||||
|
||||
---
|
||||
|
||||
## Security Disclosure
|
||||
|
||||
See [SECURITY.md](../SECURITY.md) for the vulnerability disclosure policy
|
||||
and contact details.
|
||||
@@ -0,0 +1,301 @@
|
||||
# ChronoSeal — WASM Build Guide
|
||||
|
||||
## Overview
|
||||
|
||||
The client-side cryptographic core of ChronoSeal is written in Rust and
|
||||
compiled to WebAssembly (WASM). The JavaScript frontend (`heartbeat.js`)
|
||||
imports functions from this WASM module to generate keypairs, sign heartbeat
|
||||
payloads, compute hash chain links, and execute the stack machine program.
|
||||
|
||||
The import line in `heartbeat.js`:
|
||||
|
||||
```js
|
||||
import init, { generate_keypair, sign_message, compute_next_hash, run_program }
|
||||
from './pkg/antibot_wasm.js';
|
||||
```
|
||||
|
||||
`./pkg/antibot_wasm.js` is a **generated file**. It does not exist in the
|
||||
repository and must be produced by building the `wasm/` crate before running
|
||||
the server.
|
||||
|
||||
---
|
||||
|
||||
## How the WASM Module is Built
|
||||
|
||||
The tool that compiles Rust to WASM and generates the JavaScript glue is
|
||||
[`wasm-pack`](https://rustwasm.github.io/wasm-pack/).
|
||||
|
||||
When you run:
|
||||
|
||||
```bash
|
||||
wasm-pack build wasm --target web --release
|
||||
```
|
||||
|
||||
wasm-pack does the following in sequence:
|
||||
|
||||
1. Compiles `wasm/src/lib.rs` (and its submodules) to a `.wasm` binary using
|
||||
the `wasm32-unknown-unknown` target.
|
||||
2. Runs `wasm-bindgen` to inspect every `#[wasm_bindgen]`-annotated function
|
||||
and struct and generate a JavaScript wrapper for each one.
|
||||
3. Optionally runs `wasm-opt` (from Binaryen) to size-optimise the binary.
|
||||
4. Writes all output to `wasm/pkg/`.
|
||||
|
||||
---
|
||||
|
||||
## Output: `wasm/pkg/`
|
||||
|
||||
After a successful build, `wasm/pkg/` contains:
|
||||
|
||||
```
|
||||
wasm/pkg/
|
||||
├── antibot_wasm.js ← ES module; the file heartbeat.js imports
|
||||
├── antibot_wasm_bg.wasm ← compiled WASM binary (~300–800 KB release)
|
||||
├── antibot_wasm_bg.js ← internal memory bridge (do not import directly)
|
||||
├── antibot_wasm.d.ts ← TypeScript type declarations
|
||||
├── antibot_wasm_bg.d.ts ← TypeScript declarations for the bg module
|
||||
└── package.json
|
||||
```
|
||||
|
||||
### `antibot_wasm.js`
|
||||
|
||||
This is the public entry point. It contains:
|
||||
|
||||
- An `init()` function that fetches and instantiates the `.wasm` binary.
|
||||
- One JavaScript wrapper function for each `#[wasm_bindgen]` export in
|
||||
`wasm/src/`:
|
||||
|
||||
| Rust export | JS wrapper | Description |
|
||||
|---|---|---|
|
||||
| `generate_keypair()` | `generate_keypair()` | Generate Ed25519 keypair; return hex public key |
|
||||
| `get_public_key()` | `get_public_key()` | Return hex public key, or `""` if not initialised |
|
||||
| `sign_message(msg)` | `sign_message(msg)` | Sign string; return hex signature, or `""` if not initialised |
|
||||
| `compute_next_hash(prev, ts, entropy, stack, salt)` | `compute_next_hash(...)` | Compute next Blake3 chain hash |
|
||||
| `run_program(b64)` | `run_program(b64)` | Execute base64 VM program; return `{ stack, ip }` |
|
||||
|
||||
### `antibot_wasm_bg.wasm`
|
||||
|
||||
The compiled binary. The `.bg` suffix means "background" — this is the raw
|
||||
WASM that `antibot_wasm.js` loads internally. You should not reference this
|
||||
file directly in your HTML.
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Build
|
||||
|
||||
### 1. Install the Rust WASM target
|
||||
|
||||
```bash
|
||||
rustup target add wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
This is a one-time step. Without it, the Rust compiler cannot produce WASM
|
||||
output.
|
||||
|
||||
### 2. Install wasm-pack
|
||||
|
||||
```bash
|
||||
cargo install wasm-pack
|
||||
```
|
||||
|
||||
Or via the installer script:
|
||||
|
||||
```bash
|
||||
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
|
||||
```
|
||||
|
||||
Verify:
|
||||
|
||||
```bash
|
||||
wasm-pack --version
|
||||
# wasm-pack 0.13.x
|
||||
```
|
||||
|
||||
### 3. Build the WASM module
|
||||
|
||||
From the project root:
|
||||
|
||||
```bash
|
||||
wasm-pack build wasm --target web --release
|
||||
```
|
||||
|
||||
`--target web` produces an ES module (`import`/`export` syntax) suitable for
|
||||
use directly in a browser without a bundler. Other targets (`bundler`,
|
||||
`nodejs`, `no-modules`) produce different output formats and are not
|
||||
compatible with the ChronoSeal frontend as written.
|
||||
|
||||
`--release` enables Rust's release optimisations (inlining, dead code
|
||||
elimination, size reduction). Omit it during development for faster builds
|
||||
and better panic messages.
|
||||
|
||||
### 4. Move the output to the frontend
|
||||
|
||||
```bash
|
||||
rm -rf frontend/pkg
|
||||
mv wasm/pkg frontend/pkg
|
||||
```
|
||||
|
||||
The frontend expects the WASM module at `frontend/pkg/antibot_wasm.js`
|
||||
because `heartbeat.js` imports from `./pkg/antibot_wasm.js` relative to
|
||||
the `frontend/` directory, which is where the server's static file handler
|
||||
is rooted.
|
||||
|
||||
---
|
||||
|
||||
## Using the Build Script
|
||||
|
||||
The convenience script at `scripts/build.sh` performs all steps in order:
|
||||
|
||||
```bash
|
||||
bash scripts/build.sh
|
||||
```
|
||||
|
||||
This builds the WASM module, moves it to `frontend/pkg/`, and then builds
|
||||
the server binary. Run this for a clean full build before deployment.
|
||||
|
||||
For development iteration where you are only changing Rust WASM code:
|
||||
|
||||
```bash
|
||||
wasm-pack build wasm --target web # (omit --release for speed)
|
||||
rm -rf frontend/pkg && mv wasm/pkg frontend/pkg
|
||||
```
|
||||
|
||||
For development where you are only changing server code:
|
||||
|
||||
```bash
|
||||
cargo build -p server
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## How `heartbeat.js` Loads the Module
|
||||
|
||||
`heartbeat.js` uses a standard ES module dynamic import pattern:
|
||||
|
||||
```js
|
||||
import init, { generate_keypair, sign_message, compute_next_hash, run_program }
|
||||
from './pkg/antibot_wasm.js';
|
||||
|
||||
export async function initHeartbeat() {
|
||||
// 1. Fetch and instantiate the .wasm binary
|
||||
await init();
|
||||
|
||||
// 2. Generate keypair — private key stored in WASM memory only
|
||||
const pubKeyHex = generate_keypair();
|
||||
|
||||
// 3. Send public key to server, receive session_id and chain seed
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
`init()` is the default export from `antibot_wasm.js`. It fetches
|
||||
`antibot_wasm_bg.wasm` (from the same `pkg/` directory) via `fetch()`,
|
||||
compiles it in the browser's WASM engine, and links it to the JS glue
|
||||
layer. After `await init()` returns, all the named exports
|
||||
(`generate_keypair`, `sign_message`, etc.) are ready to call.
|
||||
|
||||
The `init()` call must complete before any other WASM function is called.
|
||||
Calling `sign_message()` or `compute_next_hash()` before `await init()`
|
||||
returns will produce an empty string (the module is not yet instantiated).
|
||||
|
||||
---
|
||||
|
||||
## Serving the WASM Binary
|
||||
|
||||
Browsers require WASM files to be served with the correct MIME type:
|
||||
|
||||
```
|
||||
Content-Type: application/wasm
|
||||
```
|
||||
|
||||
Most web servers set this automatically for `.wasm` files. If you see the
|
||||
error:
|
||||
|
||||
```
|
||||
WebAssembly.instantiate(): Response has unsupported MIME type
|
||||
```
|
||||
|
||||
Add the MIME type to your server configuration:
|
||||
|
||||
**nginx:**
|
||||
```nginx
|
||||
types {
|
||||
application/wasm wasm;
|
||||
}
|
||||
```
|
||||
|
||||
**Apache `.htaccess`:**
|
||||
```apache
|
||||
AddType application/wasm .wasm
|
||||
```
|
||||
|
||||
The Axum `ServeDir` handler used by ChronoSeal's built-in static server
|
||||
sets the correct MIME type automatically via `tower-http`.
|
||||
|
||||
---
|
||||
|
||||
## What Is Not in the Repository
|
||||
|
||||
| Path | Why excluded |
|
||||
|---|---|
|
||||
| `wasm/pkg/` | Generated build output — changes on every build |
|
||||
| `frontend/pkg/` | Same generated output, moved to serve location |
|
||||
| `target/` | Standard Rust build artefacts |
|
||||
|
||||
Both `wasm/pkg/` and `frontend/pkg/` are listed in `.gitignore`. Committing
|
||||
them would bloat the repository (the `.wasm` binary alone is 300–800 KB),
|
||||
create noisy diffs on every rebuild, and give a false impression that the
|
||||
WASM module is pre-built and ready to use without a build step.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `wasm32-unknown-unknown` target not found
|
||||
|
||||
```
|
||||
error[E0463]: can't find crate for `std`
|
||||
```
|
||||
|
||||
Fix:
|
||||
|
||||
```bash
|
||||
rustup target add wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
### `wasm-pack` not found
|
||||
|
||||
```bash
|
||||
cargo install wasm-pack
|
||||
```
|
||||
|
||||
### `wasm-opt` not found (warning, not an error)
|
||||
|
||||
wasm-pack prints a warning if `wasm-opt` is not installed. The build still
|
||||
succeeds; the binary is just not size-optimised.
|
||||
|
||||
```bash
|
||||
# On Debian/Ubuntu/Arch
|
||||
sudo apt install binaryen # Debian/Ubuntu
|
||||
sudo pacman -S binaryen # Arch
|
||||
```
|
||||
|
||||
### `antibot_wasm_bg.wasm` fetch fails (404)
|
||||
|
||||
The `.wasm` file is not being served from `frontend/pkg/`. Verify:
|
||||
|
||||
```bash
|
||||
ls /mnt/Programs/ChronoSeal/frontend/pkg/
|
||||
# Should list: antibot_wasm.js antibot_wasm_bg.wasm ...
|
||||
```
|
||||
|
||||
If the directory is empty or missing, re-run the build steps above.
|
||||
|
||||
### MIME type error in browser
|
||||
|
||||
See the "Serving the WASM Binary" section above.
|
||||
|
||||
### `sign_message` or `generate_keypair` returns empty string
|
||||
|
||||
The WASM keypair has not been initialised. Ensure `await init()` and
|
||||
`generate_keypair()` are called (and awaited) before any other WASM
|
||||
function. Check the browser console for any errors during `init()`.
|
||||
@@ -0,0 +1,5 @@
|
||||
bind = "0.0.0.0:3000"
|
||||
pid_file = "/run/chronoseal.pid"
|
||||
db_path = "/var/lib/chronoseal/chronoseal.sqlite"
|
||||
frontend_dir = "/usr/share/chronoseal/frontend"
|
||||
log_file = "/var/log/chronoseal/chronoseal.jsonl"
|
||||
@@ -1,8 +1,10 @@
|
||||
import init, { generate_keypair, sign_message, compute_next_hash, run_program } from './pkg/antibot_wasm.js';
|
||||
import init, { generate_keypair, sign_message, compute_next_hash, run_program } from './pkg/chronoseal_wasm.js';
|
||||
import { collectEntropy } from './entropy.js';
|
||||
import { sendRequest } from './transport.js';
|
||||
|
||||
let session, prevHash, currentSalt, opcodesB64, lastTime;
|
||||
let minInterval = 12000;
|
||||
let maxInterval = 25000;
|
||||
|
||||
export async function initHeartbeat() {
|
||||
await init();
|
||||
@@ -12,12 +14,14 @@ export async function initHeartbeat() {
|
||||
prevHash = initResp.initial_hash;
|
||||
currentSalt = initResp.salt;
|
||||
opcodesB64 = initResp.opcodes_b64;
|
||||
minInterval = initResp.heartbeat_min_interval_ms || 12000;
|
||||
maxInterval = initResp.heartbeat_max_interval_ms || 25000;
|
||||
lastTime = performance.now();
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
function scheduleNext() {
|
||||
const delay = 12000 + Math.random() * 13000;
|
||||
const delay = minInterval + Math.random() * (maxInterval - minInterval);
|
||||
setTimeout(sendHeartbeat, delay);
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 168 KiB |
@@ -0,0 +1,127 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
version="1.1"
|
||||
id="Layer_1"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="296.99997mm"
|
||||
viewBox="0 0 1122.5196 793.7008"
|
||||
enable-background="new 0 0 1254 1254"
|
||||
xml:space="preserve"
|
||||
height="210mm"
|
||||
sodipodi:docname="chronoseal.svg"
|
||||
inkscape:export-filename="logo1.png"
|
||||
inkscape:export-xdpi="96"
|
||||
inkscape:export-ydpi="96"
|
||||
inkscape:version="1.4.4 (dcaf3e7d9e, 2026-05-05)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:zoom="1.1654266"
|
||||
inkscape:cx="561.16791"
|
||||
inkscape:cy="396.85039"
|
||||
inkscape:window-width="2048"
|
||||
inkscape:window-height="1205"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="Layer_1" /><defs
|
||||
id="defs44" />
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<path
|
||||
fill="none"
|
||||
opacity="0"
|
||||
stroke="none"
|
||||
d="m 791.89377,632.01366 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23208 63.40558,32.40548 95.07782,48.66778 14.943,7.6726 29.74964,15.6123 44.73053,23.2091 8.44464,4.2823 16.79547,9.1534 25.75525,11.9324 18.81989,5.8372 37.10712,3.9335 54.83185,-5.5578 25.51599,-13.6634 51.41541,-26.6141 77.2135,-39.7465 30.82071,-15.6894 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path2" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89376,550.60089 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77522,34.39209 -143.33662,69.23047 -215.00562,103.84463 -8.4082,4.06091 -14.3217,9.84101 -14.3998,19.74008 -0.079,10.00498 5.5228,16.22797 14.0898,20.54743 12.3277,6.21567 24.5123,12.71484 37.3422,19.41369 7.5143,3.93381 14.4228,7.5896 21.3786,11.15274 31.6877,16.23212 63.4056,32.40552 95.0778,48.66782 14.943,7.67261 29.7496,15.61227 44.73052,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path45"
|
||||
style="fill:#e1e1e4;fill-opacity:1" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89377,469.18814 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 C 767.4184,378.3558 705.7113,348.37296 643.97308,318.45444 c -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23212 63.40558,32.40552 95.07782,48.66782 14.943,7.67261 29.74964,15.61227 44.73053,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path46"
|
||||
style="fill:#b0b2b8;fill-opacity:1" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89377,387.77539 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23212 63.40558,32.40552 95.07782,48.66782 14.943,7.67261 29.74964,15.61227 44.73053,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path47"
|
||||
style="fill:#7b7e85;fill-opacity:1" /><text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;writing-mode:lr-tb;direction:ltr;fill:#e1e1e4;fill-opacity:1;stroke-width:39.1"
|
||||
x="154.54701"
|
||||
y="550.13623"
|
||||
id="text47"><tspan
|
||||
id="tspan47"
|
||||
x="154.54701"
|
||||
y="550.13623" /><tspan
|
||||
id="tspan48"
|
||||
x="154.54701"
|
||||
y="750.13623"
|
||||
style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal"><tspan
|
||||
style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:#1f2024;fill-opacity:1"
|
||||
id="tspan49">chrono</tspan>seal</tspan></text><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89376,306.36264 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77522,34.39209 -143.33662,69.23047 -215.00562,103.84463 -8.4082,4.06091 -14.3217,9.84101 -14.3998,19.74008 -0.079,10.00498 5.5228,16.22797 14.0898,20.54743 12.3277,6.21567 24.5123,12.71484 37.3422,19.41369 7.5143,3.93381 14.4228,7.5896 21.3786,11.15274 31.6877,16.23212 63.4056,32.40552 95.0778,48.66782 14.943,7.67261 29.7496,15.61227 44.73052,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path1"
|
||||
style="fill:#4a4d53;fill-opacity:1" /></svg>
|
||||
|
After Width: | Height: | Size: 8.1 KiB |
Binary file not shown.
+127
@@ -0,0 +1,127 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
version="1.1"
|
||||
id="Layer_1"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="296.99997mm"
|
||||
viewBox="0 0 1122.5196 793.7008"
|
||||
enable-background="new 0 0 1254 1254"
|
||||
xml:space="preserve"
|
||||
height="210mm"
|
||||
sodipodi:docname="logo1.svg"
|
||||
inkscape:export-filename="logo1.png"
|
||||
inkscape:export-xdpi="96"
|
||||
inkscape:export-ydpi="96"
|
||||
inkscape:version="1.4.4 (dcaf3e7d9e, 2026-05-05)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:zoom="1.1654266"
|
||||
inkscape:cx="561.16791"
|
||||
inkscape:cy="396.85039"
|
||||
inkscape:window-width="2048"
|
||||
inkscape:window-height="1205"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="Layer_1" /><defs
|
||||
id="defs44" />
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<path
|
||||
fill="none"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89377,632.01366 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23208 63.40558,32.40548 95.07782,48.66778 14.943,7.6726 29.74964,15.6123 44.73053,23.2091 8.44464,4.2823 16.79547,9.1534 25.75525,11.9324 18.81989,5.8372 37.10712,3.9335 54.83185,-5.5578 25.51599,-13.6634 51.41541,-26.6141 77.2135,-39.7465 30.82071,-15.6894 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path2" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89376,550.60089 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77522,34.39209 -143.33662,69.23047 -215.00562,103.84463 -8.4082,4.06091 -14.3217,9.84101 -14.3998,19.74008 -0.079,10.00498 5.5228,16.22797 14.0898,20.54743 12.3277,6.21567 24.5123,12.71484 37.3422,19.41369 7.5143,3.93381 14.4228,7.5896 21.3786,11.15274 31.6877,16.23212 63.4056,32.40552 95.0778,48.66782 14.943,7.67261 29.7496,15.61227 44.73052,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path45"
|
||||
style="fill:#e1e1e4;fill-opacity:1" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89377,469.18814 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 C 767.4184,378.3558 705.7113,348.37296 643.97308,318.45444 c -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23212 63.40558,32.40552 95.07782,48.66782 14.943,7.67261 29.74964,15.61227 44.73053,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path46"
|
||||
style="fill:#b0b2b8;fill-opacity:1" /><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89377,387.77539 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77527,34.39209 -143.33667,69.23047 -215.00567,103.84463 -8.40815,4.06091 -14.32166,9.84101 -14.39978,19.74008 -0.079,10.00498 5.52282,16.22797 14.08978,20.54743 12.3277,6.21567 24.51239,12.71484 37.34228,19.41369 7.51429,3.93381 14.42273,7.5896 21.37854,11.15274 31.68775,16.23212 63.40558,32.40552 95.07782,48.66782 14.943,7.67261 29.74964,15.61227 44.73053,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path47"
|
||||
style="fill:#7b7e85;fill-opacity:1" /><text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;writing-mode:lr-tb;direction:ltr;fill:#e1e1e4;fill-opacity:1;stroke-width:39.1"
|
||||
x="154.54701"
|
||||
y="550.13623"
|
||||
id="text47"><tspan
|
||||
id="tspan47"
|
||||
x="154.54701"
|
||||
y="550.13623" /><tspan
|
||||
id="tspan48"
|
||||
x="154.54701"
|
||||
y="750.13623"
|
||||
style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal"><tspan
|
||||
style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:160px;font-family:'URW Gothic';-inkscape-font-specification:'URW Gothic, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:#1f2024;fill-opacity:1"
|
||||
id="tspan49">chrono</tspan>seal</tspan></text><path
|
||||
fill="#4b4d51"
|
||||
opacity="1"
|
||||
stroke="none"
|
||||
d="m 791.89376,306.36264 c 1.04068,-1.03091 1.90903,-2.38956 3.14896,-3.04166 11.48425,-6.03955 22.98721,-12.04745 34.57742,-17.88034 8.52002,-4.28775 14.37558,-10.49713 14.23218,-20.46771 -0.14127,-9.82202 -6.25309,-15.51495 -14.66742,-19.5827 -61.76651,-29.85993 -123.47361,-59.84277 -185.21183,-89.76129 -10.48242,-5.07981 -20.81335,-10.5555 -31.58477,-14.93764 -19.71186,-8.01936 -39.87799,-8.40881 -59.18305,0.84148 -71.77522,34.39209 -143.33662,69.23047 -215.00562,103.84463 -8.4082,4.06091 -14.3217,9.84101 -14.3998,19.74008 -0.079,10.00498 5.5228,16.22797 14.0898,20.54743 12.3277,6.21567 24.5123,12.71484 37.3422,19.41369 7.5143,3.93381 14.4228,7.5896 21.3786,11.15274 31.6877,16.23212 63.4056,32.40552 95.0778,48.66782 14.943,7.67261 29.7496,15.61227 44.73052,23.20911 8.44464,4.28232 16.79547,9.15341 25.75525,11.93237 18.81989,5.83722 37.10712,3.93353 54.83185,-5.55777 25.51599,-13.66336 51.41541,-26.61407 77.2135,-39.74655 30.82071,-15.68933 61.7009,-31.26196 92.58359,-46.82907 1.56006,-0.78641 3.38776,-1.0419 5.09082,-1.54462 z"
|
||||
id="path1"
|
||||
style="fill:#4a4d53;fill-opacity:1" /></svg>
|
||||
|
After Width: | Height: | Size: 8.1 KiB |
Regular → Executable
+12
-6
@@ -1,10 +1,16 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
echo "Building WASM..."
|
||||
cd ../wasm
|
||||
wasm-pack build --target web
|
||||
mv pkg ../frontend/pkg
|
||||
cd "$ROOT/wasm"
|
||||
wasm-pack build --target web --release
|
||||
rm -rf "$ROOT/frontend/pkg"
|
||||
mv pkg "$ROOT/frontend/pkg"
|
||||
|
||||
echo "Building server..."
|
||||
cd ../server
|
||||
cargo build --release
|
||||
cd "$ROOT"
|
||||
cargo build -p chronoseal-server --bin chronoseal --release
|
||||
|
||||
echo "Done."
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
echo "🚀 ChronoSeal Installer"
|
||||
echo "======================"
|
||||
|
||||
# Create system user
|
||||
if ! id -u chronoseal &>/dev/null; then
|
||||
sudo useradd --system --no-create-home --shell /usr/sbin/nologin chronoseal
|
||||
echo "✓ Created chronoseal system user"
|
||||
fi
|
||||
|
||||
# Build
|
||||
echo "→ Building ChronoSeal..."
|
||||
cd "$(dirname "$0")/.."
|
||||
bash scripts/build.sh
|
||||
|
||||
# Install binary
|
||||
sudo install -Dm755 target/release/chronoseal /usr/local/bin/chronoseal
|
||||
echo "✓ Installed binary to /usr/local/bin/chronoseal"
|
||||
|
||||
# Install frontend assets
|
||||
sudo mkdir -p /opt/chronoseal
|
||||
sudo cp -r frontend /opt/chronoseal/
|
||||
sudo chown -R chronoseal:chronoseal /opt/chronoseal
|
||||
echo "✓ Installed frontend assets"
|
||||
|
||||
# Install systemd service
|
||||
sudo cp chronoseal.service /etc/systemd/system/chronoseal.service
|
||||
sudo systemctl daemon-reload
|
||||
echo "✓ Installed systemd service"
|
||||
|
||||
# Enable and start
|
||||
sudo systemctl enable --now chronoseal
|
||||
echo "✓ ChronoSeal service started"
|
||||
|
||||
echo ""
|
||||
echo "✅ ChronoSeal installed successfully!"
|
||||
echo ""
|
||||
echo "Useful commands:"
|
||||
echo " chronoseal status # Check service status"
|
||||
echo " chronoseal health # Health probe"
|
||||
echo " sudo systemctl status chronoseal"
|
||||
echo " sudo journalctl -u chronoseal -f"
|
||||
echo ""
|
||||
echo "To uninstall: sudo systemctl disable --now chronoseal && sudo rm /usr/local/bin/chronoseal"
|
||||
Regular → Executable
+9
-2
@@ -1,5 +1,12 @@
|
||||
#!/bin/bash
|
||||
bash build.sh
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
"$ROOT/scripts/build.sh"
|
||||
|
||||
echo "Release artifacts:"
|
||||
echo " - server/target/release/antibot-server"
|
||||
echo " - target/release/chronoseal"
|
||||
echo " - frontend/ (including pkg/)"
|
||||
echo " - chronoseal.service"
|
||||
echo " - scripts/install.sh"
|
||||
+14
-2
@@ -1,17 +1,29 @@
|
||||
[package]
|
||||
name = "chronoseal-server"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "chronoseal"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
shared = { path = "../shared" }
|
||||
axum = "0.7"
|
||||
clap = { version = "4", features = ["derive", "env", "wrap_help"] }
|
||||
clap_complete = "4"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_yaml = "0.9"
|
||||
toml = "0.8"
|
||||
rusqlite = { version = "0.31", features = ["bundled"] }
|
||||
r2d2 = "0.8"
|
||||
r2d2_sqlite = "0.24"
|
||||
thiserror = "2"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
tracing-appender = "0.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||
tower = "0.4"
|
||||
tower-http = { version = "0.5", features = ["cors", "fs"] }
|
||||
hex = "0.4"
|
||||
|
||||
+12
-8
@@ -1,5 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
use crate::session::AppState;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub async fn cleanup_loop(state: Arc<AppState>) {
|
||||
loop {
|
||||
@@ -7,18 +7,22 @@ pub async fn cleanup_loop(state: Arc<AppState>) {
|
||||
|
||||
// Evict expired sessions from SQLite.
|
||||
{
|
||||
let db = state.db.lock().await;
|
||||
let now = crate::storage::current_time_ms();
|
||||
let _ = db.execute(
|
||||
"DELETE FROM sessions WHERE expires_at < ?1",
|
||||
rusqlite::params![now],
|
||||
);
|
||||
if let Ok(conn) = state.db_pool.get() {
|
||||
let now = crate::storage::current_time_ms();
|
||||
let _ = conn.execute(
|
||||
"DELETE FROM sessions WHERE expires_at < ?1",
|
||||
rusqlite::params![now],
|
||||
);
|
||||
} else {
|
||||
tracing::error!("Failed to get database connection from pool for cleanup");
|
||||
}
|
||||
}
|
||||
|
||||
// Evict stale rate-limiter entries to prevent unbounded HashMap growth.
|
||||
{
|
||||
let window_secs = state.get_config().rate_limit_window_secs;
|
||||
let mut rl = state.rate_limiter.lock().await;
|
||||
rl.evict_stale();
|
||||
rl.evict_stale(window_secs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub enum OutputFormat {
|
||||
Text,
|
||||
Json,
|
||||
Yaml,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "chronoseal",
|
||||
version,
|
||||
about = "Linux-native cryptographic browser attestation service",
|
||||
long_about = "ChronoSeal runs as a composable Unix service. The CLI is the source of truth for daemon operation, health checks, configuration validation, metrics, and shell integration.",
|
||||
after_help = "Examples:\n chronoseal\n chronoseal run --bind 127.0.0.1:3000\n chronoseal status --format json\n chronoseal health --config /etc/chronoseal/config.toml\n chronoseal config check --output yaml\n chronoseal generate keypair\n chronoseal completion bash > /etc/bash_completion.d/chronoseal\n\nConfiguration precedence:\n CLI flags > CHRONOSEAL_* environment variables > config file > built-in defaults\n\nDefault config discovery:\n /etc/chronoseal/config.toml, then $XDG_CONFIG_HOME/chronoseal/config.toml, then ~/.config/chronoseal/config.toml"
|
||||
)]
|
||||
pub struct Cli {
|
||||
#[command(flatten)]
|
||||
pub globals: GlobalArgs,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Args)]
|
||||
pub struct GlobalArgs {
|
||||
/// Path to config file.
|
||||
#[arg(long, env = "CHRONOSEAL_CONFIG", global = true)]
|
||||
pub config: Option<PathBuf>,
|
||||
|
||||
/// Output format for machine-readable commands.
|
||||
#[arg(long, short = 'f', value_enum, default_value = "text", global = true)]
|
||||
pub format: OutputFormat,
|
||||
|
||||
/// Alias for --format, provided for Unix tool compatibility.
|
||||
#[arg(long, value_enum, global = true)]
|
||||
pub output: Option<OutputFormat>,
|
||||
|
||||
/// Override the logging filter, for example info, chronoseal=debug.
|
||||
#[arg(long, env = "CHRONOSEAL_LOG", global = true)]
|
||||
pub log: Option<String>,
|
||||
}
|
||||
|
||||
impl GlobalArgs {
|
||||
pub fn output_format(&self) -> OutputFormat {
|
||||
self.output.unwrap_or(self.format)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum Command {
|
||||
/// Run the ChronoSeal daemon.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal run\n chronoseal run --bind 127.0.0.1:3000 --frontend-dir /srv/chronoseal/frontend\n CHRONOSEAL_BIND=0.0.0.0:3000 chronoseal run"
|
||||
)]
|
||||
Run(RunArgs),
|
||||
|
||||
/// Report whether the configured daemon is reachable and which PID file is present.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal status\n chronoseal status --format json\n chronoseal status --pid-file /run/chronoseal.pid"
|
||||
)]
|
||||
Status(RuntimeArgs),
|
||||
|
||||
/// Perform a daemon health probe.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal health\n chronoseal health --format json\n chronoseal health --bind 127.0.0.1:3000"
|
||||
)]
|
||||
Health(RuntimeArgs),
|
||||
|
||||
/// Validate and print effective configuration.
|
||||
#[command(subcommand)]
|
||||
Config(ConfigCommand),
|
||||
|
||||
/// Generate operational material.
|
||||
#[command(subcommand)]
|
||||
Generate(GenerateCommand),
|
||||
|
||||
/// Print version and build information.
|
||||
#[command(after_help = "Examples:\n chronoseal version\n chronoseal version --format json")]
|
||||
Version,
|
||||
|
||||
/// Print Prometheus metrics from the running daemon.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal metrics\n chronoseal metrics --bind 127.0.0.1:3000"
|
||||
)]
|
||||
Metrics(RuntimeArgs),
|
||||
|
||||
/// Print service statistics from the running daemon.
|
||||
#[command(after_help = "Examples:\n chronoseal stats\n chronoseal stats --format json")]
|
||||
Stats(RuntimeArgs),
|
||||
|
||||
/// Generate shell completions.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal completion bash\n chronoseal completion zsh > ~/.zfunc/_chronoseal"
|
||||
)]
|
||||
Completion { shell: clap_complete::Shell },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Args)]
|
||||
pub struct RunArgs {
|
||||
#[command(flatten)]
|
||||
pub runtime: RuntimeArgs,
|
||||
|
||||
/// SQLite database path. Use ':memory:' for ephemeral state.
|
||||
#[arg(long, env = "CHRONOSEAL_DB_PATH")]
|
||||
pub db_path: Option<PathBuf>,
|
||||
|
||||
/// Static frontend directory served at /.
|
||||
#[arg(long, env = "CHRONOSEAL_FRONTEND_DIR")]
|
||||
pub frontend_dir: Option<PathBuf>,
|
||||
|
||||
/// Optional structured JSON log file.
|
||||
#[arg(long, env = "CHRONOSEAL_LOG_FILE")]
|
||||
pub log_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Args)]
|
||||
pub struct RuntimeArgs {
|
||||
/// Socket address the daemon binds to, or that CLI probes connect to.
|
||||
#[arg(long, env = "CHRONOSEAL_BIND")]
|
||||
pub bind: Option<String>,
|
||||
|
||||
/// PID file path.
|
||||
#[arg(long, env = "CHRONOSEAL_PID_FILE")]
|
||||
pub pid_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum ConfigCommand {
|
||||
/// Validate configuration and print the effective values.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal config check\n chronoseal config check --config /etc/chronoseal/config.toml\n chronoseal config check --output json"
|
||||
)]
|
||||
Check(RuntimeArgs),
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum GenerateCommand {
|
||||
/// Generate an Ed25519 keypair as hex-encoded JSON/YAML/text.
|
||||
#[command(
|
||||
after_help = "Examples:\n chronoseal generate keypair\n chronoseal generate keypair --format json"
|
||||
)]
|
||||
Keypair,
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use crate::cli::{RunArgs, RuntimeArgs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
env, fs, io,
|
||||
net::SocketAddr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
pub bind: String,
|
||||
pub pid_file: PathBuf,
|
||||
pub db_path: PathBuf,
|
||||
pub frontend_dir: PathBuf,
|
||||
pub log_file: Option<PathBuf>,
|
||||
pub heartbeat_min_interval_ms: u64,
|
||||
pub heartbeat_max_interval_ms: u64,
|
||||
pub expiration_minutes: i64,
|
||||
pub rate_limit_count: u32,
|
||||
pub rate_limit_window_secs: u64,
|
||||
pub max_timestamp_drift_ms: i64,
|
||||
pub min_mouse_total_dist: f64,
|
||||
pub max_mouse_avg_speed: f64,
|
||||
pub min_pause_count: u32,
|
||||
pub require_mouse_activity: bool,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bind: "0.0.0.0:3000".to_string(),
|
||||
pid_file: PathBuf::from("/run/chronoseal.pid"),
|
||||
db_path: default_state_dir().join("chronoseal.sqlite"),
|
||||
frontend_dir: PathBuf::from("/usr/share/chronoseal/frontend"),
|
||||
log_file: None,
|
||||
heartbeat_min_interval_ms: 12_000,
|
||||
heartbeat_max_interval_ms: 25_000,
|
||||
expiration_minutes: 30,
|
||||
rate_limit_count: 5,
|
||||
rate_limit_window_secs: 10,
|
||||
max_timestamp_drift_ms: 30_000,
|
||||
min_mouse_total_dist: 10.0,
|
||||
max_mouse_avg_speed: 2.0,
|
||||
min_pause_count: 1,
|
||||
require_mouse_activity: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load(config_path: Option<&Path>) -> Result<Self, ConfigError> {
|
||||
let mut config = Self::default();
|
||||
|
||||
if let Some(path) = config_path
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(discover_config_path)
|
||||
{
|
||||
let raw = fs::read_to_string(&path).map_err(|source| ConfigError::Read {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
config = toml::from_str(&raw).map_err(|source| ConfigError::Parse {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
config.apply_env();
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn apply_runtime_args(&mut self, args: &RuntimeArgs) {
|
||||
if let Some(bind) = &args.bind {
|
||||
self.bind.clone_from(bind);
|
||||
}
|
||||
if let Some(pid_file) = &args.pid_file {
|
||||
self.pid_file = pid_file.clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_run_args(&mut self, args: &RunArgs) {
|
||||
self.apply_runtime_args(&args.runtime);
|
||||
if let Some(db_path) = &args.db_path {
|
||||
self.db_path = db_path.clone();
|
||||
}
|
||||
if let Some(frontend_dir) = &args.frontend_dir {
|
||||
self.frontend_dir = frontend_dir.clone();
|
||||
}
|
||||
if let Some(log_file) = &args.log_file {
|
||||
self.log_file = Some(log_file.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||
self.bind
|
||||
.parse::<SocketAddr>()
|
||||
.map_err(|source| ConfigError::InvalidBind {
|
||||
bind: self.bind.clone(),
|
||||
source,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_env(&mut self) {
|
||||
if let Ok(value) = env::var("CHRONOSEAL_BIND") {
|
||||
self.bind = value;
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_PID_FILE") {
|
||||
self.pid_file = PathBuf::from(value);
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_DB_PATH") {
|
||||
self.db_path = PathBuf::from(value);
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_FRONTEND_DIR") {
|
||||
self.frontend_dir = PathBuf::from(value);
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_LOG_FILE") {
|
||||
self.log_file = Some(PathBuf::from(value));
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_HEARTBEAT_MIN_INTERVAL_MS") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.heartbeat_min_interval_ms = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_HEARTBEAT_MAX_INTERVAL_MS") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.heartbeat_max_interval_ms = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_EXPIRATION_MINUTES") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.expiration_minutes = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_RATE_LIMIT_COUNT") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.rate_limit_count = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_RATE_LIMIT_WINDOW_SECS") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.rate_limit_window_secs = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_MAX_TIMESTAMP_DRIFT_MS") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.max_timestamp_drift_ms = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_MIN_MOUSE_TOTAL_DIST") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.min_mouse_total_dist = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_MAX_MOUSE_AVG_SPEED") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.max_mouse_avg_speed = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_MIN_PAUSE_COUNT") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.min_pause_count = val;
|
||||
}
|
||||
}
|
||||
if let Ok(value) = env::var("CHRONOSEAL_REQUIRE_MOUSE_ACTIVITY") {
|
||||
if let Ok(val) = value.parse() {
|
||||
self.require_mouse_activity = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
Read {
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
source: toml::de::Error,
|
||||
},
|
||||
InvalidBind {
|
||||
bind: String,
|
||||
source: std::net::AddrParseError,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ConfigError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Read { path, source } => write!(f, "failed to read {}: {source}", path.display()),
|
||||
Self::Parse { path, source } => {
|
||||
write!(f, "failed to parse {} as TOML: {source}", path.display())
|
||||
}
|
||||
Self::InvalidBind { bind, source } => {
|
||||
write!(f, "invalid bind address {bind}: {source}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigError {}
|
||||
|
||||
fn discover_config_path() -> Option<PathBuf> {
|
||||
if let Ok(path) = env::var("CHRONOSEAL_CONFIG") {
|
||||
let p = PathBuf::from(path);
|
||||
if p.is_file() {
|
||||
return Some(p);
|
||||
}
|
||||
}
|
||||
user_config_candidates()
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.is_file())
|
||||
}
|
||||
|
||||
pub fn user_config_candidates() -> Vec<PathBuf> {
|
||||
let mut candidates = vec![PathBuf::from("/etc/chronoseal/config.toml")];
|
||||
if let Ok(xdg) = env::var("XDG_CONFIG_HOME") {
|
||||
candidates.push(PathBuf::from(xdg).join("chronoseal/config.toml"));
|
||||
} else if let Ok(home) = env::var("HOME") {
|
||||
candidates.push(PathBuf::from(home).join(".config/chronoseal/config.toml"));
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
fn default_state_dir() -> PathBuf {
|
||||
if let Ok(value) = env::var("CHRONOSEAL_STATE_DIR") {
|
||||
return PathBuf::from(value);
|
||||
}
|
||||
if let Ok(value) = env::var("XDG_STATE_HOME") {
|
||||
return PathBuf::from(value).join("chronoseal");
|
||||
}
|
||||
if let Ok(home) = env::var("HOME") {
|
||||
return PathBuf::from(home).join(".local/state/chronoseal");
|
||||
}
|
||||
PathBuf::from("/var/lib/chronoseal")
|
||||
}
|
||||
@@ -6,9 +6,7 @@ pub fn verify_signature(
|
||||
pub_key_bytes: &[u8],
|
||||
req: &HeartbeatRequest,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let pk = VerifyingKey::from_bytes(
|
||||
&pub_key_bytes.try_into().map_err(|_| "invalid pubkey")?,
|
||||
)?;
|
||||
let pk = VerifyingKey::from_bytes(&pub_key_bytes.try_into().map_err(|_| "invalid pubkey")?)?;
|
||||
let sig_bytes = hex::decode(&req.signature)?;
|
||||
let sig = Signature::from_slice(&sig_bytes)?;
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum SessionError {
|
||||
#[error("Hex decoding error: {0}")]
|
||||
Hex(#[from] hex::FromHexError),
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
Database(#[from] rusqlite::Error),
|
||||
|
||||
#[error("R2D2 pool error: {0}")]
|
||||
Pool(#[from] r2d2::Error),
|
||||
|
||||
#[error("Invalid public key length")]
|
||||
InvalidPublicKeyLength,
|
||||
}
|
||||
|
||||
impl IntoResponse for SessionError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, error_message) = match self {
|
||||
SessionError::InvalidPublicKeyLength => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||
_ => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Internal server error".to_string(),
|
||||
),
|
||||
};
|
||||
let body = Json(json!({
|
||||
"error": error_message
|
||||
}));
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum VerificationError {
|
||||
#[error("Session not found")]
|
||||
SessionNotFound,
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
Database(#[from] rusqlite::Error),
|
||||
|
||||
#[error("Hex decoding error: {0}")]
|
||||
Hex(#[from] hex::FromHexError),
|
||||
|
||||
#[error("Signature verification error: {0}")]
|
||||
Signature(String),
|
||||
|
||||
#[error("Session has expired")]
|
||||
Expired,
|
||||
|
||||
#[error("Chain is broken")]
|
||||
ChainBroken,
|
||||
|
||||
#[error("Timestamp drift exceeded threshold")]
|
||||
TimestampDrift,
|
||||
|
||||
#[error("Trust criteria failed: {0}")]
|
||||
TrustFailed(String),
|
||||
|
||||
#[error("Fingerprint validation failed: {0}")]
|
||||
FingerprintFailed(String),
|
||||
}
|
||||
@@ -2,9 +2,15 @@ use shared::protocol::Fingerprint;
|
||||
|
||||
pub fn validate(fp: &Fingerprint) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let ar: f64 = fp.aspect_ratio.parse().map_err(|_| "ar")?;
|
||||
if ar < 0.5 || ar > 3.0 { return Err("aspect ratio".into()); }
|
||||
if !(0.5..=3.0).contains(&ar) {
|
||||
return Err("aspect ratio".into());
|
||||
}
|
||||
let dpr: f64 = fp.device_pixel_ratio.parse().map_err(|_| "dpr")?;
|
||||
if dpr <= 0.0 || dpr > 5.0 { return Err("dpr".into()); }
|
||||
if fp.hardware_concurrency == 0 { return Err("hw".into()); }
|
||||
if dpr <= 0.0 || dpr > 5.0 {
|
||||
return Err("dpr".into());
|
||||
}
|
||||
if fp.hardware_concurrency == 0 {
|
||||
return Err("hw".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+128
-28
@@ -1,47 +1,147 @@
|
||||
mod cleanup;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod crypto;
|
||||
mod errors;
|
||||
mod fingerprint;
|
||||
mod middleware;
|
||||
mod output;
|
||||
mod ratelimit;
|
||||
mod routes;
|
||||
mod runtime;
|
||||
mod session;
|
||||
mod storage;
|
||||
mod trust;
|
||||
mod vm;
|
||||
|
||||
use axum::Router;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::info;
|
||||
|
||||
use session::AppState;
|
||||
use clap::{CommandFactory, Parser};
|
||||
use cli::{Cli, Command, ConfigCommand, GenerateCommand};
|
||||
use config::Config;
|
||||
use std::path::PathBuf;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
if let Err(err) = try_main().await {
|
||||
eprintln!("chronoseal: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
let conn = storage::init_db().expect("DB init");
|
||||
let state = Arc::new(AppState {
|
||||
db: Mutex::new(conn),
|
||||
rate_limiter: Mutex::new(ratelimit::RateLimiter::new(
|
||||
shared::constants::RATE_LIMIT_COUNT,
|
||||
shared::constants::RATE_LIMIT_WINDOW_SECS,
|
||||
)),
|
||||
});
|
||||
async fn try_main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cli = Cli::parse();
|
||||
if let Some(config_path) = cli.globals.config.as_deref() {
|
||||
std::env::set_var("CHRONOSEAL_CONFIG", config_path);
|
||||
}
|
||||
let log_filter = cli.globals.log.as_deref().unwrap_or("info");
|
||||
let log_file = log_file_for_command(&cli);
|
||||
let _log_guard = init_logging(log_filter, log_file)?;
|
||||
|
||||
// Periodic cleanup
|
||||
let bg_state = state.clone();
|
||||
tokio::spawn(async move { cleanup::cleanup_loop(bg_state).await });
|
||||
match &cli.command {
|
||||
None | Some(Command::Run(_)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
if let Some(Command::Run(args)) = &cli.command {
|
||||
config.apply_run_args(args);
|
||||
config.validate()?;
|
||||
}
|
||||
runtime::run_daemon(config).await?;
|
||||
}
|
||||
Some(Command::Status(args)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
config.apply_runtime_args(args);
|
||||
config.validate()?;
|
||||
output::print(cli.globals.output_format(), &runtime::probe_status(&config))?;
|
||||
}
|
||||
Some(Command::Health(args)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
config.apply_runtime_args(args);
|
||||
config.validate()?;
|
||||
let report = runtime::probe_health(&config);
|
||||
let healthy = report.status == "healthy";
|
||||
output::print(cli.globals.output_format(), &report)?;
|
||||
if !healthy {
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
Some(Command::Config(ConfigCommand::Check(args))) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
config.apply_runtime_args(args);
|
||||
config.validate()?;
|
||||
output::print(cli.globals.output_format(), &config)?;
|
||||
}
|
||||
Some(Command::Generate(GenerateCommand::Keypair)) => {
|
||||
output::print(cli.globals.output_format(), &runtime::generate_keypair())?;
|
||||
}
|
||||
Some(Command::Version) => {
|
||||
output::print(cli.globals.output_format(), &runtime::version())?;
|
||||
}
|
||||
Some(Command::Metrics(args)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
config.apply_runtime_args(args);
|
||||
config.validate()?;
|
||||
print!("{}", runtime::fetch_metrics(&config)?);
|
||||
}
|
||||
Some(Command::Stats(args)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref())?;
|
||||
config.apply_runtime_args(args);
|
||||
config.validate()?;
|
||||
output::print(cli.globals.output_format(), &runtime::fetch_stats(&config)?)?;
|
||||
}
|
||||
Some(Command::Completion { shell }) => {
|
||||
let mut command = Cli::command();
|
||||
let name = command.get_name().to_string();
|
||||
clap_complete::generate(*shell, &mut command, name, &mut std::io::stdout());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let app = Router::new()
|
||||
.route("/init", axum::routing::post(routes::init::handler))
|
||||
.route("/hb", axum::routing::post(routes::heartbeat::handler))
|
||||
.nest_service("/", tower_http::services::ServeDir::new("../frontend"))
|
||||
.layer(tower_http::cors::CorsLayer::permissive())
|
||||
.layer(axum::middleware::from_fn(middleware::log_request))
|
||||
.with_state(state);
|
||||
fn log_file_for_command(cli: &Cli) -> Option<PathBuf> {
|
||||
match &cli.command {
|
||||
None => Config::load(cli.globals.config.as_deref())
|
||||
.ok()
|
||||
.and_then(|config| config.log_file),
|
||||
Some(Command::Run(args)) => {
|
||||
let mut config = Config::load(cli.globals.config.as_deref()).ok()?;
|
||||
config.apply_run_args(args);
|
||||
config.log_file
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
info!("Server running on :3000");
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
fn init_logging(
|
||||
filter: &str,
|
||||
log_file: Option<PathBuf>,
|
||||
) -> Result<Option<tracing_appender::non_blocking::WorkerGuard>, Box<dyn std::error::Error>> {
|
||||
let env_filter = EnvFilter::try_new(filter)?;
|
||||
if let Some(path) = log_file {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let directory = path.parent().unwrap_or_else(|| std::path::Path::new("."));
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("chronoseal.jsonl");
|
||||
let appender = tracing_appender::rolling::never(directory, file_name);
|
||||
let (writer, guard) = tracing_appender::non_blocking(appender);
|
||||
tracing_subscriber::registry()
|
||||
.with(env_filter)
|
||||
.with(tracing_subscriber::fmt::layer().with_target(false))
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.json()
|
||||
.with_target(false)
|
||||
.with_writer(writer),
|
||||
)
|
||||
.init();
|
||||
Ok(Some(guard))
|
||||
} else {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(env_filter)
|
||||
.with_target(false)
|
||||
.init();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use crate::cli::OutputFormat;
|
||||
use serde::Serialize;
|
||||
|
||||
pub fn print<T>(format: OutputFormat, value: &T) -> Result<(), Box<dyn std::error::Error>>
|
||||
where
|
||||
T: Serialize + TextOutput,
|
||||
{
|
||||
match format {
|
||||
OutputFormat::Text => println!("{}", value.to_text()),
|
||||
OutputFormat::Json => println!("{}", serde_json::to_string_pretty(value)?),
|
||||
OutputFormat::Yaml => print!("{}", serde_yaml::to_string(value)?),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub trait TextOutput {
|
||||
fn to_text(&self) -> String;
|
||||
}
|
||||
+44
-10
@@ -3,22 +3,22 @@ use std::time::Instant;
|
||||
|
||||
pub struct RateLimiter {
|
||||
buckets: HashMap<String, (u32, Instant)>,
|
||||
limit: u32,
|
||||
window_secs: u64,
|
||||
}
|
||||
|
||||
impl RateLimiter {
|
||||
pub fn new(limit: u32, window_secs: u64) -> Self {
|
||||
Self { buckets: HashMap::new(), limit, window_secs }
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
buckets: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(&mut self, key: &str) -> bool {
|
||||
pub fn check(&mut self, key: &str, limit: u32, window_secs: u64) -> bool {
|
||||
let now = Instant::now();
|
||||
let entry = self.buckets.entry(key.to_string()).or_insert((0, now));
|
||||
if now.duration_since(entry.1).as_secs() >= self.window_secs {
|
||||
if now.duration_since(entry.1).as_secs() >= window_secs {
|
||||
*entry = (1, now);
|
||||
true
|
||||
} else if entry.0 >= self.limit {
|
||||
} else if entry.0 >= limit {
|
||||
false
|
||||
} else {
|
||||
entry.0 += 1;
|
||||
@@ -28,10 +28,44 @@ impl RateLimiter {
|
||||
|
||||
/// Remove entries whose rate-limit window has fully elapsed.
|
||||
/// Call this periodically (e.g. from the cleanup loop) to bound memory usage.
|
||||
pub fn evict_stale(&mut self) {
|
||||
let window = self.window_secs;
|
||||
pub fn evict_stale(&mut self, window_secs: u64) {
|
||||
let now = Instant::now();
|
||||
self.buckets
|
||||
.retain(|_, (_, ts)| now.duration_since(*ts).as_secs() < window);
|
||||
.retain(|_, (_, ts)| now.duration_since(*ts).as_secs() < window_secs);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn test_rate_limiter() {
|
||||
let mut rl = RateLimiter::new();
|
||||
// Limit of 2 requests per 1 second window
|
||||
assert!(rl.check("user1", 2, 1));
|
||||
assert!(rl.check("user1", 2, 1));
|
||||
assert!(!rl.check("user1", 2, 1)); // 3rd fails
|
||||
|
||||
assert!(rl.check("user2", 2, 1)); // different key succeeds
|
||||
|
||||
thread::sleep(Duration::from_millis(1100));
|
||||
assert!(rl.check("user1", 2, 1)); // succeeds after time window
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rate_limiter_eviction() {
|
||||
let mut rl = RateLimiter::new();
|
||||
assert!(rl.check("user1", 1, 1));
|
||||
assert_eq!(rl.buckets.len(), 1);
|
||||
|
||||
rl.evict_stale(1);
|
||||
assert_eq!(rl.buckets.len(), 1); // not stale yet
|
||||
|
||||
thread::sleep(Duration::from_millis(1100));
|
||||
rl.evict_stale(1);
|
||||
assert_eq!(rl.buckets.len(), 0); // evicted
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use axum::{extract::State, http::StatusCode, Json};
|
||||
use std::sync::Arc;
|
||||
use shared::protocol::{HeartbeatRequest, HeartbeatResponse};
|
||||
use crate::session::AppState;
|
||||
use axum::{extract::State, http::StatusCode, Json};
|
||||
use shared::protocol::{HeartbeatRequest, HeartbeatResponse};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub async fn handler(
|
||||
State(state): State<Arc<AppState>>,
|
||||
@@ -9,22 +9,54 @@ pub async fn handler(
|
||||
) -> (StatusCode, Json<HeartbeatResponse>) {
|
||||
// Rate limiting
|
||||
{
|
||||
let (limit, window_secs) = {
|
||||
let cfg = state.get_config();
|
||||
(cfg.rate_limit_count, cfg.rate_limit_window_secs)
|
||||
};
|
||||
let mut rl = state.rate_limiter.lock().await;
|
||||
if !rl.check(&payload.session_id) {
|
||||
if !rl.check(&payload.session_id, limit, window_secs) {
|
||||
tracing::debug!("Rate limit hit: {}", payload.session_id);
|
||||
return (StatusCode::OK, Json(HeartbeatResponse { status: "ok".into(), next_salt: None }));
|
||||
return (
|
||||
StatusCode::OK,
|
||||
Json(HeartbeatResponse {
|
||||
status: "ok".into(),
|
||||
next_salt: None,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let db = state.db.lock().await;
|
||||
match crate::session::verify_heartbeat(&db, &payload) {
|
||||
let config = state.get_config();
|
||||
let conn = match state.db_pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::error!("Db pool error: {}", e);
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(HeartbeatResponse {
|
||||
status: "error".into(),
|
||||
next_salt: None,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
match crate::session::verify_heartbeat(&conn, &config, &payload) {
|
||||
Ok(next_salt) => (
|
||||
StatusCode::OK,
|
||||
Json(HeartbeatResponse { status: "ok".into(), next_salt: Some(next_salt) }),
|
||||
Json(HeartbeatResponse {
|
||||
status: "ok".into(),
|
||||
next_salt: Some(next_salt),
|
||||
}),
|
||||
),
|
||||
Err(e) => {
|
||||
tracing::warn!("Heartbeat failed for {}: {}", payload.session_id, e);
|
||||
(StatusCode::OK, Json(HeartbeatResponse { status: "ok".into(), next_salt: None }))
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(HeartbeatResponse {
|
||||
status: "ok".into(),
|
||||
next_salt: None,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
use axum::{extract::State, http::StatusCode, Json};
|
||||
use std::sync::Arc;
|
||||
use shared::protocol::{InitRequest, InitResponse};
|
||||
use crate::errors::SessionError;
|
||||
use crate::session::AppState;
|
||||
use axum::{extract::State, Json};
|
||||
use shared::protocol::{InitRequest, InitResponse};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub async fn handler(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(payload): Json<InitRequest>,
|
||||
) -> Result<Json<InitResponse>, (StatusCode, String)> {
|
||||
let db = state.db.lock().await;
|
||||
crate::session::create_session(&db, &payload.public_key)
|
||||
.map(Json)
|
||||
.map_err(|e| {
|
||||
tracing::error!("Init error: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Internal".into())
|
||||
})
|
||||
) -> Result<Json<InitResponse>, SessionError> {
|
||||
let config = state.get_config();
|
||||
let conn = state.db_pool.get()?;
|
||||
let resp = crate::session::create_session(&conn, &config, &payload.public_key)?;
|
||||
Ok(Json(resp))
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
pub mod init;
|
||||
pub mod heartbeat;
|
||||
pub mod init;
|
||||
@@ -0,0 +1,341 @@
|
||||
use crate::{
|
||||
config::Config,
|
||||
output::TextOutput,
|
||||
ratelimit::RateLimiter,
|
||||
routes, session,
|
||||
storage::{self, StoreStats},
|
||||
};
|
||||
use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
net::{SocketAddr, TcpStream},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct HealthReport {
|
||||
pub status: &'static str,
|
||||
pub bind: String,
|
||||
}
|
||||
|
||||
impl TextOutput for HealthReport {
|
||||
fn to_text(&self) -> String {
|
||||
format!("{}\nbind={}", self.status, self.bind)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StatusReport {
|
||||
pub running: bool,
|
||||
pub healthy: bool,
|
||||
pub bind: String,
|
||||
pub pid_file: String,
|
||||
pub pid: Option<u32>,
|
||||
}
|
||||
|
||||
impl TextOutput for StatusReport {
|
||||
fn to_text(&self) -> String {
|
||||
let pid = self
|
||||
.pid
|
||||
.map_or_else(|| "unknown".to_string(), |pid| pid.to_string());
|
||||
format!(
|
||||
"running={}\nhealthy={}\nbind={}\npid_file={}\npid={}",
|
||||
self.running, self.healthy, self.bind, self.pid_file, pid
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct VersionReport {
|
||||
pub name: &'static str,
|
||||
pub version: &'static str,
|
||||
pub target: &'static str,
|
||||
}
|
||||
|
||||
impl TextOutput for VersionReport {
|
||||
fn to_text(&self) -> String {
|
||||
format!("{} {}", self.name, self.version)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct KeypairReport {
|
||||
pub algorithm: &'static str,
|
||||
pub public_key_hex: String,
|
||||
pub private_key_hex: String,
|
||||
}
|
||||
|
||||
impl TextOutput for KeypairReport {
|
||||
fn to_text(&self) -> String {
|
||||
format!(
|
||||
"algorithm={}\npublic_key_hex={}\nprivate_key_hex={}",
|
||||
self.algorithm, self.public_key_hex, self.private_key_hex
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl TextOutput for Config {
|
||||
fn to_text(&self) -> String {
|
||||
format!(
|
||||
"bind={}\npid_file={}\ndb_path={}\nfrontend_dir={}\nlog_file={}",
|
||||
self.bind,
|
||||
self.pid_file.display(),
|
||||
self.db_path.display(),
|
||||
self.frontend_dir.display(),
|
||||
self.log_file
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "none".to_string())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl TextOutput for StoreStats {
|
||||
fn to_text(&self) -> String {
|
||||
format!(
|
||||
"sessions={}\nexpired_sessions={}\nmax_chain_length={}",
|
||||
self.sessions, self.expired_sessions, self.max_chain_length
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_daemon(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||
install_pid_file(&config.pid_file)?;
|
||||
|
||||
let db_pool = storage::init_pool(&config.db_path)?;
|
||||
let state = Arc::new(session::AppState {
|
||||
db_pool,
|
||||
rate_limiter: Mutex::new(RateLimiter::new()),
|
||||
config: std::sync::RwLock::new(config.clone()),
|
||||
});
|
||||
|
||||
let bg_state = state.clone();
|
||||
tokio::spawn(async move { crate::cleanup::cleanup_loop(bg_state).await });
|
||||
|
||||
let app = Router::new()
|
||||
.route("/init", axum::routing::post(routes::init::handler))
|
||||
.route("/hb", axum::routing::post(routes::heartbeat::handler))
|
||||
.route("/health", get(health_handler))
|
||||
.route("/metrics", get(metrics_handler))
|
||||
.route("/stats", get(stats_handler))
|
||||
.nest_service(
|
||||
"/",
|
||||
tower_http::services::ServeDir::new(&config.frontend_dir),
|
||||
)
|
||||
.layer(tower_http::cors::CorsLayer::permissive())
|
||||
.layer(axum::middleware::from_fn(crate::middleware::log_request))
|
||||
.with_state(state.clone());
|
||||
|
||||
let addr: SocketAddr = config.bind.parse()?;
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
info!(bind = %config.bind, "chronoseal daemon started");
|
||||
|
||||
let shutdown = signal_task(state.clone());
|
||||
let result = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown)
|
||||
.await;
|
||||
|
||||
remove_pid_file(&config.pid_file);
|
||||
result?;
|
||||
info!("chronoseal daemon stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn probe_health(config: &Config) -> HealthReport {
|
||||
if http_get(&config.bind, "/health").is_ok() {
|
||||
HealthReport {
|
||||
status: "healthy",
|
||||
bind: config.bind.clone(),
|
||||
}
|
||||
} else {
|
||||
HealthReport {
|
||||
status: "unreachable",
|
||||
bind: config.bind.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn probe_status(config: &Config) -> StatusReport {
|
||||
let pid = read_pid(&config.pid_file);
|
||||
let healthy = http_get(&config.bind, "/health").is_ok();
|
||||
StatusReport {
|
||||
running: pid.is_some() || healthy,
|
||||
healthy,
|
||||
bind: config.bind.clone(),
|
||||
pid_file: config.pid_file.display().to_string(),
|
||||
pid,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_metrics(config: &Config) -> Result<String, Box<dyn std::error::Error>> {
|
||||
http_get(&config.bind, "/metrics")
|
||||
}
|
||||
|
||||
pub fn fetch_stats(config: &Config) -> Result<StoreStats, Box<dyn std::error::Error>> {
|
||||
let body = http_get(&config.bind, "/stats")?;
|
||||
Ok(serde_json::from_str(&body)?)
|
||||
}
|
||||
|
||||
pub fn generate_keypair() -> KeypairReport {
|
||||
let private_key = rand::random::<[u8; 32]>();
|
||||
let signing_key = ed25519_dalek::SigningKey::from_bytes(&private_key);
|
||||
let verifying_key = signing_key.verifying_key();
|
||||
KeypairReport {
|
||||
algorithm: "ed25519",
|
||||
public_key_hex: hex::encode(verifying_key.to_bytes()),
|
||||
private_key_hex: hex::encode(private_key),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version() -> VersionReport {
|
||||
VersionReport {
|
||||
name: "chronoseal",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
target: std::env::consts::ARCH,
|
||||
}
|
||||
}
|
||||
|
||||
async fn health_handler() -> impl IntoResponse {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({ "status": "healthy" })),
|
||||
)
|
||||
}
|
||||
|
||||
async fn stats_handler(
|
||||
axum::extract::State(state): axum::extract::State<Arc<session::AppState>>,
|
||||
) -> Result<Json<StoreStats>, (StatusCode, String)> {
|
||||
let db = state
|
||||
.db_pool
|
||||
.get()
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
storage::stats(&db)
|
||||
.map(Json)
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
|
||||
}
|
||||
|
||||
async fn metrics_handler(
|
||||
axum::extract::State(state): axum::extract::State<Arc<session::AppState>>,
|
||||
) -> Result<String, (StatusCode, String)> {
|
||||
let db = state
|
||||
.db_pool
|
||||
.get()
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
storage::stats(&db)
|
||||
.map(|stats| {
|
||||
format!(
|
||||
"# HELP chronoseal_sessions Active ChronoSeal sessions\n# TYPE chronoseal_sessions gauge\nchronoseal_sessions {}\n# HELP chronoseal_expired_sessions Expired sessions not yet removed\n# TYPE chronoseal_expired_sessions gauge\nchronoseal_expired_sessions {}\n# HELP chronoseal_max_chain_length Maximum heartbeat chain length\n# TYPE chronoseal_max_chain_length gauge\nchronoseal_max_chain_length {}\n",
|
||||
stats.sessions, stats.expired_sessions, stats.max_chain_length
|
||||
)
|
||||
})
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
|
||||
}
|
||||
|
||||
async fn signal_task(state: Arc<session::AppState>) {
|
||||
let shutdown = Arc::new(Notify::new());
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
|
||||
let shutdown_term = shutdown.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut sigterm = signal(SignalKind::terminate()).expect("install SIGTERM handler");
|
||||
sigterm.recv().await;
|
||||
info!("received SIGTERM; shutting down gracefully");
|
||||
shutdown_term.notify_one();
|
||||
});
|
||||
|
||||
let shutdown_int = shutdown.clone();
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
info!("received interrupt; shutting down gracefully");
|
||||
shutdown_int.notify_one();
|
||||
}
|
||||
});
|
||||
|
||||
let state_for_hup = state.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut sighup = signal(SignalKind::hangup()).expect("install SIGHUP handler");
|
||||
while sighup.recv().await.is_some() {
|
||||
match Config::load(None) {
|
||||
Ok(reloaded) => {
|
||||
info!(
|
||||
bind = %reloaded.bind,
|
||||
db_path = %reloaded.db_path.display(),
|
||||
"received SIGHUP; configuration reloaded"
|
||||
);
|
||||
if let Ok(mut config_write) = state_for_hup.config.write() {
|
||||
*config_write = reloaded;
|
||||
}
|
||||
}
|
||||
Err(err) => warn!(error = %err, "received SIGHUP; configuration reload failed"),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut sigusr1 = signal(SignalKind::user_defined1()).expect("install SIGUSR1 handler");
|
||||
while sigusr1.recv().await.is_some() {
|
||||
info!("received SIGUSR1; stats are available via chronoseal stats or /stats");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
shutdown.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
shutdown.notified().await;
|
||||
}
|
||||
|
||||
fn install_pid_file(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if let Some(parent) = path.parent() {
|
||||
if let Err(err) = fs::create_dir_all(parent) {
|
||||
warn!(path = %parent.display(), error = %err, "could not create PID directory");
|
||||
}
|
||||
}
|
||||
match fs::write(path, std::process::id().to_string()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
warn!(path = %path.display(), error = %err, "could not write PID file");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_pid_file(path: &Path) {
|
||||
if let Err(err) = fs::remove_file(path) {
|
||||
if err.kind() != std::io::ErrorKind::NotFound {
|
||||
error!(path = %path.display(), error = %err, "could not remove PID file");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_pid(path: &Path) -> Option<u32> {
|
||||
fs::read_to_string(path).ok()?.trim().parse().ok()
|
||||
}
|
||||
|
||||
fn http_get(bind: &str, path: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let mut stream = TcpStream::connect_timeout(&bind.parse()?, Duration::from_secs(2))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.write_all(
|
||||
format!("GET {path} HTTP/1.1\r\nHost: chronoseal\r\nConnection: close\r\n\r\n").as_bytes(),
|
||||
)?;
|
||||
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response)?;
|
||||
let (_, body) = response
|
||||
.split_once("\r\n\r\n")
|
||||
.ok_or("daemon returned an invalid HTTP response")?;
|
||||
Ok(body.to_string())
|
||||
}
|
||||
+141
-15
@@ -1,24 +1,36 @@
|
||||
pub struct AppState {
|
||||
pub db: tokio::sync::Mutex<rusqlite::Connection>,
|
||||
pub db_pool: crate::storage::DbPool,
|
||||
pub rate_limiter: tokio::sync::Mutex<crate::ratelimit::RateLimiter>,
|
||||
pub config: std::sync::RwLock<crate::config::Config>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn get_config(&self) -> crate::config::Config {
|
||||
if let Ok(cfg) = self.config.read() {
|
||||
cfg.clone()
|
||||
} else {
|
||||
crate::config::Config::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::{crypto, fingerprint, storage, trust, vm};
|
||||
use rusqlite::params;
|
||||
use shared::protocol::{HeartbeatRequest, InitResponse};
|
||||
use crate::{crypto, trust, fingerprint, vm, storage};
|
||||
|
||||
pub fn create_session(
|
||||
conn: &rusqlite::Connection,
|
||||
config: &crate::config::Config,
|
||||
pub_key_hex: &str,
|
||||
) -> Result<InitResponse, Box<dyn std::error::Error>> {
|
||||
) -> Result<InitResponse, crate::errors::SessionError> {
|
||||
let pub_key = hex::decode(pub_key_hex)?;
|
||||
if pub_key.len() != shared::constants::SESSION_ID_LEN {
|
||||
return Err("invalid pubkey len".into());
|
||||
return Err(crate::errors::SessionError::InvalidPublicKeyLength);
|
||||
}
|
||||
let session_id = hex::encode(rand::random::<[u8; shared::constants::SESSION_ID_LEN]>());
|
||||
let salt = rand::random::<[u8; shared::constants::SALT_LEN]>();
|
||||
let now = storage::current_time_ms();
|
||||
let expires_at = now + (shared::constants::EXPIRATION_MINUTES as u64) * 60 * 1000;
|
||||
let expires_at = now + (config.expiration_minutes as u64) * 60 * 1000;
|
||||
|
||||
let initial_hash = shared::hashing::initial_hash(&session_id, &pub_key, &salt);
|
||||
|
||||
@@ -37,43 +49,56 @@ pub fn create_session(
|
||||
opcodes_b64,
|
||||
initial_hash: hex::encode(&initial_hash),
|
||||
expires_at,
|
||||
heartbeat_min_interval_ms: config.heartbeat_min_interval_ms,
|
||||
heartbeat_max_interval_ms: config.heartbeat_max_interval_ms,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn verify_heartbeat(
|
||||
conn: &rusqlite::Connection,
|
||||
config: &crate::config::Config,
|
||||
req: &HeartbeatRequest,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
) -> Result<String, crate::errors::VerificationError> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT public_key, salt, last_hash, expires_at FROM sessions WHERE session_id = ?1",
|
||||
)?;
|
||||
let (pub_key, salt, stored_last_hash, expires_at): (Vec<u8>, Vec<u8>, Vec<u8>, u64) =
|
||||
stmt.query_row(params![req.session_id], |row| {
|
||||
let (pub_key, salt, stored_last_hash, expires_at): (Vec<u8>, Vec<u8>, Vec<u8>, u64) = stmt
|
||||
.query_row(params![req.session_id], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
|
||||
})
|
||||
.map_err(|e| {
|
||||
if matches!(e, rusqlite::Error::QueryReturnedNoRows) {
|
||||
crate::errors::VerificationError::SessionNotFound
|
||||
} else {
|
||||
crate::errors::VerificationError::Database(e)
|
||||
}
|
||||
})?;
|
||||
|
||||
let now = storage::current_time_ms();
|
||||
if now > expires_at {
|
||||
return Err("expired".into());
|
||||
return Err(crate::errors::VerificationError::Expired);
|
||||
}
|
||||
|
||||
// 1. Verify signature
|
||||
crypto::verify_signature(&pub_key, req)?;
|
||||
crypto::verify_signature(&pub_key, req)
|
||||
.map_err(|e| crate::errors::VerificationError::Signature(e.to_string()))?;
|
||||
|
||||
// 2. Check chain continuity
|
||||
if stored_last_hash != hex::decode(&req.prev_hash)? {
|
||||
return Err("chain broken".into());
|
||||
return Err(crate::errors::VerificationError::ChainBroken);
|
||||
}
|
||||
|
||||
// 3. Time window
|
||||
let diff = (now as i64) - (req.timestamp as i64);
|
||||
if diff.abs() > shared::constants::MAX_TIMESTAMP_DRIFT_MS {
|
||||
return Err("timestamp drift".into());
|
||||
if diff.abs() > config.max_timestamp_drift_ms {
|
||||
return Err(crate::errors::VerificationError::TimestampDrift);
|
||||
}
|
||||
|
||||
// 4. Trusted mouse & fingerprint
|
||||
trust::validate_mouse(&req.entropy_data)?;
|
||||
fingerprint::validate(&req.fingerprint)?;
|
||||
trust::validate_mouse(&req.entropy_data, config)
|
||||
.map_err(|e| crate::errors::VerificationError::TrustFailed(e.to_string()))?;
|
||||
fingerprint::validate(&req.fingerprint)
|
||||
.map_err(|e| crate::errors::VerificationError::FingerprintFailed(e.to_string()))?;
|
||||
|
||||
// 5. Compute new hash
|
||||
let prev_hash_bytes = hex::decode(&req.prev_hash)?;
|
||||
@@ -96,3 +121,104 @@ pub fn verify_heartbeat(
|
||||
|
||||
Ok(next_salt_hex)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use shared::protocol::{EntropyData, Fingerprint, HeartbeatRequest, StackState};
|
||||
use std::path::Path;
|
||||
|
||||
fn sign_request(sk: &SigningKey, req: &mut HeartbeatRequest) {
|
||||
let mut payload: std::collections::BTreeMap<&str, serde_json::Value> =
|
||||
std::collections::BTreeMap::new();
|
||||
payload.insert(
|
||||
"entropyData",
|
||||
serde_json::to_value(&req.entropy_data).unwrap(),
|
||||
);
|
||||
payload.insert(
|
||||
"fingerprint",
|
||||
serde_json::to_value(&req.fingerprint).unwrap(),
|
||||
);
|
||||
payload.insert("prevHash", serde_json::json!(req.prev_hash));
|
||||
payload.insert("sessionId", serde_json::json!(req.session_id));
|
||||
payload.insert(
|
||||
"stackState",
|
||||
serde_json::to_value(&req.stack_state).unwrap(),
|
||||
);
|
||||
payload.insert("timestamp", serde_json::json!(req.timestamp));
|
||||
let message = serde_json::to_string(&payload).unwrap();
|
||||
let sig = sk.sign(message.as_bytes());
|
||||
req.signature = hex::encode(sig.to_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_session_lifecycle_and_verification() {
|
||||
let pool = storage::init_pool(Path::new(":memory:")).unwrap();
|
||||
let conn = pool.get().unwrap();
|
||||
|
||||
let config = crate::config::Config {
|
||||
expiration_minutes: 30,
|
||||
max_timestamp_drift_ms: 30000,
|
||||
min_mouse_total_dist: 10.0,
|
||||
max_mouse_avg_speed: 2.0,
|
||||
min_pause_count: 1,
|
||||
require_mouse_activity: false, // simpler for tests
|
||||
..crate::config::Config::default()
|
||||
};
|
||||
|
||||
// Generate Ed25519 keypair
|
||||
let mut rng = rand::thread_rng();
|
||||
let sk = SigningKey::generate(&mut rng);
|
||||
let pk = sk.verifying_key();
|
||||
let pub_key_hex = hex::encode(pk.to_bytes());
|
||||
|
||||
// 1. Create Session
|
||||
let start_time = storage::current_time_ms();
|
||||
let init_resp = create_session(&conn, &config, &pub_key_hex).unwrap();
|
||||
assert!(init_resp.expires_at >= start_time + 30 * 60 * 1000);
|
||||
assert!(init_resp.expires_at <= storage::current_time_ms() + 30 * 60 * 1000);
|
||||
|
||||
// Verify stats
|
||||
let stats = storage::stats(&conn).unwrap();
|
||||
assert_eq!(stats.sessions, 1);
|
||||
assert_eq!(stats.expired_sessions, 0);
|
||||
|
||||
// 2. Heartbeat Verification
|
||||
let now = storage::current_time_ms();
|
||||
let entropy_data = EntropyData { events: vec![] };
|
||||
let stack_state = StackState {
|
||||
stack: vec![42],
|
||||
ip: 5,
|
||||
};
|
||||
let fingerprint = Fingerprint {
|
||||
aspect_ratio: "1.77".to_string(),
|
||||
device_pixel_ratio: "2.0".to_string(),
|
||||
hardware_concurrency: 8,
|
||||
};
|
||||
|
||||
let mut req = HeartbeatRequest {
|
||||
session_id: init_resp.session_id.clone(),
|
||||
prev_hash: init_resp.initial_hash.clone(),
|
||||
timestamp: now,
|
||||
entropy_data,
|
||||
stack_state,
|
||||
fingerprint,
|
||||
signature: "".to_string(),
|
||||
};
|
||||
|
||||
sign_request(&sk, &mut req);
|
||||
|
||||
// Verify successful heartbeat
|
||||
let next_salt = verify_heartbeat(&conn, &config, &req).unwrap();
|
||||
assert!(!next_salt.is_empty());
|
||||
|
||||
// Try duplicate/broken hash chain (prev_hash unchanged but expected next hash in DB)
|
||||
let res = verify_heartbeat(&conn, &config, &req);
|
||||
assert!(res.is_err());
|
||||
assert!(matches!(
|
||||
res.unwrap_err(),
|
||||
crate::errors::VerificationError::ChainBroken
|
||||
));
|
||||
}
|
||||
}
|
||||
+53
-4
@@ -1,8 +1,34 @@
|
||||
use rusqlite::Connection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub fn init_db() -> Result<Connection, rusqlite::Error> {
|
||||
let conn = Connection::open_in_memory()?;
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StoreStats {
|
||||
pub sessions: u64,
|
||||
pub expired_sessions: u64,
|
||||
pub max_chain_length: u64,
|
||||
}
|
||||
|
||||
pub type DbPool = r2d2::Pool<r2d2_sqlite::SqliteConnectionManager>;
|
||||
|
||||
pub fn init_pool(path: &Path) -> Result<DbPool, Box<dyn std::error::Error>> {
|
||||
let manager = if path == Path::new(":memory:") {
|
||||
r2d2_sqlite::SqliteConnectionManager::memory()
|
||||
} else {
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
r2d2_sqlite::SqliteConnectionManager::file(path)
|
||||
};
|
||||
|
||||
let pool = r2d2::Pool::new(manager)?;
|
||||
let conn = pool.get()?;
|
||||
init_schema(&conn)?;
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
fn init_schema(conn: &rusqlite::Connection) -> Result<(), rusqlite::Error> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
@@ -15,9 +41,32 @@ pub fn init_db() -> Result<Connection, rusqlite::Error> {
|
||||
expires_at INTEGER NOT NULL
|
||||
);",
|
||||
)?;
|
||||
Ok(conn)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stats(conn: &Connection) -> Result<StoreStats, rusqlite::Error> {
|
||||
let now = current_time_ms();
|
||||
let sessions = conn.query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))?;
|
||||
let expired_sessions = conn.query_row(
|
||||
"SELECT COUNT(*) FROM sessions WHERE expires_at < ?1",
|
||||
[now],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let max_chain_length = conn.query_row(
|
||||
"SELECT COALESCE(MAX(chain_length), 0) FROM sessions",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(StoreStats {
|
||||
sessions,
|
||||
expired_sessions,
|
||||
max_chain_length,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn current_time_ms() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis() as u64
|
||||
}
|
||||
+188
-6
@@ -1,7 +1,14 @@
|
||||
use crate::config::Config;
|
||||
use shared::protocol::EntropyData;
|
||||
|
||||
pub fn validate_mouse(data: &EntropyData) -> Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn validate_mouse(
|
||||
data: &EntropyData,
|
||||
config: &Config,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let events = &data.events;
|
||||
if !config.require_mouse_activity && events.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if events.len() < 3 {
|
||||
return Err("few events".into());
|
||||
}
|
||||
@@ -19,18 +26,193 @@ pub fn validate_mouse(data: &EntropyData) -> Result<(), Box<dyn std::error::Erro
|
||||
pauses += 1;
|
||||
}
|
||||
}
|
||||
if total_dist < shared::constants::MIN_MOUSE_TOTAL_DIST {
|
||||
if total_dist < config.min_mouse_total_dist {
|
||||
return Err("insufficient distance".into());
|
||||
}
|
||||
// Speed in px/ms: total distance over elapsed wall-clock time of the event window.
|
||||
let total_time_ms =
|
||||
(events.last().unwrap().timestamp_ms - events[0].timestamp_ms).max(1.0);
|
||||
let total_time_ms = (events.last().unwrap().timestamp_ms - events[0].timestamp_ms).max(1.0);
|
||||
let avg_speed = total_dist / total_time_ms;
|
||||
if avg_speed > shared::constants::MAX_MOUSE_AVG_SPEED {
|
||||
if avg_speed > config.max_mouse_avg_speed {
|
||||
return Err("speed too high".into());
|
||||
}
|
||||
if pauses < shared::constants::MIN_PAUSE_COUNT {
|
||||
if pauses < config.min_pause_count {
|
||||
return Err("no pause".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shared::protocol::MouseEvent;
|
||||
|
||||
fn get_default_config() -> Config {
|
||||
Config {
|
||||
min_mouse_total_dist: 10.0,
|
||||
max_mouse_avg_speed: 2.0,
|
||||
min_pause_count: 1,
|
||||
require_mouse_activity: true,
|
||||
..Config::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_success() {
|
||||
let config = get_default_config();
|
||||
// Mouse moves from (0,0) to (5,0) then (15,0) with a pause
|
||||
let events = vec![
|
||||
MouseEvent {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 100.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 5.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 200.0,
|
||||
},
|
||||
// Pause here (dist = 0, time diff = 100ms > 50ms)
|
||||
MouseEvent {
|
||||
x: 5.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 300.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 15.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 400.0,
|
||||
},
|
||||
];
|
||||
let data = EntropyData { events };
|
||||
assert!(validate_mouse(&data, &config).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_insufficient_events() {
|
||||
let config = get_default_config();
|
||||
let events = vec![
|
||||
MouseEvent {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 100.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 5.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 200.0,
|
||||
},
|
||||
];
|
||||
let data = EntropyData { events };
|
||||
let res = validate_mouse(&data, &config);
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.unwrap_err().to_string(), "few events");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_insufficient_distance() {
|
||||
let config = get_default_config();
|
||||
// Total distance is only 5.0 < 10.0
|
||||
let events = vec![
|
||||
MouseEvent {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 100.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 2.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 200.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 2.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 300.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 5.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 400.0,
|
||||
},
|
||||
];
|
||||
let data = EntropyData { events };
|
||||
let res = validate_mouse(&data, &config);
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.unwrap_err().to_string(), "insufficient distance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_too_fast() {
|
||||
let config = get_default_config();
|
||||
// Distance is 200.0, time difference is 70ms -> speed 2.85 > 2.0
|
||||
let events = vec![
|
||||
MouseEvent {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 100.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 100.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 105.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 100.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 165.0,
|
||||
}, // pause
|
||||
MouseEvent {
|
||||
x: 200.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 170.0,
|
||||
},
|
||||
];
|
||||
let data = EntropyData { events };
|
||||
let res = validate_mouse(&data, &config);
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.unwrap_err().to_string(), "speed too high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_no_pauses() {
|
||||
let config = get_default_config();
|
||||
// Constant movement without any pause
|
||||
let events = vec![
|
||||
MouseEvent {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 100.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 5.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 200.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 10.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 300.0,
|
||||
},
|
||||
MouseEvent {
|
||||
x: 15.0,
|
||||
y: 0.0,
|
||||
timestamp_ms: 400.0,
|
||||
},
|
||||
];
|
||||
let data = EntropyData { events };
|
||||
let res = validate_mouse(&data, &config);
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.unwrap_err().to_string(), "no pause");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_mouse_require_activity_toggle() {
|
||||
let mut config = get_default_config();
|
||||
config.require_mouse_activity = false;
|
||||
|
||||
let data = EntropyData { events: vec![] };
|
||||
assert!(validate_mouse(&data, &config).is_ok());
|
||||
|
||||
config.require_mouse_activity = true;
|
||||
assert!(validate_mouse(&data, &config).is_err());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "shared"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -1,11 +1,2 @@
|
||||
pub const SESSION_ID_LEN: usize = 32;
|
||||
pub const SALT_LEN: usize = 16;
|
||||
pub const HEARTBEAT_MIN_INTERVAL_MS: u64 = 12_000;
|
||||
pub const HEARTBEAT_MAX_INTERVAL_MS: u64 = 25_000;
|
||||
pub const EXPIRATION_MINUTES: i64 = 30;
|
||||
pub const RATE_LIMIT_COUNT: u32 = 5;
|
||||
pub const RATE_LIMIT_WINDOW_SECS: u64 = 10;
|
||||
pub const MAX_TIMESTAMP_DRIFT_MS: i64 = 30_000;
|
||||
pub const MIN_MOUSE_TOTAL_DIST: f64 = 10.0;
|
||||
pub const MAX_MOUSE_AVG_SPEED: f64 = 2.0; // px/ms
|
||||
pub const MIN_PAUSE_COUNT: u32 = 1;
|
||||
@@ -1,5 +1,5 @@
|
||||
use blake3::Hasher;
|
||||
use crate::protocol::{EntropyData, StackState};
|
||||
use blake3::Hasher;
|
||||
|
||||
/// Initial hash for a brand-new session: Blake3(session_id || pub_key || salt)
|
||||
pub fn initial_hash(session_id: &str, pub_key: &[u8], salt: &[u8]) -> Vec<u8> {
|
||||
|
||||
@@ -12,6 +12,8 @@ pub struct InitResponse {
|
||||
pub opcodes_b64: String,
|
||||
pub initial_hash: String,
|
||||
pub expires_at: u64,
|
||||
pub heartbeat_min_interval_ms: u64,
|
||||
pub heartbeat_max_interval_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
[package]
|
||||
name = "chronoseal-wasm"
|
||||
version = "0.2.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
shared = { path = "../shared" }
|
||||
|
||||
+3
-5
@@ -3,7 +3,7 @@ use std::cell::RefCell;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
thread_local! {
|
||||
static KEYPAIR: RefCell<Option<SigningKey>> = RefCell::new(None);
|
||||
static KEYPAIR: RefCell<Option<SigningKey>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
@@ -51,10 +51,8 @@ pub fn compute_next_hash(
|
||||
) -> String {
|
||||
let prev = hex::decode(prev_hash_hex).unwrap_or_default();
|
||||
let salt = hex::decode(salt_hex).unwrap_or_default();
|
||||
let entropy =
|
||||
serde_json::from_str::<shared::protocol::EntropyData>(entropy_data_json).unwrap();
|
||||
let stack =
|
||||
serde_json::from_str::<shared::protocol::StackState>(stack_state_json).unwrap();
|
||||
let entropy = serde_json::from_str::<shared::protocol::EntropyData>(entropy_data_json).unwrap();
|
||||
let stack = serde_json::from_str::<shared::protocol::StackState>(stack_state_json).unwrap();
|
||||
let new = shared::hashing::next_chain_hash(&prev, timestamp, &entropy, &stack, &salt);
|
||||
hex::encode(new)
|
||||
}
|
||||
+155
-7
@@ -1,10 +1,12 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
use shared::protocol::StackState;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn run_program(program_b64: &str) -> JsValue {
|
||||
use base64::Engine;
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(program_b64).unwrap();
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(program_b64)
|
||||
.unwrap();
|
||||
let state = execute(&bytes);
|
||||
serde_wasm_bindgen::to_value(&state).unwrap()
|
||||
}
|
||||
@@ -17,13 +19,22 @@ fn execute(program: &[u8]) -> StackState {
|
||||
ip += 1;
|
||||
match op {
|
||||
0x00 => {
|
||||
if ip + 4 > program.len() { break; }
|
||||
let val = u32::from_le_bytes([program[ip], program[ip+1], program[ip+2], program[ip+3]]);
|
||||
if ip + 4 > program.len() {
|
||||
break;
|
||||
}
|
||||
let val = u32::from_le_bytes([
|
||||
program[ip],
|
||||
program[ip + 1],
|
||||
program[ip + 2],
|
||||
program[ip + 3],
|
||||
]);
|
||||
ip += 4;
|
||||
stack.push(val);
|
||||
}
|
||||
0x01..=0x07 => {
|
||||
if stack.len() < 2 { break; }
|
||||
if stack.len() < 2 {
|
||||
break;
|
||||
}
|
||||
let b = stack.pop().unwrap();
|
||||
let a = stack.pop().unwrap();
|
||||
let r = match op {
|
||||
@@ -39,7 +50,9 @@ fn execute(program: &[u8]) -> StackState {
|
||||
stack.push(r);
|
||||
}
|
||||
0x08 => {
|
||||
if stack.is_empty() { break; }
|
||||
if stack.is_empty() {
|
||||
break;
|
||||
}
|
||||
let a = stack.pop().unwrap();
|
||||
stack.push(!a);
|
||||
}
|
||||
@@ -51,5 +64,140 @@ fn execute(program: &[u8]) -> StackState {
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
StackState { stack, ip: ip as u16 }
|
||||
StackState {
|
||||
stack,
|
||||
ip: ip as u16,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_push() {
|
||||
// PUSH 42, PUSH 100
|
||||
let program = vec![0x00, 42, 0, 0, 0, 0x00, 100, 0, 0, 0];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![42, 100]);
|
||||
assert_eq!(state.ip, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add() {
|
||||
// PUSH 5, PUSH 10, ADD
|
||||
let program = vec![0x00, 5, 0, 0, 0, 0x00, 10, 0, 0, 0, 0x01];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![15]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_wrapping() {
|
||||
// PUSH u32::MAX, PUSH 1, ADD
|
||||
let program = vec![0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 1, 0, 0, 0, 0x01];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sub() {
|
||||
// PUSH 20, PUSH 7, SUB
|
||||
let program = vec![0x00, 20, 0, 0, 0, 0x00, 7, 0, 0, 0, 0x02];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![13]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sub_wrapping() {
|
||||
// PUSH 0, PUSH 1, SUB
|
||||
let program = vec![0x00, 0, 0, 0, 0, 0x00, 1, 0, 0, 0, 0x02];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![u32::MAX]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mul() {
|
||||
// PUSH 6, PUSH 7, MUL
|
||||
let program = vec![0x00, 6, 0, 0, 0, 0x00, 7, 0, 0, 0, 0x03];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![42]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xor() {
|
||||
// PUSH 0b1010, PUSH 0b1100, XOR
|
||||
let program = vec![0x00, 0b1010, 0, 0, 0, 0x00, 0b1100, 0, 0, 0, 0x04];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![0b0110]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_and() {
|
||||
// PUSH 0b1010, PUSH 0b1100, AND
|
||||
let program = vec![0x00, 0b1010, 0, 0, 0, 0x00, 0b1100, 0, 0, 0, 0x05];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![0b1000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_or() {
|
||||
// PUSH 0b1010, PUSH 0b1100, OR
|
||||
let program = vec![0x00, 0b1010, 0, 0, 0, 0x00, 0b1100, 0, 0, 0, 0x06];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![0b1110]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rot() {
|
||||
// PUSH 1, PUSH 4, ROT
|
||||
let program = vec![0x00, 1, 0, 0, 0, 0x00, 4, 0, 0, 0, 0x07];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not() {
|
||||
// PUSH 0, NOT
|
||||
let program = vec![0x00, 0, 0, 0, 0, 0x08];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, vec![u32::MAX]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash() {
|
||||
// PUSH 10, PUSH 20, HASH
|
||||
let program = vec![0x00, 10, 0, 0, 0, 0x00, 20, 0, 0, 0, 0x09];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack.len(), 1);
|
||||
let expected_hash = shared::hashing::hash_stack(&[10, 20]);
|
||||
assert_eq!(state.stack[0], expected_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_underflow_binary() {
|
||||
// PUSH 42, ADD (needs 2 values, only 1 on stack)
|
||||
let program = vec![0x00, 42, 0, 0, 0, 0x01];
|
||||
let state = execute(&program);
|
||||
// ADD breaks when stack.len() < 2, stack has 42 left, ip is at the opcode ADD (6)
|
||||
assert_eq!(state.stack, vec![42]);
|
||||
assert_eq!(state.ip, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_underflow_unary() {
|
||||
// NOT (needs 1 value, empty stack)
|
||||
let program = vec![0x08];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, Vec::<u32>::new());
|
||||
assert_eq!(state.ip, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_incomplete_push() {
|
||||
// PUSH opcode, but only 2 bytes instead of 4
|
||||
let program = vec![0x00, 42, 0];
|
||||
let state = execute(&program);
|
||||
assert_eq!(state.stack, Vec::<u32>::new());
|
||||
assert_eq!(state.ip, 1); // execution stopped at op 0x00 because ip + 4 > program.len()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user