Initial Tessera backup vault (M0–M2)

Scaffold Rust workspace, React canvas, vault engine, hub API,
providers, agent wormhole path, and Docker compose per SPEC.
This commit is contained in:
Tessera Agent
2026-11-09 09:59:42 +00:00
commit a5ffb2c1b4
54 changed files with 8379 additions and 0 deletions

10
.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
/target/
/data/
**/dist/
**/dist-types/
node_modules/
web/dist/
.env
*.db
*.part
.DS_Store

2026
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

45
Cargo.toml Normal file
View File

@@ -0,0 +1,45 @@
[workspace]
resolver = "2"
members = [
"crates/tessera-core",
"crates/tessera-store",
"crates/tessera-providers",
"crates/tessera-hub",
"crates/tessera-agent",
"crates/tessera-cli",
]
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Senkensha"]
[workspace.dependencies]
anyhow = "1.0"
async-trait = "0.1"
axum = { version = "0.7", features = ["multipart"] }
blake3 = "=1.5.5"
chrono = { version = "0.4", features = ["serde"] }
clap = { version = "=4.4.18", features = ["derive", "env"] }
cron = "0.12"
hex = "0.4"
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "=0.10.8"
rusqlite = { version = "=0.31.0", features = ["bundled"] }
thiserror = "1.0"
tokio = { version = "=1.40.0", features = ["full"] }
tokio-cron-scheduler = "0.13"
tower = "0.5"
tower-http = { version = "0.6", features = ["fs", "trace", "cors"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
utoipa = { version = "4.2", features = ["axum_extras", "chrono"] }
uuid = { version = "=1.10.0", features = ["v4", "serde"] }
aes-gcm = "=0.9.4"
pbkdf2 = { version = "=0.10.1", features = ["simple"] }
hmac = "0.12"
tempfile = "3.12"
walkdir = "2.5"

22
Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:22-bookworm AS web
WORKDIR /build
COPY web/package.json web/package-lock.json* ./
RUN npm ci 2>/dev/null || npm install
COPY web/ ./
RUN npm run build
FROM rust:1.88-bookworm AS rust
WORKDIR /build
COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates
COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data
EXPOSE 8787
VOLUME ["/data"]
ENTRYPOINT ["tessera-hub"]

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

50
README.md Normal file
View File

@@ -0,0 +1,50 @@
# Tessera
Self-hosted backup vault with a space-themed canvas: **orbits**, **snapshots**, **decay**, and **wormhole** outposts.
## Quick start
```bash
# Build UI then hub
cd web && npm ci && npm run build && cd ..
cargo build --release -p tessera-hub
export TESSERA_DATA_DIR=./data
export TESSERA_VAULT_PASSPHRASE=dev-vault-key
./target/release/tessera-hub
```
Open [http://127.0.0.1:8787](http://127.0.0.1:8787) — API docs at `/swagger-ui`.
### Docker Compose
```bash
docker compose up --build
```
Hub listens on **8787**.
### CLI
```bash
cargo build --release -p tessera-cli
./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs --dry-run
./target/release/tessera snap
./target/release/tessera list
```
## Architecture
See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`.
## Limitations (v1)
- Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge.
- Wormhole uploads are **token-authenticated**; mTLS is optional via env hook (`TESSERA_WORMHOLE_MTLS`) without bundled CA generation.
- Postgres provider requires `pg_dump` on `PATH`.
- OIDC admin auth is stubbed; v1 uses open local API when hub is bound to localhost.
## License
AGPL-3.0-or-later — see [LICENSE](LICENSE).

16
compose.yaml Normal file
View File

@@ -0,0 +1,16 @@
services:
tessera-hub:
build: .
ports:
- "8787:8787"
environment:
TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:-dev-vault-key}
RUST_LOG: tessera_hub=info
volumes:
- tessera-data:/data
restart: unless-stopped
volumes:
tessera-data:

View File

@@ -0,0 +1,22 @@
[package]
name = "tessera-agent"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "tessera-agent"
path = "src/main.rs"
[dependencies]
tessera-core = { path = "../tessera-core" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
base64 = "0.22"

View File

@@ -0,0 +1,58 @@
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::TcpStream;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?;
request("POST", url, Some(&payload), Some("application/json"), headers)
}
fn request(
method: &str,
url: &str,
body: Option<&str>,
content_type: Option<&str>,
headers: &[(&str, &str)],
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (k, v) in headers {
req.push_str(&format!("{k}: {v}\r\n"));
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
req.push_str(&format!("Content-Type: {ct}\r\n"));
}
req.push_str("\r\n");
req.push_str(b);
} else {
req.push_str("\r\n");
}
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
Ok(buf[body_start..].trim().to_string())
}
fn parse_url(url: &str) -> Result<(String, u16, String)> {
let url = url.strip_prefix("http://").context("only http supported")?;
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
let path = if path.is_empty() {
"/".to_string()
} else {
format!("/{path}")
};
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
(h.to_string(), p.parse()?)
} else {
(host_port.to_string(), 80)
};
Ok((host, port, path))
}
#[allow(dead_code)]
pub type HeaderMap = HashMap<String, String>;

View File

@@ -0,0 +1,114 @@
mod http;
use anyhow::{Context, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use tessera_core::config::ProviderKind;
use tessera_providers::provider_from_config;
use tracing::info;
#[derive(Parser)]
#[command(name = "tessera-agent", about = "Tessera outpost daemon")]
struct Cli {
#[command(subcommand)]
command: Option<AgentCmd>,
#[arg(long, env = "TESSERA_HUB_URL")]
hub_url: Option<String>,
#[arg(long, env = "TESSERA_UPLOAD_TOKEN")]
upload_token: Option<String>,
#[arg(long, env = "TESSERA_ORBIT_ID")]
orbit_id: Option<String>,
}
#[derive(Clone, Subcommand)]
enum AgentCmd {
Run,
Pair {
code: String,
#[arg(long, default_value = "outpost")]
name: String,
},
Beam,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let cli = Cli::parse();
match cli.command.clone().unwrap_or(AgentCmd::Run) {
AgentCmd::Run => run_daemon(&cli).await?,
AgentCmd::Pair { code, name } => pair(&cli, &code, &name)?,
AgentCmd::Beam => beam_once(&cli).await?,
}
Ok(())
}
fn pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
let hub = cli
.hub_url
.clone()
.unwrap_or_else(|| "http://127.0.0.1:8787".into());
let body = serde_json::json!({ "code": code, "outpost_name": name });
let raw = http::post_json(
&format!("{hub}/api/v1/wormhole/claim"),
&body,
&[],
)?;
let res: serde_json::Value = serde_json::from_str(&raw)?;
println!("TESSERA_UPLOAD_TOKEN={}", res["upload_token"]);
println!("TESSERA_HUB_URL={}", res["hub_url"]);
println!("Outpost {}", res["outpost_id"]);
Ok(())
}
async fn run_daemon(cli: &Cli) -> Result<()> {
info!("outpost online — wormhole listening for beam cycles");
loop {
if let Err(e) = beam_once(cli).await {
tracing::warn!("beam failed: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
}
}
async fn beam_once(cli: &Cli) -> Result<()> {
let hub = cli
.hub_url
.clone()
.context("TESSERA_HUB_URL")?
.trim_end_matches('/')
.to_string();
let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?;
let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?;
let config = serde_json::json!({ "paths": ["./"] });
let provider = provider_from_config(&ProviderKind::Filesystem, &config)?;
let capture = provider.capture().await?;
let chunk_b64 = base64::engine::general_purpose::STANDARD.encode(&capture.payload);
let init_body = serde_json::json!({
"orbit_id": orbit_id,
"total_bytes": capture.payload.len(),
});
let init_raw = http::post_json(
&format!("{hub}/api/v1/wormhole/upload/init"),
&init_body,
&[("x-tessera-upload-token", &token)],
)?;
let init: serde_json::Value = serde_json::from_str(&init_raw)?;
let session_id = init["session_id"].as_str().context("session_id")?;
let chunk_body = serde_json::json!({
"session_id": session_id,
"offset": 0,
"data_b64": chunk_b64,
});
http::post_json(
&format!("{hub}/api/v1/wormhole/upload/chunk"),
&chunk_body,
&[("x-tessera-upload-token", &token)],
)?;
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
Ok(())
}

View File

@@ -0,0 +1,19 @@
[package]
name = "tessera-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "tessera"
path = "src/main.rs"
[dependencies]
tessera-core = { path = "../tessera-core" }
tessera-store = { path = "../tessera-store" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true
uuid.workspace = true

View File

@@ -0,0 +1,54 @@
use anyhow::{Context, Result};
use std::io::{Read, Write};
use std::net::TcpStream;
pub fn get(url: &str) -> Result<String> {
request("GET", url, None, None)
}
pub fn post_json(url: &str, body: &serde_json::Value) -> Result<String> {
let payload = serde_json::to_string(body)?;
request("POST", url, Some(&payload), Some("application/json"))
}
fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&str>) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
req.push_str(&format!("Content-Type: {ct}\r\n"));
}
req.push_str("\r\n");
req.push_str(b);
} else {
req.push_str("\r\n");
}
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
Ok(buf[body_start..].trim().to_string())
}
fn parse_url(url: &str) -> Result<(String, u16, String)> {
let url = url.strip_prefix("http://").context("only http supported")?;
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
let path = if path.is_empty() {
"/".to_string()
} else {
format!("/{path}")
};
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
(h.to_string(), p.parse()?)
} else {
(host_port.to_string(), 80)
};
Ok((host, port, path))
}
pub fn post_empty(url: &str) -> Result<()> {
request("POST", url, None, None)?;
Ok(())
}

View File

@@ -0,0 +1,202 @@
mod http;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use tessera_store::Vault;
use uuid::Uuid;
#[derive(Parser, Clone)]
#[command(name = "tessera", about = "Tessera backup vault CLI")]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
data_dir: String,
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")]
vault_pass: String,
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
hub_url: String,
}
#[derive(Subcommand, Clone)]
enum Commands {
Init,
Status,
Orbit {
name: String,
#[arg(long, default_value = "filesystem")]
provider: String,
#[arg(long)]
path: Option<String>,
#[arg(long)]
schedule: Option<String>,
#[arg(long)]
dry_run: bool,
},
Snap {
#[arg(long)]
orbit: Option<String>,
},
List,
Reconstitute {
snapshot_id: Uuid,
target: String,
},
Decay {
#[arg(long, default_value = "week-of-dailies")]
preset: String,
},
Wormhole {
#[command(subcommand)]
cmd: WormholeCmd,
},
}
#[derive(Subcommand, Clone)]
enum WormholeCmd {
Pair {
code: String,
#[arg(long, default_value = "outpost")]
name: String,
},
}
fn main() -> Result<()> {
let cli = Cli::parse();
let command = cli.command.clone();
match command {
Commands::Init => cmd_init(&cli)?,
Commands::Status => cmd_status(&cli)?,
Commands::Orbit {
name,
provider,
path,
schedule,
dry_run,
} => cmd_orbit(&cli, name, provider, path, schedule, dry_run)?,
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
Commands::List => cmd_list(&cli)?,
Commands::Reconstitute {
snapshot_id,
target,
} => cmd_reconstitute(&cli, snapshot_id, target)?,
Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
Commands::Wormhole { ref cmd } => match cmd {
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
},
}
Ok(())
}
fn vault_path(data_dir: &str) -> std::path::PathBuf {
std::path::PathBuf::from(data_dir).join("vault")
}
fn cmd_init(cli: &Cli) -> Result<()> {
let vp = vault_path(&cli.data_dir);
if vp.join("config").exists() {
println!("Vault already initialized.");
return Ok(());
}
Vault::init(&vp, &cli.vault_pass).context("init vault")?;
println!("Vault initialized at {}", vp.display());
Ok(())
}
fn cmd_status(cli: &Cli) -> Result<()> {
match http::get(&format!("{}/health", cli.hub_url)) {
Ok(body) => println!("Hub: {body}"),
Err(_) => println!("Hub: offline (is tessera-hub running?)"),
}
let vp = vault_path(&cli.data_dir);
if vp.join("config").exists() {
let vault = Vault::open(&vp, &cli.vault_pass)?;
let n = vault.list_snapshots()?.len();
println!("Vault: online — {n} snapshots");
} else {
println!("Vault: not initialized (run tessera init)");
}
Ok(())
}
fn cmd_orbit(
cli: &Cli,
name: String,
provider: String,
path: Option<String>,
schedule: Option<String>,
dry_run: bool,
) -> Result<()> {
let config = match provider.as_str() {
"filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }),
"postgres" => serde_json::json!({ "connection_url": path.context("--path or connection url required")? }),
_ => anyhow::bail!("unknown provider"),
};
let body = serde_json::json!({
"name": name,
"provider": provider,
"provider_config": config,
"schedule": schedule,
"dry_run": dry_run,
});
let raw = http::post_json(&format!("{}/api/v1/orbits", cli.hub_url), &body)?;
let orbit: serde_json::Value = serde_json::from_str(&raw)?;
println!("Orbit registered: {}", orbit["id"]);
Ok(())
}
fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
let raw = http::get(&format!("{}/api/v1/orbits", cli.hub_url))?;
let orbits: serde_json::Value = serde_json::from_str(&raw)?;
let arr = orbits.as_array().context("orbits response")?;
let id = if let Some(name) = orbit_name {
arr.iter()
.find(|o| o["name"] == name)
.and_then(|o| o["id"].as_str())
.context("orbit not found")?
} else {
arr.first()
.and_then(|o| o["id"].as_str())
.context("no orbits defined")?
};
http::post_empty(&format!("{}/api/v1/orbits/{id}/run", cli.hub_url))?;
println!("Orbit run triggered.");
Ok(())
}
fn cmd_list(cli: &Cli) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
for s in vault.list_snapshots()? {
println!(
"{} {} {} bytes orbit={}",
s.taken_at.to_rfc3339(),
s.id,
s.size_bytes,
s.manifest.orbit_name
);
}
Ok(())
}
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
println!("Reconstituted {n} bytes to {target}");
Ok(())
}
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
let pruned = vault.prune_with_decay(preset)?;
println!("{} snapshots decayed.", pruned.len());
Ok(())
}
fn wormhole_pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
let body = serde_json::json!({ "code": code, "outpost_name": name });
let raw = http::post_json(&format!("{}/api/v1/wormhole/claim", cli.hub_url), &body)?;
let res: serde_json::Value = serde_json::from_str(&raw)?;
println!("Paired outpost {}", res["outpost_id"]);
println!("Set TESSERA_UPLOAD_TOKEN on the agent.");
Ok(())
}

View File

@@ -0,0 +1,16 @@
[package]
name = "tessera-core"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
chrono.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
uuid.workspace = true
hex.workspace = true
sha2.workspace = true
utoipa = { workspace = true }

View File

@@ -0,0 +1,45 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultConfig {
pub vault_id: Uuid,
pub vault_path: String,
pub created_at: chrono::DateTime<chrono::Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HubConfig {
pub listen: String,
pub data_dir: String,
pub admin_password_hash: Option<String>,
}
impl Default for HubConfig {
fn default() -> Self {
Self {
listen: "0.0.0.0:8787".into(),
data_dir: "./data".into(),
admin_password_hash: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
Filesystem,
Postgres,
Command,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrbitSpec {
pub id: Uuid,
pub name: String,
pub provider: ProviderKind,
pub provider_config: serde_json::Value,
pub schedule: Option<String>,
pub decay_preset: String,
pub dry_run: bool,
}

View File

@@ -0,0 +1,119 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DecayPolicy {
pub keep_daily: usize,
pub keep_weekly: usize,
pub keep_monthly: usize,
}
impl DecayPolicy {
pub fn from_preset(name: &str) -> Self {
match name {
"week-of-dailies" => Self {
keep_daily: 7,
keep_weekly: 0,
keep_monthly: 0,
},
"month-of-weeklies" => Self {
keep_daily: 0,
keep_weekly: 4,
keep_monthly: 0,
},
"year-of-monthlies" => Self {
keep_daily: 0,
keep_weekly: 0,
keep_monthly: 12,
},
_ => Self {
keep_daily: 7,
keep_weekly: 4,
keep_monthly: 12,
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotRef {
pub id: Uuid,
pub taken_at: DateTime<Utc>,
}
/// Returns snapshot IDs to forget (newest-first input).
pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
snapshots.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
let mut keep = std::collections::HashSet::new();
if policy.keep_daily > 0 {
for s in snapshots.iter().take(policy.keep_daily) {
keep.insert(s.id);
}
}
if policy.keep_weekly > 0 {
let mut weeks: Vec<(i64, SnapshotRef)> = Vec::new();
for s in &snapshots {
let week = s.taken_at.timestamp() / (7 * 86400);
if let Some(pos) = weeks.iter().position(|(w, _)| *w == week) {
if s.taken_at > weeks[pos].1.taken_at {
weeks[pos] = (week, s.clone());
}
} else {
weeks.push((week, s.clone()));
}
}
weeks.sort_by(|a, b| b.1.taken_at.cmp(&a.1.taken_at));
for (_, s) in weeks.into_iter().take(policy.keep_weekly) {
keep.insert(s.id);
}
}
if policy.keep_monthly > 0 {
let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new();
for s in &snapshots {
let key = (s.taken_at.year(), s.taken_at.month());
if let Some(pos) = months.iter().position(|(y, m, _)| *y == key.0 && *m == key.1) {
if s.taken_at > months[pos].2.taken_at {
months[pos] = (key.0, key.1, s.clone());
}
} else {
months.push((key.0, key.1, s.clone()));
}
}
months.sort_by(|a, b| b.2.taken_at.cmp(&a.2.taken_at));
for (_, _, s) in months.into_iter().take(policy.keep_monthly) {
keep.insert(s.id);
}
}
snapshots
.into_iter()
.filter(|s| !keep.contains(&s.id))
.map(|s| s.id)
.collect()
}
use chrono::Datelike;
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
fn keeps_n_dailies() {
let policy = DecayPolicy::from_preset("week-of-dailies");
let now = Utc::now();
let snaps: Vec<SnapshotRef> = (0..10)
.map(|i| SnapshotRef {
id: Uuid::new_v4(),
taken_at: now - Duration::days(i),
})
.collect();
let forget = evaluate_decay(&policy, snaps);
assert_eq!(forget.len(), 3);
}
}

View File

@@ -0,0 +1,33 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum TesseraError {
#[error("vault is locked: {0}")]
VaultLocked(String),
#[error("wrong passphrase")]
WrongPassphrase,
#[error("provider unreachable: {0}")]
ProviderUnreachable(String),
#[error("disk full: need {needed} bytes")]
DiskFull { needed: u64 },
#[error("{0}")]
UserMessage(String),
}
impl TesseraError {
pub fn user_message(&self) -> &str {
match self {
TesseraError::VaultLocked(_) => {
"Another orbit is still circling the vault. Try again when it finishes."
}
TesseraError::WrongPassphrase => "That key doesn't unlock this vault.",
TesseraError::ProviderUnreachable(_) => {
"We couldn't reach the source at this outpost."
}
TesseraError::DiskFull { .. } => {
"The vault is out of space—free room or widen the hold."
}
TesseraError::UserMessage(m) => m.as_str(),
}
}
}

View File

@@ -0,0 +1,15 @@
pub mod config;
pub mod decay;
pub mod errors;
pub mod manifest;
pub mod orbit;
pub mod reconstitute;
pub mod wormhole;
pub use config::*;
pub use decay::*;
pub use errors::*;
pub use manifest::*;
pub use orbit::*;
pub use reconstitute::*;
pub use wormhole::*;

View File

@@ -0,0 +1,41 @@
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotManifest {
pub snapshot_id: Uuid,
pub orbit_id: Uuid,
pub orbit_name: String,
pub labels: Vec<String>,
pub provider: String,
pub paths: Vec<String>,
pub restore_hints: serde_json::Value,
}
pub fn manifest_hash(manifest: &SnapshotManifest) -> String {
let json = serde_json::to_vec(manifest).expect("manifest serializes");
let digest = Sha256::digest(&json);
hex::encode(digest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_is_stable() {
let m = SnapshotManifest {
snapshot_id: Uuid::nil(),
orbit_id: Uuid::nil(),
orbit_name: "nightly".into(),
labels: vec!["filesystem".into()],
provider: "filesystem".into(),
paths: vec!["/tmp".into()],
restore_hints: serde_json::json!({}),
};
let h1 = manifest_hash(&m);
let h2 = manifest_hash(&m);
assert_eq!(h1, h2);
assert_eq!(h1.len(), 64);
}
}

View File

@@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum OrbitRunState {
Idle,
Preparing,
Capturing,
Sealing,
ApplyingDecay,
Completed,
Failed,
Rehearsed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrbitRun {
pub state: OrbitRunState,
pub dry_run: bool,
pub message: Option<String>,
}

View File

@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub const RECONSTITUTE_GRACE_SECS: u64 = 12;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReconstituteState {
Idle,
Confirming,
Countdown,
Restoring,
Completed,
Failed,
Aborted,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct ReconstituteSession {
pub snapshot_id: Uuid,
pub target: String,
pub state: ReconstituteState,
pub seconds_remaining: u64,
}
impl ReconstituteSession {
pub fn countdown_copy(&self) -> String {
format!(
"Reconstituting in {}s — abort restores nothing.",
self.seconds_remaining
)
}
}

View File

@@ -0,0 +1,26 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PairingState {
Unpaired,
CodeShown,
Claimed,
Active,
Offline,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PairingCode {
pub code: String,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub hub_outpost_id: Option<Uuid>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WormholeCredentials {
pub outpost_id: Uuid,
pub upload_token: String,
pub hub_url: String,
}

View File

@@ -0,0 +1,32 @@
[package]
name = "tessera-hub"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "tessera-hub"
path = "src/main.rs"
[dependencies]
tessera-core = { path = "../tessera-core" }
tessera-store = { path = "../tessera-store" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
axum.workspace = true
chrono.workspace = true
cron.workspace = true
include_dir = "0.7"
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
rusqlite.workspace = true
tokio.workspace = true
tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
utoipa.workspace = true
uuid.workspace = true
hex.workspace = true
base64 = "0.22"
indexmap = "=2.2.6"

View File

@@ -0,0 +1,5 @@
mod orbit;
mod routes;
pub use orbit::run_orbit_internal;
pub use routes::router;

View File

@@ -0,0 +1,71 @@
use crate::db::OrbitRow;
use crate::state::HubState;
use anyhow::{Context, Result};
use tessera_core::config::ProviderKind;
use tessera_core::manifest::SnapshotManifest;
use tessera_providers::provider_from_config;
use uuid::Uuid;
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<()> {
let orbits = state.db.list_orbits().await?;
let orbit = orbits
.into_iter()
.find(|o| o.id == orbit_id)
.context("orbit not found")?;
run_orbit_row(state, orbit).await
}
pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
state.db.set_orbit_status(orbit.id, "running").await?;
let provider_kind = match orbit.provider.as_str() {
"filesystem" => ProviderKind::Filesystem,
"postgres" => ProviderKind::Postgres,
_ => ProviderKind::Command,
};
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
let provider = provider_from_config(&provider_kind, &config)?;
let capture = provider.capture().await.context("capture")?;
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: orbit.id,
orbit_name: orbit.name.clone(),
labels: capture.labels,
provider: orbit.provider.clone(),
paths: vec![],
restore_hints: capture.restore_hints,
};
let mut vault = state.vault.write().await;
let snap = vault
.snapshot(manifest, &capture.payload, orbit.dry_run)
.context("vault snapshot")?;
if !orbit.dry_run {
let _pruned = vault.prune_with_decay(&orbit.decay_preset)?;
state
.db
.audit("decay.pruned", &format!("orbit={}", orbit.name))
.await?;
}
let status = if orbit.dry_run {
"rehearsed"
} else {
"completed"
};
state.db.set_orbit_status(orbit.id, status).await?;
state
.db
.audit(
if orbit.dry_run {
"orbit.rehearsed"
} else {
"orbit.completed"
},
&format!("snapshot={}", snap.id),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,440 @@
use crate::db::OrbitRow;
use crate::state::{HubState, PairingEntry};
use axum::{
extract::{Path, State},
http::{header, StatusCode, Uri},
response::IntoResponse,
routing::{delete, get, post},
Json, Router,
};
use base64::Engine;
use include_dir::{include_dir, Dir};
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS};
use tessera_core::wormhole::PairingState;
use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use uuid::Uuid;
static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
#[derive(OpenApi)]
#[openapi(
paths(
health,
list_snapshots,
list_orbits,
create_orbit,
trigger_orbit,
start_reconstitute,
pairing_start,
pairing_claim,
wormhole_upload_init,
wormhole_upload_chunk,
),
components(schemas(
SnapshotSummary,
OrbitRow,
CreateOrbitRequest,
ReconstituteRequest,
ReconstituteSession,
PairingResponse,
ClaimRequest,
ClaimResponse,
UploadInit,
UploadChunk,
))
)]
struct ApiDoc;
#[derive(serde::Serialize, utoipa::ToSchema)]
struct SnapshotSummary {
id: Uuid,
taken_at: chrono::DateTime<chrono::Utc>,
orbit_name: String,
size_bytes: u64,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct CreateOrbitRequest {
name: String,
provider: String,
provider_config: serde_json::Value,
schedule: Option<String>,
decay_preset: Option<String>,
dry_run: Option<bool>,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct ReconstituteRequest {
snapshot_id: Uuid,
target_path: String,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct PairingResponse {
code: String,
expires_at: chrono::DateTime<chrono::Utc>,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct ClaimRequest {
code: String,
outpost_name: String,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct ClaimResponse {
outpost_id: Uuid,
upload_token: String,
hub_url: String,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct UploadInit {
orbit_id: Uuid,
total_bytes: Option<u64>,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct UploadChunk {
session_id: Uuid,
offset: u64,
data_b64: String,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct ReconstituteStartResponse {
session_id: Uuid,
session: ReconstituteSession,
}
pub fn router(state: HubState) -> Router {
let api = Router::new()
.route("/health", get(health))
.route("/api/v1/snapshots", get(list_snapshots))
.route("/api/v1/orbits", get(list_orbits).post(create_orbit))
.route("/api/v1/orbits/:id/run", post(trigger_orbit))
.route("/api/v1/reconstitute", post(start_reconstitute))
.route(
"/api/v1/reconstitute/:id",
get(reconstitute_status).delete(abort_reconstitute),
)
.route("/api/v1/wormhole/pairing", post(pairing_start))
.route("/api/v1/wormhole/claim", post(pairing_claim))
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
.route("/api/v1/wormhole/upload/chunk", post(wormhole_upload_chunk))
.with_state(state);
let api = api.route(
"/api-doc/openapi.json",
get(|| async { Json(ApiDoc::openapi()) }),
);
api.fallback(spa_fallback)
.layer(TraceLayer::new_for_http())
}
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
async fn health() -> &'static str {
"vault online"
}
#[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))]
async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<SnapshotSummary>>, StatusCode> {
let vault = state.vault.read().await;
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let out = snaps
.into_iter()
.map(|s| SnapshotSummary {
id: s.id,
taken_at: s.taken_at,
orbit_name: s.manifest.orbit_name,
size_bytes: s.size_bytes,
})
.collect();
Ok(Json(out))
}
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
async fn list_orbits(State(state): State<HubState>) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
state
.db
.list_orbits()
.await
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
async fn create_orbit(
State(state): State<HubState>,
Json(req): Json<CreateOrbitRequest>,
) -> Result<Json<OrbitRow>, StatusCode> {
let row = OrbitRow {
id: Uuid::new_v4(),
name: req.name,
provider: req.provider,
provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()),
schedule: req.schedule,
decay_preset: req
.decay_preset
.unwrap_or_else(|| "week-of-dailies".into()),
dry_run: req.dry_run.unwrap_or(false),
last_status: "idle".into(),
};
state.db.upsert_orbit(&row).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(row))
}
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204)))]
async fn trigger_orbit(
State(state): State<HubState>,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
crate::api::run_orbit_internal(state, id)
.await
.map(|_| StatusCode::NO_CONTENT)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
#[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))]
async fn start_reconstitute(
State(state): State<HubState>,
Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
let session_id = Uuid::new_v4();
let session = ReconstituteSession {
snapshot_id: req.snapshot_id,
target: req.target_path.clone(),
state: ReconstituteState::Countdown,
seconds_remaining: RECONSTITUTE_GRACE_SECS,
};
state
.reconstitute_sessions
.write()
.await
.insert(session_id, session.clone());
let state_bg = state.clone();
let target = req.target_path;
tokio::spawn(async move {
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
{
let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) {
if s.state == ReconstituteState::Aborted {
return;
}
s.seconds_remaining = remaining;
}
}
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
let aborted = {
let map = state_bg.reconstitute_sessions.read().await;
map.get(&session_id)
.map(|s| s.state == ReconstituteState::Aborted)
.unwrap_or(true)
};
if aborted {
return;
}
{
let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) {
s.state = ReconstituteState::Restoring;
s.seconds_remaining = 0;
}
}
let dest = std::path::PathBuf::from(&target);
let result = {
let vault = state_bg.vault.read().await;
vault.restore_snapshot(req.snapshot_id, &dest)
};
let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) {
s.state = if result.is_ok() {
ReconstituteState::Completed
} else {
ReconstituteState::Failed
};
}
let _ = state_bg.db.audit("reconstitute.done", &format!("session={session_id}")).await;
});
Ok(Json(ReconstituteStartResponse {
session_id,
session,
}))
}
async fn reconstitute_status(
State(state): State<HubState>,
Path(id): Path<Uuid>,
) -> Result<Json<ReconstituteSession>, StatusCode> {
let map = state.reconstitute_sessions.read().await;
map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND)
}
async fn abort_reconstitute(
State(state): State<HubState>,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let mut map = state.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&id) {
if matches!(
s.state,
ReconstituteState::Countdown | ReconstituteState::Confirming
) {
s.state = ReconstituteState::Aborted;
return Ok(StatusCode::NO_CONTENT);
}
}
Err(StatusCode::BAD_REQUEST)
}
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
async fn pairing_start(State(state): State<HubState>) -> Json<PairingResponse> {
let code: String = (0..6)
.map(|_| {
let n = rand::random::<u8>() % 36;
if n < 10 {
(b'0' + n) as char
} else {
(b'A' + n - 10) as char
}
})
.collect();
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
let outpost_id = Uuid::new_v4();
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
state.pairing_codes.write().await.push(PairingEntry {
code: code.clone(),
expires_at: expires,
state: PairingState::CodeShown,
outpost_id,
upload_token: upload_token.clone(),
});
Json(PairingResponse { code, expires_at: expires })
}
#[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))]
async fn pairing_claim(
State(state): State<HubState>,
Json(req): Json<ClaimRequest>,
) -> Result<Json<ClaimResponse>, StatusCode> {
let mut codes = state.pairing_codes.write().await;
let now = chrono::Utc::now();
let entry = codes
.iter_mut()
.find(|c| c.code == req.code && c.expires_at > now)
.ok_or(StatusCode::GONE)?;
entry.state = PairingState::Active;
let hub_url =
std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into());
state
.db
.audit("wormhole.paired", &req.outpost_name)
.await
.ok();
Ok(Json(ClaimResponse {
outpost_id: entry.outpost_id,
upload_token: entry.upload_token.clone(),
hub_url,
}))
}
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
async fn wormhole_upload_init(
State(state): State<HubState>,
headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
verify_upload_token(&state, &headers).await?;
let session_id = Uuid::new_v4();
state
.db
.insert_upload_session(
&session_id.to_string(),
&body.orbit_id.to_string(),
body.total_bytes.map(|t| t as i64),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({ "session_id": session_id })))
}
#[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))]
async fn wormhole_upload_chunk(
State(state): State<HubState>,
headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> {
verify_upload_token(&state, &headers).await?;
let data = base64::engine::general_purpose::STANDARD
.decode(&body.data_b64)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id));
if let Some(parent) = tmp.parent() {
std::fs::create_dir_all(parent).ok();
}
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&tmp)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
file.write_all(&data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::NO_CONTENT)
}
async fn verify_upload_token(
state: &HubState,
headers: &axum::http::HeaderMap,
) -> Result<(), StatusCode> {
let token = headers
.get("x-tessera-upload-token")
.and_then(|v| v.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
if state.upload_token_valid(token).await {
Ok(())
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn spa_fallback(uri: Uri) -> impl IntoResponse {
let mut path = uri.path().trim_start_matches('/').to_string();
if path.is_empty() {
path = "index.html".into();
}
if let Some(file) = WEB_DIST.get_file(&path) {
let ct = content_type(&path);
return (
StatusCode::OK,
[(header::CONTENT_TYPE, ct)],
file.contents(),
)
.into_response();
}
if let Some(index) = WEB_DIST.get_file("index.html") {
return (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")],
index.contents(),
)
.into_response();
}
(StatusCode::NOT_FOUND, "not found").into_response()
}
fn content_type(path: &str) -> &'static str {
if path.ends_with(".js") {
"application/javascript"
} else if path.ends_with(".css") {
"text/css"
} else if path.ends_with(".svg") {
"image/svg+xml"
} else {
"text/html"
}
}

View File

@@ -0,0 +1,145 @@
use anyhow::Result;
use rusqlite::{params, Connection};
use std::path::Path;
use std::sync::{Arc, Mutex};
use uuid::Uuid;
#[derive(Clone)]
pub struct Db {
conn: Arc<Mutex<Connection>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct OrbitRow {
pub id: Uuid,
pub name: String,
pub provider: String,
pub provider_config: String,
pub schedule: Option<String>,
pub decay_preset: String,
pub dry_run: bool,
pub last_status: String,
}
impl Db {
pub async fn connect(path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let conn = Connection::open(path)?;
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
}
pub async fn migrate(&self) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS orbits (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider TEXT NOT NULL,
provider_config TEXT NOT NULL,
schedule TEXT,
decay_preset TEXT NOT NULL DEFAULT 'week-of-dailies',
dry_run INTEGER NOT NULL DEFAULT 0,
last_status TEXT NOT NULL DEFAULT 'idle'
);
CREATE TABLE IF NOT EXISTS outposts (
id TEXT PRIMARY KEY,
name TEXT,
last_seen TEXT,
pairing_state TEXT NOT NULL DEFAULT 'unpaired'
);
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
event TEXT NOT NULL,
detail TEXT
);
CREATE TABLE IF NOT EXISTS upload_sessions (
id TEXT PRIMARY KEY,
outpost_id TEXT,
orbit_id TEXT,
offset INTEGER NOT NULL DEFAULT 0,
total INTEGER,
created_at TEXT NOT NULL
);
"#,
)?;
Ok(())
}
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status FROM orbits ORDER BY name")?;
let rows = stmt.query_map([], |r| {
Ok(OrbitRow {
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
name: r.get(1)?,
provider: r.get(2)?,
provider_config: r.get(3)?,
schedule: r.get(4)?,
decay_preset: r.get(5)?,
dry_run: r.get::<_, i64>(6)? != 0,
last_status: r.get(7)?,
})
})?;
Ok(rows.filter_map(|r| r.ok()).collect())
}
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name, provider=excluded.provider, provider_config=excluded.provider_config,
schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run"#,
params![
row.id.to_string(),
row.name,
row.provider,
row.provider_config,
row.schedule,
row.decay_preset,
row.dry_run as i64,
row.last_status,
],
)?;
Ok(())
}
pub async fn set_orbit_status(&self, id: Uuid, status: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE orbits SET last_status = ?1 WHERE id = ?2",
params![status, id.to_string()],
)?;
Ok(())
}
pub async fn audit(&self, event: &str, detail: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), ?1, ?2)",
params![event, detail],
)?;
Ok(())
}
pub fn insert_upload_session(
&self,
id: &str,
orbit_id: &str,
total: Option<i64>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))",
params![id, orbit_id, total],
)?;
Ok(())
}
}

View File

@@ -0,0 +1,30 @@
mod api;
mod db;
mod scheduler;
mod state;
use anyhow::Result;
use state::HubState;
use std::net::SocketAddr;
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("tessera_hub=info".parse()?))
.init();
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into());
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into());
let state = HubState::bootstrap(&data_dir, &vault_pass).await?;
scheduler::start_orbit_scheduler(state.clone()).await?;
let app = api::router(state);
let addr: SocketAddr = listen.parse()?;
tracing::info!("Tessera hub listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}

View File

@@ -0,0 +1,46 @@
use crate::state::HubState;
use anyhow::Result;
use cron::Schedule;
use std::str::FromStr;
use tokio::time::{sleep, Duration};
use tracing::{error, info};
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
tokio::spawn(async move {
loop {
if let Err(e) = tick_schedules(state.clone()).await {
error!("scheduler tick: {e}");
}
sleep(Duration::from_secs(30)).await;
}
});
Ok(())
}
async fn tick_schedules(state: HubState) -> Result<()> {
let orbits = state.db.list_orbits().await?;
let now = chrono::Utc::now();
for orbit in orbits {
let Some(cron_expr) = orbit.schedule.as_ref() else {
continue;
};
let schedule = match Schedule::from_str(cron_expr) {
Ok(s) => s,
Err(e) => {
error!("bad cron on orbit {}: {e}", orbit.name);
continue;
}
};
let upcoming = schedule.upcoming(chrono::Utc).take(1).collect::<Vec<_>>();
if let Some(next) = upcoming.first() {
let delta = (*next - now).num_seconds().abs();
if delta < 35 {
info!("scheduler firing orbit {}", orbit.name);
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit.id).await {
error!("orbit {} failed: {e}", orbit.name);
}
}
}
}
Ok(())
}

View File

@@ -0,0 +1,60 @@
use crate::db::Db;
use anyhow::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tessera_core::reconstitute::ReconstituteSession;
use tessera_core::wormhole::PairingState;
use tessera_store::Vault;
use tokio::sync::RwLock;
use uuid::Uuid;
#[derive(Clone)]
pub struct HubState {
pub db: Db,
pub data_dir: PathBuf,
pub vault_passphrase: String,
pub vault: Arc<RwLock<Vault>>,
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
}
#[derive(Clone)]
pub struct PairingEntry {
pub code: String,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub state: PairingState,
pub outpost_id: Uuid,
pub upload_token: String,
}
impl HubState {
pub async fn bootstrap(data_dir: &str, vault_pass: &str) -> Result<Self> {
let data_dir = PathBuf::from(data_dir);
std::fs::create_dir_all(&data_dir)?;
let db_path = data_dir.join("tessera.db");
let db = Db::connect(&db_path).await?;
db.migrate().await?;
let vault_path = data_dir.join("vault");
let vault = if vault_path.join("config").exists() {
Vault::open(&vault_path, vault_pass)?
} else {
Vault::init(&vault_path, vault_pass)?
};
Ok(Self {
db,
data_dir,
vault_passphrase: vault_pass.to_string(),
vault: Arc::new(RwLock::new(vault)),
pairing_codes: Arc::new(RwLock::new(Vec::new())),
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
})
}
pub async fn upload_token_valid(&self, token: &str) -> bool {
let codes = self.pairing_codes.read().await;
codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active)
}
}

View File

@@ -0,0 +1,15 @@
[package]
name = "tessera-providers"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
tessera-core = { path = "../tessera-core" }
anyhow.workspace = true
async-trait.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["process", "fs"] }
tracing.workspace = true
walkdir.workspace = true

View File

@@ -0,0 +1,83 @@
use super::{BackupProvider, CaptureResult};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::path::PathBuf;
use tessera_core::config::ProviderKind;
use walkdir::WalkDir;
#[derive(Debug, Clone, Deserialize)]
pub struct FilesystemConfig {
pub paths: Vec<String>,
#[serde(default)]
pub max_file_bytes: Option<u64>,
}
pub struct FilesystemProvider {
config: FilesystemConfig,
}
impl FilesystemProvider {
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
let config: FilesystemConfig = serde_json::from_value(config.clone())?;
Ok(Self { config })
}
}
#[async_trait]
impl BackupProvider for FilesystemProvider {
fn kind(&self) -> ProviderKind {
ProviderKind::Filesystem
}
async fn capture(&self) -> Result<CaptureResult> {
let mut archive = Vec::new();
let mut paths_meta = Vec::new();
for path_str in &self.config.paths {
let root = PathBuf::from(path_str);
if !root.exists() {
anyhow::bail!("path not found: {path_str}");
}
if root.is_file() {
let data = tokio::fs::read(&root).await.context("read file")?;
if let Some(max) = self.config.max_file_bytes {
if data.len() as u64 > max {
anyhow::bail!("file exceeds max_file_bytes");
}
}
archive.extend_from_slice(path_str.as_bytes());
archive.push(0);
archive.extend(&(data.len() as u64).to_le_bytes());
archive.extend(&data);
paths_meta.push(path_str.clone());
} else {
for entry in WalkDir::new(&root).into_iter().filter_map(|e| e.ok()) {
if entry.file_type().is_file() {
let p = entry.path();
let rel = p.strip_prefix(&root).unwrap_or(p);
let data = tokio::fs::read(p).await.context("read file")?;
if let Some(max) = self.config.max_file_bytes {
if data.len() as u64 > max {
continue;
}
}
let key = format!("{}/{}", path_str, rel.display());
archive.extend_from_slice(key.as_bytes());
archive.push(0);
archive.extend(&(data.len() as u64).to_le_bytes());
archive.extend(&data);
paths_meta.push(key);
}
}
}
}
Ok(CaptureResult {
payload: archive,
labels: vec!["filesystem".into()],
restore_hints: json!({ "paths": paths_meta, "format": "tessera-fs-v1" }),
})
}
}

View File

@@ -0,0 +1,31 @@
mod filesystem;
mod postgres;
pub use filesystem::*;
pub use postgres::*;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::Value;
use tessera_core::config::ProviderKind;
#[async_trait]
pub trait BackupProvider: Send + Sync {
fn kind(&self) -> ProviderKind;
async fn capture(&self) -> Result<CaptureResult>;
}
#[derive(Debug, Clone)]
pub struct CaptureResult {
pub payload: Vec<u8>,
pub labels: Vec<String>,
pub restore_hints: Value,
}
pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<dyn BackupProvider>> {
match kind {
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"),
}
}

View File

@@ -0,0 +1,63 @@
use super::{BackupProvider, CaptureResult};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::process::Stdio;
use tessera_core::config::ProviderKind;
use tokio::process::Command;
#[derive(Debug, Clone, Deserialize)]
pub struct PostgresConfig {
pub connection_url: String,
#[serde(default = "default_format")]
pub format: String,
}
fn default_format() -> String {
"custom".into()
}
pub struct PostgresProvider {
config: PostgresConfig,
}
impl PostgresProvider {
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
let config: PostgresConfig = serde_json::from_value(config.clone())?;
Ok(Self { config })
}
}
#[async_trait]
impl BackupProvider for PostgresProvider {
fn kind(&self) -> ProviderKind {
ProviderKind::Postgres
}
async fn capture(&self) -> Result<CaptureResult> {
let mut cmd = Command::new("pg_dump");
cmd.arg(&self.config.connection_url);
match self.config.format.as_str() {
"custom" => {
cmd.arg("-Fc");
}
"plain" => {}
other => anyhow::bail!("unknown pg format: {other}"),
}
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output = cmd.output().await.context("pg_dump failed to start")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pg_dump failed: {stderr}");
}
Ok(CaptureResult {
payload: output.stdout,
labels: vec!["postgres".into()],
restore_hints: json!({
"format": self.config.format,
"restore_command_hint": "pg_restore -d $DATABASE_URL dump.file"
}),
})
}
}

View File

@@ -0,0 +1,24 @@
[package]
name = "tessera-store"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
tessera-core = { path = "../tessera-core" }
anyhow.workspace = true
aes-gcm.workspace = true
pbkdf2.workspace = true
hmac.workspace = true
sha2.workspace = true
chrono.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
hex.workspace = true
tempfile.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["fs", "io-util"] }
tracing.workspace = true
uuid.workspace = true
walkdir.workspace = true

View File

@@ -0,0 +1,90 @@
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::Aes256Gcm;
use anyhow::{anyhow, Result};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use rand::RngCore;
use sha2::Sha256;
use std::fs;
use std::path::Path;
const NONCE_LEN: usize = 12;
const SALT_LEN: usize = 16;
pub struct VaultKey {
cipher: Aes256Gcm,
}
impl VaultKey {
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
let salt = if salt_path.exists() {
fs::read(salt_path)?
} else {
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, &salt)?;
salt.to_vec()
};
let mut key = [0u8; 32];
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(Self { cipher })
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut nonce_bytes = [0u8; NONCE_LEN];
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = GenericArray::from_slice(&nonce_bytes);
let ciphertext = self
.cipher
.encrypt(nonce, plaintext)
.map_err(|e| anyhow!("encrypt: {e}"))?;
let mut out = nonce_bytes.to_vec();
out.extend(ciphertext);
Ok(out)
}
pub fn decrypt(&self, blob: &[u8]) -> Result<Vec<u8>> {
if blob.len() < NONCE_LEN {
anyhow::bail!("blob too short");
}
let (nonce_bytes, ct) = blob.split_at(NONCE_LEN);
let nonce = GenericArray::from_slice(nonce_bytes);
self.cipher
.decrypt(nonce, ct)
.map_err(|e| anyhow!("decrypt: {e}"))
}
}
pub fn content_id(data: &[u8]) -> String {
use sha2::Digest;
hex::encode(Sha256::digest(data))
}
pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
let prefix = &id[..2.min(id.len())];
data_dir.join(prefix).join(id)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn roundtrip_crypto() {
let dir = tempdir().unwrap();
let salt = dir.path().join("salt");
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let enc = key.encrypt(b"stardust").unwrap();
let plain = key.decrypt(&enc).unwrap();
assert_eq!(plain, b"stardust");
}
}

View File

@@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ChunkIndex {
pub chunks: HashMap<String, ChunkEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkEntry {
pub pack_id: String,
pub offset: u64,
pub length: u64,
}
impl ChunkIndex {
pub fn record(&mut self, chunk_id: String, pack_id: String, offset: u64, length: u64) {
self.chunks.insert(
chunk_id,
ChunkEntry {
pack_id,
offset,
length,
},
);
}
}

View File

@@ -0,0 +1,17 @@
//! Restic-compatible path layout vault engine.
//!
//! Layout under vault root:
//! - `config` — repository version marker (restic-compatible sentinel)
//! - `data/` — content-addressed encrypted packs (`{prefix}/{id}`)
//! - `snapshots/` — JSON snapshot metadata
//! - `index/` — chunk index shards
//! - `keys/` — key material (local key file)
//!
//! Full `rustic_core` integration is deferred until toolchain meets its MSRV;
//! emergency verify may use external `rustic`/`restic` where formats align.
mod crypto;
mod index;
mod vault;
pub use vault::*;

View File

@@ -0,0 +1,260 @@
use crate::crypto::{content_id, pack_path, VaultKey};
use crate::index::ChunkIndex;
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef};
use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid;
const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredSnapshot {
pub id: Uuid,
pub taken_at: DateTime<Utc>,
pub manifest: SnapshotManifest,
pub size_bytes: u64,
pub tree_root: String,
}
pub struct Vault {
root: PathBuf,
key: VaultKey,
index: ChunkIndex,
}
impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?;
fs::create_dir_all(root.join("index"))?;
fs::create_dir_all(root.join("keys"))?;
let config_path = root.join("config");
if !config_path.exists() {
fs::write(&config_path, RESTIC_CONFIG)?;
}
let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = ChunkIndex::default();
let v = Self {
root,
key,
index,
};
v.save_index()?;
Ok(v)
}
pub fn open(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
let root = root.as_ref().to_path_buf();
if !root.join("config").exists() {
anyhow::bail!("vault not initialized");
}
let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?;
Ok(Self {
root,
key,
index,
})
}
fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json")
}
fn load_index(root: &Path) -> Result<ChunkIndex> {
let p = root.join("index/tessera-main.json");
if !p.exists() {
return Ok(ChunkIndex::default());
}
let data = fs::read_to_string(&p)?;
Ok(serde_json::from_str(&data)?)
}
fn save_index(&self) -> Result<()> {
let data = serde_json::to_string_pretty(&self.index)?;
fs::write(self.index_path(), data)?;
Ok(())
}
fn store_chunk(&mut self, plain: &[u8]) -> Result<String> {
let id = content_id(plain);
if self.index.chunks.contains_key(&id) {
return Ok(id);
}
let enc = self.key.encrypt(plain)?;
let pack_id = content_id(&enc);
let path = pack_path(&self.root.join("data"), &pack_id);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &enc)?;
self.index.record(id.clone(), pack_id, 0, enc.len() as u64);
Ok(id)
}
fn read_chunk(&self, id: &str) -> Result<Vec<u8>> {
let entry = self
.index
.chunks
.get(id)
.ok_or_else(|| anyhow!("unknown chunk {id}"))?;
let path = pack_path(&self.root.join("data"), &entry.pack_id);
let enc = fs::read(&path)?;
self.key.decrypt(&enc)
}
pub fn snapshot(
&mut self,
manifest: SnapshotManifest,
payload: &[u8],
dry_run: bool,
) -> Result<StoredSnapshot> {
if dry_run {
return Ok(StoredSnapshot {
id: manifest.snapshot_id,
taken_at: Utc::now(),
manifest,
size_bytes: payload.len() as u64,
tree_root: "dry-run".into(),
});
}
let chunk_id = self.store_chunk(payload)?;
self.save_index()?;
let snap = StoredSnapshot {
id: manifest.snapshot_id,
taken_at: Utc::now(),
manifest,
size_bytes: payload.len() as u64,
tree_root: chunk_id,
};
let path = self
.root
.join("snapshots")
.join(format!("{}.json", snap.id));
fs::write(&path, serde_json::to_string_pretty(&snap)?)?;
Ok(snap)
}
pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> {
let dir = self.root.join("snapshots");
if !dir.exists() {
return Ok(vec![]);
}
let mut out = Vec::new();
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let data = fs::read_to_string(&path)?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
out.push(snap);
}
out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
Ok(out)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let path = self.root.join("snapshots").join(format!("{id}.json"));
let data = fs::read_to_string(&path).context("snapshot metadata")?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
let bytes = self.read_chunk(&snap.tree_root)?;
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?;
}
fs::write(dest, &bytes)?;
Ok(bytes.len() as u64)
}
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
let mut removed = 0;
for id in ids {
let path = self.root.join("snapshots").join(format!("{id}.json"));
if path.exists() {
fs::remove_file(&path)?;
removed += 1;
}
}
Ok(removed)
}
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let snaps = self.list_snapshots()?;
let refs: Vec<SnapshotRef> = snaps
.iter()
.map(|s| SnapshotRef {
id: s.id,
taken_at: s.taken_at,
})
.collect();
let to_forget = evaluate_decay(&policy, refs);
self.forget(&to_forget)?;
Ok(to_forget)
}
pub fn root(&self) -> &Path {
&self.root
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
use tessera_core::manifest::SnapshotManifest;
#[test]
fn init_snap_list_restore() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "test".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault
.snapshot(manifest, b"payload bytes", false)
.unwrap();
let list = vault.list_snapshots().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].id, snap.id);
let out = dir.path().join("restored.bin");
let n = vault.restore_snapshot(snap.id, &out).unwrap();
assert_eq!(n, 13);
assert_eq!(fs::read(&out).unwrap(), b"payload bytes");
}
#[test]
fn dry_run_writes_nothing() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "rehearse".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
vault.snapshot(manifest, b"x", true).unwrap();
assert!(vault.list_snapshots().unwrap().is_empty());
}
}

166
docs/SPEC.md Normal file
View File

@@ -0,0 +1,166 @@
# Tessera — behavioral specification (v1)
Tessera is a self-hosted backup vault. This document is the contract for metaphors, state machines, error copy, and security baseline.
## Metaphor glossary
| Internal concept | User-facing term | Notes |
|------------------|------------------|-------|
| Repository | **Vault** | One encrypted store per host |
| Scheduled / manual job | **Orbit** | “Your data circles the vault on a schedule” |
| Point-in-time backup | **Snapshot** | A **tile** on the vault ring |
| Remote machine | **Outpost** | Runs `tessera-agent` |
| Encrypted link to hub | **Wormhole** | Pair once; beam snapshots upstream |
| Retention | **Decay** | Old snapshots fade per policy |
| Restore | **Reconstitute** | Destructive-capable; always confirm |
| Deduped deltas | “Only stardust that changed” | Tooltip only—not headline copy |
### Status dots (Lune-style)
| Color | Meaning |
|-------|---------|
| Green | All orbits current; last snapshot succeeded |
| Amber | Orbit running, pairing waiting, or reconstitute countdown |
| Grey | Outpost offline or never paired |
| Red | Last snapshot or reconstitute failed |
---
## State machine: orbit run
```
┌─────────────┐
schedule/ │ idle │
manual snap └──────┬──────┘
│ start
▼
┌─────────────┐
┌────│ preparing │──── timeout ──► failed
│ └──────┬──────┘
│ │ provider ready
│ ▼
│ ┌─────────────┐
│ │ capturing │◄── dry-run: skip vault write, end at rehearsed
│ └──────┬──────┘
│ │ packs sealed
│ ▼
│ ┌─────────────┐
│ │ sealing │
│ └──────┬──────┘
│ │ index updated
│ ▼
│ ┌─────────────┐
└───►│ applying │ decay after success only
│ decay │
└──────┬──────┘
│
┌───────────┴───────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ completed │ │ failed │
└─────────────┘ └─────────────┘
```
**Invariants**
- Only one active capture per orbit per vault at a time (hub enforces lock).
- Decay runs only after a **successful** non-dry-run seal.
- Dry-run (“rehearse”) never writes snapshot metadata to the vault store.
---
## State machine: reconstitute
```
user picks snapshot + target
│
▼
┌─────────────┐
│ confirming │ show evidence: size, age, paths/DB name
└──────┬──────┘
│ user confirms
▼
┌─────────────┐
│ countdown │ 12s grace; abort returns to idle
└──────┬──────┘
│ timer elapsed
▼
┌─────────────┐
│ restoring │
└──────┬──────┘
│
┌────────┴────────┐
▼ ▼
completed failed
```
**Copy during countdown:** “Reconstituting in {n}s — abort restores nothing.”
---
## State machine: wormhole pairing
```
Hub Outpost (agent)
│ │
│ display 6-char pairing code │
│◄───────────────────────────────│ user runs: tessera wormhole pair
│ │
│ POST /wormhole/claim │
│◄───────────────────────────────│
│ │
│ issue device token + id │
│───────────────────────────────►│
│ │
│ mTLS or Bearer on upload API │
│◄───────────────────────────────│
```
States: `unpaired` → `code_shown` → `claimed` → `active` → `offline` (heartbeat miss).
---
## Error UX copy (English v1)
| Situation | User message | Telemetry (expandable) |
|-----------|--------------|------------------------|
| Vault locked | “Another orbit is still circling the vault. Try again when it finishes.” | `orbit_lock:{id}` |
| Wrong passphrase | “That key doesn’t unlock this vault.” | No stack traces |
| Provider missing | “We couldn’t reach the source at this outpost.” | Provider error string |
| Postgres dump failed | “The database wouldn’t yield a snapshot.” | `pg_dump` exit code |
| Disk full | “The vault is out of space—free room or widen the hold.” | Bytes needed |
| Wormhole expired code | “That pairing code has burned up. Generate a fresh one on the vault.” | TTL 10m |
| Reconstitute aborted | “Reconstitute cancelled. Nothing was changed.” | — |
| Decay pruned | “{n} old snapshots decayed per your policy.” | Snapshot IDs |
Tone: short sentences, metaphor in headings, facts in telemetry panels.
---
## Security baseline
1. **Vault key:** Argon2id-derived key from passphrase; key file `keys/tessera.key` (mode 0600). Never logged.
2. **Hub auth (v1):** Local admin password → HTTP-only session cookie; hook point for OIDC later.
3. **Agents:** No vault master key. Hub issues **scoped upload tokens** per outpost/orbit after pairing.
4. **Wormhole:** v1 token-based HTTPS upload; mTLS optional when `TESSERA_WORMHOLE_MTLS=1` and certs present.
5. **Control plane:** SQLite (`data/tessera.db`) holds metadata only—no backup payloads.
6. **Audit:** Pairing, reconstitute start/complete, decay prune logged to `audit_log` table.
---
## Decay presets (friendly → policy)
| Preset | Rule |
|--------|------|
| `week-of-dailies` | Keep 7 daily snapshots |
| `month-of-weeklies` | Keep 4 weekly |
| `year-of-monthlies` | Keep 12 monthly |
| `custom` | Hub-stored JSON policy (see `tessera-core::decay`) |
---
## API conventions
- REST JSON under `/api/v1/`
- OpenAPI 3.1 via hub `utoipa`
- Webhooks (struct only v1): `orbit.completed`, `orbit.failed`, `decay.pruned`, `outpost.offline`

2
rust-toolchain.toml Normal file
View File

@@ -0,0 +1,2 @@
[toolchain]
channel = "1.88.0"

12
web/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Tessera Vault</title>
</head>
<body class="bg-space-950 text-star-100 overflow-hidden">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2619
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
web/package.json Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "tessera-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.62.0",
"motion": "^11.15.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"tailwindcss": "^4.0.0",
"typescript": "~5.6.2",
"vite": "^6.0.0"
}
}

159
web/src/App.tsx Normal file
View File

@@ -0,0 +1,159 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { motion, AnimatePresence } from "motion/react";
import {
fetchOrbits,
fetchSnapshots,
runOrbit,
startPairing,
startReconstitute,
abortReconstitute,
pollReconstitute,
} from "./api";
import { VaultRing } from "./components/VaultRing";
import { OrbitsPanel } from "./components/OrbitsPanel";
import { ReconstituteWizard } from "./components/ReconstituteWizard";
type Sheet = "none" | "snapshot" | "reconstitute" | "wormhole";
export default function App() {
const [sheet, setSheet] = useState<Sheet>("none");
const [selectedSnap, setSelectedSnap] = useState<string | null>(null);
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8000 });
const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8000 });
const statusColor =
orbits.data?.some((o) => o.last_status === "failed")
? "bg-orbit-red"
: orbits.data?.some((o) => o.last_status === "running" || o.last_status === "rehearsed")
? "bg-orbit-amber"
: "bg-orbit-green";
return (
<div className="h-[100dvh] flex flex-col bg-space-950 text-star-100 overflow-hidden">
<header className="shrink-0 px-4 py-3 flex items-center justify-between border-b border-space-800">
<div>
<h1 className="text-lg font-semibold tracking-wide">Tessera Vault</h1>
<p className="text-xs text-star-300">Only stardust that changed</p>
</div>
<span className={`w-3 h-3 rounded-full ${statusColor}`} title="vault status" />
</header>
<main className="flex-1 min-h-0 relative">
<VaultRing
snapshots={snaps.data ?? []}
onSelect={(id) => {
setSelectedSnap(id);
setSheet("snapshot");
}}
/>
<nav className="absolute bottom-4 inset-x-0 flex justify-center gap-2 px-4">
<TabButton onClick={() => setSheet("none")}>Vault</TabButton>
<TabButton onClick={() => setSheet("reconstitute")}>Reconstitute</TabButton>
<TabButton
onClick={async () => {
setPairing(await startPairing());
setSheet("wormhole");
}}
>
Wormhole
</TabButton>
</nav>
</main>
<AnimatePresence>
{sheet !== "none" && (
<motion.aside
className="absolute inset-x-0 bottom-0 top-12 bg-space-900/95 border-t border-space-800 rounded-t-2xl p-4 overflow-y-auto max-h-[70dvh]"
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 24 }}
>
{sheet === "snapshot" && selectedSnap && (
<SnapshotDetail
id={selectedSnap}
snaps={snaps.data ?? []}
onClose={() => setSheet("none")}
onReconstitute={() => setSheet("reconstitute")}
/>
)}
{sheet === "reconstitute" && (
<ReconstituteWizard
snapshots={snaps.data ?? []}
selected={selectedSnap}
onAbort={abortReconstitute}
onStart={startReconstitute}
onPoll={pollReconstitute}
/>
)}
{sheet === "wormhole" && pairing && (
<div className="space-y-3">
<h2 className="text-xl font-medium">Open a wormhole</h2>
<p className="text-star-300 text-sm">
On your outpost, run{" "}
<code className="text-orbit-amber">tessera-agent pair {pairing.code}</code>
</p>
<p className="text-4xl font-mono tracking-widest text-center py-6">{pairing.code}</p>
</div>
)}
</motion.aside>
)}
</AnimatePresence>
<OrbitsPanel
orbits={orbits.data ?? []}
onRun={(id) => runOrbit(id).then(() => orbits.refetch())}
/>
</div>
);
}
function TabButton({ children, onClick }: { children: React.ReactNode; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className="px-4 py-2 rounded-full bg-space-800 text-sm hover:bg-space-800/80 border border-space-800"
>
{children}
</button>
);
}
function SnapshotDetail({
id,
snaps,
onClose,
onReconstitute,
}: {
id: string;
snaps: { id: string; orbit_name: string; taken_at: string; size_bytes: number }[];
onClose: () => void;
onReconstitute: () => void;
}) {
const snap = snaps.find((s) => s.id === id);
if (!snap) return null;
return (
<div className="space-y-3">
<div className="flex justify-between items-center">
<h2 className="text-xl">Snapshot tile</h2>
<button type="button" onClick={onClose} className="text-star-300 text-sm">
Close
</button>
</div>
<p className="text-star-300 text-sm">Orbit {snap.orbit_name}</p>
<p className="text-sm">{new Date(snap.taken_at).toLocaleString()}</p>
<p className="text-sm">{snap.size_bytes} bytes</p>
<button
type="button"
onClick={onReconstitute}
className="w-full py-2 rounded-lg bg-orbit-amber/20 text-orbit-amber border border-orbit-amber/40"
>
Reconstitute…
</button>
</div>
);
}

57
web/src/api.ts Normal file
View File

@@ -0,0 +1,57 @@
export type Snapshot = {
id: string;
taken_at: string;
orbit_name: string;
size_bytes: number;
};
export type Orbit = {
id: string;
name: string;
provider: string;
last_status: string;
dry_run: boolean;
schedule?: string | null;
};
export async function fetchSnapshots(): Promise<Snapshot[]> {
const r = await fetch("/api/v1/snapshots");
if (!r.ok) throw new Error("snapshots");
return r.json();
}
export async function fetchOrbits(): Promise<Orbit[]> {
const r = await fetch("/api/v1/orbits");
if (!r.ok) throw new Error("orbits");
return r.json();
}
export async function startPairing(): Promise<{ code: string; expires_at: string }> {
const r = await fetch("/api/v1/wormhole/pairing", { method: "POST" });
return r.json();
}
export async function runOrbit(id: string): Promise<void> {
await fetch(`/api/v1/orbits/${id}/run`, { method: "POST" });
}
export async function startReconstitute(snapshotId: string, target: string): Promise<{
session_id: string;
session: { seconds_remaining: number; state: string };
}> {
const r = await fetch("/api/v1/reconstitute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ snapshot_id: snapshotId, target_path: target }),
});
return r.json();
}
export async function abortReconstitute(sessionId: string): Promise<void> {
await fetch(`/api/v1/reconstitute/${sessionId}`, { method: "DELETE" });
}
export async function pollReconstitute(sessionId: string) {
const r = await fetch(`/api/v1/reconstitute/${sessionId}`);
return r.json();
}

View File

@@ -0,0 +1,54 @@
import type { Orbit } from "../api";
export function OrbitsPanel({
orbits,
onRun,
}: {
orbits: Orbit[];
onRun: (id: string) => void;
}) {
if (!orbits.length) return null;
return (
<section className="shrink-0 border-t border-space-800 px-4 py-2 overflow-x-auto flex gap-2 scrollbar-none">
{orbits.map((o) => (
<article
key={o.id}
className="min-w-[160px] rounded-xl bg-space-900 border border-space-800 p-3 text-sm"
>
<div className="flex items-center gap-2">
<StatusDot status={o.last_status} />
<span className="font-medium truncate">{o.name}</span>
</div>
<p className="text-xs text-star-300 mt-1">
{o.dry_run ? "Rehearse orbit" : scheduleLabel(o.schedule)}
</p>
<button
type="button"
className="mt-2 text-xs text-orbit-green"
onClick={() => onRun(o.id)}
>
Capture now
</button>
</article>
))}
</section>
);
}
function StatusDot({ status }: { status: string }) {
const color =
status === "failed"
? "bg-orbit-red"
: status === "running" || status === "rehearsed"
? "bg-orbit-amber"
: status === "completed"
? "bg-orbit-green"
: "bg-star-300/40";
return <span className={`w-2 h-2 rounded-full ${color}`} />;
}
function scheduleLabel(schedule?: string | null) {
if (!schedule) return "On demand";
if (schedule.includes("0 2")) return "Every night at 2am";
return schedule;
}

View File

@@ -0,0 +1,90 @@
import { useEffect, useState } from "react";
import type { Snapshot } from "../api";
export function ReconstituteWizard({
snapshots,
selected,
onStart,
onPoll,
onAbort,
}: {
snapshots: Snapshot[];
selected: string | null;
onStart: (snapId: string, target: string) => Promise<{ session_id: string; session: { seconds_remaining: number; state: string } }>;
onPoll: (id: string) => Promise<{ state: string; seconds_remaining: number }>;
onAbort: (id: string) => Promise<void>;
}) {
const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? "");
const [target, setTarget] = useState("./restore/out");
const [sessionId, setSessionId] = useState<string | null>(null);
const [remaining, setRemaining] = useState(12);
const [state, setState] = useState<string>("idle");
useEffect(() => {
if (!sessionId) return;
const t = setInterval(async () => {
const s = await onPoll(sessionId);
setState(s.state);
setRemaining(s.seconds_remaining ?? 0);
}, 500);
return () => clearInterval(t);
}, [sessionId, onPoll]);
return (
<div className="space-y-4">
<h2 className="text-xl font-medium">Reconstitute</h2>
<p className="text-sm text-star-300">Pick a snapshot and where it should land.</p>
<label className="block text-sm">
Snapshot
<select
className="mt-1 w-full bg-space-800 rounded px-2 py-2"
value={snapId}
onChange={(e) => setSnapId(e.target.value)}
>
{snapshots.map((s) => (
<option key={s.id} value={s.id}>
{s.orbit_name} — {new Date(s.taken_at).toLocaleDateString()}
</option>
))}
</select>
</label>
<label className="block text-sm">
Target path
<input
className="mt-1 w-full bg-space-800 rounded px-2 py-2"
value={target}
onChange={(e) => setTarget(e.target.value)}
/>
</label>
{state === "countdown" && (
<p className="text-orbit-amber text-center py-2">
Reconstituting in {remaining}s — abort restores nothing.
</p>
)}
<div className="flex gap-2">
<button
type="button"
className="flex-1 py-2 rounded-lg bg-orbit-red/20 text-orbit-red border border-orbit-red/30"
disabled={!sessionId}
onClick={() => sessionId && onAbort(sessionId)}
>
Abort
</button>
<button
type="button"
className="flex-1 py-2 rounded-lg bg-orbit-green/20 text-orbit-green border border-orbit-green/40"
onClick={async () => {
const res = await onStart(snapId, target);
setSessionId(res.session_id);
setState(res.session.state);
setRemaining(res.session.seconds_remaining);
}}
>
Begin
</button>
</div>
{state === "completed" && <p className="text-orbit-green text-sm">Reconstitute complete.</p>}
{state === "aborted" && <p className="text-star-300 text-sm">Reconstitute cancelled. Nothing was changed.</p>}
</div>
);
}

View File

@@ -0,0 +1,47 @@
import { motion } from "motion/react";
import type { Snapshot } from "../api";
export function VaultRing({
snapshots,
onSelect,
}: {
snapshots: Snapshot[];
onSelect: (id: string) => void;
}) {
const count = Math.max(snapshots.length, 6);
const radius = Math.min(140, typeof window !== "undefined" ? window.innerWidth * 0.35 : 140);
return (
<div className="h-full flex items-center justify-center overflow-hidden touch-none">
<svg
viewBox="-200 -200 400 400"
className="w-full h-full max-w-[min(100vw,480px)] max-h-[min(70dvh,480px)]"
role="img"
aria-label="Vault snapshot ring"
>
<circle cx="0" cy="0" r={radius + 20} fill="none" stroke="#252d55" strokeWidth="2" strokeDasharray="4 8" />
<text x="0" y="-8" textAnchor="middle" fill="#a8b4e8" fontSize="14">
Vault
</text>
{snapshots.slice(0, 12).map((snap, i) => {
const angle = (i / count) * Math.PI * 2 - Math.PI / 2;
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
return (
<motion.g
key={snap.id}
initial={{ scale: 0 }}
animate={{ scale: 1 }}
whileTap={{ scale: 0.92 }}
style={{ cursor: "pointer" }}
onClick={() => onSelect(snap.id)}
>
<circle cx={x} cy={y} r="18" fill="#151b3a" stroke="#5ee6a8" strokeWidth="2" />
<title>{snap.orbit_name}</title>
</motion.g>
);
})}
</svg>
</div>
);
}

19
web/src/index.css Normal file
View File

@@ -0,0 +1,19 @@
@import "tailwindcss";
@theme {
--color-space-950: #05060f;
--color-space-900: #0c1024;
--color-space-800: #151b3a;
--color-star-100: #e8ecff;
--color-star-300: #a8b4e8;
--color-orbit-amber: #f5c56b;
--color-orbit-green: #5ee6a8;
--color-orbit-red: #ff6b7a;
}
html,
body,
#root {
height: 100%;
margin: 0;
}

15
web/src/main.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import "./index.css";
const queryClient = new QueryClient();
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</StrictMode>,
);

1
web/tsconfig.app.json Normal file
View File

@@ -0,0 +1 @@
{ "extends": "./tsconfig.json", "compilerOptions": { "composite": true, "noEmit": false, "outDir": "./dist-types" }, "include": ["src"] }

17
web/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true
},
"include": ["src"]
}

8
web/vite.config.ts Normal file
View File

@@ -0,0 +1,8 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
server: { port: 5173, proxy: { "/api": "http://127.0.0.1:8787", "/health": "http://127.0.0.1:8787" } },
});