Extract the wayBetter framework core from wayBetter for X
Site-agnostic parts of the X app, behind a small site adapter: - crates/waybetter-host: webview-label security policy and tab rect clamp, account profiles with native-owned accounts (AccountRules), plugin store with bundled-plugin upgrades (PluginHost), signed data-only hotfix channel, update scheduling and crash handshake, tab payloads/link routing/tab-chrome validation, and (feature "tauri") webview helpers and the Windows system menu. - packages/runtime: DOM hub, request hub, plugin API core, OKLab theme color model, split-view rail hiding, link routing and account reporting, each configured by a SiteAdapter. - packages/shell: address bar, pane, link-drop, profile, palette and update-chip models, and window controls with the Tauri API injected. Tests moved/adapted from the app: 45 Rust (headless), 40 TypeScript.
This commit is contained in:
commit
43a9e2e1a7
48 changed files with 9768 additions and 0 deletions
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
* text=auto eol=lf
|
||||||
|
# Signed test fixtures must keep their exact bytes.
|
||||||
|
crates/waybetter-host/tests/fixtures/** -text
|
||||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
node_modules/
|
||||||
|
target/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
674
LICENSE
Normal file
674
LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
186
README.md
Normal file
186
README.md
Normal file
|
|
@ -0,0 +1,186 @@
|
||||||
|
# waybetter
|
||||||
|
|
||||||
|
The framework behind the wayBetter apps: desktop apps that extend one website in place, the way
|
||||||
|
BetterDiscord extends Discord. The first app is **wayBetter for X**; wayBetter for WhatsApp and
|
||||||
|
wayBetter for Kick are meant to be built on the same core.
|
||||||
|
|
||||||
|
A wayBetter app is one native window (Tauri 2, multiwebview) with:
|
||||||
|
|
||||||
|
- a trusted local **shell** webview: tab strip, split panes (dockview), address bar, titlebar and
|
||||||
|
window controls, command palette, account switcher, the app's own settings;
|
||||||
|
- one native child webview per browser **tab**, positioned over the pane rectangles the shell
|
||||||
|
reports (`tabs_sync`), each in an account **profile** with its own WebView data directory;
|
||||||
|
- a **page runtime** injected into tabs that are on the app's site: shared DOM/request hubs,
|
||||||
|
plugins, themes, split-view rail hiding, link routing and account reporting.
|
||||||
|
|
||||||
|
This repository holds the parts that do not depend on which site the app extends. An app is mostly
|
||||||
|
a **site adapter** plus its own features.
|
||||||
|
|
||||||
|
License: GPL-3.0-or-later. Private until the owner decides otherwise.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads
|
||||||
|
src/site.rs SiteSpec + AccountRules (the native half of the adapter)
|
||||||
|
src/policy.rs webview labels, origin checks, tab rect clamp
|
||||||
|
src/profiles.rs profiles, per-profile data dirs, native-owned accounts
|
||||||
|
src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades
|
||||||
|
src/hotfix.rs signed data-only hotfix channel (minisign)
|
||||||
|
src/update.rs silent-update scheduling and crash handshake
|
||||||
|
src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation
|
||||||
|
src/host.rs (feature "tauri") webview helpers, shell events, system menu
|
||||||
|
packages/runtime/src/ page runtime core (TypeScript, no dependencies)
|
||||||
|
site.ts SiteAdapter (the page half of the adapter) + configureRuntime
|
||||||
|
domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page
|
||||||
|
pluginApi.ts core of window.<Runtime>.api for plugins
|
||||||
|
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
|
||||||
|
paneNav.ts split view: park the site's navigation rail in redundant panes
|
||||||
|
linkRouting.ts divert in-page clicks to a pane/tab/browser per setting
|
||||||
|
accountReport.ts report the signed-in account of this tab's profile
|
||||||
|
packages/shell/src/ shell core (TypeScript, no dependencies)
|
||||||
|
addressModel.ts address bar chips (site pages named by the adapter)
|
||||||
|
paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync
|
||||||
|
linkDrop.ts dropping links into the dock
|
||||||
|
profileModel.ts profiles and account labels
|
||||||
|
palette.ts command palette scoring/ranking
|
||||||
|
updateModel.ts titlebar update chip
|
||||||
|
windowControls.ts caption buttons, resize grips, system menu (Tauri API injected)
|
||||||
|
chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs)
|
||||||
|
```
|
||||||
|
|
||||||
|
Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime
|
||||||
|
dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type
|
||||||
|
stripping. Anything that needs the Tauri API (window controls) takes it as a parameter.
|
||||||
|
|
||||||
|
## The site adapter
|
||||||
|
|
||||||
|
A site adapter is three small, explicit things.
|
||||||
|
|
||||||
|
### 1. Native: `SiteSpec` (Rust)
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use waybetter_host::site::{AccountRules, SiteSpec};
|
||||||
|
|
||||||
|
fn kick_handle(value: &str) -> bool {
|
||||||
|
(3..=25).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static SITE: SiteSpec = SiteSpec {
|
||||||
|
product: "wayBetter for Kick",
|
||||||
|
hosts: &["kick.com"], // exact https origin(s) of site tabs
|
||||||
|
runtime_global: "WayBetterKick", // window.<global> of the page runtime
|
||||||
|
accounts: AccountRules {
|
||||||
|
valid_handle: kick_handle,
|
||||||
|
avatar_prefixes: &["https://files.kick.com/"],
|
||||||
|
max_name_chars: 50,
|
||||||
|
max_avatar_len: 512,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
`SiteSpec::is_origin` is the only definition of "a site tab". Site-only commands check
|
||||||
|
`policy::require_site_tab(&SITE, label, url)` (or `host::site_tab_only`), which also requires a
|
||||||
|
`tab-*` label.
|
||||||
|
|
||||||
|
### 2. Page: `SiteAdapter` (TypeScript)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts';
|
||||||
|
|
||||||
|
export const KICK: SiteAdapter = {
|
||||||
|
product: 'wayBetter for Kick',
|
||||||
|
hosts: ['kick.com'],
|
||||||
|
runtimeGlobal: 'WayBetterKick',
|
||||||
|
heavyPath: null, // pages where offOnHeavy DOM features pause
|
||||||
|
apiMarks: ['/api/'], // request URLs the net hub stages may see
|
||||||
|
xhrMarks: [],
|
||||||
|
plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:',
|
||||||
|
styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18',
|
||||||
|
itemSelector: '[data-chat-entry]', chordKeys: [] },
|
||||||
|
rail: { prefix: 'wbk', rail: '#sidebar-wrapper', anchor: 'a[href="/"]', main: 'main',
|
||||||
|
modalOpen: '[role="dialog"]', menuOpen: '[role="menu"]',
|
||||||
|
paint: { width: 64, background: '#0b0e0f', line: 'rgba(255,255,255,.12)', accent: '#53fc18', rtl: false } },
|
||||||
|
account: { read: readKickAccount, signedOut: root => !!root.querySelector('[data-test="login"]') },
|
||||||
|
links: { configKey: 'site', clickedUrl: kickClickedUrl },
|
||||||
|
themeSources: { dark: KICK_DARK_AXIS },
|
||||||
|
};
|
||||||
|
configureRuntime(KICK);
|
||||||
|
```
|
||||||
|
|
||||||
|
Each runtime module takes only its piece (`installPaneNav(window, KICK.rail!)`,
|
||||||
|
`installLinkRouting(window, KICK.links!)`, `installAccountReport(window, KICK.account!, invoke)`,
|
||||||
|
`createCorePluginApi(window, KICK.plugins)`), so a site without a rail simply does not install it.
|
||||||
|
|
||||||
|
### 3. Capabilities (Tauri JSON, keyed by webview label)
|
||||||
|
|
||||||
|
The security model is the same for every app and must stay keyed by webview label:
|
||||||
|
|
||||||
|
| webview | may call |
|
||||||
|
| --- | --- |
|
||||||
|
| `shell` (local assets only) | app, settings, vault, tab management (`tabs_sync`, `tab_navigate`, `tab_action`, ...) |
|
||||||
|
| `tab-*` (any site) | only tab chrome about itself: `tab_report`, `tab_shortcut`, `tab_link_drag` |
|
||||||
|
| `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands |
|
||||||
|
| other local webviews (`popover-*`, ...) | their own narrow capability |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "identifier": "tab-chrome", "webviews": ["tab-*"], "local": false,
|
||||||
|
"remote": { "urls": ["https://*/*", "http://*/*"] },
|
||||||
|
"permissions": ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"] }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "identifier": "site-tab", "webviews": ["tab-*"], "local": false,
|
||||||
|
"remote": { "urls": ["https://kick.com/*"] },
|
||||||
|
"permissions": ["allow-open-panel"] }
|
||||||
|
```
|
||||||
|
|
||||||
|
Native code re-checks every one of these (the capability file alone is not the boundary): the
|
||||||
|
caller's label, the webview's own URL (never the page's claim), payload bounds. A tab can speak only
|
||||||
|
about itself; the account it reports is recorded only for its own profile, only while it is on the
|
||||||
|
site, and a shell save can never change it (`ProfileSettings::keep_accounts_from`).
|
||||||
|
|
||||||
|
## What the host gives an app
|
||||||
|
|
||||||
|
- `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never
|
||||||
|
cover the titlebar or, while restored, the resize band).
|
||||||
|
- `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be
|
||||||
|
removed), `data_dir` (ids cannot escape `profiles/`), `orphan_dirs`, `store_identifier` (macOS).
|
||||||
|
- `plugins`: `PluginStore` with a `PluginHost` (runtime global, origin, product, bundled plugins).
|
||||||
|
Bundled plugins are written disabled and upgraded only while untouched.
|
||||||
|
- `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data.
|
||||||
|
- `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots).
|
||||||
|
- `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it.
|
||||||
|
- `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`,
|
||||||
|
`eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`,
|
||||||
|
`read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`,
|
||||||
|
`system_menu`.
|
||||||
|
|
||||||
|
The app keeps its own `#[tauri::command]` wrappers, so IPC command names, the build-time command
|
||||||
|
manifest and the capability files stay in the app.
|
||||||
|
|
||||||
|
## Consuming it
|
||||||
|
|
||||||
|
wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source:
|
||||||
|
|
||||||
|
- Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`,
|
||||||
|
with `features = ["tauri"]` enabled by the app's desktop feature.
|
||||||
|
- TypeScript: relative imports of `waybetter/packages/*/src/*.ts` from a few adapter modules. The
|
||||||
|
packages are not Bun workspace members of the app on purpose: the app's server CI clones without
|
||||||
|
submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's
|
||||||
|
type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's
|
||||||
|
isolated linker on Windows.
|
||||||
|
|
||||||
|
## Scripts (no CI)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun install # typescript + @types/node for the checks
|
||||||
|
bun run typecheck # tsc over both packages and their tests
|
||||||
|
bun run test # node --test (runtime + shell) and cargo test (headless host)
|
||||||
|
bun run test:ts
|
||||||
|
bun run test:rust
|
||||||
|
bun run check:tauri # cargo check with the tauri feature (slow: builds Tauri)
|
||||||
|
bun run build # typecheck + cargo build
|
||||||
|
```
|
||||||
|
|
||||||
|
Requires Bun 1.4.2+, Node 24+ and Rust 1.88+.
|
||||||
32
bun.lock
Normal file
32
bun.lock
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
{
|
||||||
|
"lockfileVersion": 2,
|
||||||
|
"configVersion": 1,
|
||||||
|
"workspaces": {
|
||||||
|
"": {
|
||||||
|
"name": "waybetter",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.0.0",
|
||||||
|
"typescript": "^5.9.0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"packages/runtime": {
|
||||||
|
"name": "@waybetter/runtime",
|
||||||
|
"version": "0.1.0",
|
||||||
|
},
|
||||||
|
"packages/shell": {
|
||||||
|
"name": "@waybetter/shell",
|
||||||
|
"version": "0.1.0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"packages": {
|
||||||
|
"@types/node": ["@types/node@24.19.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew=="],
|
||||||
|
|
||||||
|
"@waybetter/runtime": ["@waybetter/runtime@workspace:packages/runtime"],
|
||||||
|
|
||||||
|
"@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"],
|
||||||
|
|
||||||
|
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||||
|
|
||||||
|
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
|
||||||
|
}
|
||||||
|
}
|
||||||
4436
crates/waybetter-host/Cargo.lock
generated
Normal file
4436
crates/waybetter-host/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
33
crates/waybetter-host/Cargo.toml
Normal file
33
crates/waybetter-host/Cargo.toml
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
[package]
|
||||||
|
name = "waybetter-host"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "wayBetter native host: one window, a trusted shell webview and one child webview per site tab"
|
||||||
|
license = "GPL-3.0-or-later"
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.88"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "waybetter_host"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
# Tauri glue (webview helpers, window system menu). Off for headless tests.
|
||||||
|
tauri = ["dep:tauri", "dep:windows"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
url = "2"
|
||||||
|
sha2 = "0.10"
|
||||||
|
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||||
|
minisign-verify = "0.2"
|
||||||
|
base64 = "0.22"
|
||||||
|
tauri = { version = "2", features = ["unstable"], optional = true }
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"], optional = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
185
crates/waybetter-host/src/host.rs
Normal file
185
crates/waybetter-host/src/host.rs
Normal file
|
|
@ -0,0 +1,185 @@
|
||||||
|
//! Tauri glue that does not depend on the app's own state: caller checks, shell events, tab
|
||||||
|
//! webview lookups and actions, app-data JSON files, profile data folders and the Windows system
|
||||||
|
//! menu. The app keeps its `#[tauri::command]` wrappers (so IPC names and capabilities stay the
|
||||||
|
//! app's) and calls these.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
policy,
|
||||||
|
profiles::{self, ProfileSettings},
|
||||||
|
site::SiteSpec,
|
||||||
|
tabs::{self, TabAction, TabState},
|
||||||
|
};
|
||||||
|
use serde::Serialize;
|
||||||
|
use tauri::{AppHandle, Emitter, EventTarget, Manager, Runtime, Webview};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// Shell-only commands: the trusted local `shell` webview (debug builds also accept the dev server).
|
||||||
|
pub fn shell_only<R: Runtime>(webview: &Webview<R>) -> Result<(), String> {
|
||||||
|
let url = webview.url().map_err(|_| "FORBIDDEN: cannot verify workspace origin")?;
|
||||||
|
policy::require_local(webview.label(), &url, cfg!(debug_assertions))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tab-chrome commands: any tab webview, speaking only about itself. Returns its tab id.
|
||||||
|
pub fn tab_only<R: Runtime>(webview: &Webview<R>) -> Result<String, String> {
|
||||||
|
policy::tab_id(webview.label())
|
||||||
|
.map(str::to_owned)
|
||||||
|
.ok_or_else(|| "FORBIDDEN: tab webview required".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Site-only commands: a tab webview that is exactly on the site right now. Returns its URL (the
|
||||||
|
/// webview's own, never the page's claim).
|
||||||
|
pub fn site_tab_only<R: Runtime>(site: &SiteSpec, webview: &Webview<R>) -> Result<Url, String> {
|
||||||
|
let url = webview.url().map_err(|_| "FORBIDDEN: cannot verify origin")?;
|
||||||
|
policy::require_site_tab(site, webview.label(), &url)?;
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn emit_shell<R: Runtime, S: Serialize + Clone>(app: &AppHandle<R>, event: &str, payload: S) {
|
||||||
|
let _ = app.emit_to(EventTarget::webview(policy::SHELL_LABEL), event, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn emit_tab_state<R: Runtime>(app: &AppHandle<R>, state: TabState) {
|
||||||
|
emit_shell(app, tabs::EVENT_TAB_STATE, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tab_webview<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<Webview<R>> {
|
||||||
|
app.get_webview(&policy::tab_label(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates `script` in every tab that is on the site right now.
|
||||||
|
pub fn eval_in_site_tabs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, script: &str) {
|
||||||
|
for (label, webview) in app.webviews() {
|
||||||
|
if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) {
|
||||||
|
let _ = webview.eval(script);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data_file<R: Runtime>(app: &AppHandle<R>, name: &str) -> Option<std::path::PathBuf> {
|
||||||
|
app.path().app_data_dir().ok().map(|dir| dir.join(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_json<R: Runtime, T: serde::de::DeserializeOwned>(app: &AppHandle<R>, name: &str) -> Option<T> {
|
||||||
|
serde_json::from_str(&std::fs::read_to_string(data_file(app, name)?).ok()?).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_json<R: Runtime, T: Serialize>(app: &AppHandle<R>, name: &str, value: &T) -> Result<(), String> {
|
||||||
|
let path = data_file(app, name).ok_or("STORAGE: no application data directory")?;
|
||||||
|
let json = serde_json::to_string_pretty(value).map_err(|_| "STORAGE: serialization failed")?;
|
||||||
|
std::fs::write(path, json).map_err(|error| format!("STORAGE: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn navigate_tab<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str) -> Result<(), String> {
|
||||||
|
let url = tabs::parse_web_url(url)?;
|
||||||
|
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
|
||||||
|
tab.navigate(url).map_err(|error| format!("TAB: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tab_action<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str) -> Result<(), String> {
|
||||||
|
let action = TabAction::parse(action)?;
|
||||||
|
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
|
||||||
|
let result = match action {
|
||||||
|
TabAction::Back => tab.eval("history.back()"),
|
||||||
|
TabAction::Forward => tab.eval("history.forward()"),
|
||||||
|
TabAction::Reload => tab.reload(),
|
||||||
|
TabAction::Stop => tab.eval("window.stop()"),
|
||||||
|
TabAction::Focus => tab.set_focus(),
|
||||||
|
};
|
||||||
|
result.map_err(|error| format!("TAB: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`).
|
||||||
|
pub fn forward_shortcut<R: Runtime>(app: &AppHandle<R>, id: String, shortcut: String) -> Result<(), String> {
|
||||||
|
if !tabs::valid_shortcut(&shortcut) {
|
||||||
|
return Err("VALIDATION: unknown shortcut".into());
|
||||||
|
}
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct Shortcut {
|
||||||
|
id: String,
|
||||||
|
shortcut: String,
|
||||||
|
}
|
||||||
|
emit_shell(app, tabs::EVENT_TAB_SHORTCUT, Shortcut { id, shortcut });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link drag started/entered/ended in tab `id` (`link-drag`); the link opens only as a new tab.
|
||||||
|
pub fn forward_link_drag<R: Runtime>(app: &AppHandle<R>, id: String, phase: String, url: Option<String>) -> Result<(), String> {
|
||||||
|
let url = tabs::link_drag(&phase, url)?;
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct LinkDrag {
|
||||||
|
id: String,
|
||||||
|
phase: String,
|
||||||
|
url: Option<String>,
|
||||||
|
}
|
||||||
|
emit_shell(app, tabs::EVENT_LINK_DRAG, LinkDrag { id, phase, url });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the WebView data folders (the logins) of removed profiles.
|
||||||
|
pub fn remove_profile_dirs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, removed: &[String]) {
|
||||||
|
let Ok(local) = app.path().app_local_data_dir() else { return };
|
||||||
|
for id in removed {
|
||||||
|
if let Some(dir) = profiles::data_dir(&local, id) {
|
||||||
|
if let Err(error) = std::fs::remove_dir_all(&dir) {
|
||||||
|
if error.kind() != std::io::ErrorKind::NotFound {
|
||||||
|
eprintln!("{}: could not remove profile data {}: {error}", site.product, dir.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes WebView data folders of profiles that no longer exist (see [`profiles::orphan_dirs`]).
|
||||||
|
pub fn prune_profile_dirs<R: Runtime>(app: &AppHandle<R>, settings: &ProfileSettings) {
|
||||||
|
let Ok(local) = app.path().app_local_data_dir() else { return };
|
||||||
|
for dir in profiles::orphan_dirs(&local, settings) {
|
||||||
|
let _ = std::fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves app-data and app-local data (WebView profile, i.e. the site login) from a previous bundle
|
||||||
|
/// identifier. Never overwrites an existing new folder.
|
||||||
|
pub fn migrate_identifier<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, legacy_identifier: &str) {
|
||||||
|
let dirs = [app.path().app_data_dir(), app.path().app_local_data_dir()];
|
||||||
|
for new_dir in dirs.into_iter().flatten() {
|
||||||
|
let Some(parent) = new_dir.parent() else { continue };
|
||||||
|
let old_dir = parent.join(legacy_identifier);
|
||||||
|
if old_dir.is_dir() && !new_dir.exists() {
|
||||||
|
if let Err(error) = std::fs::rename(&old_dir, &new_dir) {
|
||||||
|
eprintln!("{}: could not migrate {}: {error}", site.product, old_dir.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows the native window system menu (Restore, Move, Size, Minimize, Maximize, Close) at a
|
||||||
|
/// screen position, for a right-click on the custom titlebar. No-op outside Windows.
|
||||||
|
pub fn system_menu<R: Runtime>(webview: &Webview<R>, x: f64, y: f64) -> Result<(), String> {
|
||||||
|
if !x.is_finite() || !y.is_finite() {
|
||||||
|
return Err("VALIDATION: non-finite position".into());
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use windows::Win32::Foundation::{LPARAM, WPARAM};
|
||||||
|
use windows::Win32::UI::WindowsAndMessaging::{
|
||||||
|
GetSystemMenu, PostMessageW, SetForegroundWindow, TrackPopupMenu, TPM_RETURNCMD, TPM_RIGHTBUTTON,
|
||||||
|
WM_SYSCOMMAND,
|
||||||
|
};
|
||||||
|
let hwnd = webview.window().hwnd().map_err(|error| format!("WINDOW: {error}"))?;
|
||||||
|
// SAFETY: plain Win32 calls on our own top-level window handle.
|
||||||
|
unsafe {
|
||||||
|
let menu = GetSystemMenu(hwnd, false);
|
||||||
|
if menu.is_invalid() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let _ = SetForegroundWindow(hwnd);
|
||||||
|
let command = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, x as i32, y as i32, None, hwnd, None);
|
||||||
|
if command.0 != 0 {
|
||||||
|
let _ = PostMessageW(Some(hwnd), WM_SYSCOMMAND, WPARAM(command.0 as usize), LPARAM(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
let _ = webview;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
167
crates/waybetter-host/src/hotfix.rs
Normal file
167
crates/waybetter-host/src/hotfix.rs
Normal file
|
|
@ -0,0 +1,167 @@
|
||||||
|
//! Signed, data-only hotfix channel: selector and flag overrides for site markup changes.
|
||||||
|
//!
|
||||||
|
//! The body is JSON (`{version, expires, minNative, selectors{}, flags{}}`) with a detached
|
||||||
|
//! minisign signature from a separate hotfix key. It is verified, schema-checked, required to be
|
||||||
|
//! newer than the copy already held (monotonic) and unexpired, and then handed to site tabs as
|
||||||
|
//! frozen data (`window.<global>`). It is never evaluated as code: a leaked hotfix key can at most
|
||||||
|
//! break selectors. The app owns the public key and channel URL.
|
||||||
|
|
||||||
|
use base64::Engine;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use minisign_verify::{PublicKey, Signature};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
pub const MAX_BODY_BYTES: usize = 64 * 1024;
|
||||||
|
pub const MAX_SIG_BYTES: usize = 4 * 1024;
|
||||||
|
const MAX_SELECTORS: usize = 256;
|
||||||
|
const MAX_FLAGS: usize = 128;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct Hotfix {
|
||||||
|
/// Monotonic; a client never accepts a version at or below the one it holds.
|
||||||
|
pub version: u64,
|
||||||
|
/// RFC 3339 timestamp after which the hotfix is ignored (blocks stale replay).
|
||||||
|
pub expires: String,
|
||||||
|
/// Lowest native app version this data is written for.
|
||||||
|
pub min_native: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub selectors: BTreeMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub flags: BTreeMap<String, serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts either the raw minisign text or the base64 wrapping that the Tauri signer produces.
|
||||||
|
pub fn minisign_text(value: &str) -> Result<String, String> {
|
||||||
|
let trimmed = value.trim();
|
||||||
|
if trimmed.starts_with("untrusted comment:") {
|
||||||
|
return Ok(trimmed.to_owned());
|
||||||
|
}
|
||||||
|
let bytes = base64::engine::general_purpose::STANDARD
|
||||||
|
.decode(trimmed)
|
||||||
|
.map_err(|_| "HOTFIX: key or signature is not minisign text or base64")?;
|
||||||
|
String::from_utf8(bytes).map_err(|_| "HOTFIX: key or signature is not UTF-8".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies `body` against a detached minisign signature.
|
||||||
|
pub fn verify(pubkey: &str, body: &[u8], signature: &str) -> Result<(), String> {
|
||||||
|
if signature.len() > MAX_SIG_BYTES {
|
||||||
|
return Err("HOTFIX: signature too large".into());
|
||||||
|
}
|
||||||
|
let key_text = minisign_text(pubkey)?;
|
||||||
|
let key_line = key_text
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.find(|line| !line.is_empty() && !line.starts_with("untrusted comment:"))
|
||||||
|
.ok_or("HOTFIX: empty public key")?;
|
||||||
|
let key = PublicKey::from_base64(key_line).map_err(|_| "HOTFIX: invalid public key")?;
|
||||||
|
let signature = Signature::decode(&minisign_text(signature)?).map_err(|_| "HOTFIX: invalid signature")?;
|
||||||
|
key.verify(body, &signature, false)
|
||||||
|
.map_err(|_| "HOTFIX: signature verification failed".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn semver_triplet(value: &str) -> Option<(u64, u64, u64, bool)> {
|
||||||
|
let (core, pre) = match value.split_once('-') {
|
||||||
|
Some((core, pre)) => (core, !pre.is_empty()),
|
||||||
|
None => (value, false),
|
||||||
|
};
|
||||||
|
let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
|
||||||
|
let triplet = (parts.next()??, parts.next()??, parts.next()??, pre);
|
||||||
|
parts.next().is_none().then_some(triplet)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `a >= b` for semantic versions (a prerelease sorts before its release).
|
||||||
|
pub fn version_at_least(a: &str, b: &str) -> Option<bool> {
|
||||||
|
let (a, b) = (semver_triplet(a)?, semver_triplet(b)?);
|
||||||
|
Some(match (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)) {
|
||||||
|
std::cmp::Ordering::Greater => true,
|
||||||
|
std::cmp::Ordering::Less => false,
|
||||||
|
std::cmp::Ordering::Equal => !a.3 || b.3,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_key(key: &str) -> bool {
|
||||||
|
!key.is_empty() && key.len() <= 64 && key.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schema, expiry and native-version checks on an already verified body.
|
||||||
|
pub fn validate(body: &[u8], now: DateTime<Utc>, native_version: &str) -> Result<Hotfix, String> {
|
||||||
|
if body.len() > MAX_BODY_BYTES {
|
||||||
|
return Err("HOTFIX: body too large".into());
|
||||||
|
}
|
||||||
|
let hotfix: Hotfix = serde_json::from_slice(body).map_err(|error| format!("HOTFIX: schema: {error}"))?;
|
||||||
|
let expires = DateTime::parse_from_rfc3339(&hotfix.expires).map_err(|_| "HOTFIX: invalid expires")?;
|
||||||
|
if expires.with_timezone(&Utc) <= now {
|
||||||
|
return Err("HOTFIX: expired".into());
|
||||||
|
}
|
||||||
|
match version_at_least(native_version, &hotfix.min_native) {
|
||||||
|
Some(true) => {}
|
||||||
|
Some(false) => return Err("HOTFIX: requires a newer app".into()),
|
||||||
|
None => return Err("HOTFIX: invalid minNative".into()),
|
||||||
|
}
|
||||||
|
if hotfix.selectors.len() > MAX_SELECTORS
|
||||||
|
|| hotfix.selectors.iter().any(|(k, v)| !valid_key(k) || v.is_empty() || v.len() > 1024)
|
||||||
|
{
|
||||||
|
return Err("HOTFIX: invalid selectors".into());
|
||||||
|
}
|
||||||
|
let scalar = |v: &serde_json::Value| match v {
|
||||||
|
serde_json::Value::Bool(_) | serde_json::Value::Number(_) => true,
|
||||||
|
serde_json::Value::String(s) => s.len() <= 256,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if hotfix.flags.len() > MAX_FLAGS || hotfix.flags.iter().any(|(k, v)| !valid_key(k) || !scalar(v)) {
|
||||||
|
return Err("HOTFIX: invalid flags".into());
|
||||||
|
}
|
||||||
|
Ok(hotfix)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub enum Outcome {
|
||||||
|
/// A newer valid hotfix to store and deliver.
|
||||||
|
Accepted(Hotfix),
|
||||||
|
/// Same version as the one already held; nothing to do.
|
||||||
|
Unchanged,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full client-side acceptance: signature first, then schema/expiry/minNative, then monotonicity.
|
||||||
|
pub fn accept(
|
||||||
|
pubkey: &str,
|
||||||
|
body: &[u8],
|
||||||
|
signature: &str,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
native_version: &str,
|
||||||
|
held_version: Option<u64>,
|
||||||
|
) -> Result<Outcome, String> {
|
||||||
|
verify(pubkey, body, signature)?;
|
||||||
|
let hotfix = validate(body, now, native_version)?;
|
||||||
|
match held_version {
|
||||||
|
Some(held) if hotfix.version == held => Ok(Outcome::Unchanged),
|
||||||
|
Some(held) if hotfix.version < held => Err("HOTFIX: older than the held version".into()),
|
||||||
|
_ => Ok(Outcome::Accepted(hotfix)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers the hotfix to a site page as data: parsed from a JSON string literal, frozen, stored
|
||||||
|
/// as `window.<global>` and announced with the `event` window event.
|
||||||
|
pub fn script(hotfix: &Hotfix, global: &str, event: &str) -> String {
|
||||||
|
let json = serde_json::to_string(hotfix).unwrap_or_else(|_| "null".into());
|
||||||
|
let literal = serde_json::to_string(&json).unwrap_or_else(|_| "\"null\"".into());
|
||||||
|
format!(
|
||||||
|
"(()=>{{const h=JSON.parse({literal});if(h){{Object.freeze(h.selectors);Object.freeze(h.flags);Object.freeze(h);}}window.{global}=h;try{{window.dispatchEvent(new CustomEvent('{event}'));}}catch(_){{}}}})();"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn semver_ordering() {
|
||||||
|
assert_eq!(version_at_least("0.2.0", "0.2.0"), Some(true));
|
||||||
|
assert_eq!(version_at_least("0.10.0", "0.9.9"), Some(true));
|
||||||
|
assert_eq!(version_at_least("0.2.0-beta.1", "0.2.0"), Some(false));
|
||||||
|
assert_eq!(version_at_least("0.2.0", "0.2.0-beta.1"), Some(true));
|
||||||
|
assert_eq!(version_at_least("0.2", "0.2.0"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
28
crates/waybetter-host/src/lib.rs
Normal file
28
crates/waybetter-host/src/lib.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
//! wayBetter native host.
|
||||||
|
//!
|
||||||
|
//! A wayBetter app is one native window with a trusted local **shell** webview (tab strip, address
|
||||||
|
//! bars, split panes, settings) and one native child webview per browser tab, positioned over the
|
||||||
|
//! pane rectangles the shell reports. One site (x.com, web.whatsapp.com, kick.com, ...) is the
|
||||||
|
//! app's *site*: its tabs get the app's page runtime and may call a small set of site-only commands.
|
||||||
|
//!
|
||||||
|
//! This crate holds the site-agnostic parts, all headless-testable:
|
||||||
|
//! - [`site`]: the site adapter ([`site::SiteSpec`], [`site::AccountRules`]).
|
||||||
|
//! - [`policy`]: webview labels, origin checks and the tab rectangle clamp (security boundary).
|
||||||
|
//! - [`profiles`]: account profiles, one WebView data directory each, with the account seen inside.
|
||||||
|
//! - [`plugins`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades.
|
||||||
|
//! - [`hotfix`]: the signed, data-only hotfix channel.
|
||||||
|
//! - [`update`]: silent-update scheduling and the crash handshake.
|
||||||
|
//! - [`tabs`]: tab layout/state payloads, link routing and tab-chrome validation.
|
||||||
|
//!
|
||||||
|
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state.
|
||||||
|
|
||||||
|
pub mod hotfix;
|
||||||
|
pub mod plugins;
|
||||||
|
pub mod policy;
|
||||||
|
pub mod profiles;
|
||||||
|
pub mod site;
|
||||||
|
pub mod tabs;
|
||||||
|
pub mod update;
|
||||||
|
|
||||||
|
#[cfg(feature = "tauri")]
|
||||||
|
pub mod host;
|
||||||
382
crates/waybetter-host/src/plugins.rs
Normal file
382
crates/waybetter-host/src/plugins.rs
Normal file
|
|
@ -0,0 +1,382 @@
|
||||||
|
//! BetterDiscord-style extensions for the site page: `*.plugin.js` files and custom CSS.
|
||||||
|
//!
|
||||||
|
//! Plugins are trusted by the owner who puts them in the folder. They run in the site page with
|
||||||
|
//! full page access. Native code only reads files from its own plugins directory, never from a
|
||||||
|
//! caller-supplied path, and the scripts it builds embed plugin data as JSON string literals.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub const PLUGIN_SUFFIX: &str = ".plugin.js";
|
||||||
|
pub const MAX_PLUGIN_BYTES: u64 = 2 * 1024 * 1024;
|
||||||
|
pub const MAX_CSS_BYTES: usize = 512 * 1024;
|
||||||
|
const STATE_FILE: &str = "enabled.json";
|
||||||
|
const CSS_FILE: &str = "custom.css";
|
||||||
|
/// Which first-party plugin content was last written, so upgrades never overwrite user edits.
|
||||||
|
const BUNDLED_FILE: &str = "bundled.json";
|
||||||
|
|
||||||
|
/// What the plugin host needs from the app: where plugins run and what ships with it.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct PluginHost {
|
||||||
|
/// The page runtime's window global; plugins register under `window.<global>.plugins`.
|
||||||
|
pub runtime_global: &'static str,
|
||||||
|
/// Scripts run only in the top frame of this exact origin, e.g. `https://x.com`.
|
||||||
|
pub origin: &'static str,
|
||||||
|
/// Console prefix, e.g. `wayBetter for X`.
|
||||||
|
pub product: &'static str,
|
||||||
|
/// Element id of the custom CSS `<style>`.
|
||||||
|
pub css_element_id: &'static str,
|
||||||
|
/// Written disabled into a freshly created plugins folder: (file name, source).
|
||||||
|
pub example: Option<(&'static str, &'static str)>,
|
||||||
|
/// First-party plugins, written disabled and upgraded (see [`PluginStore::install_bundled`]).
|
||||||
|
pub bundled: &'static [(&'static str, &'static str)],
|
||||||
|
}
|
||||||
|
|
||||||
|
fn content_hash(bytes: &[u8]) -> String {
|
||||||
|
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ScriptPlugin {
|
||||||
|
pub file: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub version: String,
|
||||||
|
pub author: String,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plugin file name must be a bare `name.plugin.js` inside the plugins directory.
|
||||||
|
pub fn valid_file_name(file: &str) -> bool {
|
||||||
|
file.len() > PLUGIN_SUFFIX.len()
|
||||||
|
&& file.len() <= 128
|
||||||
|
&& file.ends_with(PLUGIN_SUFFIX)
|
||||||
|
&& !file.starts_with('.')
|
||||||
|
&& file
|
||||||
|
.bytes()
|
||||||
|
.all(|ch| ch.is_ascii_alphanumeric() || b"_-. ".contains(&ch))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `@name`, `@description`, `@version` and `@author` from the leading `/** … */` block.
|
||||||
|
pub fn parse_meta(file: &str, source: &str) -> ScriptPlugin {
|
||||||
|
let mut plugin = ScriptPlugin {
|
||||||
|
file: file.to_owned(),
|
||||||
|
name: file.trim_end_matches(PLUGIN_SUFFIX).to_owned(),
|
||||||
|
description: String::new(),
|
||||||
|
version: String::new(),
|
||||||
|
author: String::new(),
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
let trimmed = source.trim_start_matches('\u{feff}').trim_start();
|
||||||
|
let Some(body) = trimmed.strip_prefix("/**") else {
|
||||||
|
return plugin;
|
||||||
|
};
|
||||||
|
let Some(end) = body.find("*/") else {
|
||||||
|
return plugin;
|
||||||
|
};
|
||||||
|
for line in body[..end].lines() {
|
||||||
|
let line = line.trim().trim_start_matches('*').trim();
|
||||||
|
let Some(rest) = line.strip_prefix('@') else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let (key, value) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
|
||||||
|
let value: String = value.trim().chars().filter(|ch| !ch.is_control()).take(300).collect();
|
||||||
|
match key {
|
||||||
|
"name" if !value.is_empty() => plugin.name = value,
|
||||||
|
"description" => plugin.description = value,
|
||||||
|
"version" => plugin.version = value,
|
||||||
|
"author" => plugin.author = value,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
plugin
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PluginStore {
|
||||||
|
dir: PathBuf,
|
||||||
|
host: &'static PluginHost,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PluginStore {
|
||||||
|
pub fn new(dir: PathBuf, host: &'static PluginHost) -> Self {
|
||||||
|
Self { dir, host }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir(&self) -> &Path {
|
||||||
|
&self.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn host(&self) -> &'static PluginHost {
|
||||||
|
self.host
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates the folder; on first creation also writes the disabled example plugin. Every call
|
||||||
|
/// installs or upgrades the first-party plugins (see [`Self::install_bundled`]).
|
||||||
|
pub fn ensure(&self) -> Result<(), String> {
|
||||||
|
let fresh = !self.dir.exists();
|
||||||
|
fs::create_dir_all(&self.dir).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||||
|
if fresh {
|
||||||
|
if let Some((file, source)) = self.host.example {
|
||||||
|
let _ = fs::write(self.dir.join(file), source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.install_bundled(self.host.bundled);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes first-party plugins without ever enabling them or touching the owner's work:
|
||||||
|
/// - missing and never installed: written (first run, or a plugin new in this version);
|
||||||
|
/// - missing but installed before: the owner deleted it, so it stays deleted;
|
||||||
|
/// - present and byte-identical to what was last installed: upgraded to the shipped content;
|
||||||
|
/// - present with any other content (edited, or an unrelated file of that name): left alone.
|
||||||
|
pub fn install_bundled(&self, bundled: &[(&str, &str)]) {
|
||||||
|
let manifest_path = self.dir.join(BUNDLED_FILE);
|
||||||
|
let mut manifest: BTreeMap<String, String> = fs::read_to_string(&manifest_path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|raw| serde_json::from_str(&raw).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let before = manifest.clone();
|
||||||
|
for (file, source) in bundled {
|
||||||
|
if !valid_file_name(file) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let path = self.dir.join(file);
|
||||||
|
let shipped = content_hash(source.as_bytes());
|
||||||
|
let installed = manifest.get(*file).cloned();
|
||||||
|
match fs::read(&path) {
|
||||||
|
Err(_) if installed.is_none() => {
|
||||||
|
if fs::write(&path, source).is_ok() {
|
||||||
|
manifest.insert((*file).to_owned(), shipped);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
Ok(current) => {
|
||||||
|
let current = content_hash(¤t);
|
||||||
|
if current == shipped {
|
||||||
|
manifest.insert((*file).to_owned(), shipped);
|
||||||
|
} else if installed.as_deref() == Some(current.as_str()) && fs::write(&path, source).is_ok() {
|
||||||
|
manifest.insert((*file).to_owned(), shipped);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if manifest != before {
|
||||||
|
if let Ok(json) = serde_json::to_string_pretty(&manifest) {
|
||||||
|
let _ = fs::write(manifest_path, json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enabled_set(&self) -> BTreeSet<String> {
|
||||||
|
fs::read_to_string(self.dir.join(STATE_FILE))
|
||||||
|
.ok()
|
||||||
|
.and_then(|raw| serde_json::from_str::<BTreeSet<String>>(&raw).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|file| valid_file_name(file))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_source(&self, file: &str) -> Result<String, String> {
|
||||||
|
if !valid_file_name(file) {
|
||||||
|
return Err("VALIDATION: invalid plugin file name".into());
|
||||||
|
}
|
||||||
|
let path = self.dir.join(file);
|
||||||
|
let meta = fs::metadata(&path).map_err(|_| "PLUGINS: plugin file not found")?;
|
||||||
|
if !meta.is_file() || meta.len() > MAX_PLUGIN_BYTES {
|
||||||
|
return Err("PLUGINS: plugin must be a regular file under 2 MiB".into());
|
||||||
|
}
|
||||||
|
fs::read_to_string(&path).map_err(|_| "PLUGINS: plugin must be UTF-8 text".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list(&self) -> Result<Vec<ScriptPlugin>, String> {
|
||||||
|
self.ensure()?;
|
||||||
|
let enabled = self.enabled_set();
|
||||||
|
let mut plugins = Vec::new();
|
||||||
|
for entry in fs::read_dir(&self.dir).map_err(|error| format!("PLUGINS: {error}"))? {
|
||||||
|
let Ok(entry) = entry else { continue };
|
||||||
|
let Some(file) = entry.file_name().to_str().map(str::to_owned) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !valid_file_name(&file) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(source) = self.read_source(&file) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mut plugin = parse_meta(&file, &source);
|
||||||
|
plugin.enabled = enabled.contains(&file);
|
||||||
|
plugins.push(plugin);
|
||||||
|
}
|
||||||
|
plugins.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||||
|
Ok(plugins)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_enabled(&self, file: &str, enabled: bool) -> Result<(), String> {
|
||||||
|
self.read_source(file)?;
|
||||||
|
let mut set = self.enabled_set();
|
||||||
|
if enabled {
|
||||||
|
set.insert(file.to_owned());
|
||||||
|
} else {
|
||||||
|
set.remove(file);
|
||||||
|
}
|
||||||
|
let json = serde_json::to_string_pretty(&set).map_err(|_| "PLUGINS: serialization failed")?;
|
||||||
|
fs::write(self.dir.join(STATE_FILE), json).map_err(|error| format!("PLUGINS: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start scripts for every enabled plugin, in name order.
|
||||||
|
pub fn start_scripts(&self) -> Vec<String> {
|
||||||
|
let enabled = self.enabled_set();
|
||||||
|
enabled
|
||||||
|
.iter()
|
||||||
|
.filter_map(|file| self.start_script(file).ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_script(&self, file: &str) -> Result<String, String> {
|
||||||
|
let source = self.read_source(file)?;
|
||||||
|
start_script(self.host, file, &source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn css(&self) -> String {
|
||||||
|
fs::read_to_string(self.dir.join(CSS_FILE)).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_css(&self, css: &str) -> Result<(), String> {
|
||||||
|
if css.len() > MAX_CSS_BYTES {
|
||||||
|
return Err("VALIDATION: custom CSS is limited to 512 KiB".into());
|
||||||
|
}
|
||||||
|
self.ensure()?;
|
||||||
|
fs::write(self.dir.join(CSS_FILE), css).map_err(|error| format!("PLUGINS: {error}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn js_string(value: &str) -> Result<String, String> {
|
||||||
|
serde_json::to_string(value).map_err(|_| "PLUGINS: serialization failed".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wraps a CommonJS-style plugin (`module.exports = class { start() {} stop() {} }`).
|
||||||
|
/// Native code evaluates the result in the site tab, so the page's CSP does not block it.
|
||||||
|
pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> {
|
||||||
|
let id = js_string(file)?;
|
||||||
|
let PluginHost { runtime_global: global, origin, product, .. } = host;
|
||||||
|
Ok(format!(
|
||||||
|
"(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\
|
||||||
|
const id={id};if(XW.plugins[id])return;\
|
||||||
|
try{{const module={{exports:{{}}}};const exports=module.exports;\
|
||||||
|
(function(module,exports){{\n{source}\n}})(module,exports);\
|
||||||
|
let P=module.exports&&module.exports.default?module.exports.default:module.exports;\
|
||||||
|
const inst=typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P;\
|
||||||
|
XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')inst.start();\
|
||||||
|
console.info('[{product}] started',id);}}\
|
||||||
|
catch(e){{XW.errors[id]=String(e&&e.stack||e);console.error('[{product}] plugin failed',id,e);}}}})();"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_script(host: &PluginHost, file: &str) -> Result<String, String> {
|
||||||
|
let id = js_string(file)?;
|
||||||
|
let PluginHost { runtime_global: global, product, .. } = host;
|
||||||
|
Ok(format!(
|
||||||
|
"(()=>{{const XW=window.{global};if(!XW)return;const id={id};const p=XW.plugins[id];\
|
||||||
|
if(!p)return;delete XW.plugins[id];\
|
||||||
|
try{{if(typeof p.stop==='function')p.stop();console.info('[{product}] stopped',id);}}\
|
||||||
|
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}}})();"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn css_script(host: &PluginHost, css: &str) -> Result<String, String> {
|
||||||
|
let css = js_string(css)?;
|
||||||
|
let PluginHost { origin, css_element_id, .. } = host;
|
||||||
|
Ok(format!(
|
||||||
|
"(()=>{{if(window.top!==window||location.origin!=='{origin}')return;\
|
||||||
|
const id='{css_element_id}';let s=document.getElementById(id);\
|
||||||
|
if(!s){{s=document.createElement('style');s.id=id;(document.head||document.documentElement).appendChild(s);}}\
|
||||||
|
s.textContent={css};}})();"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
static HOST: PluginHost = PluginHost {
|
||||||
|
runtime_global: "Demo",
|
||||||
|
origin: "https://site.test",
|
||||||
|
product: "wayBetter for Test",
|
||||||
|
css_element_id: "demo-css",
|
||||||
|
example: Some(("example.plugin.js", "/**\n * @name Example\n */\nmodule.exports = class { start(){} stop(){} };")),
|
||||||
|
bundled: &[("wb-one.plugin.js", "/** @name One */ module.exports = {};")],
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_file_names_cannot_escape_the_plugins_folder() {
|
||||||
|
assert!(valid_file_name("hide-trends.plugin.js"));
|
||||||
|
assert!(valid_file_name("My Plugin.plugin.js"));
|
||||||
|
for bad in ["../x.plugin.js", "a/b.plugin.js", r"a\b.plugin.js", ".plugin.js", ".hidden.plugin.js", "x.js", "C:x.plugin.js", ""] {
|
||||||
|
assert!(!valid_file_name(bad), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn meta_header_is_parsed_and_defaults_to_file_name() {
|
||||||
|
let source = "/**\n * @name Hide Trends\n * @description Hides trends\n * @version 1.2.0\n * @author Someone\n */\nmodule.exports = class {};";
|
||||||
|
let plugin = parse_meta("hide.plugin.js", source);
|
||||||
|
assert_eq!((plugin.name.as_str(), plugin.description.as_str(), plugin.version.as_str()), ("Hide Trends", "Hides trends", "1.2.0"));
|
||||||
|
assert_eq!(plugin.author, "Someone");
|
||||||
|
assert_eq!(parse_meta("bare.plugin.js", "module.exports = {}").name, "bare");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_lists_toggles_and_persists_css() {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let store = PluginStore::new(root.path().join("plugins"), &HOST);
|
||||||
|
let listed = store.list().unwrap();
|
||||||
|
assert_eq!(listed.len(), 2, "fresh folder gets the example and the bundled plugin");
|
||||||
|
assert!(listed.iter().all(|plugin| !plugin.enabled));
|
||||||
|
store.set_enabled("example.plugin.js", true).unwrap();
|
||||||
|
assert_eq!(store.start_scripts().len(), 1);
|
||||||
|
assert!(store.set_enabled("../escape.plugin.js", true).is_err());
|
||||||
|
store.set_enabled("example.plugin.js", false).unwrap();
|
||||||
|
assert!(store.start_scripts().is_empty());
|
||||||
|
store.set_css("body{color:red}").unwrap();
|
||||||
|
assert_eq!(store.css(), "body{color:red}");
|
||||||
|
assert!(store.set_css(&"a".repeat(MAX_CSS_BYTES + 1)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bundled_plugins_upgrade_only_untouched_copies() {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let store = PluginStore::new(root.path().to_path_buf(), &HOST);
|
||||||
|
let path = root.path().join("wb-a.plugin.js");
|
||||||
|
store.install_bundled(&[("wb-a.plugin.js", "v1")]);
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), "v1");
|
||||||
|
store.install_bundled(&[("wb-a.plugin.js", "v2")]);
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), "v2", "untouched copy is upgraded");
|
||||||
|
fs::write(&path, "mine").unwrap();
|
||||||
|
store.install_bundled(&[("wb-a.plugin.js", "v3")]);
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), "mine", "edited copy is left alone");
|
||||||
|
fs::remove_file(&path).unwrap();
|
||||||
|
store.install_bundled(&[("wb-a.plugin.js", "v4")]);
|
||||||
|
assert!(!path.exists(), "a deleted bundled plugin stays deleted");
|
||||||
|
let foreign = root.path().join("wb-b.plugin.js");
|
||||||
|
fs::write(&foreign, "foreign").unwrap();
|
||||||
|
store.install_bundled(&[("wb-b.plugin.js", "shipped")]);
|
||||||
|
assert_eq!(fs::read_to_string(&foreign).unwrap(), "foreign", "a foreign file of that name is kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scripts_are_scoped_to_the_site_and_embed_data_as_literals() {
|
||||||
|
let start = start_script(&HOST, "a\"b.plugin.js", "module.exports = {}").unwrap();
|
||||||
|
assert!(start.starts_with("(()=>{const XW=window.Demo;if(!XW||window.top!==window||location.origin!=='https://site.test')return;"));
|
||||||
|
assert!(start.contains(r#"const id="a\"b.plugin.js";"#));
|
||||||
|
assert!(start.contains("[wayBetter for Test] started"));
|
||||||
|
let stop = stop_script(&HOST, "x.plugin.js").unwrap();
|
||||||
|
assert!(stop.contains("window.Demo") && stop.contains("[wayBetter for Test] stopped"));
|
||||||
|
let css = css_script(&HOST, "</style><script>").unwrap();
|
||||||
|
assert!(css.contains("const id='demo-css'") && css.contains(r#"s.textContent="</style><script>";"#));
|
||||||
|
}
|
||||||
|
}
|
||||||
197
crates/waybetter-host/src/policy.rs
Normal file
197
crates/waybetter-host/src/policy.rs
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
//! The host's security boundary. Capabilities are keyed by webview label:
|
||||||
|
//! - `shell` (local app assets only) may call app, settings and tab-management commands;
|
||||||
|
//! - `tab-<id>` webviews may call only tab-chrome commands about themselves ([`tab_id`]), and
|
||||||
|
//! site-only commands while they are exactly on the site's origin ([`require_site_tab`]);
|
||||||
|
//! - nothing a page sends can name another webview, profile or file.
|
||||||
|
|
||||||
|
use crate::site::SiteSpec;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// The native window.
|
||||||
|
pub const MAIN_LABEL: &str = "main";
|
||||||
|
/// The trusted local shell webview (tabs, address bars, app UI).
|
||||||
|
pub const SHELL_LABEL: &str = "shell";
|
||||||
|
/// Browser-tab webviews are labelled `tab-<id>`.
|
||||||
|
pub const TAB_PREFIX: &str = "tab-";
|
||||||
|
/// The shell's Vite dev server, allowed only in debug builds.
|
||||||
|
pub const DEV_PORT: u16 = 1420;
|
||||||
|
|
||||||
|
pub fn valid_tab_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 40 && id.bytes().all(|ch| ch.is_ascii_alphanumeric() || ch == b'-')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tab id of a tab webview label, if `label` is one.
|
||||||
|
pub fn tab_id(label: &str) -> Option<&str> {
|
||||||
|
label.strip_prefix(TAB_PREFIX).filter(|id| valid_tab_id(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The webview label of tab `id`.
|
||||||
|
pub fn tab_label(id: &str) -> String {
|
||||||
|
format!("{TAB_PREFIX}{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Titlebar height in logical px. A tab webview must never cover y < TITLEBAR_H.
|
||||||
|
pub const TITLEBAR_H: f64 = 44.0;
|
||||||
|
/// Outer resize-grip band, in logical px, reserved while the window is not maximized.
|
||||||
|
pub const RESIZE_BORDER: f64 = 5.0;
|
||||||
|
|
||||||
|
/// Clamps a requested tab rectangle so it never overlaps the custom titlebar row or (while
|
||||||
|
/// restored) the outer resize band, and rejects non-finite input. The insets apply only when the
|
||||||
|
/// window is `frameless` (no OS decorations); a decorated window has native chrome and resize
|
||||||
|
/// edges, so the rect is only clipped to the window. Returns `Ok(None)` when nothing of the rect
|
||||||
|
/// is left, in which case the caller hides the webview.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn clamp_tab_rect(
|
||||||
|
x: f64,
|
||||||
|
y: f64,
|
||||||
|
width: f64,
|
||||||
|
height: f64,
|
||||||
|
win_width: f64,
|
||||||
|
win_height: f64,
|
||||||
|
maximized: bool,
|
||||||
|
frameless: bool,
|
||||||
|
) -> Result<Option<(f64, f64, f64, f64)>, &'static str> {
|
||||||
|
if ![x, y, width, height, win_width, win_height].iter().all(|v| v.is_finite()) {
|
||||||
|
return Err("VALIDATION: non-finite rect");
|
||||||
|
}
|
||||||
|
let (top, inset) = match (frameless, maximized) {
|
||||||
|
(false, _) => (0.0, 0.0),
|
||||||
|
(true, true) => (TITLEBAR_H, 0.0),
|
||||||
|
(true, false) => (TITLEBAR_H, RESIZE_BORDER),
|
||||||
|
};
|
||||||
|
let left = x.max(inset);
|
||||||
|
let upper = y.max(top);
|
||||||
|
let right = (x + width).min(win_width - inset);
|
||||||
|
let bottom = (y + height).min(win_height - inset);
|
||||||
|
if right - left < 1.0 || bottom - upper < 1.0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(Some((left, upper, right - left, bottom - upper)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn valid_identifier(value: &str) -> bool {
|
||||||
|
!value.is_empty()
|
||||||
|
&& value.len() <= 128
|
||||||
|
&& value
|
||||||
|
.bytes()
|
||||||
|
.all(|ch| ch.is_ascii_alphanumeric() || b"_-:.".contains(&ch))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No user name or password in the URL.
|
||||||
|
pub fn plain_origin(url: &Url) -> bool {
|
||||||
|
url.username().is_empty() && url.password().is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shell's own documents: bundled app assets, or the dev server in debug builds.
|
||||||
|
pub fn local_navigation_allowed(url: &Url, development: bool) -> bool {
|
||||||
|
if !plain_origin(url) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match (url.scheme(), url.host_str(), url.port()) {
|
||||||
|
("tauri", Some("localhost"), None) => true,
|
||||||
|
("http" | "https", Some("tauri.localhost"), None) => true,
|
||||||
|
("http", Some("localhost" | "127.0.0.1"), Some(DEV_PORT)) => development,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shell-only commands: the `shell` webview on a local document.
|
||||||
|
pub fn require_local(label: &str, url: &Url, development: bool) -> Result<(), String> {
|
||||||
|
if label == SHELL_LABEL && local_navigation_allowed(url, development) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("FORBIDDEN: trusted local workspace required".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Site-only commands: a tab webview that is exactly on the site's origin right now.
|
||||||
|
pub fn require_site_tab(site: &SiteSpec, label: &str, url: &Url) -> Result<(), String> {
|
||||||
|
if tab_id(label).is_some() && site.is_origin(url) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("FORBIDDEN: exact site origin required".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::site::testing::SITE;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_restricts_titlebar_and_border() {
|
||||||
|
let (x, y, w, h) = clamp_tab_rect(0.0, 0.0, 800.0, 600.0, 1000.0, 700.0, false, true).unwrap().unwrap();
|
||||||
|
assert_eq!((x, y), (RESIZE_BORDER, TITLEBAR_H));
|
||||||
|
assert_eq!((w, h), (800.0 - RESIZE_BORDER, 600.0 - TITLEBAR_H));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_negative_and_titlebar_y() {
|
||||||
|
let (_, y, _, _) = clamp_tab_rect(10.0, -50.0, 100.0, 100.0, 1000.0, 700.0, false, true).unwrap().unwrap();
|
||||||
|
assert_eq!(y, TITLEBAR_H);
|
||||||
|
let (_, y, _, h) = clamp_tab_rect(10.0, 20.0, 100.0, 100.0, 1000.0, 700.0, false, true).unwrap().unwrap();
|
||||||
|
assert_eq!((y, h), (TITLEBAR_H, 76.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_maximized_has_no_border_inset() {
|
||||||
|
let rect = clamp_tab_rect(0.0, 0.0, 1000.0, 700.0, 1000.0, 700.0, true, true).unwrap();
|
||||||
|
assert_eq!(rect, Some((0.0, TITLEBAR_H, 1000.0, 700.0 - TITLEBAR_H)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_decorated_window_is_not_inset() {
|
||||||
|
let rect = clamp_tab_rect(0.0, 0.0, 1000.0, 700.0, 1000.0, 700.0, false, false).unwrap();
|
||||||
|
assert_eq!(rect, Some((0.0, 0.0, 1000.0, 700.0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_shell_layout_passes_unchanged() {
|
||||||
|
// The shell insets the dock by RESIZE_BORDER and starts panes below TITLEBAR_H + toolbar.
|
||||||
|
let rect = clamp_tab_rect(5.0, 94.0, 990.0, 601.0, 1000.0, 700.0, false, true).unwrap();
|
||||||
|
assert_eq!(rect, Some((5.0, 94.0, 990.0, 601.0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_rejects_non_finite() {
|
||||||
|
assert!(clamp_tab_rect(f64::NAN, 0.0, 100.0, 100.0, 1000.0, 700.0, false, true).is_err());
|
||||||
|
assert!(clamp_tab_rect(0.0, f64::INFINITY, 100.0, 100.0, 1000.0, 700.0, false, true).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clamp_tab_rect_empty_result_is_none() {
|
||||||
|
assert_eq!(clamp_tab_rect(999.0, 699.0, 50.0, 50.0, 1000.0, 700.0, false, true).unwrap(), None);
|
||||||
|
assert_eq!(clamp_tab_rect(10.0, 0.0, 100.0, 30.0, 1000.0, 700.0, true, true).unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tab_labels_are_strict() {
|
||||||
|
assert_eq!(tab_id("tab-abc-123"), Some("abc-123"));
|
||||||
|
assert_eq!(tab_label("abc"), "tab-abc");
|
||||||
|
for bad in ["tab-", "tab-../x", "tab-a b", "shell", "main", "xtab-1", &format!("tab-{}", "a".repeat(41))] {
|
||||||
|
assert_eq!(tab_id(bad), None, "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn site_commands_need_a_tab_on_the_exact_origin() {
|
||||||
|
let site = Url::parse("https://x.com/home").unwrap();
|
||||||
|
assert!(require_site_tab(&SITE, "tab-1", &site).is_ok());
|
||||||
|
assert!(require_site_tab(&SITE, "shell", &site).is_err());
|
||||||
|
assert!(require_site_tab(&SITE, "popover-1", &site).is_err());
|
||||||
|
assert!(require_site_tab(&SITE, "tab-1", &Url::parse("https://example.com/").unwrap()).is_err());
|
||||||
|
assert!(require_site_tab(&SITE, "tab-1", &Url::parse("https://a@x.com/").unwrap()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_origin_has_no_production_localhost_backdoor() {
|
||||||
|
for ok in ["tauri://localhost/", "http://tauri.localhost/", "https://tauri.localhost/index.html"] {
|
||||||
|
assert!(require_local("shell", &Url::parse(ok).unwrap(), false).is_ok(), "{ok}");
|
||||||
|
}
|
||||||
|
assert!(require_local("shell", &Url::parse("http://127.0.0.1:1420/").unwrap(), true).is_ok());
|
||||||
|
for bad in ["http://127.0.0.1:1420/", "http://localhost:1420/", "https://x.com/", "tauri://evil/", "http://u@tauri.localhost/"] {
|
||||||
|
assert!(require_local("shell", &Url::parse(bad).unwrap(), false).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
assert!(require_local("tab-1", &Url::parse("tauri://localhost/").unwrap(), false).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
368
crates/waybetter-host/src/profiles.rs
Normal file
368
crates/waybetter-host/src/profiles.rs
Normal file
|
|
@ -0,0 +1,368 @@
|
||||||
|
//! Account profiles: each site tab runs in one profile, and every non-default profile has its own
|
||||||
|
//! WebView data directory (cookies, storage, cache), so several accounts can be signed in side by
|
||||||
|
//! side without sharing a session. The default profile keeps the WebView's default data directory.
|
||||||
|
//!
|
||||||
|
//! The account inside a profile is owned by native code: only a site tab of that very profile can
|
||||||
|
//! report it ([`ProfileSettings::observe`]), validated with the site's [`AccountRules`], and a save
|
||||||
|
//! from the shell never changes it ([`ProfileSettings::keep_accounts_from`]).
|
||||||
|
|
||||||
|
use crate::site::AccountRules;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub const DEFAULT_PROFILE: &str = "default";
|
||||||
|
pub const PROFILES_DIR: &str = "profiles";
|
||||||
|
const MAX_PROFILES: usize = 500;
|
||||||
|
const MAX_NAME_CHARS: usize = 40;
|
||||||
|
|
||||||
|
/// The account signed in inside a profile, as the site itself shows it (read by the page runtime
|
||||||
|
/// in that profile's tabs and reported through `tab_report`). Kept after a sign-out
|
||||||
|
/// (`signed_in: false`) so the list still says whose login it was.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Account {
|
||||||
|
/// Without the `@`.
|
||||||
|
pub handle: String,
|
||||||
|
pub name: String,
|
||||||
|
/// On the site's image CDN only (see [`AccountRules::avatar_prefixes`]).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub avatar: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub signed_in: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Profile {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// `#rrggbb`, shown as the tab's profile dot.
|
||||||
|
pub color: String,
|
||||||
|
/// Owned by native code (see `ProfileSettings::observe`); a save from the shell never changes it.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub account: Option<Account>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a site tab saw about its own profile's login.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AccountSeen {
|
||||||
|
SignedIn(Account),
|
||||||
|
SignedOut,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Account {
|
||||||
|
/// Validated and normalized, or None when the handle is not one the site allows.
|
||||||
|
pub fn validated(mut self, rules: &AccountRules) -> Option<Self> {
|
||||||
|
let handle = self.handle.trim().trim_start_matches('@').to_owned();
|
||||||
|
if !(rules.valid_handle)(&handle) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.handle = handle;
|
||||||
|
let name: String = self.name.chars().filter(|ch| !ch.is_control()).collect();
|
||||||
|
let name: String = name.trim().chars().take(rules.max_name_chars).collect();
|
||||||
|
self.name = if name.is_empty() { self.handle.clone() } else { name };
|
||||||
|
self.avatar = self.avatar.filter(|url| rules.avatar_allowed(url));
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ProfileSettings {
|
||||||
|
pub profiles: Vec<Profile>,
|
||||||
|
/// New tabs open in this profile.
|
||||||
|
pub active: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first profile's name and color (the shell's first palette color).
|
||||||
|
pub const DEFAULT_NAME: &str = "Main";
|
||||||
|
pub const DEFAULT_COLOR: &str = "#1d9bf0";
|
||||||
|
|
||||||
|
impl Default for ProfileSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
profiles: vec![Profile { id: DEFAULT_PROFILE.into(), name: DEFAULT_NAME.into(), color: DEFAULT_COLOR.into(), account: None }],
|
||||||
|
active: DEFAULT_PROFILE.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `default`, or `p` followed by 1-32 lowercase ASCII letters/digits. Ids become directory names,
|
||||||
|
/// so nothing else (no dots, slashes, separators or reserved names) is accepted.
|
||||||
|
pub fn valid_profile_id(id: &str) -> bool {
|
||||||
|
id == DEFAULT_PROFILE
|
||||||
|
|| (id.len() >= 2
|
||||||
|
&& id.len() <= 33
|
||||||
|
&& id.starts_with('p')
|
||||||
|
&& id.bytes().all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_color(color: &str) -> bool {
|
||||||
|
color.len() == 7 && color.starts_with('#') && color[1..].bytes().all(|ch| ch.is_ascii_hexdigit())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileSettings {
|
||||||
|
pub fn validated(mut self, rules: &AccountRules) -> Result<Self, String> {
|
||||||
|
if self.profiles.is_empty() || self.profiles.len() > MAX_PROFILES {
|
||||||
|
return Err("VALIDATION: invalid profile count".into());
|
||||||
|
}
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
for profile in &mut self.profiles {
|
||||||
|
if !valid_profile_id(&profile.id) || !seen.insert(profile.id.clone()) {
|
||||||
|
return Err("VALIDATION: invalid or duplicate profile id".into());
|
||||||
|
}
|
||||||
|
let name = profile.name.trim();
|
||||||
|
if name.is_empty() || name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||||
|
return Err("VALIDATION: profile name must be 1-40 visible characters".into());
|
||||||
|
}
|
||||||
|
profile.name = name.to_owned();
|
||||||
|
if !valid_color(&profile.color) {
|
||||||
|
return Err("VALIDATION: profile color must be #rrggbb".into());
|
||||||
|
}
|
||||||
|
profile.color = profile.color.to_ascii_lowercase();
|
||||||
|
profile.account = profile.account.take().and_then(|account| account.validated(rules));
|
||||||
|
}
|
||||||
|
if !seen.contains(DEFAULT_PROFILE) {
|
||||||
|
return Err("VALIDATION: the default profile cannot be removed".into());
|
||||||
|
}
|
||||||
|
if !seen.contains(&self.active) {
|
||||||
|
return Err("VALIDATION: active profile does not exist".into());
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Native code owns each profile's account: a save from the shell keeps the one on record.
|
||||||
|
pub fn keep_accounts_from(mut self, current: &ProfileSettings) -> Self {
|
||||||
|
for profile in &mut self.profiles {
|
||||||
|
profile.account = current.profiles.iter().find(|old| old.id == profile.id).and_then(|old| old.account.clone());
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records what a tab of `profile` saw. The profile takes the account's display name. Returns
|
||||||
|
/// whether anything changed, so repeated reports cost no disk write.
|
||||||
|
pub fn observe(&mut self, profile: &str, seen: AccountSeen, rules: &AccountRules) -> bool {
|
||||||
|
let Some(entry) = self.profiles.iter_mut().find(|entry| entry.id == profile) else { return false };
|
||||||
|
let before = entry.clone();
|
||||||
|
match seen {
|
||||||
|
AccountSeen::SignedIn(account) => {
|
||||||
|
// Narrow site layouts may show only the avatar: no name then means "unchanged".
|
||||||
|
let unnamed = account.name.trim().is_empty();
|
||||||
|
let Some(mut account) = account.validated(rules) else { return false };
|
||||||
|
account.signed_in = true;
|
||||||
|
if let Some(old) = entry.account.as_ref().filter(|old| unnamed && old.handle.eq_ignore_ascii_case(&account.handle)) {
|
||||||
|
account.name = old.name.clone();
|
||||||
|
}
|
||||||
|
// Some layouts show no avatar: keep the one seen before for the same login.
|
||||||
|
if account.avatar.is_none() {
|
||||||
|
if let Some(old) = entry.account.as_ref().filter(|old| old.handle.eq_ignore_ascii_case(&account.handle)) {
|
||||||
|
account.avatar = old.avatar.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entry.name = account.name.chars().take(MAX_NAME_CHARS).collect();
|
||||||
|
entry.account = Some(account);
|
||||||
|
}
|
||||||
|
AccountSeen::SignedOut => {
|
||||||
|
if let Some(account) = entry.account.as_mut() {
|
||||||
|
account.signed_in = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*entry != before
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, id: &str) -> bool {
|
||||||
|
self.profiles.iter().any(|profile| profile.id == id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Profiles present in `self` but not in `next`.
|
||||||
|
pub fn removed_in(&self, next: &ProfileSettings) -> Vec<String> {
|
||||||
|
self.profiles
|
||||||
|
.iter()
|
||||||
|
.filter(|profile| !next.contains(&profile.id))
|
||||||
|
.map(|profile| profile.id.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removed profiles when switching to `next`, or an error if any of them still has an open tab.
|
||||||
|
pub fn removal<'a>(&self, next: &ProfileSettings, open_tabs: impl IntoIterator<Item = &'a String>) -> Result<Vec<String>, String> {
|
||||||
|
let removed = self.removed_in(next);
|
||||||
|
if open_tabs.into_iter().any(|profile| removed.contains(profile)) {
|
||||||
|
return Err("PROFILE: close this profile's tabs before removing it".into());
|
||||||
|
}
|
||||||
|
Ok(removed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The WebView data directory of a profile under the app-local data dir; `None` for the default
|
||||||
|
/// profile (it keeps the WebView's existing default directory) and for invalid ids.
|
||||||
|
pub fn data_dir(local_data: &Path, id: &str) -> Option<PathBuf> {
|
||||||
|
if id == DEFAULT_PROFILE || !valid_profile_id(id) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(local_data.join(PROFILES_DIR).join(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Folders under `<local_data>/profiles` named like a profile id that `settings` no longer has
|
||||||
|
/// (e.g. a removal failed while the folder was still locked). Nothing else is ever listed.
|
||||||
|
pub fn orphan_dirs(local_data: &Path, settings: &ProfileSettings) -> Vec<PathBuf> {
|
||||||
|
let Ok(entries) = std::fs::read_dir(local_data.join(PROFILES_DIR)) else { return Vec::new() };
|
||||||
|
entries
|
||||||
|
.flatten()
|
||||||
|
.filter(|entry| {
|
||||||
|
let name = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
valid_profile_id(&name) && !settings.contains(&name) && entry.path().is_dir()
|
||||||
|
})
|
||||||
|
.map(|entry| entry.path())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable 16-byte WKWebView data-store identifier for a profile (macOS ignores data_directory).
|
||||||
|
pub fn store_identifier(id: &str) -> [u8; 16] {
|
||||||
|
let hash = |seed: u64| {
|
||||||
|
id.bytes().fold(seed, |acc, byte| (acc ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3))
|
||||||
|
};
|
||||||
|
let mut out = [0u8; 16];
|
||||||
|
out[..8].copy_from_slice(&hash(0xcbf2_9ce4_8422_2325).to_le_bytes());
|
||||||
|
out[8..].copy_from_slice(&hash(0x6c62_272e_07bb_0142).to_le_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::site::testing::SITE;
|
||||||
|
|
||||||
|
const RULES: &AccountRules = &SITE.accounts;
|
||||||
|
|
||||||
|
fn profile(id: &str) -> Profile {
|
||||||
|
Profile { id: id.into(), name: format!("Account {id}"), color: "#AABBCC".into(), account: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn account(handle: &str) -> Account {
|
||||||
|
Account { handle: handle.into(), name: "Sample".into(), avatar: Some("https://pbs.twimg.com/profile_images/1/a_normal.jpg".into()), signed_in: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_seen_login_names_the_profile_and_persists_a_sign_out() {
|
||||||
|
let mut settings = ProfileSettings { profiles: vec![profile("default"), profile("p1")], active: "default".into() };
|
||||||
|
assert!(settings.observe("p1", AccountSeen::SignedIn(account("@otheraccount")), RULES));
|
||||||
|
let seen = settings.profiles[1].account.clone().unwrap();
|
||||||
|
assert_eq!((seen.handle.as_str(), seen.signed_in, settings.profiles[1].name.as_str()), ("otheraccount", true, "Sample"));
|
||||||
|
// The same report again changes nothing (no disk write).
|
||||||
|
assert!(!settings.observe("p1", AccountSeen::SignedIn(account("otheraccount")), RULES));
|
||||||
|
assert!(settings.observe("p1", AccountSeen::SignedOut, RULES));
|
||||||
|
assert_eq!(settings.profiles[1].account.as_ref().map(|a| (a.handle.as_str(), a.signed_in)), Some(("otheraccount", false)));
|
||||||
|
assert!(!settings.observe("nope", AccountSeen::SignedOut, RULES));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unnamed_or_avatarless_report_keeps_what_was_seen() {
|
||||||
|
let mut settings = ProfileSettings::default();
|
||||||
|
assert!(settings.observe("default", AccountSeen::SignedIn(account("fish")), RULES));
|
||||||
|
let mut bare = account("FISH");
|
||||||
|
bare.name = " ".into();
|
||||||
|
bare.avatar = None;
|
||||||
|
settings.observe("default", AccountSeen::SignedIn(bare), RULES);
|
||||||
|
let kept = settings.profiles[0].account.clone().unwrap();
|
||||||
|
assert_eq!((kept.name.as_str(), kept.avatar.is_some()), ("Sample", true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn account_reports_are_validated() {
|
||||||
|
let mut settings = ProfileSettings::default();
|
||||||
|
for bad in ["", "has space", "waytoolonghandle_", "a/b"] {
|
||||||
|
assert!(!settings.observe("default", AccountSeen::SignedIn(account(bad)), RULES), "{bad:?}");
|
||||||
|
}
|
||||||
|
let mut foreign = account("ok");
|
||||||
|
foreign.avatar = Some("https://evil.test/x.png".into());
|
||||||
|
assert!(settings.observe("default", AccountSeen::SignedIn(foreign), RULES));
|
||||||
|
assert_eq!(settings.profiles[0].account.as_ref().unwrap().avatar, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_shell_save_keeps_the_native_accounts() {
|
||||||
|
let mut current = ProfileSettings { profiles: vec![profile("default"), profile("p1")], active: "default".into() };
|
||||||
|
current.observe("p1", AccountSeen::SignedIn(account("otheraccount")), RULES);
|
||||||
|
let mut incoming = ProfileSettings { profiles: vec![profile("default"), profile("p1")], active: "p1".into() };
|
||||||
|
incoming.profiles[0].account = Some(account("forged"));
|
||||||
|
let kept = incoming.keep_accounts_from(¤t);
|
||||||
|
assert_eq!(kept.profiles[0].account, None);
|
||||||
|
assert_eq!(kept.profiles[1].account.as_ref().map(|a| a.handle.as_str()), Some("otheraccount"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ids_cannot_escape_the_profiles_directory() {
|
||||||
|
for bad in ["", "p", "..", "p/../x", "p\\x", "P1", "p.1", "con", "p-1", "x1", &format!("p{}", "a".repeat(33))] {
|
||||||
|
assert!(!valid_profile_id(bad), "{bad:?}");
|
||||||
|
assert_eq!(data_dir(Path::new("/base"), bad), None);
|
||||||
|
}
|
||||||
|
assert!(valid_profile_id("p1abc"));
|
||||||
|
assert_eq!(data_dir(Path::new("/base"), "p1abc"), Some(Path::new("/base").join("profiles").join("p1abc")));
|
||||||
|
assert_eq!(data_dir(Path::new("/base"), DEFAULT_PROFILE), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn orphans_are_only_profile_shaped_folders_no_longer_listed() {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let dir = root.path().join(PROFILES_DIR);
|
||||||
|
for name in ["p1", "p2", "keep.me", "P3"] {
|
||||||
|
std::fs::create_dir_all(dir.join(name)).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(dir.join("p4"), "a file").unwrap();
|
||||||
|
let settings = ProfileSettings { profiles: vec![profile("default"), profile("p1")], active: "default".into() };
|
||||||
|
assert_eq!(orphan_dirs(root.path(), &settings), vec![dir.join("p2")]);
|
||||||
|
assert!(orphan_dirs(&root.path().join("missing"), &settings).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_profile_is_required_and_active_must_exist() {
|
||||||
|
let only_other = ProfileSettings { profiles: vec![profile("p1")], active: "p1".into() };
|
||||||
|
assert!(only_other.validated(RULES).is_err());
|
||||||
|
let missing_active = ProfileSettings { profiles: vec![profile("default")], active: "p9".into() };
|
||||||
|
assert!(missing_active.validated(RULES).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn many_profiles_are_allowed_and_normalized() {
|
||||||
|
let mut profiles = vec![profile("default")];
|
||||||
|
profiles.extend((0..20).map(|n| profile(&format!("p{n}"))));
|
||||||
|
profiles[3].name = " Work ".into();
|
||||||
|
let settings = ProfileSettings { profiles, active: "p7".into() }.validated(RULES).unwrap();
|
||||||
|
assert_eq!(settings.profiles.len(), 21);
|
||||||
|
assert_eq!(settings.profiles[3].name, "Work");
|
||||||
|
assert_eq!(settings.profiles[0].color, "#aabbcc");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicates_bad_names_and_colors_are_rejected() {
|
||||||
|
let dup = ProfileSettings { profiles: vec![profile("default"), profile("p1"), profile("p1")], active: "default".into() };
|
||||||
|
assert!(dup.validated(RULES).is_err());
|
||||||
|
for (name, color) in [(" ", "#000000"), ("a\nb", "#000000"), (&"x".repeat(41)[..], "#000000"), ("ok", "red"), ("ok", "#12345g")] {
|
||||||
|
let mut bad = profile("default");
|
||||||
|
bad.name = name.into();
|
||||||
|
bad.color = color.into();
|
||||||
|
assert!(ProfileSettings { profiles: vec![bad], active: "default".into() }.validated(RULES).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn removed_profiles_and_store_identifiers() {
|
||||||
|
let before = ProfileSettings { profiles: vec![profile("default"), profile("p1"), profile("p2")], active: "p1".into() };
|
||||||
|
let after = ProfileSettings { profiles: vec![profile("default"), profile("p2")], active: "default".into() };
|
||||||
|
assert_eq!(before.removed_in(&after), vec!["p1".to_string()]);
|
||||||
|
assert_eq!(store_identifier("p1"), store_identifier("p1"));
|
||||||
|
assert_ne!(store_identifier("p1"), store_identifier("p2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_profile_with_open_tabs_cannot_be_removed() {
|
||||||
|
let before = ProfileSettings { profiles: vec![profile("default"), profile("p1"), profile("p2")], active: "p1".into() };
|
||||||
|
let after = ProfileSettings { profiles: vec![profile("default"), profile("p2")], active: "default".into() };
|
||||||
|
let open = ["p1".to_string()];
|
||||||
|
assert!(before.removal(&after, &open).is_err());
|
||||||
|
let open = ["p2".to_string(), "default".to_string()];
|
||||||
|
assert_eq!(before.removal(&after, &open).unwrap(), vec!["p1".to_string()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
106
crates/waybetter-host/src/site.rs
Normal file
106
crates/waybetter-host/src/site.rs
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
//! The site adapter: everything the host needs to know about the one site an app extends.
|
||||||
|
//!
|
||||||
|
//! An app declares one `static SITE: SiteSpec` and passes it to the host helpers. Nothing in the
|
||||||
|
//! host hard-codes a site; the security boundary (which webviews count as "site tabs" and may call
|
||||||
|
//! site-only commands) is derived from `hosts`.
|
||||||
|
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// How the account signed in inside a profile is validated before it is stored. The page runtime
|
||||||
|
/// reads it from the site's own UI; native code accepts only values that pass these rules.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct AccountRules {
|
||||||
|
/// A normalized handle (no leading `@`) the site could really have.
|
||||||
|
pub valid_handle: fn(&str) -> bool,
|
||||||
|
/// Avatar URLs must start with one of these (the site's own image CDN), else they are dropped.
|
||||||
|
pub avatar_prefixes: &'static [&'static str],
|
||||||
|
/// Display names are cut to this many characters.
|
||||||
|
pub max_name_chars: usize,
|
||||||
|
/// Avatar URLs longer than this are dropped.
|
||||||
|
pub max_avatar_len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AccountRules {
|
||||||
|
pub fn avatar_allowed(&self, url: &str) -> bool {
|
||||||
|
url.len() <= self.max_avatar_len
|
||||||
|
&& self.avatar_prefixes.iter().any(|prefix| url.starts_with(prefix))
|
||||||
|
&& !url.contains(|ch: char| ch == '"' || ch == '\'' || ch == '\\' || ch.is_whitespace())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct SiteSpec {
|
||||||
|
/// Product name for logs and native notifications, e.g. "wayBetter for X".
|
||||||
|
pub product: &'static str,
|
||||||
|
/// Exact HTTPS hosts (port 443, no credentials) whose pages are site tabs.
|
||||||
|
pub hosts: &'static [&'static str],
|
||||||
|
/// The page runtime's window global, e.g. `BetterTwttr` (`window.BetterTwttr`).
|
||||||
|
pub runtime_global: &'static str,
|
||||||
|
pub accounts: AccountRules,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SiteSpec {
|
||||||
|
/// Whether `url` is exactly one of the site's origins (https, default port, no credentials).
|
||||||
|
pub fn is_origin(&self, url: &Url) -> bool {
|
||||||
|
crate::policy::plain_origin(url)
|
||||||
|
&& url.scheme() == "https"
|
||||||
|
&& url.host_str().is_some_and(|host| self.hosts.contains(&host))
|
||||||
|
&& url.port_or_known_default() == Some(443)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `https://<first host>`, the origin the page runtime checks before it runs.
|
||||||
|
pub fn primary_origin(&self) -> String {
|
||||||
|
format!("https://{}", self.hosts.first().copied().unwrap_or_default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod testing {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn handle(value: &str) -> bool {
|
||||||
|
(1..=15).contains(&value.len()) && value.bytes().all(|ch| ch.is_ascii_alphanumeric() || ch == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An X-shaped site for the host's own tests.
|
||||||
|
pub static SITE: SiteSpec = SiteSpec {
|
||||||
|
product: "wayBetter for Test",
|
||||||
|
hosts: &["x.com"],
|
||||||
|
runtime_global: "BetterTwttr",
|
||||||
|
accounts: AccountRules {
|
||||||
|
valid_handle: handle,
|
||||||
|
avatar_prefixes: &["https://pbs.twimg.com/"],
|
||||||
|
max_name_chars: 50,
|
||||||
|
max_avatar_len: 512,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::testing::SITE;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn site_origin_is_exact() {
|
||||||
|
assert!(SITE.is_origin(&Url::parse("https://x.com/home").unwrap()));
|
||||||
|
for bad in [
|
||||||
|
"http://x.com/",
|
||||||
|
"https://x.com:444/",
|
||||||
|
"https://user@x.com/",
|
||||||
|
"https://www.x.com/",
|
||||||
|
"https://x.com.evil.test/",
|
||||||
|
] {
|
||||||
|
assert!(!SITE.is_origin(&Url::parse(bad).unwrap()), "{bad}");
|
||||||
|
}
|
||||||
|
assert_eq!(SITE.primary_origin(), "https://x.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn avatars_must_come_from_the_site_cdn() {
|
||||||
|
assert!(SITE.accounts.avatar_allowed("https://pbs.twimg.com/profile_images/1/a.jpg"));
|
||||||
|
assert!(!SITE.accounts.avatar_allowed("https://evil.test/a.jpg"));
|
||||||
|
assert!(!SITE.accounts.avatar_allowed("https://pbs.twimg.com/a b.jpg"));
|
||||||
|
assert!(!SITE.accounts.avatar_allowed(&format!("https://pbs.twimg.com/{}", "a".repeat(600))));
|
||||||
|
}
|
||||||
|
}
|
||||||
227
crates/waybetter-host/src/tabs.rs
Normal file
227
crates/waybetter-host/src/tabs.rs
Normal file
|
|
@ -0,0 +1,227 @@
|
||||||
|
//! Tab payloads between the shell and native code, link routing and tab-chrome validation.
|
||||||
|
//! Everything a tab page sends is validated here before it reaches the shell.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// Shell events emitted by the host.
|
||||||
|
pub const EVENT_TAB_STATE: &str = "tab-state";
|
||||||
|
pub const EVENT_TAB_OPEN: &str = "tab-open";
|
||||||
|
pub const EVENT_TAB_SHORTCUT: &str = "tab-shortcut";
|
||||||
|
pub const EVENT_LINK_DRAG: &str = "link-drag";
|
||||||
|
pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed";
|
||||||
|
|
||||||
|
/// One pane as the shell lays it out (`tabs_sync`).
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct TabLayout {
|
||||||
|
pub id: String,
|
||||||
|
/// Used only when the tab's webview does not exist yet.
|
||||||
|
pub url: String,
|
||||||
|
/// Account profile; fixed per webview (a change recreates the tab's webview).
|
||||||
|
#[serde(default = "default_profile")]
|
||||||
|
pub profile: String,
|
||||||
|
pub x: f64,
|
||||||
|
pub y: f64,
|
||||||
|
pub width: f64,
|
||||||
|
pub height: f64,
|
||||||
|
pub visible: bool,
|
||||||
|
/// Another site pane of the same account already shows the site's navigation rail.
|
||||||
|
#[serde(default)]
|
||||||
|
pub nav_redundant: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_profile() -> String {
|
||||||
|
crate::profiles::DEFAULT_PROFILE.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tab's address-bar state for the shell (`tab-state`); absent fields are unchanged.
|
||||||
|
#[derive(Clone, Serialize, Default, Debug, PartialEq)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct TabState {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub title: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub loading: Option<bool>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub favicon: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub focused: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TabState {
|
||||||
|
/// What a tab reported about itself, bounded. The URL is never the page's claim: callers pass
|
||||||
|
/// the webview's own URL (and only when the page reported a change).
|
||||||
|
pub fn reported(id: String, url: Option<String>, title: Option<String>, favicon: Option<String>, focused: Option<bool>) -> Self {
|
||||||
|
let clip = |value: Option<String>, max: usize| value.filter(|v| v.len() <= max);
|
||||||
|
Self {
|
||||||
|
id,
|
||||||
|
url,
|
||||||
|
title: clip(title, 512),
|
||||||
|
favicon: clip(favicon, 2048).filter(|href| href.starts_with("https://") || href.starts_with("data:image/")),
|
||||||
|
focused,
|
||||||
|
loading: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new-window request from a tab that the shell opens as a tab or a pane (`tab-open`).
|
||||||
|
#[derive(Clone, Serialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OpenRequest {
|
||||||
|
pub url: String,
|
||||||
|
pub from: Option<String>,
|
||||||
|
pub background: bool,
|
||||||
|
/// Open in a pane beside `from` (the "pane" link setting) instead of a tab in its group.
|
||||||
|
pub beside: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only plain http(s) URLs without credentials open in tabs.
|
||||||
|
pub fn parse_web_url(value: &str) -> Result<Url, String> {
|
||||||
|
let url = Url::parse(value).map_err(|_| "VALIDATION: invalid URL")?;
|
||||||
|
if !matches!(url.scheme(), "http" | "https") || !url.username().is_empty() || url.password().is_some() {
|
||||||
|
return Err("VALIDATION: only plain http(s) URLs open in tabs".into());
|
||||||
|
}
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where links to other sites open: beside the pane, in a tab or in the system browser.
|
||||||
|
pub fn valid_external_mode(mode: &str) -> bool {
|
||||||
|
matches!(mode, "pane" | "tab" | "browser")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where clicked site pages open: "same" keeps the site's own in-place navigation.
|
||||||
|
pub fn valid_site_mode(mode: &str) -> bool {
|
||||||
|
matches!(mode, "same" | "pane" | "tab" | "browser")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a new-window request (target=_blank, window.open) opens. "same" only concerns ordinary
|
||||||
|
/// clicks, so an explicit new window on the site still gets a tab.
|
||||||
|
pub fn new_window_mode<'a>(on_site: bool, site_mode: &'a str, external_mode: &'a str) -> &'a str {
|
||||||
|
if on_site {
|
||||||
|
match site_mode {
|
||||||
|
"same" => "tab",
|
||||||
|
mode => mode,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
external_mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Browser shortcuts a tab may forward to the shell while it has keyboard focus.
|
||||||
|
pub const SHORTCUTS: [&str; 15] = [
|
||||||
|
"command-palette", "new-tab", "close-tab", "reopen-tab", "focus-address", "next-tab", "prev-tab", "reload",
|
||||||
|
"back", "forward", "split-right", "split-down", "open-panel", "find", "hard-reload",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn valid_shortcut(shortcut: &str) -> bool {
|
||||||
|
SHORTCUTS.contains(&shortcut)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `tab_link_drag`: `start` carries the dragged link (validated here, bounded), `enter`/`end` none.
|
||||||
|
pub fn link_drag(phase: &str, url: Option<String>) -> Result<Option<String>, String> {
|
||||||
|
if !matches!(phase, "start" | "enter" | "end") {
|
||||||
|
return Err("VALIDATION: unknown drag phase".into());
|
||||||
|
}
|
||||||
|
match (phase, url) {
|
||||||
|
("start", Some(url)) if url.len() <= 4096 => Ok(Some(parse_web_url(&url)?.to_string())),
|
||||||
|
("start", _) => Err("VALIDATION: a link drag needs an http(s) URL".into()),
|
||||||
|
_ => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `back | forward | reload | stop | focus`, the tab actions the shell may request.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum TabAction {
|
||||||
|
Back,
|
||||||
|
Forward,
|
||||||
|
Reload,
|
||||||
|
Stop,
|
||||||
|
Focus,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TabAction {
|
||||||
|
pub fn parse(action: &str) -> Result<Self, String> {
|
||||||
|
Ok(match action {
|
||||||
|
"back" => Self::Back,
|
||||||
|
"forward" => Self::Forward,
|
||||||
|
"reload" => Self::Reload,
|
||||||
|
"stop" => Self::Stop,
|
||||||
|
"focus" => Self::Focus,
|
||||||
|
_ => return Err("VALIDATION: unknown tab action".into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands a JSON value to a member of the page runtime: `window.<global>.<member>.<method>(value)`
|
||||||
|
/// when the runtime exists, else parked in `window.<queue>` for the runtime to pick up at start.
|
||||||
|
/// `json` must be serialized JSON (never page-supplied text).
|
||||||
|
pub fn deliver_script(global: &str, member: &str, method: &str, queue: &str, json: &str) -> String {
|
||||||
|
format!("(()=>{{const v={json};const R=window.{global};if(R&&R.{member})R.{member}.{method}(v);else window.{queue}=v;}})();")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_plain_web_urls_open() {
|
||||||
|
assert!(parse_web_url("https://example.com/a?b").is_ok());
|
||||||
|
for bad in ["javascript:alert(1)", "file:///c:/x", "https://u:p@example.com/", "about:blank", "nope"] {
|
||||||
|
assert!(parse_web_url(bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn link_modes_route_new_windows() {
|
||||||
|
assert!(valid_external_mode("pane") && !valid_external_mode("same"));
|
||||||
|
assert!(valid_site_mode("same") && !valid_site_mode("popup"));
|
||||||
|
assert_eq!(new_window_mode(true, "same", "browser"), "tab");
|
||||||
|
assert_eq!(new_window_mode(true, "pane", "browser"), "pane");
|
||||||
|
assert_eq!(new_window_mode(false, "same", "browser"), "browser");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tab_chrome_input_is_validated() {
|
||||||
|
assert!(valid_shortcut("new-tab") && !valid_shortcut("eval"));
|
||||||
|
assert_eq!(link_drag("start", Some("https://a.test/x".into())).unwrap().as_deref(), Some("https://a.test/x"));
|
||||||
|
assert!(link_drag("start", None).is_err());
|
||||||
|
assert!(link_drag("start", Some(format!("https://a.test/{}", "a".repeat(4096)))).is_err());
|
||||||
|
assert!(link_drag("start", Some("javascript:x".into())).is_err());
|
||||||
|
assert_eq!(link_drag("end", Some("https://a.test/".into())).unwrap(), None);
|
||||||
|
assert!(link_drag("drop", None).is_err());
|
||||||
|
assert_eq!(TabAction::parse("reload").unwrap(), TabAction::Reload);
|
||||||
|
assert!(TabAction::parse("close").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reports_are_bounded() {
|
||||||
|
let state = TabState::reported(
|
||||||
|
"a".into(),
|
||||||
|
None,
|
||||||
|
Some("t".repeat(513)),
|
||||||
|
Some("javascript:alert(1)".into()),
|
||||||
|
Some(true),
|
||||||
|
);
|
||||||
|
assert_eq!((state.title, state.favicon, state.focused), (None, None, Some(true)));
|
||||||
|
let state = TabState::reported("a".into(), None, Some("Home".into()), Some("data:image/png;base64,AA".into()), None);
|
||||||
|
assert_eq!(state.favicon.as_deref(), Some("data:image/png;base64,AA"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layouts_default_to_the_default_profile() {
|
||||||
|
let layout: TabLayout = serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true}"#).unwrap();
|
||||||
|
assert_eq!((layout.profile.as_str(), layout.nav_redundant), ("default", false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delivery_parks_values_until_the_runtime_exists() {
|
||||||
|
assert_eq!(
|
||||||
|
deliver_script("Demo", "pane", "set", "__demoPane", r#"{"redundantNav":true}"#),
|
||||||
|
r#"(()=>{const v={"redundantNav":true};const R=window.Demo;if(R&&R.pane)R.pane.set(v);else window.__demoPane=v;})();"#
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
114
crates/waybetter-host/src/update.rs
Normal file
114
crates/waybetter-host/src/update.rs
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
//! Pure update-scheduling and crash-handshake logic (no Tauri types, so it is unit-tested headless).
|
||||||
|
//! The app owns the updater endpoint, its public key and the manual download URL.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// First check after launch.
|
||||||
|
pub const FIRST_CHECK: Duration = Duration::from_secs(15);
|
||||||
|
/// Base interval between checks; each wait is jittered by +/- `JITTER`.
|
||||||
|
pub const CHECK_INTERVAL: Duration = Duration::from_secs(30 * 60);
|
||||||
|
pub const JITTER: Duration = Duration::from_secs(5 * 60);
|
||||||
|
/// After an update, the shell must call `app_ready` within this long.
|
||||||
|
pub const READY_DEADLINE: Duration = Duration::from_secs(30);
|
||||||
|
/// Launches of an updated version without `app_ready` before automatic apply is disabled.
|
||||||
|
pub const MAX_FAILED_BOOTS: u32 = 2;
|
||||||
|
pub const PENDING_FILE: &str = "update-pending.json";
|
||||||
|
|
||||||
|
/// Wait before the next check: 30 min +/- 5 min, from any 64-bit entropy value.
|
||||||
|
pub fn next_check_delay(entropy: u64) -> Duration {
|
||||||
|
let span = JITTER.as_secs() * 2 + 1;
|
||||||
|
CHECK_INTERVAL - JITTER + Duration::from_secs(entropy % span)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the shell's titlebar chip reflects. Only `Ready` is shown prominently.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||||
|
#[serde(tag = "state", rename_all = "camelCase")]
|
||||||
|
pub enum UpdateStatus {
|
||||||
|
Idle,
|
||||||
|
Checking,
|
||||||
|
UpToDate,
|
||||||
|
Downloading { version: String },
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Ready { version: String, notes: String },
|
||||||
|
Installing { version: String },
|
||||||
|
Error { message: String },
|
||||||
|
/// The last update failed to start repeatedly; automatic apply is off.
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Problem { download_url: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Written just before installing, cleared by `app_ready` in the new version.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct PendingUpdate {
|
||||||
|
pub version: String,
|
||||||
|
/// Launches of `version` that have not (yet) confirmed `app_ready`.
|
||||||
|
pub boots: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct BootDecision {
|
||||||
|
/// Marker to persist (`None` deletes it).
|
||||||
|
pub marker: Option<PendingUpdate>,
|
||||||
|
/// Automatic apply is disabled and the shell is told to offer a manual download.
|
||||||
|
pub problem: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called at every launch with the marker left on disk.
|
||||||
|
pub fn on_boot(pending: Option<PendingUpdate>, current_version: &str) -> BootDecision {
|
||||||
|
match pending {
|
||||||
|
// The installer never replaced the binary (or it was a different release): forget it.
|
||||||
|
Some(p) if p.version != current_version => BootDecision { marker: None, problem: false },
|
||||||
|
Some(p) => {
|
||||||
|
let boots = p.boots.saturating_add(1);
|
||||||
|
BootDecision {
|
||||||
|
// `boots - 1` earlier launches of this version never reached `app_ready`.
|
||||||
|
problem: boots > MAX_FAILED_BOOTS,
|
||||||
|
marker: Some(PendingUpdate { version: p.version, boots }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => BootDecision { marker: None, problem: false },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delay_stays_within_jitter() {
|
||||||
|
for entropy in [0, 1, 300, 600, 601, u64::MAX] {
|
||||||
|
let delay = next_check_delay(entropy);
|
||||||
|
assert!(delay >= Duration::from_secs(25 * 60) && delay <= Duration::from_secs(35 * 60));
|
||||||
|
}
|
||||||
|
assert_eq!(next_check_delay(0), Duration::from_secs(25 * 60));
|
||||||
|
assert_eq!(next_check_delay(600), Duration::from_secs(35 * 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn handshake_disables_apply_after_two_failed_boots() {
|
||||||
|
let pending = |boots| Some(PendingUpdate { version: "0.3.0".into(), boots });
|
||||||
|
// First launch of the new version: not a problem yet.
|
||||||
|
assert_eq!(on_boot(pending(0), "0.3.0"), BootDecision { marker: pending(1), problem: false });
|
||||||
|
// Second launch without app_ready: one failure.
|
||||||
|
assert!(!on_boot(pending(1), "0.3.0").problem);
|
||||||
|
// Third launch: two failures in a row.
|
||||||
|
assert!(on_boot(pending(2), "0.3.0").problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn handshake_forgets_marker_for_other_versions() {
|
||||||
|
let pending = Some(PendingUpdate { version: "0.3.0".into(), boots: 5 });
|
||||||
|
assert_eq!(on_boot(pending, "0.2.0"), BootDecision { marker: None, problem: false });
|
||||||
|
assert_eq!(on_boot(None, "0.2.0"), BootDecision { marker: None, problem: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_serializes_for_the_shell() {
|
||||||
|
let json = serde_json::to_value(UpdateStatus::Ready { version: "0.3.0".into(), notes: String::new() }).unwrap();
|
||||||
|
assert_eq!(json, serde_json::json!({ "state": "ready", "version": "0.3.0", "notes": "" }));
|
||||||
|
let json = serde_json::to_value(UpdateStatus::Problem { download_url: "https://a.test/".into() }).unwrap();
|
||||||
|
assert_eq!(json, serde_json::json!({ "state": "problem", "downloadUrl": "https://a.test/" }));
|
||||||
|
}
|
||||||
|
}
|
||||||
1
crates/waybetter-host/tests/fixtures/hotfix-test.json
vendored
Normal file
1
crates/waybetter-host/tests/fixtures/hotfix-test.json
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
{"version":7,"expires":"2099-01-01T00:00:00Z","minNative":"0.1.0","selectors":{"composer":"[data-testid=\"tweetTextarea_0\"]"},"flags":{"hideGrok":true}}
|
||||||
1
crates/waybetter-host/tests/fixtures/hotfix-test.json.sig
vendored
Normal file
1
crates/waybetter-host/tests/fixtures/hotfix-test.json.sig
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdjlNRUFJZks1emZIOENOOWRkQ0JpUDYrTVkwU2NHU0hxUmV6Wk1ZamZsUkE4azNPSG94TlBETzZvK04zWkJ4SFRrRTYwSnlwT2liU3I4TFZERzNjcXEzdG41dnRTTHdBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwNDY3Mzc1CWZpbGU6aG90Zml4LWZpeHR1cmUuanNvbgovS3lPaGUxQ2tnNW03UmdseVdCdUt1RjhucHJRdGhjdFQ1Q1VkUGpvU2ZZR1MrS1BsQWVzSUlWQ1lVdDdZaUJGdFdSNitXZjNJNU9vZzAyT2hEYXNCUT09Cg==
|
||||||
1
crates/waybetter-host/tests/fixtures/hotfix-test.key.pub
vendored
Normal file
1
crates/waybetter-host/tests/fixtures/hotfix-test.key.pub
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IENEQjlGMjIxMDBDMUY0RUYKUldUdjlNRUFJZks1elEyL29kcGxPUFZjNm50U1BpTzExb0NBZW0xUWYvVER3Z2dJNXJTTXd6dFEK
|
||||||
63
crates/waybetter-host/tests/hotfix.rs
Normal file
63
crates/waybetter-host/tests/hotfix.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
|
use waybetter_host::hotfix::{accept, minisign_text, script, validate, verify, Outcome};
|
||||||
|
|
||||||
|
// Throwaway test key pair (not a production hotfix key); fixture signed with `tauri signer sign`.
|
||||||
|
const PUBKEY: &str = include_str!("fixtures/hotfix-test.key.pub");
|
||||||
|
const BODY: &[u8] = include_bytes!("fixtures/hotfix-test.json");
|
||||||
|
const SIG: &str = include_str!("fixtures/hotfix-test.json.sig");
|
||||||
|
|
||||||
|
fn now() -> chrono::DateTime<Utc> {
|
||||||
|
Utc.with_ymd_and_hms(2026, 9, 27, 12, 0, 0).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accepts_a_signed_hotfix() {
|
||||||
|
let Outcome::Accepted(hotfix) = accept(PUBKEY, BODY, SIG, now(), "0.2.0", None).unwrap() else {
|
||||||
|
panic!("expected accepted");
|
||||||
|
};
|
||||||
|
assert_eq!(hotfix.version, 7);
|
||||||
|
assert_eq!(hotfix.flags["hideGrok"], serde_json::json!(true));
|
||||||
|
assert!(minisign_text(PUBKEY).unwrap().contains("minisign public key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_tampered_body_and_garbage() {
|
||||||
|
let tampered = String::from_utf8(BODY.to_vec()).unwrap().replace("\"version\":7", "\"version\":8");
|
||||||
|
assert!(verify(PUBKEY, tampered.as_bytes(), SIG).is_err());
|
||||||
|
assert!(verify(PUBKEY, BODY, "garbage").is_err());
|
||||||
|
assert!(verify("garbage", BODY, SIG).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn monotonic_versions() {
|
||||||
|
assert_eq!(accept(PUBKEY, BODY, SIG, now(), "0.2.0", Some(7)).unwrap(), Outcome::Unchanged);
|
||||||
|
assert!(accept(PUBKEY, BODY, SIG, now(), "0.2.0", Some(8)).is_err());
|
||||||
|
assert!(matches!(accept(PUBKEY, BODY, SIG, now(), "0.2.0", Some(6)).unwrap(), Outcome::Accepted(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expiry_and_min_native() {
|
||||||
|
let late = Utc.with_ymd_and_hms(2099, 1, 1, 0, 0, 1).unwrap();
|
||||||
|
assert!(accept(PUBKEY, BODY, SIG, late, "0.2.0", None).is_err());
|
||||||
|
assert!(accept(PUBKEY, BODY, SIG, now(), "0.0.9", None).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn schema_rejects_code_like_or_unknown_content() {
|
||||||
|
let base = |extra: &str| format!(r#"{{"version":1,"expires":"2099-01-01T00:00:00Z","minNative":"0.1.0"{extra}}}"#);
|
||||||
|
assert!(validate(base("").as_bytes(), now(), "0.2.0").is_ok());
|
||||||
|
assert!(validate(base(r#","script":"alert(1)""#).as_bytes(), now(), "0.2.0").is_err());
|
||||||
|
assert!(validate(base(r#","flags":{"x":{"nested":1}}"#).as_bytes(), now(), "0.2.0").is_err());
|
||||||
|
assert!(validate(base(r#","selectors":{"bad key!":"div"}"#).as_bytes(), now(), "0.2.0").is_err());
|
||||||
|
assert!(validate(base(r#","selectors":{"k":""}"#).as_bytes(), now(), "0.2.0").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn script_delivers_data_only_under_the_given_names() {
|
||||||
|
let Outcome::Accepted(hotfix) = accept(PUBKEY, BODY, SIG, now(), "0.2.0", None).unwrap() else { panic!() };
|
||||||
|
let script = script(&hotfix, "__demoHotfix", "demo-hotfix");
|
||||||
|
assert!(script.starts_with("(()=>{const h=JSON.parse(\""));
|
||||||
|
assert!(script.contains("window.__demoHotfix=h") && script.contains("new CustomEvent('demo-hotfix')"));
|
||||||
|
// The selector's quotes are escaped inside a JSON string literal, never raw JS.
|
||||||
|
assert!(!script.contains("[data-testid=\"tweetTextarea_0\"]"));
|
||||||
|
}
|
||||||
29
package.json
Normal file
29
package.json
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
{
|
||||||
|
"name": "waybetter",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"type": "module",
|
||||||
|
"description": "wayBetter: a framework for desktop apps that extend one website in place (tabs, splits, accounts, plugins, themes).",
|
||||||
|
"packageManager": "bun@1.4.2",
|
||||||
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc -p tsconfig.json",
|
||||||
|
"test": "bun run test:ts && bun run test:rust",
|
||||||
|
"test:ts": "node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts",
|
||||||
|
"test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked",
|
||||||
|
"check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features tauri",
|
||||||
|
"build": "bun run typecheck && cargo build --manifest-path crates/waybetter-host/Cargo.toml --locked",
|
||||||
|
"check": "bun run typecheck && bun run test"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.0.0",
|
||||||
|
"typescript": "^5.9.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.0.0",
|
||||||
|
"bun": ">=1.4.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
11
packages/runtime/package.json
Normal file
11
packages/runtime/package.json
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
{
|
||||||
|
"name": "@waybetter/runtime",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"type": "module",
|
||||||
|
"description": "wayBetter page runtime core: shared DOM/request hubs, plugin API core, theme color model, rail hiding, link routing, account reporting. No dependencies.",
|
||||||
|
"exports": {
|
||||||
|
"./*": "./src/*"
|
||||||
|
}
|
||||||
|
}
|
||||||
35
packages/runtime/src/accountReport.ts
Normal file
35
packages/runtime/src/accountReport.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
// Tells the app which account is signed in inside this tab's profile, so the account switcher
|
||||||
|
// lists real logins (avatar, name, handle) instead of hand-named slots. Read from the site's own
|
||||||
|
// UI, which the site renders anyway; nothing is requested. Only a change is reported (`tab_report`),
|
||||||
|
// and native code accepts it only from a webview that is on the site, for that webview's own profile.
|
||||||
|
|
||||||
|
import { watchDom } from './domHub.ts';
|
||||||
|
|
||||||
|
export type SeenAccount = { handle: string; name: string; avatar: string | null };
|
||||||
|
export type AccountReport = { account: SeenAccount } | { signedOut: true };
|
||||||
|
|
||||||
|
export type AccountSite = {
|
||||||
|
/** The account the site's UI shows, or null when there is none (yet). Pure over the DOM. */
|
||||||
|
read(root: ParentNode): SeenAccount | null;
|
||||||
|
/** The site shows its signed-out page. */
|
||||||
|
signedOut(root: ParentNode): boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Invoke = (command: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||||
|
|
||||||
|
export function installAccountReport(win: Window, site: AccountSite, invoke?: Invoke) {
|
||||||
|
if (!invoke) return { dispose() {} };
|
||||||
|
let last = '';
|
||||||
|
const send = (report: AccountReport) => {
|
||||||
|
const key = JSON.stringify(report);
|
||||||
|
if (key === last) return;
|
||||||
|
last = key;
|
||||||
|
invoke('tab_report', { report }).catch(() => { last = ''; });
|
||||||
|
};
|
||||||
|
const check = () => {
|
||||||
|
const account = site.read(win.document);
|
||||||
|
if (account) send({ account });
|
||||||
|
else if (site.signedOut(win.document)) send({ signedOut: true });
|
||||||
|
};
|
||||||
|
return watchDom(win as unknown as Parameters<typeof watchDom>[0], check);
|
||||||
|
}
|
||||||
146
packages/runtime/src/domHub.ts
Normal file
146
packages/runtime/src/domHub.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
// One MutationObserver and one animation frame per page for every DOM feature of a site runtime.
|
||||||
|
// Without it, each feature (nav items, tweaks, buttons, fixes, viewers) observes the whole <body>
|
||||||
|
// subtree and schedules its own frame, so every mutation the site makes costs one callback and one
|
||||||
|
// frame of scans per feature. Here a mutation marks the features interested in its kind (child list,
|
||||||
|
// text, a named attribute) and they run together in the next frame: layout readers first, then DOM
|
||||||
|
// writers, so a reader never forces a synchronous layout behind another feature's write. Features
|
||||||
|
// marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat.
|
||||||
|
|
||||||
|
export type DomWatch = {
|
||||||
|
/** Also run on text changes (characterData). */
|
||||||
|
characterData?: boolean;
|
||||||
|
/** Also run when one of these attributes changes. */
|
||||||
|
attributes?: string[];
|
||||||
|
/** Skip on the site's heavy pages (`DomHubConfig.heavyPath`). */
|
||||||
|
offOnHeavy?: boolean;
|
||||||
|
/** 'read' features (layout reads) run before 'write' features (the default) in a frame. */
|
||||||
|
phase?: 'read' | 'write';
|
||||||
|
};
|
||||||
|
export type DomWatchHandle = { schedule(): void; dispose(): void };
|
||||||
|
|
||||||
|
export type DomHubConfig = {
|
||||||
|
/** Console prefix for feature failures, e.g. "wayBetter for X". */
|
||||||
|
label: string;
|
||||||
|
/** Pathnames where `offOnHeavy` features are skipped; null = none. */
|
||||||
|
heavyPath: RegExp | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DomWindow = {
|
||||||
|
document: Document;
|
||||||
|
location: { pathname: string };
|
||||||
|
MutationObserver: typeof MutationObserver;
|
||||||
|
requestAnimationFrame(callback: FrameRequestCallback): number;
|
||||||
|
};
|
||||||
|
type Sub = { run: () => void; opts: DomWatch; pending: boolean };
|
||||||
|
type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void };
|
||||||
|
|
||||||
|
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null };
|
||||||
|
const hubs = new WeakMap<object, Hub>();
|
||||||
|
|
||||||
|
/** Set once by the site adapter, before features register. */
|
||||||
|
export function configureDomHub(next: Partial<DomHubConfig>): void {
|
||||||
|
Object.assign(config, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isHeavyPath(pathname: string): boolean {
|
||||||
|
return !!config.heavyPath && config.heavyPath.test(pathname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hubFor(win: DomWindow): Hub {
|
||||||
|
const existing = hubs.get(win);
|
||||||
|
if (existing) return existing;
|
||||||
|
const doc = win.document;
|
||||||
|
let frameRequested = false;
|
||||||
|
let observer: MutationObserver | null = null;
|
||||||
|
let observing = '';
|
||||||
|
|
||||||
|
const frame = () => {
|
||||||
|
frameRequested = false;
|
||||||
|
const heavy = isHeavyPath(win.location.pathname ?? '');
|
||||||
|
for (const phase of ['read', 'write'] as const) {
|
||||||
|
for (const sub of hub.subs.slice()) {
|
||||||
|
if (!sub.pending || (sub.opts.phase ?? 'write') !== phase) continue;
|
||||||
|
sub.pending = false;
|
||||||
|
if (heavy && sub.opts.offOnHeavy) continue;
|
||||||
|
try { sub.run(); } catch (error) { console.error(`[${config.label}] DOM feature failed`, error); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onRecords = (records: MutationRecord[]) => {
|
||||||
|
let childList = false;
|
||||||
|
let characterData = false;
|
||||||
|
let attributes: Set<string> | null = null;
|
||||||
|
const known = Array.isArray(records) && records.length > 0;
|
||||||
|
if (known) {
|
||||||
|
for (const record of records) {
|
||||||
|
if (record.type === 'childList') childList = true;
|
||||||
|
else if (record.type === 'characterData') characterData = true;
|
||||||
|
else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const sub of hub.subs) {
|
||||||
|
if (!known || childList || (characterData && sub.opts.characterData)
|
||||||
|
|| (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const start = () => {
|
||||||
|
if (!doc.body || !hub.subs.length) return;
|
||||||
|
const characterData = hub.subs.some(sub => sub.opts.characterData);
|
||||||
|
const filter = [...new Set(hub.subs.flatMap(sub => sub.opts.attributes ?? []))].sort();
|
||||||
|
const key = `${characterData}|${filter.join(',')}`;
|
||||||
|
if (observer && observing === key) return;
|
||||||
|
observer ??= new win.MutationObserver(onRecords);
|
||||||
|
observing = key;
|
||||||
|
// Re-observing the same node replaces its options.
|
||||||
|
observer.observe(doc.body, {
|
||||||
|
childList: true, subtree: true,
|
||||||
|
...(characterData ? { characterData: true } : {}),
|
||||||
|
...(filter.length ? { attributes: true, attributeFilter: filter } : {}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const hub: Hub = {
|
||||||
|
subs: [],
|
||||||
|
mark(sub) {
|
||||||
|
sub.pending = true;
|
||||||
|
if (!frameRequested) { frameRequested = true; win.requestAnimationFrame(frame); }
|
||||||
|
},
|
||||||
|
refresh() {
|
||||||
|
if (!hub.subs.length) {
|
||||||
|
observer?.disconnect();
|
||||||
|
observer = null;
|
||||||
|
observing = '';
|
||||||
|
doc.removeEventListener('DOMContentLoaded', start);
|
||||||
|
hubs.delete(win);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (doc.body) start();
|
||||||
|
else doc.addEventListener('DOMContentLoaded', start, { once: true });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
hubs.set(win, hub);
|
||||||
|
return hub;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `run` in the next animation frame after body mutations of the watched kinds (child list
|
||||||
|
* always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one
|
||||||
|
* frame run it once.
|
||||||
|
*/
|
||||||
|
export function watchDom(win: DomWindow, run: () => void, opts: DomWatch = {}): DomWatchHandle {
|
||||||
|
const hub = hubFor(win);
|
||||||
|
const sub: Sub = { run, opts, pending: false };
|
||||||
|
hub.subs.push(sub);
|
||||||
|
hub.refresh();
|
||||||
|
let active = true;
|
||||||
|
return {
|
||||||
|
schedule: () => { if (active) hub.mark(sub); },
|
||||||
|
dispose() {
|
||||||
|
if (!active) return;
|
||||||
|
active = false;
|
||||||
|
const index = hub.subs.indexOf(sub);
|
||||||
|
if (index >= 0) hub.subs.splice(index, 1);
|
||||||
|
hub.refresh();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
41
packages/runtime/src/linkRouting.ts
Normal file
41
packages/runtime/src/linkRouting.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
// "Links to site pages" setting: when it is not "same", a plain click on one of the site's own pages
|
||||||
|
// (a post, a profile, a channel, ...) opens that page beside the pane, in a new tab or in the system
|
||||||
|
// browser instead of replacing what you are reading. The click becomes an ordinary new-window
|
||||||
|
// request; native code (`new_window_mode`) decides where it opens. Which clicks count is the site
|
||||||
|
// adapter's `clickedUrl`; everything else (navigation, tabs, menus, buttons) is never touched.
|
||||||
|
|
||||||
|
export type LinkMode = 'same' | 'pane' | 'tab' | 'browser';
|
||||||
|
export type LinkRoutingHandle = { configure(value: unknown): void; dispose(): void };
|
||||||
|
|
||||||
|
export type LinkSite = {
|
||||||
|
/** The site page a click on `target` would open in place, when it is one to divert; else null. */
|
||||||
|
clickedUrl(target: Element | null, location: Location): string | null;
|
||||||
|
/** The key of the mode in the native `configure` payload (`{ [configKey]: mode }`). */
|
||||||
|
configKey: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const LINK_MODES: readonly LinkMode[] = ['same', 'pane', 'tab', 'browser'];
|
||||||
|
|
||||||
|
export function installLinkRouting(win: Window, site: LinkSite): LinkRoutingHandle {
|
||||||
|
let mode: LinkMode = 'same';
|
||||||
|
const onClick = (event: MouseEvent) => {
|
||||||
|
if (mode === 'same' || event.button !== 0 || event.defaultPrevented) return;
|
||||||
|
// Modified clicks keep the site's own meaning (Ctrl/Cmd+click already opens a new tab).
|
||||||
|
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||||
|
if (win.getSelection?.()?.toString().trim()) return;
|
||||||
|
const url = site.clickedUrl(event.target instanceof Element ? event.target : null, win.location);
|
||||||
|
if (!url) return;
|
||||||
|
// Before the site's own handlers (frameworks listen below window): the in-place navigation never starts.
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
win.open(url, '_blank', 'noopener');
|
||||||
|
};
|
||||||
|
win.addEventListener('click', onClick, true);
|
||||||
|
return {
|
||||||
|
configure(value) {
|
||||||
|
const next = (value as Record<string, unknown> | null)?.[site.configKey];
|
||||||
|
if (typeof next === 'string' && (LINK_MODES as readonly string[]).includes(next)) mode = next as LinkMode;
|
||||||
|
},
|
||||||
|
dispose() { win.removeEventListener('click', onClick, true); },
|
||||||
|
};
|
||||||
|
}
|
||||||
252
packages/runtime/src/netHub.ts
Normal file
252
packages/runtime/src/netHub.ts
Normal file
|
|
@ -0,0 +1,252 @@
|
||||||
|
// One shared fetch/XHR hook per window for everything a site runtime does with the site's own
|
||||||
|
// requests: URL rewrites, gates (e.g. serializing racing mutations) and passive JSON taps. Each
|
||||||
|
// feature registers a stage instead of stacking its own wrapper. A request whose URL contains none
|
||||||
|
// of the site's API marks (images, video, WASM, scripts, telemetry) takes one substring check and
|
||||||
|
// goes straight to the wrapped fetch, and a tapped response is cloned, read and JSON-parsed once for
|
||||||
|
// all taps. Semantics are unchanged: the page gets the very promise (and Response) the inner fetch
|
||||||
|
// returned unless a gate answers a request itself, rejections and aborts pass through, and nothing
|
||||||
|
// here ever issues a request of its own.
|
||||||
|
|
||||||
|
/** `input`/`init` are fetch's arguments; returns the rewritten URL, or null to leave the request alone. */
|
||||||
|
export type Rewrite = (input: unknown, init: RequestInit | undefined) => string | null;
|
||||||
|
/** Returns null when the request is not the gate's; otherwise the promise the page gets instead of `send()`. */
|
||||||
|
export type Gate = (input: unknown, init: RequestInit | undefined, send: () => Promise<Response>) => Promise<Response> | null;
|
||||||
|
export type Tap = { match(url: string): boolean; maxBytes: number; onJson(body: unknown): void };
|
||||||
|
/** XHR counterpart of `Gate` (many web clients still send their API calls with XMLHttpRequest). */
|
||||||
|
export type XhrGate = {
|
||||||
|
/**
|
||||||
|
* The page (re)opens this XHR object; called before the native `open`. Returning a string opens
|
||||||
|
* that URL instead (a request rewrite, like `Rewrite` for fetch).
|
||||||
|
*/
|
||||||
|
open?(xhr: XMLHttpRequest, request: { method: string; url: string }): string | void;
|
||||||
|
/**
|
||||||
|
* The page calls `send(body)` on an API (or XHR-mark) request. Returns true when the gate took it
|
||||||
|
* over: it then calls `sendNative()` itself (now or later; `sendNative(body)` sends that body
|
||||||
|
* instead of the page's) or completes the XHR on its own.
|
||||||
|
*/
|
||||||
|
send(xhr: XMLHttpRequest, request: { method: string; url: string }, body: unknown, sendNative: (...body: [] | [unknown]) => void): boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NetHubConfig = {
|
||||||
|
/** URL substrings of the site's API calls; only these reach rewrites, gates and taps. */
|
||||||
|
apiMarks: string[];
|
||||||
|
/** Extra URL substrings that reach XHR gates only (e.g. a chunked media upload endpoint). */
|
||||||
|
xhrMarks: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type HubWindow = {
|
||||||
|
fetch: typeof fetch;
|
||||||
|
XMLHttpRequest?: typeof XMLHttpRequest;
|
||||||
|
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Hub = {
|
||||||
|
rewrites: Rewrite[];
|
||||||
|
gates: Gate[];
|
||||||
|
taps: Tap[];
|
||||||
|
xhrGates: XhrGate[];
|
||||||
|
hooked(): boolean;
|
||||||
|
add<T>(list: T[], item: T): () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const config: NetHubConfig = { apiMarks: [], xhrMarks: [] };
|
||||||
|
const hubs = new WeakMap<object, Hub>();
|
||||||
|
|
||||||
|
/** Set once by the site adapter, before stages register. */
|
||||||
|
export function configureNetHub(next: Partial<NetHubConfig>): void {
|
||||||
|
if (next.apiMarks) config.apiMarks = [...next.apiMarks];
|
||||||
|
if (next.xhrMarks) config.xhrMarks = [...next.xhrMarks];
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasMark = (url: string, marks: string[]) => {
|
||||||
|
for (const mark of marks) if (url.includes(mark)) return true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Whether `url` is one of the site's API calls (plain substring checks, no URL parsing). */
|
||||||
|
export function isApiUrl(url: string): boolean {
|
||||||
|
return hasMark(url, config.apiMarks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The request URL as given (string, URL or Request), without parsing it. */
|
||||||
|
export function rawUrl(input: unknown): string {
|
||||||
|
try {
|
||||||
|
if (typeof input === 'string') return input;
|
||||||
|
if (input instanceof URL) return input.href;
|
||||||
|
if (input && typeof (input as Request).url === 'string') return (input as Request).url;
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hubFor(target: HubWindow): Hub {
|
||||||
|
const existing = hubs.get(target);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
let inner: typeof fetch | null = null;
|
||||||
|
let wrapper: typeof fetch | null = null;
|
||||||
|
const proto: XMLHttpRequest | undefined = target.XMLHttpRequest?.prototype;
|
||||||
|
let originalOpen: XMLHttpRequest['open'] | undefined;
|
||||||
|
let openWrapper: XMLHttpRequest['open'] | undefined;
|
||||||
|
let originalSend: XMLHttpRequest['send'] | undefined;
|
||||||
|
let sendWrapper: XMLHttpRequest['send'] | undefined;
|
||||||
|
const opened = new WeakMap<XMLHttpRequest, { method: string; url: string }>();
|
||||||
|
|
||||||
|
const later = (run: () => void) => {
|
||||||
|
// Parsing a large body is the expensive part; keep it out of the page's own response handling.
|
||||||
|
const idle = target.requestIdleCallback;
|
||||||
|
if (typeof idle === 'function') { try { idle.call(target, run, { timeout: 200 }); return; } catch { /* fall through */ } }
|
||||||
|
run();
|
||||||
|
};
|
||||||
|
const deliver = (taps: Tap[], text: string) => {
|
||||||
|
const live = taps.filter(tap => hub.taps.includes(tap) && text.length <= tap.maxBytes);
|
||||||
|
if (!live.length) return;
|
||||||
|
later(() => {
|
||||||
|
let body: unknown;
|
||||||
|
try { body = JSON.parse(text); } catch { return; }
|
||||||
|
for (const tap of live) {
|
||||||
|
if (!hub.taps.includes(tap)) continue;
|
||||||
|
try { tap.onJson(body); } catch { /* A consumer failure never reaches the page. */ }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const matchingTaps = (url: string) => hub.taps.length ? hub.taps.filter(tap => { try { return tap.match(url); } catch { return false; } }) : [];
|
||||||
|
|
||||||
|
const fetchWrapper = function (this: unknown, ...args: Parameters<typeof fetch>): Promise<Response> {
|
||||||
|
const url = rawUrl(args[0]);
|
||||||
|
if (!hasMark(url, config.apiMarks)) return Reflect.apply(inner!, this, args) as Promise<Response>;
|
||||||
|
let [input, init] = args;
|
||||||
|
for (const rewrite of hub.rewrites) {
|
||||||
|
const next = rewrite(input, init);
|
||||||
|
if (next != null) input = next;
|
||||||
|
}
|
||||||
|
const call = input === args[0] ? args : [input, init] as Parameters<typeof fetch>;
|
||||||
|
const send = () => Reflect.apply(inner!, this, call) as Promise<Response>;
|
||||||
|
let result: Promise<Response> | null = null;
|
||||||
|
for (const gate of hub.gates) {
|
||||||
|
result = gate(input, init, send);
|
||||||
|
if (result) break;
|
||||||
|
}
|
||||||
|
result ??= send();
|
||||||
|
const taps = matchingTaps(rawUrl(input));
|
||||||
|
if (taps.length) {
|
||||||
|
result.then(response => {
|
||||||
|
if (!response.ok) return;
|
||||||
|
const length = Number(response.headers.get('content-length') ?? 0);
|
||||||
|
if (!taps.some(tap => hub.taps.includes(tap) && length <= tap.maxBytes)) return;
|
||||||
|
return response.clone().text().then(text => deliver(taps, text));
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
const onLoad = function (this: XMLHttpRequest, taps: Tap[]) {
|
||||||
|
try {
|
||||||
|
if (this.status < 200 || this.status >= 300) return;
|
||||||
|
if (this.responseType === '' || this.responseType === 'text') deliver(taps, this.responseText);
|
||||||
|
else if (this.responseType === 'json' && this.response) {
|
||||||
|
const body = this.response;
|
||||||
|
for (const tap of taps) if (hub.taps.includes(tap)) { try { tap.onJson(body); } catch { /* ignore */ } }
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
const install = () => {
|
||||||
|
if (!wrapper && (hub.rewrites.length || hub.gates.length || hub.taps.length)) {
|
||||||
|
inner = target.fetch;
|
||||||
|
try { target.fetch = fetchWrapper; wrapper = fetchWrapper; } catch { /* Readonly runtime. */ }
|
||||||
|
}
|
||||||
|
if (!proto) return;
|
||||||
|
if (!openWrapper && (hub.taps.length || hub.xhrGates.length)) {
|
||||||
|
const open = originalOpen = proto.open;
|
||||||
|
const candidate = function (this: XMLHttpRequest, ...args: unknown[]) {
|
||||||
|
try {
|
||||||
|
let url = String(args[1]);
|
||||||
|
if (hub.xhrGates.length) {
|
||||||
|
const method = String(args[0]).toUpperCase();
|
||||||
|
for (const gate of hub.xhrGates) {
|
||||||
|
const next = gate.open?.(this, { method, url });
|
||||||
|
if (typeof next === 'string') { url = next; args = [args[0], next, ...args.slice(2)]; }
|
||||||
|
}
|
||||||
|
opened.set(this, { method, url });
|
||||||
|
} else opened.delete(this);
|
||||||
|
if (hasMark(url, config.apiMarks)) {
|
||||||
|
const taps = matchingTaps(url);
|
||||||
|
if (taps.length) this.addEventListener('load', function (this: XMLHttpRequest) { onLoad.call(this, taps); }, { once: true });
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return Reflect.apply(open, this, args);
|
||||||
|
} as XMLHttpRequest['open'];
|
||||||
|
try { proto.open = candidate; openWrapper = candidate; } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
if (!sendWrapper && hub.xhrGates.length) {
|
||||||
|
const send = originalSend = proto.send;
|
||||||
|
const candidate: XMLHttpRequest['send'] = function (this: XMLHttpRequest, ...args) {
|
||||||
|
const request = opened.get(this);
|
||||||
|
if (request && (hasMark(request.url, config.apiMarks) || hasMark(request.url, config.xhrMarks))) {
|
||||||
|
const sendNative = (...body: [] | [unknown]) => { Reflect.apply(send, this, body.length ? body : args); };
|
||||||
|
for (const gate of hub.xhrGates) if (gate.send(this, request, args[0], sendNative)) return;
|
||||||
|
}
|
||||||
|
return Reflect.apply(send, this, args);
|
||||||
|
};
|
||||||
|
try { proto.send = candidate; sendWrapper = candidate; } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const uninstall = () => {
|
||||||
|
// Anyone still holding a wrapper (another script wrapped on top) gets plain pass-through.
|
||||||
|
if (proto && openWrapper && !hub.taps.length && !hub.xhrGates.length && proto.open === openWrapper) {
|
||||||
|
proto.open = originalOpen!;
|
||||||
|
openWrapper = undefined;
|
||||||
|
}
|
||||||
|
if (proto && sendWrapper && !hub.xhrGates.length && proto.send === sendWrapper) {
|
||||||
|
proto.send = originalSend!;
|
||||||
|
sendWrapper = undefined;
|
||||||
|
}
|
||||||
|
if (!hub.rewrites.length && !hub.gates.length && !hub.taps.length && wrapper) {
|
||||||
|
if (target.fetch === wrapper) { target.fetch = inner!; wrapper = null; }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const hub: Hub = {
|
||||||
|
rewrites: [],
|
||||||
|
gates: [],
|
||||||
|
taps: [],
|
||||||
|
xhrGates: [],
|
||||||
|
hooked: () => wrapper !== null && target.fetch === wrapper,
|
||||||
|
add(list, item) {
|
||||||
|
list.push(item);
|
||||||
|
install();
|
||||||
|
let removed = false;
|
||||||
|
return () => {
|
||||||
|
if (removed) return;
|
||||||
|
removed = true;
|
||||||
|
const index = list.indexOf(item);
|
||||||
|
if (index >= 0) list.splice(index, 1);
|
||||||
|
uninstall();
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
hubs.set(target, hub);
|
||||||
|
return hub;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the shared hook is installed as `target.fetch` (for callers that report `installed`). */
|
||||||
|
export function fetchHooked(target: HubWindow): boolean {
|
||||||
|
return hubs.get(target)?.hooked() ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addRewrite(target: HubWindow, rewrite: Rewrite): () => void {
|
||||||
|
const hub = hubFor(target);
|
||||||
|
return hub.add(hub.rewrites, rewrite);
|
||||||
|
}
|
||||||
|
export function addGate(target: HubWindow, gate: Gate): () => void {
|
||||||
|
const hub = hubFor(target);
|
||||||
|
return hub.add(hub.gates, gate);
|
||||||
|
}
|
||||||
|
export function addTap(target: HubWindow, tap: Tap): () => void {
|
||||||
|
const hub = hubFor(target);
|
||||||
|
return hub.add(hub.taps, tap);
|
||||||
|
}
|
||||||
|
export function addXhrGate(target: HubWindow, gate: XhrGate): () => void {
|
||||||
|
const hub = hubFor(target);
|
||||||
|
return hub.add(hub.xhrGates, gate);
|
||||||
|
}
|
||||||
313
packages/runtime/src/paneNav.ts
Normal file
313
packages/runtime/src/paneNav.ts
Normal file
|
|
@ -0,0 +1,313 @@
|
||||||
|
// Split view: site panes of one account side by side each draw the site's whole navigation rail.
|
||||||
|
// Native code tells every site pane whether another pane already shows it (`redundantNav`, the
|
||||||
|
// leftmost pane of that account wins). With the feature on, such a pane lifts the rail out of the
|
||||||
|
// layout (the content re-centers in the freed width), parks it off-screen, and slides it back in
|
||||||
|
// over the page while the pointer rests on the pane's left edge. Which element is the rail is the
|
||||||
|
// site adapter's `RailSite`.
|
||||||
|
|
||||||
|
import { watchDom, type DomWatchHandle } from './domHub.ts';
|
||||||
|
|
||||||
|
export type PaneNavHandle = { set(state: unknown): void; setEnabled(enabled: boolean): void; dispose(): void };
|
||||||
|
export type RailPaint = { width: number; background: string; line: string; accent: string; rtl: boolean };
|
||||||
|
|
||||||
|
export type RailSite = {
|
||||||
|
/** Prefix of the ids/attributes this module owns (`<prefix>-pane-nav`, `data-<prefix>-pane-nav`, ...). */
|
||||||
|
prefix: string;
|
||||||
|
/** The site's classic rail element. */
|
||||||
|
rail: string;
|
||||||
|
/** A link inside the rail, used to find it when the classic rail element is absent. */
|
||||||
|
anchor: string;
|
||||||
|
/** The content column that re-centers once the rail is parked. */
|
||||||
|
main: string;
|
||||||
|
/** An element whose background is the site accent (for the edge handle), if any. */
|
||||||
|
accentSource?: string;
|
||||||
|
/** Open while a modal sheet is up: the rail never slides in over it. */
|
||||||
|
modalOpen: string;
|
||||||
|
/** One of the site's menus (portalled out of the rail) is open. */
|
||||||
|
menuOpen: string;
|
||||||
|
/** Paint before the page has been read. */
|
||||||
|
paint: RailPaint;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Resting on the edge this long slides the rail in; crossing it on the way to the divider does not. */
|
||||||
|
const PEEK_DELAY = 140;
|
||||||
|
/** The rail stays this long after the pointer leaves it (and while one of its menus is open). */
|
||||||
|
const LEAVE_DELAY = 280;
|
||||||
|
|
||||||
|
const names = (site: RailSite) => ({
|
||||||
|
style: `${site.prefix}-pane-nav`,
|
||||||
|
edge: `${site.prefix}-rail-edge`,
|
||||||
|
/** On <html>: "hidden" (rail parked off-screen) or "peek" (rail slid in over the page). */
|
||||||
|
state: `data-${site.prefix}-pane-nav`,
|
||||||
|
/** Marks the rail when the site draws it as something other than its classic rail element. */
|
||||||
|
rail: `data-${site.prefix}-rail`,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Pure: the stylesheet for a pane whose rail is parked. RTL pages keep the rail on the right. */
|
||||||
|
export function buildPaneNavCss(site: RailSite, paint: RailPaint = site.paint): string {
|
||||||
|
const { edge, state, rail } = names(site);
|
||||||
|
const RAIL = `:is(${site.rail}, [${rail}])`;
|
||||||
|
const ease = 'cubic-bezier(.2, .8, .2, 1)';
|
||||||
|
const [side, other, sign] = paint.rtl ? ['right', 'left', 1] : ['left', 'right', -1];
|
||||||
|
return `
|
||||||
|
html[${state}] ${RAIL} {
|
||||||
|
position: fixed !important; top: 0 !important; bottom: 0 !important; ${side}: 0 !important; ${other}: auto !important;
|
||||||
|
width: ${paint.width}px !important; min-width: 0 !important; max-width: none !important; height: 100vh !important;
|
||||||
|
flex: none !important; margin: 0 !important; overflow: visible !important; z-index: 40 !important;
|
||||||
|
background-color: ${paint.background} !important;
|
||||||
|
transform: translateX(${sign * 100}%); visibility: hidden;
|
||||||
|
transition: transform .2s ${ease}, box-shadow .2s ease, visibility 0s linear .2s;
|
||||||
|
}
|
||||||
|
html[${state}="peek"] ${RAIL} {
|
||||||
|
transform: translateX(0); visibility: visible;
|
||||||
|
box-shadow: ${-sign}px 0 0 ${paint.line}, ${-sign * 16}px 0 40px rgba(0, 0, 0, .3);
|
||||||
|
transition: transform .2s ${ease}, box-shadow .2s ease;
|
||||||
|
}
|
||||||
|
html[${state}] ${RAIL} ~ ${site.main} { align-items: center !important; }
|
||||||
|
#${edge} { position: fixed; ${side}: 0; top: 0; bottom: 0; width: 10px; z-index: 41; }
|
||||||
|
#${edge}::after {
|
||||||
|
content: ""; position: absolute; ${side}: 0; top: 50%; width: 3px; height: 56px; margin-top: -28px;
|
||||||
|
border-radius: ${paint.rtl ? '3px 0 0 3px' : '0 3px 3px 0'}; background: ${paint.accent}; opacity: 0; transform: scaleY(.5);
|
||||||
|
transition: opacity .15s ease, transform .15s ease;
|
||||||
|
}
|
||||||
|
#${edge}:hover::after { opacity: .9; transform: scaleY(1); }
|
||||||
|
html[${state}="peek"] #${edge} { pointer-events: none; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
html[${state}] ${RAIL}, #${edge}::after { transition: none !important; }
|
||||||
|
}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const TRANSPARENT = /^(transparent|rgba\([^)]*,\s*0\))$/;
|
||||||
|
const isTransparent = (color: string | null | undefined) => !color || TRANSPARENT.test(color.replace(/\s+/g, ' ').trim());
|
||||||
|
|
||||||
|
/** `rgb(r, g, b)` / `rgba(...)` at a new alpha; anything else falls back to a neutral line. */
|
||||||
|
export function withAlpha(color: string, alpha: number): string {
|
||||||
|
const parts = color.match(/\d+(?:\.\d+)?/g);
|
||||||
|
return parts && parts.length >= 3 ? `rgba(${parts[0]}, ${parts[1]}, ${parts[2]}, ${alpha})` : `rgba(128, 128, 128, ${alpha})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installPaneNav(win: Window, site: RailSite): PaneNavHandle {
|
||||||
|
const doc = win.document;
|
||||||
|
const ids = names(site);
|
||||||
|
// Installed at document start, before the parser has created <html>: never cache it.
|
||||||
|
const root = (): HTMLElement | null => doc.documentElement;
|
||||||
|
let redundant = false;
|
||||||
|
let enabled = true;
|
||||||
|
let active = false;
|
||||||
|
let disposed = false;
|
||||||
|
let rail: HTMLElement | null = null;
|
||||||
|
let edge: HTMLElement | null = null;
|
||||||
|
let watch: DomWatchHandle | null = null;
|
||||||
|
let paint: RailPaint = { ...site.paint };
|
||||||
|
let peekTimer = 0;
|
||||||
|
let leaveTimer = 0;
|
||||||
|
let resizeFrame = 0;
|
||||||
|
/** A press inside the rail may have opened one of its menus (portalled elsewhere). */
|
||||||
|
let railMenu = false;
|
||||||
|
const isRtl = () => root()?.getAttribute('dir') === 'rtl';
|
||||||
|
|
||||||
|
const ensureStyle = () => {
|
||||||
|
let style = doc.getElementById(ids.style) as HTMLStyleElement | null;
|
||||||
|
if (!style) {
|
||||||
|
const parent = doc.head || root();
|
||||||
|
if (!parent) return;
|
||||||
|
style = doc.createElement('style');
|
||||||
|
style.id = ids.style;
|
||||||
|
parent.appendChild(style);
|
||||||
|
}
|
||||||
|
const css = buildPaneNavCss(site, paint);
|
||||||
|
if (style.textContent !== css) style.textContent = css;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The site's rail: its classic element, else the sibling of <main> holding the anchor link. */
|
||||||
|
const findRail = (): HTMLElement | null => {
|
||||||
|
const classic = doc.querySelector<HTMLElement>(site.rail);
|
||||||
|
if (classic) return classic;
|
||||||
|
if (rail?.isConnected) return rail;
|
||||||
|
const main = doc.querySelector('main');
|
||||||
|
const anchor = doc.querySelector(site.anchor);
|
||||||
|
if (!main || !anchor) return null;
|
||||||
|
for (let el = anchor.parentElement; el && el !== doc.body; el = el.parentElement) {
|
||||||
|
const parent = el.parentElement;
|
||||||
|
if (!parent?.contains(main) || el.contains(main)) continue;
|
||||||
|
// Only a tall column at the start edge: never a bottom tab bar or a page-wide wrapper.
|
||||||
|
const box = el.getBoundingClientRect();
|
||||||
|
const tall = box.height >= win.innerHeight * 0.5;
|
||||||
|
const atStart = isRtl() ? box.right >= win.innerWidth - 8 : box.left <= 8;
|
||||||
|
return tall && atStart && box.width <= win.innerWidth * 0.45 ? el : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const railWidth = (el: HTMLElement): number => {
|
||||||
|
const column = el.firstElementChild?.getBoundingClientRect().width ?? 0;
|
||||||
|
const nav = el.querySelector('nav')?.getBoundingClientRect().width ?? 0;
|
||||||
|
const width = Math.round(Math.max(column, nav));
|
||||||
|
return width >= 48 && width <= 400 ? width : paint.width;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Reads the page colors for the slid-in rail (layout reads: only on state changes, never per mutation). */
|
||||||
|
const repaint = () => {
|
||||||
|
try {
|
||||||
|
const body = doc.body ? win.getComputedStyle(doc.body) : null;
|
||||||
|
const html = root() ? win.getComputedStyle(root()!) : null;
|
||||||
|
let background = body?.backgroundColor ?? '';
|
||||||
|
if (isTransparent(background)) background = html?.backgroundColor ?? '';
|
||||||
|
if (isTransparent(background)) background = /dark/.test(html?.colorScheme ?? '') ? 'rgb(0, 0, 0)' : 'rgb(255, 255, 255)';
|
||||||
|
const button = site.accentSource ? doc.querySelector(site.accentSource) : null;
|
||||||
|
const fill = button ? win.getComputedStyle(button).backgroundColor : '';
|
||||||
|
paint = {
|
||||||
|
width: rail ? railWidth(rail) : paint.width,
|
||||||
|
background,
|
||||||
|
line: withAlpha(body?.color ?? '', 0.16),
|
||||||
|
accent: isTransparent(fill) ? site.paint.accent : fill,
|
||||||
|
rtl: isRtl(),
|
||||||
|
};
|
||||||
|
} catch { /* keep the last paint */ }
|
||||||
|
ensureStyle();
|
||||||
|
};
|
||||||
|
|
||||||
|
const state = () => root()?.getAttribute(ids.state) ?? null;
|
||||||
|
const setState = (value: 'hidden' | 'peek') => { if (state() !== value) root()?.setAttribute(ids.state, value); };
|
||||||
|
const menuOpen = () => !!doc.querySelector(site.menuOpen);
|
||||||
|
|
||||||
|
const unpeek = () => {
|
||||||
|
win.clearTimeout(peekTimer);
|
||||||
|
win.clearTimeout(leaveTimer);
|
||||||
|
railMenu = false;
|
||||||
|
if (active) setState('hidden');
|
||||||
|
};
|
||||||
|
const tryLeave = () => {
|
||||||
|
if (state() !== 'peek') return;
|
||||||
|
// Only the rail's own menus hold it out; sites portal them like every other menu, so "open" is
|
||||||
|
// judged only after a press inside the rail and ends when that menu closes.
|
||||||
|
const holding = railMenu && menuOpen();
|
||||||
|
if (!holding) railMenu = false;
|
||||||
|
if (rail?.matches(':hover') || holding) { leaveTimer = win.setTimeout(tryLeave, LEAVE_DELAY); return; }
|
||||||
|
unpeek();
|
||||||
|
};
|
||||||
|
const peek = () => {
|
||||||
|
win.clearTimeout(peekTimer);
|
||||||
|
// Never over one of the site's modal sheets: the rail would sit above them.
|
||||||
|
if (!active || !rail || doc.querySelector(site.modalOpen)) return;
|
||||||
|
repaint();
|
||||||
|
setState('peek');
|
||||||
|
win.clearTimeout(leaveTimer);
|
||||||
|
leaveTimer = win.setTimeout(tryLeave, LEAVE_DELAY * 4);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onEdgeEnter = () => { win.clearTimeout(peekTimer); peekTimer = win.setTimeout(peek, PEEK_DELAY); };
|
||||||
|
const onEdgeLeave = () => { if (state() !== 'peek') win.clearTimeout(peekTimer); };
|
||||||
|
const onRailEnter = () => win.clearTimeout(leaveTimer);
|
||||||
|
const onRailPress = () => { railMenu = true; };
|
||||||
|
const onRailLeave = () => { win.clearTimeout(leaveTimer); leaveTimer = win.setTimeout(tryLeave, LEAVE_DELAY); };
|
||||||
|
// A nav link navigates or opens a sheet: get out of the way.
|
||||||
|
const onRailClick = (event: Event) => {
|
||||||
|
if ((event.target as Element | null)?.closest?.('a[href]')) win.setTimeout(unpeek, 0);
|
||||||
|
};
|
||||||
|
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && state() === 'peek') unpeek(); };
|
||||||
|
const onResize = () => {
|
||||||
|
if (resizeFrame) return;
|
||||||
|
resizeFrame = win.requestAnimationFrame(() => {
|
||||||
|
resizeFrame = 0;
|
||||||
|
if (active && rail) { paint = { ...paint, width: railWidth(rail) }; ensureStyle(); }
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindRail = (next: HTMLElement | null) => {
|
||||||
|
if (next === rail) return;
|
||||||
|
if (rail) {
|
||||||
|
rail.removeAttribute(ids.rail);
|
||||||
|
rail.removeEventListener('pointerenter', onRailEnter);
|
||||||
|
rail.removeEventListener('pointerleave', onRailLeave);
|
||||||
|
rail.removeEventListener('pointerdown', onRailPress, true);
|
||||||
|
rail.removeEventListener('click', onRailClick, true);
|
||||||
|
}
|
||||||
|
rail = next;
|
||||||
|
if (!rail) return;
|
||||||
|
if (!rail.matches(site.rail)) rail.setAttribute(ids.rail, '');
|
||||||
|
rail.addEventListener('pointerenter', onRailEnter);
|
||||||
|
rail.addEventListener('pointerleave', onRailLeave);
|
||||||
|
rail.addEventListener('pointerdown', onRailPress, true);
|
||||||
|
rail.addEventListener('click', onRailClick, true);
|
||||||
|
paint = { ...paint, width: railWidth(rail), rtl: isRtl() };
|
||||||
|
ensureStyle();
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncEdge = () => {
|
||||||
|
if (!doc.body) return;
|
||||||
|
if (edge?.isConnected) return;
|
||||||
|
edge = doc.createElement('div');
|
||||||
|
edge.id = ids.edge;
|
||||||
|
edge.setAttribute('aria-hidden', 'true');
|
||||||
|
edge.addEventListener('pointerenter', onEdgeEnter);
|
||||||
|
edge.addEventListener('pointerleave', onEdgeLeave);
|
||||||
|
edge.addEventListener('click', peek);
|
||||||
|
doc.body.appendChild(edge);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sites re-render their layout on route and breakpoint changes: keep the rail marked and the edge in place.
|
||||||
|
const sync = () => {
|
||||||
|
if (!active || disposed) return;
|
||||||
|
// The first run after <html> exists parks the rail (activation may predate the document).
|
||||||
|
ensureStyle();
|
||||||
|
if (state() !== 'peek') setState('hidden');
|
||||||
|
bindRail(findRail());
|
||||||
|
syncEdge();
|
||||||
|
// The page direction can switch with the display language, without a reload.
|
||||||
|
if (paint.rtl !== isRtl()) { paint = { ...paint, rtl: isRtl() }; ensureStyle(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const activate = () => {
|
||||||
|
// The rail's width is measured while it is still in the layout, before it is parked.
|
||||||
|
if (doc.body) bindRail(findRail());
|
||||||
|
ensureStyle();
|
||||||
|
setState('hidden');
|
||||||
|
win.addEventListener('keydown', onKey, true);
|
||||||
|
win.addEventListener('resize', onResize);
|
||||||
|
watch = watchDom(win as unknown as Parameters<typeof watchDom>[0], sync);
|
||||||
|
watch.schedule();
|
||||||
|
};
|
||||||
|
|
||||||
|
const deactivate = () => {
|
||||||
|
win.clearTimeout(peekTimer);
|
||||||
|
win.clearTimeout(leaveTimer);
|
||||||
|
railMenu = false;
|
||||||
|
if (resizeFrame) win.cancelAnimationFrame(resizeFrame);
|
||||||
|
resizeFrame = 0;
|
||||||
|
watch?.dispose();
|
||||||
|
watch = null;
|
||||||
|
win.removeEventListener('keydown', onKey, true);
|
||||||
|
win.removeEventListener('resize', onResize);
|
||||||
|
root()?.removeAttribute(ids.state);
|
||||||
|
bindRail(null);
|
||||||
|
edge?.remove();
|
||||||
|
edge = null;
|
||||||
|
doc.getElementById(ids.style)?.remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
const apply = () => {
|
||||||
|
const next = enabled && redundant && !disposed;
|
||||||
|
if (next === active) return;
|
||||||
|
active = next;
|
||||||
|
if (active) activate();
|
||||||
|
else deactivate();
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
set(value) {
|
||||||
|
const next = (value as { redundantNav?: unknown } | null)?.redundantNav;
|
||||||
|
if (typeof next !== 'boolean') return;
|
||||||
|
redundant = next;
|
||||||
|
apply();
|
||||||
|
},
|
||||||
|
setEnabled(value) {
|
||||||
|
enabled = value;
|
||||||
|
apply();
|
||||||
|
},
|
||||||
|
dispose() {
|
||||||
|
disposed = true;
|
||||||
|
apply();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
285
packages/runtime/src/pluginApi.ts
Normal file
285
packages/runtime/src/pluginApi.ts
Normal file
|
|
@ -0,0 +1,285 @@
|
||||||
|
// `window.<Runtime>.api`: small helpers shared by `*.plugin.js` files so each plugin does not
|
||||||
|
// re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to
|
||||||
|
// the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a
|
||||||
|
// post/message parser) on top of this core.
|
||||||
|
|
||||||
|
export type Dispose = () => void;
|
||||||
|
|
||||||
|
export type PluginStorage = {
|
||||||
|
get<T>(key: string, fallback: T): T;
|
||||||
|
/** Returns false when the value could not be stored (quota, storage disabled). */
|
||||||
|
set(key: string, value: unknown): boolean;
|
||||||
|
remove(key: string): void;
|
||||||
|
keys(): string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Collects disposers so a plugin's `stop()` is a single `scope.dispose()`. */
|
||||||
|
export type PluginScope = {
|
||||||
|
css(id: string, css: string): void;
|
||||||
|
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
|
||||||
|
observe(selector: string, callback: (element: Element) => void): void;
|
||||||
|
onRouteChange(callback: (href: string, previous: string) => void): void;
|
||||||
|
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void;
|
||||||
|
/** Tracks a node the plugin inserted; it is removed on dispose. */
|
||||||
|
add<T extends Node>(node: T): T;
|
||||||
|
/** Runs `fn` on dispose (restore attributes, clear timers, ...). */
|
||||||
|
defer(fn: Dispose): void;
|
||||||
|
dispose(): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CorePluginApi = {
|
||||||
|
injectCSS(id: string, css: string): void;
|
||||||
|
clearCSS(id: string): void;
|
||||||
|
waitFor(selector: string, timeoutMs?: number): Promise<Element>;
|
||||||
|
/** Namespaced JSON storage in this tab's localStorage (`<storagePrefix><namespace>:<key>`). */
|
||||||
|
storage(namespace: string): PluginStorage;
|
||||||
|
/** Called after the page changes route (pushState/replaceState/back/forward). */
|
||||||
|
onRouteChange(callback: (href: string, previous: string) => void): Dispose;
|
||||||
|
/** Calls `callback` once for every element matching `selector`, now and as the page renders more. */
|
||||||
|
observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose;
|
||||||
|
/**
|
||||||
|
* Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no
|
||||||
|
* Ctrl/Meta/Alt is held and the key is not the second half of one of the site's chords.
|
||||||
|
*/
|
||||||
|
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose;
|
||||||
|
copyText(text: string): Promise<boolean>;
|
||||||
|
toast(message: string, ms?: number): void;
|
||||||
|
scope(): PluginScope;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PluginApiSite = {
|
||||||
|
/** The runtime global, for error messages (`<name>.waitFor timed out`). */
|
||||||
|
name: string;
|
||||||
|
/** Console prefix, e.g. "wayBetter for X". */
|
||||||
|
product: string;
|
||||||
|
/** localStorage key prefix, e.g. `bt-plugin:`. */
|
||||||
|
storagePrefix: string;
|
||||||
|
/** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */
|
||||||
|
styleDataKey: string;
|
||||||
|
toastId: string;
|
||||||
|
toastBackground: string;
|
||||||
|
/** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */
|
||||||
|
itemSelector: string;
|
||||||
|
/** Keys that start a two-key chord of the site's own (their second key is never a shortcut). */
|
||||||
|
chordKeys: readonly string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const NAMESPACE = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
||||||
|
const ROUTE_POLL_MS = 300;
|
||||||
|
const CHORD_MS = 1500;
|
||||||
|
|
||||||
|
/** True when a key event belongs to text entry, not to page shortcuts. */
|
||||||
|
export function isTypingTarget(target: EventTarget | null): boolean {
|
||||||
|
const element = target as (Element & { isContentEditable?: boolean }) | null;
|
||||||
|
if (!element || typeof element.closest !== 'function') return false;
|
||||||
|
return Boolean(element.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/i.test(element.nodeName) || Boolean(element.closest('[contenteditable="true"]'));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite): CorePluginApi {
|
||||||
|
const doc = win.document;
|
||||||
|
const styleNodes = new Map<string, HTMLStyleElement>();
|
||||||
|
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
|
||||||
|
|
||||||
|
const routeListeners = new Set<(href: string, previous: string) => void>();
|
||||||
|
let lastHref = win.location.href;
|
||||||
|
let routeTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
const checkRoute = () => {
|
||||||
|
const href = win.location.href;
|
||||||
|
if (href === lastHref) return;
|
||||||
|
const previous = lastHref;
|
||||||
|
lastHref = href;
|
||||||
|
for (const listener of [...routeListeners]) {
|
||||||
|
try { listener(href, previous); } catch (error) { report(error); }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const api: CorePluginApi = {
|
||||||
|
injectCSS(id, css) {
|
||||||
|
let node = styleNodes.get(id);
|
||||||
|
if (!node?.isConnected) {
|
||||||
|
node = doc.createElement('style');
|
||||||
|
node.dataset[site.styleDataKey] = id;
|
||||||
|
(doc.head || doc.documentElement).appendChild(node);
|
||||||
|
styleNodes.set(id, node);
|
||||||
|
}
|
||||||
|
node.textContent = css;
|
||||||
|
},
|
||||||
|
clearCSS(id) {
|
||||||
|
styleNodes.get(id)?.remove();
|
||||||
|
styleNodes.delete(id);
|
||||||
|
},
|
||||||
|
waitFor(selector, timeoutMs = 15000) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const found = doc.querySelector(selector);
|
||||||
|
if (found) return resolve(found);
|
||||||
|
const observer = new win.MutationObserver(() => {
|
||||||
|
const match = doc.querySelector(selector);
|
||||||
|
if (match) { observer.disconnect(); clearTimeout(timer); resolve(match); }
|
||||||
|
});
|
||||||
|
const timer = setTimeout(() => { observer.disconnect(); reject(new Error(`${site.name}.waitFor timed out: ${selector}`)); }, timeoutMs);
|
||||||
|
observer.observe(doc.documentElement, { childList: true, subtree: true });
|
||||||
|
});
|
||||||
|
},
|
||||||
|
storage(namespace) {
|
||||||
|
if (!NAMESPACE.test(namespace)) throw new Error(`${site.name}.storage: invalid namespace ${JSON.stringify(namespace)}`);
|
||||||
|
const prefix = `${site.storagePrefix}${namespace}:`;
|
||||||
|
const store = () => { try { return win.localStorage; } catch { return null; } };
|
||||||
|
return {
|
||||||
|
get(key, fallback) {
|
||||||
|
try {
|
||||||
|
const raw = store()?.getItem(prefix + key);
|
||||||
|
return raw == null ? fallback : JSON.parse(raw);
|
||||||
|
} catch { return fallback; }
|
||||||
|
},
|
||||||
|
set(key, value) {
|
||||||
|
try {
|
||||||
|
const target = store();
|
||||||
|
if (!target) return false;
|
||||||
|
target.setItem(prefix + key, JSON.stringify(value));
|
||||||
|
return true;
|
||||||
|
} catch { return false; }
|
||||||
|
},
|
||||||
|
remove(key) {
|
||||||
|
try { store()?.removeItem(prefix + key); } catch { /* storage unavailable */ }
|
||||||
|
},
|
||||||
|
keys() {
|
||||||
|
const target = store();
|
||||||
|
if (!target) return [];
|
||||||
|
const keys: string[] = [];
|
||||||
|
for (let i = 0; i < target.length; i += 1) {
|
||||||
|
const key = target.key(i);
|
||||||
|
if (key?.startsWith(prefix)) keys.push(key.slice(prefix.length));
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
onRouteChange(callback) {
|
||||||
|
routeListeners.add(callback);
|
||||||
|
if (!routeTimer) {
|
||||||
|
lastHref = win.location.href;
|
||||||
|
routeTimer = setInterval(checkRoute, ROUTE_POLL_MS);
|
||||||
|
win.addEventListener('popstate', checkRoute);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
routeListeners.delete(callback);
|
||||||
|
if (routeListeners.size === 0 && routeTimer) {
|
||||||
|
clearInterval(routeTimer);
|
||||||
|
routeTimer = null;
|
||||||
|
win.removeEventListener('popstate', checkRoute);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
observe(selector, callback, root) {
|
||||||
|
const seen = new WeakSet<Element>();
|
||||||
|
let frame = 0;
|
||||||
|
let disposed = false;
|
||||||
|
const scan = () => {
|
||||||
|
frame = 0;
|
||||||
|
if (disposed) return;
|
||||||
|
for (const element of Array.from((root ?? doc).querySelectorAll(selector))) {
|
||||||
|
if (seen.has(element)) continue;
|
||||||
|
seen.add(element);
|
||||||
|
try { callback(element); } catch (error) { report(error); }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const observer = new win.MutationObserver(() => {
|
||||||
|
if (!frame) frame = win.requestAnimationFrame(scan);
|
||||||
|
});
|
||||||
|
observer.observe((root as Node | undefined) ?? doc.documentElement, { childList: true, subtree: true });
|
||||||
|
scan();
|
||||||
|
return () => {
|
||||||
|
disposed = true;
|
||||||
|
observer.disconnect();
|
||||||
|
if (frame) win.cancelAnimationFrame(frame);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
onKey(callback) {
|
||||||
|
let chordAt = 0;
|
||||||
|
const listener = (event: KeyboardEvent) => {
|
||||||
|
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.repeat) return;
|
||||||
|
if (isTypingTarget(event.target) || isTypingTarget(doc.activeElement)) return;
|
||||||
|
const now = Date.now();
|
||||||
|
const inChord = now - chordAt < CHORD_MS;
|
||||||
|
const chordKey = site.chordKeys.includes(event.key);
|
||||||
|
chordAt = chordKey && !inChord ? now : 0;
|
||||||
|
if (inChord || chordKey) return;
|
||||||
|
const item = doc.activeElement?.closest?.(site.itemSelector) ?? null;
|
||||||
|
try { callback(event, item); } catch (error) { report(error); }
|
||||||
|
};
|
||||||
|
doc.addEventListener('keydown', listener);
|
||||||
|
return () => doc.removeEventListener('keydown', listener);
|
||||||
|
},
|
||||||
|
async copyText(text) {
|
||||||
|
try {
|
||||||
|
await win.navigator.clipboard.writeText(text);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
const area = doc.createElement('textarea');
|
||||||
|
area.value = text;
|
||||||
|
Object.assign(area.style, { position: 'fixed', opacity: '0', pointerEvents: 'none' });
|
||||||
|
doc.body.appendChild(area);
|
||||||
|
area.select();
|
||||||
|
let ok = false;
|
||||||
|
try { ok = doc.execCommand('copy'); } catch { ok = false; }
|
||||||
|
area.remove();
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
toast(message, ms = 2200) {
|
||||||
|
let node = doc.getElementById(site.toastId) as (HTMLElement & { _wbTimer?: number }) | null;
|
||||||
|
if (!node) {
|
||||||
|
node = doc.createElement('div');
|
||||||
|
node.id = site.toastId;
|
||||||
|
node.setAttribute('role', 'status');
|
||||||
|
Object.assign(node.style, {
|
||||||
|
position: 'fixed', left: '50%', bottom: '28px', transform: 'translateX(-50%)', zIndex: '2147483646',
|
||||||
|
padding: '10px 16px', borderRadius: '10px', background: site.toastBackground, color: '#fff',
|
||||||
|
font: '600 14px/1.3 system-ui, sans-serif', boxShadow: '0 6px 24px rgba(0,0,0,.35)', maxWidth: '80vw',
|
||||||
|
});
|
||||||
|
doc.body.appendChild(node);
|
||||||
|
}
|
||||||
|
node.textContent = message;
|
||||||
|
if (node._wbTimer) clearTimeout(node._wbTimer);
|
||||||
|
const current = node;
|
||||||
|
node._wbTimer = win.setTimeout(() => current.remove(), ms);
|
||||||
|
},
|
||||||
|
scope() {
|
||||||
|
let disposers: Dispose[] = [];
|
||||||
|
return {
|
||||||
|
css(id, css) {
|
||||||
|
api.injectCSS(id, css);
|
||||||
|
disposers.push(() => api.clearCSS(id));
|
||||||
|
},
|
||||||
|
on(target, type, listener, options) {
|
||||||
|
target.addEventListener(type, listener, options);
|
||||||
|
disposers.push(() => target.removeEventListener(type, listener, options));
|
||||||
|
},
|
||||||
|
observe(selector, callback) {
|
||||||
|
disposers.push(api.observe(selector, callback));
|
||||||
|
},
|
||||||
|
onRouteChange(callback) {
|
||||||
|
disposers.push(api.onRouteChange(callback));
|
||||||
|
},
|
||||||
|
onKey(callback) {
|
||||||
|
disposers.push(api.onKey(callback));
|
||||||
|
},
|
||||||
|
add(node) {
|
||||||
|
disposers.push(() => (node as unknown as ChildNode).remove?.());
|
||||||
|
return node;
|
||||||
|
},
|
||||||
|
defer(fn) {
|
||||||
|
disposers.push(fn);
|
||||||
|
},
|
||||||
|
dispose() {
|
||||||
|
const pending = disposers.reverse();
|
||||||
|
disposers = [];
|
||||||
|
for (const fn of pending) {
|
||||||
|
try { fn(); } catch (error) { report(error); }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return api;
|
||||||
|
}
|
||||||
50
packages/runtime/src/site.ts
Normal file
50
packages/runtime/src/site.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
// The page side of a site adapter. A wayBetter app for one site is mostly this object (plus the
|
||||||
|
// native `SiteSpec` in Rust and its Tauri capability files); every runtime module takes its piece.
|
||||||
|
|
||||||
|
import { configureDomHub } from './domHub.ts';
|
||||||
|
import { configureNetHub } from './netHub.ts';
|
||||||
|
import type { AccountSite } from './accountReport.ts';
|
||||||
|
import type { LinkSite } from './linkRouting.ts';
|
||||||
|
import type { RailSite } from './paneNav.ts';
|
||||||
|
import type { PluginApiSite } from './pluginApi.ts';
|
||||||
|
import type { SourceAxis } from './themeTokens.ts';
|
||||||
|
|
||||||
|
export type SiteAdapter = {
|
||||||
|
/** e.g. "wayBetter for X"; console prefixes and toasts. */
|
||||||
|
product: string;
|
||||||
|
/** Exact hosts of the site's origin (must match the native `SiteSpec.hosts`). */
|
||||||
|
hosts: readonly string[];
|
||||||
|
/** The runtime's window global (`window.<runtimeGlobal>`), plugins included. */
|
||||||
|
runtimeGlobal: string;
|
||||||
|
/** Pages where heavy-page-sensitive DOM features pause (e.g. a WASM chat); null = none. */
|
||||||
|
heavyPath: RegExp | null;
|
||||||
|
/** Request URL substrings that are the site's API calls; only these reach the net hub stages. */
|
||||||
|
apiMarks: string[];
|
||||||
|
/** Extra URL substrings that reach XHR gates only. */
|
||||||
|
xhrMarks: string[];
|
||||||
|
plugins: PluginApiSite;
|
||||||
|
/** Split-view rail hiding; omit when the site has no navigation rail. */
|
||||||
|
rail?: RailSite;
|
||||||
|
/** Signed-in account reader for the account switcher. */
|
||||||
|
account?: AccountSite;
|
||||||
|
/** Which in-page clicks the "links to site pages" setting may divert. */
|
||||||
|
links?: LinkSite;
|
||||||
|
/** The site's own palette per color mode, the source the theme engine maps from. */
|
||||||
|
themeSources?: Record<string, SourceAxis>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Applies the adapter's global knobs (DOM hub, net hub). Call once, before features start. */
|
||||||
|
export function configureRuntime(site: SiteAdapter): void {
|
||||||
|
configureDomHub({ label: site.product, heavyPath: site.heavyPath });
|
||||||
|
configureNetHub({ apiMarks: site.apiMarks, xhrMarks: site.xhrMarks });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether `href` is on the site's origin (https, one of `hosts`). */
|
||||||
|
export function isSiteUrl(site: Pick<SiteAdapter, 'hosts'>, href: string): boolean {
|
||||||
|
try {
|
||||||
|
const url = new URL(href);
|
||||||
|
return url.protocol === 'https:' && site.hosts.includes(url.hostname) && !url.username && !url.password;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
201
packages/runtime/src/themeTokens.ts
Normal file
201
packages/runtime/src/themeTokens.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
// The color foundation every theme is built on. The site's own palette (one per site color mode) is
|
||||||
|
// the reference coordinate system: every neutral the site paints sits somewhere on its axis from page
|
||||||
|
// background to text, and a theme says where its own background, surfaces, border, secondary text and
|
||||||
|
// text sit on that same axis. Any site neutral (listed or not, hover tints included) lands at the same
|
||||||
|
// position on the theme's curve, interpolated in OKLab, so nothing keeps the site's gray and nothing
|
||||||
|
// collapses onto the wrong role. The site's accent family follows the theme accent with the same
|
||||||
|
// lightness offset. Colors that mean something (likes, errors, badges) are left alone.
|
||||||
|
//
|
||||||
|
// Pure: runs in the page runtime, the settings previews and the tests. The site adapter supplies the
|
||||||
|
// source palettes (`SourceAxis`, one per site mode); e.g. X's Default/Dim/Lights out.
|
||||||
|
|
||||||
|
/** `#rrggbb` → [r, g, b] (local, so themeSpec.ts can import this module without a cycle). */
|
||||||
|
function hexToRgb(hex: string): Rgb {
|
||||||
|
const n = parseInt(hex.slice(1, 7), 16);
|
||||||
|
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Oklab = [number, number, number];
|
||||||
|
type Rgb = [number, number, number];
|
||||||
|
export type AxisRole = 'bg' | 'surface' | 'elevated' | 'border' | 'muted' | 'text';
|
||||||
|
export type SourceAxis = Record<AxisRole | 'accent', string[]>;
|
||||||
|
export type TargetAxis = Partial<Record<AxisRole | 'accent', string>>;
|
||||||
|
|
||||||
|
const toLinear = (v: number) => { v /= 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
|
||||||
|
const toGamma = (v: number) => Math.round(255 * Math.min(1, Math.max(0, v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055)));
|
||||||
|
|
||||||
|
export function rgbToOklab([r, g, b]: Rgb): Oklab {
|
||||||
|
const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)];
|
||||||
|
const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
|
||||||
|
const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
|
||||||
|
const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
|
||||||
|
return [
|
||||||
|
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
|
||||||
|
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
|
||||||
|
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function oklabToRgb([L, A, B]: Oklab): Rgb {
|
||||||
|
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3;
|
||||||
|
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3;
|
||||||
|
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3;
|
||||||
|
return [
|
||||||
|
toGamma(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
|
||||||
|
toGamma(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
|
||||||
|
toGamma(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyRgb = (key: string) => key.split(',').map(Number) as Rgb;
|
||||||
|
const lerp = (a: Oklab, b: Oklab, t: number): Oklab => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
|
||||||
|
const chroma = (c: Oklab) => Math.hypot(c[1], c[2]);
|
||||||
|
const hue = (c: Oklab) => (Math.atan2(c[2], c[1]) * 180) / Math.PI;
|
||||||
|
|
||||||
|
/** Anything whose chroma is below this is a neutral (the site's grays carry a faint tint). */
|
||||||
|
const NEUTRAL_CHROMA = 0.05;
|
||||||
|
/** How far past the site's own background/text a neutral may sit and still be on the axis (pure white
|
||||||
|
* text in Lights out is slightly past the site's 231,233,234; black in Default is far past and is a shadow). */
|
||||||
|
const AXIS_SLACK = 0.12;
|
||||||
|
|
||||||
|
export type ColorModel = {
|
||||||
|
sourceBg: Oklab;
|
||||||
|
sourceText: Oklab;
|
||||||
|
/** Sorted by `t`: the site's position on its bg→text axis and the theme color placed there. */
|
||||||
|
anchors: Array<{ t: number; color: Oklab }>;
|
||||||
|
/** The site's listed role colors (`r,g,b`) and the theme color they become, exactly. */
|
||||||
|
exact: Map<string, Rgb>;
|
||||||
|
sourceAccent: Oklab;
|
||||||
|
accent: Oklab | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a color is used decides which site role wins where the site reuses one value for two roles (Default's
|
||||||
|
* 239,243,244 is both a raised surface and a border): backgrounds read it as a surface, borders as
|
||||||
|
* a border, text as text.
|
||||||
|
*/
|
||||||
|
export type Usage = 'background' | 'border' | 'text';
|
||||||
|
const PRIORITY: Record<Usage, AxisRole[]> = {
|
||||||
|
background: ['bg', 'surface', 'elevated', 'border', 'muted', 'text'],
|
||||||
|
border: ['bg', 'border', 'elevated', 'surface', 'muted', 'text'],
|
||||||
|
// Text pins only text roles: a theme may draw borders brighter than its secondary text (High
|
||||||
|
// Contrast), and a grey the site uses for text must not jump to that border.
|
||||||
|
text: ['bg', 'text', 'muted'],
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model for mapping the site's palette (`source`, one site mode) onto a theme's axis colors for one usage.
|
||||||
|
* Every color the site lists for a role is pinned to the theme's color for that role (so a surface the site uses
|
||||||
|
* stays exactly the theme's surface), and everything the site paints between them is interpolated.
|
||||||
|
*/
|
||||||
|
export function buildColorModel(source: SourceAxis, target: TargetAxis, usage: Usage = 'background'): ColorModel | null {
|
||||||
|
if (!target.bg || !target.text) return null;
|
||||||
|
const sourceBg = rgbToOklab(keyRgb(source.bg[0]!));
|
||||||
|
const sourceText = rgbToOklab(keyRgb(source.text[0]!));
|
||||||
|
const span = sourceText[0] - sourceBg[0];
|
||||||
|
const position = (c: Oklab) => (c[0] - sourceBg[0]) / span;
|
||||||
|
const anchors: ColorModel['anchors'] = [
|
||||||
|
{ t: 0, color: rgbToOklab(hexToRgb(target.bg)) },
|
||||||
|
{ t: 1, color: rgbToOklab(hexToRgb(target.text)) },
|
||||||
|
];
|
||||||
|
const claimed = new Set<string>();
|
||||||
|
const exact = new Map<string, Rgb>();
|
||||||
|
for (const role of PRIORITY[usage]) {
|
||||||
|
const color = target[role];
|
||||||
|
for (const key of source[role]) {
|
||||||
|
if (claimed.has(key)) continue;
|
||||||
|
claimed.add(key);
|
||||||
|
if (!color) continue;
|
||||||
|
exact.set(key, hexToRgb(color));
|
||||||
|
const t = position(rgbToOklab(keyRgb(key)));
|
||||||
|
if (t <= 0.002 || t >= 0.998 || anchors.some(anchor => Math.abs(anchor.t - t) < 0.002)) continue;
|
||||||
|
anchors.push({ t, color: rgbToOklab(hexToRgb(color)) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Text and borders in the site's blue stay exactly the theme accent (legibility is checked on it);
|
||||||
|
// accent backgrounds keep the site's lightness offsets (hover, pressed) through projectColor.
|
||||||
|
if (target.accent && usage !== 'background') for (const key of source.accent) if (!exact.has(key)) exact.set(key, hexToRgb(target.accent));
|
||||||
|
anchors.sort((a, b) => a.t - b.t);
|
||||||
|
return {
|
||||||
|
sourceBg, sourceText, anchors, exact,
|
||||||
|
sourceAccent: rgbToOklab(keyRgb(source.accent[0]!)),
|
||||||
|
accent: target.accent ? rgbToOklab(hexToRgb(target.accent)) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a neutral sits on the site's axis (0 = the site background, 1 = the site text), or null when it is off the axis. */
|
||||||
|
export function axisPosition(model: ColorModel, rgb: Rgb): number | null {
|
||||||
|
const c = rgbToOklab(rgb);
|
||||||
|
if (chroma(c) >= NEUTRAL_CHROMA) return null;
|
||||||
|
const t = (c[0] - model.sourceBg[0]) / (model.sourceText[0] - model.sourceBg[0]);
|
||||||
|
if (t < -AXIS_SLACK || t > 1 + AXIS_SLACK) return null;
|
||||||
|
return Math.min(1, Math.max(0, t));
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCurve(model: ColorModel, t: number): Oklab {
|
||||||
|
const { anchors } = model;
|
||||||
|
for (let i = 1; i < anchors.length; i++) {
|
||||||
|
const a = anchors[i - 1]!, b = anchors[i]!;
|
||||||
|
if (t <= b.t) return lerp(a.color, b.color, (t - a.t) / (b.t - a.t || 1));
|
||||||
|
}
|
||||||
|
return anchors[anchors.length - 1]!.color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The site's accent family: same hue family as the site's accent, clearly chromatic. */
|
||||||
|
function isAccentFamily(model: ColorModel, c: Oklab): boolean {
|
||||||
|
if (chroma(c) < 0.07) return false;
|
||||||
|
const delta = Math.abs(((hue(c) - hue(model.sourceAccent) + 540) % 360) - 180);
|
||||||
|
return delta < 22;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The theme color for one of the site's colors, or null to leave it as the site painted it. */
|
||||||
|
export function projectColor(model: ColorModel, rgb: Rgb): Rgb | null {
|
||||||
|
const listed = model.exact.get(rgb.join(','));
|
||||||
|
if (listed) return listed;
|
||||||
|
const c = rgbToOklab(rgb);
|
||||||
|
const t = axisPosition(model, rgb);
|
||||||
|
if (t !== null) return oklabToRgb(onCurve(model, t));
|
||||||
|
if (model.accent && isAccentFamily(model, c)) {
|
||||||
|
// Keep the site's lightness offset (hover is darker, tints lighter) on the theme's accent.
|
||||||
|
const shifted: Oklab = [Math.min(1, Math.max(0, model.accent[0] + (c[0] - model.sourceAccent[0]))), model.accent[1], model.accent[2]];
|
||||||
|
return oklabToRgb(shifted);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The base structure every theme is built on: where a raised surface, a hover/elevated surface, a
|
||||||
|
* border and secondary text sit between a theme's background (0) and its text (1), in OKLab
|
||||||
|
* lightness. Taken from the built-in themes (their median), so a theme that only names its
|
||||||
|
* background, text and accent gets the same proportions as the rest.
|
||||||
|
*/
|
||||||
|
export const BASE_STEPS: Record<'dark' | 'light', Record<'surface' | 'elevated' | 'border' | 'muted', number>> = {
|
||||||
|
dark: { surface: 0.04, elevated: 0.09, border: 0.17, muted: 0.7 },
|
||||||
|
light: { surface: 0.025, elevated: 0.06, border: 0.13, muted: 0.7 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const toHex = (rgb: Rgb) => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||||||
|
|
||||||
|
/** Fills in the roles a theme did not name from its background, text and the base structure. */
|
||||||
|
export function deriveColors<T extends { bg: string; text: string; accent: string; surface?: string; elevated?: string; border?: string; muted?: string }>(seed: T):
|
||||||
|
T & Record<'surface' | 'elevated' | 'border' | 'muted', string> {
|
||||||
|
const bg = rgbToOklab(hexToRgb(seed.bg));
|
||||||
|
const text = rgbToOklab(hexToRgb(seed.text));
|
||||||
|
const steps = BASE_STEPS[bg[0] < text[0] ? 'dark' : 'light'];
|
||||||
|
const at = (t: number) => toHex(oklabToRgb(lerp(bg, text, t)));
|
||||||
|
return {
|
||||||
|
...seed,
|
||||||
|
surface: seed.surface ?? at(steps.surface),
|
||||||
|
elevated: seed.elevated ?? at(steps.elevated),
|
||||||
|
border: seed.border ?? at(steps.border),
|
||||||
|
muted: seed.muted ?? at(steps.muted),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a theme's roles sit on its own background→text axis (0 = bg, 1 = text). */
|
||||||
|
export function rolePositions(colors: { bg: string; text: string } & Record<'surface' | 'elevated' | 'border' | 'muted', string>) {
|
||||||
|
const L = (hex: string) => rgbToOklab(hexToRgb(hex))[0];
|
||||||
|
const span = L(colors.text) - L(colors.bg);
|
||||||
|
const pos = (hex: string) => (L(hex) - L(colors.bg)) / span;
|
||||||
|
return { surface: pos(colors.surface), elevated: pos(colors.elevated), border: pos(colors.border), muted: pos(colors.muted) };
|
||||||
|
}
|
||||||
212
packages/runtime/tests/hubs.test.ts
Normal file
212
packages/runtime/tests/hubs.test.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import { configureRuntime, isSiteUrl, type SiteAdapter } from '../src/site.ts';
|
||||||
|
import { addGate, addRewrite, addTap, addXhrGate, fetchHooked, isApiUrl } from '../src/netHub.ts';
|
||||||
|
import { isHeavyPath, watchDom } from '../src/domHub.ts';
|
||||||
|
|
||||||
|
const SITE: SiteAdapter = {
|
||||||
|
product: 'wayBetter for Test',
|
||||||
|
hosts: ['site.test'],
|
||||||
|
runtimeGlobal: 'Demo',
|
||||||
|
heavyPath: /^\/chat(?:\/|$)/,
|
||||||
|
apiMarks: ['/api/'],
|
||||||
|
xhrMarks: ['/upload'],
|
||||||
|
plugins: { name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin', toastId: 'demo-toast', toastBackground: '#000', itemSelector: 'article', chordKeys: [] },
|
||||||
|
};
|
||||||
|
configureRuntime(SITE);
|
||||||
|
|
||||||
|
const tick = () => new Promise(resolve => setTimeout(resolve, 15));
|
||||||
|
const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
|
||||||
|
|
||||||
|
function countClones() {
|
||||||
|
const original = Response.prototype.clone;
|
||||||
|
let clones = 0;
|
||||||
|
Response.prototype.clone = function (this: Response) { clones++; return original.call(this); };
|
||||||
|
return { get count() { return clones; }, restore() { Response.prototype.clone = original; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('site adapter: origin and API marks come from the adapter', () => {
|
||||||
|
assert.ok(isSiteUrl(SITE, 'https://site.test/a'));
|
||||||
|
for (const url of ['http://site.test/', 'https://site.test.evil/', 'https://u:p@site.test/', 'nope']) assert.equal(isSiteUrl(SITE, url), false, url);
|
||||||
|
assert.ok(isApiUrl('https://site.test/api/v1/feed'));
|
||||||
|
assert.equal(isApiUrl('https://cdn.site.test/a.png'), false);
|
||||||
|
assert.ok(isHeavyPath('/chat/1') && !isHeavyPath('/home'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('net hub: non-API requests skip every stage and get the inner promise itself', async () => {
|
||||||
|
const promise = Promise.resolve(json({}));
|
||||||
|
const target = { fetch: (() => promise) as unknown as typeof fetch };
|
||||||
|
const seen: string[] = [];
|
||||||
|
const offTap = addTap(target, { match: url => { seen.push(url); return true; }, maxBytes: 1e6, onJson() {} });
|
||||||
|
const offRewrite = addRewrite(target, () => { seen.push('rewrite'); return null; });
|
||||||
|
for (const url of ['https://cdn.site.test/app.wasm', 'https://cdn.site.test/a.jpg', '/sw.js']) {
|
||||||
|
assert.equal(target.fetch(url), promise, url);
|
||||||
|
}
|
||||||
|
assert.deepEqual(seen, [], 'no URL parsing, matching or cloning for non-API traffic');
|
||||||
|
offTap();
|
||||||
|
offRewrite();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('net hub: one clone and one parse feed every matching tap', async () => {
|
||||||
|
const clones = countClones();
|
||||||
|
try {
|
||||||
|
const body = { data: { ok: true } };
|
||||||
|
const target = { fetch: (async () => json(body)) as typeof fetch };
|
||||||
|
const got: unknown[] = [];
|
||||||
|
const a = addTap(target, { match: url => url.includes('Feed'), maxBytes: 1e6, onJson: value => got.push(value) });
|
||||||
|
const b = addTap(target, { match: url => url.includes('HomeFeed'), maxBytes: 1e6, onJson: value => got.push(value) });
|
||||||
|
const c = addTap(target, { match: () => false, maxBytes: 1e6, onJson: value => got.push(value) });
|
||||||
|
const response = await target.fetch('https://site.test/api/HomeFeed?cursor=1');
|
||||||
|
assert.deepEqual(await response.json(), body, 'the page still reads the original body');
|
||||||
|
await tick();
|
||||||
|
assert.equal(clones.count, 1);
|
||||||
|
assert.equal(got.length, 2);
|
||||||
|
assert.equal(got[0], got[1], 'both taps get the same parsed object');
|
||||||
|
a(); b(); c();
|
||||||
|
} finally {
|
||||||
|
clones.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('net hub: oversized bodies are never cloned', async () => {
|
||||||
|
const clones = countClones();
|
||||||
|
try {
|
||||||
|
const response = new Response('{}', { status: 200, headers: { 'content-length': '5000000' } });
|
||||||
|
const target = { fetch: (async () => response) as typeof fetch };
|
||||||
|
const off = addTap(target, { match: () => true, maxBytes: 1000, onJson() { assert.fail('not delivered'); } });
|
||||||
|
await target.fetch('/api/big');
|
||||||
|
await tick();
|
||||||
|
assert.equal(clones.count, 0);
|
||||||
|
off();
|
||||||
|
} finally {
|
||||||
|
clones.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('net hub: rewrite runs before the gate; unregistering the last stage restores fetch', async () => {
|
||||||
|
const calls: unknown[] = [];
|
||||||
|
const inner = ((input: unknown) => { calls.push(input); return Promise.resolve(json({})); }) as typeof fetch;
|
||||||
|
const target = { fetch: inner };
|
||||||
|
const order: string[] = [];
|
||||||
|
const offRewrite = addRewrite(target, input => { order.push('rewrite'); return String(input).replace('A', 'B'); });
|
||||||
|
const offGate = addGate(target, (input, _init, send) => { order.push(`gate:${String(input)}`); return String(input).endsWith('B') ? send() : null; });
|
||||||
|
assert.ok(fetchHooked(target));
|
||||||
|
await target.fetch('/api/A');
|
||||||
|
assert.deepEqual(order, ['rewrite', 'gate:/api/B']);
|
||||||
|
assert.deepEqual(calls, ['/api/B']);
|
||||||
|
offRewrite();
|
||||||
|
assert.notEqual(target.fetch, inner, 'still hooked while the gate is registered');
|
||||||
|
offGate();
|
||||||
|
assert.equal(target.fetch, inner);
|
||||||
|
assert.equal(fetchHooked(target), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('net hub: XHR gates see API and XHR-mark requests only, and can rewrite the URL', () => {
|
||||||
|
const sent: unknown[] = [];
|
||||||
|
class FakeXhr {
|
||||||
|
url = '';
|
||||||
|
open(_method: string, url: string) { this.url = url; }
|
||||||
|
send(body?: unknown) { sent.push([this.url, body]); }
|
||||||
|
addEventListener() {}
|
||||||
|
}
|
||||||
|
const target = { fetch: (async () => json({})) as typeof fetch, XMLHttpRequest: FakeXhr as unknown as typeof XMLHttpRequest };
|
||||||
|
const seen: string[] = [];
|
||||||
|
const off = addXhrGate(target, {
|
||||||
|
open(_xhr, request) { return request.url.includes('/api/old') ? request.url.replace('old', 'new') : undefined; },
|
||||||
|
send(_xhr, request, body, sendNative) { seen.push(request.url); sendNative(`${String(body)}!`); return true; },
|
||||||
|
});
|
||||||
|
for (const url of ['/api/old', '/upload/chunk', '/static/app.js']) {
|
||||||
|
const xhr = new FakeXhr();
|
||||||
|
xhr.open('post', url);
|
||||||
|
xhr.send('body');
|
||||||
|
}
|
||||||
|
assert.deepEqual(seen, ['/api/new', '/upload/chunk']);
|
||||||
|
assert.deepEqual(sent, [['/api/new', 'body!'], ['/upload/chunk', 'body!'], ['/static/app.js', 'body']]);
|
||||||
|
off();
|
||||||
|
assert.equal(FakeXhr.prototype.send.name, 'send', 'the last gate restores the prototype');
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeDomWindow(pathname = '/home') {
|
||||||
|
const frames: FrameRequestCallback[] = [];
|
||||||
|
const observers: { callback: MutationCallback; options?: MutationObserverInit; connected: boolean }[] = [];
|
||||||
|
class FakeObserver {
|
||||||
|
entry: { callback: MutationCallback; options?: MutationObserverInit; connected: boolean };
|
||||||
|
constructor(callback: MutationCallback) { this.entry = { callback, connected: false }; observers.push(this.entry); }
|
||||||
|
observe(_node: Node, options: MutationObserverInit) { this.entry.options = options; this.entry.connected = true; }
|
||||||
|
disconnect() { this.entry.connected = false; }
|
||||||
|
}
|
||||||
|
const win = {
|
||||||
|
document: { body: {}, addEventListener() {}, removeEventListener() {} } as unknown as Document,
|
||||||
|
location: { pathname },
|
||||||
|
MutationObserver: FakeObserver as unknown as typeof MutationObserver,
|
||||||
|
requestAnimationFrame(callback: FrameRequestCallback) { frames.push(callback); return frames.length; },
|
||||||
|
};
|
||||||
|
const flush = () => { for (const frame of frames.splice(0)) frame(0); };
|
||||||
|
const mutate = (...types: MutationRecordType[]) => observers[0]!.callback(types.map(type => ({ type, attributeName: type === 'attributes' ? 'aria-selected' : null })) as unknown as MutationRecord[], {} as MutationObserver);
|
||||||
|
return { win, frames, observers, flush, mutate };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('dom hub: one observer and one frame for all features; kinds and phases respected', () => {
|
||||||
|
const { win, frames, observers, flush, mutate } = fakeDomWindow();
|
||||||
|
const runs: string[] = [];
|
||||||
|
const writer = watchDom(win, () => runs.push('writer'));
|
||||||
|
const text = watchDom(win, () => runs.push('text'), { characterData: true });
|
||||||
|
const reader = watchDom(win, () => runs.push('reader'), { phase: 'read' });
|
||||||
|
const tabs = watchDom(win, () => runs.push('tabs'), { attributes: ['aria-selected'] });
|
||||||
|
assert.equal(observers.length, 1);
|
||||||
|
assert.deepEqual(observers[0]!.options, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['aria-selected'] });
|
||||||
|
mutate('childList'); mutate('childList'); mutate('characterData');
|
||||||
|
assert.equal(frames.length, 1, 'many mutation callbacks, one frame');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['reader', 'writer', 'text', 'tabs'], 'layout readers before DOM writers');
|
||||||
|
runs.length = 0;
|
||||||
|
mutate('characterData');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['text'], 'text changes only wake features that asked for them');
|
||||||
|
runs.length = 0;
|
||||||
|
mutate('attributes');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['tabs']);
|
||||||
|
runs.length = 0;
|
||||||
|
writer.schedule(); writer.schedule();
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['writer'], 'explicit schedule runs once per frame');
|
||||||
|
for (const handle of [writer, text, reader, tabs]) handle.dispose();
|
||||||
|
assert.equal(observers[0]!.connected, false, 'last feature off disconnects the observer');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dom hub: heavy pages skip features marked offOnHeavy', () => {
|
||||||
|
const { win, flush, mutate } = fakeDomWindow('/chat/123');
|
||||||
|
const runs: string[] = [];
|
||||||
|
const media = watchDom(win, () => runs.push('media'), { offOnHeavy: true });
|
||||||
|
const nav = watchDom(win, () => runs.push('nav'));
|
||||||
|
mutate('childList');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['nav']);
|
||||||
|
win.location.pathname = '/home';
|
||||||
|
mutate('childList');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['nav', 'media', 'nav']);
|
||||||
|
media.dispose();
|
||||||
|
nav.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dom hub: a failing feature does not stop the others', () => {
|
||||||
|
const { win, flush, mutate } = fakeDomWindow();
|
||||||
|
const runs: string[] = [];
|
||||||
|
const errors: unknown[] = [];
|
||||||
|
const original = console.error;
|
||||||
|
console.error = (...args: unknown[]) => { errors.push(args[0]); };
|
||||||
|
try {
|
||||||
|
const bad = watchDom(win, () => { throw new Error('boom'); });
|
||||||
|
const good = watchDom(win, () => runs.push('good'));
|
||||||
|
mutate('childList');
|
||||||
|
flush();
|
||||||
|
assert.deepEqual(runs, ['good']);
|
||||||
|
assert.deepEqual(errors, ['[wayBetter for Test] DOM feature failed']);
|
||||||
|
bad.dispose();
|
||||||
|
good.dispose();
|
||||||
|
} finally {
|
||||||
|
console.error = original;
|
||||||
|
}
|
||||||
|
});
|
||||||
88
packages/runtime/tests/linkRouting.test.ts
Normal file
88
packages/runtime/tests/linkRouting.test.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { installLinkRouting } from '../src/linkRouting.ts';
|
||||||
|
import { installAccountReport, type SeenAccount } from '../src/accountReport.ts';
|
||||||
|
|
||||||
|
type Listener = (event: unknown) => void;
|
||||||
|
// Node has no DOM: `instanceof Element` needs the constructor to exist.
|
||||||
|
(globalThis as { Element?: unknown }).Element ??= class {};
|
||||||
|
|
||||||
|
function fakeWindow() {
|
||||||
|
const listeners: Listener[] = [];
|
||||||
|
const opened: string[] = [];
|
||||||
|
const win = {
|
||||||
|
location: { href: 'https://site.test/feed' },
|
||||||
|
addEventListener(_type: string, fn: Listener) { listeners.push(fn); },
|
||||||
|
removeEventListener(_type: string, fn: Listener) { listeners.splice(listeners.indexOf(fn), 1); },
|
||||||
|
getSelection: () => ({ toString: () => '' }),
|
||||||
|
open(url: string) { opened.push(url); },
|
||||||
|
};
|
||||||
|
const click = (extra: Record<string, unknown> = {}) => {
|
||||||
|
const event = { button: 0, defaultPrevented: false, target: null, prevented: false, stopped: false, preventDefault() { this.prevented = true; }, stopPropagation() { this.stopped = true; }, ...extra };
|
||||||
|
for (const fn of [...listeners]) fn(event);
|
||||||
|
return event;
|
||||||
|
};
|
||||||
|
return { win, opened, click, listeners };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('link routing diverts only site clicks the adapter names, once a mode is set', () => {
|
||||||
|
const { win, opened, click, listeners } = fakeWindow();
|
||||||
|
const handle = installLinkRouting(win as unknown as Window, { configKey: 'site', clickedUrl: () => 'https://site.test/post/1' });
|
||||||
|
click();
|
||||||
|
assert.deepEqual(opened, [], '"same" is the default');
|
||||||
|
handle.configure({ site: 'popup' });
|
||||||
|
click();
|
||||||
|
assert.deepEqual(opened, [], 'unknown modes are ignored');
|
||||||
|
handle.configure({ site: 'pane' });
|
||||||
|
const event = click();
|
||||||
|
assert.deepEqual(opened, ['https://site.test/post/1']);
|
||||||
|
assert.ok(event.prevented && event.stopped);
|
||||||
|
click({ ctrlKey: true });
|
||||||
|
click({ button: 1 });
|
||||||
|
assert.equal(opened.length, 1, 'modified and non-primary clicks keep the site meaning');
|
||||||
|
handle.dispose();
|
||||||
|
assert.equal(listeners.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('link routing leaves clicks the adapter does not claim alone', () => {
|
||||||
|
const { win, opened, click } = fakeWindow();
|
||||||
|
const handle = installLinkRouting(win as unknown as Window, { configKey: 'site', clickedUrl: () => null });
|
||||||
|
handle.configure({ site: 'tab' });
|
||||||
|
const event = click();
|
||||||
|
assert.deepEqual(opened, []);
|
||||||
|
assert.equal(event.prevented, false);
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('account report sends only changes and retries after a failed send', async () => {
|
||||||
|
let account: SeenAccount | null = null;
|
||||||
|
let signedOut = false;
|
||||||
|
const sent: unknown[] = [];
|
||||||
|
let fail = false;
|
||||||
|
const frames: FrameRequestCallback[] = [];
|
||||||
|
const win = {
|
||||||
|
document: { body: {}, addEventListener() {}, removeEventListener() {} },
|
||||||
|
location: { pathname: '/' },
|
||||||
|
MutationObserver: class { callback: MutationCallback; constructor(cb: MutationCallback) { this.callback = cb; observers.push(this); } observe() {} disconnect() {} },
|
||||||
|
requestAnimationFrame(cb: FrameRequestCallback) { frames.push(cb); return 1; },
|
||||||
|
};
|
||||||
|
const observers: { callback: MutationCallback }[] = [];
|
||||||
|
const invoke = async (_command: string, args: Record<string, unknown>) => { sent.push(args.report); if (fail) throw new Error('offline'); };
|
||||||
|
const handle = installAccountReport(win as unknown as Window, { read: () => account, signedOut: () => signedOut }, invoke);
|
||||||
|
const run = async () => { observers[0]!.callback([] as unknown as MutationRecord[], {} as MutationObserver); for (const frame of frames.splice(0)) frame(0); await Promise.resolve(); await Promise.resolve(); };
|
||||||
|
await run();
|
||||||
|
assert.deepEqual(sent, [], 'nothing seen, nothing sent');
|
||||||
|
account = { handle: 'fish', name: 'Fish', avatar: null };
|
||||||
|
await run();
|
||||||
|
await run();
|
||||||
|
assert.deepEqual(sent, [{ account }], 'the same account is sent once');
|
||||||
|
account = null;
|
||||||
|
signedOut = true;
|
||||||
|
fail = true;
|
||||||
|
await run();
|
||||||
|
fail = false;
|
||||||
|
await run();
|
||||||
|
assert.deepEqual(sent.slice(1), [{ signedOut: true }, { signedOut: true }], 'a failed send is retried');
|
||||||
|
handle.dispose();
|
||||||
|
assert.deepEqual(installAccountReport(win as unknown as Window, { read: () => null, signedOut: () => false }).dispose(), undefined);
|
||||||
|
});
|
||||||
41
packages/runtime/tests/paneNav.test.ts
Normal file
41
packages/runtime/tests/paneNav.test.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { buildPaneNavCss, withAlpha, type RailSite } from '../src/paneNav.ts';
|
||||||
|
|
||||||
|
const SITE: RailSite = {
|
||||||
|
prefix: 'demo',
|
||||||
|
rail: 'nav.sidebar',
|
||||||
|
anchor: 'a.home',
|
||||||
|
main: '#content',
|
||||||
|
modalOpen: '.modal[open]',
|
||||||
|
menuOpen: '.menu[open]',
|
||||||
|
paint: { width: 72, background: 'rgb(0, 0, 0)', line: 'rgba(1, 2, 3, 0.16)', accent: 'rgb(83, 252, 24)', rtl: false },
|
||||||
|
};
|
||||||
|
|
||||||
|
test('pane CSS parks the site rail only while the html attribute is set', () => {
|
||||||
|
const css = buildPaneNavCss(SITE);
|
||||||
|
for (const rule of css.split('}').map(part => part.trim()).filter(Boolean)) {
|
||||||
|
const selector = rule.split('{')[0]!;
|
||||||
|
// Every rule is scoped: to the parked state, to our own edge element, or inside the motion query.
|
||||||
|
assert.ok(/html\[data-demo-pane-nav|#demo-rail-edge|@media/.test(selector), selector);
|
||||||
|
}
|
||||||
|
assert.match(css, /width: 72px !important/);
|
||||||
|
assert.match(css, /translateX\(-100%\)/);
|
||||||
|
assert.match(css, /\[data-demo-pane-nav="peek"\]/);
|
||||||
|
assert.match(css, /:is\(nav\.sidebar, \[data-demo-rail\]\) ~ #content/);
|
||||||
|
assert.match(css, /background: rgb\(83, 252, 24\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('RTL: the rail parks and slides in on the right', () => {
|
||||||
|
const css = buildPaneNavCss(SITE, { ...SITE.paint, rtl: true });
|
||||||
|
assert.match(css, /right: 0 !important; left: auto !important/);
|
||||||
|
assert.match(css, /translateX\(100%\)/);
|
||||||
|
assert.doesNotMatch(css, /translateX\(-100%\)/);
|
||||||
|
assert.match(css, /#demo-rail-edge \{ position: fixed; right: 0/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('withAlpha keeps the channels and swaps the alpha', () => {
|
||||||
|
assert.equal(withAlpha('rgb(231, 233, 234)', 0.16), 'rgba(231, 233, 234, 0.16)');
|
||||||
|
assert.equal(withAlpha('rgba(15, 20, 25, 1)', 0.5), 'rgba(15, 20, 25, 0.5)');
|
||||||
|
assert.equal(withAlpha('', 0.2), 'rgba(128, 128, 128, 0.2)');
|
||||||
|
});
|
||||||
131
packages/runtime/tests/pluginApi.test.ts
Normal file
131
packages/runtime/tests/pluginApi.test.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { createCorePluginApi, isTypingTarget, type PluginApiSite } from '../src/pluginApi.ts';
|
||||||
|
|
||||||
|
type Listener = (event: unknown) => void;
|
||||||
|
|
||||||
|
class FakeTarget {
|
||||||
|
listeners = new Map<string, Set<Listener>>();
|
||||||
|
addEventListener(type: string, fn: Listener) {
|
||||||
|
if (!this.listeners.has(type)) this.listeners.set(type, new Set());
|
||||||
|
this.listeners.get(type)!.add(fn);
|
||||||
|
}
|
||||||
|
removeEventListener(type: string, fn: Listener) { this.listeners.get(type)?.delete(fn); }
|
||||||
|
emit(type: string, event: unknown = {}) { for (const fn of [...(this.listeners.get(type) ?? [])]) fn(event); }
|
||||||
|
count(type: string) { return this.listeners.get(type)?.size ?? 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeStorage {
|
||||||
|
map = new Map<string, string>();
|
||||||
|
get length() { return this.map.size; }
|
||||||
|
key(i: number) { return [...this.map.keys()][i] ?? null; }
|
||||||
|
getItem(k: string) { return this.map.get(k) ?? null; }
|
||||||
|
setItem(k: string, v: string) { this.map.set(k, v); }
|
||||||
|
removeItem(k: string) { this.map.delete(k); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const SITE: PluginApiSite = {
|
||||||
|
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
|
||||||
|
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article.message', chordKeys: ['g'],
|
||||||
|
};
|
||||||
|
|
||||||
|
function fakeEnv() {
|
||||||
|
const styles: { dataset: Record<string, string>; textContent: string; isConnected: boolean; remove(): void }[] = [];
|
||||||
|
const doc = new FakeTarget() as FakeTarget & Record<string, unknown>;
|
||||||
|
Object.assign(doc, {
|
||||||
|
activeElement: null,
|
||||||
|
documentElement: {},
|
||||||
|
head: { appendChild(node: { isConnected: boolean }) { node.isConnected = true; } },
|
||||||
|
querySelectorAll: () => [],
|
||||||
|
createElement: () => {
|
||||||
|
const node = { dataset: {} as Record<string, string>, textContent: '', isConnected: false, remove() { node.isConnected = false; } };
|
||||||
|
styles.push(node);
|
||||||
|
return node;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const win = new FakeTarget() as FakeTarget & Record<string, unknown>;
|
||||||
|
const storage = new FakeStorage();
|
||||||
|
Object.assign(win, {
|
||||||
|
document: doc,
|
||||||
|
location: { href: 'https://site.test/home' },
|
||||||
|
localStorage: storage,
|
||||||
|
requestAnimationFrame: (fn: () => void) => { fn(); return 1; },
|
||||||
|
cancelAnimationFrame: () => {},
|
||||||
|
MutationObserver: class { observe() {} disconnect() {} },
|
||||||
|
});
|
||||||
|
const api = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE);
|
||||||
|
return { api, win, doc, storage, styles };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('storage is namespaced under the site prefix and never throws', () => {
|
||||||
|
const { api, storage } = fakeEnv();
|
||||||
|
const notes = api.storage('notes');
|
||||||
|
assert.equal(notes.set('a', { text: 'hi' }), true);
|
||||||
|
assert.equal(storage.getItem('demo-plugin:notes:a'), '{"text":"hi"}');
|
||||||
|
storage.setItem('demo-plugin:notes:broken', '{not json');
|
||||||
|
assert.deepEqual(notes.get('broken', 'fallback'), 'fallback');
|
||||||
|
assert.deepEqual(notes.keys().sort(), ['a', 'broken']);
|
||||||
|
assert.throws(() => api.storage('../escape'), /Demo\.storage: invalid namespace/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('injectCSS marks its style with the site data key and replaces in place', () => {
|
||||||
|
const { api, styles } = fakeEnv();
|
||||||
|
api.injectCSS('one', 'a{}');
|
||||||
|
api.injectCSS('one', 'b{}');
|
||||||
|
assert.equal(styles.length, 1);
|
||||||
|
assert.equal(styles[0]!.dataset.demoPlugin, 'one');
|
||||||
|
assert.equal(styles[0]!.textContent, 'b{}');
|
||||||
|
api.clearCSS('one');
|
||||||
|
assert.equal(styles[0]!.isConnected, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onKey skips typing, modifiers and the second key of site chords', () => {
|
||||||
|
const { api, doc } = fakeEnv();
|
||||||
|
const keys: string[] = [];
|
||||||
|
const off = api.onKey(event => keys.push(event.key));
|
||||||
|
const press = (key: string, extra: Record<string, unknown> = {}) => doc.emit('keydown', { key, target: null, ...extra });
|
||||||
|
press('j');
|
||||||
|
press('g'); press('h');
|
||||||
|
press('k', { ctrlKey: true });
|
||||||
|
press('l', { target: { nodeName: 'INPUT', closest: () => null } });
|
||||||
|
press('m');
|
||||||
|
assert.deepEqual(keys, ['j', 'm']);
|
||||||
|
off();
|
||||||
|
assert.equal(doc.count('keydown'), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('route listeners share one poll and stop with the last listener', () => {
|
||||||
|
const { api, win } = fakeEnv();
|
||||||
|
const offA = api.onRouteChange(() => {});
|
||||||
|
const offB = api.onRouteChange(() => {});
|
||||||
|
assert.equal(win.count('popstate'), 1);
|
||||||
|
offA();
|
||||||
|
assert.equal(win.count('popstate'), 1);
|
||||||
|
offB();
|
||||||
|
assert.equal(win.count('popstate'), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scope disposes in reverse order and survives failing disposers', () => {
|
||||||
|
const { api } = fakeEnv();
|
||||||
|
const order: string[] = [];
|
||||||
|
const scope = api.scope();
|
||||||
|
const original = console.error;
|
||||||
|
console.error = () => {};
|
||||||
|
try {
|
||||||
|
scope.defer(() => order.push('first'));
|
||||||
|
scope.defer(() => { throw new Error('boom'); });
|
||||||
|
scope.defer(() => order.push('last'));
|
||||||
|
scope.dispose();
|
||||||
|
scope.dispose();
|
||||||
|
} finally {
|
||||||
|
console.error = original;
|
||||||
|
}
|
||||||
|
assert.deepEqual(order, ['last', 'first']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('isTypingTarget recognizes inputs and editable content', () => {
|
||||||
|
assert.equal(isTypingTarget(null), false);
|
||||||
|
assert.ok(isTypingTarget({ nodeName: 'TEXTAREA', closest: () => null } as unknown as EventTarget));
|
||||||
|
assert.ok(isTypingTarget({ nodeName: 'DIV', isContentEditable: true, closest: () => null } as unknown as EventTarget));
|
||||||
|
assert.equal(isTypingTarget({ nodeName: 'DIV', closest: () => null } as unknown as EventTarget), false);
|
||||||
|
});
|
||||||
52
packages/runtime/tests/themeTokens.test.ts
Normal file
52
packages/runtime/tests/themeTokens.test.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { axisPosition, buildColorModel, deriveColors, oklabToRgb, projectColor, rgbToOklab, rolePositions, BASE_STEPS, type SourceAxis } from '../src/themeTokens.ts';
|
||||||
|
|
||||||
|
// A made-up dark site palette: every role lists its colors as `r,g,b`, the first is canonical.
|
||||||
|
const SOURCE: SourceAxis = {
|
||||||
|
bg: ['10,10,12'],
|
||||||
|
surface: ['20,21,24'],
|
||||||
|
elevated: ['32,33,38'],
|
||||||
|
border: ['50,52,58'],
|
||||||
|
muted: ['140,144,150'],
|
||||||
|
text: ['235,236,238'],
|
||||||
|
accent: ['83,252,24'],
|
||||||
|
};
|
||||||
|
const THEME = { bg: '#fdf6e3', surface: '#f5eedb', elevated: '#eee8d5', border: '#d9d2bf', muted: '#657b83', text: '#073642', accent: '#268bd2' };
|
||||||
|
const rgb = (key: string) => key.split(',').map(Number) as [number, number, number];
|
||||||
|
const hex = (value: number[]) => `#${value.map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||||||
|
|
||||||
|
test('OKLab round trip is exact to one step', () => {
|
||||||
|
for (const color of [[0, 0, 0], [255, 255, 255], [29, 155, 240], [22, 24, 28], [83, 100, 113]] as [number, number, number][]) {
|
||||||
|
const back = oklabToRgb(rgbToOklab(color));
|
||||||
|
color.forEach((v, i) => assert.ok(Math.abs(v - back[i]!) <= 1, `${color} -> ${back}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listed site colors become exactly the theme role, per usage', () => {
|
||||||
|
const background = buildColorModel(SOURCE, THEME, 'background')!;
|
||||||
|
assert.equal(hex(projectColor(background, rgb(SOURCE.bg[0]!))!), THEME.bg);
|
||||||
|
assert.equal(hex(projectColor(background, rgb(SOURCE.surface[0]!))!), THEME.surface);
|
||||||
|
const text = buildColorModel(SOURCE, THEME, 'text')!;
|
||||||
|
assert.equal(hex(projectColor(text, rgb(SOURCE.text[0]!))!), THEME.text);
|
||||||
|
assert.equal(hex(projectColor(text, rgb(SOURCE.accent[0]!))!), THEME.accent, 'accent text is exactly the theme accent');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unlisted neutrals land on the theme curve in order; chromatic non-accent colors stay', () => {
|
||||||
|
const model = buildColorModel(SOURCE, THEME, 'background')!;
|
||||||
|
const steps = [15, 60, 120, 200].map(v => projectColor(model, [v, v, v + 2])!);
|
||||||
|
const lightness = steps.map(step => rgbToOklab(step)[0]);
|
||||||
|
for (let i = 1; i < lightness.length; i++) assert.ok(lightness[i]! < lightness[i - 1]!, 'light theme: darker as the site gets lighter');
|
||||||
|
assert.equal(projectColor(model, [249, 24, 128]), null, 'a pink like-heart is left alone');
|
||||||
|
assert.equal(axisPosition(model, [249, 24, 128]), null);
|
||||||
|
assert.equal(buildColorModel(SOURCE, { accent: '#ffffff' }), null, 'a theme needs a background and text');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('derived roles follow the base structure', () => {
|
||||||
|
const dark = deriveColors({ bg: '#15202b', text: '#e7e9ea', accent: '#1d9bf0' });
|
||||||
|
const positions = rolePositions(dark);
|
||||||
|
for (const role of ['surface', 'elevated', 'border', 'muted'] as const) {
|
||||||
|
assert.ok(Math.abs(positions[role] - BASE_STEPS.dark[role]) < 0.03, `${role}: ${positions[role]}`);
|
||||||
|
}
|
||||||
|
assert.equal(deriveColors({ bg: '#ffffff', text: '#000000', accent: '#000000', border: '#123456' }).border, '#123456');
|
||||||
|
});
|
||||||
11
packages/shell/package.json
Normal file
11
packages/shell/package.json
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
{
|
||||||
|
"name": "@waybetter/shell",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"type": "module",
|
||||||
|
"description": "wayBetter shell core: address bar, pane and link-drop models, profiles, update chip, command palette ranking and window controls. No dependencies.",
|
||||||
|
"exports": {
|
||||||
|
"./*": "./src/*"
|
||||||
|
}
|
||||||
|
}
|
||||||
90
packages/shell/src/addressModel.ts
Normal file
90
packages/shell/src/addressModel.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
// Pure, unit-testable model for the address bar's breadcrumb chips.
|
||||||
|
// No React, no Tauri: parseAddress(url, site) -> AddressModel | null. The site adapter turns its
|
||||||
|
// own URLs into named chips; any other site gets host + path chips.
|
||||||
|
|
||||||
|
export type Segment = { label: string; href: string; mono?: boolean; quoted?: boolean };
|
||||||
|
export type AddressModel<Kind extends string = string> = {
|
||||||
|
site: { kind: Kind | 'host'; label: string; href: string };
|
||||||
|
segments: Segment[];
|
||||||
|
insecure: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AddressSite<Kind extends string = string> = {
|
||||||
|
/** `site.kind` for the adapter's own pages, e.g. 'x'. */
|
||||||
|
kind: Kind;
|
||||||
|
/** Hostnames (lowercase) that are the site. */
|
||||||
|
hosts: ReadonlySet<string>;
|
||||||
|
/** The site chip's label. */
|
||||||
|
label: string;
|
||||||
|
/** Where the site chip links: its home page on this origin. */
|
||||||
|
home(origin: string): string;
|
||||||
|
/** Named chips for one of the site's URLs, or null to show no chips (an internal page). */
|
||||||
|
segments(url: URL): Segment[] | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function truncate(value: string, max: number): string {
|
||||||
|
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Long numeric ids shown by their last 6 characters. */
|
||||||
|
export function last6(id: string): string {
|
||||||
|
return `…${id.slice(-6)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function titleCase(part: string): string {
|
||||||
|
return part
|
||||||
|
.split(/[-_]/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||||
|
.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generic chips: one per path segment, then `?…` for a query. */
|
||||||
|
export function hostSegments(url: URL): Segment[] {
|
||||||
|
const origin = `${url.protocol}//${url.hostname}`;
|
||||||
|
const parts = url.pathname.split('/').filter(Boolean);
|
||||||
|
const segments: Segment[] = [];
|
||||||
|
parts.forEach((part, index) => {
|
||||||
|
const href = `${origin}/${parts.slice(0, index + 1).join('/')}`;
|
||||||
|
segments.push({ label: truncate(decodeURIComponent(part), 24), href });
|
||||||
|
});
|
||||||
|
if (url.search) {
|
||||||
|
segments.push({ label: '?…', href: `${origin}${url.pathname}${url.search}` });
|
||||||
|
}
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseAddress<Kind extends string>(url: string, site?: AddressSite<Kind>): AddressModel<Kind> | null {
|
||||||
|
let parsed: URL;
|
||||||
|
try {
|
||||||
|
parsed = new URL(url);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const insecure = parsed.protocol === 'http:';
|
||||||
|
const hostname = parsed.hostname.replace(/^www\./, '');
|
||||||
|
|
||||||
|
if (site && site.hosts.has(parsed.hostname.toLowerCase())) {
|
||||||
|
const origin = `${parsed.protocol}//${parsed.hostname}`;
|
||||||
|
const segments = site.segments(parsed);
|
||||||
|
if (segments === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const last = segments[segments.length - 1];
|
||||||
|
if (last) (last as Segment & { current?: boolean }).current = true;
|
||||||
|
return {
|
||||||
|
site: { kind: site.kind, label: site.label, href: site.home(origin) },
|
||||||
|
segments,
|
||||||
|
insecure,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
site: { kind: 'host', label: hostname, href: `${parsed.protocol}//${parsed.hostname}` },
|
||||||
|
segments: hostSegments(parsed),
|
||||||
|
insecure,
|
||||||
|
};
|
||||||
|
}
|
||||||
5
packages/shell/src/chrome.ts
Normal file
5
packages/shell/src/chrome.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
// Layout constants for the custom window chrome (titlebar + toolbar), in logical px. TITLEBAR_H and
|
||||||
|
// RESIZE_BORDER must match `policy::TITLEBAR_H` / `policy::RESIZE_BORDER` in waybetter-host.
|
||||||
|
export const TITLEBAR_H = 44;
|
||||||
|
export const TOOLBAR_H = 50;
|
||||||
|
export const RESIZE_BORDER = 5;
|
||||||
54
packages/shell/src/linkDrop.ts
Normal file
54
packages/shell/src/linkDrop.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
// Pure helpers for dropping a dragged link into the dock as a new tab or split pane.
|
||||||
|
// No React, no Tauri, no dockview runtime: the Shell maps dockview drop events through these.
|
||||||
|
|
||||||
|
export const MAX_LINK_LENGTH = 4096;
|
||||||
|
|
||||||
|
/** Only plain http(s) links without credentials open as tabs (same rule as the host's `tabs::parse_web_url`). */
|
||||||
|
export function webUrl(value: string | null | undefined): string | null {
|
||||||
|
const text = value?.trim();
|
||||||
|
if (!text || text.length > MAX_LINK_LENGTH) return null;
|
||||||
|
let url: URL;
|
||||||
|
try { url = new URL(text); } catch { return null; }
|
||||||
|
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) return null;
|
||||||
|
return url.href;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The link carried by a drop: `text/uri-list` (first non-comment line), then `text/x-moz-url`,
|
||||||
|
* then the first line of `text/plain`; else the URL the source tab reported on dragstart.
|
||||||
|
*/
|
||||||
|
export function dropUrl(getData: (type: string) => string, reported?: string | null): string | null {
|
||||||
|
const read = (type: string) => { try { return getData(type) || ''; } catch { return ''; } };
|
||||||
|
const firstLine = (text: string, skipComments: boolean) =>
|
||||||
|
text.split(/\r?\n/).map(line => line.trim()).find(line => line && !(skipComments && line.startsWith('#'))) ?? '';
|
||||||
|
return webUrl(firstLine(read('text/uri-list'), true))
|
||||||
|
?? webUrl(firstLine(read('text/x-moz-url'), false))
|
||||||
|
?? webUrl(firstLine(read('text/plain'), false))
|
||||||
|
?? webUrl(reported);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drag types that may carry a link. File drags are left to the page (e.g. a composer). */
|
||||||
|
export function carriesLink(types: readonly string[]): boolean {
|
||||||
|
if (types.includes('Files')) return false;
|
||||||
|
return types.includes('text/uri-list') || types.includes('text/x-moz-url');
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DropPosition = 'top' | 'bottom' | 'left' | 'right' | 'center';
|
||||||
|
export type DropDirection = 'left' | 'right' | 'above' | 'below';
|
||||||
|
export type Placement =
|
||||||
|
| { referenceGroup: string; direction: 'within' | DropDirection; index?: number }
|
||||||
|
| { direction: DropDirection };
|
||||||
|
|
||||||
|
const DIRECTIONS: Record<Exclude<DropPosition, 'center'>, DropDirection> = { top: 'above', bottom: 'below', left: 'left', right: 'right' };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a dropped link opens. `groupId`: the group under the pointer (missing for the dock's outer
|
||||||
|
* edges). `tabIndex`: the tab dropped on, if any. `undefined`: the default (active group, or a new
|
||||||
|
* group in an empty dock).
|
||||||
|
*/
|
||||||
|
export function placementFor(target: { position: DropPosition; groupId?: string; tabIndex?: number }): Placement | undefined {
|
||||||
|
const { position, groupId, tabIndex } = target;
|
||||||
|
if (!groupId) return position === 'center' ? undefined : { direction: DIRECTIONS[position] };
|
||||||
|
if (position === 'center') return tabIndex === undefined ? { referenceGroup: groupId, direction: 'within' } : { referenceGroup: groupId, direction: 'within', index: tabIndex };
|
||||||
|
return { referenceGroup: groupId, direction: DIRECTIONS[position] };
|
||||||
|
}
|
||||||
49
packages/shell/src/palette.ts
Normal file
49
packages/shell/src/palette.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
// Command palette core: fuzzy scoring, ranking and selection movement. The app builds its own
|
||||||
|
// items (tabs, profiles, settings sections, site destinations); every item is navigation only.
|
||||||
|
|
||||||
|
export type RankedItem = { label: string; keywords?: string; group: string };
|
||||||
|
|
||||||
|
/** Subsequence match, case-insensitive. 0 = no match; prefix/word-start/consecutive hits score higher. */
|
||||||
|
export function fuzzyScore(target: string, query: string): number {
|
||||||
|
const t = target.toLowerCase();
|
||||||
|
const q = query.toLowerCase().replace(/\s+/g, ' ').trim();
|
||||||
|
if (!q) return 1;
|
||||||
|
if (!t) return 0;
|
||||||
|
if (t.startsWith(q)) return 1000 - t.length;
|
||||||
|
const at = t.indexOf(q);
|
||||||
|
if (at >= 0) return 600 - at - t.length / 10 + (/[\s/_-]/.test(t[at - 1] ?? ' ') ? 100 : 0);
|
||||||
|
let score = 0;
|
||||||
|
let ti = 0;
|
||||||
|
let previous = -2;
|
||||||
|
for (const char of q) {
|
||||||
|
if (char === ' ') continue;
|
||||||
|
const found = t.indexOf(char, ti);
|
||||||
|
if (found < 0) return 0;
|
||||||
|
score += 10;
|
||||||
|
if (found === previous + 1) score += 15;
|
||||||
|
if (found === 0 || /[\s/_-]/.test(t[found - 1]!)) score += 20;
|
||||||
|
previous = found;
|
||||||
|
ti = found + 1;
|
||||||
|
}
|
||||||
|
return Math.max(1, score - t.length / 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An item's score: its label, or half of its keywords/group match. */
|
||||||
|
export function scoreItem(item: RankedItem, query: string): number {
|
||||||
|
const label = fuzzyScore(item.label, query);
|
||||||
|
const extra = Math.max(fuzzyScore(item.keywords ?? '', query), fuzzyScore(item.group, query)) * 0.5;
|
||||||
|
return Math.max(label, extra);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Matching items, best first; equal scores keep their original order. `skip` items never match. */
|
||||||
|
export function rankItems<T extends RankedItem>(items: readonly T[], query: string, skip: (item: T) => boolean = () => false): T[] {
|
||||||
|
return items
|
||||||
|
.map((item, index) => ({ item, index, score: skip(item) ? 0 : scoreItem(item, query) }))
|
||||||
|
.filter(entry => entry.score > 0)
|
||||||
|
.sort((a, b) => b.score - a.score || a.index - b.index)
|
||||||
|
.map(entry => entry.item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wraps selection movement within the list. */
|
||||||
|
export const moveSelection = (index: number, step: number, length: number) =>
|
||||||
|
length === 0 ? 0 : (index + step + length) % length;
|
||||||
55
packages/shell/src/paneModel.ts
Normal file
55
packages/shell/src/paneModel.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
// Pane geometry rules for the dock: where a link opened "beside" a pane goes, and which site panes
|
||||||
|
// repeat a navigation rail already on screen. Two site panes of the same account side by side (or
|
||||||
|
// stacked) both draw the site's rail; only the leftmost (then topmost) one needs it. Panes of
|
||||||
|
// different accounts keep theirs: the rail's account button is the only in-page sign of which
|
||||||
|
// account a pane is.
|
||||||
|
|
||||||
|
export type PaneBox = { id: string; url: string; profile: string; x: number; y: number; visible: boolean };
|
||||||
|
|
||||||
|
/** `besideOf`: the source group ids whose "beside" links this group's tabs were opened for. */
|
||||||
|
export type GroupBox = { id: string; left: number; top: number; right: number; bottom: number; besideOf?: readonly string[] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a link opened "beside" a pane goes: the side pane this source opened before (so repeated
|
||||||
|
* links reuse one), when it is still to its right and shares some of its height; else null to split
|
||||||
|
* a new one. A group the user opened themselves (another feed, another account) is never taken over.
|
||||||
|
*/
|
||||||
|
export function besideGroup(source: GroupBox, groups: readonly GroupBox[]): string | null {
|
||||||
|
let best: GroupBox | null = null;
|
||||||
|
for (const group of groups) {
|
||||||
|
if (group.id === source.id || !group.besideOf?.includes(source.id)) continue;
|
||||||
|
const overlap = Math.min(group.bottom, source.bottom) - Math.max(group.top, source.top);
|
||||||
|
if (group.left < source.right - 4 || overlap <= 0) continue;
|
||||||
|
if (!best || group.left < best.left || (group.left === best.left && group.top < best.top)) best = group;
|
||||||
|
}
|
||||||
|
return best?.id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ids of visible site panes whose navigation duplicates the leftmost site pane of the same account. */
|
||||||
|
export function redundantNavPanes(panes: readonly PaneBox[], isSiteUrl: (url: string) => boolean): Set<string> {
|
||||||
|
const lead = new Map<string, PaneBox>();
|
||||||
|
const redundant = new Set<string>();
|
||||||
|
const ordered = panes
|
||||||
|
.filter(pane => pane.visible && isSiteUrl(pane.url))
|
||||||
|
.sort((a, b) => a.x - b.x || a.y - b.y || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||||
|
for (const pane of ordered) {
|
||||||
|
if (lead.has(pane.profile)) redundant.add(pane.id);
|
||||||
|
else lead.set(pane.profile, pane);
|
||||||
|
}
|
||||||
|
return redundant;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `navRedundant` flag per tab for `tabs_sync`. Only visible panes are judged (a shell overlay
|
||||||
|
* hides them all and so changes nothing); a hidden tab keeps its last value (`memory`) so it shows
|
||||||
|
* up again without a flicker. Tabs that are gone are forgotten.
|
||||||
|
*/
|
||||||
|
export function withNavRedundant<T extends PaneBox>(boxes: readonly T[], isSiteUrl: (url: string) => boolean, memory: Map<string, boolean>): Array<T & { navRedundant: boolean }> {
|
||||||
|
const redundant = redundantNavPanes(boxes, isSiteUrl);
|
||||||
|
const items = boxes.map(box => {
|
||||||
|
if (box.visible) memory.set(box.id, redundant.has(box.id));
|
||||||
|
return { ...box, navRedundant: memory.get(box.id) ?? false };
|
||||||
|
});
|
||||||
|
for (const id of memory.keys()) if (!boxes.some(box => box.id === id)) memory.delete(id);
|
||||||
|
return items;
|
||||||
|
}
|
||||||
113
packages/shell/src/profileModel.ts
Normal file
113
packages/shell/src/profileModel.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
// Pure model for account profiles (no Tauri imports, so it is unit-tested under node).
|
||||||
|
// Mirrors `ProfileSettings` in waybetter-host `profiles.rs`; Rust validates again on save.
|
||||||
|
|
||||||
|
/** The login inside a profile, as native code last saw it (read-only here; see profiles.rs). */
|
||||||
|
export type Account = { handle: string; name: string; avatar?: string; signedIn: boolean };
|
||||||
|
export type Profile = { id: string; name: string; color: string; account?: Account };
|
||||||
|
export type ProfileSettings = { profiles: Profile[]; active: string };
|
||||||
|
|
||||||
|
/** The site's account rules, as in the native `AccountRules`. */
|
||||||
|
export type AccountRules = {
|
||||||
|
handle: RegExp;
|
||||||
|
/** Avatar URLs must start with one of these. */
|
||||||
|
avatarPrefixes: readonly string[];
|
||||||
|
/** Shown before the handle in the switcher, e.g. '@'. */
|
||||||
|
handlePrefix: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_PROFILE = 'default';
|
||||||
|
export const PROFILE_COLORS = ['#1d9bf0', '#f91880', '#00ba7c', '#ffd400', '#7856ff', '#ff7a00', '#22d3ee', '#a3a3a3'];
|
||||||
|
|
||||||
|
export const defaultProfiles = (): ProfileSettings => ({
|
||||||
|
profiles: [{ id: DEFAULT_PROFILE, name: 'Main', color: PROFILE_COLORS[0]! }],
|
||||||
|
active: DEFAULT_PROFILE,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const validProfileId = (id: unknown): id is string =>
|
||||||
|
typeof id === 'string' && (id === DEFAULT_PROFILE || /^p[a-z0-9]{1,32}$/.test(id));
|
||||||
|
|
||||||
|
export const validColor = (color: unknown): color is string => typeof color === 'string' && /^#[0-9a-fA-F]{6}$/.test(color);
|
||||||
|
|
||||||
|
export function cleanName(name: string): string | null {
|
||||||
|
const trimmed = name.trim();
|
||||||
|
// eslint-disable-next-line no-control-regex
|
||||||
|
if (!trimmed || [...trimmed].length > 40 || /[\u0000-\u001f\u007f-\u009f]/.test(trimmed)) return null;
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything from storage or IPC → a usable settings object (always has the default profile). */
|
||||||
|
export function normalizeProfiles(value: unknown, rules: AccountRules): ProfileSettings {
|
||||||
|
const input = value as Partial<ProfileSettings> | null;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const profiles: Profile[] = [];
|
||||||
|
for (const raw of Array.isArray(input?.profiles) ? input!.profiles : []) {
|
||||||
|
const name = typeof raw?.name === 'string' ? cleanName(raw.name) : null;
|
||||||
|
if (!validProfileId(raw?.id) || seen.has(raw.id) || !name || !validColor(raw.color)) continue;
|
||||||
|
seen.add(raw.id);
|
||||||
|
const account = normalizeAccount(raw.account, rules);
|
||||||
|
profiles.push({ id: raw.id, name, color: raw.color.toLowerCase(), ...(account ? { account } : {}) });
|
||||||
|
}
|
||||||
|
if (!seen.has(DEFAULT_PROFILE)) profiles.unshift(defaultProfiles().profiles[0]!);
|
||||||
|
const active = typeof input?.active === 'string' && profiles.some(p => p.id === input.active) ? input.active : DEFAULT_PROFILE;
|
||||||
|
return { profiles, active };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeAccount(value: unknown, rules: AccountRules): Account | undefined {
|
||||||
|
const raw = value as Partial<Account> | null | undefined;
|
||||||
|
if (!raw || typeof raw.handle !== 'string' || !rules.handle.test(raw.handle)) return undefined;
|
||||||
|
const avatar = typeof raw.avatar === 'string' && rules.avatarPrefixes.some(prefix => raw.avatar!.startsWith(prefix)) ? raw.avatar : undefined;
|
||||||
|
return { handle: raw.handle, name: typeof raw.name === 'string' && raw.name.trim() ? raw.name : raw.handle, signedIn: raw.signedIn === true, ...(avatar ? { avatar } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the switcher shows for a profile: the login once seen, the profile name before. */
|
||||||
|
export function accountLabel(profile: Profile, rules: Pick<AccountRules, 'handlePrefix'>): { title: string; detail: string; state: 'signed-in' | 'signed-out' | 'new' } {
|
||||||
|
if (!profile.account) return { title: profile.name, detail: 'Not signed in yet', state: 'new' };
|
||||||
|
return {
|
||||||
|
title: profile.account.name,
|
||||||
|
detail: `${rules.handlePrefix}${profile.account.handle}${profile.account.signedIn ? '' : ' · signed out'}`,
|
||||||
|
state: profile.account.signedIn ? 'signed-in' : 'signed-out',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newProfileId(random: () => number = Math.random): string {
|
||||||
|
return `p${Date.now().toString(36)}${Math.floor(random() * 36 ** 6).toString(36)}`.slice(0, 33);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function nextColor(settings: ProfileSettings): string {
|
||||||
|
const used = new Set(settings.profiles.map(p => p.color));
|
||||||
|
return PROFILE_COLORS.find(color => !used.has(color)) ?? PROFILE_COLORS[settings.profiles.length % PROFILE_COLORS.length]!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds a profile and makes it active. Unlimited count (Rust caps absurd sizes). Its name follows the
|
||||||
|
* account once someone signs in there; until then it is a placeholder. */
|
||||||
|
export function addProfile(settings: ProfileSettings, name = '', id = newProfileId()): ProfileSettings {
|
||||||
|
const clean = cleanName(name) ?? 'New account';
|
||||||
|
if (!validProfileId(id) || settings.profiles.some(p => p.id === id)) throw new Error('VALIDATION: invalid profile id');
|
||||||
|
return { profiles: [...settings.profiles, { id, name: clean, color: nextColor(settings) }], active: id };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renameProfile(settings: ProfileSettings, id: string, name: string): ProfileSettings {
|
||||||
|
const clean = cleanName(name);
|
||||||
|
if (!clean) return settings;
|
||||||
|
return { ...settings, profiles: settings.profiles.map(p => (p.id === id ? { ...p, name: clean } : p)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function recolorProfile(settings: ProfileSettings, id: string, color: string): ProfileSettings {
|
||||||
|
if (!validColor(color)) return settings;
|
||||||
|
return { ...settings, profiles: settings.profiles.map(p => (p.id === id ? { ...p, color: color.toLowerCase() } : p)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The default profile cannot be removed; removing the active one falls back to default. */
|
||||||
|
export function removeProfile(settings: ProfileSettings, id: string): ProfileSettings {
|
||||||
|
if (id === DEFAULT_PROFILE) return settings;
|
||||||
|
const profiles = settings.profiles.filter(p => p.id !== id);
|
||||||
|
return { profiles, active: settings.active === id ? DEFAULT_PROFILE : settings.active };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const setActiveProfile = (settings: ProfileSettings, id: string): ProfileSettings =>
|
||||||
|
settings.profiles.some(p => p.id === id) ? { ...settings, active: id } : settings;
|
||||||
|
|
||||||
|
/** The profile a tab really runs in: unknown or missing ids (old layouts) use the default. */
|
||||||
|
export function tabProfile(settings: ProfileSettings, id: string | undefined): Profile {
|
||||||
|
return settings.profiles.find(p => p.id === id) ?? settings.profiles.find(p => p.id === DEFAULT_PROFILE) ?? defaultProfiles().profiles[0]!;
|
||||||
|
}
|
||||||
44
packages/shell/src/updateModel.ts
Normal file
44
packages/shell/src/updateModel.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
// Pure model for the titlebar update chip (no Tauri imports, so it is unit-tested under node).
|
||||||
|
|
||||||
|
/** Mirrors `UpdateStatus` in waybetter-host `update.rs` (serde tag "state"). */
|
||||||
|
export type UpdateStatus =
|
||||||
|
| { state: 'idle' | 'checking' | 'upToDate' }
|
||||||
|
| { state: 'downloading' | 'installing'; version: string }
|
||||||
|
| { state: 'ready'; version: string; notes: string }
|
||||||
|
| { state: 'error'; message: string }
|
||||||
|
| { state: 'problem'; downloadUrl: string };
|
||||||
|
|
||||||
|
export type UpdateChip =
|
||||||
|
| { kind: 'restart'; label: string; title: string }
|
||||||
|
| { kind: 'installing'; label: string; title: string }
|
||||||
|
| { kind: 'problem'; label: string; title: string; href: string };
|
||||||
|
|
||||||
|
const STATES = new Set(['idle', 'checking', 'upToDate', 'downloading', 'installing', 'ready', 'error', 'problem']);
|
||||||
|
|
||||||
|
/** Accepts only well-formed status payloads; anything else is treated as idle. */
|
||||||
|
export function parseUpdateStatus(value: unknown): UpdateStatus {
|
||||||
|
if (!value || typeof value !== 'object') return { state: 'idle' };
|
||||||
|
const v = value as Record<string, unknown>;
|
||||||
|
if (typeof v.state !== 'string' || !STATES.has(v.state)) return { state: 'idle' };
|
||||||
|
const str = (key: string) => (typeof v[key] === 'string' ? (v[key] as string) : '');
|
||||||
|
switch (v.state) {
|
||||||
|
case 'ready': return { state: 'ready', version: str('version'), notes: str('notes') };
|
||||||
|
case 'downloading': case 'installing': return { state: v.state, version: str('version') };
|
||||||
|
case 'error': return { state: 'error', message: str('message') };
|
||||||
|
case 'problem': {
|
||||||
|
const href = str('downloadUrl');
|
||||||
|
return href.startsWith('https://') ? { state: 'problem', downloadUrl: href } : { state: 'idle' };
|
||||||
|
}
|
||||||
|
default: return { state: v.state as 'idle' | 'checking' | 'upToDate' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unobtrusive: nothing while checking/downloading/erroring; a chip only when action is useful. */
|
||||||
|
export function chipFor(status: UpdateStatus, product: string): UpdateChip | null {
|
||||||
|
switch (status.state) {
|
||||||
|
case 'ready': return { kind: 'restart', label: 'Update ready · restart', title: `Restart to update to ${product} ${status.version}. Tabs are restored.` };
|
||||||
|
case 'installing': return { kind: 'installing', label: 'Updating…', title: `Installing ${product} ${status.version}` };
|
||||||
|
case 'problem': return { kind: 'problem', label: 'Update problem', title: 'The last update did not start correctly. Download the current version.', href: status.downloadUrl };
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
packages/shell/src/windowControls.ts
Normal file
36
packages/shell/src/windowControls.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
// Native window calls for the custom titlebar, resize grips and caption buttons. The Tauri API is
|
||||||
|
// passed in (the app owns its `@tauri-apps/api` version), so this module has no dependencies.
|
||||||
|
|
||||||
|
export type ResizeDirection = 'North' | 'South' | 'East' | 'West' | 'NorthEast' | 'NorthWest' | 'SouthEast' | 'SouthWest';
|
||||||
|
|
||||||
|
/** The subset of Tauri's `Window` the shell uses. */
|
||||||
|
export type NativeWindow = {
|
||||||
|
minimize(): Promise<void>;
|
||||||
|
toggleMaximize(): Promise<void>;
|
||||||
|
close(): Promise<void>;
|
||||||
|
startResizeDragging(direction: ResizeDirection): Promise<void>;
|
||||||
|
isMaximized(): Promise<boolean>;
|
||||||
|
onResized(handler: () => void): Promise<() => void>;
|
||||||
|
};
|
||||||
|
export type Invoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||||
|
|
||||||
|
export const isTauri = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||||
|
/** macOS keeps a native (overlay) frame with traffic lights; Windows is frameless with our own caption buttons. */
|
||||||
|
export const os: 'macos' | 'windows' = typeof navigator !== 'undefined' && /Mac/i.test(navigator.userAgent) ? 'macos' : 'windows';
|
||||||
|
export const frameless = isTauri && os !== 'macos';
|
||||||
|
|
||||||
|
export function createWindowControls(invoke: Invoke, currentWindow: () => NativeWindow) {
|
||||||
|
return {
|
||||||
|
minimize: () => currentWindow().minimize().catch(() => {}),
|
||||||
|
toggleMaximize: () => currentWindow().toggleMaximize().catch(() => {}),
|
||||||
|
close: () => currentWindow().close().catch(() => {}),
|
||||||
|
startResize: (direction: ResizeDirection) => currentWindow().startResizeDragging(direction).catch(() => {}),
|
||||||
|
onMaximizedChange: (cb: (maximized: boolean) => void) => {
|
||||||
|
const read = () => { currentWindow().isMaximized().then(cb).catch(() => {}); };
|
||||||
|
read();
|
||||||
|
return currentWindow().onResized(read);
|
||||||
|
},
|
||||||
|
/** The native system menu at a screen position (host `system_menu`; Windows only). */
|
||||||
|
systemMenu: (x: number, y: number) => invoke('window_system_menu', { x, y }).catch(() => {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
56
packages/shell/tests/linkDrop.test.ts
Normal file
56
packages/shell/tests/linkDrop.test.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { carriesLink, dropUrl, placementFor, webUrl } from '../src/linkDrop.ts';
|
||||||
|
|
||||||
|
const data = (entries: Record<string, string>) => (type: string) => entries[type] ?? '';
|
||||||
|
|
||||||
|
test('only plain http(s) links are accepted', () => {
|
||||||
|
assert.equal(webUrl('https://x.com/jack/status/20'), 'https://x.com/jack/status/20');
|
||||||
|
assert.equal(webUrl(' http://example.com '), 'http://example.com/');
|
||||||
|
for (const bad of ['javascript:alert(1)', 'file:///C:/Windows/win.ini', 'data:text/html,hi', 'about:blank',
|
||||||
|
'https://user:pw@example.com/', 'x.com/home', '', null, undefined, `https://example.com/${'a'.repeat(5000)}`]) {
|
||||||
|
assert.equal(webUrl(bad), null, String(bad));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('uri-list wins, skipping comments and blank lines', () => {
|
||||||
|
const get = data({ 'text/uri-list': '# dragged from a browser\r\n\r\nhttps://x.com/home\r\nhttps://example.com/', 'text/plain': 'https://other.test/' });
|
||||||
|
assert.equal(dropUrl(get), 'https://x.com/home');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to text/x-moz-url, then text/plain, then the reported link', () => {
|
||||||
|
assert.equal(dropUrl(data({ 'text/x-moz-url': 'https://example.com/a\nExample' })), 'https://example.com/a');
|
||||||
|
assert.equal(dropUrl(data({ 'text/plain': 'https://x.com/i/lists/1\nsecond line' })), 'https://x.com/i/lists/1');
|
||||||
|
assert.equal(dropUrl(data({ 'text/plain': 'just some words' }), 'https://x.com/jack'), 'https://x.com/jack');
|
||||||
|
assert.equal(dropUrl(() => { throw new Error('protected mode'); }, 'https://x.com/jack'), 'https://x.com/jack');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a dangerous dropped link never beats a safe reported one, and nothing unsafe opens', () => {
|
||||||
|
assert.equal(dropUrl(data({ 'text/uri-list': 'javascript:alert(1)' }), 'https://x.com/home'), 'https://x.com/home');
|
||||||
|
assert.equal(dropUrl(data({ 'text/uri-list': 'file:///etc/passwd' })), null);
|
||||||
|
assert.equal(dropUrl(data({}), 'javascript:alert(1)'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('file drags are left to the page; link drags are recognised', () => {
|
||||||
|
assert.equal(carriesLink(['text/uri-list', 'text/plain']), true);
|
||||||
|
assert.equal(carriesLink(['text/x-moz-url']), true);
|
||||||
|
assert.equal(carriesLink(['Files', 'text/uri-list']), false);
|
||||||
|
assert.equal(carriesLink(['text/plain']), false);
|
||||||
|
assert.equal(carriesLink([]), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pane edges split in that direction, center and tabs open a tab in that group', () => {
|
||||||
|
assert.deepEqual(placementFor({ position: 'right', groupId: 'g1' }), { referenceGroup: 'g1', direction: 'right' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'left', groupId: 'g1' }), { referenceGroup: 'g1', direction: 'left' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'top', groupId: 'g1' }), { referenceGroup: 'g1', direction: 'above' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'bottom', groupId: 'g1' }), { referenceGroup: 'g1', direction: 'below' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'center', groupId: 'g1' }), { referenceGroup: 'g1', direction: 'within' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'center', groupId: 'g1', tabIndex: 2 }), { referenceGroup: 'g1', direction: 'within', index: 2 });
|
||||||
|
assert.deepEqual(placementFor({ position: 'center', groupId: 'g1', tabIndex: 0 }), { referenceGroup: 'g1', direction: 'within', index: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dock outer edges split the whole dock; no target means the default tab', () => {
|
||||||
|
assert.deepEqual(placementFor({ position: 'left' }), { direction: 'left' });
|
||||||
|
assert.deepEqual(placementFor({ position: 'bottom' }), { direction: 'below' });
|
||||||
|
assert.equal(placementFor({ position: 'center' }), undefined);
|
||||||
|
});
|
||||||
112
packages/shell/tests/models.test.ts
Normal file
112
packages/shell/tests/models.test.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { parseAddress, type AddressSite } from '../src/addressModel.ts';
|
||||||
|
import { besideGroup, redundantNavPanes, withNavRedundant, type PaneBox } from '../src/paneModel.ts';
|
||||||
|
import { fuzzyScore, moveSelection, rankItems } from '../src/palette.ts';
|
||||||
|
import { accountLabel, addProfile, normalizeProfiles, removeProfile, tabProfile, type AccountRules } from '../src/profileModel.ts';
|
||||||
|
import { chipFor, parseUpdateStatus } from '../src/updateModel.ts';
|
||||||
|
|
||||||
|
const SITE: AddressSite<'kick'> = {
|
||||||
|
kind: 'kick',
|
||||||
|
hosts: new Set(['kick.com', 'www.kick.com']),
|
||||||
|
label: 'Kick',
|
||||||
|
home: origin => `${origin}/`,
|
||||||
|
segments: url => {
|
||||||
|
const [channel] = url.pathname.split('/').filter(Boolean);
|
||||||
|
if (channel === 'settings') return null;
|
||||||
|
return channel ? [{ label: channel, href: `${url.origin}/${channel}` }] : [{ label: 'Home', href: `${url.origin}/` }];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
test('address: the site adapter names its own pages; other sites get host chips', () => {
|
||||||
|
const kick = parseAddress('https://kick.com/somechannel', SITE)!;
|
||||||
|
assert.deepEqual(kick.site, { kind: 'kick', label: 'Kick', href: 'https://kick.com/' });
|
||||||
|
assert.deepEqual(kick.segments.map(s => s.label), ['somechannel']);
|
||||||
|
assert.equal((kick.segments[0] as { current?: boolean }).current, true);
|
||||||
|
assert.equal(parseAddress('https://kick.com/settings/profile', SITE), null, 'an internal page shows no chips');
|
||||||
|
const other = parseAddress('http://www.example.com/a/b%20c?q=1', SITE)!;
|
||||||
|
assert.deepEqual(other.site, { kind: 'host', label: 'example.com', href: 'http://www.example.com' });
|
||||||
|
assert.deepEqual(other.segments.map(s => s.label), ['a', 'b c', '?…']);
|
||||||
|
assert.equal(other.insecure, true);
|
||||||
|
for (const bad of ['about:blank', 'file:///c:/x', 'javascript:1', 'nonsense']) assert.equal(parseAddress(bad, SITE), null, bad);
|
||||||
|
assert.equal(parseAddress('https://kick.com/x')!.site.kind, 'host', 'without an adapter every site is a host');
|
||||||
|
});
|
||||||
|
|
||||||
|
const onSite = (url: string) => url.startsWith('https://site.test/');
|
||||||
|
const pane = (id: string, x: number, y = 0, extra: Partial<PaneBox> = {}): PaneBox =>
|
||||||
|
({ id, url: 'https://site.test/feed', profile: 'default', x, y, visible: true, ...extra });
|
||||||
|
|
||||||
|
test('panes: only the leftmost (then topmost) site pane of an account keeps the rail', () => {
|
||||||
|
assert.deepEqual([...redundantNavPanes([pane('right', 800), pane('left', 0)], onSite)], ['right']);
|
||||||
|
assert.deepEqual([...redundantNavPanes([pane('bottom', 0, 400), pane('top', 0, 40)], onSite)], ['bottom']);
|
||||||
|
assert.equal(redundantNavPanes([pane('other', 0, 0, { url: 'https://example.com/' }), pane('site', 700)], onSite).size, 0);
|
||||||
|
assert.deepEqual([...redundantNavPanes([pane('main', 0), pane('alt', 700, 0, { profile: 'p2' }), pane('main-2', 1400)], onSite)], ['main-2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('panes: hidden tabs keep their last navRedundant value; closed tabs are forgotten', () => {
|
||||||
|
const memory = new Map<string, boolean>();
|
||||||
|
const first = withNavRedundant([pane('a', 0), pane('b', 700)], onSite, memory);
|
||||||
|
assert.deepEqual(first.map(item => item.navRedundant), [false, true]);
|
||||||
|
const hidden = withNavRedundant([pane('a', 0, 0, { visible: false }), pane('b', 700, 0, { visible: false })], onSite, memory);
|
||||||
|
assert.deepEqual(hidden.map(item => item.navRedundant), [false, true], 'an overlay changes nothing');
|
||||||
|
withNavRedundant([pane('a', 0)], onSite, memory);
|
||||||
|
assert.deepEqual([...memory.keys()], ['a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('panes: beside links reuse the side pane this source opened', () => {
|
||||||
|
const source = { id: 'g1', left: 0, top: 0, right: 600, bottom: 800 };
|
||||||
|
const side = { id: 'g2', left: 600, top: 0, right: 1200, bottom: 800, besideOf: ['g1'] };
|
||||||
|
const mine = { id: 'g3', left: 600, top: 0, right: 1200, bottom: 800 };
|
||||||
|
assert.equal(besideGroup(source, [source, mine, side]), 'g2');
|
||||||
|
assert.equal(besideGroup(source, [source, mine]), null, 'a group the user opened is never taken over');
|
||||||
|
assert.equal(besideGroup(source, [{ ...side, left: 0, right: 300 }]), null, 'not to the right any more');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('palette: prefix beats substring beats subsequence; ranking is stable', () => {
|
||||||
|
assert.ok(fuzzyScore('Notifications', 'noti') > fuzzyScore('Annotations', 'noti'));
|
||||||
|
assert.ok(fuzzyScore('Split right', 'spr') > 0);
|
||||||
|
assert.equal(fuzzyScore('Home', 'xyz'), 0);
|
||||||
|
const items = [
|
||||||
|
{ label: 'Open settings', group: 'App' },
|
||||||
|
{ label: 'Settings', group: 'App' },
|
||||||
|
{ label: 'Search', group: 'Search', keywords: 'settings' },
|
||||||
|
{ label: 'Other', group: 'App', keywords: 'settings page' },
|
||||||
|
];
|
||||||
|
assert.deepEqual(rankItems(items, 'settings', item => item.group === 'Search').map(i => i.label), ['Settings', 'Open settings', 'Other']);
|
||||||
|
assert.equal(moveSelection(0, -1, 3), 2);
|
||||||
|
assert.equal(moveSelection(2, 1, 3), 0);
|
||||||
|
assert.equal(moveSelection(5, 1, 0), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
const RULES: AccountRules = { handle: /^[a-z0-9_]{3,25}$/, avatarPrefixes: ['https://files.site.test/'], handlePrefix: '' };
|
||||||
|
|
||||||
|
test('profiles: storage input is normalized with the site account rules', () => {
|
||||||
|
const settings = normalizeProfiles({
|
||||||
|
active: 'p9',
|
||||||
|
profiles: [
|
||||||
|
{ id: 'p1', name: ' Work ', color: '#ABCDEF', account: { handle: 'streamer_1', name: '', signedIn: true, avatar: 'https://evil.test/a.png' } },
|
||||||
|
{ id: 'p1', name: 'Duplicate', color: '#000000' },
|
||||||
|
{ id: '../x', name: 'Bad', color: '#000000' },
|
||||||
|
{ id: 'p2', name: 'Bad handle', color: '#000000', account: { handle: 'no', name: 'x', signedIn: true } },
|
||||||
|
],
|
||||||
|
}, RULES);
|
||||||
|
assert.deepEqual(settings.profiles.map(p => p.id), ['default', 'p1', 'p2']);
|
||||||
|
assert.equal(settings.active, 'default');
|
||||||
|
assert.deepEqual(settings.profiles[1]!.account, { handle: 'streamer_1', name: 'streamer_1', signedIn: true });
|
||||||
|
assert.equal(settings.profiles[2]!.account, undefined);
|
||||||
|
assert.deepEqual(accountLabel(settings.profiles[1]!, RULES), { title: 'streamer_1', detail: 'streamer_1', state: 'signed-in' });
|
||||||
|
assert.equal(accountLabel({ ...settings.profiles[1]!, account: { handle: 'a_b', name: 'A', signedIn: false } }, { handlePrefix: '@' }).detail, '@a_b · signed out');
|
||||||
|
const added = addProfile(settings, '', 'p3');
|
||||||
|
assert.equal(added.active, 'p3');
|
||||||
|
assert.equal(removeProfile(added, 'default'), added, 'the default profile stays');
|
||||||
|
assert.equal(removeProfile(added, 'p3').active, 'default');
|
||||||
|
assert.equal(tabProfile(added, 'gone').id, 'default');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('update chip: only actionable states show, with the product name', () => {
|
||||||
|
assert.deepEqual(parseUpdateStatus({ state: 'ready', version: '1.2.0' }), { state: 'ready', version: '1.2.0', notes: '' });
|
||||||
|
assert.deepEqual(parseUpdateStatus({ state: 'problem', downloadUrl: 'http://insecure' }), { state: 'idle' });
|
||||||
|
assert.deepEqual(parseUpdateStatus('nope'), { state: 'idle' });
|
||||||
|
assert.equal(chipFor({ state: 'checking' }, 'wayBetter for Kick'), null);
|
||||||
|
assert.match(chipFor({ state: 'ready', version: '1.2.0', notes: '' }, 'wayBetter for Kick')!.title, /wayBetter for Kick 1\.2\.0/);
|
||||||
|
});
|
||||||
29
packages/shell/tests/windowControls.test.ts
Normal file
29
packages/shell/tests/windowControls.test.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { createWindowControls, type NativeWindow } from '../src/windowControls.ts';
|
||||||
|
|
||||||
|
test('window controls call the injected window and never throw', async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const failing = () => Promise.reject(new Error('no window'));
|
||||||
|
const win: NativeWindow = {
|
||||||
|
minimize: async () => { calls.push('minimize'); },
|
||||||
|
toggleMaximize: failing,
|
||||||
|
close: async () => { calls.push('close'); },
|
||||||
|
startResizeDragging: async direction => { calls.push(`resize:${direction}`); },
|
||||||
|
isMaximized: async () => true,
|
||||||
|
onResized: async () => () => {},
|
||||||
|
};
|
||||||
|
const invoked: unknown[] = [];
|
||||||
|
const controls = createWindowControls(async (command, args) => { invoked.push([command, args]); }, () => win);
|
||||||
|
await controls.minimize();
|
||||||
|
await controls.toggleMaximize();
|
||||||
|
await controls.close();
|
||||||
|
await controls.startResize('SouthEast');
|
||||||
|
await controls.systemMenu(10, 20);
|
||||||
|
let maximized: boolean | null = null;
|
||||||
|
await controls.onMaximizedChange(value => { maximized = value; });
|
||||||
|
await Promise.resolve();
|
||||||
|
assert.deepEqual(calls, ['minimize', 'close', 'resize:SouthEast']);
|
||||||
|
assert.deepEqual(invoked, [['window_system_menu', { x: 10, y: 20 }]]);
|
||||||
|
assert.equal(maximized, true);
|
||||||
|
});
|
||||||
19
tsconfig.json
Normal file
19
tsconfig.json
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["packages/*/src", "packages/*/tests"]
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue