refactor(content,core,app,editor,learn): Learn's content in pure Dart, for its agent

ADR 0044's D49 (amended in building it): what reads and seals Learn's
content moves out of the Flutter packages, so Learn's agent, which runs
without Flutter, shares it rather than repeating the privacy rules.

packages/halkyon_content (new, pure Dart) takes from halkyon_app the
envelope and its cipher, SealedFile, UnlockedAccountKeys, shared
spaces' gateway with SharedKeys and KeyPins, FileCache and
FileServerGateway, with their fakes and tests; halkyon_app exports it,
so no app changes. Its rich_text.dart takes RichContent from
halkyon_editor, which exports it. newAccountKeys makes an agent's key
pair. halkyon_core takes DelayedDeletions and gains SyncRequests, what a
synced gateway asks of the sync, which SyncService implements.

apps/learn/halkyon_learn_core (new, pure Dart) takes Learn's privacy,
sync, payloads and the models, codecs, gateways and repositories of
studysets, cards, notes, tags and feedback, with what they reach of
files, learning paths, citations and study options; the app imports them
from there. A subject's icon, colour and name stay in the app
(SubjectLook); what only the app shows (progress, exam coverage, the
card browser, deletions' waits) stays too. Nothing changes for people
using the apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-11-11 21:24:30 +01:00
commit d09625d43e
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
442 changed files with 3517 additions and 2007 deletions

View file

@ -4,7 +4,7 @@ What holds for every app and package of this repository (how work is done here,
A spaced-repetition learning app: studysets of flashcards, reviewed on an FSRS schedule. Content is rich text (`appflowy_editor` documents) everywhere. Targets: Linux, Windows, macOS, Android, iOS. There is no web build.
- **Packages** (`apps/learn/`): `halkyon_learn_server` (endpoints, models, migrations), `halkyon_learn_client` (generated, never edited), `halkyon_learn_flutter` (the app, ID `app.halkyon.learn`), `halkyon_learn_curator` (the dictionaries' converter, below), and `tool/` with the scripts that write the app's assets (maps, Anki fixtures; run them from `apps/learn`; its icon, Lucide's graduation cap since ADR 0031, is the root's `tool/app_icons.py`'s, `assets/icon/halkyon_learn_icon.png`, also atop the rail, on the launch screen and on halkyon_app's screens (`learnIcon`) since 2 Nov 2026, as Todo's and Train's show theirs, ADR 0031, D6). What every Halkyon server has comes from the Serverpod module `halkyon_base` (ADR 0014, decided 2026-10-19; `packages/halkyon_base_server` and `packages/halkyon_base_client`, which Learn's packages take by path): signing in, the account's ways in and its deletion, the pruning, and the instance's basics. The server sets it up for Learn before it starts (`HalkyonBase.configure(pod, learnBase(accounts: learnAccounts()))` in `server.dart`; `lib/src/auth/learn_base.dart`: Learn holds the instance's register of accounts (ADR 0016), `learnAccounts` reading the members from `INSTANCE_MEMBERS` and refusing to start with `ACCOUNT_REGISTER_URL`; the app it serves, `learn`, which its instances name in their basics and the app checks (never change it), the app's name in sign-in mails, this project's source, `minimumAppBuild`, Learn's own deletion as a hook), its endpoints are `client.modules.base` in the app, its tables (`email_identity`, `email_code_request`) are the module's, and tests that delete people or ask `instance.info()` set it up as the server does (`useLearnBase(sessionBuilder)`). What every Halkyon app's shell has comes from `halkyon_app` on the module's client (ADR 0014, `packages/halkyon_app`; with `halkyon_core`'s `SerialQueue` and `CoalescingRunner`): the instances and the first start, signing in and switching person, the gates (`InstanceGate`, `SessionGate`, `PersonScope`, `AppScope`), the sync service and where it stands, with texts of its own (`HalkyonAppLocalizations`, in `appLocalizationsDelegates`) that name the app from `learnFrame`. Change what they hold there, not here.
- **Packages** (`apps/learn/`): `halkyon_learn_server` (endpoints, models, migrations), `halkyon_learn_client` (generated, never edited), `halkyon_learn_flutter` (the app, ID `app.halkyon.learn`), `halkyon_learn_core` (Learn's content in pure Dart, shared with its agent, Halkyon's ADR 0044, D49: privacy, sync, payloads, and the models, gateways and repositories of studysets, cards, notes, tags and feedback; the app imports them from `package:halkyon_learn_core/…`, and what only it shows stays in it), `halkyon_learn_curator` (the dictionaries' converter, below), and `tool/` with the scripts that write the app's assets (maps, Anki fixtures; run them from `apps/learn`; its icon, Lucide's graduation cap since ADR 0031, is the root's `tool/app_icons.py`'s, `assets/icon/halkyon_learn_icon.png`, also atop the rail, on the launch screen and on halkyon_app's screens (`learnIcon`) since 2 Nov 2026, as Todo's and Train's show theirs, ADR 0031, D6). What every Halkyon server has comes from the Serverpod module `halkyon_base` (ADR 0014, decided 2026-10-19; `packages/halkyon_base_server` and `packages/halkyon_base_client`, which Learn's packages take by path): signing in, the account's ways in and its deletion, the pruning, and the instance's basics. The server sets it up for Learn before it starts (`HalkyonBase.configure(pod, learnBase(accounts: learnAccounts()))` in `server.dart`; `lib/src/auth/learn_base.dart`: Learn holds the instance's register of accounts (ADR 0016), `learnAccounts` reading the members from `INSTANCE_MEMBERS` and refusing to start with `ACCOUNT_REGISTER_URL`; the app it serves, `learn`, which its instances name in their basics and the app checks (never change it), the app's name in sign-in mails, this project's source, `minimumAppBuild`, Learn's own deletion as a hook), its endpoints are `client.modules.base` in the app, its tables (`email_identity`, `email_code_request`) are the module's, and tests that delete people or ask `instance.info()` set it up as the server does (`useLearnBase(sessionBuilder)`). What every Halkyon app's shell has comes from `halkyon_app` on the module's client (ADR 0014, `packages/halkyon_app`; with `halkyon_core`'s `SerialQueue` and `CoalescingRunner`): the instances and the first start, signing in and switching person, the gates (`InstanceGate`, `SessionGate`, `PersonScope`, `AppScope`), the sync service and where it stands, with texts of its own (`HalkyonAppLocalizations`, in `appLocalizationsDelegates`) that name the app from `learnFrame`. Change what they hold there, not here.
- **Instances**: anyone may run one. The app takes the server URL from `--dart-define=SERVER_URL=…`, so never hard-code a host.
## Working on Learn

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/>.

View file

@ -0,0 +1,20 @@
# halkyon_learn_core
Halkyon Learn's content in pure Dart (Halkyon's ADR 0044, D49): what the app and Learn's agent
both read and write, so the privacy rules and the payloads live in one place.
- `core/`: the payloads' envelope and codecs (`content/`), privacy (`privacy/`: `Privacy`,
`ContentKeys`, the ledger, shared spaces' keys), the sync's spaces (`sync/`: `SpaceRouter`,
`SyncSpaceLookup`, positions), people's files (`asset/`), `LatestValue` and `watchReads`
(`async/`), citations and public people.
- `feature/`: the models, payload codecs, gateways (the synced ones included) and repositories
of studysets, cards, notes, tags and feedback, and what they take of learning paths and study
options.
The synced gateways take halkyon_core's `SyncRequests`, which halkyon_app's `SyncService` and
the agent's own sync implement. What only the app shows (progress, exam coverage, deletions'
waits, the card browser, a subject's icon and name) stays in the app, `halkyon_learn_flutter`.
Paths' sync, PDFs, reviews and settings move here when the agent needs them.
Its tests are still the app's (`halkyon_learn_flutter/test/`), on the fakes there. Licensed under
the AGPL-3.0.

View file

@ -0,0 +1,9 @@
# The workspace's lint rules (see ../../analysis_options.yaml).
include: ../../../analysis_options.yaml
analyzer:
exclude:
- build/**
formatter:
trailing_commas: preserve

View file

@ -0,0 +1,49 @@
import 'dart:typed_data';
/// An asset row as stored: the file's id, SHA-256 (lowercase hex), media type
/// and size, and its payload, opened. A file of a private studyset (ADR
/// 0019) is sealed with its tree's key, `keyId`; the row's hash and size are
/// then the sealed file's, and `locked` where that key doesn't open here
/// (its payload then blank).
typedef AssetRow = ({
String id,
String sha256,
String mimeType,
int byteSize,
ByteData payload,
String? keyId,
bool locked,
});
/// The person's asset rows, one per file of their content (ADR 0004,
/// rule 5); the files themselves are on the server and in the
/// device's cache.
abstract interface class AssetGateway() {
/// The row [id]; null if there is none.
Future<AssetRow?> byId(String id);
/// A row of the file with [sha256]; null if there is none.
Future<AssetRow?> bySha256(String sha256);
/// Every row, sealed or readable.
Future<List<AssetRow>> all();
/// An id for a new row, made before it is stored, as a sealed file is
/// sealed for its row.
String newId();
/// Stores a new row [id], its payload sealed with [keyId] (readable
/// without), and returns its id.
Future<String> insert({
required String id,
required String sha256,
required String mimeType,
required int byteSize,
required ByteData payload,
String? keyId,
});
/// Blanks the row [id]'s payload, then deletes the row: its file goes from
/// the server once nothing refers to it any more.
Future<void> delete(String id);
}

View file

@ -0,0 +1,54 @@
import 'dart:typed_data';
import 'package:halkyon_learn_core/core/content/payload.dart';
// A file's content as its synced asset row stores it (see core/content/payload);
// the hash, media type and size are columns of their own.
//
// Schema 1 holds the name the file came with.
// Schema 2 adds, for a file of a private studyset (ADR 0019), `plain`: the
// SHA-256 of the file before it was sealed, which the row's own hash, of
// the sealed file, doesn't tell; it lives only in this payload, sealed too.
/// The schema this app writes for a readable file.
const assetSchemaVersion = 1;
/// The newest schema this app reads.
const _newestAssetSchema = 2;
/// What a file's payload holds.
typedef AssetFileInfo = ({String fileName, String? plainSha256});
/// Encodes a file's [fileName] into its payload; for a sealed file also the
/// SHA-256 of what was sealed ([plainSha256]).
ByteData encodeAssetPayload({
required String fileName,
String? plainSha256,
}) => plainSha256 == null
? encodePayload(assetSchemaVersion, {'fileName': fileName})
: encodePayload(2, {'fileName': fileName, 'plain': plainSha256});
/// Decodes a file's payload into the name it came with.
///
/// Throws a [FormatException] for anything else, including content written
/// by a newer app version in a schema this one doesn't know.
String decodeAssetPayload(ByteData payload) =>
decodeAssetInfo(payload).fileName;
/// Decodes a file's payload: the name it came with, and for a sealed file
/// the SHA-256 of what was sealed.
///
/// Throws a [FormatException] as [decodeAssetPayload] does.
AssetFileInfo decodeAssetInfo(ByteData payload) {
final json = decodePayload(payload, newestSchema: _newestAssetSchema);
if (json case {'fileName': final String fileName}) {
return (
fileName: fileName,
plainSha256: switch (json['plain']) {
final String plain => plain,
_ => null,
},
);
}
throw const FormatException('Not a file payload.');
}

View file

@ -0,0 +1,437 @@
import 'dart:async';
import 'dart:developer';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:halkyon_content/halkyon_content.dart'
show FileCache, FileLimitReached, FileRoom, FileServerGateway, isSha256;
import 'package:halkyon_core/halkyon_core.dart'
show CoalescingRunner, SerialQueue;
import 'package:halkyon_learn_core/core/asset/data/asset_gateway.dart';
import 'package:halkyon_learn_core/core/asset/data/asset_payload.dart';
import 'package:halkyon_learn_core/core/asset/data/asset_sealing.dart';
import 'package:halkyon_learn_core/core/asset/model/stored_file.dart';
import 'package:halkyon_learn_core/core/privacy/data/tree_files.dart';
/// The files of the person's content (ADR 0004, rule 5): an asset row each,
/// synced like all content, and the file itself on this device and the
/// server, by its SHA-256.
///
/// A file added here is kept on this device and waits to be uploaded; the
/// uploads run whenever `uploadTriggers` fires (after each sync, so the row
/// is usually on the server before its file), one at a time, and what fails
/// waits for the next time. A file this device lacks is downloaded when asked
/// for, checked against its hash and kept.
///
/// A file of a private studyset (ADR 0019, D5) is sealed with its tree's key
/// for its row before it is hashed ([AssetSealing]): the row's hash and the
/// file uploaded (`encrypted`) are the sealed file's, and the instance never
/// sees it readable. This device keeps the sealed file under its hash, to
/// upload and check, and the opened one under the hash of what was sealed,
/// which only the row's sealed payload tells, for what reads files by path.
/// The same file in a private and a readable studyset, or in two private
/// trees, is a file per key.
class AssetRepository(
final AssetGateway _rows,
final FileServerGateway _server,
final FileCache _files,
final AssetSealing _sealing, {
Stream<void> uploadTriggers = const Stream.empty(),
/// Whether files may go up and come down now: not while sync holds them
/// back on mobile data (Halkyon's ADR 0042); always where not said.
final bool Function() _filesAllowed = _always,
}) implements TreeFiles {
this {
_triggers = uploadTriggers.listen((_) {
// A sync may have brought rows: the index is read anew.
_sealedIndex = null;
unawaited(uploadPending());
});
}
/// The sealed rows by their key and the hash of what they hold
/// (`<keyId>|<sha256>`), read once until rows change, so adding many files
/// doesn't open every row for each (the reading of 22 Oct).
Map<String, AssetRow>? _sealedIndex;
/// The largest file the server takes, of any kind but a PDF.
static const maxBytes = 20 * 1024 * 1024;
/// The largest PDF the server takes (decided 2026-10-03; 100 MB since
/// 2026-11-09).
static const maxPdfBytes = 100 * 1024 * 1024;
/// A PDF's media type.
static const pdfMediaType = 'application/pdf';
/// The largest file of [mimeType] the server takes.
static int maxBytesOf(String mimeType) =>
mimeType == pdfMediaType ? maxPdfBytes : maxBytes;
late final StreamSubscription<void> _triggers;
/// Adding one file at a time, so a file added twice at once is one row.
final _adding = SerialQueue();
/// The downloads under way, by hash, so a file asked for twice at once is
/// downloaded once.
final _downloads = <String, Future<Uint8List?>>{};
/// Uploads what waits, one round at a time: a call during a round runs
/// one more after it.
late final _uploads = CoalescingRunner(
_uploadAll,
onError: (error, _) =>
log('Uploading files failed', name: 'Assets', error: error),
);
/// Whether it stopped: no round starts any more.
var _stopped = false;
/// Adds [bytes], a file named [fileName] of [mimeType] in the studyset
/// [studysetId] (sealed with its tree's key where it is private; readable
/// without a studyset), and returns the id of its asset row: the row of
/// the same file under the same key if there is one, else a new one.
/// Throws an [ArgumentError] for an empty file or one too large for its
/// kind ([maxBytesOf]).
Future<String> add(
Uint8List bytes, {
required String fileName,
required String mimeType,
required String? studysetId,
}) async => await addWithKey(
bytes,
fileName: fileName,
mimeType: mimeType,
keyId: studysetId == null ? null : await _sealing.keyToWriteIn(studysetId),
);
/// Adds [bytes] as [add] does, for the item [itemId] of [kind]: sealed
/// with the key of the tree it is in, where that is private.
Future<String> addToItem(
Uint8List bytes, {
required String fileName,
required String mimeType,
required ItemKind kind,
required String itemId,
}) async => await addWithKey(
bytes,
fileName: fileName,
mimeType: mimeType,
keyId: await _sealing.keyOfItem(kind, itemId),
);
/// The id of the asset row of the file with [sha256] where it would be
/// added for the item [itemId] of [kind]; null while there is none.
Future<String?> idInItem(
String sha256, {
required ItemKind kind,
required String itemId,
}) async => await _idUnder(sha256, await _sealing.keyOfItem(kind, itemId));
@override
Future<String> addWithKey(
Uint8List bytes, {
required String fileName,
required String mimeType,
required String? keyId,
}) async {
if (bytes.isEmpty || bytes.length > maxBytesOf(mimeType)) {
throw ArgumentError.value(bytes.length, 'bytes', 'is out of range');
}
return await _adding.run(() async {
final plain = sha256.convert(bytes).toString();
await _files.write(plain, bytes);
if (keyId == null) {
if (await _rows.bySha256(plain) case final row?
when row.keyId == null) {
return row.id;
}
final id = await _rows.insert(
id: _rows.newId(),
sha256: plain,
mimeType: mimeType,
byteSize: bytes.length,
payload: encodeAssetPayload(fileName: fileName),
);
// Every new row asks the server, even for a file uploaded before:
// the server may have pruned it once no row referred to it.
await _files.markPending(plain);
return id;
}
if (await _sealedRowOf(plain, keyId) case final row?) {
return row.id;
}
final id = _rows.newId();
final sealed = _sealing.sealFile(bytes, keyId: keyId, assetId: id);
final hash = sha256.convert(sealed).toString();
await _files.write(hash, sealed);
await _rows.insert(
id: id,
sha256: hash,
mimeType: mimeType,
byteSize: sealed.length,
payload: encodeAssetPayload(fileName: fileName, plainSha256: plain),
keyId: keyId,
);
// Read anew next time, with this row.
_sealedIndex = null;
await _files.markPending(hash);
return id;
});
}
/// The row of the file whose content before sealing has [plain] as its
/// hash, sealed with [keyId]; null while there is none.
Future<AssetRow?> _sealedRowOf(String plain, String keyId) async {
final index = _sealedIndex ??= {
for (final row in await _rows.all())
if (row.keyId case final rowKey? when !row.locked)
if (_plainOf(row) case final rowPlain?) '$rowKey|$rowPlain': row,
};
return index['$keyId|$plain'];
}
/// The hash of what [row]'s sealed file holds; null for a readable row,
/// or one whose payload doesn't say.
static String? _plainOf(AssetRow row) {
try {
return switch (decodeAssetInfo(row.payload).plainSha256) {
final plain? when isSha256(plain) => plain,
_ => null,
};
} on FormatException {
return null;
}
}
/// The id of the asset row of the file with [sha256] (as it is before any
/// sealing) where it would be added for the studyset [studysetId]: sealed
/// with its tree's key, or readable; null while the person has none.
Future<String?> idOf(String sha256, {required String? studysetId}) async {
final keyId = studysetId == null
? null
: await _sealing.keyOfStudyset(studysetId);
return await _idUnder(sha256, keyId);
}
/// The id of the row of the file with [sha256] sealed with [keyId], or
/// readable without one.
Future<String?> _idUnder(String sha256, String? keyId) async {
if (keyId != null) {
return (await _sealedRowOf(sha256, keyId))?.id;
}
return switch (await _rows.bySha256(sha256)) {
final row? when row.keyId == null => row.id,
_ => null,
};
}
@override
Future<String?> keyIdOf(String id) async => (await _rows.byId(id))?.keyId;
@override
Future<bool> exists(String id) async => await _rows.byId(id) != null;
/// The key of the tree the item [id] of [kind] is in; null while
/// readable.
Future<String?> keyOfItem(ItemKind kind, String id) =>
_sealing.keyOfItem(kind, id);
@override
Future<({Uint8List bytes, String fileName, String mimeType})?> plainOf(
String id,
) async => switch (await fileOf(id)) {
final file? => (
bytes: file.bytes,
fileName: file.fileName,
mimeType: file.mimeType,
),
null => null,
};
/// The file of the asset row [id]: from this device, else downloaded.
/// Null when it can't be had now: no such row, no connection, or not
/// uploaded yet.
Future<StoredFile?> fileOf(String id) async {
final row = await _rows.byId(id);
if (row == null || row.locked || !isSha256(row.sha256)) {
return null;
}
if (row.keyId != null) {
return await _sealedFileOf(row);
}
final bytes =
await _files.read(row.sha256) ??
await (_downloads[row.sha256] ??=
_download(
id,
row.sha256,
).whenComplete(() {
_downloads.remove(row.sha256);
}));
if (bytes == null) {
return null;
}
String fileName;
try {
fileName = decodeAssetPayload(row.payload);
} on FormatException {
fileName = '';
}
return StoredFile(
bytes: bytes,
mimeType: row.mimeType,
fileName: fileName,
path: _files.pathOf(row.sha256),
);
}
/// The file of the sealed [row], opened: as this device keeps it opened,
/// else its sealed file (kept, or downloaded), checked against the row's
/// hash, opened for the row, and checked against the hash of what was
/// sealed.
Future<StoredFile?> _sealedFileOf(AssetRow row) async {
final plain = _plainOf(row);
if (plain == null) {
return null;
}
var bytes = await _files.read(plain);
if (bytes == null) {
final sealed =
await _files.read(row.sha256) ??
await (_downloads[row.sha256] ??= _download(row.id, row.sha256)
.whenComplete(() {
// A block, not an arrow: the future removed is this one,
// and returned it would be waited for by itself.
_downloads.remove(row.sha256);
}));
final opened = sealed == null
? null
: _sealing.openFile(sealed, assetId: row.id);
if (opened == null || sha256.convert(opened).toString() != plain) {
return null;
}
await _files.write(plain, opened);
bytes = opened;
}
return StoredFile(
bytes: bytes,
mimeType: row.mimeType,
fileName: decodeAssetInfo(row.payload).fileName,
path: _files.pathOf(plain),
);
}
Future<Uint8List?> _download(String id, String hash) async {
if (!_filesAllowed()) {
// As without a connection: what this device lacks waits.
return null;
}
try {
final bytes = await _server.download(id);
if (bytes == null || sha256.convert(bytes).toString() != hash) {
return null;
}
await _files.write(hash, bytes);
return bytes;
} on Object catch (error) {
log('Downloading a file failed', name: 'Assets', error: error);
return null;
}
}
/// Uploads the files that wait; what fails waits for the next time. One
/// run at a time: a call during a run runs once more after it.
Future<void> uploadPending() => _uploads.run();
Future<void> _uploadAll() async {
if (_stopped || !_filesAllowed()) {
return;
}
for (final hash in await _files.pendingUploads()) {
try {
if (!await _upload(hash)) {
continue;
}
await _files.clearPending(hash);
} on FileLimitReached catch (error) {
// The others wouldn't fit either: they stay on this device, and
// the next round asks again, once room may have been made.
log('No room for more files', name: 'Assets', error: error);
return;
} on Object catch (error) {
// Without a connection the others fail too: next time.
log('Uploading a file failed', name: 'Assets', error: error);
return;
}
}
}
/// Uploads the file with [hash]; whether it no longer waits.
Future<bool> _upload(String hash) async {
final bytes = await _files.read(hash);
if (bytes == null) {
// Gone from this device: nothing to upload, ever.
return true;
}
final row = await _rows.bySha256(hash);
if (row == null) {
// No live row names it any more, as one a private studyset's rewrite
// replaced: never uploaded, least of all readable (the reading of 22
// Oct).
return true;
}
// A sealed file says so, as only a readable one is looked into.
final encrypted = row.keyId != null;
final description = await _server.startUpload(
hash,
bytes.length,
encrypted: encrypted,
);
if (description == null) {
return true;
}
return await _server.upload(description, bytes) &&
await _server.finishUpload(hash, encrypted: encrypted);
}
/// How much room the person's files take on the server, and may take; null
/// when that can't be asked now (no connection).
Future<FileRoom?> room() async {
try {
return await _server.room();
} on Exception catch (error) {
log('Asking for the room of files failed', name: 'Assets', error: error);
return null;
}
}
/// The size of the file [id] in bytes, from its row; null without one.
Future<int?> byteSizeOf(String id) async => (await _rows.byId(id))?.byteSize;
/// Deletes the row of the file [id], blanked first: the file goes from the
/// server once nothing refers to it, and stops taking the person's room.
/// Only for files no content refers to any more.
@override
Future<void> delete(String id) async {
final row = await _rows.byId(id);
await _rows.delete(id);
_sealedIndex = null;
// Its upload, if still waiting, is no longer owed (the reading of 22
// Oct), unless another row holds the same file.
if (row != null && await _rows.bySha256(row.sha256) == null) {
await _files.clearPending(row.sha256);
}
}
/// Stops uploading; an upload under way finishes first.
Future<void> dispose() async {
await _triggers.cancel();
_stopped = true;
await _uploads.idle;
}
}
bool _always() => true;

View file

@ -0,0 +1,38 @@
import 'dart:typed_data';
/// The kinds of item a file can be added to without naming its studyset.
enum ItemKind() {
card,
note,
step,
}
/// How the files of a private studyset are sealed (ADR 0019, D5): with its
/// tree's key, for the asset row they belong to, so a file moved to another
/// row never opens. `Privacy` does it; tests fake it.
abstract interface class AssetSealing() {
/// The key [studysetId]'s tree is encrypted with; null while readable.
Future<String?> keyOfStudyset(String studysetId);
/// [keyOfStudyset] for a file about to be added there; throws where this
/// device may write nothing (it lacks the keys of an account that has
/// them, the final reading of 22 Oct).
Future<String?> keyToWriteIn(String studysetId);
/// The key of the tree the item [id] of [kind] is in; null while
/// readable, or for an item that isn't there.
Future<String?> keyOfItem(ItemKind kind, String id);
/// [plain] sealed with the key [keyId] for the asset row [assetId], as it
/// is stored and uploaded. Throws a [StateError] for a key not open here.
Uint8List sealFile(
Uint8List plain, {
required String keyId,
required String assetId,
});
/// What [sealed] holds, for the asset row [assetId]; null where it
/// doesn't open here (its key isn't open, it was changed, or it belongs
/// to another row).
Uint8List? openFile(Uint8List sealed, {required String assetId});
}

View file

@ -0,0 +1,22 @@
import 'dart:typed_data';
import 'package:equatable/equatable.dart';
/// A file of the person's content (an image or a sound), on this device and
/// ready to show or play.
class const StoredFile({
/// Its content.
required final Uint8List bytes,
/// Its media type, e.g. 'image/png' or 'audio/mpeg'.
required final String mimeType,
/// The name it came with.
required final String fileName,
/// Where it is on this device, for players that read files.
required final String path,
}) with Equatable {
@override
List<Object?> get props => [bytes, mimeType, fileName, path];
}

View file

@ -0,0 +1,65 @@
import 'dart:async';
/// A value a repository reads again after every change, handed to everyone
/// following it (decided 2026-10-17): one starting to follow gets the value
/// last read at once, then every value read after it with the others. Only
/// while there is none, before the first read, after one failed or once
/// nobody followed it, does one starting to follow have it read; everyone
/// following gets what that read brings. Before, every screen opening had
/// everything read again and handed to every screen open.
///
/// While nobody follows it, nothing is kept, so a repository need not read
/// after a change then ([hasListener]).
class LatestValue<T>(
/// Has the value read and handed on ([add], [addError]).
final void Function() _read,
) {
late final _controller = StreamController<T>.broadcast(
onCancel: () => _last = null,
);
/// The value last read; null before the first read, after one failed and
/// while nobody follows it.
({T value})? _last;
/// The value last read, then every value read after it; a read that fails
/// arrives as an error.
Stream<T> get stream => Stream.multi((listener) {
final subscription = _controller.stream.listen(
listener.add,
onError: listener.addError,
);
listener.onCancel = subscription.cancel;
if (_last case (:final value)?) {
listener.add(value);
} else {
_read();
}
});
/// The value last read; null before the first read, after one failed and
/// while nobody follows it.
T? get value => _last?.value;
/// Whether anyone follows it: while nobody does, there is no need to read.
bool get hasListener => _controller.hasListener;
bool get isClosed => _controller.isClosed;
/// Hands [value], just read, to everyone following, and keeps it for
/// those starting to; with nobody following, it isn't kept, as changes
/// from now on may not be read.
void add(T value) {
_last = hasListener ? (value: value) : null;
_controller.add(value);
}
/// Hands a read that failed to everyone following; the next one starting
/// to follow has it read again.
void addError(Object error, StackTrace stackTrace) {
_last = null;
_controller.addError(error, stackTrace);
}
Future<void> close() => _controller.close();
}

View file

@ -0,0 +1,41 @@
import 'dart:async';
import 'dart:developer';
import 'package:halkyon_core/halkyon_core.dart' show CoalescingRunner;
/// [read]'s value now and after every event of [changes], for each listener
/// on its own: one read at a time, changes during a read making one more
/// after it rather than one each, so an older value never overtakes a newer
/// one. A failed read is logged under [logName] as reading [what] and
/// arrives as an error; the next change reads again.
Stream<T> watchReads<T>(
Stream<void> changes,
Future<T> Function() read, {
required String what,
required String logName,
}) => Stream.multi((listener) {
var cancelled = false;
final reads = CoalescingRunner(
() async {
if (cancelled) {
return;
}
final value = await read();
if (!cancelled) {
listener.add(value);
}
},
onError: (error, stackTrace) {
log('Reading $what failed', name: logName, error: error);
if (!cancelled) {
listener.addError(error, stackTrace);
}
},
);
final subscription = changes.listen((_) => unawaited(reads.run()));
listener.onCancel = () {
cancelled = true;
return subscription.cancel();
};
unawaited(reads.run());
});

View file

@ -0,0 +1,141 @@
import 'package:equatable/equatable.dart';
/// What kind of work a source is, which its form asks for and its citation
/// says (decided 2026-10-12).
enum SourceKind() {
/// A book, an article, a chapter: the default.
work,
/// A page on the web, [Source.container] the website's name.
website,
/// A YouTube video, its [Source.authors] the channel; played in the app
/// where it can be.
video,
}
/// A work cited: by a step of a learning path, or in a studyset's
/// bibliography. Every part is optional and plain text, as the person wrote
/// it; `formatCitation` puts them together in the style the device uses.
final class const Source({
/// What kind of work it is.
final SourceKind kind = SourceKind.work,
/// Who wrote it, one full name per line (or separated by `;`), as
/// "Jonathan Gregory Pevsner"; each style abbreviates and orders them
/// itself.
final String authors = '',
/// When it appeared, as "2020"; empty when unknown.
final String year = '',
/// Its title.
final String title = '',
/// What it is a part of: the journal, book or website it appeared in, with
/// pages where they matter, as "Nature 591, 12–15"; empty for a work of
/// its own, such as a book. The styles set a part's title apart from the
/// whole's by this.
final String container = '',
/// Who published it, as "Wiley-Blackwell".
final String publisher = '',
/// The book's ISBN, as written.
final String isbn = '',
/// Where to find it on the web.
final String url = '',
/// The citation as a file brought it, for what couldn't be split into the
/// parts above; shown as it is while those are empty.
final String raw = '',
}) with Equatable {
/// The source in [json], as [toJson] writes it.
///
/// Each part is text; a number reads as its text (a file written by hand
/// may give the year as one). A [FormatException] for anything else.
factory fromJson(Object? json) {
if (json is! Map<String, Object?>) {
throw const FormatException('A source is an object.');
}
String part(String key) => switch (json[key]) {
null => '',
final String text => text,
final num number => '$number',
_ => throw FormatException('A source with a malformed $key.'),
};
return Source(
// A kind this app doesn't know yet reads as a work: its parts still
// cite it.
kind:
SourceKind.values
.where((kind) => kind.name == json['kind'])
.firstOrNull ??
SourceKind.work,
authors: part('authors'),
year: part('year'),
title: part('title'),
container: part('container'),
publisher: part('publisher'),
isbn: part('isbn'),
url: part('url'),
raw: part('raw'),
);
}
/// Whether nothing of it is written.
bool get isEmpty =>
authors.isEmpty &&
year.isEmpty &&
title.isEmpty &&
container.isEmpty &&
publisher.isEmpty &&
isbn.isEmpty &&
url.isEmpty &&
raw.isEmpty;
/// This source without spaces around its parts, nor around each author.
Source trimmed() => Source(
kind: kind,
authors: authors
.split('\n')
.map((line) => line.trim())
.where((line) => line.isNotEmpty)
.join('\n'),
year: year.trim(),
title: title.trim(),
container: container.trim(),
publisher: publisher.trim(),
isbn: isbn.trim(),
url: url.trim(),
raw: raw.trim(),
);
/// This source as JSON, each part left out when empty, and its kind
/// when it isn't a work.
Map<String, Object?> toJson() => {
if (kind != SourceKind.work) 'kind': kind.name,
if (authors.isNotEmpty) 'authors': authors,
if (year.isNotEmpty) 'year': year,
if (title.isNotEmpty) 'title': title,
if (container.isNotEmpty) 'container': container,
if (publisher.isNotEmpty) 'publisher': publisher,
if (isbn.isNotEmpty) 'isbn': isbn,
if (url.isNotEmpty) 'url': url,
if (raw.isNotEmpty) 'raw': raw,
};
@override
List<Object?> get props => [
kind,
authors,
year,
title,
container,
publisher,
isbn,
url,
raw,
];
}

View file

@ -0,0 +1,42 @@
import 'dart:convert';
import 'dart:typed_data';
// The content payload of synced rows: UTF-8 JSON with a `schemaVersion`. A new
// content field raises the version instead of migrating a synced table, which
// would lock older app versions out of syncing (ADR 0002, rule 3).
/// The payload deleted content keeps: the sync engine keeps deleted rows until
/// their space is deleted, so the content is blanked first (ADR 0002, rule 2).
final redactedPayload = ByteData(0);
/// [json] as a payload in [schemaVersion].
ByteData encodePayload(int schemaVersion, Map<String, Object?> json) =>
ByteData.sublistView(
utf8.encode(jsonEncode({'schemaVersion': schemaVersion, ...json})),
);
/// The JSON in [payload], its `schemaVersion` included.
///
/// Throws a [FormatException] for anything else, including a schema newer
/// than [newestSchema]: content written by a newer app version.
Map<String, Object?> decodePayload(
ByteData payload, {
required int newestSchema,
}) {
final Object? json;
try {
json = jsonDecode(utf8.decode(Uint8List.sublistView(payload)));
} on FormatException {
throw const FormatException('Not a content payload.');
}
if (json case {'schemaVersion': final int version}) {
if (version > newestSchema) {
throw FormatException(
'Content in schema $version, but this app only knows schemas up to '
'$newestSchema.',
);
}
return json as Map<String, Object?>;
}
throw const FormatException('Not a content payload.');
}

View file

@ -0,0 +1,20 @@
/// A page of a PDF that content is tied to: a card made from it, a note
/// about it. The PDF is named by its row's id; pages count from 1.
typedef PdfPageRef = ({String pdfId, int page});
/// [ref] as content payloads store it: `{"pdf", "page"}`.
Map<String, Object?> pdfPageRefToJson(PdfPageRef ref) => {
'pdf': ref.pdfId,
'page': ref.page,
};
/// The page [json] names, as [pdfPageRefToJson] wrote it; null for null.
/// Throws a [FormatException] for anything else.
PdfPageRef? pdfPageRefFromJson(Object? json) => switch (json) {
null => null,
{'pdf': final String pdfId, 'page': final int page} when page > 0 => (
pdfId: pdfId,
page: page,
),
_ => throw const FormatException('A malformed page of a PDF.'),
};

View file

@ -0,0 +1,57 @@
import 'package:equatable/equatable.dart';
/// Where an item of a copy came from (ADR 0005, rule 4): the published
/// studyset ([publication], its public id), the item there (its card's,
/// note's, step's, path's, PDF's or studyset's id in the release), and the
/// release whose content the item last took ([version]). A later release
/// is taken from that one on, so what the learner changed since stays. An
/// item the author withdrew in [version] stays the learner's, [withdrawn].
final class const PublishedRef({
required final String publication,
required final String item,
required final int version,
final bool withdrawn = false,
}) with Equatable {
/// This origin as of release [version], whose content the item took.
PublishedRef taking(int version) =>
PublishedRef(publication: publication, item: item, version: version);
/// This origin with the item withdrawn in release [version].
PublishedRef withdrawnIn(int version) => PublishedRef(
publication: publication,
item: item,
version: version,
withdrawn: true,
);
@override
List<Object?> get props => [publication, item, version, withdrawn];
}
/// [ref] as content payloads store it: `{"publication", "item", "version"}`,
/// and `"withdrawn": true` for an item the author withdrew.
Map<String, Object?> publishedRefToJson(PublishedRef ref) => {
'publication': ref.publication,
'item': ref.item,
'version': ref.version,
if (ref.withdrawn) 'withdrawn': true,
};
/// The origin [json] names, as [publishedRefToJson] wrote it; null for null.
/// Throws a [FormatException] for anything else.
PublishedRef? publishedRefFromJson(Object? json) => switch (json) {
null => null,
{
'publication': final String publication,
'item': final String item,
'version': final int version,
}
when version > 0 =>
PublishedRef(
publication: publication,
item: item,
version: version,
withdrawn: json['withdrawn'] == true,
),
_ => throw const FormatException('A malformed published origin.'),
};

View file

@ -0,0 +1,161 @@
import 'package:equatable/equatable.dart';
/// Content whose fields merge separately when devices edited it while
/// offline (ADR 0003): a card's sides, a note's title and body.
abstract interface class MergeableContent<
F,
C extends MergeableContent<F, C>
>() {
/// The value of [field].
Object? operator [](F field);
/// This content with [field] set to [value], which must be of the field's
/// kind.
C withField(F field, Object? value);
}
/// One version of some content, never changed once written (ADR 0001,
/// rule 2): editing appends a revision whose [parents] are the versions it
/// replaces.
abstract interface class Revision<C>() {
/// A UUID v7, made on the device that wrote it; ids sort by creation.
String get id;
/// The revisions this one replaces: none for the first, several when it
/// resolves a conflict.
Set<String> get parents;
/// The content as of this revision.
C get content;
}
/// Content merged from its revisions by [mergeRevisionsOf].
final class const Merged<F, C>({
/// The current content. For a field in [conflicts], the newest version
/// shows until the person chooses.
required final C content,
/// The current heads: what an edit of the merged content replaces.
required final Set<String> heads,
/// The fields changed differently on different devices, with every
/// version, oldest first.
final Map<F, List<Object?>> conflicts = const {},
}) with Equatable {
@override
List<Object?> get props => [content, heads, conflicts];
}
/// Merges [revisions] of one piece of content field by field (decided
/// 2026-09-30, ADR 0003), or null without any.
///
/// The heads are the revisions no other revision replaces. One head is the
/// current version. Several heads, from edits on different devices while
/// offline, merge field by field against their newest common ancestor: a
/// field only one of them changed takes that change, a field they changed
/// differently is a conflict. Nothing is merged silently inside a field.
/// Revisions whose parents haven't arrived yet count as they are.
Merged<F, C>? mergeRevisionsOf<F, C extends MergeableContent<F, C>>(
Iterable<Revision<C>> revisions, {
required List<F> fields,
}) {
final byId = {for (final revision in revisions) revision.id: revision};
if (byId.isEmpty) {
return null;
}
final replaced = {for (final revision in byId.values) ...revision.parents};
// UUID v7 ids sort by creation (ADR 0001, rule 7): the newest head is last.
final heads = [
for (final revision in byId.values)
if (!replaced.contains(revision.id)) revision,
]..sort((a, b) => a.id.compareTo(b.id));
if (heads.length == 1) {
return Merged(content: heads.single.content, heads: {heads.single.id});
}
final base = _commonAncestor(heads, byId)?.content;
var content = heads.last.content;
final conflicts = <F, List<Object?>>{};
for (final field in fields) {
// What the heads changed this field to, oldest first, without repeats.
final changed = <Object?>[];
for (final head in heads) {
final version = head.content[field];
if (!_same(version, base?[field]) &&
!changed.any((each) => _same(each, version))) {
changed.add(version);
}
}
switch (changed) {
case []:
// Unchanged everywhere; the newest head holds it already.
break;
case [final only]:
content = content.withField(field, only);
default:
conflicts[field] = changed;
content = content.withField(field, changed.last);
}
}
return Merged(
content: content,
heads: {for (final head in heads) head.id},
conflicts: conflicts,
);
}
/// The newest revision all [heads] descend from, or null if they share none.
///
/// Of the common ancestors, only those no other common ancestor descends from
/// qualify; of those (possible after criss-cross merges), the newest.
Revision<C>? _commonAncestor<C>(
List<Revision<C>> heads,
Map<String, Revision<C>> byId,
) {
Set<String> lineage(String id) {
final seen = <String>{};
final pending = [id];
while (pending.isNotEmpty) {
final next = pending.removeLast();
if (byId.containsKey(next) && seen.add(next)) {
pending.addAll(byId[next]!.parents);
}
}
return seen;
}
final common = heads
.map((head) => lineage(head.id))
.reduce((a, b) => a.intersection(b));
final nearest = [
for (final candidate in common)
if (!common.any(
(other) => other != candidate && lineage(other).contains(candidate),
))
candidate,
]..sort();
return nearest.isEmpty ? null : byId[nearest.last];
}
/// Whether two values of a field are the same: lists by their elements.
bool _same(Object? a, Object? b) => switch ((a, b)) {
(final List<Object?> a, final List<Object?> b) =>
a.length == b.length &&
[for (var i = 0; i < a.length; i++) a[i] == b[i]].every((same) => same),
_ => a == b,
};
/// What taking an update into content kept as revisions came to: a
/// dictionary's correction into a card, a release into a copy's card, note
/// or step.
enum UpdateTaken() {
/// Nothing: the content can't take it.
none,
/// Taken whole.
taken,
/// Taken, but the person changed a side the update changed too: a
/// conflict to settle.
toSettle,
}

View file

@ -0,0 +1,42 @@
import 'dart:typed_data';
/// What kind of data key a row of `content_key` holds (ADR 0019).
enum ContentKeyKind() {
/// A private studyset's: everything in its tree.
studyset,
/// The person's own: their tags and settings.
personal,
/// No key to write with: a signed record that a studyset was made
/// readable (ADR 0019, the reading of 22 Oct).
readable,
}
/// A data key as its row keeps it: sealed to the person's account. Only its
/// sealed ID is trusted, which says what the key is for (`ContentKeyId`);
/// its kind, studyset and time are the instance's to change.
typedef ContentKeyRow = ({
String id,
String dataKeyId,
ContentKeyKind kind,
String? studysetId,
Uint8List sealedKey,
DateTime createdAt,
});
/// The person's data keys (ADR 0019), synced in their space.
abstract interface class ContentKeyGateway() {
/// Every key kept, of every kind; rows of a kind this app doesn't know are
/// left out.
Future<List<ContentKeyRow>> all();
/// Keeps a new key.
Future<void> insert({
required String dataKeyId,
required ContentKeyKind kind,
required String? studysetId,
required Uint8List sealedKey,
required DateTime createdAt,
});
}

View file

@ -0,0 +1,103 @@
import 'dart:convert';
import 'dart:math';
import 'package:clock/clock.dart';
import 'package:equatable/equatable.dart';
/// What a data key is for, as its ID says (ADR 0019, the reading of 22 Oct).
enum ContentKeyScope() {
/// A private studyset's key, for everything in its tree.
studyset,
/// The person's own key, for their tags and settings.
personal,
/// No key to write with, but a signed record that the studyset it names
/// was made readable then, which ends its earlier keys.
readable,
}
/// A data key's ID, which says what the key is for: its scope, the
/// studyset it names, and when it was made. The ID is sealed with the key
/// and signed by the account (halkyon_keys' `sealDataKey` opens a key only
/// under the ID it was sealed with), so the instance can relabel no key:
/// the `content_key` row's own columns are never trusted.
final class const ContentKeyId({
/// What the key is for.
required final ContentKeyScope scope,
/// The studyset a studyset's key or a readable record names.
required final String? studysetId,
/// When it was made, in milliseconds since the epoch (UTC), on the device
/// that made it: what orders a studyset's records.
required final int madeAt,
/// The ID as it is stored.
required final String value,
}) with Equatable {
/// A new ID for [scope], naming [studysetId] for a studyset's key or
/// readable record, made now.
///
/// Made later than [after] (milliseconds), the latest record known about
/// that studyset, whatever this device's clock says: a clock behind would
/// make a record that never counts (the short reading of 22 Oct).
factory next(ContentKeyScope scope, {String? studysetId, int? after}) {
final random = Random.secure();
final nonce = base64Url
.encode([for (var i = 0; i < 12; i++) random.nextInt(256)])
.replaceAll('=', '');
final now = clock.now().toUtc().millisecondsSinceEpoch;
final ms = after != null && after >= now ? after + 1 : now;
final value = switch (scope) {
ContentKeyScope.personal => 'p1.$ms.$nonce',
ContentKeyScope.studyset => 's1.${studysetId!}.$ms.$nonce',
ContentKeyScope.readable => 'r1.${studysetId!}.$ms.$nonce',
};
return ContentKeyId(
scope: scope,
studysetId: studysetId,
madeAt: ms,
value: value,
);
}
/// [value] read as an ID; null for one of another form (a key made
/// before IDs said what they are for, or one this app doesn't know),
/// which never counts as a fact about privacy.
static ContentKeyId? parse(String value) {
final parts = value.split('.');
switch (parts) {
case ['p1', final ms, final _]:
final madeAt = int.tryParse(ms);
return madeAt == null
? null
: ContentKeyId(
scope: ContentKeyScope.personal,
studysetId: null,
madeAt: madeAt,
value: value,
);
case [final kind, final studyset, final ms, final _]
when (kind == 's1' || kind == 'r1') && studyset.isNotEmpty:
final madeAt = int.tryParse(ms);
return madeAt == null
? null
: ContentKeyId(
scope: kind == 's1'
? ContentKeyScope.studyset
: ContentKeyScope.readable,
studysetId: studyset,
madeAt: madeAt,
value: value,
);
}
return null;
}
@override
List<Object?> get props => [scope, studysetId, madeAt, value];
@override
String toString() => value;
}

View file

@ -0,0 +1,251 @@
import 'dart:developer';
import 'package:halkyon_content/halkyon_content.dart';
import 'package:halkyon_core/halkyon_core.dart';
import 'package:halkyon_learn_core/core/privacy/data/content_key_gateway.dart';
import 'package:halkyon_learn_core/core/privacy/data/content_key_id.dart';
import 'package:halkyon_learn_core/core/privacy/data/privacy_ledger.dart';
/// The person's data keys on this device (ADR 0019): each private
/// studyset's and their personal key, sealed to their account and synced,
/// opened here with the account's keys. Without those keys on the device (an
/// account signed in without its password here, or one that has none yet,
/// D8) nothing opens and nothing new is made private.
///
/// What a key is for is its sealed ID's to say ([ContentKeyId]), never its
/// row's: so the keys that open are also the signed facts about which
/// studysets are private ([ledger] keeps the latest seen of each), and the
/// instance can neither relabel a key nor make one up (the reading of 22
/// Oct).
class ContentKeys(
final ContentKeyGateway _gateway,
/// Seals and opens with the keys; [ContentKeys] owns it.
final ContentCipher cipher,
/// The account's keys on this device; null where none are.
final Future<UnlockedAccountKeys?> Function() _accountKeys, {
/// Whether the register says the account has keys (a password); null
/// where it can't be asked. Without it, the keys kept are the clue.
final Future<bool?> Function()? registerHasKeys,
/// What this device has seen of the person's privacy; one in memory
/// unless given.
PrivacyLedger? seen,
}) {
/// What this device has seen of the person's privacy, kept in their
/// folder.
final PrivacyLedger ledger =
seen ?? PrivacyLedger(MemoryPrivacyLedgerStore());
var _unlocked = false;
var _rows = const <ContentKeyRow>[];
/// The rows whose key wouldn't open, by row: a forged row never shadows
/// the real key of the same ID, and keys not open yet are tried again.
final _refusedRows = <String>{};
/// The personal keys open here, by their IDs.
final _personal = <ContentKeyId>[];
late final _refreshing = CoalescingRunner(
_refresh,
onError: (error, st) =>
log('Opening data keys failed', name: 'Privacy', error: error),
);
/// How many keys were opened here so far: rows that didn't open may with
/// more.
int opened = 0;
/// Whether this device holds the account's keys, so new content can be
/// made private; known once [refresh] ran.
bool get canEncrypt => _unlocked;
/// Whether the person has keys at all. A device without the account's
/// keys on such an account writes nothing that would be private (the
/// reading of 22 Oct).
///
/// Any sign is enough, and none is taken back (the final reading of 22
/// Oct): the keys open here, the register saying so (once it said yes),
/// key rows kept, records or sealed tags and settings this device saw. The
/// register's answer comes through the instance unsigned, so its "no"
/// never outweighs the rest, and it is asked again until it says yes: a
/// password set on another device later counts here too. Rows the instance
/// plants on an account without keys only make this device refuse to
/// write, never write readable.
bool get accountHasKeys =>
_unlocked ||
ledger.registerHasKeys == true ||
_rows.isNotEmpty ||
ledger.keysSeen ||
ledger.studysetsWithFacts.isNotEmpty ||
ledger.personalSealed;
/// Opens the keys kept that aren't open yet: as the person's data opens,
/// and once a sync may have brought more.
Future<void> refresh() => _refreshing.run();
Future<void> _refresh() async {
if (!_unlocked) {
final account = await _accountKeys();
if (account != null) {
await cipher.unlock(account);
_unlocked = true;
}
}
// Asked only while nothing else says the account has keys: its yes
// would change nothing then, and every read refreshes, so reads waited
// on the instance, minutes on a poor connection (10 Nov 2026).
if (!accountHasKeys && registerHasKeys != null) {
try {
// Kept only once it says yes; a no is asked again next time.
if (await registerHasKeys!() == true) {
ledger.registerHasKeys = true;
}
} on Object catch (error) {
log(
'Asking whether the account has keys failed',
name: 'Privacy',
error: error.runtimeType,
);
}
}
_rows = await _gateway.all();
// Remembered, so withholding them later changes nothing here.
if (_rows.isNotEmpty) {
ledger.keysSeen = true;
}
if (!_unlocked) {
return;
}
for (final row in _rows) {
if (_refusedRows.contains(row.id)) {
continue;
}
final id = ContentKeyId.parse(row.dataKeyId);
if (!cipher.has(row.dataKeyId)) {
if (!cipher.openKey(row.dataKeyId, row.sealedKey)) {
_refusedRows.add(row.id);
continue;
}
opened++;
}
if (id != null) {
_learn(id);
}
}
// The signed records are back: a damaged ledger is whole again.
ledger.damaged = false;
}
/// Keeps what the open key [id] says: a studyset made private or
/// readable, or the person's key.
void _learn(ContentKeyId id) {
switch (id.scope) {
case ContentKeyScope.studyset:
ledger.learnFact(id.studysetId!, (at: id.madeAt, keyId: id.value));
case ContentKeyScope.readable:
ledger.learnFact(id.studysetId!, (at: id.madeAt, keyId: null));
case ContentKeyScope.personal:
if (!_personal.contains(id)) {
_personal.add(id);
}
}
}
/// Whether the key [keyId] is open here.
bool canOpen(String keyId) => cipher.has(keyId);
/// A new key for the private studyset [studysetId], kept and synced, and
/// the fact that it is private from now on; its ID. Throws a
/// [StateError] where this device can't encrypt.
Future<String> newStudysetKey(String studysetId) => _newKey(
ContentKeyId.next(
ContentKeyScope.studyset,
studysetId: studysetId,
after: ledger.factOf(studysetId)?.at,
),
);
/// Keeps and syncs the signed record that [studysetId] is readable from
/// now on, which ends its earlier keys. Throws a [StateError] where this
/// device can't encrypt.
Future<void> recordReadable(String studysetId) async {
await _newKey(
ContentKeyId.next(
ContentKeyScope.readable,
studysetId: studysetId,
after: ledger.factOf(studysetId)?.at,
),
);
}
/// The person's key for their tags and settings, made the first time;
/// null where this device can't encrypt. Two devices making one at once
/// each keep theirs, every device opening both; the oldest is written
/// with, by when its sealed ID says it was made.
Future<String?> personalKey() async {
if (!_unlocked) {
return null;
}
if (_personal.isEmpty) {
return await _newKey(ContentKeyId.next(ContentKeyScope.personal));
}
final oldest = [..._personal]
..sort(
(a, b) => a.madeAt != b.madeAt
? a.madeAt.compareTo(b.madeAt)
: a.value.compareTo(b.value),
);
return oldest.first.value;
}
/// Whether a personal key is open here, or this device saw one: from
/// then on, a readable tag or settings row is no longer trusted.
bool get hasPersonalKey => _personal.isNotEmpty || ledger.personalSealed;
Future<String> _newKey(ContentKeyId id) async {
if (!_unlocked) {
throw StateError('The account keys are not on this device');
}
final createdAt = DateTime.fromMillisecondsSinceEpoch(
id.madeAt,
isUtc: true,
);
final sealedKey = cipher.newKey(id.value);
opened++;
final kind = switch (id.scope) {
ContentKeyScope.studyset => ContentKeyKind.studyset,
ContentKeyScope.personal => ContentKeyKind.personal,
ContentKeyScope.readable => ContentKeyKind.readable,
};
await _gateway.insert(
dataKeyId: id.value,
kind: kind,
studysetId: id.studysetId,
sealedKey: sealedKey,
createdAt: createdAt,
);
_rows = [
..._rows,
(
id: id.value,
dataKeyId: id.value,
kind: kind,
studysetId: id.studysetId,
sealedKey: sealedKey,
createdAt: createdAt,
),
];
_learn(id);
return id.value;
}
/// Wipes the keys kept open here, and writes what the device saw.
Future<void> dispose() async {
cipher.dispose();
await ledger.flush();
}
}

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more