Compare commits

...

172 commits

Author SHA1 Message Date
2418cb636a
Merge pull request #37 from marcoallegretti/build/set-version-0.0.1-alpha.0
Some checks failed
ci / portable (push) Has been cancelled
ci / linux-only (push) Has been cancelled
ci / runtime-grants (push) Has been cancelled
ci / servo-embed-linux (push) Has been cancelled
ci / contributor-toolkit (push) Has been cancelled
2026-10-10 18:10:41 +02:00
d0864fcbe9
build: set the workspace version to 0.0.1-alpha.0
The workspace declared 0.1.0, the stable target, although nothing has
been released: it was a development placeholder. The workspace crates
and the Nix packages now carry 0.0.1-alpha.0, the first prerelease
toward 0.0.1, and the README records that 0.1.0 was never published.
Application, package and WIT interface versions are unchanged.
2026-10-10 15:37:19 +00:00
90669ae93b
Merge fix/confine-mount-helper: confine the setuid mount helper and install it in the graphical VM (#35) 2026-10-10 09:28:06 +02:00
f2d84de5f1
Merge remote-tracking branch 'origin/main' into fix/confine-mount-helper
# Conflicts:
#	docs/security.md
2026-10-10 07:27:58 +00:00
5937025697
Merge fix/image-session-wiring: start the reference session's services and connect them to the compositor (#34) 2026-10-10 09:27:29 +02:00
7e9df63d87
Merge fix/end-runtime-on-ipc-hangup: end the runtime when its session's IPC connection closes (#36) 2026-10-10 09:27:22 +02:00
a454efa869
Merge remote-tracking branch 'origin/main' into fix/end-runtime-on-ipc-hangup
# Conflicts:
#	docs/architecture.md
2026-10-10 07:27:15 +00:00
e1796d39a1
Merge fix/bound-desktop-helpers: bound the clipboard and notification helpers and attribute notifications (#30) 2026-10-10 09:26:47 +02:00
0c527dfada
Merge fix/runtime-resource-limits: bound component memory and app messages in the runtime (#27) 2026-10-10 09:26:39 +02:00
e28897d987
Merge remote-tracking branch 'origin/main' into fix/runtime-resource-limits
# Conflicts:
#	tests/runtime/check_grants.py
2026-10-10 07:26:31 +00:00
8e874714ad
Merge fix/ipc-relay-framing: keep component messages whole in the session IPC relay (#32) 2026-10-10 09:25:51 +02:00
da3247667e
Merge fix/nixos-mesa-package: use the mesa package for the VM's graphics drivers (#31) 2026-10-10 09:25:49 +02:00
656c3df8fd
Merge fix/confine-file-portal: confine file portal operations beneath the granted directory (#28) 2026-10-10 09:25:46 +02:00
2020bfe2c2
Merge fix/fetch-public-destinations: reach only public addresses through a fetch grant for a name (#26) 2026-10-10 09:25:44 +02:00
3f4545ae66
Merge fix/keyboard-system-navigation: reach and operate the system UI from the keyboard (#33) 2026-10-10 09:25:35 +02:00
373cec1bab
Merge remote-tracking branch 'origin/main' into fix/keyboard-system-navigation
# Conflicts:
#	docs/building.md
2026-10-10 07:25:25 +00:00
400f430ced
Merge feat/app-close-policy: let an application decline a close to keep unsaved changes (#24) 2026-10-10 09:25:00 +02:00
da485a182b
Merge fix/close-sessions-gracefully: close app sessions gracefully before terminating them (#23) 2026-10-10 09:24:51 +02:00
3577b3ee1a
Merge fix/close-app-windows: close the focused window on Alt+F4 and let the Servo hosts exit without crashing (#22) 2026-10-10 09:24:41 +02:00
c557b24dce
Merge fix/reserve-panel-work-area: reserve the taskbar strip and lay application windows out in the work area (#21) 2026-10-10 09:24:31 +02:00
4b9e7b7773
Merge remote-tracking branch 'origin/main' into fix/reserve-panel-work-area
# Conflicts:
#	docs/building.md
2026-10-10 07:24:23 +00:00
87b7125281
Merge fix/activate-app-windows: own window stacking and focus in the compositor and activate app windows on request (#20) 2026-10-10 09:24:09 +02:00
bc2c155d24
Merge remote-tracking branch 'origin/main' into fix/activate-app-windows
# Conflicts:
#	docs/building.md
2026-10-10 07:23:50 +00:00
ff6ecacbb6
Merge fix/bind-app-surfaces-to-sessions: bind each app session's Wayland client to its session through appd (#18) 2026-10-10 09:23:18 +02:00
94d43b12f3
Merge feat/capability-approval: grant an app only the capabilities the user approved (#29) 2026-10-10 09:22:36 +02:00
74135a462a
Merge feat/transactional-package-install: install and update packages as immutable revisions activated atomically (#25) 2026-10-10 09:22:06 +02:00
76839f6ec2
Merge fix/verify-packages-at-launch: verify package owner and signature before a session starts (#19) 2026-10-10 09:21:40 +02:00
9b1e7cb940
Merge fix/verify-package-trust: install only trusted packages and bind each app ID to its owner (#17) 2026-10-10 09:21:27 +02:00
8e910c507c
docs(architecture): say where weft-appd's children log
Following the move of weft-runtime and weft-app-shell logging to
standard error: their stdout carries only the readiness line, and appd
records stderr at info level and other stdout output at debug level.
2026-10-09 21:22:29 +00:00
83fca91772
fix(runtime): log to standard error, without colours when piped
weft-runtime and weft-app-shell logged to standard output, which carries
their readiness line to weft-appd. weft-appd keeps that stream only at
debug level, so the runtime's warnings and errors, such as a failed
grant or an ended IPC connection, never reached its log, and the lines
carried terminal colour codes.

Both now log to standard error, which weft-appd records at info level,
with colours only on a terminal. In the nested desktop Counter check,
the runtime's own lines appear in weft-appd's log; the grants check
reads the hangup message from standard error.
2026-10-09 21:13:29 +00:00
57f364890f
fix(runtime): end the runtime when its session's IPC connection closes
A runtime outlived the weft-appd that started it. Runtimes run in their
own systemd scopes, outside weft-appd's service, and a component that
waits for messages, as the Counter and Notes demos do, keeps polling a
closed connection forever. Each time weft-appd stopped or restarted and
restored the previous session, the earlier runtimes stayed behind.

The connection is the session: a thread waits for it to hang up, without
reading from it, and the runtime then exits whatever the component is
doing. That covers weft-appd closing the connection, weft-appd ending,
and the runtime ending the connection itself after a failed send or an
overlong message. A runtime given an IPC socket it cannot connect to now
fails instead of running unreachable. weft-appd's relay notes that it
must not shut down half of the connection, which would now end the
session.

tests/runtime/check_grants.py runs the real runtime on the Counter
component over a Unix socket: it answers an increment, and once the test
closes its end the runtime exits with status 0 within 10 seconds; with
the watcher removed it keeps running and the check fails. A unit test
checks that the wait sees a hangup but neither wakes on nor consumes
pending data; CI's runtime-grants job now runs the runtime's unit tests
with its features. The nested desktop Counter and Notes checks pass with
this runtime.
2026-10-09 21:11:23 +00:00
bc649d17c4
fix(nixos): show the session and install the mount helper setuid
The VM ran without graphics, so the desktop could not be seen, and
weft-appd was pointed at the mount helper's store path, which cannot be
set-user-ID, so verified package images could not mount.

The VM opens a graphics window, with tty0 as the primary console and the
serial console as a secondary one. weft-mount-helper is installed
through security.wrappers, setuid root and executable only by the
users group, built to run cryptsetup's veritysetup, and weft-appd uses
/run/wrappers/bin/weft-mount-helper.
2026-10-09 20:56:52 +00:00
076ed95eb1
fix(mount-helper): confine what a setuid caller can mount and unmount
weft-mount-helper is meant to be installed setuid root, but it trusted
its caller entirely: it ran veritysetup, mount and umount from the
caller's PATH, mounted a caller's image at any directory, such as over
/etc, and unmounted any mountpoint. Any local user could have gained
root through it.

It now mounts only at an empty directory
/run/user/<uid>/weft/mnt/<name> of the real user, where weft-appd puts
its mountpoints, with every component from <uid> on owned by that user,
not writable by others and opened without following symbolic links,
and mounts through the opened directory, so the path cannot be swapped
meanwhile. It opens the image and hash tree with the real user's
permissions, checks the root hash is a hex digest, mounts read-only with
nosuid, nodev and noexec through mount(2), and unmounts only an EROFS
filesystem at such a directory. veritysetup runs from the absolute path
fixed at build time (WEFT_VERITYSETUP, /usr/sbin/veritysetup by
default), with an empty environment. Devices are named
weft-<uid>-<name>, so a user reaches only their own; a device left by an
interrupted mount is closed by the next mount or unmount at that
directory, and a user may have at most 64 open, counted from the
kernel's list of device-mapper devices under a root-owned lock. Closed standard streams
are reopened on /dev/null before anything else is opened, and errors and
panics are printed as one-line messages.

Run setuid as nobody with a PATH holding a hostile veritysetup and
mount, the helper refuses /etc and another user's directory as
mountpoints, a symbolic link to /etc, a file nobody cannot read, a
malformed root hash, and unmounting /etc or a directory with no image;
a valid request reaches veritysetup at its fixed path, also with the
standard streams closed, and the hostile programs never run. Unit tests cover the mountpoint rules.
2026-10-09 20:56:52 +00:00
a1edac63b8
fix(session): start the session as user units through its own target
The tty1 login hook ran systemctl --user start graphical-session.target,
which systemd refuses (RefuseManualStart=yes), so none of the NixOS
session's services started. The units in infra/systemd were wanted by
graphical.target, a system target, although weft-appd's needs the
session user's runtime and home directories and the compositor publishes
its socket to the user manager; run as system units the shell could
never learn the socket.

weft-session.target binds graphical-session.target and wants the
compositor, shell and weft-appd, in the NixOS configuration and as a
user unit in infra/systemd; the login hook starts it. The services are
part of the graphical session, the shell no longer hardcodes the
compositor's socket, and the compositor's units unset WAYLAND_DISPLAY
and DISPLAY so a restarted compositor does not take them for an
enclosing session and pick the nested backend. As a user unit, weft-appd
drops ProtectSystem= and PrivateTmp=, which a user manager implements
with PrivateUsers=yes, under which the setuid mount helper cannot mount
verified images. docs/building.md adds the VM's disabled graphics and
its mount helper, which the Nix store cannot hold setuid, to what still
keeps the image from a working desktop.

Rendered from the NixOS configuration, and as installed from
infra/systemd, the units pass systemd-analyze --user verify.
2026-10-09 20:35:58 +00:00
239afc2d11
fix(compositor): publish the Wayland socket to the systemd user manager
The services started after the compositor had no way to learn its
socket: the NixOS shell service hardcoded wayland-1, weft-appd's service
had no WAYLAND_DISPLAY at all, so the app shells it starts could not
connect, and the plain unit's comment claimed the compositor posted the
socket to the environment, which it did not.

Started by systemd, the compositor now sets WAYLAND_DISPLAY in the user
manager with systemctl --user set-environment right after creating its
socket and before reporting readiness, so the units ordered after it
inherit it. The winit backend now reports readiness too, as a Type=notify
unit expects.
2026-10-09 20:34:33 +00:00
5db3d1ddce
fix(nixos): start weft-appd and give the session its shell page and app shell
The reference session could not show the system UI or open an app, even
with every package built:

- weft-servo-shell ignores command-line arguments, yet
  infra/systemd/servo-shell.service passed it the page path, and the
  binary's packaged fallback named a path no package provides. The
  Nix package did not install the page and its NixOS service did not
  name it either, so the shell exited at startup.
- The NixOS weft-appd user service was wanted by nothing, so it never
  started, and it had no WEFT_APP_SHELL_BIN, so every launch would stop
  before its UI host started.

The weft-servo-shell package now installs the page as
share/weft/shell/system-ui.html, the binary falls back to that path in
the package's active revision, the systemd unit drops the ignored
argument, and the NixOS service sets WEFT_SYSTEM_UI_HTML to the package's
copy. weft-appd is wanted by the graphical session and is given the app
shell. docs/building.md lists what still keeps the image from a working
desktop: the Servo source hash, servo-embed in the shell packages and the
fixed Wayland socket name.
2026-10-09 20:26:05 +00:00
fda9a7c22f
fix(shell): make the system UI operable from the keyboard
The launcher button, app icons and taskbar entries were custom elements
with click handlers only: none could be focused, named or activated from
the keyboard, and the launcher overlay neither took nor returned focus.

They are now buttons with accessible names and a visible focus ring. The
launcher is a modal dialog that a Super tap or the Apps button opens
with focus on its first app; Tab moves between apps, Enter opens one and
Escape or another Super tap closes it, returning focus to the Apps
button. Each taskbar entry has an activate and a close button reachable
with Tab, and focus moves to a remaining control when an entry closes or
goes away. Notifications, including the offer to force quit, are
announced as status.

Servo does not tell the document when its window loses keyboard focus,
so weft-servo-shell calls window.weftShellBlurred() then and the launcher
closes; the next Super tap opens it again. Servo does not evaluate
prefers-reduced-motion either, so the page has no transitions.

tests/frame/check_system_ui.py drives the real page on the nested
desktop with keys: opening apps from the launcher, reaching the shell
with a Super tap from an application, a Super chord that stays with the
app and leaves no Super modifier held there, activating and closing apps
from the taskbar, the launcher closing when the shell loses focus, and
toggling it. It fails without the compositor's Super handling or the
focus-loss call.
2026-10-09 20:21:32 +00:00
e83c3f6df0
fix(appd): list installed apps in name order
The catalog followed the store's directory listing, so the launcher's
order, and with it its keyboard order, could change between scans. Apps
are listed by name, ignoring case, then by ID.
2026-10-09 20:21:26 +00:00
73dc2cbaa5
fix(shells): report the Super keys to pages as Meta
winit names the Super keys NamedKey::Super, which the key conversion did
not map, so pages saw an Unidentified key. The DOM names these keys
Meta.
2026-10-09 20:21:26 +00:00
72dda72432
fix(compositor): show the shell on a Super key tap
From an application window there was no keyboard path to the system
shell: only a pointer click on the taskbar strip raised the panel.

The Super keys now belong to the compositor and are never delivered to
an application. A tap, Super pressed and released without another key,
activates the shell's panel, raising it with keyboard focus, and then
delivers the tap to it so the shell can open its launcher; a key or a
pointer button pressed meanwhile makes it no tap. Keys pressed while
Super is held reach the focused window with the Super modifier: a client
is sent the modifiers whenever a key the compositor takes changes them,
so none stays held there. With several panels, the first registered one
is the shell's.
2026-10-09 20:21:26 +00:00
8c476fdf15
fix(appd): keep the relay's platform attribute on the function and bound frames exactly
The frame limit constant was inserted between spawn_ipc_relay's doc
comment and its cfg(unix) attribute, so the attribute applied to the
constant instead. A non-Unix build would have had two definitions of
the function.

The size is now checked before the line ending, so a frame one byte
over the limit is refused even when its line break arrives in the same
read. A message that is not UTF-8 ends the relay, as it did before,
rather than reaching the page with replacement characters. The test now
also covers a message at exactly the limit ending in CRLF.
2026-10-09 19:43:20 +00:00
2cd7ee735b
fix(appd): keep a component's message whole when the relay also forwards one from the page
The session's IPC relay read component messages with read_line inside
select!, into a buffer created anew on each pass. When a message from
the page won the select while a component message was half read, the
read part was lost, and the page received the remainder as a message of
its own. The line was also unbounded.

The relay now keeps the frame being read across passes and fills it
with read_until, which keeps partial reads when cancelled. It ends the
relay on a line longer than any message the runtime sends.

A new test writes half a component message, has the relay forward a page
message, then completes it and checks that it arrives whole. On the
previous code the test receives only the second half. It also checks
that an overlong line ends the relay.
2026-10-09 19:39:01 +00:00
d0ee6d685e
fix(nixos): use the mesa package for the graphics drivers
nixpkgs deprecates mesa.drivers in favour of mesa, and evaluating the VM
configuration warned about it.
2026-10-09 19:35:48 +00:00
6055e0b0a0
fix(runtime): keep helper error messages, and send notification bodies as plain text
Discarding wl-copy's output also lost its error message, such as a
missing Wayland connection. Its standard error is now kept and read
only when it fails, which is always before it leaves its selection
server.

Other fixes:
- An output over the limit is reported as such, instead of as the
  helper dying of the broken pipe.
- The clipboard is read as any text type, since the content is checked
  as UTF-8 anyway.
- Notification bodies are sent with markup escaped, since notification
  servers may render links and images.
- A failed wait for a helper kills and reaps it.
2026-10-09 19:30:47 +00:00
0c9b2c2b0d
fix(runtime): do not wait for the process wl-copy leaves serving the selection
wl-copy forks a process that keeps serving the selection. That process
inherits the helper's output pipes, so reading them to the end would
block a clipboard write until the selection changed. wl-copy's output is
now discarded, and its failure is reported by exit status.
2026-10-09 19:27:39 +00:00
cb4e50b78c
fix(runtime): bound the clipboard and notification helpers, and attribute notifications
The clipboard and notification imports ran wl-paste, wl-copy and
notify-send with no deadline and no size limits, and took the clipboard
text whole. A notification's icon could be any path or URL, and nothing
said which app sent it, so an app could pass one off as the system's.

Each helper now runs with a 5-second deadline, after which it is killed
and the call fails. Clipboard text is at most 1 MiB in either direction.
A notification's title is at most 256 bytes and its body 4096, its icon
must be an icon theme name, and it is sent with the app's ID as the
application name.

Unit tests run real processes for the deadline, the output limit, input
passing and failure reporting, and check the notification bounds.
check_grants.py still passes.
2026-10-09 19:26:47 +00:00
e482fec07c
fix(pack): add approvals by name only for installed, declared capabilities
Pruning compared a list of the declared capabilities with the set of
approved ones by length. A manifest repeating a capability could
therefore keep an approval it no longer declared. The two are now
compared as sets.

weft-pack approve <id> <capability>... replaced the app's approval
instead of adding to it. It also accepted any app ID and any
capability, which let an approval cover a capability declared later. It
now adds to the approval, requires the app to be installed, and for a
package weft-pack can read, requires each listed capability to be
declared. The docs state the remaining limits for verified images.
2026-10-09 19:20:52 +00:00
9b83625778
fix(pack): approve the package weft-appd launches, and drop approvals no longer declared
weft-pack approve read only the user store, so an app in the system
store, or installed as a verified image, could not be approved. The
remedy the launch refusal named also did not work.

approve now resolves the package in weft-appd's store order. It also
accepts the capabilities by name, which is how an image is approved,
since weft-pack cannot read its manifest.

An install or rollback without --approve now drops approvals for
capabilities the package no longer declares. A capability declared
again later therefore asks again. Both commands report what still needs
approval. weft-appd validates capabilities without side effects first,
then refuses unapproved ones, then derives grants, so an unsupported
capability is reported as such and not as one needing approval. The
docs state that approvals are per user.
2026-10-09 19:18:22 +00:00
3186e524ab
feat: grant an app only the capabilities the user approved
Every capability a package declared was granted at launch, so a signed
package received all the permissions it asked for. Blueprint 5.2 rules
that out.

A package now gets only the capabilities the user approved. weft-pack
install --approve approves those the installed package declares, and
weft-pack approve <id> approves those of the installed app later.
Without approval, install lists what still needs it. The approval is
recorded in $XDG_DATA_HOME/weft/approvals/<id>. weft-appd refuses to
launch an app declaring a capability the record does not hold, with
403 and the capabilities named, after refusing unknown or unsupported
ones as before.

An update that declares a new capability needs approval again, and
uninstalling forgets the approval. Private app data is a minimal
execution resource and needs no approval, so Notes and the existing
fixtures are unchanged.

Unit tests cover the approval record, install and approve, an update
adding a capability, uninstall, and appd refusing and then launching.
tests/frame/check_update.py launches a real app declaring notifications:
it is refused until weft-pack approve, then runs.
2026-10-09 19:11:53 +00:00
0f4fafe701
test(portal): point the relative escape link at the planted directory
The relative link in the race test climbed one level too high, so it
pointed at a directory that does not exist and could not catch a read
that left the granted directory.
2026-10-09 19:00:54 +00:00
ff1388c6d9
test(portal): make the link-swap race test exercise both states, and fix limits
The race test could finish before its swapping thread first ran, so in
some runs nothing was exercised and the test failed. The link now
exists from the start. The test runs until it has seen both reads that
stay inside and reads refused for leading out, and it also swaps in a
relative link that climbs out.

Other fixes:
- A request line ending in CRLF is measured without the CRLF.
- Responses that the client stops reading time out like requests do.
- Temporary file names include the portal's start time, so a file left
  by an earlier instance cannot collide with a new one.

The test binary passed 30 runs in a row.
2026-10-09 18:59:01 +00:00
36ae676d83
fix(runtime): close the IPC socket when the connection ends, and do not count refused growth
When the runtime ended an IPC connection, it only marked it closed.
weft-appd therefore kept a session whose messages went nowhere. The
socket is now shut down, so weft-appd ends the session as it does when a
component closes the connection.

A growth past a memory's or table's own maximum is refused without
being counted against the store's limit, since Wasmtime would reject it
anyway.
2026-10-09 18:42:18 +00:00
cbc984eef6
fix(runtime): limit a component's memory in total and end IPC on failed sends
The memory limit applied to each linear memory separately, so a
component made of several core modules could multiply it. A limiter now
accounts all memories together, and bounds table elements, memories,
tables and core instances.

IPC fixes:
- A failed or timed-out send (10 seconds) ends the connection, since
  part of the line may already have been written.
- A line over the limit ends the connection, also when its newline
  arrives in the same read.
- A line that is not UTF-8 is dropped and logged.

TasksMax is raised to 512, since the runtime runs a few threads per CPU.

Counter and Notes still run under the limits (check_counter.py and
check_notes.py), and check_grants.py passes.
2026-10-09 18:39:05 +00:00
044634692f
fix(runtime): bound component memory and app messages
The runtime set no limits of its own:
- A component could grow its linear memory until the host ran out, with
  no ceiling at all where systemd is unavailable.
- An app message could contain line breaks and split into several
  messages.
- An overlong message from weft-appd was buffered without bound.
- A closed connection looked the same as an empty one.

The Wasmtime store now has a limiter: linear memory is capped at 256 MiB
by default (--max-memory-mib changes it), and tables and instances are
bounded too. A memory that would grow past the limit does not grow, and
the component sees an allocation failure.

App messages are single lines of at most 64 KiB, the limit weft-appd
applies. A longer message, or one containing a line break, is refused.
A longer line from weft-appd ends the connection, and sending afterwards
reports that it is closed. The systemd scope also gets TasksMax=64.

The grants probe component now also tries a 300 MiB allocation and the
two refused messages. tests/runtime/check_grants.py checks that the
allocation fails at the default limit and succeeds with a 512 MiB
limit.
2026-10-09 18:23:07 +00:00
5f5474774a
fix(runtime): match the IPv6 special-purpose ranges exactly
The documentation range was matched as 3ff0::/12 instead of 3fff::/20,
which also refused unallocated global space. ORCHIDv2 (2001:20::/28)
was missing. IPv4-translated addresses are now judged by the IPv4
address they carry. Tests cover the NAT64 /32 outside the well-known
/96.
2026-10-09 18:17:57 +00:00
b163655b87
fix(runtime): judge IPv6 forms of IPv4 addresses and never fetch through a proxy
The public-address check missed several kinds of IPv6 address:
- IPv4-compatible and 6to4 addresses carrying a private IPv4 address;
- site-local, Teredo, local-use NAT64, discard-only, benchmarking,
  ORCHID and documentation ranges.

It also refused all well-known NAT64 addresses, which would break every
named grant on a DNS64 network.

Addresses carrying an IPv4 address are now judged by that address, and
the special-purpose ranges are refused. The HTTP client is told never to
take a proxy from the environment, since it would connect to the proxy
rather than to the checked address.
2026-10-09 18:16:42 +00:00
50418d4c0b
fix(portal): refuse indirect paths as given and harden connection handling
Path parsing drops '.' components, empty components and a trailing '/'.
A request like dir/. was therefore accepted, and a write renamed over
the directory itself instead of failing. The path text is now checked as
given.

Other fixes:
- A replaced file keeps its permission bits.
- A connection's slot is released even when its handler panics.
- Connections close after 60 seconds without a request.
- Temporary files get unique names and are not listed.
- A request of exactly the line limit is accepted.

A new test swaps a link between a directory inside the granted root and
one outside while reads and writes run, and checks that nothing outside
is read or written.

weft-appd no longer sets WEFT_FILE_PORTAL_SOCKET for the runtime, which
no longer reads it.
2026-10-09 18:15:28 +00:00
4e95c49062
fix(runtime): reach only public addresses through a fetch grant for a name
A fetch grant for a host name, or for any host, let a component reach
this machine and the local network whenever the name resolved there. A
granted name could therefore be pointed by DNS at loopback, link-local
metadata or private services.

The runtime now resolves each destination itself. It passes only the
allowed addresses to the HTTP client, so the address checked is the one
connected to. Names and the wildcard reach only public unicast
addresses. An IPv4 address named in a grant is still reached as
declared. Credentials in a URL are refused.

tests/runtime/check_grants.py runs the real component and checks these
refusals: the local server through the wildcard, the name localhost,
and credentials in a URL. The server records that none of the refused
requests reached it.
2026-10-09 18:12:31 +00:00
ae2e864941
fix(portal): report a path leading out of the granted directory as denied
openat2 reports a resolution that would leave the directory as EXDEV,
which reached clients as an invalid cross-device link.
2026-10-09 18:06:59 +00:00
f519832af1
fix(portal): confine file operations beneath the granted directory
The portal normalised a request path to check it against the granted
directories, but then operated on the raw path. A link inside a granted
directory, followed by '..', therefore reached files outside it. Links
pointing outside were followed too.

Each granted directory is now opened once. Every request is resolved
beneath that descriptor with openat2(RESOLVE_BENEATH | NO_MAGICLINKS),
so the kernel keeps the operation inside the directory even when links
are replaced while it runs. Paths with '.' or '..' components are
refused.

Other changes:
- Writes replace the file atomically and no longer create directories.
- Files are limited to 16 MiB, listings to 10,000 entries, request
  lines to the size of a full write, and the portal to 4 concurrent
  connections.
- The runtime no longer passes the portal's socket path to components,
  which cannot reach it.
2026-10-09 18:06:25 +00:00
d76d4c726d
test(appd): check that an unusable store entry does not hide a later store
The test also covers the refusal reported when no other store has the
app. The new comment states that a package found and then refused is not
replaced by another store's copy. The architecture doc says that a
re-signed copy of the same content is visible at once.
2026-10-09 17:56:27 +00:00
a65fb89662
fix(pack): replace a differing revision of the same name in one exchange
Installing the same content with another signature file gives the same
revision name. The existing revision, possibly the active one, was
removed before the new copy was renamed into place, so a failure in
between left the store link pointing at nothing. The new copy now
replaces it in one exchange.

If an activation fails before its switch, the kept rollback link is
restored, and dropping a stale rollback link is flushed. The staging
claim is released once the copy is placed, so launches are not refused
while the operation finishes. A launch now passes over a store whose
entry for the app is unusable, as the listing does.
2026-10-09 17:52:38 +00:00
194fb9f0fa
fix(pack): keep earlier app data and committed activations through updates
An update of a package directory from before revisions removed it
together with the app data an earlier weft-appd kept in its data
directory. That data is now moved out under the uninstall rules first,
or the update stops.

A failure after the store link was switched removed the new revision
while the link pointed to it. The switch is now the commit point;
cleanup after it is left to collection.

Other fixes:
- A revision is reused only when its content and signature file match.
- The revisions directory is flushed before activation.
- A rollback link is not inherited by a new installation, and rollback
  refuses a link to the active revision.
- Staging and unpacking directories are held while in use, so another
  operation never collects them.
- weft-appd refuses a launch, instead of waiting, while a package
  operation holds the revision.
- Listings read only an app's active package.
2026-10-09 17:44:50 +00:00
9206088d10
test(frame): check package updates against running sessions
check_update.py installs a test app with weft-pack, runs it with the
real runtime and app shell, and checks the following:
- an update leaves a running session on the bytes and the revision it
  started from;
- a failed update keeps the active revision;
- a later launch gets the update;
- the old revision is collected only after its session ends;
- rollback reactivates the kept revision;
- uninstall refuses new launches without disturbing a running session,
  and a later uninstall removes the revisions.
2026-10-09 17:38:10 +00:00
a57cdbc8be
feat(pack): install and update packages as immutable revisions activated atomically
An installed package could not be updated: install refused it, and
uninstalling and reinstalling it was neither atomic nor safe for running
sessions, which read files from the package directory.

A package is now staged, checked, verified, admitted and flushed. It is
then renamed to an immutable revision named by its content digest,
<store>/.revisions/<id>/<digest>, and activated by one rename of the
link <store>/<id>. A failure or interruption at any point leaves the
previously active revision active, and a failed first installation
leaves nothing installed. The revision active before an update is kept,
and weft-pack rollback makes it active again after checking it against
the owner record. Other revisions are collected by later operations on
the app, unless a session still runs from them. Leftovers of interrupted
operations are collected too.

weft-appd follows the store link only to one of the app's own
revisions. It runs a session from the revision directory and holds a
shared lock on it for the session's lifetime, so an update, rollback or
uninstall never changes or removes the bytes of a running session. A
package directory from before revisions is still read. An update
replaces it in one exchange, and only while no session runs from it.
2026-10-09 17:33:57 +00:00
d8e9b5a87a
fix(appd): keep room for a forced stop behind repeated close requests
Repeated close requests could fill the stop queue, so a forced stop sent
after them was dropped while the session was reported as stopping. A
close is now queued only into an empty queue, which leaves room for a
forced stop.
2026-10-09 17:19:51 +00:00
d509513e0a
fix(appd): stop a session whose stop request races its readiness
A stop requested while a session was starting could still be queued
when the app shell reported ready. The session was then shown as
running and asked to close, instead of being stopped. The supervisor
now checks for that request before it marks the session running.

Stop requests use a small bounded queue. A repeated request on a
stopping session is neither queued nor broadcast again; only a forced
one is sent. The taskbar's Force quit returns to a normal close when
the entry is activated, or 20 s after it is offered.
2026-10-09 17:16:42 +00:00
ddd79f6ab1
fix(appd): keep a session running while it answers a close, and add a forced stop
An application with the ask close policy could decline every close, and
nothing could end it. TERMINATE_APP now takes force, which terminates
the session without asking. The taskbar offers it as Force quit once an
app has had longer than the close timeout to answer.

The close interaction now comes before Running -> Stopping, as blueprint
6.2 requires. The session stays running while the application answers,
and a declined close no longer moves Stopping back to Running. Stop
requests reach the supervisor on a channel, so a repeated or forced
request during the close wait is seen without registering again. A
declining window is brought to the front, so its prompt is visible. A
clean exit after a close request is recorded as a close on request. A
decline report is recognised after page output that lacks a newline.

Notes keeps a pending Save and close when asked again. It saves text
typed during that save before closing, and reports when it cannot save
because it is not connected.
2026-10-09 17:10:15 +00:00
551df84562
feat: let an application decline a close to keep unsaved changes
A package declares its unsaved-change policy in [ui].close. With
"ask", the app shell dispatches a cancelable weftclose event before
the window closes and waits up to 2 s for the page. A page that
cancels the close keeps running, and the app shell reports this to
weft-appd with its readiness token, which returns the session to
running. The page closes itself later with window.close().

Notes declares "ask". With unsaved changes it offers Save and close,
Close without saving, and Cancel. It closes after a save only once the
save is acknowledged. The taskbar shows a declined close as running
again.
2026-10-09 17:00:08 +00:00
e72c55c87c
fix(appd): tell every client that a session is closing
TERMINATE_APP broadcasts the Stopping state, so every system UI marks
the entry. A closing taskbar entry is marked once and no longer sends
ACTIVATE_APP. The docs describe which stopped sessions are kept.
2026-10-09 16:45:25 +00:00
0866befc16
fix(appd): keep a closing session registered until it settles
A repeated TERMINATE_APP during the close wait no longer removes the
session from the registry. The close wait also watches the runtime and
the IPC relay, and reports a failed app shell exit as a failure rather
than a close. A session being closed is not saved for restore, only the
32 most recent stopped sessions stay registered, and the taskbar shows
an entry as closing until its session stops.
2026-10-09 16:41:30 +00:00
80d7451abf
fix(appd): close a running session as a user close would before terminating it
TERMINATE_APP, which the taskbar sends, killed the session's processes
at once, so an application had no chance to finish, for example to
save. A running session is now asked to close through the compositor
(AppCloseRequest, which sends xdg_toplevel close to its windows) and
the app shell is given five seconds to exit by itself before what
remains is terminated. The stop reason records whether the app closed
or was terminated after the timeout. TERMINATE_APP replies stopping and
the session stays registered until it settles; a starting session is
stopped at once, and appd shutting down terminates sessions without a
close.

check_counter.py requires the compositor to ask the session's window
to close and the app shell to exit with status 0 on the close; a unit
test requires an app that ignores the close to be terminated after the
timeout and not before.
2026-10-09 16:36:29 +00:00
102c20d2b4
fix(shells): release the rendering context and window before the display goes away
The software rendering path (softbuffer) and the EGL path keep their
own Wayland objects on winit's display, so dropping the rendering
context after the event loop could destroy proxies on a disconnected
display just like the shell client did. Both hosts now release the
rendering context and the window in winit's exiting handler as well.

The compositor records the keys whose press a shortcut took and takes
only those releases, so no client sees a release without its press or
keeps a key pressed. check_activation.py watches the panel for six
seconds after Alt+F4 instead of sampling it once.
2026-10-09 16:29:22 +00:00
828984be4b
fix(compositor): close the focused window on Alt+F4 and let the shells exit without crashing
There was no compositor-owned way to close an application window. Alt+F4
is now taken by the compositor: it sends xdg_toplevel close to the
focused application window, never the panel, and the key does not reach
the client.

Closing exposed a crash in both Servo hosts: their shell-protocol
client, created on winit's Wayland display, was dropped after that
display was torn down, so wl_proxy_destroy touched freed memory and
the process ended with SIGSEGV. The hosts now release Servo and the
shell client in winit's exiting handler, while the display is alive.

check_activation.py closes the focused application with Alt+F4 and
requires its session to stop with the app shell exiting with status 0,
the window to disappear, and Alt+F4 with the panel focused to leave
the panel in place.
2026-10-09 16:22:59 +00:00
c8bae1cc4d
fix(compositor): hand focus on when a registering panel is lowered
A shell restarted while applications run took keyboard focus before it
registered as the panel and kept it after being lowered beneath them;
the window in front now gets it. Without an output, windows are still
reordered, so a window that maps without taking focus does not cover
the one in front.
2026-10-09 16:14:31 +00:00
cdc4a9e15d
fix(compositor): keep the stacking order through layout changes
Laying windows out re-mapped every application window, which smithay
puts on top, so a session mapping another window, an exclusive zone
change or an output resize pushed the shell's home back under the
applications while it kept keyboard focus. Placement now re-maps every
window in its current order. Panels are lowered only when they
register, and a window that maps without taking focus goes beneath the
window in front, so a session cannot cover the shell's home or another
application by creating windows. A panel's zweft window that is
destroyed while its surface lives also removes its window slot.
2026-10-09 16:11:20 +00:00
8399914dfa
fix(compositor): show the shell's home on a panel click and release a dead panel's strip
With applications filling the work area, the system UI's launcher, drawn
in the panel beneath them, could not be seen while any application was
open. Clicking the panel now brings it to the front as the shell's home
until an application is activated again.

A panel that is destroyed, or whose client goes away, releases its
reserved strip and the applications are laid out again; dead panels no
longer count toward the work area, so a restarted shell does not reserve
the strip twice. A work area is never configured with a zero size. The
zweft_shell configure for an application window, at creation and in
reply to set_geometry, reports the work area the layout gives it, and a
panel's reports the output.

check_activation.py now clicks the taskbar strip, requires the panel to
cover both applications, and activates one back.
2026-10-09 16:06:19 +00:00
5253eaf251
fix(compositor): reserve the taskbar strip and lay app windows out in the work area
Application windows opened at the client's default size at the origin,
so one as large as the output hid the taskbar with no way back.

zweft_shell_window_v1 version 3 adds set_exclusive_zone: a panel
reserves a strip along an output edge, and other windows get the new
invalid_exclusive_zone error. weft-servo-shell reserves its 48-pixel
taskbar at the bottom (TASKBAR_HEIGHT, matching --taskbar-height in the
system UI). The compositor computes the work area as the output less the
reserved strips and configures every application window to fill it,
again when the output or a reservation changes.

The desktop harness now uses a 1400x900 X screen so the nested
compositor's whole 1280x800 output is captured. check_activation.py
requires both applications to fill the work area and end at the
reserved strip; check_notes.py finds the Discard button from the window's
right edge and check_confinement.py samples its probes from the measured
page instead of a fixed 800x600 window.
2026-10-09 16:00:38 +00:00
16af8d2a8c
fix(compositor): give a session focus on map only once in its lifetime
Unmapping a closed window made a session with no mapped window count
as new again, so destroying and recreating its only window took
keyboard focus from the application the user had activated. The
compositor now remembers which sessions already received focus on map
until the session ends.
2026-10-09 15:45:52 +00:00
65c02231a0
fix(compositor): restore focus when a window closes and keep later windows from taking it
When the focused window closed, keys went to a dead surface until the
next click; the topmost remaining application window, or the panel,
now gets focus. Only a session's first window takes focus when it
maps, so a client cannot take keystrokes meant for another application
by creating windows. A panel is fitted and kept beneath however the
shell orders its requests, and focusing the panel clears the
applications' activated state. ACTIVATE_APP is refused while the
compositor is not connected rather than queued.

check_activation.py now also ends the focused application and checks
that keys reach the remaining one.
2026-10-09 15:42:42 +00:00
aa67e7f190
fix(compositor): own stacking and focus, and activate app windows on request
The system shell's panel was an ordinary toplevel at winit's default
size, stacked by map order with the applications, and clicking or the
taskbar could never bring an application back to the front.

The compositor now sizes the panel to the output and keeps it beneath
every application window. A newly mapped, clicked or activated
application window is raised, marked activated and given keyboard
focus. weft-appd accepts ACTIVATE_APP for a running session and asks
the compositor to activate that session's window (AppFocusRequest),
and the system UI's taskbar entries send it when chosen.

check_activation.py runs the system shell with a solid panel page and
two test applications: the panel fills the output beneath them, each
launch comes to the front with keyboard focus, ACTIVATE_APP switches
between the sessions with focus, and activating a session that is not
running is refused.
2026-10-09 15:36:55 +00:00
db042fcb5c
fix(appd): keep the previous session when shutdown interrupts its restore
The session file is read and removed at startup, and restoring now runs
in its own task, so a shutdown during the restore would have saved only
the apps launched so far. Until the restore finishes, a shutdown stops
it and saves the restored list unchanged.
2026-10-09 15:25:57 +00:00
2e27adc4f6
fix(compositor): retry queued appd frames until sent and restore sessions in the background
Frames queued for a slow appd were sent only on later traffic, so the
end of a burst could wait indefinitely. A timer now retries the flush
every 20 ms, armed only while frames are queued. weft-appd restores the
previous session in its own task, so waiting for the compositor no
longer delays clients or shutdown, and the security docs describe the
launch refusal and the backlog limit exactly.
2026-10-09 15:23:41 +00:00
d6a2f94a1d
fix(compositor): buffer appd-bound frames and ignore stale session disconnects
A full socket buffer toward a stalled appd closed the connection and
with it every app. Frames for appd are now queued whole and flushed on
each send and read, and only a backlog beyond the frame limit or a
write error ends the connection. A disconnect report is applied only
when it comes from the session's current client, so a client closed
with an earlier appd cannot remove the mapping of a new session that
reused its ID. A failure to watch a new appd connection no longer
leaves the compositor refusing every later one.

weft-appd refuses a launch with 503 before anything starts while the
compositor is not connected, and waits up to 10 s for the connection
before restoring the previous session.
2026-10-09 15:20:29 +00:00
4c778330a3
fix(compositor): keep shell-level interfaces from sessions and harden the appd connection
Session clients could still create layer-shell surfaces, including
full-screen overlays with exclusive keyboard input, and bind the input
method, which bypassed the refusal of shell roles. Both globals are now
hidden from clients bound to a session.

The compositor IPC connection is tracked by its read source, so a write
error can no longer let a second peer feed the same buffers; a failed
write shuts the connection down. An undecodable or oversized frame ends
the connection, since descriptors could otherwise pair with the wrong
messages, and the descriptor limit counts only descriptors no message
claims, so a burst of launches is not taken for abuse. When appd's
connection ends, the compositor closes the clients of the sessions it
attached.

weft-appd notices when the compositor closes the connection, resends a
message whose write failed after reconnecting, and refuses a launch
while the compositor is not connected instead of starting an app shell
that can never connect.
2026-10-09 15:15:01 +00:00
7cf8639ae3
fix(compositor): bind each app session's Wayland client to its session through appd
The compositor stored appd's (pid, session) announcements and never used
them, so no surface could be attributed to a session and any client
could claim any app ID or the panel role.

weft-appd now creates a connected socket pair for each session, gives
the app shell one end as standard input with WAYLAND_SOCKET=0 and no
WAYLAND_DISPLAY, and sends the other end to the compositor with the
session and app ID over the compositor IPC socket (SCM_RIGHTS). The
compositor inserts it as a client bound to that session: holding the
connection is the session's identity. A session's zweft_shell windows
carry its app ID, the panel and overlay roles are refused to sessions
with a new role_not_permitted error, the session's first toplevel is
reported to appd, an ended session's client is closed, and a client's
disconnection is reported. The compositor accepts one appd connection
at a time.

The counter desktop check now requires the compositor to bind the app's
client to its session and to close it when the session is terminated.
2026-10-09 15:07:33 +00:00
af6f716823
fix(pack): let --claim-data install without HOME and test HOME refusals
Claiming data does not depend on finding earlier-layout data, so an
install that claims it no longer needs HOME. Tests cover a first launch
and a first install with an unusable HOME refusing and recording no
owner, and the security docs state the HOME requirement.
2026-10-09 14:56:42 +00:00
d3adced897
fix(appd): require a usable HOME for ownership decisions and keep records for earlier-layout data
Without an absolute HOME the earlier data layout could not be checked,
so a first-launch or install owner record was written anyway and that
data was migrated to the new owner later. Both now refuse instead.
Uninstall keeps an owner record while data exists in either layout, or
while it cannot tell. Launch tests use a private HOME, and the test
data-home cleanup never removes the running process's own.
2026-10-09 14:46:21 +00:00
95db80a86d
fix(appd): count app data in the earlier layout as existing before recording an owner
App data in the earlier layout, <home>/.local/share/weft/apps/<id>/data,
is migrated to the app data directory after the owner check, so a
trusted package from another store could be recorded as owner on its
first launch and then receive that data. Both layouts now count as
existing data, in weft-appd and in weft-pack install, so unowned data
is only given away with --claim-data. The refusal says how to claim
it. Stale test data homes are removed only when their process has
exited, and the app-data check records the owner of the data it seeds.
2026-10-09 14:41:23 +00:00
39aacac822
fix(appd): bind the launched manifest to the signature and record first owners
The manifest is now read once, and its bytes must match the verified
inventory, so a manifest swapped in around the check cannot grant
capabilities or entries the owner did not sign. A trusted package with
no owner record is recorded as its signer's on its first launch, and
app data without a recorded owner is refused rather than handed to the
first publisher, matching weft-pack's --claim-data rule. A damaged
trust store or owner record is a host error (500), and the trust store
is not consulted for development content.

Supervisor tests use a private data home and an empty trust store; the
counter check runs with a private home, and the notes check records
the owner of the data it seeds.
2026-10-09 14:36:06 +00:00
11cea5e7e3
fix(appd): verify package owner and signature before a session starts
weft-appd trusted an installed directory as installed, so content
changed after installation, or signed by a key since removed from the
trust store, still ran with the owner's app data. Before anything
starts, a package recorded as a publisher's must carry that
publisher's valid signature over its current content, with the key
still trusted; a package with no record must be signed by a trusted
key; development content, recorded by weft-pack install --dev, runs
unverified. Failures are refused with code 403.

The desktop checks trust the demo key, and the confinement check,
whose package deliberately holds a link, records it as development
content.
2026-10-09 14:29:14 +00:00
fb13a99e17
fix(pack): remove a new store directory whose mode cannot be set
A directory left private after a failed mode change would stay
unreadable to other users on every later install, since existing
directories are not touched. It is now removed again. The test's
relative store is cleaned up even when an assertion fails.
2026-10-09 14:26:43 +00:00
025388f84e
fix(pack): create relative stores and set new store modes through a no-follow descriptor
A relative store none of whose components existed failed, because the
empty ancestor was treated as a directory to create. New store
directories are now created private and set to 0755 through a
descriptor opened without following links, so a swapped path cannot
redirect the mode change. The security docs state the hard-link
protection as the kernel enforces it.
2026-10-09 14:25:09 +00:00
d67ea24004
fix(pack): create a missing store at 0755 regardless of umask
A first root install under a restrictive umask created the store and its
parents unreadable to other users even though the package inside was
0755/0644. Missing store directories are now created and set to 0755.
The copy comment and the hard-link note in the security docs describe
exactly what is checked and what the kernel enforces.
2026-10-09 14:22:37 +00:00
8221e6fc3d
fix(pack): set installed modes regardless of umask and hold one descriptor per level
Modes requested at creation were masked by the umask, so a root install
under umask 077 produced system packages other users could not read.
They are now set explicitly after creation. The copy reads each
directory's names and closes the listing before recursing, so deep
trees hold one descriptor per level. The owner-lock test now uses an
ID that would otherwise open, and the docs describe the copy check and
its device-node residual precisely.
2026-10-09 14:20:35 +00:00
181aa0fefa
fix(pack): copy packages by directory descriptor so swapped links cannot redirect the copy
Checking each file's device and inode against a path-based listing still
followed a directory replaced by a link after it was listed. The copy now
holds each source directory open and opens its entries relative to it
with O_NOFOLLOW, checking type, device and inode against the listing.
Only real packages in other stores keep an owner record, the store list
is deduplicated, archive names must be valid app IDs, and the help text
is wrapped.
2026-10-09 14:17:09 +00:00
c64ee531ee
fix(pack): take the app ID from the staged copy and check copied file identity
The app ID now comes from the staged copy, so a source changed after
validation cannot steer paths outside the store or the owners directory,
and lock_owner refuses invalid IDs. Copied files must keep the device and
inode they were listed with, and are opened without following links or
blocking on FIFOs, which no longer depends on /proc. Uninstall keeps an
owner record while another known store holds the package, and a failure
to inspect app data refuses rather than counting as no data.
2026-10-09 14:13:18 +00:00
39f7ca2a3f
fix(pack): close inventory forgery, serialize ownership changes and refuse to follow links
Names with control characters have no content digest, so a crafted name
can no longer reproduce other inventory lines and drop signed files.
Installs and uninstalls of an ID hold a per-ID lock, so a failed
concurrent install cannot remove the record of the one that won. App
data without a recorded owner goes to a new owner only with
--claim-data. Uninstall releases a record left by an interrupted
install once no data remains. Files are opened without following links
and, on Linux, must be the file that was listed.
2026-10-09 14:04:53 +00:00
d175bf012e
fix(pack): normalize installed modes and never leave a partial or orphaned owner record
Installed files take fixed modes (0644, or 0755 when executable) and
directories 0755, so a world-writable source cannot install as such.
An owner record created by an installation whose package then fails to
be placed is removed, and records are written under a temporary name
and linked into place, so they are never partial. Archives unpack into
a random private directory that is always removed. Uninstall frees an
ID only when the app data is truly absent, signatures are checked with
verify_strict, and list marks development installs.
2026-10-09 13:59:54 +00:00
88c2e9f6a5
fix(pack): install only trusted packages and bind each app ID to its owner
weft-pack install copied any package into the store: signatures were
never checked, no key was trusted for anything, any publisher could
install over another's app ID and reach its retained data, and the
signing inventory followed symbolic links, so a package could sign and
install files from outside itself.

Installation now requires a signature by a key in the trust store
($XDG_CONFIG_HOME/weft/trusted-keys and /etc/weft/trusted-keys, or
$WEFT_TRUSTED_KEYS alone). Unsigned or untrusted content installs only
with --dev, recorded as development content. The package is copied
into the store, checked and verified on that copy, and renamed into
place, so the verified bytes are the installed bytes.

The first installation of an app ID records its owner beside the app
data; later installations must have the same owner, so neither another
publisher nor a development build can take the ID over. The record
outlives uninstall while app data remains.

The content digest moves to weft_ipc_types::trust and refuses links,
special files and non-UTF-8 paths; it keeps the existing inventory
format, and both committed demo signatures still verify. Catalogs list
only directories named after their package ID. The security guide
described a signature over wapp.toml and app.wasm only; it now
describes the full inventory and the trust and ownership rules.
2026-10-09 13:49:49 +00:00
5c82b540e6
Merge fix/resolve-verified-package: resolve each launch to one package and fail closed on images (#16)
weft-appd resolves each launch once: a verified image in any store wins over a directory install and must mount or the launch is refused, with no fallback to a mutable directory. The manifest must declare the requested ID and its entries must be contained regular files without links. weft-runtime receives --module and weft-app-shell --ui; neither searches the stores. Grants come from the same manifest and the mount belongs to the session. The manifest parser and image file names are shared through weft-ipc-types with weft-pack.
2026-10-09 14:53:49 +02:00
cad8c016d6
Merge remote-tracking branch 'origin/main' into fix/resolve-verified-package 2026-10-09 12:50:31 +00:00
c0fdca18b6
Merge fix/confine-app-renderer: confine application pages to their UI files and bridge (#15)
weft-app-shell checks every resource load: files inside the UI directory, also after resolving links, inline data: and blob: resources, about:blank and the session bridge are allowed; other files and network destinations, redirects and loads not tied to the webview fail before a request leaves the renderer. The Servo pin moves to e5d9a51, which keeps pending classic scripts traced until they run and withholds navigator.servo from about:blank and about:srcdoc documents.
2026-10-09 14:50:24 +02:00
ba82535ae2
Merge remote-tracking branch 'origin/main' into fix/confine-app-renderer 2026-10-09 12:33:46 +00:00
8214c12d7e
Merge fix/session-owned-ipc-relay: make the IPC relay part of the session it serves (#14)
The session supervisor opens and owns each session's IPC relay; every exit path stops the relay task, removes its socket and unregisters its sender. A session ends when its IPC connection closes. IPC_FORWARD never waits on a component and reports an error for a missing relay or a full queue. appd's runtime directory is created mode 0700 and the relay socket 0600.
2026-10-09 14:33:28 +02:00
969f719d2d
Merge remote-tracking branch 'origin/main' into fix/session-owned-ipc-relay 2026-10-09 12:18:43 +00:00
84930b13d8
Merge fix/separate-app-data: keep app data apart from installed packages (#13)
App data lives in $XDG_DATA_HOME/weft/app-data/<id>, private to the user, and is moved from the earlier layout in one no-replace rename; conflicting or cross-filesystem data is never moved or deleted. weft-pack never removes a data directory with a package. Notes stores text exactly, refuses saves edited from a stale revision and writes through a locked, synced staging file.
2026-10-09 14:18:28 +02:00
1f58a7be11
Merge remote-tracking branch 'origin/main' into fix/separate-app-data 2026-10-09 11:57:17 +00:00
744acc8164
Merge fix/enforce-session-grants: enforce effective capability grants per session (#12)
weft-appd derives each session's grants once, before the session exists, from one shared capability vocabulary and refuses packages it cannot satisfy. weft-runtime receives them as --grant and --preopen arguments, preopens read-only directories read-only and checks every notifications, clipboard and fetch call. Fetch is limited to http and https to granted hosts, standard methods, no Host or hop-by-hop headers, unfollowed redirects and bounded time and size.
2026-10-09 13:56:57 +02:00
6f2f566fe4
Merge remote-tracking branch 'origin/fix/confine-app-renderer' into fix/resolve-verified-package
# Conflicts:
#	crates/weft-runtime/src/main.rs
2026-10-09 11:43:01 +00:00
b45fe27e9b
Merge remote-tracking branch 'origin/fix/session-owned-ipc-relay' into fix/confine-app-renderer 2026-10-09 11:37:44 +00:00
cda9c14426
Merge remote-tracking branch 'origin/fix/separate-app-data' into fix/session-owned-ipc-relay 2026-10-09 11:37:17 +00:00
b17b74f310
Merge remote-tracking branch 'origin/fix/enforce-session-grants' into fix/separate-app-data 2026-10-09 11:36:27 +00:00
12e4c1d91a
Merge remote-tracking branch 'origin/main' into fix/enforce-session-grants
# Conflicts:
#	.gitignore
#	README.md
#	docs/building.md
2026-10-09 11:30:01 +00:00
0ab429b2ea
Merge fix/authorize-session-messages: authorize WebSocket clients by role and session (#11)
weft-appd's WebSocket requires HELLO within 5 seconds. A system role authenticated with appd.systoken manages sessions; an app role authenticated with a per-session bridge token exchanges APP_MESSAGE envelopes with its own session only. The Servo hosts hand credentials only to their own top-level documents and deny navigation outside them.
2026-10-09 13:28:43 +02:00
8eed654be7
fix(appd): let no directory shadow an image, and refuse linked roots
- A verified image in any store now takes precedence over a directory
  install in any store, so a user's directory cannot shadow a system
  image of the same app.
- The package root must be a directory and wapp.toml a regular file,
  not links to content outside the root the entries are checked in.
- Incomplete or malformed image metadata is refused with 403; a
  missing helper, a failed mount or an unreadable manifest with 500.
- A supervisor test records the arguments of both children and
  requires the resolved component and UI document.

The documentation states that the root hash is read from the store
and not yet authenticated.
2026-10-09 11:08:41 +00:00
04cde8901c
Merge remote-tracking branch 'origin/fix/confine-app-renderer' into fix/resolve-verified-package 2026-10-09 10:29:32 +00:00
fecf4c5b55
fix(app-shell): report a UI path that is not absolute 2026-10-09 10:29:32 +00:00
1641bf31a8
build(servo): trace pending classic scripts instead of rooting them
Servo e5d9a51 replaces the root that kept a pending classic script
alive with tracing through the document that holds it. A root also
kept the script's global alive, so a document dropped while a script
was pending would leak. The crash the root fixed stays fixed.
2026-10-09 10:29:24 +00:00
e2f9746fb5
Merge remote-tracking branch 'origin/fix/confine-app-renderer' into fix/resolve-verified-package
# Conflicts:
#	docs/architecture.md
2026-10-09 10:18:47 +00:00
d056045ad8
test(appd): launch complete packages in the supervisor tests
Launch tests wrote manifests without names, versions or entries, which
the shared parser rejects. They now write complete packages.
2026-10-09 10:18:36 +00:00
687439a2a3
test(frame): make the worker and srcdoc confinement probes observable
Servo refuses worker scripts for file: pages, blob: ones included, so
the worker probe now requires only that no worker fetch succeeds, and
the worker is built from the page itself. The srcdoc frame reports to a
listener installed before the frame exists. Band failures and requests
that reached the servers are reported together, so a run without the
policy shows every leak.
2026-10-09 10:16:22 +00:00
2148ffc8ae
fix(appd): resolve each launch to one package and fail closed on images
The runtime, the app shell and grant derivation each searched the
package stores and parsed wapp.toml on their own, so they could use
different roots; the runtime ignored [runtime].module, the image loader
looked for companion files the builder never wrote, and a failed image
mount fell back to the mutable directory install.

weft-appd now resolves a launch once: a verified image wins over a
directory in the same store, and when any image file exists the image
must mount or the launch is refused. The manifest must declare the
requested ID, and both entries must be plain relative paths to regular
files without links. The runtime receives --module and the app shell
--ui; neither looks for the package. Grants come from the same
manifest, and the mount belongs to the session.

The manifest parser and the image file names move to weft-ipc-types,
shared with weft-pack, whose check now applies the same entry rules.
Mapper devices are named after their per-launch mountpoint, so
concurrent sessions no longer collide.
2026-10-09 10:03:40 +00:00
16a184ad9e
fix(app-shell): close the remaining paths out of the application page
Review of the renderer policy found loads it did not see or judged
wrongly:

- Loads Servo does not attribute to the webview, such as
  navigator.sendBeacon(), reached the network. They are all refused.
- On a redirect Servo reports the first URL again, so every redirect
  is refused.
- A symbolic link inside the UI directory led anywhere on disk; file
  loads are checked again after resolving links.
- Only about:blank is allowed among about: URLs.

The Servo pin moves to 5d90f51, which keeps compiled classic scripts
rooted until they run (a parser-blocking script waiting for a failed
stylesheet import crashed the content process) and withholds
navigator.servo from about:blank and about:srcdoc documents.

The confinement check gains probes for links, workers, beacons,
imports, fonts and srcdoc frames, and its WebSocket server completes
the handshake. The slow stylesheet's delay now starts when the host
first tries to open it.
2026-10-09 10:03:30 +00:00
d60152f443
fix(app-shell): confine application pages to their UI files and bridge
An application page could load any local file through file: URLs and
reach any network destination with images, fetch, XHR or WebSockets,
bypassing the component's fetch grants. The shell now checks every
resource load: files inside the UI directory, inline data:, blob: and
about: resources and the session bridge are allowed; anything else
fails with a network error before a request leaves the renderer.

tests/frame/check_confinement.py probes each path on the nested desktop
and requires that no HTTP request or TCP connection reaches the host.
The frame check's slow stylesheet becomes a file next to the page held
back with a file lease, so it stays inside the confined scope.
2026-10-09 09:39:37 +00:00
010573eb16
fix(appd): create the runtime directory private wherever it is made
appd created $XDG_RUNTIME_DIR/weft with the umask mode when it opened
its own socket, wrote its port or system token, or opened a portal
socket, so the 0700 mode requested for session sockets never applied.
All of them now use one helper that creates the directory 0700 and
tightens an existing one.
2026-10-09 09:27:28 +00:00
ec00531c75
test(appd): give each test process its own runtime directory
Session sockets are named by session ID and every test registry starts
at 1, so test processes running at the same time shared one socket path
in the common test runtime directory and broke each other's sessions.
Each test process now uses its own directory under the system temporary
directory, and directories of ended test processes are removed. The
test of a closed IPC connection connects to the socket itself instead
of relying on python3 in a child script.

A session whose component closes its IPC connection during startup now
stops before it is reported ready. The weft runtime directory is
created with mode 0700, and the socket is removed if its permissions
cannot be restricted.
2026-10-09 09:24:49 +00:00
67bce2fb22
Merge branch 'main' into fix/authorize-session-messages 2026-10-09 09:19:26 +00:00
5174a58d47
Merge pull request #9: report sessions running only after the UI host is ready
Sessions become Running only after token-authenticated READY from the runtime and the app shell, and every exit path shares one teardown.
2026-10-09 11:19:16 +02:00
818a831895
Merge pull request #6: stop reporting readiness without an engine
A runtime built without wasmtime-runtime now exits with an error instead of printing READY; its env-dependent tests are serialised.
2026-10-09 11:19:13 +02:00
26bd5b5079
fix(appd): end sessions whose IPC connection closes and never block on it
IPC_FORWARD held the registry lock while awaiting a send to the
component; with a full queue it stalled appd, and once the relay was
closed it locked the registry again and deadlocked. It now sends without
waiting and reports an error when the session has no relay or its queue
is full.

A relay whose component disconnected left the session running with no
way to exchange messages. The session now stops when its IPC connection
closes. The relay releases its task and socket when dropped, so a
cancelled supervisor leaks neither, and the socket is created with mode
0600.

New tests fail against the previous code: IPC_FORWARD against a missing
relay and a full queue must answer at once, and a runtime that closes
its IPC connection while still running must end its session. The test
runtime directory lives under target/ instead of one directory per run.
2026-10-09 09:18:39 +00:00
ac6559a814
Merge pull request #10: add the stability blueprint, engineering contract and contributor toolkit
BLUEPRINT.md defines the 0.1.0 target; AGENTS.md and .agents/ give the contribution procedures and checks.
2026-10-09 11:14:20 +02:00
d9d9d24205
fix(appd): make the IPC relay part of the session it serves
dispatch opened each session's IPC socket and registered its sender
before the supervisor existed, and nothing released them: a relay whose
runtime never connected waited forever with its socket file in place,
and every stopped session left its sender registered, so app messages
for it were still accepted and queued.

The supervisor now opens the relay after its early checks, and the
session owns it: every exit path stops the relay task, removes the
socket and unregisters the sender. A session whose socket cannot be
opened does not start. The relay accepts a single connection.

A dispatch-level test launches a package whose runtime reports ready
and exits without connecting; it requires the stopped session to leave
no sender and no socket, and fails against the previous code. The
Counter and Notes checks pass end to end.
2026-10-09 09:11:35 +00:00
481495d929
fix(notes): show loading status and check the editor after a failed load
The first load showed an empty status while the editor was read-only;
it now says loading. check_notes.py also types and saves after a failed
load and requires the stored file to stay unchanged.
2026-10-09 09:07:27 +00:00
c1ea57fbef
fix(notes): keep Discard usable after a failed load
Discard waited for a stored revision, so after a load failed (stored
notes not valid UTF-8, a read error, a lost reply) the editor stayed
read-only with no way to reload. The page now tracks the outstanding
load itself: Discard is refused only while a load or save is in flight,
a load error or a ten-second timeout ends the load, and Discard retries.

A save acknowledgement arriving after its timeout and after Discard had
started a reload replaced the saved state while the editor still showed
older text, so the next save would silently revert it. Acknowledgements
are ignored while a load is outstanding, and a reload forgets the last
save.

The component removes a lock whose token could not be written and
cleans up renamed stale locks with the abandoned staging files.
check_notes.py adds a failed load followed by a repaired file and
Discard; the previous package stays read-only there and fails.
2026-10-09 09:05:25 +00:00
87436d0e08
fix(notes): apply only the outstanding load and own the save lock
A second load reply, from Discard clicked twice or during the first
load, replaced the editor again after it had become editable. Only the
reply to the outstanding load is applied now, and Discard does nothing
while a load is outstanding.

The save lock holds an owner token and is released only by its owner; a
stale lock is renamed away before removal, so two saves cannot both take
it over. A save removes only a staging file it created and, holding the
lock, removes staging files left by saves that ended before their
rename. A save acknowledgement arriving after the page's timeout is
still accepted, and text that cannot be encoded is refused before it is
sent. app.wasm is rebuilt and the package re-signed with the demo key.
2026-10-09 09:01:28 +00:00
1928ffb661
fix(pack): never delete a data directory that was not moved
weft-pack uninstall moved earlier app data only when the package
manifest could be read and declared an app-data capability, and only
when the store path was spelled exactly as the user store; otherwise it
removed the package directory with the data in it. A directory left
holding only data by an earlier weft-appd, which has no manifest, was
deleted that way.

A data directory is now never removed with a package. In the user
store, recognised by its real location rather than its spelling, it is
moved when the package declares app data or its manifest cannot be
read; in every other case uninstall stops and changes nothing. Tests
cover a directory holding only data, a store reached through '..', a
symbolically linked home, an app without the capability and another
store.

weft-appd reports both locations when a move fails with an I/O error and
creates the data directory with mode 0700 instead of tightening it
afterwards.
2026-10-09 09:01:28 +00:00
d2bc176344
Merge branch 'main' into fix/appd-session-readiness
# Conflicts:
#	crates/weft-appd/src/runtime.rs
2026-10-09 08:57:41 +00:00
e3c2e80142
Merge branch 'main' into fix/runtime-stub-readiness 2026-10-09 10:57:06 +02:00
8ae7b8517c
docs: describe the portable profile without implying other hosts
The portable checks run on Linux only; they cover the crates that need
no Linux system libraries.
2026-10-09 08:57:00 +00:00
1e344d684d
docs: name the portable CI job in the verification runner
The portable profile mirrors the CI job that now runs on Ubuntu only
under the name portable.
2026-10-09 08:56:50 +00:00
4d39ec3a8b
Merge branch 'main' into docs/add-engineering-contract 2026-10-09 08:56:42 +00:00
87222599f1
Merge pull request #8: verify native pointer and keyboard input through weft-compositor
tests/frame/check_input.py drives a page through weft-compositor with real X input and checks the presented pixels.
2026-10-09 10:56:29 +02:00
ce40916a98
Merge pull request #4: build and test on Linux only
The Windows CI job tested no supported configuration; the portable checks now run on Ubuntu only.
2026-10-09 10:56:22 +02:00
f39a330027
fix(notes): serialise saves and keep unseen notes from being replaced
The editor accepted typing before the stored notes had loaded, and a
load reply then adopted the stored revision for text edited from
nothing, so a save replaced notes the user never saw; the same happened
when typing during a Discard reload. The editor is now read-only until
it holds the stored text.

Two Notes windows saving at once shared one staging file and could each
pass the revision check, storing a mix of both texts. Each save now
holds a lock file while it checks the revision and replaces the notes,
writes its own staging file, syncs it before the rename, and removes
only that file on failure; a lock left by an ended session expires
after ten seconds.

A save larger than the 64 KiB app message limit after JSON encoding was
dropped on its way and left the page waiting forever with Save
disabled. The page now refuses such saves before sending, gives up on a
save after ten seconds without a reply, and the component answers every
request, including malformed ones, so no request goes unanswered.

check_notes.py now pauses weft-runtime with SIGSTOP to make text typed
during a save and keys typed during a Discard reload deterministic; the
previous package fails it by saving text typed before the reload. The
building guide lists the application checks, the pinned toolchain for
reproducing the demo binaries and the demo key path.
2026-10-09 08:55:50 +00:00
a508f1ebe4
fix(appd): move only real app data and never replace a directory
weft-pack treated any top-level data directory in a package as app
data from the earlier layout, in every store and for every app: a
package shipping data/ lost that content to the app data directory on
uninstall and could then no longer be uninstalled. Data is now moved
only from ~/.local/share/weft/apps/<id>/data, the only place earlier
versions wrote it, and only for packages declaring an app-data
capability; packages may no longer contain a top-level data entry.

The move left an empty package directory behind, which then blocked
weft-pack install although nothing was listed; an emptied package
directory is now removed, and install accepts an empty leftover. The
rename uses RENAME_NOREPLACE, so a target created after the check is
reported as a conflict instead of being replaced, and a move across
filesystems is refused with a message naming both locations instead of
a bare OS error. Directories moved by weft-pack are made private too,
and a symbolic link at the target is refused rather than followed.

The system UI now shows launch refusals, which it only logged, and the
weft-appd unit may write under ~/.local/share/weft, which
ProtectSystem=strict made read-only. check_app_data.py also types into
Notes after the move and requires the save to reach the moved file, and
checks that no empty package directory remains.
2026-10-09 08:52:09 +00:00
2a39fe0be3
Merge pull request #7: drop --wait from the systemd-run scope launch
systemd rejects --wait together with --scope, so every launch failed on hosts with a systemd user manager.
2026-10-09 10:48:06 +02:00
4b27d7f16c
fix(notes): store notes exactly and never overwrite newer text
The Notes demo exchanged hand-escaped strings: the page turned every
literal backslash-n into a line break on load and save, the component
escaped only some control characters, so other text produced invalid
replies, and every reply replaced the editor contents, discarding text
typed while a save was in flight. Saves wrote the file in place and
replaced whatever another Notes window had stored.

Requests and replies are now JSON objects. The component reports a
revision (a hash of the stored bytes) with each load; a save names the
revision it was edited from and is refused when the stored notes have
changed since, so a second window's text is never replaced silently. The
file is written beside notes.txt and renamed over it. A save
acknowledgement updates only the saved state, never the editor, and
Discard reloads the stored notes.

tests/frame/check_notes.py edits Notes with real keyboard input on the
nested desktop: text with a literal backslash sequence, quotes, a tab and
non-ASCII characters is stored byte for byte, text typed during a save
survives, and a save after another window changed the file is refused.
It fails against the previous package, which turned the seeded "\n"
into a line break. app.wasm is rebuilt and the package re-signed with the
demo key.
2026-10-09 08:47:01 +00:00
cc69c048c0
fix(appd): keep app data apart from installed packages
App data lived in ~/.local/share/weft/apps/<id>/data, inside the user
package store under the installed package directory. Uninstalling a
package deleted its data, and launching a package installed elsewhere
created that directory, after which installing the package for the user
failed because its directory already existed.

App data now lives in $XDG_DATA_HOME/weft/app-data/<id>, one shared
rule in weft_ipc_types::package, and is made private (0700) on every
launch. Data in the earlier location is moved there in one rename on the
first launch with an app-data capability, and by weft-pack before it
uninstalls a package or installs over a directory holding only data. If
both locations hold data, nothing is moved: the launch is refused with
409 and weft-pack stops, so neither copy is lost or merged.

tests/frame/check_app_data.py launches the Notes demo on the nested
desktop with notes in the earlier location and checks that they arrive
byte for byte (including a literal backslash sequence and non-ASCII
text), that the old directory is gone, that the new one is 0700 and that
a second copy makes the next launch fail with 409 without changing
either. The weft-pack tests that change the environment now share a lock.
2026-10-09 08:43:42 +00:00
ca09b8ed90
test(runtime): serialise tests that use WEFT_APP_STORE
One test set WEFT_APP_STORE while another, running on a parallel
thread, expected the default store roots, so the default-roots test
failed intermittently (5 of 60 local runs, and in CI). The four tests
that read or change the variable now share a lock, and the default-roots
test clears the variable for its duration (0 of 30 runs fail).
2026-10-09 08:38:15 +00:00
722cd7479e
docs: stop runner toolchain installs and widen maintenance form
The verification runner inherited rustup's default of installing a
missing pinned toolchain or component on demand, contradicting its
documented guarantee. Run every profile with RUSTUP_AUTO_INSTALL=0 so a
missing toolchain fails the check, and document how to install it.

The maintenance form and CONTRIBUTING described only duplication and
fallback problems, while the architecture debt scout also reports
ownership, untrusted-authority and unenforced-grant problems through that
form. Widen both descriptions to match. Correct the README CI trigger to
pushes to main and pull requests.

This branch builds on docs/add-stability-blueprint, which adds the
BLUEPRINT.md the contract and toolkit checks link to; merge that first.

Validation, against the committed lockfiles:
- verify.py toolkit: checker passes, 28 tests pass
- verify.py portable packages: pass
2026-10-09 08:34:48 +00:00
dcc09f319d
docs: add engineering contract, contributor toolkit and templates
Add AGENTS.md as the single engineering contract: sources of truth,
evidence and proof requirements, ownership, working modes, the reviewed
change loop, maintenance isolation, decision authority, dependency and
fork rules, the 0.0.x to 0.1.0 release progression, and branch and
publication rules.

Add .agents/ with scope, implement, verify, maintenance and release
procedures; reviewer, architecture debt scout, simplicity and refactoring
roles; skills for the compositor, Servo rendering, runtime capabilities,
appd sessions, packages and data, Linux deployment, integration
verification and documentation; and verify.py, which runs the existing
check profiles with --locked from any directory, stops on the first
failure and supports --dry-run.

check_toolkit.py validates local links and heading anchors, metadata,
catalog coverage and issue forms. A new contributor-toolkit CI job runs
both. The structure follows the Resina Design System toolkit at
1e768064f57a1e403ab271822383e732795905a6, adapted to WEFT.

Validation, against the committed lockfiles:
- verify.py toolkit: checker passes, 28 runner/checker tests pass
- verify.py portable, demos, packages: pass
- verify.py linux, runtime, servo-embed: fail on existing defects
  (clippy collapsible_if in the winit backend, three clippy lints in
  weft-runtime with wasmtime-runtime, and an E0308 in the selected Servo
  revision's servo-layout); the runner reports the failing status

Add CONTRIBUTING.md, issue forms for defects and changes, maintenance
problems and decisions of direction, and a pull request template asking
for ownership, proof and the validation actually performed. README.md
links the contribution guide.
2026-10-09 08:34:48 +00:00
0d30ed4ed9
Merge branch 'main' into ci/drop-windows-job 2026-10-09 10:29:22 +02:00
edfd47ecc1
Merge pull request #3: compile and present the Servo hosts against pinned Servo and Stylo forks
Compile and present the Servo hosts against pinned Servo and Stylo forks
2026-10-09 10:28:39 +02:00
a66e73d564
fix(ipc-types): refuse fetch hosts with a hexadecimal last label
URL parsing reads a last label such as 0x1 as a number, so a grant for
example.0x1 could never match a request.
2026-10-09 08:27:44 +00:00
b0bd763e70
fix(compositor): collapse nested submit condition in winit backend
The nested if around backend.submit failed clippy::collapsible_if under
-D warnings, breaking the linux-only clippy job. Use a let chain instead.
2026-10-09 08:26:15 +00:00
51ca194acb
fix(runtime): close fetch and preopen gaps in grant enforcement
A component with a host-specific fetch grant could reach another origin
by setting its own Host header, and could inject request lines through
the method string, which ureq writes unvalidated. Fetch now accepts only
standard methods and refuses Host, framing and hop-by-hop headers. Fetch
grants accept canonical DNS names and dotted IPv4 addresses only, so a
grant can never be written in a form that silently never matches.

--preopen split host and guest at the first `::`, so a host path
containing `::` widened the preopened directory; it now splits from the
right, and appd refuses host paths that are not UTF-8 or contain `::`.

appd validated capabilities one at a time, creating the data directory
before a later capability was refused, and required HOME even for
packages without filesystem capabilities. It now checks every capability
first, resolves host directories only when needed, validates the app ID
with the rule weft-pack uses (now shared in weft_ipc_types::package), and
reports 400, 404, 403 or 500 according to the cause. user-dirs.dirs is
read as a shell would: the last assignment wins, $HOME must be followed
by a slash, escaped values are ignored and a relative XDG_CONFIG_HOME is
not used.

The grants probe now also overwrites, renames, removes and creates
directories in read-only data, and sends a forged Host header, an
injected method and a file: URL; it fails when directory permissions of
a read-only preopen are widened or the header check is removed. A new
CI job builds the runtime with its engine and fetch support and runs the
check. The mount test that sets WEFT_APP_STORE now holds the env lock.

Package images are still located separately from directory installs;
deriving grants from the verified image is part of resolving one package
descriptor.
2026-10-09 08:25:40 +00:00
29a7f6f508
ci: build and test on Linux only
WEFT OS targets Linux and systemd. The Windows runner only compiled and
tested the crates without Linux system libraries, which says nothing
about a supported configuration, and was the slowest job in every run.

The job is now `portable` on Ubuntu, matching the verification profile
of the same name. The building guide, README and development
environment notes now state that builds are validated on Linux only.
2026-10-09 08:16:59 +00:00
1e19326d39
fix(compositor): collapse nested submit condition in winit backend
The nested if around backend.submit failed clippy::collapsible_if under
-D warnings, breaking the linux-only clippy job. Use a let chain instead.
2026-10-09 08:09:41 +00:00
c28a829624
fix(runtime): enforce effective capability grants per session
Every host import was registered and callable whatever the package
declared, read-only directory capabilities were preopened read-write,
and appd launched packages whose capabilities it could not satisfy. The
fetch import also could not be linked: the host returned a tuple where
the WIT declares the response record, so any component importing
weft:app/fetch failed to instantiate.

One capability vocabulary now lives in weft_ipc_types::capability and
is used by weft-pack, weft-appd and weft-runtime. weft-appd derives a
session's grants once, before the session exists, and refuses the launch
with error 403 when a capability is unknown, unsupported (hw:gpu:*) or
unsatisfiable (documents without an XDG documents directory). The
documents directory now comes from user-dirs.dirs instead of a guessed
~/Documents.

The runtime receives grants explicitly (--grant CAP, --preopen
HOST::GUEST::ro|rw), preopens read-only directories read-only, and checks
the grant on every notifications, clipboard and fetch call. Fetch accepts
only http and https to granted hosts, returns redirects and HTTP error
statuses as responses instead of following or failing them, and bounds
connect time, total time and response size. The file portal takes
read-only directories with --allow-read and refuses writes there.

tests/runtime/check_grants.py runs the real runtime on a probe component
under each kind of grant and checks the outcome of every operation; it
fails when read-only data is writable or an import ignores its grant.
The appd dispatch tests that read WEFT_RUNTIME_BIN now hold the env lock
shared with the tests that set it.
2026-10-09 08:08:58 +00:00
f41937bd7e
Merge branch 'fix/runtime-stub-readiness' into fix/enforce-session-grants 2026-10-09 07:58:07 +00:00
3875650226
fix(app-shell): refuse encoded separators in the UI scope
A file URL whose path holds an encoded slash or backslash keeps the UI
directory prefix while a loader may decode it into a path outside that
directory. Navigation and the bridge now refuse such URLs.

appd removes the system token file at shutdown only while it still holds
its own token, and the HELLO deadline in unit tests is one second.
2026-10-09 07:53:23 +00:00
db712e056e
fix(appd): authorize WebSocket clients by role and session
The browser-facing WebSocket accepted requests from any local page, so a
page could launch or terminate apps and inject messages into any session.

Every connection now completes the upgrade and sends HELLO within five
seconds. The system role authenticates with a token appd writes to
$XDG_RUNTIME_DIR/weft/appd.systoken (mode 0600) and may manage sessions,
but never sees or sends application messages. The app role authenticates
with a per-session bridge token passed to weft-app-shell in
WEFT_BRIDGE_TOKEN and exchanges APP_MESSAGE envelopes with its own
session only; it is disconnected when that session stops.

weft-servo-shell hands the system endpoint only to the system UI
document and denies navigation away from it. weft-app-shell installs the
bridge only in top-level documents inside the application's UI
directory and denies navigation outside it. The launcher renders package
names as text.

tests/frame/check_counter.py drives the Counter demo end to end through
the compositor, appd, the Wasm runtime and the app shell.
2026-10-09 07:45:49 +00:00
c80103bdc1
Merge branch 'test/servo-native-input' into fix/authorize-session-messages 2026-10-09 07:26:24 +00:00
f9945c055c
fix(appd): report sessions running only after the UI host is ready
weft-appd marked a session Running and broadcast APP_READY as soon as the
runtime printed READY, then started weft-app-shell with its output
discarded and never watched it. A session with no UI, a UI host that
failed to start, or one that crashed was still reported running. Early
failure paths skipped parts of the cleanup: the image mount was not
unmounted, the compositor association was not released, and the abort
sender leaked on spawn failure. Readiness was any stdout line equal to
READY, which a Wasm guest (inherited stdout) or a page (window.alert
writes to the app shell's stdout) could print.

Now a session becomes Running only after the runtime and then the app
shell report readiness, each within 30 s; WEFT_APP_SHELL_BIN is required
and checked before anything starts. After that, the runtime exiting, the
app shell exiting or a terminate request ends the session. Every exit
path goes through one teardown that kills both children, releases the
compositor association, unmounts the image, stops the file portal and
broadcasts Stopped.

Readiness uses a per-session random token passed to both children in
WEFT_READY_TOKEN. weft-runtime and weft-app-shell print READY <token>,
and appd accepts only a line ending with it; guests receive only the
variables the runtime names and pages cannot read the host environment.
Child output is read in bounded, lossily decoded lines, so invalid UTF-8
or long lines no longer stop the readers. Compositor notifications use
try_send so a disconnected compositor cannot stall teardown, and all
children are killed if the supervisor is dropped.

The IPC relay is not yet owned by the session, and children are killed
without a graceful period.

Validation:
- cargo test -p weft-appd (43 passed); new tests cover: not ready until
  the app shell is ready, runtime exit before that, no app shell
  configured (runtime never starts), app shell exit ending a running
  session with the runtime process gone, and READY lines without the
  token; they fail against the previous supervisor
- end to end with weft-compositor (nested), weft-appd, weft-runtime
  (wasmtime-runtime) and weft-app-shell: the Counter demo reaches
  APP_READY and is on screen; a page that prints a READY line through
  alert and never loads is stopped after 30 s without APP_READY;
  terminate leaves no child processes
- clippy -D warnings and fmt --check for weft-appd and weft-runtime
2026-10-09 01:41:09 +00:00
cb48227906
fix(appd): drop --wait from the systemd-run scope launch
When a systemd user manager was detected, weft-appd launched the runtime
with `systemd-run --user --scope --wait ...`. systemd rejects that
combination while parsing options ("--wait may not be combined with
--scope"), so every app launch on such a host exited immediately and the
session stopped without the runtime ever starting.

A scope already runs the command in the foreground: systemd-run registers
the scope and then executes the command in its own process, so stdout and
the exit status still reach appd without --wait.

The options now live in one constant. A Linux test runs the installed
systemd-run with them against an empty runtime directory and bus address
and requires it to reach the manager connection; option and combination
errors stop it earlier. The test does not validate the -p property values
or start a scope. It requires systemd-run to be installed.

This keeps the existing ownership scope for the runtime only; placing the
app shell and helpers under the same owner is separate lifecycle work.

Validation:
- systemd-run 255: the test passes with the new options and fails with
  the old --wait (and with --pty) using systemd's own message
- cargo test -p weft-appd (38 passed), clippy -D warnings, fmt --check
2026-10-09 01:29:24 +00:00
ae176aae93
test: verify native pointer and keyboard input through weft-compositor
Nothing checked that input reaches a page through the compositor; the
Servo hosts' input forwarding had only been compiled.

tests/frame/check_input.py runs weft-servo-shell with
tests/frame/input.html on the nested desktop and injects real X input
with xdotool into weft-compositor's window. The compositor's winit backend
routes it through its seat to the Wayland client, which has no X display.
The page must react in its presented pixels: clicks 6 px either side of
the boundary between its halves change only the half under the pointer,
and the a and Shift+a key presses arrive with the right key value and
modifier. The harness gives the compositor's X window input focus, as a
window manager would; the client's keyboard focus comes from the
compositor's click-to-focus.

The nested desktop setup shared with check_frame.py moves to
tests/frame/session.py. Xvfb now reports the display it picked through
-displayfd, so concurrent runs cannot share an X server, and a run clears
only the logs and capture it writes.

Validation:
- check_input.py: 3 of 3 runs pass; two concurrent runs pass
- negative pages fail: no script; left click handled by the right half;
  an element extending the left half 20 px across the boundary; a key
  handler ignoring Shift
- check_frame.py --host system, --host app, --host app --slow-style 3 pass
  after the refactor
- unverified: key release and repeat, pointer motion and button release
  events, wheel, focus loss, non-US layouts, non-ASCII text, scale changes,
  weft-app-shell input
2026-10-09 01:18:53 +00:00
64f8cff6fd
fix(shells): paint and present Servo frames and report readiness truthfully
With servo-embed, weft-servo-shell and weft-app-shell did not compile
against the selected Servo revision: the keyboard event shape, key and
mouse action variants, frame readback, shutdown, URL type and window
handle APIs had changed. The frame path never called WebView::paint; the
software path rebuilt its softbuffer surface every frame and read pixels
without painting, and the EGL path presented nothing. weft-app-shell
printed READY right after creating its WebView, before any frame, and its
feature-disabled build printed READY and parked. Servo also disables CSS
Grid by default, which the system UI uses.

Both hosts now build against the selected API. Each frame is painted with
WebView::paint and presented: the software path reads the painted frame
back, presents the context and copies it into a persistent softbuffer
surface; the EGL path presents its window context. Nothing is presented
before Servo's first repaint request. Shutdown drops the WebView and
Servo, whose drop completes the shutdown, and exits the event loop. Both
hosts enable layout_grid_enabled.

weft-app-shell prints READY on the first frame presented after the
document has loaded and Servo reports its rendering settled: on load
completion it requests WebView::take_screenshot, which completes only once
every frame has fired load, render-blocking resources, images and web
fonts are done and the rendering is up to date. Feature-disabled builds of
both hosts exit with an error instead of reporting readiness. weft-appd
does not consume the app shell's READY yet.

tests/frame/check_frame.py runs weft-compositor nested on Xvfb with the
winit backend, starts a host showing tests/frame/reference.html and checks
the presented pixels (four colour quadrants and text). For the app host
the page must be on screen within two seconds of READY; --slow-style
delays a render-blocking stylesheet that reveals the page, so premature
readiness fails.

Validation (Ubuntu 24.04, Mesa 25.2.8 llvmpipe, software path):
- check_frame.py --host system, --host app and --host app --slow-style 3:
  5 of 5 runs pass each
- negative fixtures fail: page with red and green swapped; a fake host
  printing READY without rendering; a local build printing READY on its
  first presented frame (--slow-style 4, 3 of 3)
- cargo clippy -D warnings with and without servo-embed; cargo fmt --check
- unverified: EGL path, DRM, resize, output scale, idle wakeup, input
2026-10-09 01:02:26 +00:00
ef7d105118
fix(appd): drop --wait from the systemd-run scope launch
When a systemd user manager was detected, weft-appd launched the runtime
with `systemd-run --user --scope --wait ...`. systemd rejects that
combination while parsing options ("--wait may not be combined with
--scope"), so every app launch on such a host exited immediately and the
session stopped without the runtime ever starting.

A scope already runs the command in the foreground: systemd-run registers
the scope and then executes the command in its own process, so stdout and
the exit status still reach appd without --wait.

The options now live in one constant. A Linux test runs the installed
systemd-run with them against an empty runtime directory and bus address
and requires it to reach the manager connection; option and combination
errors stop it earlier. The test does not validate the -p property values
or start a scope. It requires systemd-run to be installed.

This keeps the existing ownership scope for the runtime only; placing the
app shell and helpers under the same owner is separate lifecycle work.

Validation:
- systemd-run 255: the test passes with the new options and fails with
  the old --wait (and with --pty) using systemd's own message
- cargo test -p weft-appd (38 passed), clippy -D warnings, fmt --check
2026-10-09 00:57:30 +00:00
f6d5cf102c
fix(runtime): stop reporting readiness without an engine
Built without the wasmtime-runtime feature, weft-runtime printed READY
and exited without executing anything. weft-appd treats READY on the
runtime's stdout as the readiness signal, so such a build made a session
appear to start successfully although no component ran.

The feature-disabled build now exits with an error naming the missing
feature, so appd sees the runtime close without READY and stops the
session. The binary still builds for the portable type, lint and unit
checks. The Nix package keeps building the engine-enabled runtime.

Validation:
- new unit test: run_module in a feature-disabled build returns an error
  naming the feature; it fails against the previous stub
- feature-disabled binary against a minimal package: exits 1 with the
  error and prints no READY
- cargo test -p weft-runtime (5 passed), clippy -D warnings, fmt --check
2026-10-09 00:55:07 +00:00
93b67834a7
build: select compiling Servo and Stylo fork revisions
Both Servo hosts tracked the marcoallegretti/servo `servo-weft` branch,
which the lockfile resolved to 8e7dc40. That revision's servo-layout does
not compile (E0308 and E0716 in build_backdrop_filter). WEFT also resolved
upstream Stylo dca3934, where backdrop-filter is gated behind
layout.unimplemented, because the Servo fork's own [patch] for Stylo does
not apply to dependents.

Pin Servo by revision to f0bb1aa (8e7dc40 plus the build fix) and add a
root [patch."https://github.com/servo/stylo"] selecting the
marcoallegretti/stylo fork at f1ba496 for all eight Stylo crates Servo
uses. Cargo.lock changes only the 66 source lines of those packages.

Record both pins, their reachable branches, purpose and removal
conditions in SERVO_PIN.md, and restate its limitations against executed
evidence. Update the Nix outputHashes: the Stylo hash is recomputed for
f1ba496 with the method that reproduces the previous dca3934 value; the
Servo hash is not yet known for f0bb1aa and is left as lib.fakeHash, so
Nix builds report the expected value instead of using a stale one.

Validation:
- cargo metadata --locked: ok; no servo/stylo sources remain in the lock
- cargo check -p weft-servo-shell --features servo-embed --locked:
  all of Servo, including servo-layout, compiles; the remaining errors are
  in the shell's own embedder code
- cargo fmt --check; portable workspace tests: 78 passed
- Nix fetchgit could not run here (archive downloads and the sandbox's
  TLS to the proxy fail), so the Servo hash remains unverified
2026-10-09 00:13:08 +00:00
f70518b64e
docs: add stability blueprint for 0.1.0
Add the stability blueprint defining the 0.1.0 release profile, the
architecture and ownership boundaries, the capability and IPC contracts,
the verification profiles and the stable release gate.
2026-10-08 22:58:47 +00:00
122 changed files with 20859 additions and 2212 deletions

121
.agents/README.md Normal file
View file

@ -0,0 +1,121 @@
# WEFT OS contributor toolkit
Procedures, review roles, area knowledge and a verification runner for
contributors. [AGENTS.md](../AGENTS.md) is the engineering
contract; [BLUEPRINT.md](../BLUEPRINT.md) is the accepted product direction;
[CONTRIBUTING.md](../CONTRIBUTING.md) is the maintainer-facing summary.
These files help apply the contract. They do not grant permissions, approve
decisions, schedule work or change the [working mode](../AGENTS.md#4-working-modes).
If a guide here seems to disagree with `AGENTS.md`, the contract wins and the
guide needs fixing.
## Start
1. Read `AGENTS.md`, identify the accepted scope and the owning component.
2. Load only the skills that match the boundary you are changing.
3. Use [scope](commands/scope.md) for an unverified report or proposal, and
[implement](commands/implement.md) for accepted, verifiable work.
4. Select checks and evidence with [verify](commands/verify.md), then have the
[reviewer](agents/reviewer.md) inspect the actual diff.
## Commands
Commands are portable Markdown procedures. Follow them as checklists.
| Command | Input | Result |
|---|---|---|
| [scope](commands/scope.md) | Report, defect or proposal | Evidence-backed issue draft with owner, acceptance criterion and proof |
| [implement](commands/implement.md) | Issue or accepted scope | Reviewed atomic change on a descriptive branch |
| [verify](commands/verify.md) | Scope or diff | Coverage map and actual check results |
| [maintenance](commands/maintenance.md) | One named maintenance role | One justified issue, or one isolated reviewed change |
| [release](commands/release.md) | Milestone scope and candidate commit | Candidate evidence and a promotion recommendation |
## Roles
Roles are checklists for a reviewer or a focused pass over the code. A role
file does nothing until a task invokes it.
| Role | Responsibility |
|---|---|
| [reviewer](agents/reviewer.md) | Review a specified diff for correctness, scope, ownership and evidence without editing it |
| [architecture-debt-scout](agents/architecture-debt-scout.md) | Report the strongest present ownership or boundary problem; never edit repository files |
| [continuous-simplicity](agents/continuous-simplicity.md) | Remove one duplicated decision, unnecessary state or misleading fallback path |
| [continuous-refactoring](agents/continuous-refactoring.md) | Resolve one structural problem while preserving behavior, ownership and proof |
## Skills
Each skill is a `SKILL.md` with `name` and `description` metadata. The `weft-`
prefix keeps them distinct from skills installed by other projects.
| Skill | Load when changing |
|---|---|
| [weft-compositor-input](skills/weft-compositor-input/SKILL.md) | Smithay compositor, Wayland protocols, surfaces, focus, geometry, input, DRM or winit backends |
| [weft-servo-rendering](skills/weft-servo-rendering/SKILL.md) | Servo embedding, painting and presentation, the Servo fork and Stylo overrides, system UI and app pages |
| [weft-runtime-capabilities](skills/weft-runtime-capabilities/SKILL.md) | Wasmtime host, WIT, WASI preopens, host imports, grants, file portal, seccomp |
| [weft-appd-sessions](skills/weft-appd-sessions/SKILL.md) | Session lifecycle, readiness, child supervision, cleanup, appd IPC, WebSocket bridge |
| [weft-packages-data](skills/weft-packages-data/SKILL.md) | Manifests, `weft-pack`, signing and trust, installation, updates, app data, EROFS images |
| [weft-linux-deployment](skills/weft-linux-deployment/SKILL.md) | Nix flake and VM, systemd units, native dependencies, installed paths and endpoints |
| [weft-integration-verification](skills/weft-integration-verification/SKILL.md) | End-to-end fixtures, pixels and input, failure injection, reliability and evidence records |
| [weft-documentation](skills/weft-documentation/SKILL.md) | Public documentation, the blueprint, this toolkit, templates and the runner |
## Verification runner
[`scripts/verify.py`](scripts/verify.py) runs the repository's actual check
profiles. It needs Python 3.10 or newer. It works from any directory, runs fixed
argument arrays from the repository root without a shell, stops at the first
failure and returns its status. It never formats files, installs packages or
toolchain targets, regenerates expectations, signs packages, commits or
publishes. It sets `RUSTUP_AUTO_INSTALL=0`, so a missing pinned toolchain or
component fails the check instead of being downloaded; install it with
`rustup show` or `rustup component add`.
```sh
python .agents/scripts/verify.py --help
python .agents/scripts/verify.py portable linux --dry-run
python .agents/scripts/verify.py portable linux
```
| Profile | Runs | Prerequisites |
|---|---|---|
| `toolkit` | Link, anchor, metadata, catalog and issue-form checks; runner tests | `pip install -r .agents/scripts/requirements.txt` |
| `portable` | `cargo fmt --check`; Clippy and tests for crates that need no Linux system libraries | Pinned toolchain |
| `linux` | Clippy and tests for `weft-compositor` and the feature-disabled shells | Linux Wayland, input, DRM and systemd development libraries |
| `servo-embed` | `cargo check` of both Servo hosts with the real renderer feature | As `linux`, plus the Servo build dependencies; long first build |
| `runtime` | Clippy and tests for `weft-runtime` with `wasmtime-runtime,net-fetch` | Pinned toolchain |
| `demos` | `cargo check` of the demo components for `wasm32-wasip2` | `rustup target add wasm32-wasip2` |
| `packages` | `weft-pack check` and `weft-pack verify` of the demo packages | Pinned toolchain |
All Cargo commands use `--locked`. Local `[patch]` overrides used for
cross-repository development change the resolved graph and make locked checks
fail; run the runner without them for evidence about the committed graph.
The runner covers compilation, lints, unit tests and package checks. It does not
run a compositor, render pixels, launch a session, boot the VM or exercise a
real component's host imports. Select that evidence with
[verify](commands/verify.md). Profiles are not a replacement for
[CI](../.github/workflows/ci.yml), and a passing profile is not approval to
publish, merge or release. No hooks are installed by this toolkit; if you call
the runner from a local hook, configure it in your own client or Git setup.
## Maintaining the toolkit
Put area knowledge in a skill, repeatable steps in a command, review criteria in
a role and executable checks in `scripts/`. Link to the contract and to the
owning source instead of restating policy or freezing implementation status.
List every command, role and skill in its table above; `toolkit` fails when a
document is not linked from this catalog. Changes to the runner need a test
showing failure behavior.
`check_toolkit.py` parses CommonMark links, images and reference links in this
directory and in the top-level contributor documents. It ignores code spans,
code blocks and HTML comments. It checks that local targets exist inside the
repository, that `#fragment` links into Markdown files match a GitHub-style
heading anchor, that metadata is a YAML mapping with unique string `name` and
`description` fields and a `name` matching its path, and that issue forms parse.
External URLs, raw HTML and the truth of the instructions still need review.
The structure follows the
[Resina Design System contributor toolkit](https://github.com/marcoallegretti/Resina-Design_System/tree/1e768064f57a1e403ab271822383e732795905a6/.agents)
at revision `1e768064f57a1e403ab271822383e732795905a6`. WEFT's contract,
ownership and evidence requirements determine its contents.

View file

@ -0,0 +1,39 @@
---
name: architecture-debt-scout
description: Find the strongest present ownership or boundary problem in WEFT OS with evidence and report it; never edit repository files.
---
# Architecture debt scout
Run through [maintenance](../commands/maintenance.md) under the contract's
[maintenance rules](../../AGENTS.md#8-maintenance). You may read the whole
repository and its history. You edit no repository files and create no branches,
commits or pull requests.
Look for present consequences at WEFT's boundaries:
- Responsibility held by the wrong owner, or two owners for one decision: session
state in both appd and the shell, package roots rediscovered by each child,
geometry decided outside the compositor.
- Authority taken from untrusted input: caller-supplied session IDs, PIDs,
window titles or stdout text treated as identity or readiness.
- Grants declared but not enforced at a host entry, or enforced differently in
WASI, the file portal and the renderer.
- Synthetic success: feature-disabled or fallback paths that report readiness,
delivery or verification.
- Contract drift between bridge and daemon messages, manifest and runtime
loading, image builder and loader, documentation and code.
- Dependency use that differs from the selected revision, or overrides that do
not reach the consuming workspace.
Check the blueprint's [baseline findings](../../BLUEPRINT.md#32-findings-that-determine-the-implementation-order)
and existing issues first: a known, already-scoped problem is not a new finding,
and one owned by the active goal is fixed there.
Apply the threshold: a named affected party, repository evidence, present cost
and an independent acceptance criterion. Return the single highest-value
qualifying problem with file and line evidence, owner and boundary, present
cost, acceptance criterion, expected proof and, where a decision is needed, the
meaningful alternatives. Create or update its issue only within granted
authority. When nothing qualifies, say so and stop. Do not decide architecture
or launch speculative work.

View file

@ -0,0 +1,30 @@
---
name: continuous-refactoring
description: Resolve one concrete structural problem in WEFT OS while preserving accepted behavior, ownership and proof.
---
# Continuous refactoring
Run through [maintenance](../commands/maintenance.md) under the contract's
[maintenance rules](../../AGENTS.md#8-maintenance). Establish the affected
caller, contract or test harness, the present cost and an independent acceptance
criterion.
Valid targets are demonstrated: duplicated logic with a working path on both
sides, coupled responsibilities that prevent testing, repeated conversions,
modules with several reasons to change, or structure that blocks a required
fixture. The blueprint names candidates that become justified once working paths
and regression evidence exist: shared package resolution, one effective-grants
model, one session cleanup owner, one bridge message contract and common Servo
host and input behavior. Extract a boundary only when that evidence exists.
Behavior, public contracts and ownership stay unchanged. Moving responsibility
between owners or changing a public contract needs a
[decision](../../AGENTS.md#9-decisions-and-authority): record it and stop the
change. Scope follows the acceptance criterion and ownership, not a file or line
budget.
Establish preservation proof first, refactor completely, run
[verify](../commands/verify.md) and have the [reviewer](reviewer.md) inspect the
committed range. Return the structural result, the contracts left unchanged and
the actual checks. Stop after one result.

View file

@ -0,0 +1,26 @@
---
name: continuous-simplicity
description: Remove one evidenced duplicated decision, unnecessary state or misleading fallback path while preserving WEFT OS behavior and ownership.
---
# Continuous simplicity
Run through [maintenance](../commands/maintenance.md) under the contract's
[maintenance rules](../../AGENTS.md#8-maintenance). Establish the affected
caller, contributor or contract, the present cost and the acceptance criterion
before changing anything.
Candidates are concrete: the same decision computed in two places, state that
can disagree with its source, a fallback that hides a failure or reports success
it did not achieve, an obsolete path, indirection without a second caller, or
documentation that restates and contradicts code. Prefer deletion and existing
concepts. Do not optimize for line count, merge distinct privileges or failure
domains, or replace explicit errors and authority checks with something shorter.
Removing a misleading fallback can change observable behavior from silent
success to explicit failure. That is in scope when the fallback contradicts the
contract; state the change and prove the new failure mode.
Establish preservation evidence first, implement, run [verify](../commands/verify.md)
and have the [reviewer](reviewer.md) inspect the committed range. Stop after one
issue and pull request result; simplification never becomes the primary goal.

View file

@ -0,0 +1,56 @@
---
name: reviewer
description: Review a specified WEFT OS diff for correctness, ownership, scope and evidence without editing it.
---
# Review a change
Input: the acceptance criterion, a base/head range or pull request diff, and the
validation evidence claimed. Read [AGENTS.md](../../AGENTS.md) and the
[skills](../README.md#skills) for the boundaries touched.
Inspect the actual change first: `git diff <base> <head>` for commits, or both
`git diff --staged` and `git diff` for uncommitted work. An empty `git diff HEAD`
after a commit means the wrong range was chosen, not that nothing changed. Read
the surrounding code and contracts needed to understand the behavior; do not turn
the review into repository-wide cleanup.
You report findings. You do not edit the change, approve decisions or releases,
or publish anything beyond the authority granted for the review.
Check:
1. **Behavior.** Does the change do what the acceptance criterion says on every
path, including errors, cancellation, timeouts, partial failure and teardown?
Are resources (processes, sockets, relays, mounts, temporary files) settled?
2. **Proof.** Would the named tests or fixtures fail if the behavior broke? Do
they exercise the real boundary, or a mock, a feature-disabled build or a log
line? Were expectations, fixtures or signatures changed with a contractual
reason? Were the claimed checks actually run, against the committed graph?
3. **Ownership.** Does each responsibility stay with its owner from the
[blueprint](../../BLUEPRINT.md#4-architecture-and-ownership)? Is a second
source of truth created for session state, grants, package resolution or
geometry? Is a decision of direction hidden inside cleanup?
4. **Trust and data.** Can application content, a forged session identifier or a
symlink obtain access it was not granted? Is user data preserved across
failure, update and uninstall? Are secrets and payloads kept out of logs?
5. **Compatibility.** Are manifest, WIT, protocol, IPC and package format changes
deliberate, versioned or converted? Do documentation and code agree?
6. **Dependencies.** Is every external API used as it exists in the revision the
lockfile selects? Are overrides applied at the workspace root?
7. **Scope and quality.** Is the change focused and atomic, free of unrelated
edits, generated or local-environment files, synthetic success paths and
unjustified abstraction? Are commit and pull request texts free of
attribution, trailers and process narration?
Each finding states severity, file and line, the concrete consequence, the
evidence you read or ran, and the required correction. Separate verified defects
from suspicions. **Blocking** findings concern correctness, promised behavior,
trust, data preservation, compatibility, accepted scope or required evidence.
Lower-impact findings are nonblocking. Do not manufacture findings or raise
preferences to blockers; unrelated debt does not block this change.
Return the findings, the checks you performed and whether any blocking finding
remains. Say so only after completing the review. State if you authored the
change or share its context, so the limitation can be reported honestly. Keep
this output separate from published pull request text.

View file

@ -0,0 +1,56 @@
---
name: implement
description: Carry accepted scope through proof, implementation, validation and diff review to one atomic result.
---
# Implement accepted scope
Input: an issue or an explicitly accepted task with an acceptance criterion.
Read [AGENTS.md](../../AGENTS.md) and the matching [skills](../README.md#skills).
This procedure applies the [reviewed change loop](../../AGENTS.md#5-reviewed-change-loop)
to contribution work and to each step of primary development. It adds no
approval layer: in primary development, continue to the next accepted step after
each accepted result.
1. **Inspect and confirm scope.** Verify the problem against current source and
evidence. If the acceptance criterion or proof is missing, use
[scope](scope.md). An issue is not a decision; if one is required and
unresolved, prepare it and work on something independent.
2. **Prepare the branch.** Inspect `git status`, the current branch, worktrees and
remotes. Fetch `main` and branch from it, or from the unmerged branch the work
depends on, with a descriptive
[branch name](../../AGENTS.md#14-branches-commits-and-publication). Preserve
unrelated changes; never commit contribution work directly to `main`.
3. **Review the plan.** Name the owner, the boundary touched, compatibility
promises affected and the proof. Check uncertain APIs in the dependency
source selected by the lockfile. Fix it here if the design crosses ownership.
4. **Establish proof.** Reproduce a defect first. For new behavior, add the
fixture or contract case that fails without the change. Identify which
evidence needs a real environment (compositor, renderer, VM) and whether it is
available.
5. **Implement** the smallest complete change. Keep manifests, WIT, protocol,
IPC types, documentation and callers coherent. No synthetic success paths.
6. **Validate** with [verify](verify.md): the smallest sufficient profiles plus
any boundary-specific evidence. Fix failures within scope. Explain every
changed expectation; never re-bless output to make it pass.
7. **Review the actual diff** with the [reviewer](../agents/reviewer.md), from a
reviewer who did not write it when available, otherwise as a fresh separate
pass whose limitation you state. Review `git diff <base> <head>` for commits,
or both staged and unstaged diffs before committing.
8. **Correct, revalidate and re-review** until no blocking finding remains.
Recheck after material corrections, rebases and conflict resolutions.
9. **Commit atomically.** Inspect `git status` and the complete diff; exclude
generated, transient and local-environment files (for example lockfile changes
caused by local `[patch]` overrides). Write the message for maintainers.
10. **Publish within authority.** If pushing or opening a pull request is
authorized and available, fill the
[pull request template](../../.github/pull_request_template.md) and inspect
automated review integrations first. Otherwise return the local result and
the prepared description.
11. **Reassess** the goal from the new repository state and continue with the
next dependent step.
Report what changed, what proves it, the checks actually run with results, and
material limitations. A separately actionable problem found on the way goes
through the [maintenance threshold](../../AGENTS.md#8-maintenance) instead of
the pull request body. Completing a change grants no merge or release authority.

View file

@ -0,0 +1,36 @@
---
name: maintenance
description: Run one maintenance role for one qualifying problem from the verified current main, isolated from primary development.
---
# Run one maintenance task
Input: one named role, [architecture-debt-scout](../agents/architecture-debt-scout.md),
[continuous-simplicity](../agents/continuous-simplicity.md) or
[continuous-refactoring](../agents/continuous-refactoring.md), and optionally a
candidate problem. Read [maintenance](../../AGENTS.md#8-maintenance) in the
contract and load the role.
1. **Verify the base.** Fetch `main` and record its revision. If freshness cannot
be verified, state the revision you used and the limitation. Never switch,
reset or edit the active development checkout.
2. **Apply the threshold.** Find the strongest problem that has a named affected
party, present repository evidence, present cost and an independent acceptance
criterion. A problem inside the active goal's acceptance criterion belongs to
that goal, not here. If nothing qualifies, report that and stop.
3. **Check for existing work.** Search issues and pull requests for the same
underlying problem and update the existing one instead of duplicating. Report
incomplete duplicate checking when access is unavailable.
4. **Record it.** Draft the issue with [scope](scope.md) and the
[maintenance form](../../.github/ISSUE_TEMPLATE/maintenance.yml), creating or
updating it only within granted authority. The scout stops here.
5. **Isolate.** For simplicity or refactoring, add a worktree from the fetched
`main`, for example `git worktree add ../weft-share-package-resolution -b refactor/share-package-resolution origin/main`.
Use a branch name that describes the change, not the role.
6. **Change and review.** Follow [implement](implement.md) from proof to one
reviewed pull request, or to a prepared local result when publication is not
authorized. If the change turns out to need a
[decision](../../AGENTS.md#9-decisions-and-authority), stop it and record
the decision needed.
7. **Stop.** One run handles one problem. Do not continue collecting
opportunities, and do not merge.

View file

@ -0,0 +1,43 @@
---
name: release
description: Prepare a 0.0.x or 0.1.0 candidate's evidence and recommend promotion without promoting it automatically.
---
# Prepare a release stage
Input: the milestone scope, the target version and stage, and the exact
candidate commit. Read [versions and releases](../../AGENTS.md#13-versions-and-releases),
the blueprint's [version progression](../../BLUEPRINT.md#121-version-progression)
and, for stable `0.1.0`, the [stable release gate](../../BLUEPRINT.md#14-stable-release-gate).
1. **Inventory.** List existing tags, published releases and the versions in
`Cargo.toml`, crate manifests and package manifests. Choose the next unused
`0.0.x` for an accepted milestone scope; never reuse, move or rewrite a
published tag or release. Record how the unreleased workspace value `0.1.0`
is reconciled.
2. **Check the stage contract.** `alpha.N` needs defined scope, ownership and
fixtures with incompleteness stated. `beta.N` needs the declared scope
implemented, relevant integration and failure paths passing and interfaces,
support scope and budgets frozen. `rc.N` needs the exact candidate complete
for its scope, the required matrix passing, independent technical review and
ready artifacts and migration behavior. Final, released as the plain version
without a `-final` suffix, needs every scoped promise to pass.
3. **Collect candidate evidence** for that exact commit with [verify](verify.md):
every applicable runner profile plus the blueprint fixtures and target
environments in scope. Record commit, environment, features, commands, results
and artifact digests. A missing environment leaves the gate incomplete.
4. **Obtain independent technical review** of the candidate with the
[reviewer](../agents/reviewer.md), aimed at showing it is not ready. A self
review does not satisfy a release gate; an unavailable reviewer leaves the gate
pending while other authorized work continues.
5. **Resolve or scope.** Blocking findings prevent promotion. Corrections after
review invalidate the affected evidence: rebuild the candidate, rerun the
affected checks and re-review. Unsupported features are excluded explicitly,
not left as silent success paths.
6. **Prepare release notes** for maintainers: scope, support matrix, known
limitations, compatibility and migration notes, commit and artifact digests,
and the evidence actually executed.
7. **Recommend.** Return the evidence, open findings and a recommendation.
Promotion, tagging and publication happen only under granted release
authority, and publish the artifact that was tested. If final metadata
requires a rebuild, verify that rebuilt artifact before publishing it.

43
.agents/commands/scope.md Normal file
View file

@ -0,0 +1,43 @@
---
name: scope
description: Establish a reported problem or proposal and draft verifiable scope with owner, acceptance criterion and proof.
---
# Establish the scope
Input: a defect report, desired behavior or proposal. Read
[AGENTS.md](../../AGENTS.md), the relevant sections of
[BLUEPRINT.md](../../BLUEPRINT.md) and the matching
[skills](../README.md#skills). The result is a draft; this procedure neither
implements it nor authorizes publication.
1. **Inspect.** Read the implemented source, the public contract involved
(manifest, WIT, shell protocol, IPC types) and the selected dependency source
when an external API matters. Check whether the blueprint already records the
problem, for example in its [baseline findings](../../BLUEPRINT.md#32-findings-that-determine-the-implementation-order).
2. **Reproduce** where practical, with the exact commit, environment, features
and command. Separate observations from assumptions and say which level of
[evidence](../../BLUEPRINT.md#111-evidence-levels) each observation reached.
3. **Name the owner** from the
[ownership table](../../BLUEPRINT.md#4-architecture-and-ownership) and the
affected user, caller or contract. If nobody is worse off today, stop: there
is no issue.
4. **Check for duplicates** among existing issues and pull requests. If access is
unavailable, say that duplicate checking is incomplete.
5. **Decide the path.** Ordinary work within accepted architecture becomes a
change. A material departure from accepted direction, compatibility, trust,
support scope or data policy needs a
[decision](../../AGENTS.md#9-decisions-and-authority): prepare the evidence,
alternatives and trade-offs and mark implementation as waiting for it.
6. **Draft** against the matching form:
[defect or change](../../.github/ISSUE_TEMPLATE/change.yml),
[maintenance](../../.github/ISSUE_TEMPLATE/maintenance.yml) or
[decision](../../.github/ISSUE_TEMPLATE/decision.yml).
The draft states observed and expected behavior, evidence with file and line
references, owner and affected boundary, present impact, one acceptance
criterion, the proof that would fail today and pass afterwards, and relevant
non-goals. A claim without a verification surface is unfinished scope.
Return the draft plus any missing evidence or decision. Create or update an
issue only when that is part of the authorized task.

View file

@ -0,0 +1,43 @@
---
name: verify
description: Map a change to the evidence that proves it, run the applicable checks and report actual results and gaps.
---
# Select and run the evidence
Input: accepted scope and a diff or explicit base/head range. Read the
[proof rules](../../AGENTS.md#6-proof-before-implementation), the blueprint's
[verification profiles](../../BLUEPRINT.md#112-verification-profiles) and
[acceptance fixtures](../../BLUEPRINT.md#113-required-acceptance-fixtures), and
[CI](../../.github/workflows/ci.yml).
List the observable behaviors the change affects, not the files. For each,
name the check that would fail if it were wrong and classify it as direct proof,
incidental coverage or missing. Then select:
| Affected area | Runner profiles | Evidence the runner cannot provide |
|---|---|---|
| Portable crates (`weft-appd`, `weft-pack`, `weft-ipc-types`, `weft-file-portal`, `weft-mount-helper`, `weft-build-meta`, `weft-runtime` stub) | `portable` | Child processes, sockets and filesystems exercised for real where the change depends on them |
| `weft-compositor` | `portable linux` | Nested winit session with real clients; DRM session on the declared target |
| Servo hosts | `linux servo-embed` | Painted and presented pixels, input, resize and idle wakeup on a running compositor |
| `weft-runtime` engine or host imports | `portable runtime` | Actual component fixtures for allowed, denied and failure paths; a Linux build of the `seccomp` feature when it is touched |
| WIT, demo components | `demos packages` | Instantiating the rebuilt component under `weft-runtime` |
| Package tooling, signing, demo packages | `portable packages` | Tamper, interruption and data-retention fixtures |
| Dependency or fork change | Every profile whose crates resolve the changed package | Resolved graph inspection; the rendered or runtime behavior the change claims |
| Nix, systemd, VM | None directly | `infra/vm/build.sh` and a booted graphical image |
| Contributor documentation and toolkit | `toolkit` | Manual consistency with `AGENTS.md` and the blueprint |
Run the selected profiles with `python .agents/scripts/verify.py <profiles>`, or
the equivalent commands directly, and record actual exit results. Run them
against the committed graph, without local `[patch]` overrides.
A missing native library, toolchain target, display, GPU, VM or Nix installation
is unavailable evidence: name it and the boundary left unverified. Never count a
skip, a feature-disabled build or a mocked boundary as proof of the real path.
Choose expensive checks by risk; do not repeat unrelated ones once the risk is
resolved. Release gates need the complete matrix in [release](release.md).
Return a compact table of behaviors, proof and status; the commands actually run
with results; remaining gaps; and the single most valuable missing check if one
exists. Do not change product code to probe coverage unless that experiment is
authorized and isolated.

View file

@ -0,0 +1,174 @@
"""Check contributor documents: local links and anchors, toolkit metadata, catalog and issue forms."""
import re
import sys
from pathlib import Path
from urllib.parse import unquote, urlsplit
try:
import yaml
from markdown_it import MarkdownIt
except ImportError as error:
sys.exit(f"{error}; install .agents/scripts/requirements.txt to run the toolkit checks")
ROOT = Path(__file__).resolve().parents[2]
MARKDOWN = MarkdownIt("commonmark")
FRONTMATTER = re.compile(r"\A---\n(.*?)\n---(?:\n|\Z)", re.DOTALL)
CATALOGUED = ("commands", "agents", "skills")
TOP_LEVEL = ("AGENTS.md", "CONTRIBUTING.md", "README.md", "BLUEPRINT.md",
".github/pull_request_template.md")
SLUG_DROP = re.compile(r"[^\w\- ]", re.UNICODE)
def body(source):
match = FRONTMATTER.match(source)
return source[match.end():] if match else source
def tokens(source):
for block in MARKDOWN.parse(body(source)):
yield block
yield from block.children or []
def local_links(path, source, *, images=True):
"""Yield (target, resolved path, fragment) for each relative link or image."""
for token in tokens(source):
if token.type == "link_open":
target = token.attrGet("href")
elif images and token.type == "image":
target = token.attrGet("src")
else:
continue
if not target:
continue
url = urlsplit(target)
if url.scheme or url.netloc:
continue
resolved = (path.parent / unquote(url.path)).resolve() if url.path else path.resolve()
yield target, resolved, unquote(url.fragment)
def anchors(source):
"""Return GitHub-style heading anchors, including numbered duplicates."""
result, seen = set(), {}
blocks = MARKDOWN.parse(body(source))
for index, block in enumerate(blocks):
if block.type != "heading_open":
continue
inline = blocks[index + 1]
text = "".join(child.content for child in inline.children or []
if child.type in ("text", "code_inline"))
slug = SLUG_DROP.sub("", text.strip().lower()).replace(" ", "-")
count = seen.get(slug, 0)
seen[slug] = count + 1
result.add(slug if count == 0 else f"{slug}-{count}")
return result
def metadata_fields(source):
"""Return name/description from a YAML mapping with unique string fields, else None."""
try:
node = yaml.compose(source, Loader=yaml.SafeLoader)
except yaml.YAMLError:
return None
if not isinstance(node, yaml.MappingNode):
return None
fields = {}
for key, value in node.value:
if (not isinstance(key, yaml.ScalarNode) or key.tag != "tag:yaml.org,2002:str"
or key.value in fields):
return None
fields[key.value] = value
result = {}
for name in ("name", "description"):
value = fields.get(name)
if not isinstance(value, yaml.ScalarNode) or value.tag != "tag:yaml.org,2002:str":
return None
result[name] = value.value
return result
def check_issue_forms(root):
errors = []
for path in sorted((root / ".github/ISSUE_TEMPLATE").glob("*.yml")):
label = path.relative_to(root)
try:
form = yaml.safe_load(path.read_text(encoding="utf-8"))
except yaml.YAMLError as error:
errors.append(f"{label}: invalid YAML: {error}")
continue
if path.name == "config.yml":
if not isinstance(form, dict) or "blank_issues_enabled" not in form:
errors.append(f"{label}: missing blank_issues_enabled")
continue
if (not isinstance(form, dict) or not isinstance(form.get("name"), str)
or not isinstance(form.get("description"), str)
or not isinstance(form.get("body"), list) or not form["body"]):
errors.append(f"{label}: issue form needs name, description and a nonempty body")
continue
ids = [item.get("id") for item in form["body"]
if isinstance(item, dict) and item.get("type") != "markdown"]
if None in ids or len(ids) != len(set(ids)):
errors.append(f"{label}: every input needs a unique id")
return errors
def check(root):
root = root.resolve()
toolkit = root / ".agents"
catalog_path = toolkit / "README.md"
if not catalog_path.is_file():
return ["missing .agents/README.md"]
catalog = catalog_path.read_text(encoding="utf-8")
catalog_targets = {resolved for _, resolved, _ in local_links(catalog_path, catalog,
images=False)}
errors = []
documents = sorted(toolkit.rglob("*.md")) + [root / name for name in TOP_LEVEL]
anchor_cache = {}
for path in documents:
label = path.relative_to(root)
if not path.is_file():
errors.append(f"missing {label}")
continue
source = path.read_text(encoding="utf-8")
for target, resolved, fragment in local_links(path, source):
if not resolved.is_relative_to(root) or not resolved.exists():
errors.append(f"{label}: broken local link {target}")
continue
if fragment and resolved.suffix == ".md":
if resolved not in anchor_cache:
anchor_cache[resolved] = anchors(resolved.read_text(encoding="utf-8"))
if fragment not in anchor_cache[resolved]:
errors.append(f"{label}: missing anchor {target}")
relative = path.relative_to(toolkit) if path.is_relative_to(toolkit) else None
if relative and relative.parts[0] in CATALOGUED:
match = FRONTMATTER.match(source)
if not match:
errors.append(f"{label}: missing front matter")
continue
fields = metadata_fields(match[1])
expected = path.parent.name if path.name == "SKILL.md" else path.stem
if not fields or fields["name"] != expected or not fields["description"].strip():
errors.append(f"{label}: name must match path and description must be nonempty; "
"use a YAML mapping with unique string fields")
if path.resolve() not in catalog_targets:
errors.append(f"{label}: absent from toolkit catalog")
for kind in CATALOGUED:
if not list((toolkit / kind).rglob("*.md")):
errors.append(f"no documents in .agents/{kind}")
return errors + check_issue_forms(root)
def main():
errors = check(ROOT)
if errors:
print("\n".join(errors), file=sys.stderr)
return 1
print("Contributor toolkit links, anchors, metadata, catalog and issue forms passed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,3 @@
markdown-it-py==4.2.0
mdurl==0.1.2
PyYAML==6.0.3

View file

@ -0,0 +1,240 @@
import contextlib
import importlib.util
import io
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
def load(name):
spec = importlib.util.spec_from_file_location(f"weft_toolkit_{name}", HERE / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
checker = load("check_toolkit")
verify = load("verify")
SKILL = "---\nname: example\ndescription: An example skill.\n---\n[Contract](../../../AGENTS.md)\n"
COMMAND = "---\nname: run\ndescription: An example command.\n---\n# Run\n"
ROLE = "---\nname: role\ndescription: An example role.\n---\n# Role\n"
CATALOG = ("[Example](skills/example/SKILL.md)\n[Run](commands/run.md)\n"
"[Role](agents/role.md)\n")
FORM = ("name: Change\ndescription: A change.\nbody:\n"
" - type: markdown\n attributes:\n value: Intro\n"
" - type: textarea\n id: observed\n attributes:\n label: Observed\n")
class ToolkitCheck(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.root = Path(directory.name)
for name in checker.TOP_LEVEL:
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("# Contract\n\n## 2. Evidence levels\n", encoding="utf-8")
self.skill = self.write(".agents/skills/example/SKILL.md", SKILL)
self.write(".agents/commands/run.md", COMMAND)
self.write(".agents/agents/role.md", ROLE)
self.catalog = self.write(".agents/README.md", CATALOG)
self.form = self.write(".github/ISSUE_TEMPLATE/change.yml", FORM)
self.write(".github/ISSUE_TEMPLATE/config.yml", "blank_issues_enabled: false\n")
def write(self, relative, text):
path = self.root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def errors_containing(self, text):
return [error for error in checker.check(self.root) if text in error]
def append_to_skill(self, text):
self.skill.write_text(SKILL + text + "\n", encoding="utf-8")
def test_valid_toolkit_passes(self):
self.assertEqual(checker.check(self.root), [])
def test_missing_contract_breaks_links(self):
(self.root / "AGENTS.md").unlink()
self.assertTrue(self.errors_containing("broken local link"))
def test_link_outside_repository_is_rejected(self):
self.append_to_skill("[Outside](../../../../outside.md)")
self.assertTrue(self.errors_containing("broken local link"))
def test_existing_and_missing_anchors(self):
self.append_to_skill("[Levels](../../../AGENTS.md#2-evidence-levels)")
self.assertEqual(checker.check(self.root), [])
self.append_to_skill("[Levels](../../../AGENTS.md#3-missing)")
self.assertTrue(self.errors_containing("missing anchor"))
def test_same_document_anchor(self):
self.skill.write_text(SKILL + "## Local `code` heading\n[Here](#local-code-heading)\n",
encoding="utf-8")
self.assertEqual(checker.check(self.root), [])
self.skill.write_text(SKILL + "[Here](#absent)\n", encoding="utf-8")
self.assertTrue(self.errors_containing("missing anchor"))
def test_duplicate_headings_receive_numbered_anchors(self):
self.skill.write_text(SKILL + "## Step\n## Step\n[Second](#step-1)\n", encoding="utf-8")
self.assertEqual(checker.check(self.root), [])
def test_literal_examples_are_not_links(self):
for example in ["`[X](missing.md)`", "```md\n[X](missing.md)\n```",
"<!-- [X](missing.md) -->", r"\[X](missing.md)"]:
with self.subTest(example=example):
self.append_to_skill(example)
self.assertEqual(checker.check(self.root), [])
def test_reference_links_are_checked(self):
self.append_to_skill("[Missing][doc]\n\n[doc]: missing.md")
self.assertTrue(self.errors_containing("broken local link"))
def test_metadata_must_match_path_and_be_unique_strings(self):
for fields in ["name: other\ndescription: Example.", "name: example\ndescription:",
"name: example\ndescription: 42", "name: example\nname: example\n"
"description: Example.", "name: example\ndescription: [unterminated"]:
with self.subTest(fields=fields):
self.skill.write_text(f"---\n{fields}\n---\n", encoding="utf-8")
self.assertTrue(self.errors_containing("name must match path"))
def test_missing_front_matter_is_rejected(self):
self.skill.write_text("# No metadata\n", encoding="utf-8")
self.assertTrue(self.errors_containing("missing front matter"))
def test_uncatalogued_document_is_rejected(self):
self.catalog.write_text("[Example](skills/example/SKILL.md)\n", encoding="utf-8")
errors = self.errors_containing("absent from toolkit catalog")
self.assertEqual(len(errors), 2)
def test_catalog_needs_a_visible_link(self):
self.catalog.write_text("`[Example](skills/example/SKILL.md)`\n"
"[Run](commands/run.md)\n[Role](agents/role.md)\n",
encoding="utf-8")
self.assertTrue(self.errors_containing("absent from toolkit catalog"))
def test_empty_toolkit_directory_is_rejected(self):
(self.root / ".agents/agents/role.md").unlink()
self.catalog.write_text("[Example](skills/example/SKILL.md)\n[Run](commands/run.md)\n",
encoding="utf-8")
self.assertTrue(self.errors_containing("no documents in .agents/agents"))
def test_issue_forms_are_validated(self):
self.form.write_text("name: Change\nbody: []\n", encoding="utf-8")
self.assertTrue(self.errors_containing("issue form needs"))
self.form.write_text(FORM + " - type: input\n id: observed\n", encoding="utf-8")
self.assertTrue(self.errors_containing("unique id"))
self.form.write_text("name: [unterminated\n", encoding="utf-8")
self.assertTrue(self.errors_containing("invalid YAML"))
def test_repository_toolkit_passes(self):
self.assertEqual(checker.check(ROOT), [])
def test_missing_dependencies_fail_with_instructions(self):
result = subprocess.run([sys.executable, "-I", "-S", "-B", str(HERE / "check_toolkit.py")],
capture_output=True, text=True, check=False)
self.assertEqual(result.returncode, 1)
self.assertIn("requirements.txt", result.stderr)
class Runner(unittest.TestCase):
def run_quietly(self, argv):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
return verify.main(argv)
def test_dry_run_from_another_directory_executes_nothing(self):
with tempfile.TemporaryDirectory() as directory:
result = subprocess.run(
[sys.executable, str(HERE / "verify.py"), "portable", "demos", "--dry-run"],
cwd=directory, capture_output=True, text=True, check=False,
)
self.assertEqual(list(Path(directory).iterdir()), [])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("cargo fmt --all --check", result.stdout)
self.assertIn("--target wasm32-wasip2", result.stdout)
def test_dry_run_calls_no_subprocess(self):
with patch.object(verify.subprocess, "run") as run:
self.assertEqual(self.run_quietly(list(verify.PROFILES) + ["--dry-run"]), 0)
run.assert_not_called()
def test_commands_run_from_repository_root(self):
with patch.object(verify.subprocess, "run") as run:
run.return_value = subprocess.CompletedProcess([], 0)
self.assertEqual(self.run_quietly(["servo-embed"]), 0)
self.assertEqual(run.call_count, 2)
for call in run.call_args_list:
self.assertEqual(call.kwargs["cwd"], ROOT)
self.assertEqual(call.kwargs["env"]["RUSTUP_AUTO_INSTALL"], "0")
self.assertIsInstance(call.args[0], list)
def test_failure_stops_remaining_checks_and_keeps_status(self):
with patch.object(verify.subprocess, "run") as run:
run.return_value = subprocess.CompletedProcess([], 7)
self.assertEqual(self.run_quietly(["portable", "linux"]), 7)
self.assertEqual(run.call_count, 1)
def test_failure_in_later_command_stops_profile(self):
statuses = [subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 101)]
with patch.object(verify.subprocess, "run", side_effect=statuses) as run:
self.assertEqual(self.run_quietly(["portable", "linux"]), 101)
self.assertEqual(run.call_count, 2)
def test_signal_termination_is_failure(self):
with patch.object(verify.subprocess, "run") as run:
run.return_value = subprocess.CompletedProcess([], -9)
self.assertEqual(self.run_quietly(["toolkit"]), 1)
def test_missing_executable_is_failure(self):
with patch.object(verify.subprocess, "run", side_effect=FileNotFoundError("cargo")):
self.assertEqual(self.run_quietly(["linux"]), 1)
def test_real_failing_command_propagates(self):
failing = {"failing": ("fails", [[sys.executable, "-c", "raise SystemExit(3)"]])}
with patch.dict(verify.PROFILES, failing):
self.assertEqual(self.run_quietly(["failing"]), 3)
def test_unknown_profile_is_rejected_before_execution(self):
with patch.object(verify.subprocess, "run") as run:
with self.assertRaises(SystemExit) as error:
self.run_quietly(["unknown"])
self.assertEqual(error.exception.code, 2)
run.assert_not_called()
def test_repeated_profiles_run_once(self):
with patch.object(verify.subprocess, "run") as run:
run.return_value = subprocess.CompletedProcess([], 0)
self.run_quietly(["servo-embed", "servo-embed"])
self.assertEqual(run.call_count, 2)
def test_profiles_never_mutate_install_or_publish(self):
forbidden = {"install", "add", "update", "fix", "publish", "push", "commit", "sign",
"uninstall", "--bless", "--fix", "--allow-dirty"}
for name, (_, commands) in verify.PROFILES.items():
for command in commands:
with self.subTest(profile=name, command=command):
self.assertTrue(all(isinstance(part, str) for part in command))
self.assertFalse(forbidden.intersection(command))
if command[:2] == ["cargo", "fmt"]:
self.assertIn("--check", command)
def test_cargo_checks_use_the_locked_graph(self):
for name, (_, commands) in verify.PROFILES.items():
for command in commands:
if command[0] == "cargo" and command[1] != "fmt":
with self.subTest(profile=name, command=command):
self.assertIn("--locked", command)
if __name__ == "__main__":
unittest.main()

128
.agents/scripts/verify.py Normal file
View file

@ -0,0 +1,128 @@
"""Run WEFT OS verification profiles without installing, formatting or publishing anything.
Each profile is a fixed list of argument arrays executed from the repository root.
The runner stops at the first failing command and returns its exit status.
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# Stop rustup from installing the pinned toolchain or its components on demand.
ENVIRONMENT = {**os.environ, "RUSTUP_AUTO_INSTALL": "0"}
LINUX_CRATES = ["weft-compositor", "weft-servo-shell", "weft-app-shell"]
DEMOS = ["examples/org.weft.demo.counter", "examples/org.weft.demo.notes"]
DEMO_KEY = "examples/keys/weft-sign.pub"
RUNTIME_FEATURES = "wasmtime-runtime,net-fetch"
def _packages(flag, crates):
return [part for crate in crates for part in (flag, crate)]
PROFILES = {
"toolkit": (
"Contributor toolkit links, catalog, metadata and runner tests",
[
[sys.executable, "-B", ".agents/scripts/check_toolkit.py"],
[sys.executable, "-B", "-m", "unittest", "discover", "-s", ".agents/scripts",
"-p", "test_*.py"],
],
),
"portable": (
"Formatting, Clippy and tests for crates that need no Linux system libraries (CI portable)",
[
["cargo", "fmt", "--all", "--check"],
["cargo", "clippy", "--workspace", *_packages("--exclude", LINUX_CRATES),
"--all-targets", "--locked", "--", "-D", "warnings"],
["cargo", "test", "--workspace", *_packages("--exclude", LINUX_CRATES), "--locked"],
],
),
"linux": (
"Clippy and tests for the Wayland compositor and feature-disabled shells (CI linux-only)",
[
["cargo", "clippy", *_packages("-p", LINUX_CRATES), "--all-targets", "--locked",
"--", "-D", "warnings"],
["cargo", "test", *_packages("-p", LINUX_CRATES), "--locked"],
],
),
"servo-embed": (
"Type-check both Servo hosts with the real renderer feature (CI servo-embed-linux)",
[
["cargo", "check", "-p", "weft-servo-shell", "--features", "servo-embed", "--locked"],
["cargo", "check", "-p", "weft-app-shell", "--features", "servo-embed", "--locked"],
],
),
"runtime": (
"Clippy and tests for weft-runtime with the Wasmtime engine and fetch enabled",
[
["cargo", "clippy", "-p", "weft-runtime", "--features", RUNTIME_FEATURES,
"--all-targets", "--locked", "--", "-D", "warnings"],
["cargo", "test", "-p", "weft-runtime", "--features", RUNTIME_FEATURES, "--locked"],
],
),
"demos": (
"Check the demo components for wasm32-wasip2 against their own lockfiles",
[
["cargo", "check", "--locked", "--manifest-path", f"{demo}/Cargo.toml",
"--target", "wasm32-wasip2", "--target-dir", "target/examples"]
for demo in DEMOS
],
),
"packages": (
"Validate the demo packages and verify their committed signatures with weft-pack",
[
command
for demo in DEMOS
for command in (
["cargo", "run", "--quiet", "--locked", "-p", "weft-pack", "--", "check", demo],
["cargo", "run", "--quiet", "--locked", "-p", "weft-pack", "--", "verify", demo,
"--key", DEMO_KEY],
)
],
),
}
def describe():
width = max(map(len, PROFILES))
lines = [f" {name:<{width}} {summary}" for name, (summary, _) in PROFILES.items()]
return "profiles:\n" + "\n".join(lines)
def main(argv=None):
parser = argparse.ArgumentParser(
description=__doc__,
epilog=describe(),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("profiles", nargs="+", choices=PROFILES, metavar="profile",
help="one or more profiles, run in the given order")
parser.add_argument("--dry-run", action="store_true",
help="print the commands without running them")
args = parser.parse_args(argv)
for profile in dict.fromkeys(args.profiles):
for command in PROFILES[profile][1]:
print(f"[{profile}] {subprocess.list2cmdline(command)}", flush=True)
if args.dry_run:
continue
try:
result = subprocess.run(command, cwd=ROOT, env=ENVIRONMENT, check=False)
except OSError as error:
print(f"[{profile}] cannot run {command[0]}: {error}", file=sys.stderr)
return 1
if result.returncode != 0:
print(f"[{profile}] failed with exit status {result.returncode}", file=sys.stderr)
return result.returncode if result.returncode > 0 else 1
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,59 @@
---
name: weft-appd-sessions
description: Use for weft-appd session lifecycle, readiness, child supervision and cleanup, the appd IPC and WebSocket bridge, and compositor association.
---
# Appd sessions and IPC
Owner: `weft-appd` owns resolved package selection, effective grants, session
identity, child supervision, readiness and cleanup. The shells display that
state; they do not keep a second authoritative copy. Read the blueprint's
[resolved package descriptor](../../../BLUEPRINT.md#41-one-resolved-package-descriptor),
[role-separated protocol](../../../BLUEPRINT.md#61-role-separated-protocol) and
[single lifecycle owner](../../../BLUEPRINT.md#62-single-lifecycle-owner).
## Where things live
| Concern | Source |
|---|---|
| Daemon, session registry, request dispatch | [appd main.rs](../../../crates/weft-appd/src/main.rs) |
| Child spawning, preopens, systemd wrapping, data paths | [runtime.rs](../../../crates/weft-appd/src/runtime.rs) |
| Unix socket messages | [ipc.rs](../../../crates/weft-appd/src/ipc.rs) |
| Browser-facing WebSocket server | [ws.rs](../../../crates/weft-appd/src/ws.rs) |
| Compositor association client | [compositor_client.rs](../../../crates/weft-appd/src/compositor_client.rs), [weft-ipc-types](../../../crates/weft-ipc-types/src/lib.rs) |
| Image mount path | [mount.rs](../../../crates/weft-appd/src/mount.rs) |
| Injected app bridge | [app-shell embedder](../../../crates/weft-app-shell/src/embedder.rs) |
| Shell-side client | [system-ui.html](../../../infra/shell/system-ui.html) |
## Working rules
- One session model: `Starting -> Running -> Stopping -> Stopped`, with
structured terminal reasons. `Running` requires the component initialized,
session IPC connected, the document and bridge initialized and the surface's
first frame presented. Stdout text cannot establish readiness.
- Every exit path enters the same cleanup: spawn failure, invalid package,
initialization failure, timeout, cancellation, guest trap, child crash,
explicit close and daemon shutdown. Owned resources include both children,
portals, relays, sockets, compositor associations, temporary directories and
mounts.
- Use a process-group or systemd mechanism that is valid for the selected
systemd and preserves ownership; verify `systemd-run` argument combinations
against the installed version. Terminate gracefully for a bounded time, then
forcibly, and await settlement instead of sleeping.
- A caller-supplied `session_id` is a routing claim. Bind role, session and
generation on the server, authenticate the browser bootstrap, and never
deliver private payloads to unrelated subscribers.
- The bridge and daemon share one versioned semantic envelope. Bound frame size,
queued messages and bytes and concurrency; preserve partial frames across
cancellation; do not hold the registry lock across awaits; remove closed
relays; resynchronize from a snapshot after overflow.
- Default logs exclude application payloads, clipboard contents, saved notes and
credentials.
## Evidence
`python .agents/scripts/verify.py portable` runs the appd and IPC unit tests.
Lifecycle and protocol claims need fixtures with real child processes and
sockets: each startup phase failing or cancelled, children crashing, fragmented
and concurrent frames, full queues, forged and stale credentials, and checks that
no owned process, socket, relay or mount remains.

View file

@ -0,0 +1,55 @@
---
name: weft-compositor-input
description: Use for the Smithay compositor, Wayland protocols, surfaces, focus, geometry, input routing and the DRM and winit backends.
---
# Compositor, Wayland and input
Owner: `weft-compositor` owns surfaces, accepted geometry, focus, stacking, work
areas, input routing and presentation. Appd owns session identity; the shells
request and render. Read the blueprint's
[surface and window contract](../../../BLUEPRINT.md#72-surface-and-window-contract),
[input requirements](../../../BLUEPRINT.md#73-required-input-and-accessibility-behavior)
and [backend completion](../../../BLUEPRINT.md#74-backend-specific-completion).
## Where things live
| Concern | Source |
|---|---|
| Wayland globals and handlers (xdg-shell, layer-shell, DMA-BUF state, presentation) | [state.rs](../../../crates/weft-compositor/src/state.rs) |
| Keyboard, pointer and wheel routing | [input.rs](../../../crates/weft-compositor/src/input.rs) |
| `zweft-shell-unstable-v1` server side | [protocols/mod.rs](../../../crates/weft-compositor/src/protocols/mod.rs), [protocol XML](../../../protocol/weft-shell-unstable-v1.xml) |
| Appd association channel | [appd_ipc.rs](../../../crates/weft-compositor/src/appd_ipc.rs), [weft-ipc-types](../../../crates/weft-ipc-types/src/lib.rs) |
| Nested backend | [backend/winit.rs](../../../crates/weft-compositor/src/backend/winit.rs) |
| DRM/KMS, udev, libinput, session | [backend/drm.rs](../../../crates/weft-compositor/src/backend/drm.rs), [backend/drm_device.rs](../../../crates/weft-compositor/src/backend/drm_device.rs) |
## Working rules
- Verify Smithay behavior in the `smithay 0.7` source selected by `Cargo.lock`
(output frame submission, DMA-BUF global creation, seat and focus handling),
not in newer upstream examples. Advertise only globals the compositor actually
serves.
- Bind surfaces to sessions through trusted launch or connection evidence and
observed client identity, with opaque IDs and generations. A PID, title or
custom shell-protocol request is not authority. Only the trusted shell acquires
privileged roles such as `panel`.
- Effective xdg geometry and acknowledged configure state must agree; echoing a
`set_geometry` request does not move a surface.
- Prevent stuck keys and buttons after focus loss, client exit, drag
cancellation and output changes. Keep logical and physical coordinates
consistent across scale changes.
- DRM paths need the frame completion transition, presentation feedback,
idle and empty-frame scheduling that resumes on commits, session pause and
activation, and error recovery. Do not replace existing layer rendering on a
false premise.
## Evidence
`python .agents/scripts/verify.py portable linux` covers compilation, lints and
the protocol unit tests in `protocols/mod.rs`. It does not run a compositor.
Geometry, focus, stacking, input and presentation claims need a nested winit
session with real clients, and DRM claims need a DRM session on the declared
target; see [integration verification](../weft-integration-verification/SKILL.md).
The compositor and both shells generate their protocol code from the same XML,
so a protocol change affects all three; check them with the `linux` and
`servo-embed` profiles and keep the interface version deliberate.

View file

@ -0,0 +1,53 @@
---
name: weft-documentation
description: Use for WEFT OS public documentation, the blueprint, this contributor toolkit, issue and pull request templates and the verification runner.
---
# Documentation and the toolkit
[AGENTS.md](../../../AGENTS.md) is the only policy source. The
[blueprint](../../../BLUEPRINT.md) holds accepted direction. Public documentation
in [README.md](../../../README.md) and [docs/](../../../docs/architecture.md)
describes implemented behavior and must agree with source.
## Working rules
- Verify every command, path, feature, environment variable and API you document
against the current source, and run commands where practical. Keep blueprint
intent, implemented behavior and executed evidence distinct: "implemented",
"verified" and "planned" are different claims.
- Correct documentation that contradicts source instead of working around it;
for example, a pin file that disagrees with `Cargo.lock`, or a signing
description that differs from the implemented inventory.
- Link durable decisions and requirements to their owning artifact. Toolkit files
provide procedures and area knowledge, never a second policy, permissions,
schedules or an internal log.
- Write issues, pull requests, commits and release notes for maintainers: the
problem, the resulting behavior and the evidence. No attribution, trailers,
prompts or process narration.
- Keep Markdown portable: standard CommonMark links and tables, YAML front matter
with `name` and `description` only, no client-specific syntax required to
follow a procedure.
## Toolkit changes
Add area knowledge in a skill, repeatable steps in a command, review criteria in
a role and executable checks in `.agents/scripts/`. Update the
[catalog](../../README.md) for every new document. Then run:
```sh
pip install -r .agents/scripts/requirements.txt
python .agents/scripts/verify.py toolkit
```
That checks links, anchors, metadata, catalog coverage and issue forms, and runs
the runner tests. For runner changes, add tests for failure propagation,
unknown input, missing executables and execution from another directory. Review
the instructions manually against `AGENTS.md`, the blueprint and CI; passing
checks does not establish that the instructions are true.
Changes to the blueprint or contract are governance changes: follow the
[reviewed loop](../../../AGENTS.md#5-reviewed-change-loop), check every document
that links to the changed sections, and seek a
[decision](../../../AGENTS.md#9-decisions-and-authority) for a material change of
direction.

View file

@ -0,0 +1,54 @@
---
name: weft-integration-verification
description: Use for end-to-end and visual evidence in WEFT OS — real sessions, pixels and native input, failure injection, reliability runs and evidence records.
---
# Integration and visual verification
Integration evidence shows what unit tests cannot: real frames, native input,
real child processes, real components and an installed system. Read the
blueprint's [evidence levels](../../../BLUEPRINT.md#111-evidence-levels),
[verification profiles](../../../BLUEPRINT.md#112-verification-profiles),
[acceptance fixtures](../../../BLUEPRINT.md#113-required-acceptance-fixtures) and
[user journeys](../../../BLUEPRINT.md#22-required-user-journeys).
## Fixture design
- Choose the fixture before implementing. It must fail when the promised
behavior breaks and must not restate the implementation or only grep a success
log.
- For rendering, use a deterministic page with known color regions, text,
scrolling content, a text field, an interactive counter and a controlled
animation. Compare actual pixels read back after painting at the relevant
scales and sizes, including first frame, resize and idle wakeup.
- For input, drive the real native path on a running compositor: key press and
release, modifiers, declared US and Italian layouts with non-ASCII text,
buttons, motion, wheel, focus changes and scale changes. Check for stuck input
after focus loss and client exit.
- For lifecycle, inject failures at each startup phase and after `Running`:
missing binary, invalid package, renderer failure, runtime trap, crash,
cancellation and timeout. Assert a terminal reason and that no owned process,
socket, relay or mount remains.
- For data, use Notes with empty, non-ASCII, multi-line, quoted and literal
backslash text, delayed replies, failed writes and competing writers; repeat
after close, daemon restart, update and reboot.
- Counter and Notes are conformance applications: their happy paths are
necessary but insufficient.
## Running and recording
The [runner](../../scripts/verify.py) provides only build, lint, unit and
package checks. Integration fixtures run in the environment they claim: a nested
winit session for nested-desktop evidence, a DRM session on the declared target,
the booted reference image for installed behavior. Keep captures and logs under
ignored paths such as `target/`; commit fixtures, not their outputs.
Record for each run the commit, environment (host, compositor backend, GPU or
virtual device, Mesa, kernel), enabled features, exact command, observed result
and diagnostics. A screenshot shows pixels, not input routing or accessibility.
An unavailable display, GPU or VM leaves the gate incomplete; say which boundary
remained unverified.
Reliability qualification follows the blueprint targets: repeated clean boots,
launch and close cycles without orphans, mixed interactive and idle runs.
Performance and budget claims need measurements on the reference target.

View file

@ -0,0 +1,53 @@
---
name: weft-linux-deployment
description: Use for the Nix flake and reference VM, systemd units, native dependencies, installed paths, endpoints and service activation.
---
# Linux deployment
Owner: Linux and systemd own the seat, session substrate, service lifecycle and
process and resource boundaries. The installed closure must carry the real
feature-enabled product. Read the blueprint's
[release profile](../../../BLUEPRINT.md#21-required-release-profile),
[installed session](../../../BLUEPRINT.md#102-installed-session) and
[developer workflow](../../../BLUEPRINT.md#103-diagnostics-and-developer-workflow).
## Where things live
| Concern | Source |
|---|---|
| Flake, toolchain, dev shell | [flake.nix](../../../flake.nix), [flake.lock](../../../flake.lock) |
| Package derivations and features | [weft-packages.nix](../../../infra/nixos/weft-packages.nix) |
| VM configuration | [configuration.nix](../../../infra/nixos/configuration.nix) |
| VM build and run | [build.sh](../../../infra/vm/build.sh), [run.sh](../../../infra/vm/run.sh) |
| Service units | [infra/systemd](../../../infra/systemd/weft-appd.service) |
| Native build dependencies | [building.md](../../../docs/building.md), [CI](../../../.github/workflows/ci.yml) |
| Environment variables | [architecture.md](../../../docs/architecture.md) and the `std::env` reads in each crate |
## Working rules
- Keep one authoritative Nix and systemd configuration; make development units
and scripts consistent with it.
- The closure includes the feature-enabled binaries (`servo-embed` for both
shells, `wasmtime-runtime` for the runtime), the shell HTML and UI assets at
installed paths, reference packages with an explicit trust configuration, the
binary paths appd needs, and explicit activation and dependencies.
- Pass the real compositor display and daemon endpoints; never guess names such
as `wayland-1`. Keep persistent data and ephemeral runtime storage separate.
- Fill fixed-output hashes, including Servo's git `outputHashes`, from an actual
build, never by copying an unrelated value.
- Never fabricate `pkg-config` files or library versions to satisfy a build.
Repair the environment or exclude the feature explicitly. Do not commit
machine-specific usernames or checkout paths.
- Record the exact VM machine, graphics device, kernel, Mesa, CPU and memory
used for evidence. A headless VM or a successful evaluation is not graphical
acceptance.
## Evidence
The runner has no Nix or VM profile. Build with `bash infra/vm/build.sh` and run
with `bash infra/vm/run.sh` where Nix with flakes is available, and record the
environment. Installed-system claims need a fresh graphical boot that starts the
complete system without checkout paths or manual repair, plus persistence across
reboot and update. A missing Nix installation or virtualization support is
unavailable evidence.

View file

@ -0,0 +1,57 @@
---
name: weft-packages-data
description: Use for wapp.toml manifests, weft-pack, signing and trust, installation and updates, app data storage and EROFS dm-verity images.
---
# Packages, trust, data and updates
Owner: package tooling owns manifest validation, content identity, trust,
staging, activation and retention. User data has its own lifecycle and is never
owned by installed package bytes. Read the blueprint's
[packages, trust, storage and updates](../../../BLUEPRINT.md#9-packages-trust-storage-and-updates)
and [Notes requirements](../../../BLUEPRINT.md#82-notes).
## Where things live
| Concern | Source |
|---|---|
| `check`, `info`, `install`, `uninstall`, `list`, `generate-key`, `sign`, `verify`, `bundle`, `unbundle`, `build-image`, `build-verity` | [weft-pack](../../../crates/weft-pack/src/main.rs) |
| Manifests | [counter wapp.toml](../../../examples/org.weft.demo.counter/wapp.toml), [notes wapp.toml](../../../examples/org.weft.demo.notes/wapp.toml) |
| Demo signing fixture keys | [examples/keys](../../../examples/keys/weft-sign.pub) |
| Data and package roots used at launch | [appd runtime.rs](../../../crates/weft-appd/src/runtime.rs) |
| Image mount and privileged helper | [appd mount.rs](../../../crates/weft-appd/src/mount.rs), [weft-mount-helper](../../../crates/weft-mount-helper/src/main.rs) |
## Working rules
- The implemented signature covers the recursively enumerated package inventory,
including UI content and excluding the signature file, and both demo
signatures verify under it. Preserve that compatibility deliberately when
formalizing the format; do not re-sign demos to match a different description.
Correct documentation that describes a narrower inventory.
- Demo keys are fixtures and never production signing authority. Release
private keys stay outside the repository.
- Separate verified and development installation policies. Verified installs
fail closed on invalid, missing, revoked or untrusted signatures; development
installs are explicit and visibly marked.
- Validate IDs, entry containment, duplicates, link policy and the actual
component before trust decisions. Bind each app ID and its retained data to a
publisher key policy.
- Install and update through staging, validation, verification, immutable
content and atomic activation. Failure preserves the previous active revision
and user data; a live session stays pinned to its revision; uninstall keeps
data unless an explicit purge is requested.
- Migrating the existing `apps/<id>/data` layout needs detection, backup, conflict
handling and a test proving Notes contents survive. Keep it out of unrelated
cleanups.
- Verified image mode never falls back to a mutable directory, and the privileged
helper is enabled only after its caller authorization and failure paths are
specified and tested.
## Evidence
`python .agents/scripts/verify.py portable packages` runs the package unit tests
and checks and verifies the committed demo packages. Trust, install and update
claims need tamper, interruption, publisher-ownership, active-update and
uninstall fixtures from the blueprint's
[acceptance list](../../../BLUEPRINT.md#113-required-acceptance-fixtures), and
persistence claims need reruns after reinstall, restart and reboot.

View file

@ -0,0 +1,58 @@
---
name: weft-runtime-capabilities
description: Use for the Wasmtime runtime, WIT host imports, WASI preopens, effective grants, the file portal and seccomp.
---
# Runtime, WASI and capabilities
Owner: `weft-runtime` instantiates the component and enforces every host call;
appd derives the effective grants once from the resolved package. Portals and
host services act only on explicitly granted resources. Read the blueprint's
[security and capability contract](../../../BLUEPRINT.md#5-security-and-capability-contract)
and [component compatibility](../../../BLUEPRINT.md#42-manifest-and-component-compatibility).
## Where things live
| Concern | Source |
|---|---|
| Engine setup, linker, host imports, preopens, seccomp | [weft-runtime main.rs](../../../crates/weft-runtime/src/main.rs) |
| Host WIT (`weft:app@0.1.0`: notify, ipc, fetch, notifications, clipboard) | [weft-app.wit](../../../crates/weft-runtime/wit/weft-app.wit) |
| Demo copies of the WIT | `examples/*/wit/deps/weft-app/weft-app.wit` |
| Capability strings accepted at package check | `is_known_capability` and its `EXACT` list in [weft-pack](../../../crates/weft-pack/src/main.rs) |
| Capability to preopen mapping at launch | [appd runtime.rs](../../../crates/weft-appd/src/runtime.rs) |
| File portal | [weft-file-portal](../../../crates/weft-file-portal/src/main.rs) |
## Working rules
- Features: `wasmtime-runtime` enables the engine, `net-fetch` the fetch import,
`seccomp` the syscall blocklist. Without `wasmtime-runtime` the binary prints
READY and exits; that path is a limited build fixture, never product
evidence.
- Verify Wasmtime and wasmtime-wasi behavior in the version `Cargo.lock`
selects, including how the linker treats differing WIT patch versions. A
textual version difference is not an ABI defect until an actual component
shows it.
- Every advertised import checks the effective grant on every call. Absent or
unsupported operations fail explicitly; they are not successful no-ops.
- Keep read-only and read/write access distinct through preopens and the
portal. Confinement uses descriptor-relative or equivalent kernel-enforced
operations; lexical prefix checks and `canonicalize()` followed by reopening
are not sufficient against symlinks and replacement races.
- Fetch needs explicit schemes, destinations, methods, deadlines, size limits
and redirect authorization; keep HTTP errors distinct from transport errors.
- Keep one canonical WIT source with a checked synchronization mechanism for its
copies.
- Do not describe the seccomp blocklist or process separation as complete
confinement.
## Evidence
`python .agents/scripts/verify.py portable runtime` covers the stub and the
engine-enabled build, lints and unit tests. It does not instantiate a component.
Host import behavior needs an actual component fixture for the allowed, denied
and failure paths of each import; confinement needs traversal, symlink and
race cases against the real portal and preopens. No profile or CI job compiles
the `seccomp` feature; check it on Linux with
`cargo clippy -p weft-runtime --features wasmtime-runtime,seccomp --all-targets --locked -- -D warnings`
and prove filtering with a component or process fixture, not by compilation.
Rebuild demo components with the `demos` profile when the WIT changes.

View file

@ -0,0 +1,72 @@
---
name: weft-servo-rendering
description: Use for the Servo embedders, painting and presentation, the Servo fork and Stylo overrides, the system UI and application pages.
---
# Servo rendering and the forks
Owners: `weft-servo-shell` renders trusted system chrome; `weft-app-shell`
renders one untrusted application document and its narrow bridge. Neither holds
session lifecycle. Read the blueprint's
[Servo host contract](../../../BLUEPRINT.md#71-servo-host-contract),
[system interface](../../../BLUEPRINT.md#8-system-interface-and-application-behavior)
and [build policy](../../../BLUEPRINT.md#101-one-reproducible-product-build).
## Where things live
| Concern | Source |
|---|---|
| System shell host and event loop | [weft-servo-shell embedder](../../../crates/weft-servo-shell/src/embedder.rs), [main.rs](../../../crates/weft-servo-shell/src/main.rs) |
| Application host, `resolve_weft_app_url` (app ID and `ui.entry` to a `file://` URL), injected bridge | [weft-app-shell embedder](../../../crates/weft-app-shell/src/embedder.rs), [main.rs](../../../crates/weft-app-shell/src/main.rs) |
| Key mapping | [servo-shell keyutils](../../../crates/weft-servo-shell/src/keyutils.rs), [app-shell keyutils](../../../crates/weft-app-shell/src/keyutils.rs) |
| Shell protocol clients | [servo-shell client](../../../crates/weft-servo-shell/src/shell_client.rs), [app-shell client](../../../crates/weft-app-shell/src/shell_client.rs) |
| System UI page and UI kit | [system-ui.html](../../../infra/shell/system-ui.html), [weft-ui-kit.js](../../../infra/shell/weft-ui-kit.js) |
| Pin notes (not authoritative for the selected revision) | [SERVO_PIN.md](../../../crates/weft-servo-shell/SERVO_PIN.md) |
## Selected revisions
The Servo and Stylo revisions are the ones `Cargo.lock` records for the `servo`
and `stylo` packages, not a branch name or `SERVO_PIN.md`. Servo comes from the
`marcoallegretti/servo` fork; Stylo currently comes from upstream `servo/stylo`,
because no root-level override selects the `marcoallegretti/stylo` fork. Inspect
them with:
```sh
grep -A2 'name = "servo"' Cargo.lock
grep -A2 'name = "stylo"' Cargo.lock
```
Read the `servo` crate (`components/servo`), shared embedder input types and
rendering contexts at that revision before using an API. Servo's own `[patch]`
tables do not apply to WEFT: a Stylo override that a Servo-fork feature depends
on must be declared in WEFT's root `Cargo.toml` and confirmed in the resolved
graph. Each fork patch keeps a purpose, upstream status and removal condition.
For cross-repository work, clone the forks next to WEFT and point Cargo at them
with local `[patch]` entries outside the repository. Those overrides rewrite
`Cargo.lock`; never commit that change, and rerun checks without the overrides
before reporting evidence for the committed graph.
## Working rules
- A frame exists only after `WebView::paint` and the backend's present
operation. Event-loop progress, a READY message or a softbuffer present of an
unpainted buffer is not a rendered frame. Readback follows painting.
- Handle zero-size and minimized windows, resize, output scale, first frame,
idle wakeup and shutdown without continuous unbounded repainting.
- Keep the trust distinction: system-control endpoints and credentials never
reach application documents. Policy for package resources, navigation,
downloads, file URLs and network requests is enforced in the engine or OS, not
in page JavaScript.
- Treat manifest names, descriptions and icons as untrusted in the launcher; no
unsafe HTML injection. Use one endpoint configuration and bridge.
- Extract common host, render and input code only after one working path exists
in both hosts.
## Evidence
`python .agents/scripts/verify.py servo-embed` type-checks both hosts with the
real renderer. Without `servo-embed` the shells build as stubs; their success is
not rendering evidence. Rendering, input and backdrop or transparency claims need
the deterministic page and pixel checks described in
[integration verification](../weft-integration-verification/SKILL.md).

63
.github/ISSUE_TEMPLATE/change.yml vendored Normal file
View file

@ -0,0 +1,63 @@
name: Defect or change
description: Report a concrete defect or propose an ordinary change within accepted architecture.
body:
- type: markdown
attributes:
value: |
Use a title that states the defect or the behavior that should hold. Search existing issues
and pull requests first. Use the Decision form for a material change of product direction,
public compatibility, trust boundaries, support scope or data policy.
- type: textarea
id: observed
attributes:
label: Observed
description: What happens now, and who or what is affected (user journey, caller, contract, test harness, contributor).
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected
description: What should hold instead. Cite the implemented contract or the BLUEPRINT.md section, and say which one applies.
validations:
required: true
- type: textarea
id: evidence
attributes:
label: Evidence
description: Commit, environment (host, compositor backend, GPU or VM), enabled features, exact reproduction steps and actual output, with file and line references.
validations:
required: true
- type: textarea
id: owner
attributes:
label: Owner and boundary
description: The owning component (compositor, servo-shell, app-shell, appd, runtime, package tooling, portal, deployment) and any public contract touched (wapp.toml, WIT, shell protocol, IPC types).
validations:
required: true
- type: textarea
id: impact
attributes:
label: Why it matters now
description: The concrete present impact. A hypothetical future need or a stylistic preference is not enough.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criterion
description: One independently checkable condition that resolves this issue. Keep unrelated work out of scope.
validations:
required: true
- type: textarea
id: proof
attributes:
label: Expected proof
description: The test, component or integration fixture, pixel check or measurement that fails today and will pass afterwards, and the environment it needs. Compilation and mocks do not prove rendering, input, isolation or persistence.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope and related work
description: Related issues, pull requests or blueprint findings, and explicit non-goals.

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View file

@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Contribution guide
url: https://github.com/marcoallegretti/WEFT_OS/blob/main/CONTRIBUTING.md
about: Read the contribution workflow, ownership and validation guidance before opening an issue or pull request.

58
.github/ISSUE_TEMPLATE/decision.yml vendored Normal file
View file

@ -0,0 +1,58 @@
name: Decision
description: Request a maintainer decision on a material change of direction, compatibility, trust boundaries, support scope or data policy.
body:
- type: markdown
attributes:
value: |
This form requests a decision before implementation; opening it does not approve the change.
Ordinary implementation of an accepted BLUEPRINT.md boundary does not need this form.
Search existing decisions and issues first.
- type: textarea
id: observed
attributes:
label: Observed
description: The current problem and the concrete affected user, caller or contract.
validations:
required: true
- type: textarea
id: direction
attributes:
label: Accepted direction affected
description: The BLUEPRINT.md section, public contract or support promise this would change, and how.
validations:
required: true
- type: textarea
id: evidence
attributes:
label: Evidence
description: Commit, source references, executed checks and the selected dependency revisions that establish the problem. Separate verified facts from assumptions.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and trade-offs
description: Viable options including keeping the current direction, with their costs for ownership, security, data, compatibility and schedule.
validations:
required: true
- type: textarea
id: decision
attributes:
label: Decision requested
description: The specific decision needed and the work it unblocks. Independent authorized work continues meanwhile.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criterion
description: The independently evaluable outcome an accepted option must satisfy.
validations:
required: true
- type: textarea
id: proof
attributes:
label: Expected proof
description: The fixtures, measurements or integration evidence that will show the chosen option works.
validations:
required: true

58
.github/ISSUE_TEMPLATE/maintenance.yml vendored Normal file
View file

@ -0,0 +1,58 @@
name: Maintenance
description: Report one present ownership, boundary, enforcement or structural problem that is independent of active development.
body:
- type: markdown
attributes:
value: |
Search existing issues and pull requests for the same underlying problem first. Maintenance
preserves accepted behavior, public contracts and ownership; use the Decision form if
resolving the problem changes them. One problem maps to one branch and one pull request.
- type: textarea
id: observed
attributes:
label: Observed
description: One concrete problem (responsibility held by the wrong owner, authority taken from untrusted input, a grant declared but not enforced, a duplicated decision, unnecessary state, a misleading fallback, coupling or an obsolete path) and who or what it affects today.
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected
description: The intended structure and the behavior, contracts and ownership that must stay unchanged.
validations:
required: true
- type: textarea
id: evidence
attributes:
label: Evidence
description: Commit and file and line references that demonstrate the problem and its present cost.
validations:
required: true
- type: textarea
id: owner
attributes:
label: Owner and boundary
description: The owning component and why the problem can be resolved without a decision of direction.
validations:
required: true
- type: textarea
id: impact
attributes:
label: Why it matters now
description: The observable present cost. Generic cleanup wishes and speculative abstractions do not qualify.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criterion
description: One independently verifiable outcome.
validations:
required: true
- type: textarea
id: proof
attributes:
label: Expected proof
description: The checks or fixtures that show the problem is resolved and the accepted behavior is preserved.
validations:
required: true

29
.github/pull_request_template.md vendored Normal file
View file

@ -0,0 +1,29 @@
## Problem and scope
<!-- The concrete problem and its present impact. Link the issue (Closes #...) or the accepted scope. For a material change of direction, link the decision that approved it. -->
## What changed
<!-- The resulting behavior or structure, for a reader without access to your working notes. State relevant exclusions. -->
## Ownership
<!-- The owning component and the public contracts touched (wapp.toml, WIT, shell protocol, IPC types, package format). Explain how ownership and compatibility are preserved, or how an approved change keeps them coherent. -->
## What proves it
<!-- The test, component fixture, integration fixture, pixel check or measurement that fails without this change and passes with it. Explain any changed expectation, fixture or signature. Compilation and mocks do not prove rendering, native input, isolation or persistence. -->
## Validation performed
<!-- Actual commands and results, e.g. python .agents/scripts/verify.py portable linux. Name the environment for integration evidence (backend, GPU or virtual device, VM). List checks not run and why. -->
## Manual verification
<!-- What automation cannot establish, the environment and scenario used, and the observed result. If none is needed, say why automated evidence covers the scope. -->
## Limitations and related issues
<!-- Limitations that affect evaluation or use. Link separately actionable problems as issues; do not store future work here or leave a supported path knowingly incomplete. -->
<!-- Keep this text about the project problem, change and evidence. No model or provider attribution, co-author or generated-by trailers, reviewer counts or personas, prompts or process narration. -->

View file

@ -7,15 +7,9 @@ on:
pull_request:
jobs:
# Crates that must compile on every supported host platform.
cross-platform:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- windows-latest
# Crates that build without Wayland or other Linux system libraries.
portable:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
@ -24,14 +18,14 @@ jobs:
components: rustfmt, clippy
- name: cargo fmt
run: cargo fmt --all --check
- name: cargo clippy (cross-platform crates)
- name: cargo clippy (portable crates)
run: >
cargo clippy --workspace
--exclude weft-compositor
--exclude weft-servo-shell
--exclude weft-app-shell
--all-targets -- -D warnings
- name: cargo test (cross-platform crates)
- name: cargo test (portable crates)
run: >
cargo test --workspace
--exclude weft-compositor
@ -78,6 +72,30 @@ jobs:
-p weft-servo-shell
-p weft-app-shell
# weft-runtime with its Wasm engine and fetch support, exercised on a real
# component under each kind of capability grant.
runtime-grants:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: 1.93.0
components: clippy
targets: wasm32-wasip2
- name: cargo clippy (weft-runtime with wasmtime-runtime and net-fetch)
run: >
cargo clippy
-p weft-runtime
--features wasmtime-runtime,net-fetch
--all-targets -- -D warnings
- name: cargo build (weft-runtime with wasmtime-runtime and net-fetch)
run: cargo build -p weft-runtime --features wasmtime-runtime,net-fetch
- name: cargo test (weft-runtime with wasmtime-runtime and net-fetch)
run: cargo test -p weft-runtime --features wasmtime-runtime,net-fetch
- name: grants check
run: python3 -B tests/runtime/check_grants.py
# Type-check the servo-embed feature gate.
# Full Servo compilation (30-60 min) is not run in CI; this job checks
# that the feature-gated code at least type-checks against the declared deps.
@ -111,3 +129,16 @@ jobs:
cargo check
-p weft-app-shell
--features servo-embed
# Contributor contract, toolkit documents and verification runner.
contributor-toolkit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: install toolkit check dependencies
run: python -m pip install -r .agents/scripts/requirements.txt
- name: check contributor toolkit
run: python .agents/scripts/verify.py toolkit

3
.gitignore vendored
View file

@ -1,4 +1,5 @@
/target/
__pycache__/
/.windsurf/
/docu_dev/
@ -6,3 +7,5 @@
/infra/vm/*.qcow2
Thumbs.db
/tests/components/*/target/
/examples/*/target/

368
AGENTS.md Normal file
View file

@ -0,0 +1,368 @@
# WEFT OS engineering contract
This is the single engineering contract for everyone who changes WEFT OS:
maintainers and external contributors. It governs scope, evidence, review, validation, branches and publication.
[`.agents/`](.agents/README.md) contains linked procedures, review roles, area
knowledge and a verification runner. Those files help apply this contract. They
do not define competing policy, grant permissions, schedule work, change the
active working mode or add approval steps. Local tool configuration may point
here; it must not restate, weaken or reinterpret these rules.
## 1. Sources of truth
| Question | Authority |
|---|---|
| Accepted product direction, ownership, support scope and completion criteria | [BLUEPRINT.md](BLUEPRINT.md) |
| Implemented behavior | Source code and the checks that actually executed against it |
| Public contracts | Package manifests (`wapp.toml`), [WIT](crates/weft-runtime/wit/weft-app.wit), the [shell protocol](protocol/weft-shell-unstable-v1.xml), [IPC types](crates/weft-ipc-types/src/lib.rs) and the versioned specifications that replace them |
| Selected dependency APIs | [Cargo.lock](Cargo.lock) and the demo lockfiles, at the exact selected revisions |
| Engineering process | This file |
The blueprint describes where WEFT is going. It is not evidence that a behavior
exists. Code that resembles a blueprint requirement does not satisfy it until
the requirement's acceptance evidence passes. Existing documentation, pin files
and version labels cannot establish behavior on their own; where they disagree
with source or executed checks, the documentation is wrong and needs correcting.
Before changing a public contract, inspect existing compatibility promises and
callers. Preserve compatibility deliberately or provide a tested conversion or
error path.
When evidence contradicts the blueprint, preserve its intent, establish why the
discrepancy exists and choose the maintainable evidence-backed solution. A
material change of direction follows [section 9](#9-decisions-and-authority).
## 2. Evidence
Never invent an API, protocol behavior, platform guarantee, capability or
measurement. Verify uncertain assumptions against the selected dependency
revision before relying on them: read the source of the crate version recorded
in the lockfile (Servo, Stylo, Smithay, Wasmtime, wasmtime-wasi, Tokio, winit,
surfman and others), not current upstream documentation or memory. Record the
revision used when the result matters to the change.
Research order: repository contracts and evidence, selected dependency source,
upstream documentation for that version, relevant standards or protocols,
comparable mature implementations, then a measured experiment.
The blueprint's [evidence levels](BLUEPRINT.md#111-evidence-levels) define what
each kind of check can establish. In particular:
- Compilation, type-checking and clippy prove that code builds, not that it
renders, routes input, isolates, persists or recovers.
- Mocked sockets, DOMs, processes or compositors prove the logic exercised
against the mock, not the real boundary.
- A capability string in a manifest, a host function registration or a
frontend check does not prove enforcement.
- A success log line, `READY` message or exit code `0` from a feature-disabled
build does not prove readiness of the product path.
- A skipped check, missing environment or unavailable device is an incomplete
gate, never a pass.
Record the commit, environment, enabled features, exact command or harness,
result and useful diagnostics for evidence other contributors will rely on.
Distinguish tests that executed from tests that were only designed.
## 3. Ownership
Every change has an owner from the
[blueprint ownership table](BLUEPRINT.md#4-architecture-and-ownership). Identify
it before implementation. Do not let a component implicitly acquire
responsibility that belongs elsewhere:
- `weft-compositor` owns surfaces, geometry, focus, stacking, input routing and
presentation.
- `weft-appd` owns package selection, effective grants, session identity, child
supervision, readiness and cleanup.
- `weft-runtime` owns component instantiation and enforced host calls.
- `weft-servo-shell` and `weft-app-shell` render; they hold no second copy of
session lifecycle and no authority the session did not grant.
- Package tooling owns validation, content identity, trust, staging and
activation; it does not own user data.
Keep the UI and Wasm runtime in separate processes. Share code where behavior is
actually common, without merging privileges or failure domains. Do not replace
the compositor, browser engine or runtime as a shortcut around finishing their
contracts. Introduce a shared crate or abstraction only when it removes present
duplication or establishes a single source of truth.
## 4. Working modes
The modes below do not mix silently. Loading an `.agents/` file never switches
mode.
**Primary development** advances the blueprint under maintainer direction. A
goal may span many consecutive changes. At the start of a new goal, read the
blueprint and inspect the relevant source, manifests, tests, CI, lockfiles,
pins and Git state. Afterwards, reinspect the changed boundary and new evidence
for each step instead of repeating full discovery. Continue autonomously through
successive accepted changes while authorized independent work remains; do not
stop after a single patch or pull request. Fix related debt inside the active
acceptance criterion.
**Contribution** carries one issue or explicitly accepted scope through an
isolated branch to a pull request.
**Maintenance** handles exactly one qualifying problem that is unrelated to the
active goal, under [section 8](#8-maintenance). It never modifies the active
development checkout.
## 5. Reviewed change loop
Apply this loop to every workflow: primary development, fixes, simplification,
refactoring, dependency changes, build and packaging, documentation, governance
and release preparation.
1. **Inspect** current evidence and the implemented and accepted contract.
2. **State** the present problem, owner, bounded scope, observable acceptance
criterion and the proof that will show it.
3. **Review scope** — ownership, proof and design — before changing the affected
boundary.
4. **Implement** one coherent result, preserving unrelated work.
5. **Validate** with the smallest sufficient checks for the changed behavior and
its concrete risks.
6. **Review the actual diff** against acceptance, compatibility, security, data
and failure behavior.
7. **Correct** findings, revalidate and review the corrected content.
8. **Accept** an atomic result only when no blocking finding remains, then
**reassess** the next dependent step from the new repository state.
Do not stop after planning when implementation and verification are possible.
Do not advance dependent work while a blocking finding is open.
## 6. Proof before implementation
Identify what proves a change before or alongside implementing it. For a defect,
reproduce the failure first. For new behavior, establish the fixture, contract
case or invariant that will fail when the behavior is wrong. Proof must fail
when the promised behavior breaks; a test that restates the implementation or
only inspects a success log is not proof.
| Change | Expected proof |
|---|---|
| Parser, serialization, state machine | Unit or contract tests with accepting and rejecting cases |
| Host import or capability | Actual component fixture: allowed, denied and failure paths |
| IPC or session protocol | Integration test over the real transport: framing, authorization, limits, cancellation |
| Session lifecycle | Child-process fixtures for each start, failure, cancellation and teardown path, checking owned resources settle |
| Rendering or presentation | Deterministic page with known pixels on the supported backend; readback after paint |
| Input or window management | Native input and geometry on a real compositor backend |
| Filesystem confinement | Traversal, symlink and replacement-race cases against the real implementation |
| Package trust, install or update | Tamper, interruption and data-retention fixtures |
| Installed system | Built and booted reference image |
| Dependency change | Resolved graph inspection plus the checks of every affected boundary |
| Performance claim | Repeatable measurement on the named target |
| Documentation or toolkit | Claims checked against source; links, catalog and metadata checks |
A change without an identifiable proof surface is not ready unless the
limitation is intrinsic and stated in the result. Never update expected output,
re-sign fixtures or regenerate artifacts merely to turn a failing check green;
explain the contractual reason for every changed expectation.
## 7. Definition of done
A change is done when its contract is coherent and evidenced, not when it
compiles.
- No synthetic success: feature-disabled builds, stubs and fallbacks must not
report readiness, success or enforcement they do not provide.
- No silent no-ops for unsupported operations; fail explicitly with a useful
diagnostic.
- No product UI or documentation that promises unavailable behavior.
- No placeholder paths left knowingly incomplete in a supported product path.
- Security and data preservation are part of the first implementation, not a
later hardening stage.
- Accessibility, keyboard operation, scaling and declared keyboard layouts are
product requirements where the change touches them.
Prefer small explicit APIs, deletion over new abstraction and existing concepts
over new ones. Add a dependency only for concrete value.
## 8. Maintenance
Maintenance work never rides inside an unrelated development branch and never
switches or edits the active development checkout.
An issue is justified only when all of these hold: a concrete affected user,
caller, contract, test harness or contributor can be named; repository evidence
demonstrates the problem; it matters in the current state; and it has an
independently verifiable acceptance criterion. Stylistic preferences,
hypothetical future needs and generic cleanup wishes do not qualify. Search for
an existing issue or pull request first and update it instead of duplicating.
One maintenance run handles one qualifying problem:
1. Verify the current default branch (`main`) by fetching it. If freshness
cannot be verified, state the actual revision and the limitation.
2. Create one isolated worktree and one descriptive branch from it.
3. Follow the [reviewed loop](#5-reviewed-change-loop) to one reviewed pull
request, or to a prepared local result when publication is not authorized.
4. Stop. Do not continue collecting opportunities.
The maintenance roles in [`.agents/agents/`](.agents/README.md#roles) apply this
section:
- **Architecture debt scout** inspects and reports the strongest justified
issue. It edits no repository files and creates no implementation branches or
commits. It may prepare or publish that issue only within granted authority.
When nothing meets the threshold, it says so and stops.
- **Continuous simplicity** removes duplicated decisions, unnecessary state and
misleading fallback paths without changing accepted behavior.
- **Continuous refactoring** changes internal structure while preserving accepted
behavior, ownership and proof.
Neither simplification nor refactoring is a license for repeated architecture
replacement or line-count optimization at the expense of explicit authority,
errors or useful tests. If a maintenance change turns out to need a decision
under [section 9](#9-decisions-and-authority), stop it and record the decision
needed.
## 9. Decisions and authority
Make ordinary engineering decisions within accepted architecture without asking.
Decisions already accepted in the blueprint and authorization already granted
remain effective; do not request them again.
Seek a maintainer decision only for a material departure from accepted product
direction, public compatibility promises, trust boundaries, support scope or
destructive data policy, or when required authority is missing. Prepare the
problem, evidence, alternatives and trade-offs first, and continue independent
authorized work meanwhile. Do not disguise a change of direction as cleanup or
an implementation detail.
Publication, merge, release and deployment follow the authority actually
granted for them. A successful review, green CI or a passing hook grants none of
them by itself. Preserve branch protections, existing branches, other
contributors' work and unrelated working-tree changes.
## 10. Review
Review the actual change: a staged and unstaged diff, or an explicit
`git diff <base> <head>` range. An empty `git diff HEAD` after committing is not
a review of the committed change. Recheck material corrections, rebases and
conflict resolutions before integration, and review the final aggregate change
for cross-step effects before a pull request or release candidate.
Prefer a reviewer who did not author the change. When none is available, use a
fresh, separate critical pass and state that limitation honestly. Never present
self-review as independent review.
A **blocking** finding concerns correctness, promised behavior, trust, data
preservation, compatibility, accepted scope or required evidence. Fix it before
dependent work advances. An unrelated improvement goes to separately scoped
maintenance. Preferences are not blockers and findings are not a quota.
[Reviewer](.agents/agents/reviewer.md) describes the review procedure.
## 11. Validation
Run the smallest sufficient set for the change and expand it for a concrete
affected boundary, regression risk or release gate. Do not repeatedly run
unrelated expensive suites once the remaining risk is resolved, and never weaken,
skip or re-bless a required check to make it pass.
The [verification runner](.agents/scripts/verify.py) runs the repository's
actual check profiles; [verify](.agents/commands/verify.md) maps changes to
profiles and to evidence the runner cannot provide. [CI](.github/workflows/ci.yml)
remains the integration gate. Demo applications are separate workspaces; root
workspace tests do not cover them. Feature-disabled builds cannot stand in for
the `servo-embed` or `wasmtime-runtime` product paths.
## 12. Dependencies and forks
Servo is consumed from the `marcoallegretti/servo` fork (`servo-weft` branch).
Stylo currently resolves to upstream `servo/stylo`; the `marcoallegretti/stylo`
fork applies to WEFT only once a root-level override selects it and the resolved
graph confirms it. The selected revisions are those in `Cargo.lock`, not
`SERVO_PIN.md` or a branch name.
- Apply required Cargo overrides at the consuming workspace root. A dependency's
own `[patch]` table does not apply transitively. Inspect the resolved graph and
verify each claimed fix on the selected code.
- Keep a purpose, upstream status and removal condition for every retained fork
patch.
- Local path overrides used for cross-repository development change the resolved
graph. Do not commit the lockfile changes they cause and do not present
results from them as evidence for the committed graph.
- A dependency update needs scope, compatibility evidence, relevant security
review and the same reviewed loop as product code.
- Never fabricate `pkg-config` metadata, native library versions or readiness
messages to make a build pass. Repair the supported environment or exclude
the unsupported feature explicitly.
- Do not copy machine-specific usernames or checkout paths into documented
workflows.
## 13. Versions and releases
Follow the blueprint's [version progression](BLUEPRINT.md#121-version-progression):
scoped `0.0.x` releases toward stable `0.1.0`, each moving through
`alpha.N -> beta.N -> rc.N -> final`, where final is the plain version without
a `-final` suffix. Assign the next `0.0.x` to an accepted
milestone scope after inspecting existing tags and published releases. Reconcile
the unreleased workspace value `0.1.0` deliberately.
Promotion is an explicit evidence-based decision under release authority. No
label, test count, absence of bug reports or successful build promotes a
candidate automatically. A release candidate requires the complete evidence for
its scope and an independent technical review of that exact candidate; an
unavailable required reviewer leaves the gate pending. Corrections after
candidate approval invalidate the affected evidence. Never rewrite or move
published tags or releases. Publish the artifact that was tested.
## 14. Branches, commits and publication
Branch from the verified current `main` unless the work depends on another
unmerged branch; then say so. Name every branch after the concrete change,
with a type prefix:
```text
fix/authorize-session-messages
refactor/share-servo-frame-loop
feat/keyboard-app-switching
build/enable-servo-vm-packages
test/reject-portal-symlink-escapes
docs/add-weft-contribution-contract
```
Reject task numbers, lane, phase or role labels, model or provider names and
generic names such as `maintenance`, `stability` or `cleanup`. Link the issue
from the pull request instead of naming the branch after it.
Commits are atomic, focused and revertible. Before committing, inspect
`git status` and the complete diff, and confirm no generated, transient or
local-environment files are included. Keep subjects short and technical; add a
body when it explains the problem, resulting behavior or evidence.
Branch names, commit messages, issues, pull requests, review comments and
release notes are written for maintainers: the concrete problem, the resulting
behavior, the affected boundaries and the validation actually performed. Do not
include model or provider attribution, co-author or generated-by trailers,
reviewer counts or personas, prompts, internal role handoffs or process
narration. A technical validation section with real commands and results is
useful.
Reusable governance files, the adopted blueprint and protocol or product
documentation are intentional tracked artifacts. Temporary plans, transcripts,
review notes, scratch output and internal progress reports stay out of Git.
A decision that exists only in a conversation does not exist for the project:
record durable decisions in the owning public artifact.
Before an action that can trigger automated public review or publication,
inspect the repository's integrations. Do not knowingly trigger publication that
conflicts with this section or bypass a required protection to avoid it.
## 15. Code
Follow the workspace configuration: edition 2024, the pinned toolchain in
[`rust-toolchain.toml`](rust-toolchain.toml) and `unsafe_code = "forbid"` where
crates inherit workspace lints. Keep `cargo fmt` and `clippy -D warnings`
clean. Do not silence a diagnostic without understanding its cause.
Product, helper and privileged subprocesses use exact executable paths and
argument arrays. Bound queues, frames, payloads and operation lifetimes. Keep
secrets, application payloads, clipboard contents and saved user data out of
default logs.
Prefer self-explanatory names and structure. Comment non-obvious invariants,
protocol constraints and safety reasoning; avoid narrative comments. Remove dead
code instead of commenting it out.

657
BLUEPRINT.md Normal file
View file

@ -0,0 +1,657 @@
# WEFT OS — Stability Blueprint
**Target:** a usable, supportable `0.1.0` Linux desktop and application environment.
**Baseline inspected:** WEFT `b99cc73a4704615521c38ca84dc46dc1bd641bc6` (`main`, 13 March 2026).
**Contributor reference inspected:** Resina Design System `1e768064f57a1e403ab271822383e732795905a6` (`master`, 8 October 2026).
**Prepared:** 8 October 2026.
**Status:** source-verified development specification. The requirements below are the proposed completion contract; they are not a certification that the current implementation satisfies them.
## 1. Purpose and authority
WEFT is a Linux desktop in which Servo renders the system interface and application interfaces, Smithay manages Wayland presentation and input, Wasmtime executes application components, and `weft-appd` supervises their sessions. Applications combine a web interface with a separate Wasm component. A package manifest declares their identity, entries and requested host capabilities. This blueprint preserves that product model and completes its missing boundaries. [Existing architecture][architecture] [Workspace][workspace]
The intended user outcome is concrete: boot into the desktop, discover installed applications, launch and use them, switch and close them, preserve their data, install updates, and recover from a failed application without losing control of the desktop.
When this blueprint is adopted:
- `AGENTS.md` is the single engineering policy. It governs scope, validation, review, contribution and publication.
- This blueprint defines the accepted product direction, ownership, support scope and completion criteria.
- Versioned manifest, IPC, WIT and packaging specifications define public contracts. Existing compatibility promises must be inspected before changing them; this document does not silently erase them.
- Source and executed checks establish implemented behavior. Documentation and version labels cannot establish behavior independently.
- `.agents/` provides linked procedures and area knowledge. Reading a guide does not change the active task, grant authority, schedule maintenance or introduce a new approval requirement.
Reconcile any earlier local blueprint before implementation. Historical repository documentation referred to `docu_dev/WEFT-OS-COMPREHENSIVE-BLUEPRINT.md`, but its contents were not available in the inspected tracked tree. Do not claim to have incorporated unseen requirements. Preserve compatible decisions, identify material contradictions and prepare a concrete decision only where the accepted direction actually changes. [Historical baseline][historical-baseline]
This is durable product documentation and can be tracked in the repository when adopted. Temporary investigation notes, execution transcripts, review scratch files and progress reports are not product documentation.
## 2. Meaning of stable
### 2.1 Required release profile
Stable `0.1.0` means the complete supported path works on a named reference environment. It does not imply compatibility with every architecture, GPU, Linux distribution or checked-in backend.
| Profile | Status required for `0.1.0` | Scope |
|---|---|---|
| Linux `x86_64` nested session | Required | Real Smithay winit backend, both Servo hosts, Wasmtime, package tooling, session supervisor and reference applications |
| Bootable Linux `x86_64` reference VM | Required | Pinned Nix image, systemd session startup, graphical shell, real application execution, persistent storage, shutdown/reboot and recovery |
| Reference VM graphics | Required | One recorded QEMU/KVM configuration, virtual GPU, renderer path and host requirements; exercise DRM if the image uses it |
| Physical devices | Conditional | Support only devices and configurations present in the executed support matrix |
| Additional CPU architectures or host operating systems | Conditional | Utility compilation alone does not establish desktop support |
| EROFS/dm-verity packages | Conditional | May be supported only after the complete image, identity, privilege and failure-path contract in section 9 passes |
Choose the exact VM machine, graphics device, kernel/Mesa, CPU and memory settings during environment recovery and record them. QEMU with virtio-gpu is a candidate to evaluate, not a compatibility result established by this audit. A headless VM or successful Nix evaluation cannot satisfy graphical acceptance.
During environment recovery, boot a minimal instance of the intended reference VM and present a real compositor diagnostic surface. This checks the selected graphics/seat path early; full installed-product acceptance remains the later reference-image milestone. Continue independent nested fixes while arranging this target check.
The mandatory initial application model is one primary window per session, with explicitly supported dialogs and popups. Closing that primary application window terminates its session. Background execution needs a separate accepted contract and must not emerge from an unobserved runtime process.
Keyboard, mouse, wheel, app switching, resizing, focus and text editing are required. Validate declared US and Italian keyboard configurations. Touch, stylus, complex IME workflows, multi-monitor arrangements, native assistive-technology integration and advanced GPU APIs must not be advertised without corresponding complete fixtures. Features outside the supported profile must be visibly unavailable or clearly documented; they must not silently succeed.
### 2.2 Required user journeys
1. A fresh reference image boots into a usable system interface without terminal repairs or development checkout paths.
2. The launcher lists actual installed packages and exposes truthful launching, running, failed and stopped states.
3. Counter changes state through its real Wasm component and returns that state to its rendered interface.
4. Notes preserves exact text through save, close, reopen, daemon restart, package update and VM reboot.
5. Two applications run together, switch through keyboard and shell controls, receive correct input, and close independently.
6. A failed runtime, renderer, startup or package update produces an actionable error and converges to a recoverable state.
7. Undeclared host operations and forged session messages are denied at the host boundary.
8. A documented developer workflow builds, validates, installs, launches, diagnoses, updates and removes a real application package.
Counter and Notes are conformance applications. Passing their happy paths is necessary but insufficient: permission denial, malformed input, update interruption, process failure and graphical recovery are separate release gates.
## 3. Evidence and current baseline
### 3.1 What was verified
The audit inspected the tracked workspace, demos, manifests, WIT, dependency lockfile, graphics hosts, supervisor, package tools, service/Nix definitions and available CI metadata. The Resina contributor contract and complete `.agents/` tree were inspected at the reference revision above.
Additional bounded checks executed outside the Rust product build:
- The actual injected JavaScript bridge was exercised in Node with a mocked WebSocket; its messages were compared with the daemon's declared request/response shapes.
- The actual Notes frontend was exercised with a mocked DOM and controlled replies, reproducing stale-response replacement of newer edits.
- Both committed demo signatures were verified with Python's Ed25519 implementation against the canonical inventory algorithm in `weft-pack`: both were valid, covering nine files each.
- Temporary filesystem probes demonstrated the symlink behavior and package/data coupling relevant to the inspected path logic. These were source-directed probes, not execution of the Rust portal or installer.
- The current `systemd-run --user --scope --wait ... -- /usr/bin/true` argument combination was rejected with `--wait may not be combined with --scope`. No application service was launched by that check.
The execution environment did not contain Cargo, rustc or Nix. No full Rust compilation, real Servo window, running Wasm application session, DRM session or reference VM was executed during this audit. Those checks remain mandatory work. Passing observations below must not be broadened into unexecuted runtime claims.
### 3.2 Findings that determine the implementation order
| ID | Observed baseline | Consequence and required response |
|---|---|---|
| E01 | The selected Servo revision differs from `SERVO_PIN.md`; both embedders use APIs absent or changed in that revision. [Lockfile][lockfile] [Pin document][servo-pin] [App embedder][app-embedder] [Selected input API][servo-input] [Selected render API][servo-render] | Recover one reproducible dependency graph and compile both real embedding configurations before relying on graphics claims. |
| E02 | Both host frame paths omit `WebView.paint`; the EGL path has no actual presentation. [System embedder][system-embedder] [App embedder][app-embedder] [Servo rendering contract][servo-webview] | Implement paint and present, then verify pixels, wakeups, resize and idle recovery. |
| E03 | The workspace does not apply Servo's dependency-level Stylo patch; the selected upstream property remains gated. [Workspace][workspace] [Lockfile][lockfile] [Servo patch][servo-patch] [Stylo gate][stylo-gate] | Put necessary overrides at the workspace root and verify the selected graph and rendered feature. Parsing or a pin document is insufficient. |
| E04 | Without the runtime feature, `weft-runtime` prints readiness and exits; the feature-disabled app shell prints readiness and parks. The system shell instead reports its missing feature. Nix shell builds omit `servo-embed`. [Runtime][runtime] [App host][app-main] [System host][system-main] [Nix packages][nix-packages] | Separate limited build fixtures from product binaries. Ship and test actual engines; no synthetic success path may satisfy readiness. |
| E05 | The systemd launch path combines `--scope` and `--wait`. [Session implementation][appd-runtime] | Replace it with a valid, tested ownership mechanism that includes all session processes. |
| E06 | The UI bridge sends bare payloads, while the daemon expects tagged requests; replies are also differently wrapped. WebSocket clients enter the common dispatcher and receive common broadcasts without a session-specific authenticated binding. [Bridge][app-embedder] [Daemon messages][appd-ipc] [WebSocket server][appd-ws] | Define a single semantic protocol, separate system control from app messaging, and authorize each connection before repairing demo interaction. |
| E07 | Host imports are registered without applying effective per-session grants. Read-only and writable preopens converge to unrestricted directory/file permissions. The portal checks lexical prefixes before following paths. [Runtime][runtime] [Session preopens][appd-runtime] [Portal][file-portal] | Enforce capabilities at every host entry, preserve access modes and use filesystem confinement that survives symlinks and races. |
| E08 | Appd marks a session running before UI readiness; UI spawn/exit and several early failures do not share complete cleanup. IPC paths contain stale relay and lock/cancellation risks. [Session implementation][appd-runtime] [Daemon lifecycle][appd-main] | Give the session one owner, readiness contract and cleanup path; test every child failure and fragmented/cancelled transport. |
| E09 | Pending PID associations are not consumed; focus/destroy requests only log; toplevels start at the same position; custom geometry requests do not establish effective placement. [Compositor association][compositor-appd] [Compositor state][compositor-state] | Implement authenticated session/surface association and compositor-owned focus, geometry, stacking and destruction. |
| E10 | DRM submission lacks the completion transition, idle/empty-frame scheduling is incomplete, activation only logs, and the DMA-BUF global is not created. Layer rendering exists; layer input hit-testing is incomplete. [DRM backend][drm] [State][compositor-state] [Input][compositor-input] | Complete the selected backend's presentation, recovery and input contract; do not replace already existing layer rendering on a false premise. |
| E11 | Default app data lives under the installed package directory; installation rejects an existing package and removal deletes that tree. [Session data paths][appd-runtime] [Package operations][pack] | Separate user data before an update workflow. Never require uninstalling the old package to update it. |
| E12 | Signing covers the recursively enumerated inventory, including UI assets, while documentation describes only manifest plus Wasm. Installation does not establish trust by invoking signature verification. Both committed signatures are valid under the implemented inventory algorithm. [Package signing/install][pack] [Existing security documentation][security] | Preserve the working cryptographic behavior, define trust policy and enforce it transactionally. Correct the documentation; do not “repair” valid signatures by signing the wrong content. |
| E13 | Image builder and loader disagree on companion filenames; mount failure can fall back to a mutable directory; runtime, UI and capability resolution can use different roots. [Image builder][pack] [Mount loader][mount] [Session resolver][appd-runtime] | Resolve one verified package descriptor and make verified-mode failures fail closed. |
| E14 | Manifest entry paths lack complete confinement, Wasm checking is only a magic-prefix check, and runtime loading ignores the declared module entry. Installation writes directly into its final destination. [Package validation][pack] [Runtime entry][runtime] | Use shared manifest/entry validation, component validation and recoverable staging before activation. |
| E15 | Notes can overwrite newer editor content with a late reply and transforms literal backslash sequences. [Notes UI][notes-ui] [Notes component][notes-runtime] | Use structured serialization, revision-aware replies and atomic persistence with an explicit concurrent-writer policy. |
| E16 | Nix/session configuration omits required features/assets or launch configuration, guesses a Wayland display, and disables VM graphics. [Nix packages][nix-packages] [Nix configuration][nix-config] [Flake][flake] [Service units][services] | Produce and exercise one coherent installed image, with real assets, endpoints and activation. |
At the inspected HEAD, the available GitHub run metadata reported successful portable Ubuntu/Windows jobs and failed Linux-only/Servo jobs. The old detailed logs were unavailable; the audit does not assign a historical CI failure to a particular finding above. Re-run the exact relevant configurations to establish current results. [Recorded CI run][ci-run]
The manifest already declares `0.1.0`; the inspected checkout contained no tags and the release listing was empty. A manifest number is not release qualification. Inventory current remote refs and published artifacts again before assigning versions. [Workspace version][workspace] [Releases][releases]
### 3.3 Questions requiring execution, not assumptions
- Demo components and host WASI dependencies show different WIT patch versions (`0.2.6` and `0.2.3`); Wasmtime's linker has compatible-version behavior. A textual version difference alone does not establish an ABI defect. Instantiate actual components and exercise imports. [Wasmtime linker][wasmtime-linker]
- Validate the fetch response shape against an actual component. Do not report an ABI mismatch from a Rust tuple versus WIT record appearance alone.
- Clipboard and notifications call real external helpers; they are not logging stubs. Their services, permission enforcement and behavior still need integration evidence. [Runtime host functions][runtime]
- The mount helper contains a privileged execution path, but the inspected Nix image does not establish a functioning setuid deployment. Review and test privilege before enabling it; do not describe a hypothetical deployed privilege escalation as an observed VM exploit. [Mount helper][mount-helper] [Nix packages][nix-packages]
- No performance, battery, hardware compatibility or accessibility-service result was established by the audit.
## 4. Architecture and ownership
| Owner | Authoritative responsibility | Must not own implicitly |
|---|---|---|
| Linux and systemd | Seat/session substrate, service lifecycle and enforced process/resource boundaries | Product session identity inferred from arbitrary child output |
| `weft-compositor` | Surface ownership, geometry, focus, stacking, work areas, input routing and presentation | Application data, package trust or unvalidated shell privilege |
| `weft-servo-shell` | System chrome, launcher, navigation and user-visible session controls | A second authoritative copy of app/session lifecycle |
| `weft-appd` | Resolved package selection, grants, session identity, child supervision, readiness and cleanup | Unbounded global application broadcasts or frontend-supplied authority |
| `weft-runtime` | Component instantiation, WIT host calls and enforced WASI resource access | Package selection independent of appd or unrestricted ambient imports |
| `weft-app-shell` | One application's document, rendering and narrow session bridge | System-control credentials, another app's data or privileged shell roles |
| Package tooling/store | Manifest validation, content identity, trust, staging, activation and retention | User data lifecycle coupled to installed bytes |
| Portals/host services | Operations on explicitly granted resources | A second, weaker permission model |
Keep the UI and Wasm runtime in separate processes. Share code where behavior is actually common, without merging their privileges or failure domains. Do not replace the compositor or browser engine as a shortcut around finishing their contracts.
### 4.1 One resolved package descriptor
Before spawning children, appd must resolve and validate one immutable launch descriptor:
| Field | Required meaning |
|---|---|
| Package identity | Validated application ID, package version and immutable content identity |
| Package root | Exact validated root of that selected revision |
| Runtime entry | Contained, validated `[runtime].module` |
| UI entry | Contained, validated `[ui].entry` from the same revision |
| Effective grants | Manifest requests intersected with explicit host/user policy |
| Data root | Persistent application storage independent of package bytes |
| Session identity | Opaque session ID plus generation/epoch sufficient to reject stale references |
| Owned resources | Supervisor-controlled handles/endpoints required by the chosen launch path |
Runtime, app shell, portals and compositor registration must derive from this descriptor. Do not independently rediscover package roots, parse a different manifest or infer identity from a title/PID. An active session remains pinned to its selected revision across package updates.
Implement one manifest parser and resolution contract at the narrow shared boundary where required. A new shared crate is justified only when it removes actual duplication; the crate structure itself is not a release goal.
### 4.2 Manifest and component compatibility
Specify schema version, identifier rules, required entries, supported capability syntax and unknown-field/version behavior. Preserve existing manifest compatibility deliberately or provide a tested conversion/error path. Validate entry containment, file kinds, link policy and package identity before execution.
Validate an actual WebAssembly component and the required world/imports/exports using the selected toolchain; four magic bytes do not establish compatibility. Maintain one canonical WIT source and generated bindings or a checked synchronization mechanism. Each supported host import needs an actual component fixture proving its ABI, allowed behavior, denial and error handling.
## 5. Security and capability contract
### 5.1 Threat model
Treat both packaged web content and the Wasm component as untrusted application code. They must not read another app's data, obtain undeclared host operations, issue system lifecycle commands, impersonate another session or assign themselves privileged surface roles.
Treat the compositor, supervisor, installed package resolver, host policy and trusted system shell as the control boundary. Bootstrap authority must come from a trusted channel and observed peer identity, not from application-provided metadata.
The initial product does not promise protection from an arbitrary hostile native process already running as the same host user or an administrator who modifies the installation. State that scope explicitly. It does not excuse unsafe privileged helpers, application-facing host APIs or package code escaping the declared resource boundary. Do not claim that separate processes or a syscall blocklist alone provide complete confinement.
The renderer must obey the same declared authority as its component. Define policy for package resources, external navigation, downloads, local file URLs, network requests and subprocess/service access. Enforcement must exist at the engine or operating-system boundary; frontend JavaScript checks are insufficient. If the selected Servo build cannot enforce a required boundary, complete an effective containment mechanism or narrow the supported content policy through an explicit product decision before release. Do not advertise a sandbox that has only been implemented on the Wasm side.
### 5.2 Effective grants
The default is no application access beyond the documented minimal execution resources. The supervisor derives effective grants once, and each host operation checks them. Unknown or unsupported capability requests fail clearly. Installing a signature-valid package does not automatically approve all its permissions.
| Resource | Required behavior |
|---|---|
| Package content | Read-only access to the selected revision; no package path outside it |
| Private app data | App-specific root; read and read/write remain distinct |
| User-selected directories | Actual platform directory resolution and explicit grant; no guessed home subdirectory treated as authority |
| File portal | Same mode/path policy as WASI; operations confined against traversal, symlinks and races |
| Fetch | Explicit supported schemes, destinations/ports, methods and budgets; authorize redirect destinations and define credential forwarding |
| Clipboard | Separate read/write grants, usable platform service, bounded payloads and meaningful errors |
| Notifications | Individual grant, actual delivery path, bounded content and actionable failure |
Filesystem confinement must use descriptor-relative or equivalent kernel-supported operations that enforce the policy during the operation. `canonicalize()` followed by reopening an attacker-controlled path is not sufficient against replacement races. Cover intermediate and final symlinks, `..`, nonexistent write targets and links changed during access. Apply the same constraints to installation, extraction and manifest entry resolution.
Fetch must have explicit connect/overall deadlines, request and response limits, and cancellation behavior. Handle each redirected destination under the grant. Keep HTTP error statuses distinct from transport errors. If domain grants are supported, specify normalization, subdomain matching, ports and the treatment of resolved local/private destinations rather than leaving those decisions to the HTTP library.
No host import, including a convenience helper, may bypass the effective policy. Every compiled and advertised import belongs in the conformance matrix; absent support must not be represented as a successful no-op.
### 5.3 Resource and privilege limits
Apply session ownership and resource limits to the runtime, renderer and helpers together. Bound memory, active processes, queued messages/bytes, in-flight requests, logs, host response sizes and operation lifetimes. Use finite configurable defaults and measure them on the reference target; freeze release budgets before beta. Do not invent measured performance claims.
Before enabling a privileged helper, specify its caller authorization, allowable package identifiers, trusted store roots, output locations, command paths and environment. Use exact executable paths and argument arrays. Reject arbitrary caller-controlled mount sources/destinations. Apply appropriate read-only, `nodev` and `nosuid` policies and prove cleanup after every failure. Privilege must not be enabled merely to bypass a failing development configuration.
## 6. IPC and session lifecycle
### 6.1 Role-separated protocol
System control and application messaging must have separate authority, even if a transport implementation is shared.
| Connection | Authority |
|---|---|
| Trusted system shell/administrative client | Authorized catalog, lifecycle and window operations |
| Application bridge/runtime | Only the operations and private messages of its own authenticated session |
| Diagnostic client | Only the explicitly granted diagnostic/control subset |
Bind role, session and generation on the server. A caller-provided `session_id` is a routing claim, not authentication. Never deliver private payloads to unrelated subscribers. Do not expose a system-control secret inside application content.
Use private local endpoints with appropriate ownership and permissions. A browser-facing WebSocket requires an authenticated session bootstrap with expiry, replay handling and termination behavior. Loopback binding and Origin validation are additional controls; neither substitutes for authorization. Keep credentials out of logs and unintended URLs/referrers, and ensure a reconnect cannot acquire a different session.
Define a versioned semantic envelope with message kind, request correlation, payload, result/error and session generation as appropriate. Native framing and browser serialization may differ, but the bridge and daemon must share these meanings. Publish real request/response examples from the tested contract. App content should use a small bridge API, without rebuilding daemon envelopes or receiving administration messages.
Bound frame size, queued message count, queued bytes and per-connection concurrency. Preserve partial frames across cancellation. Do not hold the session registry lock while awaiting socket/channel work or reacquire it through an error branch. Closed relays must be removed. Detect overflow or missed events and resynchronize from an authoritative snapshot; do not continue with silently stale state. Tokio specifically documents cancellation concerns for `read_line`; choose a framing primitive or buffered decoder with the required behavior. [Tokio I/O contract][tokio-lines]
### 6.2 Single lifecycle owner
Use one session model, with structured terminal reasons:
```mermaid
stateDiagram-v2
[*] --> Starting
Starting --> Running: Required readiness reached
Starting --> Stopping: Failure, timeout or cancellation
Running --> Stopping: Close, exit, crash or shutdown
Stopping --> Stopped: All resources settled
Stopped --> [*]
```
`Running` means the component is initialized, session IPC is connected, the application document and bridge are initialized, and the associated surface has reached the defined first-frame presentation condition. A minimized or temporarily occluded session can remain running; initial readiness and ongoing visibility are different facts.
Readiness must use trusted host signaling. The component's `notify.ready` is one input to the host lifecycle, not authority to bypass UI readiness. Arbitrary stdout text cannot establish readiness. Drain stdout/stderr from process creation onward, independently of lifecycle signals.
Authenticated session bootstrap and the narrowly defined initialization exchange must be permitted while `Starting`. Specify which messages are legal in each lifecycle state. Do not require `Running` to complete an exchange that is itself necessary for readiness. Bound startup traffic and apply the same grants, session binding and cleanup rules as during normal execution.
A user close request must allow the application's declared unsaved-change policy to complete before primary-surface destruction and session teardown. Define cancellation and a bounded response timeout. Once close is accepted, settle the entire session. Explicit force termination, crashes and system-session shutdown have separate documented policies and must not be reported as a successful save. This interaction precedes `Running -> Stopping`; it does not require another independent lifecycle model.
A session owns both children, portal/helper processes, relays, sockets, compositor associations, temporary directories and optional mounts. Every exit path enters the same cleanup mechanism: spawn failure, malformed package, initialization failure, timeout, cancellation, guest trap, child crash, explicit close and daemon shutdown. Do not let renderer failure leave an apparently running invisible application.
Use a valid process-group or systemd mechanism that preserves that ownership. Attempt graceful termination for a bounded interval, then terminate remaining owned processes and await settlement. Do not sleep for an arbitrary duration and assume cleanup finished. Test direct and systemd paths only if both are supported; otherwise remove the unsupported path from product promises.
On daemon failure, use durable/OS-backed ownership to reconcile or terminate owned stale sessions. Do not infer ownership from a recycled PID, a matching directory prefix or an untrusted client claim. The initial policy may restart applications explicitly after cleanup; it does not promise restoration of arbitrary in-memory application state. Prevent restart loops and retain useful terminal reasons.
## 7. Rendering, windowing and input
### 7.1 Servo host contract
Recover the exact selected API first. Implement frame notification, repaint scheduling, `WebView.paint`, backend presentation and meaningful error handling. Event-loop progress alone is not a rendered frame. Readback must follow painting, and EGL requires a real present operation. [Selected Servo contract][servo-webview] [Rendering context][servo-render]
Handle zero-size/minimized windows, resize, output scale, logical/physical coordinates, graphics context lifetime, first frame, waking from idle and shutdown. Keep reusable rendering resources alive where required. Do not hide missing wakeups with continuous unbounded repainting.
Use a deterministic page with known color regions, text, scrolling content, a text field, an interactive counter and controlled animation. Check actual pixels and input results on the supported path. For transparency/backdrop effects, verify the selected dependency graph and rendered behavior; unsupported effects need an honest usable fallback in the UI.
After one working path exists, extract demonstrated common host/render/input behavior from the two embedders. Preserve the distinction between trusted system chrome and an untrusted application document. Do not build a generic engine abstraction without a present requirement.
### 7.2 Surface and window contract
The compositor owns accepted geometry, stacking, focus and work areas. Appd owns session identity. The shell issues requests and renders the resulting state. Bind surfaces through trusted launch/connection evidence and observed client identity, with opaque window/session IDs and generations. PID alone is not durable authority.
Support creation, activation, move/resize under the selected window policy, maximize/restore, close, child dialogs/popups and destruction. Effective Wayland geometry and acknowledged state must agree. Define one coherent relationship with xdg configure/acknowledgement; an echoed custom geometry request does not move a surface.
Establish painting and hit-testing order for background, application work area, panel/navigation, overlays and popups. Define input regions, reserved work areas, parentage, dismissal and focus restoration. Only the trusted shell can acquire privileged roles. A normal opaque toplevel labelled `panel` cannot substitute for that behavior.
A multi-surface shell hosted by one trusted Servo process is a reasonable implementation. A single-document implementation is also acceptable if it proves correct clipping, transparency, ordering and input regions. Choose once based on the selected APIs and a working fixture; keep product ownership unchanged.
### 7.3 Required input and accessibility behavior
Forward key press/release, modifiers, mouse buttons, motion, enter/leave, wheel, focus changes and scale changes correctly. Preserve physical/logical coordinate consistency. Prevent stuck keys/buttons after focus loss, client exit, drag cancellation or output changes. Verify declared keyboard layouts and non-ASCII editing through the real native path.
The system UI requires semantic controls, accessible names, logical keyboard order, visible focus, no keyboard traps, Escape/dismiss behavior and focus return for overlays. Verify theme contrast and reduced-motion behavior. Native screen-reader/AT-SPI support requires an actual accessibility inspector and assistive-technology test with the selected engine; a dependency name or DOM attribute does not establish platform integration.
### 7.4 Backend-specific completion
For the nested backend, verify real surfaces, resizing, input, focus, idle wakeups and application failure recovery. For every release path using DRM, additionally implement and test:
- Completion of queued frames, including the required `frame_submitted()` transition.
- Synchronization and presentation feedback tied to successful presentation.
- Empty-frame and idle scheduling that resumes on input/content commits.
- Render/submission error recovery.
- Session pause and activation.
- The declared output add/remove and mode-change behavior.
- Cursor and DMA-BUF mechanisms actually advertised to clients.
Use the selected Smithay contracts; unsupported globals must not be advertised. [Smithay output contract][smithay-output] [DMA-BUF global contract][smithay-dmabuf]
## 8. System interface and application behavior
The launcher must derive its catalog from validated installed packages. Treat manifest names, descriptions, icons and other metadata as untrusted input; avoid unsafe HTML injection. Use one authoritative endpoint configuration and bridge rather than a second hardcoded WebSocket connection in the page.
Provide launch, activate/switch and close actions, including keyboard access to system navigation. The taskbar must activate applications as well as terminate them. Loading and failure states must correspond to authoritative lifecycle state and explain what the user can do next. Reconnecting the shell must restore a coherent snapshot without duplicate or stale applications.
Show only supported settings and controls. Theme or visual refinement must preserve readable text, focus, error states and performance. Shutdown/reboot must use the supported image's authorized host path. Do not put implementation details, development roles or internal status claims in product UI.
### 8.1 Counter
Counter is the smallest complete proof of application execution. A user action must reach the real component; the component's reply must drive the rendered value. Local JavaScript state cannot stand in for the component. Closing Counter must settle its runtime, renderer, relays and compositor state.
### 8.2 Notes
Notes is the reference for persistent user data. Use a real serialization implementation and preserve Unicode, whitespace, actual newlines and literal backslash sequences exactly. No ad hoc replacement of `\\n` with newline or string concatenation for structured JSON.
Associate load/save replies with the operation and editor revision that produced them. A late response must never overwrite edits made after that operation began. Define an explicit concurrent-writer policy, such as revision-checked writes with a visible conflict, and test it. Do not silently accept lost updates.
Persist through a temporary file and recoverable atomic replacement, with durability semantics appropriate to the filesystem and the acknowledgement promised to the UI. Keep the previous saved copy when writing fails. Acknowledge a save only after the specified persistence operation succeeds. Show unsaved changes and actionable failures; closing must follow a defined unsaved-change policy.
The reference fixture must cover empty text, non-ASCII text, multiple lines, quotes, literal backslashes, delayed load/save responses, a failed write, repeated saves and competing writers. Repeat persistence checks after reinstall/update, app and daemon restart, and VM reboot.
## 9. Packages, trust, storage and updates
### 9.1 Independent storage lifecycles
Use distinct locations and ownership for immutable package revisions, persistent application data, disposable cache and session runtime resources. Resolve platform directories from the supported environment. Do not place writable data beneath content that is signed, removed or replaced during package operations.
A suitable logical layout is:
| Store | Lifecycle |
|---|---|
| Package revisions, keyed by app ID and content identity | Immutable after activation; retained while referenced by sessions or rollback policy |
| App data, keyed by app ID | Persists independently across package updates and ordinary uninstall |
| App cache | Reconstructible; cleanup must not remove user data |
| Session runtime resources | Private, ephemeral and settled by the session owner |
Choose actual XDG/system paths once and use the common resolver. Preserve overrides only where their behavior and authority are explicit. Migrating the existing `apps/<id>/data` layout requires detection, backup/recovery behavior, conflict handling and a test proving existing Notes contents survive. Do not hide data migration inside an unrelated cleanup.
### 9.2 Package identity and trust
Specify canonical inventory ordering, path representation, supported file types, normalization and signature algorithm. The current implementation signs a hash of the recursively enumerated inventory, including UI content and excluding the signature file; the supplied demos verify under that algorithm. Preserve compatibility deliberately when formalizing the format. [Canonical implementation][pack]
Validate IDs, entry paths, duplicates, link policy and package structure before trust decisions. For the initial format, rejecting package symlinks is a reasonable simplification; if links are supported, define and enforce their integrity and confinement consistently across archives, signing, copying and runtime access. No format may verify one set of bytes and then execute different bytes after a race or mutable replacement.
Define two explicit operating policies:
- **Verified installation:** trust is established against an authorized key/store policy; invalid, missing, revoked or untrusted signatures fail closed. Verification must cover all executed and rendered package content.
- **Development installation:** unsigned/local content is allowed only through an explicit developer choice and visibly identified as such. It must not silently replace or masquerade as a verified revision.
The distributed reference image uses verified packages for its shipped applications. Demo keys are fixtures and must never become production signing authority. Keep release private keys outside the repository. Document how trusted keys are added, removed and rotated, and how installed/running revisions respond to revocation. A networked key service or general PKI is unnecessary unless a concrete distribution requirement justifies it.
Bind each installed application ID and its retained data to an authorized publisher/update-key policy. A generally trusted key must not be able to replace an unrelated publisher's application merely by reusing its ID. Preserve that ownership record across ordinary uninstall while data remains. Key rotation or ownership transfer requires the established authorization and an explicit transition. Refuse developer-install collisions with a verified identity, or use a separate development identity and data namespace. A new package requesting additional grants must follow the explicit grant policy; prior approval does not silently expand with an update.
Signed bytes establish origin/integrity under a trust policy, not safety or unrestricted permissions. Grant approval and signature verification remain separate decisions.
### 9.3 Transactional installation and update
The supported package workflow must:
1. Stage a complete candidate revision in a controlled location on the target filesystem.
2. Validate its structure, manifest, component and entries.
3. Verify its canonical content and trust under the selected installation policy.
4. Establish immutable, correctly owned installed content.
5. Activate the revision through a recoverable atomic transition.
6. Retain the previous revision while active sessions or rollback retention require it.
7. Clean unreferenced staging/revisions through a defined recovery policy.
A failed validation, full disk, denied write, crash or interruption must preserve the previous active revision when one exists; a failed first installation must leave the package uninstalled without phantom activation. User data remains intact in either case. A live session remains pinned to its original package bytes. Uninstall removes availability for new launches and follows an explicit policy for live sessions; it preserves user data by default. Purging data is a separate, explicit destructive action.
Package rollback and data rollback are different operations. If an application changes its data schema, define compatibility and recovery for that actual migration before shipping it. Do not invent a generic migration framework or imply that switching package revisions reverses user data automatically.
### 9.4 Verified images
If EROFS/dm-verity is part of a supported release profile, the builder and loader must share artifact names, version identity and metadata. Authenticate the image identity, root hash and necessary companion data under the package trust model. Verify that runtime, UI, manifest and grants refer to the same mounted revision.
A mount or verification failure in verified mode must not select an unverified mutable directory. Privileged operations must satisfy section 5.3. Test invalid image/hash pairs, tampered metadata, missing tools, caller authorization, partial mount failure, process termination and cleanup. Until these gates pass, keep this mode out of the supported image and document that limitation accurately.
Verified directory packages can satisfy the initial package profile only when their installed content cannot be modified by application code and the trust/identity checks remain effective through launch. Merely marking a same-user directory read-only by convention is insufficient.
## 10. Build, deployment and dependency policy
### 10.1 One reproducible product build
Record the actual Rust toolchain, target, workspace feature set, lockfiles, Servo/Stylo revisions, native libraries and build commands. Build both Servo hosts with their real renderer feature and the runtime with its real Wasmtime feature. Keep feature-disabled paths clearly confined to limited tooling checks; they cannot be distributed as functioning product components.
The selected dependency graph is authoritative for APIs. The inspected Cargo lockfile selects Servo `8e7dc40bff42448980b7249798f17e3131547138` and Stylo `dca3934667dae76c49bb579b268c5eb142d09c6a`; these are recovery evidence, not a direction to preserve old revisions indefinitely. Confirm whether the selected compatible stack should be repaired or updated in a bounded dependency change. [Lockfile][lockfile]
Apply required Cargo overrides at the consuming workspace root; dependency-level patch tables do not apply transitively. Inspect the resolved graph and verify each claimed fix on the actual selected code. Keep a short purpose, upstream status and removal condition for retained fork patches. [Cargo patch rules][cargo-patch]
Never fabricate `pkg-config` metadata, native library versions or readiness messages to pass a build. Repair the supported environment or clearly exclude an unsupported feature. Do not copy machine-specific usernames or checkout paths into the documented workflow.
Dependency updates need scope, compatibility evidence, relevant security review and the same per-step review as product code. Before beta, check the actual chosen versions against current upstream fixes/advisories and release support requirements. Record the assessment rather than assuming either that the latest tip is suitable or that an old pin is safe.
### 10.2 Installed session
Choose one authoritative Nix/systemd configuration and make supporting development units/scripts consistent with it. The installed closure must include:
- Correct feature-enabled binaries and runtime native dependencies.
- Shell HTML and required UI assets at real installed paths.
- Reference application packages with an explicit trust configuration.
- The actual app-shell and runtime paths, and paths for enabled portals/helpers, passed to appd.
- Explicit service activation/dependencies and truthful readiness.
- The real compositor display and daemon endpoints, without guessed names such as `wayland-1`.
- A seat/session arrangement that works in the reference VM.
- Separate persistent data and ephemeral runtime storage.
- Bounded restart behavior, diagnostics and authorized shutdown/reboot.
Build and boot the complete graphical closure from a clean environment. Verify updates/rebuilds preserve persistent data. No checkout-relative assets, manual environment repair or silently disabled product checks may be necessary for the documented release path.
### 10.3 Diagnostics and developer workflow
Document one supported path from checkout to real system and one installed-package workflow: build, check, verify, install, inspect, launch, status, terminate, update and uninstall. Existing commands plus a small diagnostic harness are sufficient; a new general CLI framework is not a goal.
Emit structured error categories for invalid packages, denied grants, startup timeouts, child exits, transport failures and rendering failures. Correlate diagnostics with safe session identifiers. Default logs must not dump application payloads, clipboard contents, saved notes or credentials. Preserve useful terminal reasons without indefinite log growth.
## 11. Verification contract
### 11.1 Evidence levels
| Level | What it can establish | What it cannot establish alone |
|---|---|---|
| Source inspection | Ownership, missing paths, API use and policy inconsistencies | Successful execution |
| Unit or pure contract test | Deterministic parser, state, serialization or boundary behavior | Full child-process, graphics or platform integration |
| Actual component/protocol integration | ABI, message semantics, grants and exercised lifecycle paths | Installed desktop behavior unless it runs that path |
| Graphical nested execution | Presented pixels, native input and desktop interactions on that backend | Reference-image boot or unrelated DRM behavior |
| Booted image and target-specific tests | Installed closure, session startup and behavior on the named target | Compatibility with untested devices |
| Failure and soak qualification | Defined recovery/reliability behavior within measured conditions | Absence of every possible defect |
Record commit, environment, selected features, command/harness, result and useful diagnostics. A missing environment or skipped required test is an incomplete gate, not a pass. Distinguish tests executed from tests only designed. Fixtures must fail when the promised behavior is broken; avoid tests that restate the implementation or only inspect a success log.
### 11.2 Verification profiles
Create profiles from commands that actually exist in the recovered repository. Names below describe responsibilities; they are not a claim that corresponding commands are currently installed.
| Profile | Required coverage |
|---|---|
| Contributor documentation | Policy consistency, Markdown links/catalog/metadata, runner behavior and actual diff review |
| Portable Rust/tooling | Relevant format/lint/tests for supported portable crates; no desktop-support inference |
| Linux product build | Correct runtime and Servo features, native dependencies, locked graph and required Linux crates |
| Component and protocol | Actual Wasm fixtures, canonical WIT, authenticated bridge, framing, limits and denied operations |
| Nested desktop | Real shell/app pixels, Counter, Notes, input, geometry, switching, lifecycle and reconnection |
| Package and data | Trust, confinement, atomic activation, interruption, retained data and live revision pinning |
| Reference image | Build, graphical boot, installed assets/endpoints, persistence, shutdown and service recovery |
| DRM or optional feature | Feature-specific positive, negative and recovery scenarios on the declared target |
| Release qualification | Full supported matrix, regression/failure suite, reliability runs, exact artifacts and independent review |
Demos are excluded from the current root workspace; their builds and actual component fixtures must be included explicitly where relevant. Default `cargo test --workspace` cannot prove their execution or the feature-enabled product behavior. [Workspace exclusions][workspace]
Use the smallest sufficient validation set for each change. Expand testing for a concrete affected boundary, regression risk or release gate. Do not repeatedly run unrelated expensive suites after the remaining risk is resolved. Conversely, do not weaken required checks or regenerate expectations merely to make a failing result green.
### 11.3 Required acceptance fixtures
| Fixture | Observable acceptance |
|---|---|
| Real first frame | Both hosts paint and present known content; no fake readiness or permanently blank surface |
| Initialization exchange | A UI that needs an initial component response completes its authenticated bootstrap while Starting and reaches truthful readiness |
| Counter | UI action reaches the actual component and its returned value updates the DOM |
| Notes exactness | Unicode, newlines, quotes and literal backslashes round-trip exactly |
| Notes ordering | Delayed load/save replies cannot replace newer edits; concurrent writes follow the declared policy |
| Notes close policy | Save/discard/cancel behavior follows the declared policy before teardown; forced termination never claims a successful save |
| Notes durability | Failed write preserves prior content; close/reopen, reboot and package update preserve successful saves |
| Two sessions | Switch and close independently; focus, stacking and payload delivery match ownership |
| Unauthorized client | Forged/mismatched/stale credentials cannot call system operations or access another session |
| Capability denial | Every advertised host import has allowed, denied and failure-path component tests |
| Filesystem confinement | Read-only writes, parent traversal, intermediate/final symlinks and replacement races are rejected |
| Entry validation | Escaping paths, wrong component world, missing entries and invalid identities fail before launch |
| Startup failures | Missing binaries, renderer failure, invalid package and readiness timeout produce a terminal reason and complete cleanup |
| Cancellation/crash | Runtime/UI death and cancellation at each startup phase leave no owned processes, relays, sockets or mounts |
| Framing/backpressure | Fragmentation, cancellation, concurrent traffic, full queues and closed relays do not corrupt frames or deadlock appd |
| Reconnection | Daemon/shell restart follows ownership policy and restores a coherent catalog/session snapshot |
| Geometry/input | Move/resize/maximize, focus, wheel, declared layouts and scale changes work without stuck input or coordinate drift |
| Idle/redraw | Input/content changes resume rendering after idle; no unbounded repaint loop is required |
| Package integrity | Tampering with executable, manifest or UI content fails verified installation/launch |
| Publisher ownership | A different trusted key cannot take over an app ID or retained data, including after uninstall; developer collisions are isolated/refused; authorized key rotation preserves ownership |
| First-install interruption | Failure leaves the package uninstalled, data intact and staging recoverable/removable; partial content is never active |
| Update interruption | Failure preserves the previously active revision, intact user data and recoverable staging |
| Active update | Existing session retains its package revision while a new launch resolves the new revision |
| Uninstall/migration | User data survives ordinary removal and legacy-layout migration; purge is explicit |
| Host services | Supported fetch/notification/clipboard behavior works in the installed environment and respects grants |
| Reference boot | Fresh graphical image starts the complete system without checkout paths or manual fixes |
| DRM recovery | Supported session deactivate/reactivate and output changes resume presentation correctly |
| Optional image mode | Tamper, mount failure and interrupted cleanup never downgrade verified execution |
For reliability qualification, adopt these initial acceptance targets and freeze any justified adjustments before beta:
- 20 consecutive clean reference-VM boots without failed session bring-up.
- 100 application launch/activate/close cycles without orphan processes or stale sessions.
- A two-hour mixed interactive run plus a separate idle/resume test.
- No uncaught host crash, deadlock, lost acknowledged data, cross-session disclosure or unbounded process/queue growth in those runs.
These are proposed acceptance targets, not measured baseline results. Measure launch time, input responsiveness, idle CPU, memory and log/queue growth on the reference target. Select and document acceptable budgets before beta; release candidates must meet the frozen budgets or present a reviewed scope decision before promotion.
## 12. Development sequence
Use dependency order and complete observable results. Do not begin with a repository-wide rewrite or treat security/data preservation as a late hardening stage.
| Milestone | Complete result | Exit evidence | Dependencies |
|---|---|---|---|
| Reproducible product build | One selected dependency graph, truthful feature configuration, real nested shell and app-host frames | Clean feature-enabled build; selected graph/pin agreement; pixel/input fixture | Contributor contract and supported environment recorded |
| Isolated application path | One resolved package/session identity, authenticated bridge, initial grants, renderer/package-resource/network restrictions, independent data, owned cleanup, Counter and Notes | Real component round-trip; exact Notes persistence; two-session denial; undeclared renderer/runtime operations denied; child/startup failure fixtures | Product build |
| Operable desktop | Authoritative windows, focus/stacking, geometry, shell activation, input, accessible keyboard navigation and state resynchronization | Two-app desktop workflow; layouts, wheel, resize/scale; close/reconnect and idle recovery | Isolated application path |
| Complete declared capabilities | Expand and qualify the supported operations within the established renderer/component boundaries; all advertised imports and budgets are enforced | Positive/negative actual component tests, portal race/confinement tests, browser resource policy and installed host-service fixtures | Isolated application path; product graphics |
| Recoverable package management | Shared validation, trust, staged activation, live revision pinning, retained data, migration and uninstall semantics | Tamper, interruption, rollback-compatibility, data-migration and update-during-session fixtures | Package identity and independent data established earlier |
| Bootable reference image | One coherent graphical Nix/systemd closure with real assets, endpoint propagation and backend recovery | Fresh build/boot, real app usage, persistence/reboot and DRM tests if selected | Desktop, capabilities and package paths integrated |
| Complete supported distribution | Honest support matrix, application authoring guide, package diagnostics, optional modes either qualified or clearly unavailable | Clean-checkout and installed workflows reproduced; documented features map to passing fixtures | Reference image and supported feature set |
| Stability qualification | Candidate contains the complete declared scope with measured budgets and no blocking defects | Full acceptance matrix, failure/soak runs, candidate artifacts and independent technical review | All required supported paths |
The **first implementation task** is to recover the truthful full-feature baseline: select the dependency graph, repair the actual Servo API use, paint/present a reference frame, and verify the product feature configuration. Split this into reviewed coherent changes where needed. Do not combine it with speculative visual redesign or package-format redesign.
The **first integrated application milestone** must already include authenticated IPC, one package identity, publisher/data ownership, renderer and runtime resource restrictions, data outside package content and owned cleanup. Unsupported host imports must fail explicitly until implemented. Early development may use controlled local fixtures, but must not publish sandbox, trust or stability claims beyond the exercised contract.
Later milestones may proceed in parallel only when they have independent contracts and acceptance criteria. Shared schemas, lifecycle owners and dependency decisions require coordination before edits; parallel work must not create competing sources of truth. Every branch still passes its own review and integration gates.
### 12.1 Version progression
Use scoped `0.0.x` releases toward stable `0.1.0`. Assign the next available `0.0.x` to an accepted milestone scope after inspecting existing refs and publication history. Do not mechanically assign a new version to every commit or promise a fixed count of intermediate releases.
The current unreleased manifest value `0.1.0` must be reconciled deliberately. Do not rewrite published tags, force users onto a lower published version or change application/package versions accidentally. Document whether the existing workspace value was only a development placeholder before establishing the next prerelease.
Each planned version follows `alpha.N -> beta.N -> rc.N -> final`:
For example: `0.0.1-alpha.1`, `0.0.1-beta.1`, `0.0.1-rc.1`, then `0.0.1`. “Final” names the promotion stage, not a literal `-final` version suffix.
| Stage | Entry/exit contract |
|---|---|
| `alpha.N` | Scope, ownership and fixtures defined; bounded implementation proceeds through reviewed steps; known incompleteness is explicit |
| `beta.N` | The version's declared scope is implemented; relevant integration and failure paths pass; interfaces/support/budgets are frozen for qualification |
| `rc.N` | Exact candidate is feature-complete for its scope; required matrix and independent technical review pass; artifacts and migration/recovery behavior are ready |
| Final for a `0.0.x` version | That version's scoped promises pass; remaining product milestones stay explicit and the release is not presented as stable `0.1.0` |
| Stable `0.1.0` | Every required product journey, trust/data boundary, supported target and release gate in this blueprint passes |
Promotion is an explicit evidence-based decision under existing release authority. No label, test count, lack of bug reports or successful compile triggers promotion automatically. Corrections after candidate approval invalidate affected evidence; material changes require a new candidate and review. Publish the tested artifact. If final version metadata or packaging requires a rebuild, verify that final artifact under the applicable candidate gates before publication.
## 13. Contribution, review and continuous simplification
### 13.1 Toolkit structure
Adapt the actual Resina arrangement to WEFT. Retain the distinction between the root contract and optional linked knowledge; do not copy design-system-specific backends, schemas or contribution hierarchy. [Resina contract][resina-contract] [Resina toolkit][resina-toolkit]
| Path | Responsibility |
|---|---|
| `AGENTS.md` | Canonical engineering policy, scope, review, validation and publication rules |
| `.agents/README.md` | Catalog, precedence, entry points and actual capabilities |
| `.agents/commands/` | Scope/specification, implementation, verification, maintenance and release procedures |
| `.agents/agents/` | Reviewer, architecture-debt scout, continuous simplicity and continuous refactoring responsibilities |
| `.agents/skills/` | Focused WEFT area knowledge linked to canonical contracts and selected sources |
| `.agents/scripts/verify.py` | Small portable runner for actual repository verification profiles |
| `CONTRIBUTING.md` and issue/PR templates | Maintainer-facing contribution expectations and useful problem/behavior/evidence fields |
Area knowledge should cover compositor/input, Servo, runtime/capabilities, appd lifecycle/IPC, packages/data/trust, Linux deployment, integration/visual verification and documentation. Combine related subjects where that produces a useful guide. Do not duplicate root policy in every file or create empty guides for symmetry.
Commands are portable Markdown procedures, not a claim that every client has automatically registered slash commands. Any metadata must be internally consistent and compatible with the chosen consumer. The runner uses argument arrays, resolves the repository root, works from another directory, fails on required failures and supports dry-run. It must not silently install dependencies, mutate files, bless expectations, skip required checks or publish changes. Test its meaningful behavior, especially failure propagation and missing prerequisites. [Resina runner reference][resina-runner]
### 13.2 Every coherent step is reviewed
Apply this loop to primary development, bug fixes, simplification, refactoring, dependencies, documentation, governance, packaging and release work:
1. Inspect current evidence and the relevant implemented/accepted contract.
2. State the present problem, owner, bounded scope, observable acceptance and proof.
3. Review that scope and design before changing the affected boundary.
4. Implement one coherent result, preserving unrelated work.
5. Run the smallest sufficient checks for the changed behavior and concrete risks.
6. Review the actual diff against acceptance, compatibility, security, data and failure behavior.
7. Correct findings, revalidate and review the corrected content.
8. Accept the atomic result only when blockers are resolved; then reassess the next dependent step.
Review a real staged/unstaged diff or explicit base-to-head commit range. An empty `git diff HEAD` after committing is not review of the committed change. Recheck material rebases, conflict resolutions and corrections before integration. Review the final aggregate change for cross-step effects when preparing a PR or candidate.
Use a reviewer who did not author the change when available. If that is unavailable, use a fresh separate critical pass and record its limitation honestly; never claim independent review occurred. Release gates require independent technical review of the candidate. An unavailable required release reviewer leaves that release gate pending while other authorized work continues.
A blocking finding concerns correctness, promised behavior, trust, data preservation, compatibility, the accepted scope or required evidence. Fix it before advancing dependent work. A present but unrelated improvement belongs in separately scoped maintenance; speculative preferences must not become blockers or recurring issue quotas.
Review is an engineering checkpoint, not a requirement for a new human confirmation at every step. Decisions already accepted in this blueprint and prior authorization remain effective.
### 13.3 Autonomous primary development and bounded maintenance
Continue primary development through successive accepted changes toward the active goal. Do not stop after a single patch or PR when more authorized independent work remains. Reinspect the changed boundary and new evidence rather than repeating full repository discovery for each step.
Fix related debt within the active acceptance criterion. For unrelated maintenance, require an affected user/contract, present evidence and cost, and an independently verifiable acceptance criterion. Check for existing work first. Base an isolated worktree and descriptive branch on a verified current revision of the default branch, preserving the active development checkout. If freshness cannot be verified, state the actual revision and limitation. Each separately invoked maintenance run handles one qualifying problem and stops after its issue or reviewed PR; primary development continues independently. Publication follows existing authority. When publication is not authorized or available, prepare the local result and concrete issue/PR content without publishing it.
The debt scout identifies the strongest justified issue without editing repository files or creating implementation branches or commits; it may prepare or publish that issue only within granted authority. It must not manufacture a backlog or launch speculative work. Simplicity removes duplicated decisions, unnecessary state and misleading fallback paths. Refactoring changes internal structure while preserving the accepted behavior and proof. Neither is a license for repeated architecture replacement.
High-value candidates already supported by the audit are shared package resolution, a single effective-grants model, one session cleanup owner, one bridge/message contract and common Servo host/input behavior. Extract them when the working path and regression evidence justify the boundary. Do not optimize for line-count reduction at the expense of explicit authority, errors or useful tests.
Seek a new decision only for a material departure from accepted product direction, public compatibility promises, trust boundaries, support scope, destructive data policy or missing authority. Prepare the alternatives and evidence first, and continue independent authorized work. Ordinary implementation of an accepted boundary must not trigger repeated architecture approval requests.
### 13.4 Branches and publication text
Use descriptive technical branch names in every workflow:
| Change | Suitable branch |
|---|---|
| Contributor contract | `docs/add-weft-contribution-contract` |
| Real frame presentation | `fix/servo-frame-presentation` |
| Session authorization | `fix/authorize-session-messages` |
| Data preservation | `fix/preserve-notes-on-package-update` |
| Shared package resolution | `refactor/share-package-resolution` |
| Keyboard app switching | `feat/keyboard-app-switching` |
| Installed Servo features | `build/enable-servo-vm-packages` |
| Portal regression coverage | `test/reject-portal-symlink-escapes` |
Reject generic task/lane/phase labels, model/provider names, role names and generic “maintenance” or “stability” branches. The branch must describe the actual change even when the change originated during maintenance. Discover the real default branch; do not copy Resina's `master` assumption into WEFT's `main` workflow.
Public branch names, commit subjects/bodies, issue/PR titles and descriptions, comments, release notes and product text must describe the concrete problem, resulting behavior, affected boundaries and actual validation. Do not include model/provider attribution, generated-by/co-author trailers, reviewer counts/personas, prompts, internal role handoffs or process narration. A technical “Validation” section with real commands and results is useful; claims about how many reviewers participated are not product evidence.
Keep commits atomic and technically named. Reusable governance files, this adopted blueprint and legitimate protocol/product documentation are intentional tracked artifacts. Temporary plans, transcripts, review scratch files and internal progress reports stay out of Git.
Preserve unrelated working-tree changes, existing branches and protections. Never use a successful review as implicit merge, release or deployment authority. Honor existing authorization without requesting it again. Before a public action, inspect applicable repository integrations and controls; do not knowingly trigger incompatible branded publication or bypass required protections to avoid it. Resolve an actual conflict explicitly while continuing safe authorized work.
## 14. Stable release gate
Stable `0.1.0` is ready only when all applicable statements are true for the exact candidate:
- The full feature-enabled product builds from the documented pinned environment.
- Both Servo hosts present real content and respond correctly to required input/window events.
- The reference image boots into the usable desktop without manual repair.
- The complete Counter and Notes workflows run through actual components and host processes.
- Session identity, authenticated IPC, grants and renderer restrictions enforce the declared boundaries.
- All child failures, startup cancellation, daemon/shell recovery and teardown paths settle owned resources.
- Package integrity, transactional activation, live version pinning and data retention survive their negative/failure fixtures.
- Every advertised host import and supported backend has actual integration evidence.
- Declared keyboard accessibility, support matrix and installed developer/user workflows are verified.
- Measured budgets and the frozen reliability targets pass.
- Known failures in these promises are resolved; unsupported features are clearly excluded and unavailable as successful product paths.
- Documentation, manifest/WIT/IPC contracts, selected dependencies, build configuration and observed behavior agree.
- The candidate has independent technical review, and material findings/corrections have been revalidated and reviewed.
- Release metadata identifies the commit, artifact digests, environment, support scope, compatibility/migration notes and known limitations accurately.
- Publication follows the established authority and repository protections; tags and artifacts refer to the tested candidate.
## 15. Source references
Inline repository links are pinned to the inspected revisions unless they intentionally identify a live release listing or recorded CI run. Upstream links identify the API versions used to verify baseline findings. Recheck them against the selected implementation revision when work begins.
[workspace]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/Cargo.toml
[architecture]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/docs/architecture.md
[historical-baseline]: https://github.com/marcoallegretti/WEFT_OS/blob/a236a3a9f4f7a90288beed6ffc6412bdbc0b042e/docs/architecture/baseline.md
[security]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/docs/security.md
[lockfile]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/Cargo.lock
[servo-pin]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-servo-shell/SERVO_PIN.md
[app-embedder]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-app-shell/src/embedder.rs
[system-embedder]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-servo-shell/src/embedder.rs
[app-main]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-app-shell/src/main.rs
[system-main]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-servo-shell/src/main.rs
[runtime]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-runtime/src/main.rs
[appd-runtime]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-appd/src/runtime.rs
[appd-main]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-appd/src/main.rs
[appd-ipc]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-appd/src/ipc.rs
[appd-ws]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-appd/src/ws.rs
[file-portal]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-file-portal/src/main.rs
[compositor-appd]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-compositor/src/appd_ipc.rs
[compositor-state]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-compositor/src/state.rs
[compositor-input]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-compositor/src/input.rs
[drm]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-compositor/src/backend/drm.rs
[pack]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-pack/src/main.rs
[mount]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-appd/src/mount.rs
[mount-helper]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/crates/weft-mount-helper/src/main.rs
[notes-ui]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/examples/org.weft.demo.notes/ui/index.html
[notes-runtime]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/examples/org.weft.demo.notes/src/main.rs
[nix-packages]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/infra/nixos/weft-packages.nix
[nix-config]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/infra/nixos/configuration.nix
[flake]: https://github.com/marcoallegretti/WEFT_OS/blob/b99cc73a4704615521c38ca84dc46dc1bd641bc6/flake.nix
[services]: https://github.com/marcoallegretti/WEFT_OS/tree/b99cc73a4704615521c38ca84dc46dc1bd641bc6/infra/systemd
[ci-run]: https://github.com/marcoallegretti/WEFT_OS/actions/runs/23053354517
[releases]: https://github.com/marcoallegretti/WEFT_OS/releases
[servo-input]: https://github.com/marcoallegretti/servo/blob/8e7dc40bff42448980b7249798f17e3131547138/components/shared/embedder/input_events.rs#L195-L202
[servo-render]: https://github.com/marcoallegretti/servo/blob/8e7dc40bff42448980b7249798f17e3131547138/components/shared/paint/rendering_context.rs#L305-L371
[servo-webview]: https://github.com/marcoallegretti/servo/blob/8e7dc40bff42448980b7249798f17e3131547138/components/servo/webview.rs#L47-L69
[servo-patch]: https://github.com/marcoallegretti/servo/blob/8e7dc40bff42448980b7249798f17e3131547138/Cargo.toml#L348-L356
[stylo-gate]: https://github.com/servo/stylo/blob/dca3934667dae76c49bb579b268c5eb142d09c6a/style/properties/longhands.toml#L351-L359
[smithay-output]: https://github.com/Smithay/smithay/blob/v0.7.0/src/backend/drm/output.rs#L503-L637
[smithay-dmabuf]: https://github.com/Smithay/smithay/blob/v0.7.0/src/wayland/dmabuf/mod.rs#L585-L609
[cargo-patch]: https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html#the-patch-section
[tokio-lines]: https://docs.rs/tokio/1.50.0/tokio/io/trait.AsyncBufReadExt.html#method.read_line
[wasmtime-linker]: https://github.com/bytecodealliance/wasmtime/blob/v30.0.2/crates/wasmtime/src/runtime/component/linker.rs#L28-L55
[resina-contract]: https://github.com/marcoallegretti/Resina-Design_System/blob/1e768064f57a1e403ab271822383e732795905a6/AGENTS.md
[resina-toolkit]: https://github.com/marcoallegretti/Resina-Design_System/blob/1e768064f57a1e403ab271822383e732795905a6/.agents/README.md
[resina-runner]: https://github.com/marcoallegretti/Resina-Design_System/blob/1e768064f57a1e403ab271822383e732795905a6/.agents/scripts/verify.py

77
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,77 @@
# Contributing to WEFT OS
[AGENTS.md](AGENTS.md) is the engineering contract for every contribution.
[BLUEPRINT.md](BLUEPRINT.md) describes the accepted product direction toward
`0.1.0`. This guide points to the workflow; the contract
defines the requirements.
The [contributor toolkit](.agents/README.md) provides procedures, review roles,
area knowledge and a verification runner.
## Describe a verifiable change
Search [existing issues](https://github.com/marcoallegretti/WEFT_OS/issues) and
pull requests first, then open a
[new issue](https://github.com/marcoallegretti/WEFT_OS/issues/new/choose):
- **Defect or change** for a concrete problem or ordinary work within accepted
architecture.
- **Maintenance** for one present ownership, boundary, enforcement or structural
problem outside active development.
- **Decision** for a material change of product direction, public compatibility,
trust boundaries, support scope or data policy. Opening it does not approve the
change.
Each form asks for observed and expected behavior, evidence, the owning
component, present impact, an acceptance criterion and the proof that would
show the change works. The [maintenance threshold](AGENTS.md#8-maintenance)
separates a present problem from a cleanup preference.
## Find the owner
Each component owns specific responsibilities, listed in the blueprint's
[ownership table](BLUEPRINT.md#4-architecture-and-ownership). Public contracts
are the package manifests, the [host WIT](crates/weft-runtime/wit/weft-app.wit),
the [shell protocol](protocol/weft-shell-unstable-v1.xml) and the
[IPC types](crates/weft-ipc-types/src/lib.rs). Selected dependency APIs are
those in [Cargo.lock](Cargo.lock), including the Servo fork and the Stylo revision.
## Prove and implement the change
Follow the [reviewed change loop](AGENTS.md#5-reviewed-change-loop): confirm
scope, name the proof, implement, validate, review the actual diff, correct and
commit atomically. Reproduce a defect before fixing it. Compilation, mocks and
capability declarations do not prove rendering, native input, isolation or
persistence; see [proof before implementation](AGENTS.md#6-proof-before-implementation).
Branch from the current `main` with a descriptive name such as
`fix/authorize-session-messages` or `refactor/share-servo-frame-loop`; the
[branch rules](AGENTS.md#14-branches-commits-and-publication) list what to avoid.
Install the native dependencies from [docs/building.md](docs/building.md) and
run the relevant [runner](.agents/README.md#verification-runner) profiles, for
example:
```sh
python .agents/scripts/verify.py portable linux
python .agents/scripts/verify.py servo-embed
pip install -r .agents/scripts/requirements.txt
python .agents/scripts/verify.py toolkit
```
[verify](.agents/commands/verify.md) maps each kind of change to its profiles and
to the evidence the runner cannot provide, such as a running compositor, real
pixels, actual components or a booted image. Report checks that could not run
and why.
## Submit a pull request
The [pull request template](.github/pull_request_template.md) asks for the
problem and scope, what changed, ownership, what proves it, the validation
actually performed, manual verification and material limitations. Write for a
maintainer who has no access to your working notes: no attribution, generated-by
or co-author trailers, prompts or process narration.
Contribution work is reviewed from its actual diff, preferably by someone who
did not write it. Maintainers decide merges and release promotion; a green CI
run or a review does not merge or release anything by itself.

169
Cargo.lock generated
View file

@ -6476,7 +6476,7 @@ dependencies = [
[[package]]
name = "selectors"
version = "0.36.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"bitflags 2.11.0",
"cssparser",
@ -6590,7 +6590,7 @@ dependencies = [
[[package]]
name = "servo"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accesskit",
"bitflags 2.11.0",
@ -6651,7 +6651,7 @@ dependencies = [
[[package]]
name = "servo-allocator"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"libc",
"tikv-jemalloc-sys",
@ -6662,7 +6662,7 @@ dependencies = [
[[package]]
name = "servo-background-hang-monitor"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"backtrace",
"crossbeam-channel",
@ -6677,7 +6677,7 @@ dependencies = [
[[package]]
name = "servo-background-hang-monitor-api"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"serde",
"servo-base",
@ -6686,7 +6686,7 @@ dependencies = [
[[package]]
name = "servo-base"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accesskit",
"crossbeam-channel",
@ -6711,7 +6711,7 @@ dependencies = [
[[package]]
name = "servo-canvas"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bytemuck",
"crossbeam-channel",
@ -6736,7 +6736,7 @@ dependencies = [
[[package]]
name = "servo-canvas-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"crossbeam-channel",
"euclid",
@ -6758,7 +6758,7 @@ dependencies = [
[[package]]
name = "servo-config"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"serde",
"serde_json",
@ -6770,7 +6770,7 @@ dependencies = [
[[package]]
name = "servo-config-macro"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"proc-macro2",
"quote",
@ -6781,7 +6781,7 @@ dependencies = [
[[package]]
name = "servo-constellation"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"backtrace",
"content-security-policy",
@ -6828,7 +6828,7 @@ dependencies = [
[[package]]
name = "servo-constellation-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"content-security-policy",
"encoding_rs",
@ -6863,7 +6863,7 @@ dependencies = [
[[package]]
name = "servo-deny-public-fields"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"syn",
"synstructure",
@ -6872,7 +6872,7 @@ dependencies = [
[[package]]
name = "servo-devtools"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"atomic_refcell",
"base64 0.22.1",
@ -6901,7 +6901,7 @@ dependencies = [
[[package]]
name = "servo-devtools-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bitflags 2.11.0",
"http 1.4.0",
@ -6920,7 +6920,7 @@ dependencies = [
[[package]]
name = "servo-dom-struct"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"proc-macro2",
"quote",
@ -6930,7 +6930,7 @@ dependencies = [
[[package]]
name = "servo-embedder-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accesskit",
"bitflags 2.11.0",
@ -6963,7 +6963,7 @@ dependencies = [
[[package]]
name = "servo-fonts"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"app_units",
"bitflags 2.11.0",
@ -7016,7 +7016,7 @@ dependencies = [
[[package]]
name = "servo-fonts-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"atomic_refcell",
"dwrote",
@ -7039,7 +7039,7 @@ dependencies = [
[[package]]
name = "servo-geometry"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"app_units",
"euclid",
@ -7052,7 +7052,7 @@ dependencies = [
[[package]]
name = "servo-hyper-serde"
version = "0.13.2"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"cookie 0.18.1",
"headers 0.4.1",
@ -7066,7 +7066,7 @@ dependencies = [
[[package]]
name = "servo-jstraceable-derive"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"proc-macro2",
"syn",
@ -7076,7 +7076,7 @@ dependencies = [
[[package]]
name = "servo-layout"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accesskit",
"app_units",
@ -7130,7 +7130,7 @@ dependencies = [
[[package]]
name = "servo-layout-api"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"app_units",
"atomic_refcell",
@ -7164,7 +7164,7 @@ dependencies = [
[[package]]
name = "servo-malloc-size-of"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accountable-refcell",
"app_units",
@ -7204,7 +7204,7 @@ dependencies = [
[[package]]
name = "servo-media"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"once_cell",
"servo-media-audio",
@ -7217,7 +7217,7 @@ dependencies = [
[[package]]
name = "servo-media-audio"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"byte-slice-cast",
"euclid",
@ -7240,7 +7240,7 @@ dependencies = [
[[package]]
name = "servo-media-derive"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"proc-macro2",
"quote",
@ -7250,7 +7250,7 @@ dependencies = [
[[package]]
name = "servo-media-dummy"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"ipc-channel",
"servo-media",
@ -7264,7 +7264,7 @@ dependencies = [
[[package]]
name = "servo-media-player"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"ipc-channel",
"malloc_size_of_derive",
@ -7278,7 +7278,7 @@ dependencies = [
[[package]]
name = "servo-media-streams"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"malloc_size_of_derive",
"servo-malloc-size-of",
@ -7288,7 +7288,7 @@ dependencies = [
[[package]]
name = "servo-media-thread"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"euclid",
"ipc-channel",
@ -7306,7 +7306,7 @@ dependencies = [
[[package]]
name = "servo-media-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"malloc_size_of_derive",
"servo-malloc-size-of",
@ -7315,7 +7315,7 @@ dependencies = [
[[package]]
name = "servo-media-webrtc"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"log",
"servo-media-streams",
@ -7325,7 +7325,7 @@ dependencies = [
[[package]]
name = "servo-metrics"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"malloc_size_of_derive",
"servo-base",
@ -7340,7 +7340,7 @@ dependencies = [
[[package]]
name = "servo-net"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"async-compression",
"async-recursion",
@ -7409,7 +7409,7 @@ dependencies = [
[[package]]
name = "servo-net-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"content-security-policy",
"cookie 0.18.1",
@ -7449,7 +7449,7 @@ dependencies = [
[[package]]
name = "servo-paint"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bitflags 2.11.0",
"crossbeam-channel",
@ -7486,7 +7486,7 @@ dependencies = [
[[package]]
name = "servo-paint-api"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bitflags 2.11.0",
"crossbeam-channel",
@ -7522,7 +7522,7 @@ dependencies = [
[[package]]
name = "servo-pixels"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"euclid",
"image",
@ -7537,7 +7537,7 @@ dependencies = [
[[package]]
name = "servo-profile"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"libc",
"log",
@ -7556,7 +7556,7 @@ dependencies = [
[[package]]
name = "servo-profile-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"crossbeam-channel",
"ipc-channel",
@ -7573,7 +7573,7 @@ dependencies = [
[[package]]
name = "servo-script"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"aes",
"aes-gcm",
@ -7712,7 +7712,7 @@ dependencies = [
[[package]]
name = "servo-script-bindings"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bitflags 2.11.0",
"crossbeam-channel",
@ -7750,7 +7750,7 @@ dependencies = [
[[package]]
name = "servo-script-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"accesskit",
"content-security-policy",
@ -7787,7 +7787,7 @@ dependencies = [
[[package]]
name = "servo-storage"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"libc",
"log",
@ -7817,7 +7817,7 @@ dependencies = [
[[package]]
name = "servo-storage-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"malloc_size_of_derive",
"serde",
@ -7831,7 +7831,7 @@ dependencies = [
[[package]]
name = "servo-timers"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"crossbeam-channel",
"malloc_size_of_derive",
@ -7841,7 +7841,7 @@ dependencies = [
[[package]]
name = "servo-tracing"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"proc-macro2",
"quote",
@ -7851,7 +7851,7 @@ dependencies = [
[[package]]
name = "servo-url"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"encoding_rs",
"malloc_size_of_derive",
@ -7865,7 +7865,7 @@ dependencies = [
[[package]]
name = "servo-webgl"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"bitflags 2.11.0",
"byteorder",
@ -7889,7 +7889,7 @@ dependencies = [
[[package]]
name = "servo-webgpu"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"arrayvec",
"euclid",
@ -7908,7 +7908,7 @@ dependencies = [
[[package]]
name = "servo-webgpu-traits"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"arrayvec",
"malloc_size_of_derive",
@ -7924,7 +7924,7 @@ dependencies = [
[[package]]
name = "servo-webxr"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"crossbeam-channel",
"euclid",
@ -7943,7 +7943,7 @@ dependencies = [
[[package]]
name = "servo-webxr-api"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"euclid",
"ipc-channel",
@ -7959,7 +7959,7 @@ dependencies = [
[[package]]
name = "servo-xpath"
version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138"
source = "git+https://github.com/marcoallegretti/servo?rev=e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163#e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
dependencies = [
"log",
"malloc_size_of_derive",
@ -7970,7 +7970,7 @@ dependencies = [
[[package]]
name = "servo_arc"
version = "0.4.3"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"serde",
"stable_deref_trait",
@ -8396,7 +8396,7 @@ dependencies = [
[[package]]
name = "stylo"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"app_units",
"arrayvec",
@ -8452,7 +8452,7 @@ dependencies = [
[[package]]
name = "stylo_atoms"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"string_cache",
"string_cache_codegen",
@ -8461,7 +8461,7 @@ dependencies = [
[[package]]
name = "stylo_derive"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"darling",
"proc-macro2",
@ -8473,7 +8473,7 @@ dependencies = [
[[package]]
name = "stylo_dom"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"bitflags 2.11.0",
"stylo_malloc_size_of",
@ -8482,7 +8482,7 @@ dependencies = [
[[package]]
name = "stylo_malloc_size_of"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"app_units",
"cssparser",
@ -8499,12 +8499,12 @@ dependencies = [
[[package]]
name = "stylo_static_prefs"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
[[package]]
name = "stylo_traits"
version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"app_units",
"bitflags 2.11.0",
@ -8904,7 +8904,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "to_shmem"
version = "0.3.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"cssparser",
"servo_arc",
@ -8917,7 +8917,7 @@ dependencies = [
[[package]]
name = "to_shmem_derive"
version = "0.1.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a"
source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [
"darling",
"proc-macro2",
@ -10451,14 +10451,12 @@ checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "weft-app-shell"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"bitflags 2.11.0",
"serde",
"servo",
"softbuffer",
"toml 0.8.23",
"tracing",
"tracing-subscriber",
"wayland-backend",
@ -10469,12 +10467,13 @@ dependencies = [
[[package]]
name = "weft-appd"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"futures-util",
"libc",
"rmp-serde",
"rustix 1.1.4",
"sd-notify",
"serde",
"serde_json",
@ -10488,14 +10487,15 @@ dependencies = [
[[package]]
name = "weft-build-meta"
version = "0.1.0"
version = "0.0.1-alpha.0"
[[package]]
name = "weft-compositor"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"bitflags 2.11.0",
"rustix 1.1.4",
"sd-notify",
"smithay",
"smithay-drm-extras",
@ -10509,47 +10509,54 @@ dependencies = [
[[package]]
name = "weft-file-portal"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"rustix 1.1.4",
"serde",
"serde_json",
]
[[package]]
name = "weft-ipc-types"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"ed25519-dalek",
"hex",
"rmp-serde",
"rustix 1.1.4",
"serde",
"sha2",
"toml 0.8.23",
]
[[package]]
name = "weft-mount-helper"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"libc",
]
[[package]]
name = "weft-pack"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"ed25519-dalek",
"hex",
"rand 0.8.5",
"serde",
"rustix 1.1.4",
"sha2",
"tar",
"toml 0.8.23",
"weft-ipc-types",
"zstd",
]
[[package]]
name = "weft-runtime"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"cap-std",
@ -10558,13 +10565,15 @@ dependencies = [
"tracing",
"tracing-subscriber",
"ureq",
"url",
"wasmtime",
"wasmtime-wasi",
"weft-ipc-types",
]
[[package]]
name = "weft-servo-shell"
version = "0.1.0"
version = "0.0.1-alpha.0"
dependencies = [
"anyhow",
"bitflags 2.11.0",

View file

@ -14,13 +14,28 @@ members = [
exclude = [
"examples/org.weft.demo.counter",
"examples/org.weft.demo.notes",
"tests/components/grants-probe",
]
resolver = "2"
[workspace.package]
version = "0.1.0"
version = "0.0.1-alpha.0"
edition = "2024"
rust-version = "1.93"
[workspace.lints.rust]
unsafe_code = "forbid"
# Servo's own [patch] tables do not apply to dependents. The servo fork's
# backdrop-filter support needs the stylo fork that removes the property's
# `layout.unimplemented` gate, so the override lives here. Remove it once the
# change is available from upstream stylo at the revision Servo selects.
[patch."https://github.com/servo/stylo"]
selectors = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
servo_arc = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_atoms = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_dom = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_malloc_size_of = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_static_prefs = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_traits = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }

View file

@ -6,17 +6,17 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
**Compositor** — `weft-compositor` is a Smithay-based Wayland compositor with DRM/KMS and winit backends. It implements the `zweft-shell-unstable-v1` protocol extension, which typed shell slots (panel, application) register against.
**System shell** — `weft-servo-shell` embeds Servo (feature-gated, `--features servo-embed`) and renders `system-ui.html` as a Wayland panel. Without `servo-embed`, the binary builds as a no-op stub. Navigation gestures from the compositor are forwarded to `weft-appd` over WebSocket.
**System shell** — `weft-servo-shell` embeds Servo (feature-gated, `--features servo-embed`) and renders `system-ui.html` as a Wayland panel. Without `servo-embed`, the binary exits with an error instead of rendering. Navigation gestures from the compositor are forwarded to `weft-appd` over WebSocket.
**App shell** — `weft-app-shell` is a per-process Servo host for application WebViews. It resolves `weft-app://<id>/ui/index.html`, injects a `weftIpc` WebSocket bridge into the page, and registers with the compositor as an application surface. Also feature-gated behind `servo-embed`.
**App shell** — `weft-app-shell` is a per-process Servo host for application WebViews. It shows the UI document `weft-appd` resolved from the package, injects a `weftIpc` WebSocket bridge into the page, and registers with the compositor as an application surface. Also feature-gated behind `servo-embed`.
**App daemon** — `weft-appd` supervises sessions: spawns `weft-runtime`, waits for READY, spawns `weft-app-shell`, manages the per-session IPC relay between the Wasm component and the WebView, and handles session teardown. Wraps processes in systemd scopes (`CPUQuota=200%`, `MemoryMax=512M`) when available.
**App daemon** — `weft-appd` supervises sessions: spawns `weft-runtime`, waits for its READY, spawns `weft-app-shell` and reports the session running only after the app shell's READY, manages the per-session IPC relay between the Wasm component and the WebView, and handles session teardown. Wraps processes in systemd scopes (`CPUQuota=200%`, `MemoryMax=512M`) when available.
**Runtime** — `weft-runtime` runs WASI Component Model binaries under Wasmtime 30 (`--features wasmtime-runtime`). Provides `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard` host imports. Preopens filesystem paths according to declared capabilities.
**Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time.
**Package management** — `weft-pack` handles check, sign, verify, install and update, rollback, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. Installs only packages signed by a trusted key (or explicitly as development content) and binds each app ID to its first publisher. App data is stored apart from packages and survives uninstall.
**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking.
**File portal** — `weft-file-portal` is a per-session file proxy for the session's directory grants, with every operation confined beneath the granted directory by the kernel.
**Mount helper** — `weft-mount-helper` is a setuid helper for EROFS dm-verity mount/umount via `veritysetup`.
@ -75,11 +75,13 @@ See `docs/building.md` for full instructions including Wasm component builds, Ni
## CI
Three jobs on every push and pull request:
Jobs on every push to `main` and on pull requests:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows
- `portable` — fmt, clippy and tests for the crates that need no Linux system libraries
- `linux-only` — clippy and tests for compositor and shell crates
- `runtime-grants` — clippy for `weft-runtime` with its Wasm engine and fetch, and `tests/runtime/check_grants.py`
- `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates
- `contributor-toolkit` — links, metadata and catalog of the contributor toolkit, and runner tests
## Security
@ -94,7 +96,13 @@ See `docs/security.md`. Key points:
## Servo fork
- Repository: `https://github.com/marcoallegretti/servo`, branch `servo-weft`
- Base revision: `04ca254f`
- Patches: keyboard input, backdrop-filter in stylo
- Servo: `https://github.com/marcoallegretti/servo` at `e5d9a518`, pinned by revision
- Stylo: `https://github.com/marcoallegretti/stylo` at `f1ba4969`, through the root `[patch]`
- Patches: `backdrop-filter` parsing (Stylo) and rendering (Servo), rooting of compiled classic scripts and `navigator.servo` exposure (Servo)
- See `crates/weft-servo-shell/SERVO_PIN.md` for Servo integration status and known limitations
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md). [AGENTS.md](AGENTS.md) is the engineering contract and [BLUEPRINT.md](BLUEPRINT.md) the accepted direction toward `0.1.0`.
The workspace is at `0.0.1-alpha.0`, the first prerelease on the way to `0.0.1`. The `0.1.0` it declared before was an unreleased development placeholder; no release was published under it.

View file

@ -12,7 +12,7 @@ path = "src/main.rs"
# Enable actual Servo rendering. Deps are declared as optional below and only
# fetched when this feature is active. The Servo monorepo (~1 GB) is not
# downloaded during a plain `cargo check` or `cargo build` without this feature.
servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer", "dep:serde", "dep:toml"]
servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer"]
[dependencies]
anyhow = "1.0"
@ -22,12 +22,10 @@ wayland-client = "0.31"
wayland-backend = "0.3"
wayland-scanner = "0.31"
bitflags = "2"
serde = { version = "1", features = ["derive"], optional = true }
toml = { version = "0.8", optional = true }
[dependencies.servo]
git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft"
rev = "e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
optional = true
default-features = false

View file

@ -1,20 +1,21 @@
#![cfg(feature = "servo-embed")]
use std::path::PathBuf;
use std::num::NonZeroU32;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate,
DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent, LoadStatus,
MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
NavigationRequest, RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl,
UserContentManager, UserScript, WebViewBuilder, WebViewDelegate,
};
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland},
raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId},
};
@ -46,31 +47,342 @@ impl ServoDelegate for WeftServoDelegate {
fn notify_error(&self, error: servo::ServoError) {
tracing::error!(?error, "Servo error");
}
/// Loads not tied to the webview, such as `navigator.sendBeacon()`,
/// worklets and notification icons, also come from the application page,
/// and none of them is needed: all are refused.
fn load_web_resource(&self, load: servo::WebResourceLoad) {
let url = load.request().url.clone();
tracing::warn!(%url, "resource load outside the webview denied");
load.intercept(servo::WebResourceResponse::new(url))
.cancel();
}
}
/// Frame and load progress reported by Servo, shared with the event loop.
#[derive(Default)]
struct FrameSignals {
/// A new frame is waiting to be painted.
redraw: AtomicBool,
/// Servo has requested at least one repaint.
content: AtomicBool,
/// The document has loaded and Servo reports its rendering is up to date.
settled: AtomicBool,
/// The page closed itself with `window.close()`.
page_closed: AtomicBool,
/// The page's answer to the pending close request; see `CloseAnswer`.
close_answer: std::sync::atomic::AtomicU8,
}
/// The page's answer to a close request, as stored in `close_answer`.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum CloseAnswer {
Pending = 0,
Close = 1,
Cancel = 2,
}
/// How long a page with the `ask` close policy has to answer a close
/// request; a page that does not answer in time is closed.
const CLOSE_ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// Asks the page whether it may close: dispatches a cancelable `weftclose`
/// event on the top-level window. The page cancels the close by calling
/// `preventDefault()` and closes itself later with `window.close()`.
const ASK_CLOSE_SCRIPT: &str = "window.dispatchEvent(new Event('weftclose', { cancelable: true }))";
/// The application's declared close policy, from `WEFT_APP_CLOSE`.
fn close_policy_asks() -> bool {
std::env::var("WEFT_APP_CLOSE").is_ok_and(|v| v == "ask")
}
struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
/// URL prefix of the application's UI directory; see `ui_scope`.
scope: String,
/// The UI directory with symbolic links resolved, if it exists.
ui_dir: Option<std::path::PathBuf>,
/// The bridge's WebSocket handshake URL, as the network layer requests it
/// (`ws:` becomes `http:`).
bridge: String,
}
impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested
.store(true, std::sync::atomic::Ordering::Relaxed);
self.signals.content.store(true, Ordering::Relaxed);
self.signals.redraw.store(true, Ordering::Relaxed);
}
/// The application page called `window.close()`, which Servo allows for
/// a top-level document with a single history entry.
fn notify_closed(&self, _webview: servo::WebView) {
self.signals.page_closed.store(true, Ordering::Relaxed);
}
/// The webview carries the session's bridge, so it stays within the
/// application's own UI files.
fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) {
if in_scope(request.url.as_str(), &self.scope) {
request.allow();
} else {
tracing::warn!(url = %request.url, "navigation outside the application UI denied");
request.deny();
}
}
/// Every resource the webview loads passes through here, including
/// `fetch()`, XHR, subresources and WebSocket handshakes. The page may
/// read its own UI files and open the session bridge; any other local
/// file or network destination is refused with a network error. Network
/// access belongs to the component, under its fetch grants.
///
/// On a redirect Servo reports the first URL of the chain again, not the
/// target, so every redirect is refused.
fn load_web_resource(&self, _webview: servo::WebView, load: servo::WebResourceLoad) {
let request = load.request();
let url = request.url.clone();
if !request.is_redirect && self.allows(&ServoUrl::from_url(url.clone())) {
return;
}
tracing::warn!(%url, "resource outside the application denied");
load.intercept(servo::WebResourceResponse::new(url))
.cancel();
}
fn notify_load_status_changed(&self, webview: servo::WebView, status: LoadStatus) {
if status != LoadStatus::Complete {
return;
}
// Servo completes a screenshot request only once every frame has fired
// `load`, render-blocking resources, images and web fonts are done and
// the rendering is up to date, which is the readiness this host reports.
let signals = Arc::clone(&self.signals);
webview.take_screenshot(None, move |result| match result {
Ok(_) => {
signals.settled.store(true, Ordering::Relaxed);
signals.redraw.store(true, Ordering::Relaxed);
}
Err(e) => tracing::error!(?e, "document rendering did not settle; not ready"),
});
}
}
/// The readiness line for weft-appd: `READY <token>` with the session token
/// from `WEFT_READY_TOKEN`, or `READY` when run without appd.
fn ready_line() -> String {
match std::env::var("WEFT_READY_TOKEN") {
Ok(token) => format!("READY {token}"),
Err(_) => "READY".to_owned(),
}
}
/// The session's application bridge credential from weft-appd.
///
/// Only 32 lowercase hex characters are accepted, so the value can be placed
/// in the injected script without escaping.
fn bridge_token() -> Option<String> {
let token = std::env::var("WEFT_BRIDGE_TOKEN").ok()?;
(token.len() == 32
&& token
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.then_some(token)
}
/// The URL prefix covering the application's UI: the directory holding its
/// entry document.
fn ui_scope(entry: &ServoUrl) -> String {
let url = entry.as_str();
let end = url.rfind('/').map_or(url.len(), |slash| slash + 1);
url[..end].to_owned()
}
/// Whether `url` lies inside the UI directory `scope`. Encoded path
/// separators are refused, since a file loader may decode them into a path
/// that leaves the directory.
fn in_scope(url: &str, scope: &str) -> bool {
url.strip_prefix(scope).is_some_and(|rest| {
let rest = rest.to_ascii_lowercase();
!rest.contains("%2f") && !rest.contains("%5c")
})
}
impl WeftWebViewDelegate {
/// Whether an application page may load `url`: a file inside its UI
/// directory, also after resolving symbolic links, an inline (`data:`,
/// `blob:`) resource, `about:blank`, or the session bridge.
fn allows(&self, url: &ServoUrl) -> bool {
match url.scheme() {
"file" => {
in_scope(url.as_str(), &self.scope)
&& self.ui_dir.as_deref().is_some_and(|dir| {
url.to_file_path()
.ok()
.and_then(|path| path.canonicalize().ok())
.is_some_and(|path| path.starts_with(dir))
})
}
"data" | "blob" => true,
"about" => url.as_str() == "about:blank",
_ => url.as_str() == self.bridge,
}
}
}
/// The UI directory behind the URL prefix `scope`, with symbolic links
/// resolved.
fn ui_dir(scope: &str) -> Option<std::path::PathBuf> {
ServoUrl::parse(scope)
.ok()?
.to_file_path()
.ok()?
.canonicalize()
.ok()
}
/// `value` as a single-quoted JavaScript string literal.
fn js_string(value: &str) -> String {
let mut literal = String::with_capacity(value.len() + 2);
literal.push('\'');
for c in value.chars() {
match c {
' '..='~' if c != '\'' && c != '\\' => literal.push(c),
_ => literal.push_str(&format!("\\u{{{:x}}}", u32::from(c))),
}
}
literal.push('\'');
literal
}
/// The `window.weftIpc` bridge injected into the application document.
///
/// Servo runs user scripts in every document, frames included, so the bridge
/// installs itself only in a top-level document within the application's UI
/// directory `scope`. It authenticates as this session's application bridge and exchanges
/// `APP_MESSAGE` envelopes with weft-appd. `send` accepts a string or a
/// JSON-serialisable value; `onmessage` receives each payload string. The
/// credential stays inside the closure.
fn bridge_script(port: u16, session_id: u64, token: &str, scope: &str) -> String {
let scope = js_string(scope);
format!(
r#"(function () {{
var rest = location.href.indexOf({scope}) === 0 ? location.href.slice({scope}.length) : null;
if (window !== window.top || rest === null || /%2f|%5c/i.test(rest)) return;
var ws = new WebSocket('ws://127.0.0.1:{port}/app');
var queue = [];
var open = false;
function envelope(m) {{
return JSON.stringify({{ type: 'APP_MESSAGE', payload: typeof m === 'string' ? m : JSON.stringify(m) }});
}}
ws.onopen = function () {{
ws.send(JSON.stringify({{ type: 'HELLO', role: 'app', session_id: {session_id}, token: '{token}' }}));
open = true;
queue.forEach(function (m) {{ ws.send(envelope(m)); }});
queue.length = 0;
}};
ws.onmessage = function (e) {{
var msg;
try {{ msg = JSON.parse(e.data); }} catch (_) {{ return; }}
if (msg.type === 'APP_MESSAGE' && window.weftIpc.onmessage) window.weftIpc.onmessage(msg.payload);
}};
window.weftSessionId = {session_id};
window.weftIpc = {{
send: function (m) {{ if (open) ws.send(envelope(m)); else queue.push(m); }},
onmessage: null
}};
}})();"#
)
}
/// Servo preferences shared by the WEFT hosts.
fn host_preferences() -> servo::Preferences {
servo::Preferences {
// The system UI and application pages lay out with CSS Grid, which
// Servo disables by default.
layout_grid_enabled: true,
..Default::default()
}
}
// ── Rendering ───────────────────────────────────────────────────────────────
type BlitSurface = softbuffer::Surface<Arc<Window>, Arc<Window>>;
enum RenderingCtx {
Software(Rc<servo::SoftwareRenderingContext>),
/// Servo renders offscreen; each frame is read back and copied to the window.
Software {
context: Rc<servo::SoftwareRenderingContext>,
surface: BlitSurface,
},
/// Servo renders directly to the window's EGL surface.
Egl(Rc<servo::WindowRenderingContext>),
}
impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> {
fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(context) => Rc::clone(context) as Rc<dyn RenderingContext>,
}
}
/// Paints the webview into this context and presents the frame on the window.
fn paint_and_present(&mut self, webview: &servo::WebView) -> Result<(), String> {
match self {
Self::Software { context, surface } => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
let size = context.size();
let rect = DeviceIntRect::from_size(DeviceIntSize::new(
size.width as i32,
size.height as i32,
));
let image = context.read_to_image(rect);
context.present();
let image = image.ok_or("frame readback failed")?;
blit(surface, &image)
}
Self::Egl(context) => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
context.present();
Ok(())
}
}
}
}
/// Copies an RGBA frame into the window's software surface and presents it.
fn blit(surface: &mut BlitSurface, image: &RgbaImage) -> Result<(), String> {
let (width, height) = image.dimensions();
let (Some(w), Some(h)) = (NonZeroU32::new(width), NonZeroU32::new(height)) else {
return Ok(());
};
surface.resize(w, h).map_err(|e| format!("resize: {e}"))?;
let mut buffer = surface.buffer_mut().map_err(|e| format!("buffer: {e}"))?;
for (dst, src) in buffer.iter_mut().zip(image.as_raw().chunks_exact(4)) {
*dst = u32::from(src[0]) << 16 | u32::from(src[1]) << 8 | u32::from(src[2]);
}
buffer.present().map_err(|e| format!("present: {e}"))
}
/// Returns winit's `wl_display` and `wl_surface` pointers when running on Wayland.
fn wayland_handles(
event_loop: &ActiveEventLoop,
window: &Window,
) -> Option<(*mut std::ffi::c_void, *mut std::ffi::c_void)> {
let RawDisplayHandle::Wayland(display) = event_loop.display_handle().ok()?.as_raw() else {
return None;
};
let RawWindowHandle::Wayland(surface) = window.window_handle().ok()?.as_raw() else {
return None;
};
Some((display.display.as_ptr(), surface.surface.as_ptr()))
}
struct App {
@ -82,13 +394,17 @@ struct App {
servo: Option<servo::Servo>,
webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker,
shutting_down: bool,
ready_signalled: bool,
modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>,
cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>,
/// Whether the page is asked before its window closes.
ask_before_close: bool,
/// When the pending close request is closed regardless of the page.
close_deadline: Option<std::time::Instant>,
}
impl App {
@ -108,51 +424,124 @@ impl App {
servo: None,
webview: None,
rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
signals: Arc::default(),
waker,
shutting_down: false,
ready_signalled: false,
modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(),
cursor_pos: DevicePoint::origin(),
shell_client: None,
ask_before_close: close_policy_asks(),
close_deadline: None,
}
}
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) {
match ctx {
RenderingCtx::Software(rc) => Self::blit_software(window, rc),
RenderingCtx::Egl(_) => {}
/// Handles a request to close the window. Under the `ask` policy the
/// page answers first; otherwise, or without a page, the app closes.
fn request_close(&mut self, event_loop: &ActiveEventLoop) {
if self.close_deadline.is_some() {
return;
}
let Some(webview) = self.webview.as_ref().filter(|_| self.ask_before_close) else {
self.shut_down();
event_loop.exit();
return;
};
self.signals
.close_answer
.store(CloseAnswer::Pending as u8, Ordering::Relaxed);
self.close_deadline = Some(std::time::Instant::now() + CLOSE_ANSWER_TIMEOUT);
let signals = Arc::clone(&self.signals);
webview.evaluate_javascript(ASK_CLOSE_SCRIPT, move |result| {
// dispatchEvent returns false when the page cancelled the event.
let answer = match result {
Ok(servo::JSValue::Boolean(false)) => CloseAnswer::Cancel,
Ok(_) => CloseAnswer::Close,
Err(e) => {
tracing::warn!(?e, "the page could not be asked to close; closing");
CloseAnswer::Close
}
};
signals.close_answer.store(answer as u8, Ordering::Relaxed);
});
}
/// Acts on the page's answer to a pending close request, or on its
/// absence once the answer is due. Returns whether the app is closing.
fn settle_close_request(&mut self) -> bool {
let Some(deadline) = self.close_deadline else {
return false;
};
let answer = self.signals.close_answer.load(Ordering::Relaxed);
if answer == CloseAnswer::Cancel as u8 {
self.close_deadline = None;
tracing::info!("the page cancelled the close");
// weft-appd learns that the session keeps running; the token
// keeps page output from forging this report.
if let Ok(token) = std::env::var("WEFT_READY_TOKEN") {
use std::io::Write;
println!("CLOSE_CANCELLED {token}");
let _ = std::io::stdout().flush();
}
return false;
}
if answer == CloseAnswer::Close as u8 {
return true;
}
if std::time::Instant::now() >= deadline {
tracing::warn!("the page did not answer the close request in time; closing");
return true;
}
false
}
/// Paints and presents once Servo has requested its first repaint.
///
/// Nothing is presented before that request; the first frames can still be
/// blank or unstyled while the document loads. READY is printed after a
/// frame is presented once the document has loaded and its rendering has
/// settled.
fn render_frame(&mut self) {
if !self.signals.content.load(Ordering::Relaxed) {
return;
}
let (Some(webview), Some(context)) = (&self.webview, &mut self.rendering_context) else {
return;
};
if let Err(e) = context.paint_and_present(webview) {
tracing::warn!("frame not presented: {e}");
return;
}
if !self.ready_signalled && self.signals.settled.load(Ordering::Relaxed) {
self.ready_signalled = true;
println!("{}", ready_line());
use std::io::Write;
let _ = std::io::stdout().flush();
}
}
fn blit_software(window: &Arc<Window>, rendering_context: &servo::SoftwareRenderingContext) {
let size = window.inner_size();
let Some(pixels) = rendering_context.read_pixels() else {
return;
};
let Ok(ctx) = softbuffer::Context::new(Arc::clone(window)) else {
tracing::warn!("softbuffer context creation failed; skipping frame");
return;
};
let Ok(mut surface) = softbuffer::Surface::new(&ctx, Arc::clone(window)) else {
tracing::warn!("softbuffer surface creation failed; skipping frame");
return;
};
let _ = surface.resize(
std::num::NonZeroU32::new(size.width).unwrap_or(std::num::NonZeroU32::MIN),
std::num::NonZeroU32::new(size.height).unwrap_or(std::num::NonZeroU32::MIN),
);
let Ok(mut buf) = surface.buffer_mut() else {
return;
};
for (dst, src) in buf.iter_mut().zip(pixels.chunks(4)) {
*dst = u32::from_be_bytes([0, src[0], src[1], src[2]]);
}
let _ = buf.present();
/// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
fn shut_down(&mut self) {
self.shutting_down = true;
self.webview = None;
self.servo = None;
}
}
impl ApplicationHandler<ServoWake> for App {
/// Releases everything that holds Wayland objects of winit's display
/// (Servo, the rendering context, whose software and EGL paths keep
/// their own proxies on it, the shell protocol client and the window)
/// while that display is still connected; dropped after the event loop,
/// they would be destroyed on a display that is gone. A panic unwinding
/// out of a handler skips this.
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
self.shut_down();
self.rendering_context = None;
self.shell_client = None;
self.window = None;
}
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
@ -171,23 +560,22 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size();
self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() {
if let (Some(disp), Some(surf)) =
(event_loop.wayland_display(), window.wayland_surface())
{
match crate::shell_client::ShellClient::connect_as_app_with_display(
&self.app_id,
self.session_id,
disp,
surf,
) {
Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
if self.shell_client.is_none()
&& let Some((disp, surf)) = wayland_handles(event_loop, &window)
{
match crate::shell_client::ShellClient::connect_as_app_with_display(
&self.app_id,
self.session_id,
disp,
surf,
) {
Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
}
let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone()))
.build();
@ -203,31 +591,30 @@ impl ApplicationHandler<ServoWake> for App {
if let Some(kit_js) = load_ui_kit_script() {
ucm.add_script(Rc::new(UserScript::new(kit_js, None)));
}
let bridge_js = format!(
r#"(function(){{var ws=new WebSocket('ws://127.0.0.1:{p}');var sid={sid};var q=[];var r=false;ws.onopen=function(){{r=true;q.forEach(function(m){{ws.send(JSON.stringify(m))}});q.length=0}};window.weftSessionId=sid;window.weftIpc={{send:function(m){{if(r)ws.send(JSON.stringify(m));else q.push(m)}},onmessage:null}};ws.onmessage=function(e){{if(window.weftIpc.onmessage)window.weftIpc.onmessage(JSON.parse(e.data))}}}})()"#,
p = self.ws_port,
sid = self.session_id,
);
ucm.add_script(Rc::new(UserScript::new(bridge_js, None)));
match bridge_token() {
Some(token) => ucm.add_script(Rc::new(UserScript::new(
bridge_script(self.ws_port, self.session_id, &token, &ui_scope(&self.url)),
None,
))),
None => {
tracing::warn!("WEFT_BRIDGE_TOKEN missing or malformed; app messaging disabled")
}
}
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested),
signals: Arc::clone(&self.signals),
scope: ui_scope(&self.url),
ui_dir: ui_dir(&ui_scope(&self.url)),
bridge: format!("http://127.0.0.1:{}/app", self.ws_port),
}))
.user_content_manager(ucm)
.url(self.url.clone())
.url(self.url.clone().into_url())
.build();
self.servo = Some(servo);
self.webview = Some(webview);
self.rendering_context = Some(rendering_context);
if !self.ready_signalled {
self.ready_signalled = true;
println!("READY");
use std::io::Write;
let _ = std::io::stdout().flush();
}
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: ServoWake) {
@ -241,28 +628,37 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit();
return;
}
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() {
Ok(false) => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Ok(false) => compositor_closed = true,
Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {}
}
}
if compositor_closed {
self.shut_down();
event_loop.exit();
return;
}
if let Some(servo) = &self.servo {
servo.spin_event_loop();
}
if self
.redraw_requested
.swap(false, std::sync::atomic::Ordering::Relaxed)
// The page answers a close request while Servo spins.
if self.signals.page_closed.load(Ordering::Relaxed) || self.settle_close_request() {
self.shut_down();
event_loop.exit();
return;
}
// Wake for the close answer's deadline even when nothing else happens.
event_loop.set_control_flow(match self.close_deadline {
Some(deadline) => winit::event_loop::ControlFlow::WaitUntil(deadline),
None => winit::event_loop::ControlFlow::Wait,
});
if self.signals.redraw.swap(false, Ordering::Relaxed)
&& let Some(w) = &self.window
{
if let Some(w) = &self.window {
w.request_redraw();
}
w.request_redraw();
}
}
@ -273,18 +669,13 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent,
) {
match event {
WindowEvent::RedrawRequested => {
if let (Some(window), Some(servo)) = (&self.window, &self.servo) {
if let Some(rc) = &self.rendering_context {
Self::render_frame(window, rc);
}
servo.spin_event_loop();
}
}
WindowEvent::RedrawRequested => self.render_frame(),
WindowEvent::Resized(new_size) => {
let sz = servo::euclid::Size2D::new(new_size.width, new_size.height);
if new_size.width == 0 || new_size.height == 0 {
return;
}
if let Some(wv) = &self.webview {
wv.resize(sz);
wv.resize(new_size);
}
}
WindowEvent::ModifiersChanged(mods) => {
@ -297,10 +688,11 @@ impl ApplicationHandler<ServoWake> for App {
}
}
WindowEvent::CursorMoved { position, .. } => {
let pt = servo::euclid::default::Point2D::new(position.x as f32, position.y as f32);
let pt = DevicePoint::new(position.x as f32, position.y as f32);
self.cursor_pos = pt;
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt)));
let _ = wv
.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt.into())));
}
}
WindowEvent::MouseInput { state, button, .. } => {
@ -311,24 +703,18 @@ impl ApplicationHandler<ServoWake> for App {
_ => return,
};
let action = match state {
ElementState::Pressed => MouseButtonAction::Click,
ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up,
};
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action,
btn,
self.cursor_pos.cast_unit(),
self.cursor_pos.into(),
)));
}
}
WindowEvent::CloseRequested => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
event_loop.exit();
}
WindowEvent::CloseRequested => self.request_close(event_loop),
_ => {}
}
}
@ -337,7 +723,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx(
event_loop: &ActiveEventLoop,
window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>,
size: PhysicalSize<u32>,
) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle();
@ -349,16 +735,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc)));
}
Err(e) => {
tracing::warn!("EGL rendering context failed ({e}), falling back to software");
tracing::warn!(
"EGL rendering context failed ({e:?}), falling back to software"
);
}
}
}
}
match servo::SoftwareRenderingContext::new(servo::euclid::Size2D::new(size.width, size.height))
{
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
let context = match servo::SoftwareRenderingContext::new(size) {
Ok(rc) => Rc::new(rc),
Err(e) => {
tracing::error!("SoftwareRenderingContext failed: {e}");
tracing::error!("SoftwareRenderingContext failed: {e:?}");
return None;
}
};
let surface = softbuffer::Context::new(Arc::clone(window))
.and_then(|display| softbuffer::Surface::new(&display, Arc::clone(window)));
match surface {
Ok(surface) => Some(RenderingCtx::Software { context, surface }),
Err(e) => {
tracing::error!("software presentation surface failed: {e}");
None
}
}
@ -388,73 +784,17 @@ fn resolve_weft_system_url(url: &ServoUrl) -> Option<ServoUrl> {
ServoUrl::parse(&format!("file://{}", file.display())).ok()
}
fn read_ui_entry(app_id: &str) -> Option<String> {
#[derive(serde::Deserialize)]
struct Ui {
entry: String,
}
#[derive(serde::Deserialize)]
struct Manifest {
ui: Ui,
}
let erofs_manifest = std::path::Path::new("/run/weft/apps")
.join(app_id)
.join("merged")
.join("wapp.toml");
let toml_text = std::fs::read_to_string(&erofs_manifest).ok().or_else(|| {
app_store_roots()
.into_iter()
.find_map(|r| std::fs::read_to_string(r.join(app_id).join("wapp.toml")).ok())
})?;
let m: Manifest = toml::from_str(&toml_text).ok()?;
Some(m.ui.entry)
}
fn resolve_app_file_path(app_id: &str, rel: &str) -> Option<std::path::PathBuf> {
let erofs_root = std::path::Path::new("/run/weft/apps")
.join(app_id)
.join("merged");
if erofs_root.exists() {
let p = erofs_root.join(rel);
if p.exists() {
return Some(p);
}
}
app_store_roots()
.into_iter()
.map(|r| r.join(app_id).join(rel))
.find(|p| p.exists())
}
fn resolve_weft_app_url(app_id: &str) -> Option<ServoUrl> {
let entry = read_ui_entry(app_id).unwrap_or_else(|| "ui/index.html".to_owned());
let file_path = resolve_app_file_path(app_id, &entry)?;
let s = format!("file://{}", file_path.display());
ServoUrl::parse(&s).ok()
}
fn app_store_roots() -> Vec<PathBuf> {
if let Ok(v) = std::env::var("WEFT_APP_STORE") {
return vec![PathBuf::from(v)];
}
let mut roots = Vec::new();
if let Ok(home) = std::env::var("HOME") {
roots.push(
PathBuf::from(home)
.join(".local")
.join("share")
.join("weft")
.join("apps"),
);
}
roots.push(PathBuf::from("/usr/share/weft/apps"));
roots
}
pub fn run(app_id: &str, session_id: u64, ws_port: u16) -> anyhow::Result<()> {
let url = resolve_weft_app_url(app_id)
.ok_or_else(|| anyhow::anyhow!("no ui/index.html found for app {app_id}"))?;
/// Shows the UI document `ui` of `app_id`, the file weft-appd resolved from
/// the package; the shell never looks for the package itself.
pub fn run(
app_id: &str,
session_id: u64,
ws_port: u16,
ui: &std::path::Path,
) -> anyhow::Result<()> {
let url = ServoUrl::from_file_path(ui)
.map_err(|_| anyhow::anyhow!("{} is not an absolute path", ui.display()))?;
tracing::info!(%app_id, %url, "showing application UI");
let event_loop = EventLoop::<ServoWake>::with_user_event()
.build()

View file

@ -1,5 +1,3 @@
#![cfg(feature = "servo-embed")]
use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use winit::event::ElementState;
use winit::keyboard::{Key as WinitKey, KeyLocation, ModifiersState, NamedKey, PhysicalKey};
@ -14,10 +12,11 @@ pub fn keyboard_event_from_winit(
};
let key = match &event.logical_key {
WinitKey::Named(NamedKey::Space) => Key::Character(" ".to_string()),
WinitKey::Named(n) => Key::Named(named_key(*n)),
WinitKey::Character(c) => Key::Character(c.to_string().into()),
WinitKey::Unidentified(_) => Key::Unidentified,
WinitKey::Dead(c) => Key::Dead(*c),
WinitKey::Character(c) => Key::Character(c.to_string()),
WinitKey::Unidentified(_) => Key::Named(servo::NamedKey::Unidentified),
WinitKey::Dead(_) => Key::Named(servo::NamedKey::Dead),
};
let code = match event.physical_key {
@ -46,15 +45,7 @@ pub fn keyboard_event_from_winit(
mods |= Modifiers::META;
}
KeyboardEvent {
state,
key,
code,
location,
modifiers: mods,
repeat: event.repeat,
is_composing: false,
}
KeyboardEvent::new_without_event(state, key, code, location, mods, event.repeat, false)
}
fn named_key(n: NamedKey) -> servo::NamedKey {
@ -66,7 +57,8 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::Control => S::Control,
NamedKey::Fn => S::Fn,
NamedKey::FnLock => S::FnLock,
NamedKey::Meta => S::Meta,
// winit names the Super keys Super; the DOM names them Meta.
NamedKey::Meta | NamedKey::Super => S::Meta,
NamedKey::NumLock => S::NumLock,
NamedKey::ScrollLock => S::ScrollLock,
NamedKey::Shift => S::Shift,
@ -74,7 +66,6 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::SymbolLock => S::SymbolLock,
NamedKey::Enter => S::Enter,
NamedKey::Tab => S::Tab,
NamedKey::Space => S::Space,
NamedKey::ArrowDown => S::ArrowDown,
NamedKey::ArrowLeft => S::ArrowLeft,
NamedKey::ArrowRight => S::ArrowRight,

View file

@ -11,26 +11,33 @@ mod keyutils;
use anyhow::Context;
fn main() -> anyhow::Result<()> {
// Standard output carries the readiness line to weft-appd, which keeps
// standard error as the process's log.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
const USAGE: &str = "usage: weft-app-shell <app_id> <session_id> --ui <path>";
let mut args = std::env::args().skip(1);
let app_id = args
.next()
.context("usage: weft-app-shell <app_id> <session_id>")?;
let app_id = args.next().context(USAGE)?;
let session_id: u64 = args
.next()
.context("usage: weft-app-shell <app_id> <session_id>")?
.context(USAGE)?
.parse()
.context("session_id must be a number")?;
let ui = match (args.next().as_deref(), args.next(), args.next()) {
(Some("--ui"), Some(path), None) => std::path::PathBuf::from(path),
_ => anyhow::bail!(USAGE),
};
let ws_port = appd_ws_port();
embed_app(&app_id, session_id, ws_port)
embed_app(&app_id, session_id, ws_port, &ui)
}
fn appd_ws_port() -> u16 {
@ -50,17 +57,18 @@ fn appd_ws_port() -> u16 {
7410
}
fn embed_app(app_id: &str, session_id: u64, ws_port: u16) -> anyhow::Result<()> {
fn embed_app(
app_id: &str,
session_id: u64,
ws_port: u16,
ui: &std::path::Path,
) -> anyhow::Result<()> {
#[cfg(feature = "servo-embed")]
return embedder::run(app_id, session_id, ws_port);
return embedder::run(app_id, session_id, ws_port, ui);
#[cfg(not(feature = "servo-embed"))]
{
let _ = (app_id, session_id, ws_port);
println!("READY");
use std::io::Write;
let _ = std::io::stdout().flush();
std::thread::park();
Ok(())
let _ = (app_id, session_id, ws_port, ui);
anyhow::bail!("weft-app-shell was built without the servo-embed feature and cannot render")
}
}

View file

@ -215,8 +215,4 @@ impl ShellClient {
self.event_queue.flush().context("Wayland flush")?;
Ok(!self.data.window_state.closed)
}
pub fn window_state(&self) -> &ShellWindowState {
&self.data.window_state
}
}

View file

@ -21,6 +21,7 @@ futures-util = { version = "0.3", default-features = false, features = ["sink",
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
libc = "0.2"
rustix = { version = "1", features = ["net"] }
[target.'cfg(unix)'.dependencies]
sd-notify = "0.4"

View file

@ -1,4 +1,7 @@
use std::os::fd::OwnedFd;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc;
@ -6,7 +9,39 @@ use weft_ipc_types::{
AppdToCompositor, CompositorToAppd, MAX_FRAME_LEN, frame_decode, frame_encode,
};
pub type CompositorSender = mpsc::Sender<AppdToCompositor>;
/// A message for the compositor and the file descriptor it carries, if any.
pub struct Outbound {
pub msg: AppdToCompositor,
pub fd: Option<OwnedFd>,
}
impl From<AppdToCompositor> for Outbound {
fn from(msg: AppdToCompositor) -> Self {
Self { msg, fd: None }
}
}
/// Queues messages for the compositor and tells whether it is connected.
#[derive(Clone)]
pub struct CompositorSender {
tx: mpsc::Sender<Outbound>,
connected: Arc<AtomicBool>,
}
impl CompositorSender {
pub fn new(tx: mpsc::Sender<Outbound>, connected: Arc<AtomicBool>) -> Self {
Self { tx, connected }
}
/// Whether the compositor IPC connection is currently up.
pub fn is_connected(&self) -> bool {
self.connected.load(Ordering::Acquire)
}
pub fn try_send(&self, outbound: Outbound) -> Result<(), Outbound> {
self.tx.try_send(outbound).map_err(|e| e.into_inner())
}
}
/// Resolve the compositor IPC socket path.
///
@ -24,17 +59,24 @@ pub fn socket_path() -> Option<PathBuf> {
/// Spawn the compositor IPC client task and return a sender for outbound messages.
///
/// The task connects to `socket_path`, retrying every 2 s on failure. If the
/// connection drops while sending, it waits 500 ms then reconnects. Incoming
/// `CompositorToAppd` frames are decoded and logged; no behavioural action is
/// taken yet (surface lifecycle hookup happens in a later task).
/// The task connects to `socket_path`, retrying every 2 s on failure. When
/// the connection drops, whether noticed by a failed write or by the
/// compositor closing it, it waits 500 ms and reconnects; a message whose
/// write failed is sent again on the new connection. Incoming
/// `CompositorToAppd` frames are decoded and logged.
pub fn spawn(socket_path: PathBuf) -> CompositorSender {
let (tx, rx) = mpsc::channel::<AppdToCompositor>(32);
tokio::spawn(run_client(socket_path, rx));
tx
let (tx, rx) = mpsc::channel::<Outbound>(32);
let connected = Arc::new(AtomicBool::new(false));
tokio::spawn(run_client(socket_path, rx, connected.clone()));
CompositorSender::new(tx, connected)
}
async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<AppdToCompositor>) {
async fn run_client(
socket_path: PathBuf,
mut rx: mpsc::Receiver<Outbound>,
connected: Arc<AtomicBool>,
) {
let mut unsent: Option<Outbound> = None;
loop {
let stream = loop {
match tokio::net::UnixStream::connect(&socket_path).await {
@ -49,28 +91,85 @@ async fn run_client(socket_path: PathBuf, mut rx: mpsc::Receiver<AppdToComposito
};
let (read_half, mut write_half) = stream.into_split();
tokio::spawn(read_unix_incoming(read_half));
let mut reader = tokio::spawn(read_unix_incoming(read_half));
connected.store(true, Ordering::Release);
loop {
let Some(msg) = rx.recv().await else {
return;
};
match frame_encode(&msg) {
Ok(frame) => {
if write_half.write_all(&frame).await.is_err() {
tracing::warn!("compositor IPC write failed; reconnecting");
let outbound = match unsent.take() {
Some(outbound) => outbound,
None => tokio::select! {
next = rx.recv() => match next {
Some(outbound) => outbound,
None => return,
},
_ = &mut reader => {
tracing::warn!("compositor closed the IPC connection; reconnecting");
break;
}
},
};
let frame = match frame_encode(&outbound.msg) {
Ok(frame) => frame,
Err(e) => {
tracing::warn!(?e, "compositor IPC encode error");
continue;
}
Err(e) => tracing::warn!(?e, "compositor IPC encode error"),
};
if send_frame(&mut write_half, &frame, outbound.fd.as_ref())
.await
.is_err()
{
tracing::warn!("compositor IPC write failed; reconnecting");
unsent = Some(outbound);
break;
}
}
connected.store(false, Ordering::Release);
reader.abort();
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}
}
/// Writes `frame`, attaching `fd` to its first bytes so the compositor
/// receives the descriptor together with the message it belongs to.
async fn send_frame(
stream: &mut tokio::net::unix::OwnedWriteHalf,
frame: &[u8],
fd: Option<&OwnedFd>,
) -> std::io::Result<()> {
use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg};
use std::mem::MaybeUninit;
use std::os::fd::AsFd;
let Some(fd) = fd else {
return stream.write_all(frame).await;
};
let socket: &tokio::net::UnixStream = stream.as_ref();
let sent = loop {
socket.writable().await?;
let result = socket.try_io(tokio::io::Interest::WRITABLE, || {
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut control = SendAncillaryBuffer::new(&mut space);
let fds = [fd.as_fd()];
control.push(SendAncillaryMessage::ScmRights(&fds));
sendmsg(
socket,
&[std::io::IoSlice::new(frame)],
&mut control,
SendFlags::NOSIGNAL,
)
.map_err(std::io::Error::from)
});
match result {
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
other => break other?,
}
};
// The descriptor travelled with the first bytes; the rest of a partly
// sent frame follows as plain data.
stream.write_all(&frame[sent..]).await
}
async fn read_unix_incoming(mut reader: tokio::net::unix::OwnedReadHalf) {
use tokio::io::AsyncReadExt;
@ -110,8 +209,8 @@ fn handle_incoming(msg: CompositorToAppd) {
CompositorToAppd::SurfaceReady { session_id } => {
tracing::debug!(session_id, "SurfaceReady from compositor");
}
CompositorToAppd::ClientDisconnected { pid } => {
tracing::debug!(pid, "ClientDisconnected from compositor");
CompositorToAppd::ClientDisconnected { session_id } => {
tracing::debug!(session_id, "ClientDisconnected from compositor");
}
}
}

View file

@ -0,0 +1,468 @@
//! Effective grants for a session, derived once from the package manifest.
//!
//! Every capability the package declares must be understood and satisfiable
//! by this host, or the session does not start. The result is passed to
//! weft-runtime explicitly (`--preopen`, `--grant`) and to the file portal;
//! neither reads the manifest itself.
use std::path::{Path, PathBuf};
use weft_ipc_types::capability::{Access, Capability};
/// A host directory made visible to the component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GrantedDir {
pub host: PathBuf,
pub guest: &'static str,
pub access: Access,
}
impl GrantedDir {
/// The `--preopen` argument for weft-runtime.
pub fn preopen_arg(&self) -> String {
let mode = match self.access {
Access::Read => "ro",
Access::ReadWrite => "rw",
};
format!("{}::{}::{mode}", self.host.display(), self.guest)
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct SessionGrants {
pub dirs: Vec<GrantedDir>,
/// Host-import capabilities, passed as `--grant`.
pub imports: Vec<Capability>,
}
/// Why a launch is refused, with the error code reported to the client:
/// 400 for a malformed app ID, 404 for a package that is not installed, 403
/// for a package this host will not run as declared, 409 for app data the
/// user must reconcile and 500 for a host fault.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Refusal {
pub code: u32,
pub message: String,
}
impl Refusal {
pub(crate) fn new(code: u32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
}
/// Where the host resources behind filesystem capabilities live.
pub(crate) struct HostDirs {
/// The user's data home (`$XDG_DATA_HOME`); app data lives under it in
/// `weft/app-data/<id>`, apart from installed packages.
pub data_home: PathBuf,
/// The home directory, under which earlier versions kept app data.
pub home: PathBuf,
/// The user's documents directory, if the platform configures one.
pub documents: Option<PathBuf>,
}
impl HostDirs {
pub fn from_env() -> Result<Self, Refusal> {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
.ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?;
// The XDG base directory specification ignores relative values.
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.unwrap_or_else(|| home.join(".config"));
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
Refusal::new(500, "no data home: XDG_DATA_HOME and HOME are unusable")
})?;
Ok(Self {
data_home,
documents: documents_dir(&home, &config),
home,
})
}
}
/// Parses the declared capabilities, refusing unknown ones and those this
/// host does not support, without touching the host.
pub(crate) fn validate(declared: &[String]) -> Result<Vec<Capability>, Refusal> {
let mut capabilities = Vec::new();
for text in declared {
let capability: Capability =
text.parse()
.map_err(|e: weft_ipc_types::capability::UnknownCapability| {
Refusal::new(403, e.to_string())
})?;
if matches!(capability, Capability::GpuCompute | Capability::GpuRender) {
return Err(Refusal::new(
403,
format!("{capability} is not supported by this host"),
));
}
capabilities.push(capability);
}
Ok(capabilities)
}
/// Derives grants for the declared capabilities. Every capability is
/// checked before host directories are resolved or the app's data
/// directory is created, so a refused launch leaves nothing behind.
pub(crate) fn derive(
app_id: &str,
declared: &[String],
host_dirs: impl FnOnce() -> Result<HostDirs, Refusal>,
) -> Result<SessionGrants, Refusal> {
let capabilities = validate(declared)?;
let mut grants = SessionGrants::default();
let needs_dirs = capabilities
.iter()
.any(|c| matches!(c, Capability::AppData(_) | Capability::Documents(_)));
let host = if needs_dirs { Some(host_dirs()?) } else { None };
for capability in capabilities {
match (&capability, &host) {
(Capability::AppData(access), Some(host)) => {
let dir = weft_ipc_types::package::app_data_dir(&host.data_home, app_id);
grant_dir(&mut grants, dir, "/data", *access)?;
}
(Capability::Documents(access), Some(host)) => {
let dir = host.documents.clone().ok_or_else(|| {
Refusal::new(
403,
format!("{capability} requested, but no documents directory is configured"),
)
})?;
grant_dir(&mut grants, dir, "/xdg/documents", *access)?;
}
_ => {
if !grants.imports.contains(&capability) {
grants.imports.push(capability);
}
}
}
}
if let (Some(dir), Some(host)) = (grants.dirs.iter().find(|d| d.guest == "/data"), &host) {
prepare_app_data(app_id, &dir.host, host)?;
}
Ok(grants)
}
/// Creates the app's data directory, first moving data an earlier version
/// kept inside the user package store, and makes it private. A conflict
/// between the two locations refuses the launch (409) and leaves both
/// untouched.
fn prepare_app_data(app_id: &str, dir: &Path, host: &HostDirs) -> Result<(), Refusal> {
use weft_ipc_types::package::{
Migration, MigrationError, legacy_app_data_dir, migrate_app_data,
};
let legacy = legacy_app_data_dir(&host.home, app_id);
match migrate_app_data(&legacy, dir) {
Ok(Migration::Moved) => {
tracing::info!(%app_id, from = %legacy.display(), to = %dir.display(), "app data moved");
}
Ok(Migration::NotNeeded) => {}
Err(e @ MigrationError::Conflict { .. }) => return Err(Refusal::new(409, e.to_string())),
Err(MigrationError::Io(e)) => {
return Err(Refusal::new(
500,
format!(
"cannot move app data from {} to {}: {e}",
legacy.display(),
dir.display()
),
));
}
Err(e) => return Err(Refusal::new(500, e.to_string())),
}
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder
.create(dir)
.and_then(|()| weft_ipc_types::package::make_private(dir))
.map_err(|e| Refusal::new(500, format!("cannot prepare {}: {e}", dir.display())))
}
/// Adds a directory grant; declaring both modes for one directory grants the
/// wider one. The host path must survive the `--preopen HOST::GUEST::MODE`
/// encoding unchanged: it must be UTF-8 and must not contain `::`.
fn grant_dir(
grants: &mut SessionGrants,
host: PathBuf,
guest: &'static str,
access: Access,
) -> Result<(), Refusal> {
if host.to_str().is_none_or(|path| path.contains("::")) {
return Err(Refusal::new(
403,
format!("{} cannot be granted to a session", host.display()),
));
}
match grants.dirs.iter_mut().find(|dir| dir.guest == guest) {
Some(existing) => {
if access == Access::ReadWrite {
existing.access = Access::ReadWrite;
}
}
None => grants.dirs.push(GrantedDir {
host,
guest,
access,
}),
}
Ok(())
}
/// The documents directory from the XDG user directories configuration
/// (`user-dirs.dirs`), or None when it is not configured, is disabled (set
/// to the home directory) or does not exist. Values are `"$HOME/path"` or
/// `"/absolute/path"`; the last assignment wins, as when the file is sourced
/// by a shell. Values with escapes are not interpreted and are ignored.
fn documents_dir(home: &Path, config: &Path) -> Option<PathBuf> {
let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?;
let value = text
.lines()
.filter_map(|line| line.trim().strip_prefix("XDG_DOCUMENTS_DIR="))
.next_back()?
.trim();
let value = value.strip_prefix('"')?.strip_suffix('"')?;
if value.contains('\\') || value.contains('"') {
return None;
}
let dir = match value.strip_prefix("$HOME") {
Some("") => home.to_path_buf(),
Some(rest) => home.join(rest.strip_prefix('/')?),
None => PathBuf::from(value),
};
(dir.is_absolute() && dir != home && dir.is_dir()).then_some(dir)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_grants_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn host(root: &Path, documents: Option<PathBuf>) -> impl FnOnce() -> Result<HostDirs, Refusal> {
let root = root.to_path_buf();
move || {
Ok(HostDirs {
data_home: root.join("share"),
home: root.join("home"),
documents,
})
}
}
fn no_host() -> Result<HostDirs, Refusal> {
Err(Refusal::new(500, "HOME is not set to an absolute path"))
}
fn caps(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn no_capabilities_grant_nothing_and_need_no_home() {
let grants = derive("org.example.app", &[], no_host).unwrap();
assert_eq!(grants, SessionGrants::default());
let grants = derive("org.example.app", &caps(&["sys:notifications"]), no_host).unwrap();
assert_eq!(grants.imports, [Capability::Notifications]);
assert_eq!(
derive("org.example.app", &caps(&["fs:rw:app-data"]), no_host)
.unwrap_err()
.code,
500
);
}
#[test]
fn data_access_modes_stay_distinct() {
let root = temp("modes");
let read = derive(
"org.example.app",
&caps(&["fs:read:app-data"]),
host(&root, None),
)
.unwrap();
assert_eq!(read.dirs[0].access, Access::Read);
assert!(read.dirs[0].preopen_arg().ends_with("::/data::ro"));
assert!(root.join("share/weft/app-data/org.example.app").is_dir());
let both = derive(
"org.example.app",
&caps(&["fs:read:app-data", "fs:rw:app-data"]),
host(&root, None),
)
.unwrap();
assert_eq!(both.dirs.len(), 1);
assert_eq!(both.dirs[0].access, Access::ReadWrite);
}
#[test]
fn imports_are_listed_once() {
let root = temp("imports");
let grants = derive(
"org.example.app",
&caps(&[
"sys:notifications",
"net:fetch:api.example.org",
"sys:notifications",
]),
host(&root, None),
)
.unwrap();
let listed: Vec<String> = grants.imports.iter().map(|c| c.to_string()).collect();
assert_eq!(listed, ["sys:notifications", "net:fetch:api.example.org"]);
assert!(grants.dirs.is_empty());
}
#[test]
fn refused_launches_create_nothing() {
let root = temp("fail");
for declared in [
&["sys:everything"][..],
&["hw:gpu:compute"],
&["fs:read:xdg-documents"],
&["fs:rw:app-data", "hw:gpu:render"],
&["fs:rw:app-data", "fs:read:xdg-documents"],
] {
let refusal =
derive("org.example.app", &caps(declared), host(&root, None)).unwrap_err();
assert_eq!(refusal.code, 403, "{declared:?}");
}
assert!(!root.join("share").exists());
}
#[test]
fn paths_that_cannot_be_encoded_are_refused() {
let root = temp("encode");
let odd = root.join("a::b");
std::fs::create_dir_all(&odd).unwrap();
let refusal = derive(
"org.example.app",
&caps(&["fs:read:xdg-documents"]),
host(&root, Some(odd)),
)
.unwrap_err();
assert_eq!(refusal.code, 403);
}
#[test]
fn documents_come_from_user_dirs() {
let home = temp("home");
let config = home.join(".config");
std::fs::create_dir_all(home.join("Docs")).unwrap();
std::fs::create_dir_all(home.join("Later")).unwrap();
std::fs::create_dir_all(&config).unwrap();
assert_eq!(documents_dir(&home, &config), None);
let write = |text: &str| std::fs::write(config.join("user-dirs.dirs"), text).unwrap();
write("# comment\nXDG_DOCUMENTS_DIR=\"$HOME/Docs\"\n");
assert_eq!(documents_dir(&home, &config), Some(home.join("Docs")));
write("XDG_DOCUMENTS_DIR=\"$HOME/Docs\"\nXDG_DOCUMENTS_DIR=\"$HOME/Later\"\n");
assert_eq!(documents_dir(&home, &config), Some(home.join("Later")));
let absolute = format!("XDG_DOCUMENTS_DIR=\"{}\"\n", home.join("Docs").display());
write(&absolute);
assert_eq!(documents_dir(&home, &config), Some(home.join("Docs")));
// Disabled, missing, relative, escaped and malformed values.
for text in [
"XDG_DOCUMENTS_DIR=\"$HOME/\"\n",
"XDG_DOCUMENTS_DIR=\"$HOME\"\n",
"XDG_DOCUMENTS_DIR=\"$HOME/Missing\"\n",
"XDG_DOCUMENTS_DIR=\"$HOMEDocs\"\n",
"XDG_DOCUMENTS_DIR=\"Docs\"\n",
"XDG_DOCUMENTS_DIR=\"$HOME/Do\\\"cs\"\n",
"XDG_DOCUMENTS_DIR=$HOME/Docs\n",
] {
write(text);
assert_eq!(documents_dir(&home, &config), None, "{text:?}");
}
let grants = derive(
"org.example.app",
&caps(&["fs:rw:xdg-documents"]),
host(&home, Some(home.join("Docs"))),
)
.unwrap();
assert_eq!(grants.dirs[0].guest, "/xdg/documents");
assert_eq!(grants.dirs[0].access, Access::ReadWrite);
}
#[test]
fn earlier_app_data_is_moved_on_launch() {
let root = temp("migrate");
let legacy = root.join("home/.local/share/weft/apps/org.example.app/data");
std::fs::create_dir_all(&legacy).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&legacy, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(legacy.join("notes.txt"), "kept").unwrap();
let grants = derive(
"org.example.app",
&caps(&["fs:rw:app-data"]),
host(&root, None),
)
.unwrap();
let data = root.join("share/weft/app-data/org.example.app");
assert_eq!(grants.dirs[0].host, data);
assert_eq!(
std::fs::read_to_string(data.join("notes.txt")).unwrap(),
"kept"
);
assert!(!legacy.exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&data).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o700);
}
}
#[test]
fn conflicting_app_data_refuses_the_launch() {
let root = temp("conflict");
let legacy = root.join("home/.local/share/weft/apps/org.example.app/data");
let data = root.join("share/weft/app-data/org.example.app");
std::fs::create_dir_all(&legacy).unwrap();
std::fs::create_dir_all(&data).unwrap();
let refusal = derive(
"org.example.app",
&caps(&["fs:read:app-data"]),
host(&root, None),
)
.unwrap_err();
assert_eq!(refusal.code, 409);
assert!(legacy.is_dir() && data.is_dir());
}
#[cfg(unix)]
#[test]
fn app_data_is_private() {
use std::os::unix::fs::PermissionsExt;
let root = temp("private");
derive(
"org.example.app",
&caps(&["fs:rw:app-data"]),
host(&root, None),
)
.unwrap();
let mode = std::fs::metadata(root.join("share/weft/app-data/org.example.app"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o700);
}
}

View file

@ -8,8 +8,16 @@ pub enum Request {
app_id: String,
surface_id: u64,
},
/// Asks a running session to close as a user close would, or with
/// `force`, terminates it without asking.
TerminateApp {
session_id: u64,
#[serde(default)]
force: bool,
},
/// Brings the session's window to the front with keyboard focus.
ActivateApp {
session_id: u64,
},
QueryRunning,
QueryAppState {
@ -211,10 +219,19 @@ mod tests {
#[test]
fn terminate_app_request_roundtrip() {
let req = Request::TerminateApp { session_id: 42 };
let req = Request::TerminateApp {
session_id: 42,
force: false,
};
let bytes = rmp_serde::to_vec(&req).unwrap();
let decoded: Request = rmp_serde::from_slice(&bytes).unwrap();
assert!(matches!(decoded, Request::TerminateApp { session_id: 42 }));
assert!(matches!(
decoded,
Request::TerminateApp {
session_id: 42,
force: false
}
));
}
#[test]

View file

@ -0,0 +1,787 @@
//! The package a session runs, resolved once before anything is started.
//!
//! The runtime and the app shell receive the exact files resolved here and
//! never look for the package themselves, so the component, the UI and the
//! capabilities a session is granted all come from the same package root.
//!
//! Before anything starts, the package must still be what its owner
//! installed: a package recorded as a publisher's must carry that
//! publisher's valid signature over its current content, and a package with
//! no record must be signed by a trusted key, which is then recorded as its
//! owner. Development content, recorded as such by `weft-pack install
//! --dev`, runs unverified.
use std::path::{Path, PathBuf};
use weft_ipc_types::manifest::{ClosePolicy, MANIFEST_FILE, Manifest, ManifestError, entry_path};
use weft_ipc_types::package::{ImageFiles, is_valid_app_id};
use weft_ipc_types::trust::{
Inventory, Owner, PublisherKey, TrustError, TrustStore, lock_owner, owner_record_path,
read_owner, read_signature, write_owner,
};
use crate::grants::Refusal;
use crate::mount::Mount;
pub(crate) struct LaunchPackage {
pub(crate) app_id: String,
pub(crate) version: String,
pub(crate) root: PathBuf,
/// The Wasm component, from `[runtime].module`.
pub(crate) module: PathBuf,
/// The UI document, from `[ui].entry`.
pub(crate) ui_entry: PathBuf,
/// What a user close does, from `[ui].close`.
pub(crate) close: ClosePolicy,
pub(crate) capabilities: Vec<String>,
/// The image the package root is mounted from, held for as long as the
/// session runs.
pub(crate) image: Option<Mount>,
/// The lock that keeps an installed revision from being removed while
/// the session runs from it.
pub(crate) pin: Option<weft_ipc_types::store::Pin>,
}
/// Resolves `app_id` in the package stores.
pub(crate) fn resolve(app_id: &str) -> Result<LaunchPackage, Refusal> {
resolve_in(app_id, &crate::app_store_roots())
}
/// Resolves `app_id` in `stores`. A verified image in any store takes
/// precedence over a directory install in any store, so a writable user
/// directory cannot shadow a system image. When any image file is present
/// for the ID, the image must mount: a missing or damaged image never falls
/// back to a directory, which nothing verifies.
fn resolve_in(app_id: &str, stores: &[PathBuf]) -> Result<LaunchPackage, Refusal> {
use crate::mount::MountError;
if !is_valid_app_id(app_id) {
return Err(Refusal::new(400, "invalid app ID"));
}
if let Some(files) = stores
.iter()
.map(|store| ImageFiles::in_store(store, app_id))
.find(ImageFiles::any_present)
{
let image = crate::mount::mount(app_id, &files).map_err(|e| match e {
MountError::Invalid(e) => {
Refusal::new(403, format!("the verified image is invalid: {e}"))
}
MountError::Host(e) => {
Refusal::new(500, format!("the verified image cannot be mounted: {e}"))
}
})?;
let root = image.root().to_path_buf();
return from_root(app_id, root, Some(image));
}
// A store whose entry for the app cannot be used does not hide the app
// in a later store, as it does not in the list of installed apps; the
// first such problem is reported when no store has the app.
let mut unusable = None;
for store in stores {
let active = match weft_ipc_types::store::active(store, app_id) {
Ok(Some(active)) => active,
Ok(None) => continue,
Err(e) => {
tracing::warn!(app_id, error = %e, "package entry skipped");
unusable.get_or_insert(match e {
weft_ipc_types::store::StoreError::NotAPackage(_) => {
Refusal::new(403, e.to_string())
}
weft_ipc_types::store::StoreError::Io(..) => Refusal::new(500, e.to_string()),
});
continue;
}
};
let dir = active.dir().to_path_buf();
// A directory left with only app data by an earlier layout is not a
// package.
if std::fs::symlink_metadata(dir.join(MANIFEST_FILE)).is_err() {
continue;
}
// The session runs from the revision itself, not the link, so an
// update or rollback that switches the link while it runs leaves it
// on the bytes it started with. From here on a refusal is final: a
// package that is being changed, or that fails its checks, is not
// silently replaced by another store's copy.
let pin = weft_ipc_types::store::pin(&dir).map_err(|e| {
Refusal::new(
500,
format!("cannot hold {} while it runs: {e}", dir.display()),
)
})?;
let mut package = from_root(app_id, dir, None)?;
package.pin = Some(pin);
return Ok(package);
}
Err(unusable.unwrap_or_else(|| Refusal::new(404, format!("package {app_id} is not installed"))))
}
fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<LaunchPackage, Refusal> {
// The entries are checked inside `root`, so the root and its manifest
// must be the directory and file they appear to be, not links to
// something else.
let is_dir = std::fs::symlink_metadata(&root).is_ok_and(|m| m.file_type().is_dir());
let manifest_is_file =
std::fs::symlink_metadata(root.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file());
if !is_dir || !manifest_is_file {
return Err(Refusal::new(
403,
format!(
"{} must be a directory holding a regular {MANIFEST_FILE}, not a link",
root.display()
),
));
}
// The manifest is read once; the same bytes are parsed and checked
// against the signed inventory, so the capabilities and entries a
// session gets are the ones the owner signed.
let manifest_path = root.join(MANIFEST_FILE);
let manifest_bytes = std::fs::read(&manifest_path)
.map_err(|e| Refusal::new(500, format!("cannot read {}: {e}", manifest_path.display())))?;
let manifest = Manifest::parse(&manifest_path, &manifest_bytes).map_err(|e| match e {
ManifestError::Io(..) | ManifestError::Parse(..) => Refusal::new(403, e.to_string()),
})?;
if manifest.package.id != app_id {
return Err(Refusal::new(
403,
format!(
"the package in {} declares ID '{}'",
root.display(),
manifest.package.id
),
));
}
verify_owner(app_id, &root, &manifest_bytes)?;
let entry = |field: &str, value: &str| {
entry_path(&root, value).map_err(|e| Refusal::new(403, format!("{field}: {e}")))
};
let module = entry("runtime.module", &manifest.runtime.module)?;
let ui_entry = entry("ui.entry", &manifest.ui.entry)?;
Ok(LaunchPackage {
app_id: app_id.to_owned(),
version: manifest.package.version.clone(),
capabilities: manifest.capabilities().to_vec(),
module,
ui_entry,
close: manifest.ui.close,
root,
image,
pin: None,
})
}
/// Checks that the package at `root`, whose manifest was read as
/// `manifest_bytes`, is what its owner installed. A trusted package with no
/// owner record is recorded as its signer's on its first launch, so its app
/// data stays with that publisher; existing app data with no recorded owner
/// is not handed to whichever publisher launches first.
fn verify_owner(app_id: &str, root: &Path, manifest_bytes: &[u8]) -> Result<(), Refusal> {
// Errors in the host's trust store or owner records are the host's, not
// the package's.
let host = |e: TrustError| Refusal::new(500, e.to_string());
let package = |e: TrustError| match e {
TrustError::Io(..) => Refusal::new(500, e.to_string()),
_ => Refusal::new(403, e.to_string()),
};
let data_home = weft_ipc_types::package::data_home().ok_or_else(|| {
Refusal::new(
500,
"cannot locate the data home holding package owner records",
)
})?;
let record = owner_record_path(&data_home, app_id);
let owner = read_owner(&record).map_err(host)?;
if owner == Some(Owner::Development) {
return Ok(());
}
let trusted = TrustStore::load(&TrustStore::directories()).map_err(host)?;
let inventory = Inventory::read(root).map_err(package)?;
if !inventory.holds(MANIFEST_FILE, manifest_bytes) {
return Err(Refusal::new(
403,
format!("{} changed while it was checked", root.display()),
));
}
let digest = inventory.digest();
let signature = read_signature(root).map_err(package)?;
let signer = signature.and_then(|sig| trusted.signer_of(&digest, &sig));
match (owner, signer) {
(Some(Owner::Verified(key)), Some(signer)) if key == signer => Ok(()),
(Some(Owner::Verified(key)), _) => Err(Refusal::new(
403,
format!(
"{} is not signed by its owner, publisher {}, or that key is no longer \
trusted; the package was changed or its key was withdrawn",
root.display(),
key.to_hex()
),
)),
(_, None) => Err(Refusal::new(
403,
format!(
"{} has no recorded owner and is not signed by a trusted key; install it \
with weft-pack",
root.display()
),
)),
(_, Some(signer)) => record_first_owner(app_id, &data_home, &record, signer),
}
}
/// Records `signer` as the owner of `app_id` on the first launch of a trusted
/// package that has no owner record and no app data yet.
fn record_first_owner(
app_id: &str,
data_home: &Path,
record: &Path,
signer: PublisherKey,
) -> Result<(), Refusal> {
let host = |e: TrustError| Refusal::new(500, e.to_string());
let _lock = lock_owner(data_home, app_id).map_err(host)?;
match read_owner(record).map_err(host)? {
Some(Owner::Verified(key)) if key == signer => return Ok(()),
Some(existing) => {
return Err(Refusal::new(
403,
format!(
"{app_id} belongs to {existing}, not publisher {}",
signer.to_hex()
),
));
}
None => {}
}
// Data in the earlier layout counts: it would be moved to this app's
// data directory when the session starts.
let home = weft_ipc_types::package::home_dir()
.ok_or_else(|| Refusal::new(500, "HOME is not set to an absolute path"))?;
match weft_ipc_types::package::existing_app_data(data_home, &home, app_id) {
Err(e) => Err(Refusal::new(
500,
format!("cannot inspect the app data of {app_id}: {e}"),
)),
Ok(Some(data)) => Err(Refusal::new(
403,
format!(
"{} holds app data for {app_id} with no recorded owner, so it is not given to \
publisher {}. To give it to this publisher, install the package into the user \
store with weft-pack install --claim-data (uninstalling it there first); \
otherwise move the data aside",
data.display(),
signer.to_hex()
),
)),
Ok(None) => write_owner(record, Owner::Verified(signer)).map_err(host),
}
}
impl LaunchPackage {
/// A package for supervisor tests whose children ignore their files.
#[cfg(test)]
pub(crate) fn unresolved(app_id: &str) -> Self {
Self {
app_id: app_id.to_owned(),
version: "0.0.0".to_owned(),
root: PathBuf::from("/nonexistent"),
module: PathBuf::from("/nonexistent/app.wasm"),
ui_entry: PathBuf::from("/nonexistent/ui/index.html"),
close: ClosePolicy::Immediate,
capabilities: Vec::new(),
image: None,
pin: None,
}
}
pub(crate) fn root(&self) -> &Path {
&self.root
}
}
#[cfg(test)]
mod tests {
use super::*;
const ID: &str = "org.weft.test.resolve";
/// HOME as the test process found it, restored by `finish`.
static HOME_AT_START: std::sync::OnceLock<Option<std::ffi::OsString>> =
std::sync::OnceLock::new();
/// A store holding a directory install of `ID`, with WEFT_APP_STORE
/// pointing at it. Callers hold env_lock.
fn store(name: &str, manifest_id: &str, module: &str) -> PathBuf {
let store =
std::env::temp_dir().join(format!("weft_appd_launch_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&store);
let package = store.join(ID);
std::fs::create_dir_all(package.join("ui")).unwrap();
std::fs::write(package.join("app.wasm"), b"\0asm\x01\0\0\0").unwrap();
std::fs::write(package.join("ui/index.html"), b"<p>").unwrap();
std::fs::write(
package.join(MANIFEST_FILE),
format!(
"[package]\nid = \"{manifest_id}\"\nname = \"T\"\nversion = \"1.2.3\"\n\
capabilities = [\"sys:notifications\"]\n\
[runtime]\nmodule = \"{module}\"\n[ui]\nentry = \"ui/index.html\"\n"
),
)
.unwrap();
// The fixture is unsigned development content, recorded as such.
weft_ipc_types::trust::write_owner(
&owner_record_path(&store.join("share"), ID),
Owner::Development,
)
.unwrap();
HOME_AT_START.get_or_init(|| std::env::var_os("HOME"));
// SAFETY: callers hold env_lock, which serialises environment changes.
unsafe {
std::env::set_var("WEFT_APP_STORE", &store);
std::env::set_var("XDG_DATA_HOME", store.join("share"));
std::env::set_var("HOME", store.join("home"));
}
store
}
fn finish(store: &Path) {
// SAFETY: as in `store`.
unsafe {
std::env::remove_var("WEFT_APP_STORE");
std::env::remove_var("WEFT_MOUNT_HELPER");
std::env::remove_var("XDG_DATA_HOME");
std::env::remove_var("WEFT_TRUSTED_KEYS");
match HOME_AT_START.get() {
Some(Some(home)) => std::env::set_var("HOME", home),
_ => std::env::remove_var("HOME"),
}
}
let _ = std::fs::remove_dir_all(store);
}
fn refusal(result: Result<LaunchPackage, Refusal>) -> Refusal {
match result {
Ok(package) => panic!("resolved {}", package.root.display()),
Err(refusal) => refusal,
}
}
#[test]
fn a_directory_install_resolves_to_its_own_files() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("dir", ID, "app.wasm");
let package = resolve(ID).unwrap();
finish(&store);
assert_eq!(package.root, store.join(ID));
assert_eq!(package.module, store.join(ID).join("app.wasm"));
assert_eq!(package.ui_entry, store.join(ID).join("ui/index.html"));
assert_eq!(package.version, "1.2.3");
assert_eq!(package.capabilities, ["sys:notifications"]);
assert!(package.image.is_none());
}
#[test]
fn an_image_in_a_later_store_is_not_shadowed_by_a_directory() {
let _env = crate::tests::env_lock().blocking_lock();
crate::tests::use_test_runtime_dir();
// A directory install in the user store, an incomplete image in the
// system store: the image is chosen, and refused.
let user = store("shadow_user", ID, "app.wasm");
let system = std::env::temp_dir().join(format!(
"weft_appd_launch_shadow_system_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&system);
std::fs::create_dir_all(&system).unwrap();
std::fs::write(ImageFiles::in_store(&system, ID).image, b"image").unwrap();
let refused = refusal(resolve_in(ID, &[user.clone(), system.clone()]));
finish(&user);
let _ = std::fs::remove_dir_all(&system);
assert_eq!(refused.code, 403, "{}", refused.message);
assert!(
refused.message.contains("verified image"),
"{}",
refused.message
);
}
#[cfg(unix)]
#[test]
fn a_linked_package_root_or_manifest_is_refused() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("linked", ID, "app.wasm");
let elsewhere =
std::env::temp_dir().join(format!("weft_appd_launch_elsewhere_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&elsewhere);
std::fs::rename(store.join(ID), &elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, store.join(ID)).unwrap();
let root_link = refusal(resolve(ID));
std::fs::remove_file(store.join(ID)).unwrap();
std::fs::rename(&elsewhere, store.join(ID)).unwrap();
let manifest = store.join(ID).join(MANIFEST_FILE);
std::fs::rename(&manifest, store.join("manifest.toml")).unwrap();
std::os::unix::fs::symlink(store.join("manifest.toml"), &manifest).unwrap();
let manifest_link = refusal(resolve(ID));
finish(&store);
// Only a link to one of the app's own revisions is followed.
assert_eq!(root_link.code, 403, "{}", root_link.message);
assert!(
root_link
.message
.contains("nor a link to one of its revisions"),
"{}",
root_link.message
);
assert_eq!(manifest_link.code, 403, "{}", manifest_link.message);
assert!(
manifest_link.message.contains("not a link"),
"{}",
manifest_link.message
);
}
#[cfg(unix)]
#[test]
fn an_unusable_store_entry_does_not_hide_a_later_store() {
let _env = crate::tests::env_lock().blocking_lock();
let user = store("unusable_user", ID, "app.wasm");
let system = std::env::temp_dir().join(format!(
"weft_appd_launch_unusable_system_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&system);
std::fs::create_dir_all(&system).unwrap();
std::fs::rename(user.join(ID), system.join(ID)).unwrap();
// A link to something other than one of the app's revisions.
std::os::unix::fs::symlink("/tmp", user.join(ID)).unwrap();
let found = resolve_in(ID, &[user.clone(), system.clone()]).map(|p| p.root);
let alone = refusal(resolve_in(ID, std::slice::from_ref(&user)));
finish(&user);
let _ = std::fs::remove_dir_all(&system);
assert_eq!(found.ok(), Some(system.join(ID)));
// With no other store, its problem is reported, not "not installed".
assert_eq!(alone.code, 403, "{}", alone.message);
}
#[cfg(unix)]
#[test]
fn a_session_runs_from_its_revision_and_holds_it() {
use weft_ipc_types::store::{link_target, revisions_of, try_claim};
let _env = crate::tests::env_lock().blocking_lock();
let store = store("revision", ID, "app.wasm");
let revision = "ab".repeat(32);
let dir = revisions_of(&store, ID).join(&revision);
std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
std::fs::rename(store.join(ID), &dir).unwrap();
std::os::unix::fs::symlink(link_target(ID, &revision), store.join(ID)).unwrap();
let package = resolve(ID).unwrap();
let held = try_claim(&dir).unwrap().is_none();
let root = package.root.clone();
let module = package.module.clone();
drop(package);
let released = try_claim(&dir).unwrap().is_some();
finish(&store);
// The children get the revision's own paths, not the link's.
assert_eq!(root, dir);
assert_eq!(module, dir.join("app.wasm"));
assert!(held, "the revision is not held while the session runs");
assert!(released, "the revision is still held after the session");
}
const DEMO: &str = "org.weft.demo.counter";
/// A store holding a copy of the signed Counter demo, with the demo key
/// trusted when `trusted`. Callers hold env_lock.
fn demo_store(name: &str, trusted: bool) -> PathBuf {
let store = store(name, ID, "app.wasm");
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples");
copy_tree(&examples.join(DEMO), &store.join(DEMO));
let keys = store.join("keys");
std::fs::create_dir_all(&keys).unwrap();
if trusted {
std::fs::copy(examples.join("keys/weft-sign.pub"), keys.join("demo.pub")).unwrap();
}
// SAFETY: as in `store`.
unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) };
store
}
fn copy_tree(src: &Path, dst: &Path) {
std::fs::create_dir_all(dst).unwrap();
for entry in std::fs::read_dir(src).unwrap().flatten() {
let to = dst.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &to);
} else {
std::fs::copy(entry.path(), to).unwrap();
}
}
}
fn record(store: &Path, app_id: &str, owner: Owner) {
weft_ipc_types::trust::write_owner(&owner_record_path(&store.join("share"), app_id), owner)
.unwrap();
}
fn demo_key() -> weft_ipc_types::trust::PublisherKey {
weft_ipc_types::trust::PublisherKey::from_file(
&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/keys/weft-sign.pub"),
)
.unwrap()
}
#[test]
fn a_package_signed_by_its_owner_launches() {
let _env = crate::tests::env_lock().blocking_lock();
// Recorded as the publisher's, and with no record but a trusted
// signature.
let store = demo_store("signed", true);
let first = resolve(DEMO).map(|p| p.root);
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
let again = resolve(DEMO).map(|p| p.root);
finish(&store);
assert_eq!(first.ok(), Some(store.join(DEMO)));
assert_eq!(owner, Some(Owner::Verified(demo_key())));
assert_eq!(again.ok(), Some(store.join(DEMO)));
}
#[test]
fn unowned_app_data_is_not_given_to_the_first_publisher() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("unowned_data", true);
let data = weft_ipc_types::package::app_data_dir(&store.join("share"), DEMO);
std::fs::create_dir_all(&data).unwrap();
let refused = refusal(resolve(DEMO));
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
finish(&store);
assert_eq!(refused.code, 403, "{}", refused.message);
assert!(
refused.message.contains("--claim-data"),
"{}",
refused.message
);
assert_eq!(owner, None);
}
#[test]
fn unowned_data_in_the_earlier_layout_is_not_given_away() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("legacy_data", true);
let legacy = weft_ipc_types::package::legacy_app_data_dir(&store.join("home"), DEMO);
std::fs::create_dir_all(&legacy).unwrap();
let refused = refusal(resolve(DEMO));
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
finish(&store);
assert_eq!(refused.code, 403, "{}", refused.message);
assert!(
refused.message.contains("no recorded owner"),
"{}",
refused.message
);
assert_eq!(owner, None);
}
#[test]
fn a_first_launch_without_a_usable_home_records_nothing() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("no_home", true);
// SAFETY: env_lock is held; finish restores HOME.
unsafe { std::env::set_var("HOME", "relative") };
let refused = refusal(resolve(DEMO));
let owner = read_owner(&owner_record_path(&store.join("share"), DEMO)).unwrap();
finish(&store);
assert_eq!(refused.code, 500, "{}", refused.message);
assert_eq!(owner, None);
}
#[test]
fn only_the_signed_manifest_is_accepted() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("manifest", true);
record(&store, DEMO, Owner::Verified(demo_key()));
let root = store.join(DEMO);
let signed = std::fs::read(root.join(MANIFEST_FILE)).unwrap();
let mut other = signed.clone();
other.extend_from_slice(b"\n# other\n");
let accepted = verify_owner(DEMO, &root, &signed);
let refused = verify_owner(DEMO, &root, &other).err();
finish(&store);
assert!(accepted.is_ok());
let refused = refused.expect("a manifest that was not signed was accepted");
assert_eq!(refused.code, 403, "{}", refused.message);
}
#[test]
fn development_content_does_not_depend_on_the_trust_store() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("dev_store", ID, "app.wasm");
let keys = store.join("keys");
std::fs::create_dir_all(&keys).unwrap();
std::fs::write(keys.join("broken.pub"), "not a key").unwrap();
// SAFETY: as in `store`.
unsafe { std::env::set_var("WEFT_TRUSTED_KEYS", &keys) };
let resolved = resolve(ID).map(|p| p.root);
finish(&store);
assert_eq!(resolved.ok(), Some(store.join(ID)));
}
#[test]
fn a_damaged_trust_store_or_record_is_a_host_error() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("damaged", true);
std::fs::write(store.join("keys/broken.pub"), "not a key").unwrap();
let bad_key = refusal(resolve(DEMO));
std::fs::remove_file(store.join("keys/broken.pub")).unwrap();
let record = owner_record_path(&store.join("share"), DEMO);
std::fs::write(&record, "nonsense\n").unwrap();
let bad_record = refusal(resolve(DEMO));
finish(&store);
for refused in [bad_key, bad_record] {
assert_eq!(refused.code, 500, "{}", refused.message);
}
}
#[test]
fn a_package_changed_after_installation_is_refused() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("changed", true);
record(&store, DEMO, Owner::Verified(demo_key()));
let page = store.join(DEMO).join("ui/index.html");
let mut text = std::fs::read_to_string(&page).unwrap();
text.push_str("<script>changed</script>");
std::fs::write(&page, text).unwrap();
let changed = refusal(resolve(DEMO));
// Without a record, the changed package matches no trusted key.
std::fs::remove_file(owner_record_path(&store.join("share"), DEMO)).unwrap();
let unrecorded = refusal(resolve(DEMO));
finish(&store);
assert_eq!(changed.code, 403, "{}", changed.message);
assert!(
changed.message.contains("not signed by its owner"),
"{}",
changed.message
);
assert_eq!(unrecorded.code, 403, "{}", unrecorded.message);
assert!(
unrecorded.message.contains("no recorded owner"),
"{}",
unrecorded.message
);
}
#[test]
fn a_withdrawn_key_no_longer_launches_its_packages() {
let _env = crate::tests::env_lock().blocking_lock();
let store = demo_store("withdrawn", false);
record(&store, DEMO, Owner::Verified(demo_key()));
let refused = refusal(resolve(DEMO));
finish(&store);
assert_eq!(refused.code, 403, "{}", refused.message);
assert!(refused.message.contains("no longer"), "{}", refused.message);
}
#[test]
fn unsigned_content_needs_a_development_record() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("unrecorded", ID, "app.wasm");
std::fs::remove_file(owner_record_path(&store.join("share"), ID)).unwrap();
let refused = refusal(resolve(ID));
// Another owner's record does not admit it either.
record(&store, ID, Owner::Verified(demo_key()));
let other_owner = refusal(resolve(ID));
finish(&store);
for refused in [refused, other_owner] {
assert_eq!(refused.code, 403, "{}", refused.message);
}
}
#[test]
fn a_package_declaring_another_id_is_refused() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("id", "org.weft.test.other", "app.wasm");
let refused = refusal(resolve(ID));
finish(&store);
assert_eq!(refused.code, 403);
assert!(
refused.message.contains("org.weft.test.other"),
"{}",
refused.message
);
}
#[test]
fn entries_outside_the_package_are_refused() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("entry", ID, "../escape.wasm");
std::fs::write(store.join("escape.wasm"), b"\0asm").unwrap();
let refused = refusal(resolve(ID));
finish(&store);
assert_eq!(refused.code, 403);
assert!(
refused.message.contains("runtime.module"),
"{}",
refused.message
);
}
#[test]
fn missing_packages_and_invalid_ids_are_refused() {
let _env = crate::tests::env_lock().blocking_lock();
let store = store("missing", ID, "app.wasm");
let missing = refusal(resolve("org.weft.test.absent"));
let invalid = refusal(resolve("../etc"));
finish(&store);
assert_eq!(missing.code, 404);
assert_eq!(invalid.code, 400);
}
#[test]
fn an_image_that_cannot_be_used_never_falls_back_to_the_directory() {
let _env = crate::tests::env_lock().blocking_lock();
crate::tests::use_test_runtime_dir();
let store = store("image", ID, "app.wasm");
let files = ImageFiles::in_store(&store, ID);
// Only the image: its companions are missing.
std::fs::write(&files.image, b"image").unwrap();
// SAFETY: as in `store`.
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/true") };
let partial = refusal(resolve(ID));
// All three files, but the helper fails to mount them.
std::fs::write(&files.hash_tree, b"tree").unwrap();
std::fs::write(&files.root_hash, "ab".repeat(32)).unwrap();
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/false") };
let failed = refusal(resolve(ID));
// The helper is not installed.
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/nonexistent/weft-mount-helper") };
let absent = refusal(resolve(ID));
// A root hash that is not one.
std::fs::write(&files.root_hash, "not a hash").unwrap();
unsafe { std::env::set_var("WEFT_MOUNT_HELPER", "/bin/true") };
let malformed = refusal(resolve(ID));
let mountpoints = std::env::var_os("XDG_RUNTIME_DIR")
.map(|dir| PathBuf::from(dir).join("weft/mnt"))
.and_then(|dir| std::fs::read_dir(dir).ok())
.map_or(0, Iterator::count);
finish(&store);
for refused in [&partial, &malformed] {
assert_eq!(refused.code, 403, "{}", refused.message);
}
for refused in [&failed, &absent] {
assert_eq!(refused.code, 500, "{}", refused.message);
}
for refused in [&partial, &failed, &absent, &malformed] {
assert!(
refused.message.contains("verified image"),
"{}",
refused.message
);
}
assert!(partial.message.contains(".app.hash"), "{}", partial.message);
assert_eq!(mountpoints, 0, "a failed mount left its mountpoint behind");
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,105 +1,124 @@
//! Verified package images, mounted read-only for the session that runs
//! them.
use std::path::{Path, PathBuf};
fn mount_helper_bin() -> Option<String> {
if let Ok(v) = std::env::var("WEFT_MOUNT_HELPER") {
return Some(v);
use weft_ipc_types::package::ImageFiles;
fn mount_helper_bin() -> Option<PathBuf> {
if let Some(path) = std::env::var_os("WEFT_MOUNT_HELPER") {
return Some(PathBuf::from(path));
}
for candidate in [
[
"/usr/lib/weft/weft-mount-helper",
"/usr/local/lib/weft/weft-mount-helper",
] {
if Path::new(candidate).exists() {
return Some(candidate.to_string());
}
}
None
]
.into_iter()
.map(PathBuf::from)
.find(|candidate| candidate.exists())
}
pub struct MountOrchestrator {
mountpoint: Option<PathBuf>,
/// A mounted image. Dropping it unmounts the image and removes the empty
/// mountpoint; a mountpoint that cannot be unmounted is left in place.
pub(crate) struct Mount {
helper: PathBuf,
mountpoint: PathBuf,
}
impl MountOrchestrator {
pub fn mount_if_needed(app_id: &str, session_id: u64) -> (Self, Option<PathBuf>) {
let Some(helper) = mount_helper_bin() else {
return (Self { mountpoint: None }, None);
};
let (img, hash_dev, root_hash) = match find_image(app_id) {
Some(t) => t,
None => return (Self { mountpoint: None }, None),
};
let base = std::env::temp_dir().join(format!("weft-mnt-{session_id}"));
let mountpoint = base.join(app_id);
if let Err(e) = std::fs::create_dir_all(&mountpoint) {
tracing::warn!(session_id, %app_id, error=%e, "cannot create mount dir; skipping image mount");
return (Self { mountpoint: None }, None);
}
let status = std::process::Command::new(&helper)
.args([
"mount",
&img.to_string_lossy(),
&hash_dev.to_string_lossy(),
&root_hash,
&mountpoint.to_string_lossy(),
])
.status();
match status {
Ok(s) if s.success() => {
tracing::info!(session_id, %app_id, path=%mountpoint.display(), "EROFS image mounted");
(
Self {
mountpoint: Some(mountpoint),
},
Some(base),
)
}
Ok(s) => {
tracing::warn!(session_id, %app_id, status=%s, "mount-helper failed; using directory install");
let _ = std::fs::remove_dir_all(&base);
(Self { mountpoint: None }, None)
}
Err(e) => {
tracing::warn!(session_id, %app_id, error=%e, "spawn mount-helper failed; using directory install");
let _ = std::fs::remove_dir_all(&base);
(Self { mountpoint: None }, None)
}
}
impl Mount {
/// The package root inside the image.
pub(crate) fn root(&self) -> &Path {
&self.mountpoint
}
}
pub fn umount(&self) {
let Some(ref mp) = self.mountpoint else {
impl Drop for Mount {
fn drop(&mut self) {
let unmounted = std::process::Command::new(&self.helper)
.arg("umount")
.arg(&self.mountpoint)
.status()
.is_ok_and(|status| status.success());
if !unmounted {
tracing::error!(path = %self.mountpoint.display(), "cannot unmount package image");
return;
};
let Some(helper) = mount_helper_bin() else {
return;
};
let _ = std::process::Command::new(&helper)
.args(["umount", &mp.to_string_lossy()])
.status();
if let Some(parent) = mp.parent() {
let _ = std::fs::remove_dir_all(parent);
}
if let Err(e) = std::fs::remove_dir(&self.mountpoint) {
tracing::warn!(path = %self.mountpoint.display(), error = %e, "cannot remove mountpoint");
}
}
}
fn find_image(app_id: &str) -> Option<(PathBuf, PathBuf, String)> {
for root in crate::app_store_roots() {
let img = root.join(format!("{app_id}.app.img"));
let hash_dev = root.join(format!("{app_id}.hash"));
let roothash_file = root.join(format!("{app_id}.roothash"));
if img.exists() && hash_dev.exists() && roothash_file.exists() {
let Ok(root_hash) = std::fs::read_to_string(&roothash_file) else {
continue;
};
return Some((img, hash_dev, root_hash.trim().to_string()));
/// Why an image was not mounted.
pub(crate) enum MountError {
/// The image files are incomplete or malformed.
Invalid(String),
/// The host could not mount a well-formed image.
Host(String),
}
/// Mounts the verified image `files` of `app_id`. Every failure is returned:
/// the caller must not fall back to another copy of the package.
pub(crate) fn mount(app_id: &str, files: &ImageFiles) -> Result<Mount, MountError> {
use MountError::{Host, Invalid};
for path in [&files.image, &files.hash_tree, &files.root_hash] {
let is_file = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file());
if !is_file {
return Err(Invalid(format!(
"{} is missing or not a regular file",
path.display()
)));
}
}
None
let root_hash = std::fs::read_to_string(&files.root_hash)
.map_err(|e| Host(format!("cannot read {}: {e}", files.root_hash.display())))?;
let root_hash = root_hash.trim();
if !is_root_hash(root_hash) {
return Err(Invalid(format!(
"{} holds no root hash",
files.root_hash.display()
)));
}
let helper = mount_helper_bin().ok_or(Host("weft-mount-helper is not installed".into()))?;
let runtime_dir =
std::env::var_os("XDG_RUNTIME_DIR").ok_or(Host("XDG_RUNTIME_DIR is not set".into()))?;
let base = PathBuf::from(runtime_dir).join("weft/mnt");
crate::private_dir(&base)
.map_err(|e| Host(format!("cannot create {}: {e}", base.display())))?;
let name =
crate::runtime::random_token().map_err(|e| Host(format!("no mountpoint name: {e}")))?;
let mountpoint = base.join(name);
std::fs::create_dir(&mountpoint)
.map_err(|e| Host(format!("cannot create {}: {e}", mountpoint.display())))?;
let status = std::process::Command::new(&helper)
.arg("mount")
.arg(&files.image)
.arg(&files.hash_tree)
.arg(root_hash)
.arg(&mountpoint)
.status();
match status {
Ok(status) if status.success() => {
tracing::info!(%app_id, path = %mountpoint.display(), "package image mounted");
Ok(Mount { helper, mountpoint })
}
outcome => {
let _ = std::fs::remove_dir(&mountpoint);
Err(Host(match outcome {
Ok(status) => format!("weft-mount-helper failed: {status}"),
Err(e) => format!("cannot run {}: {e}", helper.display()),
}))
}
}
}
/// A dm-verity root hash in hex, as `veritysetup format` prints it.
fn is_root_hash(text: &str) -> bool {
(64..=128).contains(&text.len())
&& text.len().is_multiple_of(2)
&& text.bytes().all(|b| b.is_ascii_hexdigit())
}
#[cfg(test)]
@ -107,10 +126,17 @@ mod tests {
use super::*;
#[test]
fn find_image_returns_none_when_absent() {
unsafe { std::env::set_var("WEFT_APP_STORE", "/tmp/nonexistent_weft_store_xyz") };
let result = find_image("com.example.missing");
unsafe { std::env::remove_var("WEFT_APP_STORE") };
assert!(result.is_none());
fn root_hashes_are_hex_digests() {
assert!(is_root_hash(&"a".repeat(64)));
assert!(is_root_hash(&"0F".repeat(64)));
for bad in [
"",
"abc",
&"g".repeat(64),
&"a".repeat(65),
&"a".repeat(130),
] {
assert!(!is_root_hash(bad), "{bad:?}");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,54 +1,553 @@
use futures_util::{SinkExt, StreamExt};
use tokio::sync::broadcast;
use tokio_tungstenite::{accept_async, tungstenite::Message};
//! Browser-facing WebSocket endpoint with role-separated authority.
//!
//! Every connection starts with a `HELLO` message naming its role and
//! credential:
//!
//! - `{"type":"HELLO","role":"system","token":…}` — the trusted system shell,
//! holding the token appd writes to `$XDG_RUNTIME_DIR/weft/appd.systoken`.
//! It may use the catalog, lifecycle and gesture requests and receives
//! session state notifications, but never application payloads.
//! - `{"type":"HELLO","role":"app","session_id":N,"token":…}` — the bridge of
//! one application session, holding the token appd gave that session's app
//! shell. It may only exchange `{"type":"APP_MESSAGE","payload":"…"}`
//! messages with its own session's component.
//!
//! Connections that do not complete the upgrade and authenticate within
//! `HELLO_TIMEOUT` are closed.
use crate::{Registry, dispatch, ipc::Request, ipc::Response};
use std::sync::Arc;
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use serde::Deserialize;
use tokio::sync::{broadcast, mpsc};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use crate::ipc::{AppStateKind, Request, Response};
use crate::{Registry, dispatch};
const HELLO_TIMEOUT: Duration = if cfg!(test) {
Duration::from_secs(1)
} else {
Duration::from_secs(5)
};
/// Largest WebSocket message accepted from any client.
const MAX_MESSAGE: usize = 1024 * 1024;
/// Largest application payload forwarded to a component.
const MAX_APP_PAYLOAD: usize = 64 * 1024;
pub struct WsAuth {
pub system_token: String,
}
/// Compares credentials without exiting early on the first differing byte.
pub(crate) fn tokens_match(expected: &str, given: &str) -> bool {
let (expected, given) = (expected.as_bytes(), given.as_bytes());
expected.len() == given.len()
&& expected
.iter()
.zip(given)
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
== 0
}
#[derive(Deserialize)]
#[serde(tag = "role", rename_all = "lowercase")]
enum Hello {
System { token: String },
App { session_id: u64, token: String },
}
#[derive(Deserialize)]
struct HelloEnvelope {
#[serde(rename = "type")]
kind: String,
#[serde(flatten)]
hello: Hello,
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
enum AppRequest {
AppMessage { payload: String },
}
enum Role {
System,
App(u64),
}
pub async fn handle_ws_connection(
stream: tokio::net::TcpStream,
registry: Registry,
broadcast_rx: broadcast::Receiver<Response>,
auth: Arc<WsAuth>,
) -> anyhow::Result<()> {
let ws_stream = accept_async(stream).await?;
let (mut ws_write, mut ws_read) = ws_stream.split();
let mut broadcast_rx = broadcast_rx;
let config = WebSocketConfig {
max_message_size: Some(MAX_MESSAGE),
max_frame_size: Some(MAX_MESSAGE),
..Default::default()
};
// The upgrade and HELLO share one deadline, so a client that never
// completes either holds nothing for longer than HELLO_TIMEOUT.
let handshake = async {
let ws_stream = tokio_tungstenite::accept_async_with_config(stream, Some(config)).await?;
let (ws_write, mut ws_read) = ws_stream.split();
let hello = match ws_read.next().await {
Some(Ok(Message::Text(text))) => serde_json::from_str::<HelloEnvelope>(&text).ok(),
_ => None,
};
anyhow::Ok((ws_write, ws_read, hello))
};
let Ok(handshake) = tokio::time::timeout(HELLO_TIMEOUT, handshake).await else {
tracing::debug!("WebSocket client did not complete its handshake in time");
return Ok(());
};
let (mut ws_write, mut ws_read, hello) = handshake?;
let role = match hello {
Some(HelloEnvelope {
kind,
hello: Hello::System { token },
}) if kind == "HELLO" && tokens_match(&auth.system_token, &token) => Role::System,
Some(HelloEnvelope {
kind,
hello: Hello::App { session_id, token },
}) if kind == "HELLO" && registry.lock().await.authorize_bridge(session_id, &token) => {
Role::App(session_id)
}
_ => {
tracing::warn!("WebSocket client failed to authenticate; closing");
let refusal = Response::Error {
code: 401,
message: "authentication required".to_owned(),
};
let _ = ws_write
.send(Message::Text(serde_json::to_string(&refusal)?))
.await;
let _ = ws_write.close().await;
return Ok(());
}
};
match role {
Role::System => tracing::debug!("system client connected"),
Role::App(session_id) => tracing::debug!(session_id, "application bridge connected"),
}
let mut broadcast_rx = broadcast_rx;
loop {
tokio::select! {
msg = ws_read.next() => {
match msg {
Some(Ok(Message::Text(text))) => {
let req: Request = match serde_json::from_str(&text) {
Ok(r) => r,
Err(e) => {
tracing::debug!(error = %e, "unrecognised WS message");
continue;
}
};
tracing::debug!(?req, "ws request");
let resp = dispatch(req, &registry).await;
let json = serde_json::to_string(&resp)?;
ws_write.send(Message::Text(json)).await?;
}
let text = match msg {
Some(Ok(Message::Text(text))) => text,
Some(Ok(Message::Close(_))) | None => break,
Some(Ok(_)) => {}
Some(Ok(_)) => continue,
Some(Err(e)) => {
tracing::warn!(error = %e, "ws error");
break;
}
};
let reply = match role {
Role::System => system_request(&text, &registry).await,
Role::App(session_id) => {
app_request(&text, session_id, &registry).await;
None
}
};
if let Some(reply) = reply {
ws_write.send(Message::Text(serde_json::to_string(&reply)?)).await?;
}
}
notification = broadcast_rx.recv() => {
match notification {
Ok(resp) => {
let json = serde_json::to_string(&resp)?;
ws_write.send(Message::Text(json)).await?;
let notification = match notification {
Ok(notification) => notification,
Err(broadcast::error::RecvError::Lagged(missed)) => {
tracing::warn!(missed, "ws client missed notifications");
continue;
}
Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => break,
};
match (&role, notification) {
(Role::System, Response::IpcMessage { .. }) => {}
(Role::System, other) => {
ws_write.send(Message::Text(serde_json::to_string(&other)?)).await?;
}
(Role::App(bound), Response::IpcMessage { session_id, payload })
if *bound == session_id =>
{
let message = serde_json::json!({ "type": "APP_MESSAGE", "payload": payload });
ws_write.send(Message::Text(message.to_string())).await?;
}
(Role::App(bound), Response::AppState { session_id, state: AppStateKind::Stopped })
if *bound == session_id => break,
(Role::App(_), _) => {}
}
}
}
}
let _ = ws_write.close().await;
Ok(())
}
/// Dispatches a system-role request. Application messages are not part of
/// the system role's authority.
async fn system_request(text: &str, registry: &Registry) -> Option<Response> {
let request: Request = match serde_json::from_str(text) {
Ok(request) => request,
Err(e) => {
tracing::debug!(error = %e, "unrecognised system ws message");
return None;
}
};
if matches!(request, Request::IpcForward { .. }) {
return Some(Response::Error {
code: 403,
message: "application messages are not available to the system role".to_owned(),
});
}
Some(dispatch(request, registry).await)
}
/// Forwards an application message to the bound session's component.
async fn app_request(text: &str, session_id: u64, registry: &Registry) {
let payload = match serde_json::from_str::<AppRequest>(text) {
Ok(AppRequest::AppMessage { payload }) => payload,
Err(e) => {
tracing::debug!(session_id, error = %e, "unrecognised app ws message");
return;
}
};
// The component reads newline-delimited messages; a payload is dropped
// rather than altered when it cannot be framed that way.
if payload.len() > MAX_APP_PAYLOAD || payload.contains('\n') {
tracing::warn!(
session_id,
len = payload.len(),
"application payload rejected"
);
return;
}
let Some(tx) = registry.lock().await.ipc_sender_for(session_id) else {
tracing::debug!(session_id, "no IPC relay for session; message dropped");
return;
};
// A component that stops reading must not stall this connection, which
// also has to see its session stop.
match tx.try_send(payload) {
Ok(()) => {}
Err(mpsc::error::TrySendError::Full(_)) => {
tracing::warn!(
session_id,
"component is not reading; application message dropped"
);
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::warn!(session_id, "IPC relay closed");
registry.lock().await.remove_ipc_sender(session_id);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{SessionRegistry, ipc::Response};
use tokio::sync::Mutex;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
type Client = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
const SYSTEM_TOKEN: &str = "0123456789abcdef0123456789abcdef";
/// Serves one WebSocket connection with `handle_ws_connection`.
async fn serve(registry: Registry) -> Client {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let reg = Arc::clone(&registry);
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let rx = reg.lock().await.subscribe();
let auth = Arc::new(WsAuth {
system_token: SYSTEM_TOKEN.to_owned(),
});
handle_ws_connection(stream, reg, rx, auth).await.unwrap();
});
let (client, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/"))
.await
.unwrap();
client
}
async fn send(client: &mut Client, value: serde_json::Value) {
client.send(Message::Text(value.to_string())).await.unwrap();
}
/// The next text message, or None if the server closed the connection.
async fn next(client: &mut Client) -> Option<serde_json::Value> {
loop {
match tokio::time::timeout(Duration::from_secs(2), client.next()).await {
Ok(Some(Ok(Message::Text(text)))) => return serde_json::from_str(&text).ok(),
Ok(Some(Ok(Message::Close(_)))) | Ok(None) | Ok(Some(Err(_))) => return None,
Ok(Some(Ok(_))) => continue,
Err(_) => panic!("no message within 2 s"),
}
}
}
/// True if nothing arrives within 300 ms.
async fn silent(client: &mut Client) -> bool {
tokio::time::timeout(Duration::from_millis(300), client.next())
.await
.is_err()
}
fn registry() -> Registry {
Arc::new(Mutex::new(SessionRegistry::default()))
}
/// A session with an IPC relay channel standing in for its component.
async fn session(registry: &Registry) -> (u64, String, tokio::sync::mpsc::Receiver<String>) {
let mut reg = registry.lock().await;
let id = reg.launch("test.app");
let (tx, rx) = tokio::sync::mpsc::channel(8);
reg.register_ipc_sender(id, tx);
let token = reg.bridge_token(id).unwrap();
(id, token, rx)
}
fn refused(message: &Option<serde_json::Value>) -> bool {
matches!(message, Some(m) if m["type"] == "ERROR" && m["code"] == 401)
}
#[tokio::test]
async fn requests_before_hello_are_refused() {
let mut client = serve(registry()).await;
send(&mut client, serde_json::json!({ "type": "QUERY_RUNNING" })).await;
assert!(refused(&next(&mut client).await));
assert!(next(&mut client).await.is_none());
}
#[tokio::test]
async fn wrong_system_token_is_refused() {
let mut client = serve(registry()).await;
let token = "fedcba9876543210fedcba9876543210";
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "system", "token": token }),
)
.await;
assert!(refused(&next(&mut client).await));
}
#[tokio::test]
async fn system_role_controls_sessions_but_not_app_messages() {
let registry = registry();
let (id, _, mut component) = session(&registry).await;
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "system", "token": SYSTEM_TOKEN }),
)
.await;
send(&mut client, serde_json::json!({ "type": "QUERY_RUNNING" })).await;
assert_eq!(next(&mut client).await.unwrap()["type"], "RUNNING_APPS");
send(
&mut client,
serde_json::json!({ "type": "IPC_FORWARD", "session_id": id, "payload": "x" }),
)
.await;
assert_eq!(next(&mut client).await.unwrap()["code"], 403);
assert!(component.try_recv().is_err());
let broadcast = registry.lock().await.broadcast().clone();
let _ = broadcast.send(Response::IpcMessage {
session_id: id,
payload: "private".to_owned(),
});
let _ = broadcast.send(Response::AppState {
session_id: id,
state: AppStateKind::Running,
});
assert_eq!(next(&mut client).await.unwrap()["type"], "APP_STATE");
}
#[tokio::test]
async fn app_role_reaches_only_its_own_session() {
let registry = registry();
let (id, token, mut component) = session(&registry).await;
let (other, _, mut other_component) = session(&registry).await;
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }),
)
.await;
send(
&mut client,
serde_json::json!({ "type": "APP_MESSAGE", "payload": "increment" }),
)
.await;
let delivered = tokio::time::timeout(Duration::from_secs(2), component.recv()).await;
assert_eq!(delivered.unwrap().as_deref(), Some("increment"));
// System requests and other sessions are out of reach.
send(
&mut client,
serde_json::json!({ "type": "TERMINATE_APP", "session_id": other }),
)
.await;
send(
&mut client,
serde_json::json!({ "type": "IPC_FORWARD", "session_id": other, "payload": "x" }),
)
.await;
assert!(silent(&mut client).await);
assert!(other_component.try_recv().is_err());
assert!(!matches!(
registry.lock().await.state(other),
AppStateKind::NotFound
));
let broadcast = registry.lock().await.broadcast().clone();
let _ = broadcast.send(Response::IpcMessage {
session_id: other,
payload: "not yours".to_owned(),
});
let _ = broadcast.send(Response::IpcMessage {
session_id: id,
payload: "{\"count\":1}".to_owned(),
});
let received = next(&mut client).await.unwrap();
assert_eq!(received["type"], "APP_MESSAGE");
assert_eq!(received["payload"], "{\"count\":1}");
let _ = broadcast.send(Response::AppState {
session_id: id,
state: AppStateKind::Stopped,
});
assert!(next(&mut client).await.is_none());
}
#[tokio::test]
async fn app_token_of_another_or_stopped_session_is_refused() {
let registry = registry();
let (id, _, _component) = session(&registry).await;
let (_, other_token, _other_component) = session(&registry).await;
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": other_token }),
)
.await;
assert!(refused(&next(&mut client).await));
let (stopped, token, _stopped_component) = session(&registry).await;
registry
.lock()
.await
.set_state(stopped, AppStateKind::Stopped);
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "app", "session_id": stopped, "token": token }),
)
.await;
assert!(refused(&next(&mut client).await));
}
#[tokio::test]
async fn app_payloads_that_cannot_be_framed_are_dropped() {
let registry = registry();
let (id, token, mut component) = session(&registry).await;
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }),
)
.await;
send(
&mut client,
serde_json::json!({ "type": "APP_MESSAGE", "payload": "a\nb" }),
)
.await;
send(
&mut client,
serde_json::json!({ "type": "APP_MESSAGE", "payload": "ok" }),
)
.await;
let delivered = tokio::time::timeout(Duration::from_secs(2), component.recv()).await;
assert_eq!(delivered.unwrap().as_deref(), Some("ok"));
}
#[tokio::test]
async fn stalled_upgrade_is_closed() {
use tokio::io::AsyncReadExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let reg = registry();
let handler = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let rx = reg.lock().await.subscribe();
let auth = Arc::new(WsAuth {
system_token: SYSTEM_TOKEN.to_owned(),
});
handle_ws_connection(stream, reg, rx, auth).await
});
// Connects but never sends the HTTP upgrade request.
let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
let finished = tokio::time::timeout(HELLO_TIMEOUT * 4, handler).await;
assert!(finished.expect("handler still waiting").unwrap().is_ok());
let mut byte = [0u8; 1];
assert_eq!(stream.read(&mut byte).await.unwrap(), 0);
}
#[tokio::test]
async fn component_that_stops_reading_does_not_stall_the_bridge() {
let registry = registry();
let id = {
let mut reg = registry.lock().await;
let id = reg.launch("test.app");
let (tx, rx) = tokio::sync::mpsc::channel(1);
// The receiver stays alive but is never read.
std::mem::forget(rx);
reg.register_ipc_sender(id, tx);
id
};
let token = registry.lock().await.bridge_token(id).unwrap();
let mut client = serve(Arc::clone(&registry)).await;
send(
&mut client,
serde_json::json!({ "type": "HELLO", "role": "app", "session_id": id, "token": token }),
)
.await;
for _ in 0..4 {
send(
&mut client,
serde_json::json!({ "type": "APP_MESSAGE", "payload": "increment" }),
)
.await;
}
let broadcast = registry.lock().await.broadcast().clone();
let _ = broadcast.send(Response::IpcMessage {
session_id: id,
payload: "still here".to_owned(),
});
assert_eq!(next(&mut client).await.unwrap()["payload"], "still here");
let _ = broadcast.send(Response::AppState {
session_id: id,
state: AppStateKind::Stopped,
});
assert!(next(&mut client).await.is_none());
}
#[test]
fn tokens_match_requires_equal_length_and_bytes() {
assert!(tokens_match("abc", "abc"));
assert!(!tokens_match("abc", "abd"));
assert!(!tokens_match("abc", "abcd"));
assert!(!tokens_match("abc", ""));
}
}

View file

@ -26,6 +26,7 @@ wayland-scanner = "0.31"
wayland-server = "0.31"
wayland-backend = "0.3"
bitflags = "2"
rustix = { version = "1", features = ["net"] }
# DRM/KMS and hardware input depend on Linux kernel interfaces; compile only on Linux.
[target.'cfg(target_os = "linux")'.dependencies]

View file

@ -1,13 +1,21 @@
#[cfg(unix)]
use std::{
collections::HashMap,
io::{self, Read, Write},
collections::{HashMap, HashSet, VecDeque},
io,
os::fd::OwnedFd,
os::unix::net::{UnixListener, UnixStream},
path::PathBuf,
sync::Arc,
};
#[cfg(unix)]
use smithay::reexports::calloop::{Interest, Mode, PostAction, generic::Generic};
use smithay::reexports::calloop::{
Interest, LoopHandle, Mode, PostAction, RegistrationToken, channel,
generic::Generic,
timer::{TimeoutAction, Timer},
};
#[cfg(unix)]
use smithay::reexports::wayland_server::backend::{ClientId, DisconnectReason};
#[cfg(unix)]
use weft_ipc_types::{
@ -15,15 +23,40 @@ use weft_ipc_types::{
};
#[cfg(unix)]
use crate::state::WeftCompositorState;
use crate::state::{SessionBinding, WeftClientState, WeftCompositorState};
/// Descriptors received ahead of the messages that claim them; more than
/// this means the peer is not following the protocol.
#[cfg(unix)]
const MAX_PENDING_FDS: usize = 16;
#[cfg(unix)]
pub struct WeftAppdIpc {
pub socket_path: PathBuf,
read_buf: Vec<u8>,
write_stream: Option<UnixStream>,
/// pid → (app_id, session_id) for Wayland clients whose surface has not yet arrived.
pub pending_pids: HashMap<u32, (String, u64)>,
/// Whether an appd connection's read source is registered. Only one
/// connection is served at a time.
connected: bool,
/// Descriptors received with appd messages, in arrival order. Each
/// `AttachClient` frame is sent with exactly one, attached to its first
/// bytes, so it has arrived by the time the frame is decoded.
fds: VecDeque<OwnedFd>,
/// The Wayland client of each appd session.
sessions: HashMap<u64, ClientId>,
/// Sessions whose first toplevel was reported to appd.
reported: HashSet<u64>,
/// Sessions that already received keyboard focus for a mapped window;
/// kept until the session ends, so recreating a window gains nothing.
focused_on_map: HashSet<u64>,
/// Where clients report their session's disconnection.
disconnected: Option<channel::Sender<(u64, ClientId)>>,
/// Bytes for appd that did not fit in the socket buffer, sent before
/// anything else so frames stay whole.
out_buf: Vec<u8>,
/// Retries `flush` while `out_buf` holds bytes; armed only then.
flush_retry: Option<RegistrationToken>,
loop_handle: Option<LoopHandle<'static, WeftCompositorState>>,
}
#[cfg(unix)]
@ -33,26 +66,111 @@ impl WeftAppdIpc {
socket_path,
read_buf: Vec::new(),
write_stream: None,
pending_pids: HashMap::new(),
connected: false,
fds: VecDeque::new(),
sessions: HashMap::new(),
reported: HashSet::new(),
focused_on_map: HashSet::new(),
disconnected: None,
out_buf: Vec::new(),
flush_retry: None,
loop_handle: None,
}
}
#[allow(dead_code)]
pub fn send(&mut self, msg: &CompositorToAppd) {
let Some(stream) = &mut self.write_stream else {
return;
};
match frame_encode(msg) {
Ok(frame) => {
if stream.write_all(&frame).is_err() {
self.write_stream = None;
if self.write_stream.is_some() {
self.out_buf.extend_from_slice(&frame);
self.flush();
self.schedule_flush();
}
}
Err(e) => tracing::warn!(?e, "failed to encode compositor IPC message"),
}
}
fn try_decode_frames(&mut self) -> Vec<AppdToCompositor> {
/// Writes what appd's socket accepts now; the rest waits for the next
/// send or read. A backlog appd never drains, or a write error, ends the
/// connection, whose read side then cleans up.
fn flush(&mut self) {
use std::io::Write;
let Some(stream) = &mut self.write_stream else {
self.out_buf.clear();
return;
};
while !self.out_buf.is_empty() {
match stream.write(&self.out_buf) {
Ok(0) => break,
Ok(n) => {
self.out_buf.drain(..n);
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => {
tracing::warn!(
?e,
"compositor IPC write failed; closing the appd connection"
);
let _ = stream.shutdown(std::net::Shutdown::Both);
self.write_stream = None;
self.out_buf.clear();
return;
}
}
}
if self.out_buf.len() > MAX_FRAME_LEN {
tracing::warn!("weft-appd is not reading compositor IPC; closing the connection");
let _ = stream.shutdown(std::net::Shutdown::Both);
self.write_stream = None;
self.out_buf.clear();
}
}
/// Retries the flush until appd has taken every queued byte, so the
/// last frames of a burst do not wait for unrelated traffic.
fn schedule_flush(&mut self) {
if self.out_buf.is_empty() || self.flush_retry.is_some() {
return;
}
let Some(handle) = &self.loop_handle else {
return;
};
let retry = Timer::from_duration(std::time::Duration::from_millis(20));
self.flush_retry = handle
.insert_source(retry, |_, _, state| {
let Some(ipc) = state.appd_ipc.as_mut() else {
return TimeoutAction::Drop;
};
ipc.flush();
if ipc.out_buf.is_empty() {
ipc.flush_retry = None;
TimeoutAction::Drop
} else {
TimeoutAction::ToDuration(std::time::Duration::from_millis(20))
}
})
.ok();
}
/// Whether a window `session_id` maps now may take keyboard focus: only
/// the first one in the session's lifetime.
pub fn take_focus_on_map(&mut self, session_id: u64) -> bool {
self.sessions.contains_key(&session_id) && self.focused_on_map.insert(session_id)
}
/// Reports a session's first toplevel to appd.
pub fn surface_created(&mut self, session_id: u64) {
if self.sessions.contains_key(&session_id) && self.reported.insert(session_id) {
self.send(&CompositorToAppd::SurfaceReady { session_id });
}
}
/// Decodes the complete frames in the buffer, and reports whether the
/// stream can no longer be trusted: after an oversized or undecodable
/// frame, descriptors could be paired with the wrong messages.
fn try_decode_frames(&mut self) -> (Vec<AppdToCompositor>, bool) {
let mut out = Vec::new();
loop {
if self.read_buf.len() < 4 {
@ -66,9 +184,7 @@ impl WeftAppdIpc {
]) as usize;
if declared_len > MAX_FRAME_LEN {
tracing::warn!(declared_len, "appd IPC frame too large; disconnecting");
self.write_stream = None;
self.read_buf.clear();
break;
return (out, true);
}
if self.read_buf.len() < 4 + declared_len {
break;
@ -76,24 +192,45 @@ impl WeftAppdIpc {
let frame_end = 4 + declared_len;
match frame_decode::<AppdToCompositor>(&self.read_buf[..frame_end]) {
Ok(msg) => out.push(msg),
Err(e) => tracing::warn!(?e, "appd IPC frame decode error"),
Err(e) => {
tracing::warn!(?e, "appd IPC frame decode error; disconnecting");
return (out, true);
}
}
self.read_buf.drain(..frame_end);
}
out
(out, false)
}
pub fn on_read(&mut self, stream: &mut UnixStream) -> (Vec<AppdToCompositor>, bool) {
/// Reads what is available, keeping descriptors that arrive with the
/// data, and returns the complete messages and whether appd hung up.
pub fn on_read(&mut self, stream: &UnixStream) -> (Vec<AppdToCompositor>, bool) {
use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, recvmsg};
use std::mem::MaybeUninit;
let mut buf = [0u8; 8192];
let mut eof = false;
loop {
match stream.read(&mut buf) {
Ok(0) => {
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];
let mut control = RecvAncillaryBuffer::new(&mut space);
let received = recvmsg(
stream,
&mut [io::IoSliceMut::new(&mut buf)],
&mut control,
RecvFlags::CMSG_CLOEXEC | RecvFlags::DONTWAIT,
);
for message in control.drain() {
if let RecvAncillaryMessage::ScmRights(fds) = message {
self.fds.extend(fds);
}
}
match received {
Ok(msg) if msg.bytes == 0 => {
eof = true;
break;
}
Ok(n) => self.read_buf.extend_from_slice(&buf[..n]),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Ok(msg) => self.read_buf.extend_from_slice(&buf[..msg.bytes]),
Err(rustix::io::Errno::AGAIN) => break,
Err(rustix::io::Errno::INTR) => continue,
Err(e) => {
tracing::warn!(?e, "appd IPC stream read error");
eof = true;
@ -101,37 +238,118 @@ impl WeftAppdIpc {
}
}
}
let messages = self.try_decode_frames();
if eof {
self.write_stream = None;
self.read_buf.clear();
let (messages, broken) = self.try_decode_frames();
eof |= broken;
let claimed = messages
.iter()
.filter(|m| matches!(m, AppdToCompositor::AttachClient { .. }))
.count();
if self.fds.len().saturating_sub(claimed) > MAX_PENDING_FDS {
tracing::warn!("appd sent descriptors without messages; disconnecting");
eof = true;
}
(messages, eof)
}
/// Forgets the appd connection once its read source is gone. The
/// sessions it started are closed: they belong to that appd.
fn disconnect(&mut self) -> Vec<ClientId> {
self.connected = false;
self.write_stream = None;
self.out_buf.clear();
self.read_buf.clear();
self.fds.clear();
self.reported.clear();
self.focused_on_map.clear();
self.sessions.drain().map(|(_, client)| client).collect()
}
}
#[cfg(unix)]
fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) {
match msg {
AppdToCompositor::AppSurfaceCreated {
app_id,
session_id,
pid,
} => {
tracing::debug!(app_id, session_id, pid, "AppSurfaceCreated");
if let Some(ipc) = &mut state.appd_ipc {
ipc.pending_pids.insert(pid, (app_id, session_id));
}
AppdToCompositor::AttachClient { session_id, app_id } => {
attach_client(state, session_id, app_id);
}
AppdToCompositor::AppSurfaceDestroyed { session_id } => {
tracing::debug!(session_id, "AppSurfaceDestroyed");
let Some(ipc) = state.appd_ipc.as_mut() else {
return;
};
ipc.reported.remove(&session_id);
ipc.focused_on_map.remove(&session_id);
if let Some(client) = ipc.sessions.remove(&session_id) {
tracing::info!(session_id, "closing the client of an ended session");
state
.display_handle
.backend_handle()
.kill_client(client, DisconnectReason::ConnectionClosed);
}
}
AppdToCompositor::AppCloseRequest { session_id } => {
let closed = state.close_session_windows(session_id);
tracing::info!(session_id, windows = closed, "session asked to close");
}
AppdToCompositor::AppFocusRequest { session_id } => {
tracing::debug!(session_id, "AppFocusRequest");
if state.activate_session(session_id) {
tracing::info!(session_id, "session activated");
} else {
tracing::info!(
session_id,
"activation requested for a session with no window"
);
}
}
}
}
/// Makes the descriptor that came with an `AttachClient` message a Wayland
/// client bound to `session_id`.
#[cfg(unix)]
fn attach_client(state: &mut WeftCompositorState, session_id: u64, app_id: String) {
let Some(ipc) = state.appd_ipc.as_mut() else {
return;
};
let Some(fd) = ipc.fds.pop_front() else {
tracing::warn!(
session_id,
"AttachClient arrived without a connection; ignored"
);
return;
};
if !weft_ipc_types::package::is_valid_app_id(&app_id) {
tracing::warn!(session_id, "AttachClient with an invalid app ID; ignored");
return;
}
if ipc.sessions.contains_key(&session_id) {
tracing::warn!(
session_id,
"session already has a client; connection refused"
);
return;
}
let Some(disconnected) = ipc.disconnected.clone() else {
return;
};
let stream = UnixStream::from(fd);
let data = Arc::new(WeftClientState {
session: Some(SessionBinding {
session_id,
app_id: app_id.clone(),
disconnected,
}),
..WeftClientState::default()
});
match state.display_handle.insert_client(stream, data) {
Ok(client) => {
tracing::info!(session_id, %app_id, "client bound to session");
if let Some(ipc) = state.appd_ipc.as_mut() {
ipc.sessions.insert(session_id, client.id());
}
}
Err(e) => tracing::warn!(session_id, ?e, "cannot add the session's client"),
}
}
#[cfg(unix)]
pub fn compositor_socket_path() -> PathBuf {
if let Ok(p) = std::env::var("WEFT_COMPOSITOR_SOCKET") {
@ -168,6 +386,32 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
tracing::info!(path = %socket_path.display(), "compositor IPC socket open");
if let Some(ipc) = state.appd_ipc.as_mut() {
ipc.loop_handle = Some(state.loop_handle.clone());
}
// Clients bound to a session report their disconnection here.
let (sender, receiver) = channel::channel::<(u64, ClientId)>();
if let Some(ipc) = state.appd_ipc.as_mut() {
ipc.disconnected = Some(sender);
}
state
.loop_handle
.insert_source(receiver, |event, _, state| {
// Only the session's current client: a client closed when its
// appd went away may report after a new appd reused the ID.
if let channel::Event::Msg((session_id, client)) = event
&& let Some(ipc) = state.appd_ipc.as_mut()
&& ipc.sessions.get(&session_id) == Some(&client)
{
ipc.sessions.remove(&session_id);
ipc.reported.remove(&session_id);
ipc.focused_on_map.remove(&session_id);
tracing::info!(session_id, "session client disconnected");
ipc.send(&CompositorToAppd::ClientDisconnected { session_id });
}
})
.map_err(|e| anyhow::anyhow!("insert session disconnect source: {e}"))?;
let handle = state.loop_handle.clone();
state
.loop_handle
@ -177,6 +421,14 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
loop {
match listener.accept() {
Ok((stream, _addr)) => {
// One appd at a time: a second connection while
// one is live is refused rather than replacing it.
if state.appd_ipc.as_ref().is_some_and(|ipc| ipc.connected) {
tracing::warn!(
"second compositor IPC connection refused; weft-appd is connected"
);
continue;
}
tracing::info!("weft-appd connected to compositor IPC");
let write_clone = match stream.try_clone() {
Ok(c) => c,
@ -187,10 +439,12 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
};
if let Some(ipc) = &mut state.appd_ipc {
ipc.write_stream = Some(write_clone);
ipc.connected = true;
ipc.read_buf.clear();
ipc.fds.clear();
}
stream.set_nonblocking(true).ok();
let _ = handle.insert_source(
let registered = handle.insert_source(
Generic::new(stream, Interest::READ, Mode::Edge),
|_, stream, state| {
// Safety: calloop wraps the fd in NoIoDrop to prevent
@ -203,16 +457,37 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
for msg in messages {
handle_message(state, msg);
}
if let Some(ipc) = state.appd_ipc.as_mut() {
ipc.flush();
}
if eof {
tracing::info!(
"weft-appd disconnected from compositor IPC"
"weft-appd disconnected from compositor IPC; \
closing its sessions' clients"
);
let orphans = state
.appd_ipc
.as_mut()
.map(WeftAppdIpc::disconnect)
.unwrap_or_default();
for client in orphans {
state.display_handle.backend_handle().kill_client(
client,
DisconnectReason::ConnectionClosed,
);
}
Ok(PostAction::Remove)
} else {
Ok(PostAction::Continue)
}
},
);
if let Err(e) = registered {
tracing::warn!(?e, "cannot watch the appd IPC connection");
if let Some(ipc) = state.appd_ipc.as_mut() {
ipc.disconnect();
}
}
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) => tracing::warn!(?e, "accept error on compositor IPC socket"),
@ -225,3 +500,176 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> {
Ok(())
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg};
use std::mem::MaybeUninit;
use std::os::fd::AsFd;
fn send_with_fd(stream: &UnixStream, bytes: &[u8], fd: &impl AsFd) {
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut control = SendAncillaryBuffer::new(&mut space);
let fds = [fd.as_fd()];
assert!(control.push(SendAncillaryMessage::ScmRights(&fds)));
let sent = sendmsg(
stream,
&[io::IoSlice::new(bytes)],
&mut control,
SendFlags::empty(),
)
.unwrap();
assert_eq!(sent, bytes.len());
}
#[test]
fn a_connection_arrives_with_the_message_that_claims_it() {
let (appd, compositor) = UnixStream::pair().unwrap();
compositor.set_nonblocking(true).unwrap();
let (shell, client) = UnixStream::pair().unwrap();
let frame = frame_encode(&AppdToCompositor::AttachClient {
session_id: 7,
app_id: "org.weft.demo.counter".into(),
})
.unwrap();
send_with_fd(&appd, &frame, &client);
drop(client);
let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent"));
let (messages, eof) = ipc.on_read(&compositor);
assert!(!eof);
assert!(matches!(
messages.as_slice(),
[AppdToCompositor::AttachClient { session_id: 7, .. }]
));
// The received descriptor is the other end of the shell's connection.
let received = UnixStream::from(ipc.fds.pop_front().expect("no descriptor"));
use std::io::{Read, Write};
(&shell).write_all(b"hello").unwrap();
let mut buf = [0u8; 5];
(&received).read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"hello");
}
#[test]
fn descriptors_without_messages_end_the_connection() {
let (appd, compositor) = UnixStream::pair().unwrap();
compositor.set_nonblocking(true).unwrap();
let (_shell, client) = UnixStream::pair().unwrap();
let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent"));
for _ in 0..=MAX_PENDING_FDS {
send_with_fd(&appd, &[0], &client);
}
let (messages, eof) = ipc.on_read(&compositor);
assert!(messages.is_empty());
assert!(eof);
ipc.disconnect();
assert!(ipc.fds.is_empty());
}
#[test]
fn a_burst_of_attachments_is_not_mistaken_for_abuse() {
let (appd, compositor) = UnixStream::pair().unwrap();
compositor.set_nonblocking(true).unwrap();
let mut keep = Vec::new();
for session_id in 0..(MAX_PENDING_FDS as u64 + 4) {
let (shell, client) = UnixStream::pair().unwrap();
let frame = frame_encode(&AppdToCompositor::AttachClient {
session_id,
app_id: "org.weft.demo.counter".into(),
})
.unwrap();
send_with_fd(&appd, &frame, &client);
// A plain frame between attachments keeps its place.
let plain = frame_encode(&AppdToCompositor::AppFocusRequest { session_id }).unwrap();
use std::io::Write;
(&appd).write_all(&plain).unwrap();
keep.push(shell);
}
let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent"));
let mut messages = Vec::new();
let mut connections = 0;
loop {
let (batch, eof) = ipc.on_read(&compositor);
assert!(!eof, "a legitimate burst ended the connection");
if batch.is_empty() {
break;
}
// As the handler does, each attachment takes its connection.
for message in &batch {
if matches!(message, AppdToCompositor::AttachClient { .. }) {
ipc.fds
.pop_front()
.expect("an attachment without its connection");
connections += 1;
}
}
messages.extend(batch);
}
assert_eq!(connections, MAX_PENDING_FDS + 4);
assert_eq!(messages.len(), 2 * (MAX_PENDING_FDS + 4));
assert!(ipc.fds.is_empty());
}
#[test]
fn a_slow_appd_gets_whole_frames_later_instead_of_losing_its_apps() {
let (appd, compositor) = UnixStream::pair().unwrap();
compositor.set_nonblocking(true).unwrap();
let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent"));
ipc.write_stream = Some(compositor);
ipc.connected = true;
// More than the socket buffer holds while appd is not reading.
let count = 20_000u64;
for session_id in 0..count {
ipc.send(&CompositorToAppd::SurfaceReady { session_id });
}
assert!(
ipc.write_stream.is_some(),
"a full buffer closed the connection"
);
assert!(!ipc.out_buf.is_empty());
// appd reads; every flush moves more, and every frame arrives whole.
appd.set_nonblocking(true).unwrap();
let mut received = Vec::new();
let mut buf = [0u8; 65536];
loop {
ipc.flush();
use std::io::Read;
match (&appd).read(&mut buf) {
Ok(n) => received.extend_from_slice(&buf[..n]),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
if ipc.out_buf.is_empty() {
break;
}
}
Err(e) => panic!("{e}"),
}
}
let mut frames = 0u64;
while !received.is_empty() {
let len = u32::from_le_bytes(received[..4].try_into().unwrap()) as usize;
let frame: CompositorToAppd = frame_decode(&received[..4 + len]).unwrap();
assert!(
matches!(frame, CompositorToAppd::SurfaceReady { session_id } if session_id == frames)
);
received.drain(..4 + len);
frames += 1;
}
assert_eq!(frames, count);
}
#[test]
fn an_undecodable_frame_ends_the_connection() {
let (appd, compositor) = UnixStream::pair().unwrap();
compositor.set_nonblocking(true).unwrap();
use std::io::Write;
let mut frame = 3u32.to_le_bytes().to_vec();
frame.extend_from_slice(&[0xc1, 0xc1, 0xc1]);
(&appd).write_all(&frame).unwrap();
let mut ipc = WeftAppdIpc::new(PathBuf::from("/nonexistent"));
let (_, eof) = ipc.on_read(&compositor);
assert!(eof);
}
}

View file

@ -134,6 +134,8 @@ pub fn run() -> anyhow::Result<()> {
let socket_name = listening_socket.socket_name().to_os_string();
unsafe { std::env::set_var("WAYLAND_DISPLAY", &socket_name) };
tracing::info!(?socket_name, "Wayland socket open");
// Before readiness, so the units ordered after this one see it.
crate::session_env::publish_wayland_display(&socket_name);
loop_handle
.insert_source(listening_socket, |stream, _, state| {
@ -550,6 +552,7 @@ fn connector_connected(
tracing::info!(?name, "output connected");
let (pw, ph) = (wl_mode.size.w, wl_mode.size.h);
state.weft_shell_state.reconfigure_panels(0, 0, pw, ph);
state.layout_app_windows();
state.weft_shell_state.retain_alive_panels();
render_output(state, node, crtc);
}
@ -578,6 +581,7 @@ fn connector_disconnected(
.map(|g| (g.size.w, g.size.h))
.unwrap_or((0, 0));
state.weft_shell_state.reconfigure_panels(0, 0, pw, ph);
state.layout_app_windows();
state.weft_shell_state.retain_alive_panels();
}

View file

@ -60,6 +60,7 @@ pub fn run() -> anyhow::Result<()> {
let socket_name = listening_socket.socket_name().to_os_string();
unsafe { std::env::set_var("WAYLAND_DISPLAY", &socket_name) };
tracing::info!(?socket_name, "Wayland compositor socket open");
crate::session_env::publish_wayland_display(&socket_name);
loop_handle
.insert_source(listening_socket, |client_stream, _, state| {
@ -124,6 +125,7 @@ pub fn run() -> anyhow::Result<()> {
state
.weft_shell_state
.reconfigure_panels(0, 0, size.w, size.h);
state.layout_app_windows();
state.weft_shell_state.retain_alive_panels();
}
WinitEvent::Input(input_event) => {
@ -157,10 +159,8 @@ pub fn run() -> anyhow::Result<()> {
false
}
};
if render_ok {
if let Err(e) = backend.submit(Some(&[full_damage])) {
tracing::warn!(?e, "backend submit failed");
}
if render_ok && let Err(e) = backend.submit(Some(&[full_damage])) {
tracing::warn!(?e, "backend submit failed");
}
state.space.elements().for_each(|window| {
@ -187,6 +187,10 @@ pub fn run() -> anyhow::Result<()> {
})
.map_err(|e| anyhow::anyhow!("winit source insertion failed: {e}"))?;
// A Type=notify unit waits for this, as with the DRM backend.
#[cfg(target_os = "linux")]
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]);
event_loop.run(None, &mut state, |_| {})?;
Ok(())

View file

@ -6,7 +6,7 @@ use smithay::{
TouchEvent,
},
input::{
keyboard::FilterResult,
keyboard::{FilterResult, KeyboardTarget},
pointer::{AxisFrame, ButtonEvent, MotionEvent},
},
utils::{Logical, Point, SERIAL_COUNTER},
@ -42,20 +42,97 @@ pub fn process_input_event<B: InputBackend>(state: &mut WeftCompositorState, eve
}
}
/// What the compositor does with a key instead of forwarding it.
enum Shortcut {
/// Alt+F4: close the focused application window.
Close,
/// A Super key tap: show the shell.
Shell,
/// Nothing: a suppressed key.
None,
}
fn handle_keyboard<B: InputBackend>(state: &mut WeftCompositorState, event: B::KeyboardKeyEvent) {
use smithay::backend::input::KeyState;
use smithay::input::keyboard::keysyms;
let serial = SERIAL_COUNTER.next_serial();
let time = event.time_msec();
let key_state = event.state();
let Some(keyboard) = state.seat.get_keyboard() else {
return;
};
if let Some(keyboard) = state.seat.get_keyboard() {
keyboard.input::<(), _>(
state,
event.key_code(),
key_state,
serial,
time,
|_state, _mods, _keysym| FilterResult::Forward,
);
// Alt+F4 and the Super keys belong to the compositor. Alt+F4 asks the
// focused application window to close. Super's key events are never
// delivered to an application: tapped alone, without another key or a
// button, it brings the shell's panel to the front with keyboard focus
// and is then delivered to the shell, which opens or closes its
// launcher. Held, it still sets the Super modifier for other keys.
let (filtered, mods_changed) = keyboard.input_intercept::<_, _>(
state,
event.key_code(),
key_state,
|state, mods, keysym| {
// A release is taken only when its press was, so no client
// sees half of a key.
let code = keysym.raw_code().raw();
let sym = keysym.modified_sym();
if key_state == KeyState::Pressed {
if mods.alt && sym == keysyms::KEY_F4.into() {
state.super_tap = None;
state.suppressed_keys.push(code);
return FilterResult::Intercept(Shortcut::Close);
}
if sym == keysyms::KEY_Super_L.into() || sym == keysyms::KEY_Super_R.into() {
state.super_tap = (!mods.ctrl && !mods.alt && !mods.shift).then_some(code);
state.suppressed_keys.push(code);
return FilterResult::Intercept(Shortcut::None);
}
state.super_tap = None;
} else if let Some(i) = state.suppressed_keys.iter().position(|&k| k == code) {
state.suppressed_keys.remove(i);
if state.super_tap.take() == Some(code) {
return FilterResult::Intercept(Shortcut::Shell);
}
return FilterResult::Intercept(Shortcut::None);
}
FilterResult::Forward
},
);
let shortcut = match filtered {
FilterResult::Forward => {
keyboard.input_forward(
state,
event.key_code(),
key_state,
serial,
time,
mods_changed,
);
return;
}
FilterResult::Intercept(shortcut) => shortcut,
};
// The focused client follows the modifiers even when the key that
// changed them is taken, so none stays held there.
if mods_changed && let Some(focus) = keyboard.current_focus() {
let seat = state.seat.clone();
focus.modifiers(&seat, state, keyboard.modifier_state(), serial);
}
match shortcut {
Shortcut::Close => state.close_focused_window(),
Shortcut::Shell => {
if state.activate_panel() {
// The tap itself, for the shell; the keyboard's own state
// already saw it.
let code = event.key_code();
keyboard.input_forward(state, code, KeyState::Pressed, serial, time, false);
let release = SERIAL_COUNTER.next_serial();
keyboard.input_forward(state, code, KeyState::Released, release, time, false);
}
}
Shortcut::None => {}
}
}
@ -122,10 +199,19 @@ fn handle_pointer_button<B: InputBackend>(
let button = event.button_code();
let button_state = event.state();
// On press: focus the surface under the pointer.
// On press: activate the window under the pointer, which raises an
// application window and focuses it. A held Super key is then no
// longer a tap.
if button_state == ButtonState::Pressed {
state.super_tap = None;
let pointer_location = state.pointer_location;
if let Some((surface, _loc)) = surface_under(state, pointer_location) {
let window = state
.space
.element_under(pointer_location)
.map(|(window, _)| window.clone());
if let Some(window) = window {
state.activate_window(&window);
} else if let Some((surface, _loc)) = surface_under(state, pointer_location) {
if let Some(keyboard) = state.seat.get_keyboard() {
keyboard.set_focus(state, Some(surface), serial);
}
@ -193,6 +279,7 @@ fn handle_pointer_axis<B: InputBackend>(
}
fn handle_touch_down<B: InputBackend>(state: &mut WeftCompositorState, event: B::TouchDownEvent) {
state.super_tap = None;
let serial = SERIAL_COUNTER.next_serial();
let output = state.space.outputs().next().cloned();
if let Some(output) = output {

View file

@ -4,7 +4,9 @@ mod appd_ipc;
mod backend;
mod input;
mod protocols;
mod session_env;
mod state;
mod windows;
fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()

View file

@ -33,6 +33,8 @@ pub struct WeftShellWindowData {
pub role: String,
pub surface: Option<wayland_server::protocol::wl_surface::WlSurface>,
pub closed: std::sync::atomic::AtomicBool,
/// The edge strip a panel reserved with set_exclusive_zone.
pub exclusive_zone: std::sync::Mutex<Option<(server::zweft_shell_window_v1::Edge, i32)>>,
}
impl WeftShellState {
@ -41,7 +43,7 @@ impl WeftShellState {
D: GlobalDispatch<ZweftShellManagerV1, ()>,
D: 'static,
{
let global = display.create_global::<D, ZweftShellManagerV1, ()>(2, ());
let global = display.create_global::<D, ZweftShellManagerV1, ()>(3, ());
Self {
_global: global,
panels: Vec::new(),
@ -52,6 +54,13 @@ impl WeftShellState {
self.panels.push(window);
}
/// Forgets a panel; returns whether it was one.
pub fn remove_panel(&mut self, window: &ZweftShellWindowV1) -> bool {
let before = self.panels.len();
self.panels.retain(|panel| panel != window);
self.panels.len() != before
}
pub fn reconfigure_panels(&self, x: i32, y: i32, width: i32, height: i32) {
for panel in &self.panels {
if panel.is_alive() {
@ -97,6 +106,7 @@ mod tests {
role: "normal".into(),
surface: None,
closed: std::sync::atomic::AtomicBool::new(false),
exclusive_zone: std::sync::Mutex::new(None),
};
assert_eq!(d.app_id, "com.example.test");
assert_eq!(d.title, "Test Window");
@ -112,6 +122,7 @@ mod tests {
role: String::new(),
surface: None,
closed: std::sync::atomic::AtomicBool::new(false),
exclusive_zone: std::sync::Mutex::new(None),
};
assert!(!d.closed.load(Ordering::Relaxed));
d.closed.store(true, Ordering::Relaxed);
@ -122,14 +133,14 @@ mod tests {
fn manager_interface_name_and_version() {
let iface = ZweftShellManagerV1::interface();
assert_eq!(iface.name, "zweft_shell_manager_v1");
assert_eq!(iface.version, 2);
assert_eq!(iface.version, 3);
}
#[test]
fn window_interface_name_and_version() {
let iface = ZweftShellWindowV1::interface();
assert_eq!(iface.name, "zweft_shell_window_v1");
assert_eq!(iface.version, 2);
assert_eq!(iface.version, 3);
}
#[test]

View file

@ -0,0 +1,85 @@
//! Tells the systemd user manager which Wayland socket the compositor
//! serves, so the services started after it, the shell and weft-appd and
//! through it the app shells, connect to this compositor. Only done when
//! systemd started the compositor; its own unit unsets the variable, so a
//! restarted compositor does not mistake the value for an enclosing
//! Wayland session.
use std::ffi::{OsStr, OsString};
use std::process::{Command, Stdio};
/// Publishes `socket_name` as `WAYLAND_DISPLAY` for the units the user
/// manager starts from now on, when running under systemd.
pub fn publish_wayland_display(socket_name: &OsStr) {
if std::env::var_os("NOTIFY_SOCKET").is_none() {
return;
}
publish_with(OsStr::new("systemctl"), socket_name);
}
fn publish_with(systemctl: &OsStr, socket_name: &OsStr) -> bool {
let mut assignment = OsString::from("WAYLAND_DISPLAY=");
assignment.push(socket_name);
let status = Command::new(systemctl)
.args(["--user", "set-environment"])
.arg(&assignment)
.stdin(Stdio::null())
.status();
match status {
Ok(status) if status.success() => {
tracing::info!(
?socket_name,
"WAYLAND_DISPLAY published to the user manager"
);
true
}
Ok(status) => {
tracing::warn!(%status, "cannot publish WAYLAND_DISPLAY to the user manager");
false
}
Err(e) => {
tracing::warn!(error = %e, "cannot publish WAYLAND_DISPLAY to the user manager");
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn the_socket_name_is_set_in_the_user_manager() {
let dir = std::env::temp_dir().join(format!("weft_session_env_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let record = dir.join("args");
let fake = dir.join("systemctl");
std::fs::write(
&fake,
format!(
"#!/bin/sh\nprintf '%s\\n' \"$@\" > '{}'\n",
record.display()
),
)
.unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(publish_with(fake.as_os_str(), OsStr::new("wayland-3")));
assert_eq!(
std::fs::read_to_string(&record).unwrap(),
"--user\nset-environment\nWAYLAND_DISPLAY=wayland-3\n"
);
let failing = dir.join("failing");
std::fs::write(&failing, "#!/bin/sh\nexit 1\n").unwrap();
std::fs::set_permissions(&failing, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(!publish_with(failing.as_os_str(), OsStr::new("wayland-3")));
assert!(!publish_with(
dir.join("missing").as_os_str(),
OsStr::new("wayland-3")
));
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -53,11 +53,35 @@ use smithay::{
#[derive(Default)]
pub struct WeftClientState {
pub compositor_state: CompositorClientState,
/// The appd session this client's connection was created for. Clients
/// that connect through the display socket have none.
pub session: Option<SessionBinding>,
}
/// The appd session a client belongs to, established by weft-appd handing
/// the compositor the client's connection, never by the client itself.
pub struct SessionBinding {
pub session_id: u64,
pub app_id: String,
/// Reports the session's disconnection to the event loop.
pub disconnected: smithay::reexports::calloop::channel::Sender<(u64, ClientId)>,
}
/// Whether `client` connected through the display socket rather than
/// through a connection weft-appd created for an application session.
pub fn outside_sessions(client: &Client) -> bool {
client
.get_data::<WeftClientState>()
.is_none_or(|data| data.session.is_none())
}
impl ClientData for WeftClientState {
fn initialized(&self, _client_id: ClientId) {}
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
fn disconnected(&self, client_id: ClientId, _reason: DisconnectReason) {
if let Some(binding) = &self.session {
let _ = binding.disconnected.send((binding.session_id, client_id));
}
}
}
/// Accumulated state for a multi-touch swipe gesture in progress.
@ -74,6 +98,12 @@ pub struct WeftCompositorState {
pub loop_signal: LoopSignal,
pub loop_handle: LoopHandle<'static, WeftCompositorState>,
pub gesture_state: GestureState,
/// Keycodes whose press a compositor shortcut took, so their release is
/// taken as well and no client sees half of a key.
pub suppressed_keys: Vec<u32>,
/// The Super key held down while no other key was pressed since; its
/// release is a tap that opens the shell.
pub super_tap: Option<u32>,
pub compositor_state: CompositorState,
pub xdg_shell_state: XdgShellState,
@ -124,7 +154,10 @@ impl WeftCompositorState {
) -> Self {
let compositor_state = CompositorState::new::<Self>(&display_handle);
let xdg_shell_state = XdgShellState::new::<Self>(&display_handle);
let layer_shell_state = WlrLayerShellState::new::<Self>(&display_handle);
// Layer surfaces and input methods are shell-level: an application
// session's client is not offered them.
let layer_shell_state =
WlrLayerShellState::new_with_filter::<Self, _>(&display_handle, outside_sessions);
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
let dmabuf_state = DmabufState::new();
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
@ -132,7 +165,7 @@ impl WeftCompositorState {
let presentation_state = PresentationState::new::<Self>(&display_handle, 1);
let text_input_state = TextInputManagerState::new::<Self>(&display_handle);
let input_method_state =
InputMethodManagerState::new::<Self, _>(&display_handle, |_client| true);
InputMethodManagerState::new::<Self, _>(&display_handle, outside_sessions);
let pointer_constraints_state = PointerConstraintsState::new::<Self>(&display_handle);
let cursor_shape_state = CursorShapeManagerState::new::<Self>(&display_handle);
let weft_shell_state = WeftShellState::new::<Self>(&display_handle);
@ -169,6 +202,8 @@ impl WeftCompositorState {
dmabuf_global: None,
running: true,
gesture_state: GestureState::default(),
suppressed_keys: Vec::new(),
super_tap: None,
#[cfg(unix)]
appd_ipc: None,
#[cfg(target_os = "linux")]
@ -239,10 +274,22 @@ impl XdgShellHandler for WeftCompositorState {
&mut self.xdg_shell_state
}
fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
self.window_closed(surface.wl_surface());
}
fn new_toplevel(&mut self, surface: ToplevelSurface) {
surface.send_configure();
let session = surface.wl_surface().client().and_then(|client| {
client
.get_data::<WeftClientState>()
.and_then(|data| data.session.as_ref().map(|s| s.session_id))
});
let window = Window::new_wayland_window(surface);
self.space.map_element(window, (0, 0), false);
self.map_new_window(window);
if let (Some(session_id), Some(ipc)) = (session, self.appd_ipc.as_mut()) {
ipc.surface_created(session_id);
}
}
fn new_popup(&mut self, surface: PopupSurface, positioner: PositionerState) {
@ -466,7 +513,7 @@ impl GlobalDispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
fn request(
state: &mut Self,
_client: &Client,
client: &Client,
_resource: &ZweftShellManagerV1,
request: zweft_shell_manager_v1::Request,
_data: &(),
@ -486,6 +533,14 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
width,
height,
} => {
// An application session's windows carry the identity appd
// bound to its connection, and only the trusted shell, which
// connects through the display socket, may take shell roles.
let session = client
.get_data::<WeftClientState>()
.and_then(|data| data.session.as_ref());
let shell_role = matches!(role.as_str(), "panel" | "overlay");
let app_id = session.map_or(app_id, |s| s.app_id.clone());
let is_panel = role == "panel";
let window = data_init.init(
id,
@ -495,8 +550,21 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
role,
surface,
closed: std::sync::atomic::AtomicBool::new(false),
exclusive_zone: std::sync::Mutex::new(None),
},
);
if let Some(session) = session
&& shell_role
{
window.post_error(
crate::protocols::server::zweft_shell_window_v1::Error::RoleNotPermitted,
format!(
"session {} ({}) may not create shell windows",
session.session_id, session.app_id
),
);
return;
}
if is_panel {
let (ox, oy, ow, oh) = state
.space
@ -515,8 +583,13 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
),
);
state.weft_shell_state.add_panel(window);
state.fit_panels();
} else {
window.configure(x, y, width, height, 0);
// The compositor decides application geometry: the work
// area, whatever was requested.
let _ = (x, y, width, height);
let (x, y, w, h) = state.app_geometry();
window.configure(x, y, w, h, 0);
}
}
}
@ -525,7 +598,7 @@ impl Dispatch<ZweftShellManagerV1, ()> for WeftCompositorState {
impl Dispatch<ZweftShellWindowV1, WeftShellWindowData> for WeftCompositorState {
fn request(
_state: &mut Self,
state: &mut Self,
_client: &Client,
resource: &ZweftShellWindowV1,
request: zweft_shell_window_v1::Request,
@ -545,14 +618,64 @@ impl Dispatch<ZweftShellWindowV1, WeftShellWindowData> for WeftCompositorState {
zweft_shell_window_v1::Request::UpdateMetadata { title, role } => {
let _ = (title, role);
}
zweft_shell_window_v1::Request::SetGeometry {
x,
y,
width,
height,
} => {
resource.configure(x, y, width, height, 0);
zweft_shell_window_v1::Request::SetGeometry { .. } => {
// The request is advisory: the configure reports the
// geometry the compositor's layout gives the window.
let is_panel = state
.weft_shell_state
.panels()
.any(|panel| panel == resource);
let (x, y, w, h) = if is_panel {
state.output_geometry()
} else {
state.app_geometry()
};
let flags = if is_panel {
u32::from(crate::protocols::server::zweft_shell_window_v1::State::Maximized)
} else {
0
};
resource.configure(x, y, w, h, flags);
}
zweft_shell_window_v1::Request::SetExclusiveZone { edge, size } => {
let is_panel = state
.weft_shell_state
.panels()
.any(|panel| panel == resource);
let edge = edge.into_result().ok();
match edge {
Some(edge) if is_panel && size >= 0 => {
let zone = (size > 0).then_some((edge, size));
*data
.exclusive_zone
.lock()
.unwrap_or_else(|p| p.into_inner()) = zone;
state.layout_app_windows();
}
_ => resource.post_error(
crate::protocols::server::zweft_shell_window_v1::Error::InvalidExclusiveZone,
"only a panel may reserve an edge, with a size of at least 0",
),
}
}
}
}
fn destroyed(
state: &mut Self,
_client: wayland_server::backend::ClientId,
resource: &ZweftShellWindowV1,
data: &WeftShellWindowData,
) {
// A panel that goes away, by destroy or with its client, releases
// its reserved strip and its window slot; applications take the
// space back. The surface's window is not mapped again if it
// registers once more.
if state.weft_shell_state.remove_panel(resource) {
if let Some(surface) = &data.surface {
state.window_closed(surface);
}
state.layout_app_windows();
}
}
}

View file

@ -0,0 +1,362 @@
//! Stacking, focus and activation of toplevel windows.
//!
//! The compositor decides the order and the geometry. The trusted shell's
//! panel fills the output and starts beneath every application window;
//! application windows fill the work area, the output less the strips the
//! panel reserves. A session's first window, a clicked window (the panel
//! included, which then shows the shell's home over the applications), one
//! appd asks to activate and the panel when a Super key is tapped are
//! raised to the top, marked activated and given keyboard focus; apart
//! from a panel being lowered when it registers, nothing else changes the
//! order, and a window that maps without taking focus goes beneath the
//! window in front. When the focused window closes, the topmost remaining
//! application window gets focus.
use smithay::desktop::Window;
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
use smithay::reexports::wayland_server::Resource;
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::utils::{Logical, Rectangle, SERIAL_COUNTER};
use smithay::wayland::seat::WaylandFocus;
use crate::protocols::WeftShellWindowData;
use crate::state::{WeftClientState, WeftCompositorState};
impl WeftCompositorState {
/// Whether `surface` backs a window the trusted shell registered as its
/// panel.
pub fn is_panel_surface(&self, surface: &WlSurface) -> bool {
self.weft_shell_state
.panels()
.filter(|p| p.is_alive())
.any(|panel| {
panel
.data::<WeftShellWindowData>()
.and_then(|data| data.surface.as_ref())
.is_some_and(|s| s == surface)
})
}
fn is_panel(&self, window: &Window) -> bool {
window
.wl_surface()
.is_some_and(|surface| self.is_panel_surface(&surface))
}
/// Raises `window` to the top, marks it activated and gives it keyboard
/// focus. Activating the panel shows the shell's home, with its launcher,
/// over the applications until one is activated again.
pub fn activate_window(&mut self, window: &Window) {
self.space.raise_element(window, true);
self.send_pending_configures();
if let (Some(keyboard), Some(surface)) = (self.seat.get_keyboard(), window.wl_surface()) {
keyboard.set_focus(
self,
Some(surface.into_owned()),
SERIAL_COUNTER.next_serial(),
);
}
}
/// Activates the shell's panel; returns whether one is registered. With
/// several, the first registered is the shell's.
pub fn activate_panel(&mut self) -> bool {
let panel = self
.weft_shell_state
.panels()
.filter(|p| p.is_alive())
.find_map(|panel| {
let surface = panel
.data::<WeftShellWindowData>()
.and_then(|data| data.surface.clone())?;
self.space
.elements()
.find(|window| window.wl_surface().is_some_and(|s| *s == surface))
.cloned()
});
match panel {
Some(panel) => {
self.activate_window(&panel);
true
}
None => false,
}
}
/// Asks the focused application window to close. Its client decides
/// how to end; for an app shell that ends the session. The panel is not
/// closed this way.
pub fn close_focused_window(&mut self) {
let Some(focus) = self
.seat
.get_keyboard()
.and_then(|keyboard| keyboard.current_focus())
else {
return;
};
if self.is_panel_surface(&focus) {
return;
}
let window = self
.space
.elements()
.find(|window| window.wl_surface().is_some_and(|s| *s == focus))
.cloned();
if let Some(toplevel) = window.as_ref().and_then(|w| w.toplevel()) {
tracing::info!(session = ?window.as_ref().and_then(window_session), "closing the focused window");
toplevel.send_close();
}
}
/// Asks every window of `session_id` to close; returns how many.
pub fn close_session_windows(&mut self, session_id: u64) -> usize {
let mut closed = 0;
for window in self.space.elements() {
if window_session(window) == Some(session_id)
&& let Some(toplevel) = window.toplevel()
{
toplevel.send_close();
closed += 1;
}
}
closed
}
/// Activates the topmost window of `session_id`; returns whether the
/// session has one.
pub fn activate_session(&mut self, session_id: u64) -> bool {
let window = self
.space
.elements()
.rev()
.find(|window| window_session(window) == Some(session_id))
.cloned();
match window {
Some(window) => {
self.activate_window(&window);
true
}
None => false,
}
}
/// Sizes the panels to the output and keeps them beneath every
/// application window; used when a panel registers.
pub fn fit_panels(&mut self) {
self.place_windows(true, None);
// A shell that took focus before registering as the panel, such as
// one restarted while applications run, hands it to the window that
// is now in front.
let focus_on_panel = self
.seat
.get_keyboard()
.and_then(|keyboard| keyboard.current_focus())
.is_some_and(|focus| self.is_panel_surface(&focus));
let front = self.space.elements().last().cloned();
if focus_on_panel
&& let Some(front) = front
&& !self.is_panel(&front)
{
self.activate_window(&front);
}
}
/// Places every window for the current output and reservations: panels
/// fill the output, application windows the work area. The stacking
/// order is kept, except that `lower_panels` moves the panels beneath
/// the applications, and `below_top` slips that window under the
/// window that was on top.
pub fn place_windows(&mut self, lower_panels: bool, below_top: Option<&Window>) {
// Without an output the order still changes; windows keep their
// size and place until one is mapped.
let output = self
.space
.outputs()
.next()
.and_then(|output| self.space.output_geometry(output));
let area = self.work_area();
let mut order: Vec<Window> = self.space.elements().cloned().collect();
if lower_panels {
let (panels, apps): (Vec<Window>, Vec<Window>) =
order.into_iter().partition(|window| self.is_panel(window));
order = panels.into_iter().chain(apps).collect();
}
if let Some(window) = below_top
&& let Some(position) = order.iter().position(|w| w == window)
&& position + 1 == order.len()
&& order.len() > 1
{
order.swap(position, position - 1);
}
for window in &order {
let panel = self.is_panel(window);
let Some(geometry) = (if panel { output } else { area }) else {
let location = self.space.element_location(window).unwrap_or_default();
self.space.map_element(window.clone(), location, false);
continue;
};
if let Some(toplevel) = window.toplevel() {
toplevel.with_pending_state(|state| {
state.size = Some(geometry.size);
state.states.set(xdg_toplevel::State::Maximized);
});
toplevel.send_pending_configure();
}
// Mapping puts a window on top; mapping all of them in `order`
// leaves exactly that order.
self.space.map_element(window.clone(), geometry.loc, false);
}
}
/// Maps a new toplevel. The first window a session maps in its lifetime
/// comes to the front with keyboard focus; its later windows, including
/// recreated ones, are shown without taking focus, so a session cannot
/// take keystrokes meant for another application by creating windows.
/// A client outside any session (one connected through the display
/// socket) takes focus only while no other such window is mapped. A
/// panel is fitted and kept beneath.
pub fn map_new_window(&mut self, window: Window) {
let session = window_session(&window);
let first = match session {
Some(session_id) => self
.appd_ipc
.as_mut()
.is_some_and(|ipc| ipc.take_focus_on_map(session_id)),
None => !self
.space
.elements()
.any(|other| window_session(other).is_none()),
};
self.space.map_element(window.clone(), (0, 0), false);
if self.is_panel(&window) {
self.fit_panels();
} else if first {
self.layout_app_windows();
self.activate_window(&window);
} else {
// A window that does not take focus does not cover the window
// in front either, the shell's home included.
self.place_windows(false, Some(&window));
}
}
/// Unmaps a closed toplevel and, if it had keyboard focus, gives focus
/// to the topmost remaining application window, or the panel.
pub fn window_closed(&mut self, surface: &WlSurface) {
let Some(window) = self
.space
.elements()
.find(|window| window.wl_surface().is_some_and(|s| *s == *surface))
.cloned()
else {
return;
};
self.space.unmap_elem(&window);
let had_focus = self
.seat
.get_keyboard()
.and_then(|keyboard| keyboard.current_focus())
.is_none_or(|focus| focus == *surface);
if !had_focus {
return;
}
let next = self
.space
.elements()
.rev()
.find(|window| !self.is_panel(window))
.or_else(|| self.space.elements().next())
.cloned();
match next {
Some(next) => self.activate_window(&next),
None => {
if let Some(keyboard) = self.seat.get_keyboard() {
keyboard.set_focus(self, None, SERIAL_COUNTER.next_serial());
}
}
}
}
/// The part of the output that application windows occupy: the output
/// less the strips the panels reserved.
pub fn work_area(&self) -> Option<Rectangle<i32, Logical>> {
use crate::protocols::server::zweft_shell_window_v1::Edge;
let output = self.space.outputs().next()?;
let mut area = self.space.output_geometry(output)?;
for panel in self.weft_shell_state.panels().filter(|p| p.is_alive()) {
let Some(data) = panel.data::<WeftShellWindowData>() else {
continue;
};
let zone = *data
.exclusive_zone
.lock()
.unwrap_or_else(|p| p.into_inner());
let Some((edge, size)) = zone else {
continue;
};
match edge {
Edge::Top => {
let size = size.min(area.size.h);
area.loc.y += size;
area.size.h -= size;
}
Edge::Bottom => area.size.h -= size.min(area.size.h),
Edge::Left => {
let size = size.min(area.size.w);
area.loc.x += size;
area.size.w -= size;
}
Edge::Right => area.size.w -= size.min(area.size.w),
}
}
// A zone covering the output still leaves applications a size the
// client must honour, never 0, which would let it pick its own.
area.size.w = area.size.w.max(1);
area.size.h = area.size.h.max(1);
Some(area)
}
/// The output's geometry as (x, y, width, height).
pub fn output_geometry(&self) -> (i32, i32, i32, i32) {
self.space
.outputs()
.next()
.and_then(|output| self.space.output_geometry(output))
.map_or((0, 0, 0, 0), |g| (g.loc.x, g.loc.y, g.size.w, g.size.h))
}
/// The geometry the layout gives application windows, as
/// (x, y, width, height).
pub fn app_geometry(&self) -> (i32, i32, i32, i32) {
self.work_area()
.map_or((0, 0, 0, 0), |a| (a.loc.x, a.loc.y, a.size.w, a.size.h))
}
/// Lays the windows out again after the work area changed, keeping the
/// stacking order.
pub fn layout_app_windows(&mut self) {
self.place_windows(false, None);
}
/// Sends the configure for every toplevel whose pending state changed,
/// such as its activated state.
fn send_pending_configures(&self) {
for window in self.space.elements() {
if let Some(toplevel) = window.toplevel() {
toplevel.send_pending_configure();
}
}
}
}
/// The appd session `window`'s client is bound to, if any.
pub fn window_session(window: &Window) -> Option<u64> {
window
.toplevel()?
.wl_surface()
.client()?
.get_data::<WeftClientState>()?
.session
.as_ref()
.map(|binding| binding.session_id)
}

View file

@ -13,3 +13,6 @@ anyhow = "1.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
base64 = "0.22"
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "1", features = ["fs"] }

View file

@ -1,17 +1,37 @@
#[cfg(unix)]
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
//! A per-session file proxy for the directories a session is granted.
//!
//! Requests name absolute host paths inside a granted directory. Each
//! granted directory is opened once at startup, and every operation resolves
//! the rest of the path relative to that descriptor with `openat2` and
//! `RESOLVE_BENEATH`, so the kernel keeps it inside the directory while it
//! runs: `..`, absolute symbolic links, links that point outside and links
//! replaced during the operation cannot leave it. Paths must name their
//! location directly, without `.` or `..` components. Writes replace a file
//! atomically and never create directories.
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
#[cfg(unix)]
use std::sync::Arc;
#[cfg(unix)]
use anyhow::Context;
#[cfg(unix)]
use std::os::unix::net::{UnixListener, UnixStream};
/// The largest file read or written, in bytes.
const MAX_FILE: usize = 16 * 1024 * 1024;
/// The longest request line: a write of the largest file, base64-encoded,
/// with room for its path.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const MAX_LINE: usize = MAX_FILE / 3 * 4 + 64 * 1024;
/// The most entries one listing returns.
const MAX_ENTRIES: usize = 10_000;
/// The most connections served at once.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const MAX_CONNECTIONS: usize = 4;
/// How long a connection may stay silent before it is closed.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
/// The prefix of the temporary files writes create, never listed.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const TEMPORARY_PREFIX: &str = ".weft-portal-";
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
@ -38,86 +58,207 @@ impl Response {
}
}
#[cfg(unix)]
#[cfg(target_os = "linux")]
fn main() -> anyhow::Result<()> {
use anyhow::Context;
use std::os::unix::net::UnixListener;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("usage: weft-file-portal <socket_path> [--allow <path>]...");
eprintln!(
"usage: weft-file-portal <socket_path> [--allow <path>]... [--allow-read <path>]..."
);
std::process::exit(1);
}
let socket_path = &args[1];
let allowed = Arc::new(parse_allowed(&args[2..]));
let mut roots = Vec::new();
for grant in parse_allowed(&args[2..]) {
match Root::open(grant) {
Ok(root) => roots.push(root),
Err((path, e)) => eprintln!("cannot open granted directory {}: {e}", path.display()),
}
}
let roots = Arc::new(roots);
if Path::new(socket_path).exists() {
std::fs::remove_file(socket_path)
.with_context(|| format!("remove stale socket {socket_path}"))?;
}
let listener =
UnixListener::bind(socket_path).with_context(|| format!("bind {socket_path}"))?;
let active = Arc::new(AtomicUsize::new(0));
for stream in listener.incoming() {
match stream {
Ok(s) => {
let allowed = Arc::clone(&allowed);
std::thread::spawn(move || handle_connection(s, &allowed));
let mut stream = match stream {
Ok(s) => s,
Err(e) => {
eprintln!("accept error: {e}");
continue;
}
Err(e) => eprintln!("accept error: {e}"),
};
if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
active.fetch_sub(1, Ordering::SeqCst);
let _ = stream.write_all(b"{\"error\":\"too many connections\"}\n");
continue;
}
// The slot is released however the connection ends, a panic
// included.
struct Slot(Arc<AtomicUsize>);
impl Drop for Slot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
let slot = Slot(Arc::clone(&active));
let roots = Arc::clone(&roots);
if let Err(e) = std::thread::Builder::new().spawn(move || {
let _slot = slot;
handle_connection(stream, &roots);
}) {
eprintln!("cannot serve a connection: {e}");
}
}
Ok(())
}
#[cfg(not(unix))]
#[cfg(not(target_os = "linux"))]
fn main() -> anyhow::Result<()> {
anyhow::bail!("weft-file-portal requires a Unix platform")
anyhow::bail!("weft-file-portal requires Linux")
}
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
fn parse_allowed(args: &[String]) -> Vec<PathBuf> {
/// A directory the session may use: `--allow` grants reading and writing,
/// `--allow-read` reading only.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Allowed {
root: PathBuf,
writable: bool,
}
fn parse_allowed(args: &[String]) -> Vec<Allowed> {
let mut allowed = Vec::new();
let mut i = 0;
while i < args.len() {
if args[i] == "--allow"
&& let Some(p) = args.get(i + 1)
{
allowed.push(PathBuf::from(p));
i += 2;
continue;
let writable = match args[i].as_str() {
"--allow" => true,
"--allow-read" => false,
_ => {
i += 1;
continue;
}
};
if let Some(p) = args.get(i + 1) {
allowed.push(Allowed {
root: PathBuf::from(p),
writable,
});
}
i += 1;
i += 2;
}
allowed
}
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
fn normalize_path(path: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for c in path.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
other => out.push(other),
/// The part of `path` inside the granted directory `root`, if `path` lies
/// in it and names its location directly: an absolute path of plain
/// components only, without `.`, `..`, empty components or a trailing `/`.
/// The text is checked as given, since path parsing drops `.` and repeated
/// separators.
fn relative_to<'a>(path: &'a Path, root: &Path) -> Option<&'a Path> {
let text = path.to_str()?;
let direct = text.starts_with('/')
&& text[1..]
.split('/')
.all(|segment| !matches!(segment, "" | "." | ".."));
if !direct {
return None;
}
let rest = path.strip_prefix(root).ok()?;
rest.components()
.all(|c| matches!(c, Component::Normal(_)))
.then_some(rest)
}
/// A granted directory, held open for the life of the portal.
#[cfg(target_os = "linux")]
struct Root {
path: PathBuf,
dir: rustix::fd::OwnedFd,
writable: bool,
}
#[cfg(target_os = "linux")]
impl Root {
fn open(grant: Allowed) -> Result<Self, (PathBuf, std::io::Error)> {
use rustix::fs::{Mode, OFlags};
match rustix::fs::open(
&grant.root,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(dir) => Ok(Self {
path: grant.root,
dir,
writable: grant.writable,
}),
Err(e) => Err((grant.root, e.into())),
}
}
out
}
fn is_allowed(path: &Path, allowed: &[PathBuf]) -> bool {
if allowed.is_empty() {
return false;
}
let norm = normalize_path(path);
allowed.iter().any(|a| norm.starts_with(a))
/// The granted directory holding `path` and the path inside it, for an
/// operation that writes when `write` is set.
#[cfg(target_os = "linux")]
fn locate<'a, 'p>(
roots: &'a [Root],
path: &'p str,
write: bool,
) -> Result<(&'a Root, &'p Path), Response> {
let requested = Path::new(path);
roots
.iter()
.filter(|root| root.writable || !write)
.find_map(|root| relative_to(requested, &root.path).map(|rest| (root, rest)))
.ok_or_else(|| Response::err(format!("access denied: {path}")))
}
#[cfg(unix)]
fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) {
/// Opens `rest` inside `root`, never leaving it.
#[cfg(target_os = "linux")]
fn open_beneath(
root: &Root,
rest: &Path,
flags: rustix::fs::OFlags,
) -> std::io::Result<rustix::fd::OwnedFd> {
use rustix::fs::{Mode, OFlags, ResolveFlags};
let rest = if rest.as_os_str().is_empty() {
Path::new(".")
} else {
rest
};
rustix::fs::openat2(
&root.dir,
rest,
flags | OFlags::CLOEXEC | OFlags::NOCTTY,
Mode::empty(),
ResolveFlags::BENEATH | ResolveFlags::NO_MAGICLINKS,
)
.map_err(|e| {
// The kernel reports a resolution that would leave the directory as
// EXDEV.
if e == rustix::io::Errno::XDEV {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"access denied: the path leads out of the granted directory",
)
} else {
e.into()
}
})
}
#[cfg(target_os = "linux")]
fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) {
let mut writer = match stream.try_clone() {
Ok(s) => s,
Err(e) => {
@ -125,22 +266,33 @@ fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) {
return;
}
};
let reader = BufReader::new(stream);
for line in reader.lines() {
let line = match line {
Ok(l) => l,
Err(_) => break,
};
if line.is_empty() {
let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT));
let _ = stream.set_write_timeout(Some(IDLE_TIMEOUT));
let mut reader = BufReader::new(stream);
let mut line = Vec::new();
loop {
line.clear();
match (&mut reader)
.take(MAX_LINE as u64 + 3)
.read_until(b'\n', &mut line)
{
Ok(0) | Err(_) => break,
Ok(_) => {}
}
let content = line.strip_suffix(b"\n").unwrap_or(&line);
if content.strip_suffix(b"\r").unwrap_or(content).len() > MAX_LINE {
let _ = writer.write_all(b"{\"error\":\"request too long\"}\n");
break;
}
let text = String::from_utf8_lossy(&line);
let text = text.trim_end_matches(['\n', '\r']);
if text.is_empty() {
continue;
}
let response = match serde_json::from_str::<Request>(&line) {
Ok(req) => handle_request(req, allowed),
let response = match serde_json::from_str::<Request>(text) {
Ok(req) => handle_request(req, roots),
Err(e) => Response::err(format!("bad request: {e}")),
};
let mut out = serde_json::to_string(&response)
.unwrap_or_else(|_| r#"{"error":"serialize"}"#.to_string());
out.push('\n');
@ -150,96 +302,175 @@ fn handle_connection(stream: UnixStream, allowed: &[PathBuf]) {
}
}
#[cfg_attr(not(any(unix, test)), allow(dead_code))]
fn handle_request(req: Request, allowed: &[PathBuf]) -> Response {
match req {
#[cfg(target_os = "linux")]
fn handle_request(req: Request, roots: &[Root]) -> Response {
let result = match req {
Request::Read { path } => {
let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) {
return Response::err(format!("access denied: {path}"));
}
match std::fs::read(&p) {
Ok(data) => Response::OkData {
data_b64: base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
&data,
),
},
Err(e) => Response::err(e),
}
locate(roots, &path, false).and_then(|(root, rest)| read(root, rest))
}
Request::Write { path, data_b64 } => {
let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) {
return Response::err(format!("access denied: {path}"));
}
Request::Write { path, data_b64 } => locate(roots, &path, true).and_then(|(root, rest)| {
let data =
match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
{
Ok(d) => d,
Err(e) => return Response::err(format!("bad base64: {e}")),
};
if let Some(Err(e)) = p.parent().map(std::fs::create_dir_all) {
return Response::err(e);
}
match std::fs::write(&p, &data) {
Ok(()) => Response::Ok,
Err(e) => Response::err(e),
}
}
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
.map_err(|e| Response::err(format!("bad base64: {e}")))?;
write(root, rest, &data)
}),
Request::List { path } => {
let p = PathBuf::from(&path);
if !is_allowed(&p, allowed) {
return Response::err(format!("access denied: {path}"));
}
match std::fs::read_dir(&p) {
Ok(entries) => {
let mut names = Vec::new();
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
names.push(name.to_string());
}
}
names.sort();
Response::OkEntries { entries: names }
}
Err(e) => Response::err(e),
}
locate(roots, &path, false).and_then(|(root, rest)| list(root, rest))
}
}
};
result.unwrap_or_else(|response| response)
}
#[cfg(test)]
#[cfg(target_os = "linux")]
fn read(root: &Root, rest: &Path) -> Result<Response, Response> {
use rustix::fs::{FileType, OFlags};
let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::NONBLOCK).map_err(Response::err)?;
let stat = rustix::fs::fstat(&fd).map_err(Response::err)?;
if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
return Err(Response::err("not a regular file"));
}
let mut data = Vec::new();
std::fs::File::from(fd)
.take(MAX_FILE as u64 + 1)
.read_to_end(&mut data)
.map_err(Response::err)?;
if data.len() > MAX_FILE {
return Err(Response::err(format!("file larger than {MAX_FILE} bytes")));
}
Ok(Response::OkData {
data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &data),
})
}
#[cfg(target_os = "linux")]
fn list(root: &Root, rest: &Path) -> Result<Response, Response> {
use rustix::fs::OFlags;
let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::DIRECTORY).map_err(Response::err)?;
let mut entries = rustix::fs::Dir::read_from(&fd).map_err(Response::err)?;
let mut names = Vec::new();
while let Some(entry) = entries.read() {
let entry = entry.map_err(Response::err)?;
let Ok(name) = entry.file_name().to_str() else {
continue;
};
if name == "." || name == ".." || name.starts_with(TEMPORARY_PREFIX) {
continue;
}
if names.len() == MAX_ENTRIES {
return Err(Response::err(format!("more than {MAX_ENTRIES} entries")));
}
names.push(name.to_owned());
}
names.sort();
Ok(Response::OkEntries { entries: names })
}
/// Replaces the file `rest` in `root` with `data`: the data is written to a
/// new file in the same directory, flushed and renamed over the name, so
/// the file holds either the old or the new content.
#[cfg(target_os = "linux")]
fn write(root: &Root, rest: &Path, data: &[u8]) -> Result<Response, Response> {
use rustix::fs::{Mode, OFlags};
if data.len() > MAX_FILE {
return Err(Response::err(format!("file larger than {MAX_FILE} bytes")));
}
let name = rest
.file_name()
.ok_or_else(|| Response::err("a write needs a file name"))?;
let parent = open_beneath(
root,
rest.parent().unwrap_or(Path::new("")),
OFlags::RDONLY | OFlags::DIRECTORY,
)
.map_err(Response::err)?;
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// Unique within this portal by the counter, and across restarts by the
// time of its first write, so a file left by an earlier instance does
// not collide.
static STARTED: std::sync::OnceLock<u128> = std::sync::OnceLock::new();
let started = STARTED.get_or_init(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
});
let temporary = format!(
"{TEMPORARY_PREFIX}{}-{started}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
// A replaced file keeps its permission bits; a new one is private.
let mode = match rustix::fs::statat(&parent, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat)
if rustix::fs::FileType::from_raw_mode(stat.st_mode)
== rustix::fs::FileType::RegularFile =>
{
stat.st_mode & 0o777
}
_ => 0o600,
};
let file = rustix::fs::openat(
&parent,
temporary.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::from_raw_mode(0o600),
)
.map_err(Response::err)?;
let _ = rustix::fs::fchmod(&file, Mode::from_raw_mode(mode));
let mut file = std::fs::File::from(file);
let written = file
.write_all(data)
.and_then(|()| file.sync_all())
.and_then(|()| {
rustix::fs::renameat(&parent, temporary.as_str(), &parent, name)
.map_err(std::io::Error::from)
});
if let Err(e) = written {
let _ = rustix::fs::unlinkat(&parent, temporary.as_str(), rustix::fs::AtFlags::empty());
return Err(Response::err(e));
}
let _ = rustix::fs::fsync(&parent);
Ok(Response::Ok)
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::*;
use std::fs;
#[test]
fn allowed_path_accepted() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")];
assert!(is_allowed(
Path::new("/tmp/weft-test-allowed/file.txt"),
&allowed
));
fn grant(root: &Path, writable: bool) -> Vec<Root> {
vec![
Root::open(Allowed {
root: root.to_path_buf(),
writable,
})
.unwrap(),
]
}
#[test]
fn disallowed_path_rejected() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")];
assert!(!is_allowed(Path::new("/etc/passwd"), &allowed));
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("wfp_{name}_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("granted")).unwrap();
dir
}
#[test]
fn dotdot_traversal_blocked() {
let allowed = vec![PathBuf::from("/tmp/weft-test-allowed")];
assert!(!is_allowed(
Path::new("/tmp/weft-test-allowed/../etc/passwd"),
&allowed
));
fn path(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn empty_allowlist_rejects_all() {
assert!(!is_allowed(Path::new("/tmp/anything"), &[]));
fn denied(resp: &Response) -> bool {
matches!(resp, Response::Err { .. })
}
fn read_req(p: &Path) -> Request {
Request::Read { path: path(p) }
}
fn write_req(p: &Path, data: &[u8]) -> Request {
Request::Write {
path: path(p),
data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, data),
}
}
#[test]
@ -247,102 +478,277 @@ mod tests {
let args: Vec<String> = vec![
"--allow".into(),
"/tmp/a".into(),
"--allow".into(),
"/tmp/b".into(),
"--allow-read".into(),
"/tmp/c".into(),
];
let result = parse_allowed(&args);
assert_eq!(
result,
vec![PathBuf::from("/tmp/a"), PathBuf::from("/tmp/b")]
parse_allowed(&args),
vec![
Allowed {
root: "/tmp/a".into(),
writable: true
},
Allowed {
root: "/tmp/c".into(),
writable: false
},
]
);
}
#[test]
fn handle_request_read_denied() {
let resp = handle_request(
Request::Read {
path: "/etc/shadow".into(),
},
&[PathBuf::from("/tmp/safe")],
fn paths_must_name_a_place_inside_a_granted_directory_directly() {
let root = Path::new("/srv/granted");
assert_eq!(
relative_to(Path::new("/srv/granted/a/b"), root),
Some(Path::new("a/b"))
);
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("access denied"));
}
#[test]
fn handle_request_read_roundtrip() {
use std::fs;
let dir = std::env::temp_dir().join(format!("wfp_test_{}", std::process::id()));
let _ = fs::create_dir_all(&dir);
let file = dir.join("hello.txt");
fs::write(&file, b"hello world").unwrap();
let allowed = vec![dir.clone()];
let resp = handle_request(
Request::Read {
path: file.to_string_lossy().into(),
},
&allowed,
assert_eq!(
relative_to(Path::new("/srv/granted"), root),
Some(Path::new(""))
);
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("data_b64"));
if let Response::OkData { data_b64 } = resp {
let decoded =
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64)
.unwrap();
assert_eq!(decoded, b"hello world");
} else {
panic!("expected OkData");
for outside in [
"/srv/grantedx/a",
"/srv/granted/../x",
"/srv/granted/a/../../x",
"/etc",
"/srv/granted/a/./b",
"/srv/granted/a/.",
"/srv/granted/a/",
"/srv/granted//a",
"srv/granted/a",
] {
assert_eq!(relative_to(Path::new(outside), root), None, "{outside}");
}
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn handle_request_list() {
use std::fs;
let dir = std::env::temp_dir().join(format!("wfp_list_{}", std::process::id()));
let _ = fs::create_dir_all(&dir);
fs::write(dir.join("b.txt"), b"").unwrap();
fs::write(dir.join("a.txt"), b"").unwrap();
let allowed = vec![dir.clone()];
let resp = handle_request(
fn reads_writes_and_lists_inside_the_directory() {
let dir = temp("roundtrip");
let granted = dir.join("granted");
let roots = grant(&granted, true);
assert!(matches!(
handle_request(write_req(&granted.join("b.txt"), b"hello"), &roots),
Response::Ok
));
fs::write(granted.join("a.txt"), b"").unwrap();
match handle_request(read_req(&granted.join("b.txt")), &roots) {
Response::OkData { data_b64 } => assert_eq!(
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64)
.unwrap(),
b"hello"
),
_ => panic!("expected data"),
}
match handle_request(
Request::List {
path: dir.to_string_lossy().into(),
path: path(&granted),
},
&allowed,
);
if let Response::OkEntries { entries } = resp {
assert_eq!(entries, vec!["a.txt", "b.txt"]);
} else {
panic!("expected OkEntries");
&roots,
) {
Response::OkEntries { entries } => assert_eq!(entries, ["a.txt", "b.txt"]),
_ => panic!("expected entries"),
}
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn handle_request_write_creates_parent_dirs() {
use std::fs;
let dir = std::env::temp_dir().join(format!("wfp_write_{}", std::process::id()));
fn links_cannot_lead_out_of_the_directory() {
let dir = temp("links");
let granted = dir.join("granted");
fs::write(dir.join("secret.txt"), b"secret").unwrap();
fs::create_dir(granted.join("sub")).unwrap();
std::os::unix::fs::symlink("/", granted.join("root")).unwrap();
std::os::unix::fs::symlink("../secret.txt", granted.join("up")).unwrap();
std::os::unix::fs::symlink(&dir, granted.join("parent")).unwrap();
let roots = grant(&granted, true);
for escape in [
granted.join("root/etc/passwd"),
granted.join("up"),
granted.join("parent/secret.txt"),
// The check this replaced normalised `link/..` away and then
// followed the link.
granted.join("root/../secret.txt"),
] {
assert!(
denied(&handle_request(read_req(&escape), &roots)),
"{}",
escape.display()
);
if escape != granted.join("up") {
assert!(
denied(&handle_request(write_req(&escape, b"x"), &roots)),
"{}",
escape.display()
);
}
}
// A write to a name that is a link replaces the link, inside the
// directory, rather than writing where it points.
match handle_request(read_req(&granted.join("root/etc/passwd")), &roots) {
Response::Err { error } => assert!(error.contains("leads out"), "{error}"),
_ => panic!("read through a link out of the directory"),
}
assert!(matches!(
handle_request(write_req(&granted.join("up"), b"x"), &roots),
Response::Ok
));
assert!(fs::symlink_metadata(granted.join("up")).unwrap().is_file());
assert_eq!(fs::read(dir.join("secret.txt")).unwrap(), b"secret");
// A link that stays inside is followed.
std::os::unix::fs::symlink("sub", granted.join("inside")).unwrap();
assert!(matches!(
handle_request(write_req(&granted.join("inside/f"), b"ok"), &roots),
Response::Ok
));
assert_eq!(fs::read(granted.join("sub/f")).unwrap(), b"ok");
let _ = fs::remove_dir_all(&dir);
let nested = dir.join("sub").join("deep").join("file.txt");
let data = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
b"nested content",
}
#[test]
fn a_directory_swapped_for_a_link_mid_operation_cannot_lead_out() {
let dir = temp("race");
let granted = dir.join("granted");
fs::create_dir(dir.join("outside")).unwrap();
fs::write(dir.join("outside/f"), b"secret").unwrap();
fs::create_dir(granted.join("real")).unwrap();
fs::write(granted.join("real/f"), b"inside").unwrap();
let roots = grant(&granted, true);
// `swap` is a link, replaced in a loop, alternately to the inside
// directory and out of the granted one, absolute and relative.
std::os::unix::fs::symlink("real", granted.join("swap")).unwrap();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let swapper = {
let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone());
std::thread::spawn(move || {
let targets = [PathBuf::from("real"), outside, PathBuf::from("../outside")];
for target in targets.iter().cycle() {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
let _ = std::os::unix::fs::symlink(target, granted.join("next"));
let _ = fs::rename(granted.join("next"), granted.join("swap"));
}
})
};
let (mut inside, mut refused) = (0, 0);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while (inside < 50 || refused < 50) && std::time::Instant::now() < deadline {
match handle_request(read_req(&granted.join("swap/f")), &roots) {
Response::OkData { data_b64 } => {
let data = base64::Engine::decode(
&base64::engine::general_purpose::STANDARD,
data_b64,
)
.unwrap();
assert_eq!(data, b"inside", "a read left the directory");
inside += 1;
}
Response::Err { error } if error.contains("leads out") => refused += 1,
_ => {}
}
let _ = handle_request(write_req(&granted.join("swap/f"), b"inside"), &roots);
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
swapper.join().unwrap();
assert_eq!(fs::read(dir.join("outside/f")).unwrap(), b"secret");
assert!(
inside >= 50 && refused >= 50,
"the race was not exercised: {inside} reads inside, {refused} refused"
);
let allowed = vec![dir.clone()];
let resp = handle_request(
Request::Write {
path: nested.to_string_lossy().into(),
data_b64: data,
},
&allowed,
);
assert!(matches!(resp, Response::Ok), "expected Ok response");
assert_eq!(fs::read(&nested).unwrap(), b"nested content");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_replaced_file_keeps_its_mode() {
use std::os::unix::fs::PermissionsExt;
let dir = temp("mode");
let granted = dir.join("granted");
fs::write(granted.join("shared.txt"), b"old").unwrap();
fs::set_permissions(
granted.join("shared.txt"),
fs::Permissions::from_mode(0o644),
)
.unwrap();
let roots = grant(&granted, true);
assert!(matches!(
handle_request(write_req(&granted.join("shared.txt"), b"new"), &roots),
Response::Ok
));
let mode = fs::metadata(granted.join("shared.txt"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o644);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn read_only_directories_refuse_writes() {
let dir = temp("ro");
let granted = dir.join("granted");
fs::write(granted.join("kept.txt"), b"original").unwrap();
let roots = grant(&granted, false);
assert!(denied(&handle_request(
write_req(&granted.join("kept.txt"), b"x"),
&roots
)));
assert_eq!(fs::read(granted.join("kept.txt")).unwrap(), b"original");
assert!(matches!(
handle_request(read_req(&granted.join("kept.txt")), &roots),
Response::OkData { .. }
));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn writes_create_no_directories_and_leave_no_temporary_files() {
let dir = temp("nodirs");
let granted = dir.join("granted");
let roots = grant(&granted, true);
assert!(denied(&handle_request(
write_req(&granted.join("missing/f"), b"x"),
&roots
)));
assert!(!granted.join("missing").exists());
assert!(denied(&handle_request(write_req(&granted, b"x"), &roots)));
let left: Vec<_> = fs::read_dir(&granted).unwrap().flatten().collect();
assert!(left.is_empty(), "{left:?}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn oversized_files_are_refused() {
let dir = temp("size");
let granted = dir.join("granted");
fs::File::create(granted.join("big"))
.unwrap()
.set_len(MAX_FILE as u64 + 1)
.unwrap();
let roots = grant(&granted, true);
assert!(denied(&handle_request(
read_req(&granted.join("big")),
&roots
)));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn overlong_requests_end_the_connection() {
let dir = temp("line");
let granted = dir.join("granted");
let roots = grant(&granted, true);
let (client, server) = std::os::unix::net::UnixStream::pair().unwrap();
let serve = std::thread::spawn(move || handle_connection(server, &roots));
let mut writer = client.try_clone().unwrap();
let sent = std::thread::spawn(move || {
let _ = writer.write_all(&vec![b'x'; MAX_LINE + 64]);
});
let mut reply = String::new();
BufReader::new(client).read_line(&mut reply).unwrap();
serve.join().unwrap();
let _ = sent.join();
assert!(reply.contains("request too long"), "{reply}");
let _ = fs::remove_dir_all(&dir);
}
}

View file

@ -11,6 +11,13 @@ path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
rmp-serde = "1"
toml = "0.8"
sha2 = "0.10"
hex = "0.4"
ed25519-dalek = "2"
[lints]
workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "1", features = ["fs"] }

View file

@ -0,0 +1,144 @@
//! The capabilities the user approved for an installed app.
//!
//! A package declares capabilities; it gets only those the user approved.
//! `weft-pack` records the approval, `$XDG_DATA_HOME/weft/approvals/<id>`,
//! one capability per line, and weft-appd refuses to launch an app that
//! declares a capability the record does not hold. An app's own private
//! data is a minimal execution resource and needs no approval. Signature
//! verification and approval are separate decisions: a trusted signature
//! approves nothing.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use crate::capability::Capability;
/// Where the approval record of `app_id` lives.
pub fn approval_path(data_home: &Path, app_id: &str) -> PathBuf {
data_home.join("weft/approvals").join(app_id)
}
/// Whether a declared capability needs the user's approval. Strings that
/// are not capabilities are left to the capability checks, which refuse
/// them.
pub fn needs_approval(capability: &str) -> bool {
capability
.parse::<Capability>()
.is_ok_and(|c| !matches!(c, Capability::AppData(_)))
}
/// The declared capabilities that need approval and are not in `approved`.
pub fn unapproved<'a>(declared: &'a [String], approved: &BTreeSet<String>) -> Vec<&'a str> {
declared
.iter()
.map(String::as_str)
.filter(|c| needs_approval(c) && !approved.contains(*c))
.collect()
}
/// The capabilities approved for an app; none when there is no record.
pub fn read_approved(record: &Path) -> std::io::Result<BTreeSet<String>> {
match std::fs::read_to_string(record) {
Ok(text) => Ok(text
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(str::to_owned)
.collect()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
Err(e) => Err(e),
}
}
/// Records exactly the capabilities of `declared` that need approval as the
/// app's approval, replacing an earlier one in one rename. With none to
/// approve, the record is removed.
pub fn write_approved(record: &Path, declared: &[String]) -> std::io::Result<()> {
use std::io::Write;
let approved: BTreeSet<&str> = declared
.iter()
.map(String::as_str)
.filter(|c| needs_approval(c))
.collect();
if approved.is_empty() {
return remove_approval(record);
}
let parent = record
.parent()
.expect("approval records live in a directory");
std::fs::create_dir_all(parent)?;
let temp = parent.join(format!(
".{}.{}.tmp",
record
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("record"),
std::process::id()
));
let written = (|| {
let mut file = std::fs::File::create(&temp)?;
for capability in &approved {
writeln!(file, "{capability}")?;
}
file.sync_all()?;
std::fs::rename(&temp, record)
})();
if written.is_err() {
let _ = std::fs::remove_file(&temp);
}
written?;
std::fs::File::open(parent).and_then(|dir| dir.sync_all())
}
/// Removes an app's approval, so a later installation asks again.
pub fn remove_approval(record: &Path) -> std::io::Result<()> {
match std::fs::remove_file(record) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn caps(list: &[&str]) -> Vec<String> {
list.iter().map(|c| (*c).to_owned()).collect()
}
#[test]
fn private_app_data_needs_no_approval() {
assert!(!needs_approval("fs:rw:app-data"));
assert!(!needs_approval("fs:read:app-data"));
assert!(needs_approval("net:fetch:example.org"));
assert!(needs_approval("sys:notifications"));
assert!(needs_approval("fs:read:xdg-documents"));
// Not a capability: refused elsewhere, not reported as unapproved.
assert!(!needs_approval("sys:everything"));
}
#[test]
fn approvals_cover_exactly_what_was_approved() {
let dir = std::env::temp_dir().join(format!("weft_approval_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let record = approval_path(&dir, "org.weft.test");
let declared = caps(&["fs:rw:app-data", "net:fetch:example.org"]);
assert_eq!(read_approved(&record).unwrap(), BTreeSet::new());
assert_eq!(
unapproved(&declared, &read_approved(&record).unwrap()),
["net:fetch:example.org"]
);
write_approved(&record, &declared).unwrap();
assert!(unapproved(&declared, &read_approved(&record).unwrap()).is_empty());
// An update that asks for more needs approval for the new capability.
let updated = caps(&["net:fetch:example.org", "sys:clipboard:read"]);
assert_eq!(
unapproved(&updated, &read_approved(&record).unwrap()),
["sys:clipboard:read"]
);
// Nothing left to approve removes the record.
write_approved(&record, &caps(&["fs:rw:app-data"])).unwrap();
assert!(!record.exists());
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -0,0 +1,195 @@
//! Capabilities an application declares in `wapp.toml`.
//!
//! This is the one vocabulary shared by package validation (weft-pack), the
//! session supervisor that derives effective grants (weft-appd) and the
//! runtime that enforces them (weft-runtime).
use std::fmt;
use std::str::FromStr;
/// Access mode of a filesystem capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Access {
Read,
ReadWrite,
}
/// Destinations covered by a fetch capability.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FetchScope {
/// `net:fetch:*`: any host.
AnyHost,
/// `net:fetch:<host>`: exactly this host, in lowercase.
Host(String),
}
/// One declared capability.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Capability {
/// `fs:read:app-data` / `fs:rw:app-data`: the app's private data directory.
AppData(Access),
/// `fs:read:xdg-documents` / `fs:rw:xdg-documents`: the user's documents
/// directory.
Documents(Access),
/// `net:fetch:*` / `net:fetch:<host>`: the `weft:app/fetch` import.
Fetch(FetchScope),
/// `sys:notifications`: the `weft:app/notifications` import.
Notifications,
/// `sys:clipboard:read`: `weft:app/clipboard#read`.
ClipboardRead,
/// `sys:clipboard:write`: `weft:app/clipboard#write`.
ClipboardWrite,
/// `hw:gpu:compute`.
GpuCompute,
/// `hw:gpu:render`.
GpuRender,
}
/// A capability string outside the vocabulary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownCapability(pub String);
impl fmt::Display for UnknownCapability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown capability '{}'", self.0)
}
}
impl std::error::Error for UnknownCapability {}
impl FromStr for Capability {
type Err = UnknownCapability;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let capability = match s {
"fs:read:app-data" => Self::AppData(Access::Read),
"fs:rw:app-data" => Self::AppData(Access::ReadWrite),
"fs:read:xdg-documents" => Self::Documents(Access::Read),
"fs:rw:xdg-documents" => Self::Documents(Access::ReadWrite),
"net:fetch:*" => Self::Fetch(FetchScope::AnyHost),
"sys:notifications" => Self::Notifications,
"sys:clipboard:read" => Self::ClipboardRead,
"sys:clipboard:write" => Self::ClipboardWrite,
"hw:gpu:compute" => Self::GpuCompute,
"hw:gpu:render" => Self::GpuRender,
_ => match s.strip_prefix("net:fetch:") {
Some(host) if is_host_name(host) => Self::Fetch(FetchScope::Host(host.to_owned())),
_ => return Err(UnknownCapability(s.to_owned())),
},
};
Ok(capability)
}
}
impl fmt::Display for Capability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mode = |access: &Access| match access {
Access::Read => "read",
Access::ReadWrite => "rw",
};
match self {
Self::AppData(access) => write!(f, "fs:{}:app-data", mode(access)),
Self::Documents(access) => write!(f, "fs:{}:xdg-documents", mode(access)),
Self::Fetch(FetchScope::AnyHost) => f.write_str("net:fetch:*"),
Self::Fetch(FetchScope::Host(host)) => write!(f, "net:fetch:{host}"),
Self::Notifications => f.write_str("sys:notifications"),
Self::ClipboardRead => f.write_str("sys:clipboard:read"),
Self::ClipboardWrite => f.write_str("sys:clipboard:write"),
Self::GpuCompute => f.write_str("hw:gpu:compute"),
Self::GpuRender => f.write_str("hw:gpu:render"),
}
}
}
/// A host in the canonical form URL parsing produces, so that a grant can
/// be compared with a request's host as a string: a lowercase DNS name of
/// 1–63 character labels of letters, digits and inner hyphens (at most 253
/// characters) whose last label is neither numeric nor `0x`-prefixed, or an IPv4 address in
/// dotted-decimal form without leading zeros. IPv6 literals are not
/// supported.
fn is_host_name(host: &str) -> bool {
let labels: Vec<&str> = host.split('.').collect();
// URL parsing reads a last label of `0x…` as a hexadecimal number.
if labels.last().is_some_and(|last| last.starts_with("0x")) {
return false;
}
if labels
.last()
.is_some_and(|last| !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit()))
{
return is_ipv4(&labels);
}
host.len() <= 253
&& labels.iter().all(|label| {
!label.is_empty()
&& label.len() <= 63
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
fn is_ipv4(labels: &[&str]) -> bool {
labels.len() == 4
&& labels.iter().all(|octet| {
!octet.is_empty()
&& octet.len() <= 3
&& (octet.len() == 1 || !octet.starts_with('0'))
&& octet.bytes().all(|b| b.is_ascii_digit())
&& octet.parse::<u16>().is_ok_and(|n| n <= 255)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_capability_round_trips() {
for text in [
"fs:read:app-data",
"fs:rw:app-data",
"fs:read:xdg-documents",
"fs:rw:xdg-documents",
"net:fetch:*",
"net:fetch:api.example.org",
"net:fetch:127.0.0.1",
"net:fetch:a1.example",
"sys:notifications",
"sys:clipboard:read",
"sys:clipboard:write",
"hw:gpu:compute",
"hw:gpu:render",
] {
let capability: Capability = text.parse().unwrap();
assert_eq!(capability.to_string(), text);
}
}
#[test]
fn malformed_capabilities_are_unknown() {
for text in [
"",
"fs:write:app-data",
"net:fetch",
"net:fetch:",
"net:fetch:Example.org",
"net:fetch:example.org:443",
"net:fetch:https://example.org",
"net:fetch:*.example.org",
"net:fetch:-bad.example",
"net:fetch:a..b",
"net:fetch:0177.0.0.1",
"net:fetch:999.1.1.1",
"net:fetch:1.2.3",
"net:fetch:example.123",
"net:fetch:[::1]",
"net:fetch:example.0x1",
"sys:clipboard",
] {
assert!(text.parse::<Capability>().is_err(), "{text:?} accepted");
}
}
}

View file

@ -1,3 +1,10 @@
pub mod approval;
pub mod capability;
pub mod manifest;
pub mod package;
pub mod store;
pub mod trust;
use serde::{Deserialize, Serialize};
pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024;
@ -6,25 +13,36 @@ pub const MAX_FRAME_LEN: usize = 4 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AppdToCompositor {
AppSurfaceCreated {
app_id: String,
/// Hands the compositor its end of the Wayland connection weft-appd
/// created for the session's app shell. The frame is sent with exactly
/// one file descriptor attached (SCM_RIGHTS): the compositor end of that
/// connection. Holding the connection is the session's identity; no
/// client-supplied ID or process ID is trusted for it.
AttachClient {
session_id: u64,
pid: u32,
app_id: String,
},
/// The session ended; the compositor closes its client and windows.
AppSurfaceDestroyed {
session_id: u64,
},
AppFocusRequest {
session_id: u64,
},
/// Asks the session's windows to close, as a user close would.
AppCloseRequest {
session_id: u64,
},
}
/// Messages sent from weft-compositor to weft-appd.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CompositorToAppd {
/// The session's client mapped its first toplevel.
SurfaceReady { session_id: u64 },
ClientDisconnected { pid: u32 },
/// The session's Wayland client disconnected.
ClientDisconnected { session_id: u64 },
}
/// Encode a message as a length-prefixed MessagePack frame.
@ -107,23 +125,17 @@ mod tests {
use super::*;
#[test]
fn roundtrip_appd_to_compositor_surface_created() {
let msg = AppdToCompositor::AppSurfaceCreated {
fn roundtrip_appd_to_compositor_attach_client() {
let msg = AppdToCompositor::AttachClient {
app_id: "com.example.app".into(),
session_id: 42,
pid: 1234,
};
let frame = frame_encode(&msg).unwrap();
let decoded: AppdToCompositor = frame_decode(&frame).unwrap();
match decoded {
AppdToCompositor::AppSurfaceCreated {
app_id,
session_id,
pid,
} => {
AppdToCompositor::AttachClient { app_id, session_id } => {
assert_eq!(app_id, "com.example.app");
assert_eq!(session_id, 42);
assert_eq!(pid, 1234);
}
_ => panic!("unexpected variant"),
}
@ -164,11 +176,11 @@ mod tests {
#[test]
fn roundtrip_compositor_to_appd_disconnected() {
let msg = CompositorToAppd::ClientDisconnected { pid: 5678 };
let msg = CompositorToAppd::ClientDisconnected { session_id: 5678 };
let frame = frame_encode(&msg).unwrap();
let decoded: CompositorToAppd = frame_decode(&frame).unwrap();
match decoded {
CompositorToAppd::ClientDisconnected { pid } => assert_eq!(pid, 5678),
CompositorToAppd::ClientDisconnected { session_id } => assert_eq!(session_id, 5678),
_ => panic!("unexpected variant"),
}
}

View file

@ -0,0 +1,275 @@
//! The package manifest, `wapp.toml`, and the package files it names.
//!
//! This is the one parser for manifests: the packaging tool validates
//! packages with it and the session supervisor resolves launches with it.
use std::fmt;
use std::path::{Component, Path, PathBuf};
use serde::Deserialize;
/// The manifest's file name at the root of a package.
pub const MANIFEST_FILE: &str = "wapp.toml";
#[derive(Debug, Clone, Deserialize)]
pub struct Manifest {
pub package: PackageMeta,
pub runtime: RuntimeMeta,
pub ui: UiMeta,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PackageMeta {
pub id: String,
pub name: String,
pub version: String,
pub description: Option<String>,
pub author: Option<String>,
pub capabilities: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RuntimeMeta {
/// The Wasm component, relative to the package root.
pub module: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct UiMeta {
/// The UI document, relative to the package root.
pub entry: String,
/// What happens when the user asks the application's window to close.
#[serde(default)]
pub close: ClosePolicy,
}
/// An application's declared unsaved-change policy: what a user close does.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ClosePolicy {
/// The window closes at once; the application keeps no unsaved state.
#[default]
Immediate,
/// The page is asked first and may cancel the close, for example to
/// offer saving unsaved changes; it then closes itself when done.
Ask,
}
impl ClosePolicy {
/// The value weft-appd passes to the app shell in `WEFT_APP_CLOSE`.
pub fn as_str(self) -> &'static str {
match self {
Self::Immediate => "immediate",
Self::Ask => "ask",
}
}
}
/// Why a manifest could not be read.
#[derive(Debug)]
pub enum ManifestError {
Io(PathBuf, std::io::Error),
Parse(PathBuf, toml::de::Error),
}
impl fmt::Display for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(path, e) => write!(f, "cannot read {}: {e}", path.display()),
Self::Parse(path, e) => write!(f, "invalid {}: {e}", path.display()),
}
}
}
impl std::error::Error for ManifestError {}
impl Manifest {
/// Reads `<package_root>/wapp.toml`.
pub fn read(package_root: &Path) -> Result<Self, ManifestError> {
let path = package_root.join(MANIFEST_FILE);
let bytes = std::fs::read(&path).map_err(|e| ManifestError::Io(path.clone(), e))?;
Self::parse(&path, &bytes)
}
/// Parses manifest bytes already read from `path`.
pub fn parse(path: &Path, bytes: &[u8]) -> Result<Self, ManifestError> {
let text = std::str::from_utf8(bytes).map_err(|e| {
ManifestError::Io(
path.to_path_buf(),
std::io::Error::new(std::io::ErrorKind::InvalidData, e),
)
})?;
toml::from_str(text).map_err(|e| ManifestError::Parse(path.to_path_buf(), e))
}
pub fn capabilities(&self) -> &[String] {
self.package.capabilities.as_deref().unwrap_or_default()
}
}
/// Why a manifest entry does not name a usable package file.
#[derive(Debug, PartialEq, Eq)]
pub enum EntryError {
/// The entry is empty, absolute, or has `.` or `..` components.
NotContained(String),
/// A component of the entry is a symbolic link.
Link(String),
/// The entry does not exist, or is not a regular file.
NotAFile(String),
}
impl fmt::Display for EntryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotContained(entry) => {
write!(f, "'{entry}' is not a relative path inside the package")
}
Self::Link(entry) => write!(f, "'{entry}' passes through a symbolic link"),
Self::NotAFile(entry) => write!(f, "'{entry}' is not a file in the package"),
}
}
}
impl std::error::Error for EntryError {}
/// The package file a manifest entry names: `entry` must be a relative path
/// of plain components, none of them a symbolic link, ending at a regular
/// file inside `package_root`.
pub fn entry_path(package_root: &Path, entry: &str) -> Result<PathBuf, EntryError> {
let relative = Path::new(entry);
let mut components = relative.components().peekable();
if components.peek().is_none()
|| !relative
.components()
.all(|c| matches!(c, Component::Normal(_)))
{
return Err(EntryError::NotContained(entry.to_owned()));
}
let mut path = package_root.to_path_buf();
while let Some(component) = components.next() {
path.push(component);
let metadata =
std::fs::symlink_metadata(&path).map_err(|_| EntryError::NotAFile(entry.to_owned()))?;
if metadata.file_type().is_symlink() {
return Err(EntryError::Link(entry.to_owned()));
}
let last = components.peek().is_none();
if (last && !metadata.is_file()) || (!last && !metadata.is_dir()) {
return Err(EntryError::NotAFile(entry.to_owned()));
}
}
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
fn package(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_manifest_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("ui")).unwrap();
std::fs::write(dir.join("app.wasm"), b"\0asm").unwrap();
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
dir
}
#[test]
fn entries_resolve_to_package_files() {
let dir = package("files");
assert_eq!(entry_path(&dir, "app.wasm").unwrap(), dir.join("app.wasm"));
assert_eq!(
entry_path(&dir, "ui/index.html").unwrap(),
dir.join("ui/index.html")
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn entries_must_stay_inside_the_package() {
let dir = package("contained");
for entry in [
"",
"/etc/passwd",
"../app.wasm",
"ui/../app.wasm",
"./app.wasm",
] {
assert_eq!(
entry_path(&dir, entry),
Err(EntryError::NotContained(entry.to_owned())),
"{entry:?}"
);
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn entries_must_name_existing_regular_files() {
let dir = package("kinds");
for entry in ["missing.wasm", "ui", "app.wasm/x"] {
assert_eq!(
entry_path(&dir, entry),
Err(EntryError::NotAFile(entry.to_owned())),
"{entry:?}"
);
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn entries_never_follow_links() {
let dir = package("links");
std::os::unix::fs::symlink(dir.join("app.wasm"), dir.join("linked.wasm")).unwrap();
std::os::unix::fs::symlink(dir.join("ui"), dir.join("view")).unwrap();
assert_eq!(
entry_path(&dir, "linked.wasm"),
Err(EntryError::Link("linked.wasm".to_owned()))
);
assert_eq!(
entry_path(&dir, "view/index.html"),
Err(EntryError::Link("view/index.html".to_owned()))
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn manifests_parse_with_their_entries() {
let dir = package("parse");
std::fs::write(
dir.join(MANIFEST_FILE),
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
capabilities = [\"sys:notifications\"]\n\
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\n",
)
.unwrap();
let manifest = Manifest::read(&dir).unwrap();
assert_eq!(manifest.package.id, "org.weft.test");
assert_eq!(manifest.capabilities(), ["sys:notifications"]);
assert_eq!(manifest.ui.close, ClosePolicy::Immediate);
std::fs::write(
dir.join(MANIFEST_FILE),
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"ask\"\n",
)
.unwrap();
assert_eq!(Manifest::read(&dir).unwrap().ui.close, ClosePolicy::Ask);
std::fs::write(
dir.join(MANIFEST_FILE),
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"later\"\n",
)
.unwrap();
assert!(matches!(
Manifest::read(&dir),
Err(ManifestError::Parse(..))
));
std::fs::write(dir.join(MANIFEST_FILE), "[package]\nid = \"x\"\n").unwrap();
assert!(matches!(
Manifest::read(&dir),
Err(ManifestError::Parse(..))
));
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -0,0 +1,374 @@
//! Package identity and storage rules shared by the packaging tool and the
//! supervisor.
use std::path::{Path, PathBuf};
/// Whether `id` is a valid application ID: at least three dot-separated
/// segments, each starting with a lowercase ASCII letter and containing only
/// lowercase ASCII letters and digits. A valid ID is safe to use as a single
/// path component.
pub fn is_valid_app_id(id: &str) -> bool {
let parts: Vec<&str> = id.split('.').collect();
parts.len() >= 3
&& parts.iter().all(|p| {
p.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& p.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
})
}
/// The files of a verified package image in a package store: the EROFS
/// image, its dm-verity hash tree and the hex root hash, named after the
/// application ID. `weft-pack build-image` and `build-verity` produce these
/// names and the supervisor looks for them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageFiles {
pub image: PathBuf,
pub hash_tree: PathBuf,
pub root_hash: PathBuf,
}
impl ImageFiles {
pub fn in_store(store_root: &Path, app_id: &str) -> Self {
Self::for_image(&store_root.join(format!("{app_id}.app.img")))
}
/// The companions of `image`, named by replacing its extension.
pub fn for_image(image: &Path) -> Self {
Self {
image: image.to_path_buf(),
hash_tree: image.with_extension("hash"),
root_hash: image.with_extension("roothash"),
}
}
/// Whether any of the three files is present, whether or not it is
/// usable.
pub fn any_present(&self) -> bool {
[&self.image, &self.hash_tree, &self.root_hash]
.iter()
.any(|path| std::fs::symlink_metadata(path).is_ok())
}
}
/// The user's data home: `$XDG_DATA_HOME` when it is an absolute path,
/// otherwise `$HOME/.local/share`.
pub fn data_home() -> Option<PathBuf> {
std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
.map(|home| home.join(".local/share"))
})
}
/// The private data directory of an application, independent of where or
/// whether its package is installed.
pub fn app_data_dir(data_home: &Path, app_id: &str) -> PathBuf {
data_home.join("weft/app-data").join(app_id)
}
/// Where earlier versions kept application data: inside the user package
/// store, under the installed package directory.
pub fn legacy_app_data_dir(home: &Path, app_id: &str) -> PathBuf {
home.join(".local/share/weft/apps")
.join(app_id)
.join("data")
}
/// The home directory, when `HOME` is set to an absolute path.
pub fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
}
/// Where app data for `app_id` already exists, in the current layout or in
/// the earlier one under `home`, if anywhere. Data in the earlier layout is
/// moved to the current one when the app next launches, so it counts too.
pub fn existing_app_data(
data_home: &Path,
home: &Path,
app_id: &str,
) -> std::io::Result<Option<PathBuf>> {
let places = [
app_data_dir(data_home, app_id),
legacy_app_data_dir(home, app_id),
];
for place in places {
match std::fs::symlink_metadata(&place) {
Ok(_) => return Ok(Some(place)),
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) => {}
Err(e) => return Err(e),
}
}
Ok(None)
}
/// The result of moving data from the earlier layout.
#[derive(Debug, PartialEq, Eq)]
pub enum Migration {
/// No data in the earlier layout.
NotNeeded,
/// The directory was moved to the new location.
Moved,
}
/// Why data in the earlier layout could not be moved. Nothing was changed.
#[derive(Debug)]
pub enum MigrationError {
/// Data exists in both locations; either may hold the user's latest
/// data, so the user has to choose.
Conflict {
legacy: PathBuf,
target: PathBuf,
},
/// The two locations are on different filesystems, so the data cannot
/// be moved in one step.
CrossDevice {
legacy: PathBuf,
target: PathBuf,
},
/// The earlier location is not a plain directory.
NotADirectory(PathBuf),
Io(std::io::Error),
}
impl std::fmt::Display for MigrationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Conflict { legacy, target } => write!(
f,
"app data exists both in {} and in {}; keep one of them and remove the other",
legacy.display(),
target.display()
),
Self::CrossDevice { legacy, target } => write!(
f,
"app data in {} cannot be moved to {} on another filesystem; move it there by hand",
legacy.display(),
target.display()
),
Self::NotADirectory(path) => write!(
f,
"{} is not a plain directory; move it aside to continue",
path.display()
),
Self::Io(e) => e.fmt(f),
}
}
}
impl std::error::Error for MigrationError {}
/// Moves `legacy` to `target` if `legacy` is a directory, in one rename so
/// the data is never partly in both places, and then removes the earlier
/// package directory if that leaves it empty. Refuses, changing nothing,
/// when `target` already exists (even empty), when `legacy` is a symbolic
/// link or not a directory, and when the rename would cross filesystems.
pub fn migrate_app_data(legacy: &Path, target: &Path) -> Result<Migration, MigrationError> {
let conflict = || MigrationError::Conflict {
legacy: legacy.to_path_buf(),
target: target.to_path_buf(),
};
let metadata = match std::fs::symlink_metadata(legacy) {
Ok(metadata) => metadata,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Migration::NotNeeded),
Err(e) => return Err(MigrationError::Io(e)),
};
if !metadata.is_dir() {
return Err(MigrationError::NotADirectory(legacy.to_path_buf()));
}
if std::fs::symlink_metadata(target).is_ok() {
return Err(conflict());
}
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(MigrationError::Io)?;
}
match rename_no_replace(legacy, target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Err(conflict()),
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
return Err(MigrationError::CrossDevice {
legacy: legacy.to_path_buf(),
target: target.to_path_buf(),
});
}
Err(e) => return Err(MigrationError::Io(e)),
}
if let Some(package_dir) = legacy.parent() {
// Fails, harmlessly, unless the directory is now empty.
let _ = std::fs::remove_dir(package_dir);
}
Ok(Migration::Moved)
}
/// Renames `from` to `to`, failing with `AlreadyExists` instead of replacing
/// an existing `to`, even one created after the caller checked for it.
#[cfg(target_os = "linux")]
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
use rustix::fs::{CWD, RenameFlags, renameat_with};
renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE).map_err(std::io::Error::from)
}
#[cfg(not(target_os = "linux"))]
pub fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
if std::fs::symlink_metadata(to).is_ok() {
return Err(std::io::ErrorKind::AlreadyExists.into());
}
std::fs::rename(from, to)
}
/// Makes `dir` accessible only to its owner. A symbolic link is refused
/// rather than followed.
pub fn make_private(dir: &Path) -> std::io::Result<()> {
let metadata = std::fs::symlink_metadata(dir)?;
if !metadata.is_dir() {
return Err(std::io::Error::other(format!(
"{} is not a plain directory",
dir.display()
)));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn image_companions_share_the_image_name() {
let files = ImageFiles::in_store(Path::new("/store"), "org.weft.demo.notes");
assert_eq!(files.image, Path::new("/store/org.weft.demo.notes.app.img"));
assert_eq!(
files.hash_tree,
Path::new("/store/org.weft.demo.notes.app.hash")
);
assert_eq!(
files.root_hash,
Path::new("/store/org.weft.demo.notes.app.roothash")
);
assert_eq!(ImageFiles::for_image(&files.image), files);
}
#[test]
fn app_ids() {
assert!(is_valid_app_id("org.weft.demo"));
assert!(is_valid_app_id("com.example2.app3"));
for bad in [
"",
"org.weft",
"Org.weft.demo",
"org..demo",
"../x.y.z",
"org.weft.a::b",
"org.1weft.demo",
] {
assert!(!is_valid_app_id(bad), "{bad:?}");
}
}
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_migrate_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn data_lives_outside_the_package_store() {
let home = Path::new("/home/u");
let data = app_data_dir(&home.join(".local/share"), "org.weft.demo");
assert_eq!(
data,
Path::new("/home/u/.local/share/weft/app-data/org.weft.demo")
);
assert!(!data.starts_with("/home/u/.local/share/weft/apps"));
assert_eq!(
legacy_app_data_dir(home, "org.weft.demo"),
Path::new("/home/u/.local/share/weft/apps/org.weft.demo/data")
);
}
#[test]
fn migration_keeps_a_package_directory_with_other_content() {
let root = temp("keep-package");
let legacy = root.join("apps/org.weft.app/data");
std::fs::create_dir_all(&legacy).unwrap();
std::fs::write(root.join("apps/org.weft.app/wapp.toml"), "").unwrap();
migrate_app_data(&legacy, &root.join("new")).unwrap();
assert!(root.join("apps/org.weft.app/wapp.toml").exists());
}
#[test]
fn migration_moves_data_intact() {
let root = temp("move");
let legacy = root.join("apps/org.weft.notes/data");
std::fs::create_dir_all(legacy.join("sub")).unwrap();
std::fs::write(legacy.join("notes.txt"), "line one\nline \\two").unwrap();
std::fs::write(legacy.join("sub/x"), [0u8, 255, 10]).unwrap();
let target = root.join("app-data/org.weft.notes");
assert_eq!(
migrate_app_data(&legacy, &target).unwrap(),
Migration::Moved
);
assert!(!legacy.exists());
assert_eq!(
std::fs::read_to_string(target.join("notes.txt")).unwrap(),
"line one\nline \\two"
);
assert_eq!(std::fs::read(target.join("sub/x")).unwrap(), [0u8, 255, 10]);
assert_eq!(
migrate_app_data(&legacy, &target).unwrap(),
Migration::NotNeeded
);
}
#[test]
fn migration_refuses_conflicts_and_leaves_both() {
let root = temp("conflict");
let legacy = root.join("old");
let target = root.join("new");
std::fs::create_dir_all(&legacy).unwrap();
std::fs::create_dir_all(&target).unwrap();
std::fs::write(legacy.join("a"), "old").unwrap();
std::fs::write(target.join("a"), "new").unwrap();
let err = migrate_app_data(&legacy, &target).unwrap_err();
assert!(matches!(err, MigrationError::Conflict { .. }));
// An empty target is a conflict too: it may be in use.
std::fs::remove_file(target.join("a")).unwrap();
assert!(matches!(
migrate_app_data(&legacy, &target),
Err(MigrationError::Conflict { .. })
));
std::fs::write(target.join("a"), "new").unwrap();
assert_eq!(std::fs::read_to_string(legacy.join("a")).unwrap(), "old");
assert_eq!(std::fs::read_to_string(target.join("a")).unwrap(), "new");
}
#[cfg(unix)]
#[test]
fn migration_refuses_a_linked_legacy_directory() {
let root = temp("link");
std::fs::create_dir_all(root.join("elsewhere")).unwrap();
std::os::unix::fs::symlink(root.join("elsewhere"), root.join("old")).unwrap();
assert!(matches!(
migrate_app_data(&root.join("old"), &root.join("new")),
Err(MigrationError::NotADirectory(_))
));
assert!(!root.join("new").exists());
}
}

View file

@ -0,0 +1,238 @@
//! The layout of a package store and the revisions it holds.
//!
//! Each installed revision of a package is an immutable directory named by
//! its content digest, `<store>/.revisions/<app_id>/<digest>`. The active
//! revision is chosen by `<store>/<app_id>`, a symbolic link to it that one
//! rename replaces, so an update or rollback switches every new launch at
//! once and an interrupted one leaves the previous choice in place. Stores
//! written before revisions existed hold the package directly in
//! `<store>/<app_id>`; that layout is still read.
//!
//! A session pins the revision it was launched from with a shared lock on
//! the revision directory, held for the session's lifetime. Package
//! operations remove a revision only after taking that lock exclusively, so
//! a live session keeps running on the bytes it started with.
use std::fs::File;
use std::path::{Path, PathBuf};
/// The directory of a store that holds package revisions.
pub const REVISIONS_DIR: &str = ".revisions";
/// The directory holding the revisions of `app_id`.
pub fn revisions_of(store_root: &Path, app_id: &str) -> PathBuf {
store_root.join(REVISIONS_DIR).join(app_id)
}
/// The link target that makes `revision` the active revision of `app_id`,
/// relative to the store root.
pub fn link_target(app_id: &str, revision: &str) -> PathBuf {
Path::new(REVISIONS_DIR).join(app_id).join(revision)
}
/// Whether `name` is a revision name: the hex content digest of a package.
pub fn is_revision_name(name: &str) -> bool {
name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
/// Where the active package of `app_id` is in a store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Active {
/// A revision, by name, in `.revisions/<app_id>/`.
Revision { name: String, dir: PathBuf },
/// A package directory installed before revisions existed.
Directory(PathBuf),
}
impl Active {
/// The package root.
pub fn dir(&self) -> &Path {
match self {
Self::Revision { dir, .. } | Self::Directory(dir) => dir,
}
}
}
/// Why the active package of a store cannot be determined.
#[derive(Debug)]
pub enum StoreError {
Io(PathBuf, std::io::Error),
/// `<store>/<app_id>` is neither a package directory nor a link to one
/// of its revisions.
NotAPackage(PathBuf),
}
impl std::fmt::Display for StoreError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(path, e) => write!(f, "cannot read {}: {e}", path.display()),
Self::NotAPackage(path) => write!(
f,
"{} is neither a package directory nor a link to one of its revisions",
path.display()
),
}
}
}
impl std::error::Error for StoreError {}
/// The active package of `app_id` in `store_root`, if any. A link is
/// followed only when it names one of the app's own revisions, exactly as
/// package operations write it, and that revision is a directory.
pub fn active(store_root: &Path, app_id: &str) -> Result<Option<Active>, StoreError> {
let entry = store_root.join(app_id);
let metadata = match std::fs::symlink_metadata(&entry) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(StoreError::Io(entry, e)),
};
if metadata.is_dir() {
return Ok(Some(Active::Directory(entry)));
}
if !metadata.file_type().is_symlink() {
return Err(StoreError::NotAPackage(entry));
}
let target = std::fs::read_link(&entry).map_err(|e| StoreError::Io(entry.clone(), e))?;
let name = target
.file_name()
.and_then(|n| n.to_str())
.filter(|n| is_revision_name(n))
.map(str::to_owned);
let Some(name) = name.filter(|n| target == link_target(app_id, n)) else {
return Err(StoreError::NotAPackage(entry));
};
let dir = revisions_of(store_root, app_id).join(&name);
match std::fs::symlink_metadata(&dir) {
Ok(m) if m.is_dir() => Ok(Some(Active::Revision { name, dir })),
Ok(_) => Err(StoreError::NotAPackage(entry)),
Err(e) => Err(StoreError::Io(dir, e)),
}
}
/// A shared lock on a package directory, held while a session runs from it.
#[derive(Debug)]
pub struct Pin {
_dir: File,
}
/// Pins the package directory `dir`. The lock is taken on the directory
/// that is opened, and the path must still name that directory afterwards:
/// a revision removed or replaced in between is not pinned. A directory a
/// package operation holds is not waited for, so nobody able to lock a
/// package directory can stall launches; the launch is refused instead.
pub fn pin(dir: &Path) -> std::io::Result<Pin> {
let file = File::open(dir)?;
match file.try_lock_shared() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => {
return Err(std::io::Error::other(format!(
"{} is being changed; try again",
dir.display()
)));
}
Err(std::fs::TryLockError::Error(e)) => return Err(e),
}
if !same_file(&file, dir)? {
return Err(std::io::Error::other(format!(
"{} changed while it was being pinned",
dir.display()
)));
}
Ok(Pin { _dir: file })
}
/// Takes the exclusive lock on a package directory that no session pins,
/// or returns `None` while one does.
pub fn try_claim(dir: &Path) -> std::io::Result<Option<File>> {
let file = File::open(dir)?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(e)) => Err(e),
}
}
#[cfg(unix)]
fn same_file(file: &File, path: &Path) -> std::io::Result<bool> {
use std::os::unix::fs::MetadataExt;
let opened = file.metadata()?;
let named = std::fs::symlink_metadata(path)?;
Ok(opened.dev() == named.dev() && opened.ino() == named.ino())
}
#[cfg(not(unix))]
fn same_file(_file: &File, _path: &Path) -> std::io::Result<bool> {
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
fn store(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_store_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
const REV: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
#[cfg(unix)]
#[test]
fn only_links_to_the_apps_own_revisions_are_followed() {
use std::os::unix::fs::symlink;
let root = store("links");
std::fs::create_dir_all(revisions_of(&root, "org.a").join(REV)).unwrap();
std::fs::create_dir_all(revisions_of(&root, "org.b").join(REV)).unwrap();
assert!(active(&root, "org.a").unwrap().is_none());
symlink(link_target("org.a", REV), root.join("org.a")).unwrap();
assert_eq!(
active(&root, "org.a").unwrap(),
Some(Active::Revision {
name: REV.to_owned(),
dir: revisions_of(&root, "org.a").join(REV),
})
);
// Another app's revision, an absolute target, a non-revision name.
for target in [
link_target("org.b", REV),
revisions_of(&root, "org.c").join(REV),
PathBuf::from(".revisions/org.c/latest"),
] {
let _ = std::fs::remove_file(root.join("org.c"));
std::fs::create_dir_all(revisions_of(&root, "org.c").join(REV)).unwrap();
symlink(&target, root.join("org.c")).unwrap();
assert!(
matches!(active(&root, "org.c"), Err(StoreError::NotAPackage(_))),
"{}",
target.display()
);
}
// A package installed before revisions existed.
std::fs::create_dir(root.join("org.d")).unwrap();
assert_eq!(
active(&root, "org.d").unwrap(),
Some(Active::Directory(root.join("org.d")))
);
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn a_pinned_directory_cannot_be_claimed() {
let root = store("pin");
let dir = root.join("rev");
std::fs::create_dir(&dir).unwrap();
let pinned = pin(&dir).unwrap();
assert!(try_claim(&dir).unwrap().is_none());
// Other sessions can pin it too.
let again = pin(&dir).unwrap();
drop((pinned, again));
let claimed = try_claim(&dir).unwrap();
assert!(claimed.is_some());
drop(claimed);
std::fs::remove_dir_all(&root).unwrap();
}
}

View file

@ -0,0 +1,521 @@
//! Package content identity, publisher keys and the trust decisions made
//! before a package is installed or launched.
//!
//! A package is signed over its content digest: the SHA-256 of a canonical
//! inventory listing every file except the root `signature.sig`, one
//! `<relative path>\t<hex sha-256>\n` line per file, sorted by path. Paths use
//! `/` and must be UTF-8 without control characters, so no name can imitate
//! the separators of other lines. Symbolic links and special files are
//! refused, so the signed bytes are exactly the files a package holds.
use std::fmt;
use std::path::{Path, PathBuf};
use ed25519_dalek::{Signature, VerifyingKey};
use sha2::{Digest, Sha256};
/// The signature file at the root of a signed package.
pub const SIGNATURE_FILE: &str = "signature.sig";
/// Why a package's content or trust could not be established.
#[derive(Debug)]
pub enum TrustError {
/// The package holds a symbolic link.
Link(PathBuf),
/// The package holds something other than directories and regular files.
NotAFile(PathBuf),
/// A path in the package is not UTF-8.
NonUtf8(PathBuf),
/// A name in the package holds a control character.
ControlCharacter(PathBuf),
/// A key, signature or owner record is malformed.
Malformed(PathBuf, String),
Io(PathBuf, std::io::Error),
}
impl fmt::Display for TrustError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Link(p) => write!(f, "{} is a symbolic link", p.display()),
Self::NotAFile(p) => write!(f, "{} is not a regular file or directory", p.display()),
Self::NonUtf8(p) => write!(f, "{} is not a UTF-8 path", p.display()),
Self::ControlCharacter(p) => {
write!(f, "{:?} has a control character in its name", p.display())
}
Self::Malformed(p, why) => write!(f, "{}: {why}", p.display()),
Self::Io(p, e) => write!(f, "{}: {e}", p.display()),
}
}
}
impl std::error::Error for TrustError {}
fn io(path: &Path) -> impl FnOnce(std::io::Error) -> TrustError + '_ {
move |e| TrustError::Io(path.to_path_buf(), e)
}
/// The SHA-256 content digest a package signature covers.
pub fn content_digest(package_root: &Path) -> Result<[u8; 32], TrustError> {
Inventory::read(package_root).map(|inventory| inventory.digest())
}
/// The files of a package and their SHA-256 hashes, as read once: the digest
/// and the hash of any one file come from the same reading.
#[derive(Debug)]
pub struct Inventory(Vec<(String, [u8; 32])>);
impl Inventory {
pub fn read(package_root: &Path) -> Result<Self, TrustError> {
let mut entries = Vec::new();
collect(package_root, package_root, &mut entries)?;
entries.sort();
Ok(Self(entries))
}
/// The content digest a package signature covers.
pub fn digest(&self) -> [u8; 32] {
let mut inventory = String::new();
for (path, hash) in &self.0 {
inventory.push_str(path);
inventory.push('\t');
inventory.push_str(&hex::encode(hash));
inventory.push('\n');
}
Sha256::digest(inventory.as_bytes()).into()
}
/// Whether the file at `path`, relative to the package root, had exactly
/// these bytes when the inventory was read.
pub fn holds(&self, path: &str, bytes: &[u8]) -> bool {
let hash: [u8; 32] = Sha256::digest(bytes).into();
self.0.iter().any(|(p, h)| p == path && *h == hash)
}
}
fn collect(
root: &Path,
dir: &Path,
entries: &mut Vec<(String, [u8; 32])>,
) -> Result<(), TrustError> {
for entry in std::fs::read_dir(dir).map_err(io(dir))? {
let path = entry.map_err(io(dir))?.path();
let relative = path
.strip_prefix(root)
.expect("read_dir yields children of the directory it reads")
.to_str()
.ok_or_else(|| TrustError::NonUtf8(path.clone()))?
.to_owned();
if relative.chars().any(char::is_control) {
return Err(TrustError::ControlCharacter(path));
}
let kind = std::fs::symlink_metadata(&path)
.map_err(io(&path))?
.file_type();
if kind.is_symlink() {
return Err(TrustError::Link(path));
} else if kind.is_dir() {
collect(root, &path, entries)?;
} else if !kind.is_file() {
return Err(TrustError::NotAFile(path));
} else if relative != SIGNATURE_FILE {
let bytes = std::fs::read(&path).map_err(io(&path))?;
entries.push((relative, Sha256::digest(&bytes).into()));
}
}
Ok(())
}
/// A publisher's Ed25519 public key.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PublisherKey(VerifyingKey);
impl fmt::Debug for PublisherKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PublisherKey({})", self.to_hex())
}
}
impl PublisherKey {
/// Parses 64 hex digits, the format `weft-pack generate-key` writes.
pub fn from_hex(text: &str) -> Result<Self, String> {
let bytes: [u8; 32] = hex::decode(text.trim())
.map_err(|_| "expected 64 hex digits".to_owned())?
.try_into()
.map_err(|_| "expected a 32-byte key".to_owned())?;
VerifyingKey::from_bytes(&bytes)
.map(Self)
.map_err(|_| "not a valid Ed25519 public key".to_owned())
}
pub fn from_file(path: &Path) -> Result<Self, TrustError> {
let text = std::fs::read_to_string(path).map_err(io(path))?;
Self::from_hex(&text).map_err(|why| TrustError::Malformed(path.to_path_buf(), why))
}
/// The key as 64 lowercase hex digits; it also identifies the publisher.
pub fn to_hex(&self) -> String {
hex::encode(self.0.as_bytes())
}
/// Whether `signature` signs `digest` with this key.
pub fn signed(&self, digest: &[u8; 32], signature: &Signature) -> bool {
self.0.verify_strict(digest, signature).is_ok()
}
}
/// Reads the package's signature, or `None` when the package is unsigned.
pub fn read_signature(package_root: &Path) -> Result<Option<Signature>, TrustError> {
let path = package_root.join(SIGNATURE_FILE);
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(TrustError::Io(path, e)),
Ok(m) if !m.file_type().is_file() => return Err(TrustError::NotAFile(path)),
Ok(_) => {}
}
let text = std::fs::read_to_string(&path).map_err(io(&path))?;
let bytes: [u8; 64] = hex::decode(text.trim())
.ok()
.and_then(|b| b.try_into().ok())
.ok_or_else(|| TrustError::Malformed(path, "expected 128 hex digits".to_owned()))?;
Ok(Some(Signature::from_bytes(&bytes)))
}
/// The publisher keys this host trusts to sign packages.
#[derive(Debug, Default)]
pub struct TrustStore {
keys: Vec<PublisherKey>,
}
impl TrustStore {
/// The trust store directories, in order: `$WEFT_TRUSTED_KEYS` alone when
/// set; otherwise the user's `$XDG_CONFIG_HOME/weft/trusted-keys` (or
/// `~/.config/weft/trusted-keys`) and the system `/etc/weft/trusted-keys`.
pub fn directories() -> Vec<PathBuf> {
if let Some(dir) = std::env::var_os("WEFT_TRUSTED_KEYS") {
return vec![PathBuf::from(dir)];
}
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|home| home.is_absolute())
.map(|home| home.join(".config"))
});
let mut dirs: Vec<PathBuf> = config
.map(|dir| dir.join("weft/trusted-keys"))
.into_iter()
.collect();
dirs.push(PathBuf::from("/etc/weft/trusted-keys"));
dirs
}
/// Loads every `*.pub` file in `directories`. A missing directory holds no
/// keys; a malformed key file is an error rather than silently ignored.
pub fn load(directories: &[PathBuf]) -> Result<Self, TrustError> {
let mut keys = Vec::new();
for dir in directories {
let entries = match std::fs::read_dir(dir) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
other => other.map_err(io(dir))?,
};
let mut files: Vec<PathBuf> = entries
.map(|e| e.map(|e| e.path()).map_err(io(dir)))
.collect::<Result<_, _>>()?;
files.sort();
for file in files
.into_iter()
.filter(|f| f.extension().is_some_and(|e| e == "pub"))
{
keys.push(PublisherKey::from_file(&file)?);
}
}
Ok(Self { keys })
}
pub fn keys(&self) -> &[PublisherKey] {
&self.keys
}
/// The trusted key that signed the package at `package_root`, if any.
pub fn signer(&self, package_root: &Path) -> Result<Option<PublisherKey>, TrustError> {
let Some(signature) = read_signature(package_root)? else {
return Ok(None);
};
Ok(self.signer_of(&content_digest(package_root)?, &signature))
}
/// The trusted key that made `signature` over `digest`, if any.
pub fn signer_of(&self, digest: &[u8; 32], signature: &Signature) -> Option<PublisherKey> {
self.keys
.iter()
.copied()
.find(|k| k.signed(digest, signature))
}
}
/// Who an application ID belongs to on this host. The record outlives the
/// package while the app's data remains, so another publisher cannot take
/// over the ID, and the data with it, by reusing it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
/// Installed from packages signed by this trusted key.
Verified(PublisherKey),
/// Installed as development content, without a trusted signature.
Development,
}
impl fmt::Display for Owner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Verified(key) => write!(f, "publisher {}", key.to_hex()),
Self::Development => f.write_str("development installation"),
}
}
}
/// Where the owner of `app_id` is recorded, beside the app's data. Callers
/// pass a valid app ID, which cannot leave the owners directory.
pub fn owner_record_path(data_home: &Path, app_id: &str) -> PathBuf {
data_home.join("weft/owners").join(app_id)
}
/// Reads an owner record: `verified <key>` or `development`.
pub fn read_owner(record: &Path) -> Result<Option<Owner>, TrustError> {
let text = match std::fs::read_to_string(record) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
other => other.map_err(io(record))?,
};
let malformed = |why: &str| TrustError::Malformed(record.to_path_buf(), why.to_owned());
match text.trim().split_once(' ') {
Some(("verified", key)) => PublisherKey::from_hex(key)
.map(|k| Some(Owner::Verified(k)))
.map_err(|why| malformed(&why)),
None if text.trim() == "development" => Ok(Some(Owner::Development)),
_ => Err(malformed("expected 'verified <key>' or 'development'")),
}
}
/// Records the owner of an app ID. An existing record is never replaced, and
/// a record is either absent or complete: it is written and synced under a
/// temporary name, then linked into place.
pub fn write_owner(record: &Path, owner: Owner) -> Result<(), TrustError> {
use std::io::Write;
let parent = record.parent().expect("owner records live in a directory");
std::fs::create_dir_all(parent).map_err(io(parent))?;
let text = match owner {
Owner::Verified(key) => format!("verified {}\n", key.to_hex()),
Owner::Development => "development\n".to_owned(),
};
let name = record
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("record");
let temp = parent.join(format!(".{name}.{}.tmp", std::process::id()));
let _ = std::fs::remove_file(&temp);
let written = (|| {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)?;
file.write_all(text.as_bytes())?;
file.sync_all()
})()
.map_err(io(&temp));
let linked = written.and_then(|()| std::fs::hard_link(&temp, record).map_err(io(record)));
let _ = std::fs::remove_file(&temp);
linked?;
std::fs::File::open(parent)
.and_then(|dir| dir.sync_all())
.map_err(io(parent))
}
/// Takes the lock that serialises every change to the installation and
/// owner record of `app_id`, held until the returned file is dropped.
pub fn lock_owner(data_home: &Path, app_id: &str) -> Result<std::fs::File, TrustError> {
let dir = data_home.join("weft/owners");
if !crate::package::is_valid_app_id(app_id) {
return Err(TrustError::Malformed(
dir,
format!("'{app_id}' is not a valid app ID"),
));
}
std::fs::create_dir_all(&dir).map_err(io(&dir))?;
let path = dir.join(format!(".{app_id}.lock"));
let file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(io(&path))?;
file.lock().map_err(io(&path))?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
fn dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("weft_trust_{name}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("ui")).unwrap();
std::fs::write(dir.join("wapp.toml"), b"[package]\n").unwrap();
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
dir
}
fn sign(dir: &Path, seed: u8) -> PublisherKey {
let key = SigningKey::from_bytes(&[seed; 32]);
let signature = key.sign(&content_digest(dir).unwrap());
std::fs::write(dir.join(SIGNATURE_FILE), hex::encode(signature.to_bytes())).unwrap();
PublisherKey(key.verifying_key())
}
fn store(keys: &[PublisherKey]) -> TrustStore {
TrustStore {
keys: keys.to_vec(),
}
}
#[test]
fn the_committed_demo_signatures_verify_with_the_demo_key() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let key = PublisherKey::from_file(&root.join("examples/keys/weft-sign.pub")).unwrap();
for demo in ["org.weft.demo.counter", "org.weft.demo.notes"] {
let package = root.join("examples").join(demo);
assert_eq!(store(&[key]).signer(&package).unwrap(), Some(key), "{demo}");
}
}
#[test]
fn any_changed_file_breaks_the_signature() {
let dir = dir("tamper");
let key = sign(&dir, 1);
assert_eq!(store(&[key]).signer(&dir).unwrap(), Some(key));
std::fs::write(dir.join("ui/index.html"), b"<p>changed").unwrap();
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
std::fs::write(dir.join("ui/index.html"), b"<p>").unwrap();
std::fs::write(dir.join("ui/extra.js"), b"").unwrap();
assert_eq!(store(&[key]).signer(&dir).unwrap(), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn only_trusted_keys_are_signers_and_unsigned_packages_have_none() {
let dir = dir("untrusted");
assert_eq!(store(&[]).signer(&dir).unwrap(), None);
let key = sign(&dir, 2);
let other = PublisherKey(SigningKey::from_bytes(&[3; 32]).verifying_key());
assert_eq!(store(&[other]).signer(&dir).unwrap(), None);
assert_eq!(store(&[other, key]).signer(&dir).unwrap(), Some(key));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(unix)]
#[test]
fn names_cannot_imitate_other_inventory_lines() {
// With files ui/policy.txt and ui/z.css signed, a directory named
// "ui/policy.txt\t<hash>\nui" holding z.css would reproduce the
// inventory without policy.txt. Such names have no digest.
let dir = dir("forged");
std::fs::write(dir.join("ui/policy.txt"), b"default-src 'self'").unwrap();
std::fs::write(dir.join("ui/z.css"), b"p{}").unwrap();
let signed = content_digest(&dir).unwrap();
let policy_hash = hex::encode(Sha256::digest(b"default-src 'self'"));
std::fs::remove_file(dir.join("ui/policy.txt")).unwrap();
let forged = dir.join(format!("ui/policy.txt\t{policy_hash}\nui"));
std::fs::create_dir_all(&forged).unwrap();
std::fs::rename(dir.join("ui/z.css"), forged.join("z.css")).unwrap();
let refused = content_digest(&dir);
assert!(matches!(refused, Err(TrustError::ControlCharacter(_))));
assert_ne!(refused.ok(), Some(signed));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn an_inventory_knows_the_bytes_it_hashed() {
let dir = dir("inventory");
let inventory = Inventory::read(&dir).unwrap();
assert_eq!(inventory.digest(), content_digest(&dir).unwrap());
assert!(inventory.holds("wapp.toml", b"[package]\n"));
assert!(!inventory.holds("wapp.toml", b"[package]\ncapabilities = []\n"));
assert!(!inventory.holds("absent.toml", b"[package]\n"));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn owner_locks_exclude_each_other() {
let home = std::env::temp_dir().join(format!("weft_trust_lock_{}", std::process::id()));
let held = lock_owner(&home, "org.weft.test.lock").unwrap();
let path = home.join("weft/owners/.org.weft.test.lock.lock");
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(other.try_lock().is_err());
drop(held);
assert!(other.try_lock().is_ok());
// A name that would open fine but is not an app ID is refused.
assert!(lock_owner(&home, "Org.weft.test").is_err());
assert!(!home.join("weft/owners/.Org.weft.test.lock").exists());
std::fs::remove_dir_all(&home).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn links_and_special_files_have_no_content_digest() {
let dir = dir("links");
std::os::unix::fs::symlink("/etc/hostname", dir.join("ui/linked")).unwrap();
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
std::fs::remove_file(dir.join("ui/linked")).unwrap();
std::os::unix::fs::symlink(dir.join("ui"), dir.join("view")).unwrap();
assert!(matches!(content_digest(&dir), Err(TrustError::Link(_))));
std::fs::remove_file(dir.join("view")).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
dir.join("fifo"),
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.unwrap();
assert!(matches!(content_digest(&dir), Err(TrustError::NotAFile(_))));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn trust_stores_load_pub_files_and_refuse_malformed_keys() {
let dir = dir("store");
let keys = dir.join("keys");
std::fs::create_dir_all(&keys).unwrap();
let key = PublisherKey(SigningKey::from_bytes(&[4; 32]).verifying_key());
std::fs::write(keys.join("a.pub"), key.to_hex()).unwrap();
std::fs::write(keys.join("notes.txt"), "not a key").unwrap();
let loaded = TrustStore::load(&[keys.clone(), dir.join("missing")]).unwrap();
assert_eq!(loaded.keys(), [key]);
std::fs::write(keys.join("b.pub"), "zz").unwrap();
assert!(matches!(
TrustStore::load(&[keys]),
Err(TrustError::Malformed(..))
));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn owner_records_round_trip_and_are_never_replaced() {
let dir = dir("owners");
let key = PublisherKey(SigningKey::from_bytes(&[5; 32]).verifying_key());
let verified = owner_record_path(&dir, "org.weft.test.a");
let development = owner_record_path(&dir, "org.weft.test.b");
assert_eq!(read_owner(&verified).unwrap(), None);
write_owner(&verified, Owner::Verified(key)).unwrap();
write_owner(&development, Owner::Development).unwrap();
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
assert_eq!(read_owner(&development).unwrap(), Some(Owner::Development));
assert!(write_owner(&verified, Owner::Development).is_err());
assert_eq!(read_owner(&verified).unwrap(), Some(Owner::Verified(key)));
std::fs::write(&development, "someone else\n").unwrap();
assert!(read_owner(&development).is_err());
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -10,3 +10,4 @@ path = "src/main.rs"
[dependencies]
anyhow = "1.0"
libc = "0.2"

View file

@ -1,29 +1,78 @@
use std::path::Path;
//! Mounts a dm-verity protected EROFS package image for weft-appd, and
//! unmounts it.
//!
//! The helper is installed setuid root, and every argument and the whole
//! environment come from the user who runs it. It therefore:
//!
//! - mounts only at an empty directory `/run/user/<uid>/weft/mnt/<name>` of
//! the real user, where each component from `<uid>` on is owned by that
//! user, not writable by others and opened without following symbolic
//! links; the mount goes through the opened directory, so the path cannot
//! be swapped meanwhile;
//! - opens the image and its hash tree with the real user's permissions;
//! - mounts read-only, without set-user-ID programs or device files;
//! - unmounts only an EROFS filesystem at such a directory;
//! - runs `veritysetup` from the absolute path fixed when it was built
//! (`WEFT_VERITYSETUP`), with an empty environment, and the mount
//! system calls itself.
use anyhow::Context;
use std::ffi::CString;
use std::fs::File;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Component, Path};
fn main() -> anyhow::Result<()> {
let args: Vec<String> = std::env::args().collect();
match args.get(1).map(String::as_str) {
Some("mount") => {
let img = args.get(2).context(
"usage: weft-mount-helper mount <img> <hash_dev> <root_hash> <mountpoint>",
)?;
let hash_dev = args.get(3).context("missing <hash_dev>")?;
let root_hash = args.get(4).context("missing <root_hash>")?;
let mountpoint = args.get(5).context("missing <mountpoint>")?;
cmd_mount(
Path::new(img),
Path::new(hash_dev),
root_hash,
Path::new(mountpoint),
)?;
use anyhow::{Context, bail};
const VERITYSETUP: &str = match option_env!("WEFT_VERITYSETUP") {
Some(path) => path,
None => "/usr/sbin/veritysetup",
};
/// The parent of every user's runtime directory.
const RUN_USER: &str = "/run/user";
const EROFS_SUPER_MAGIC: libc::c_long = 0xE0F5_E1E2;
/// How many package images one user may have open at a time, so a user
/// cannot use up the system's device-mapper and loop devices.
const MAX_DEVICES_PER_USER: usize = 64;
fn main() {
// Panics print one line too, whatever RUST_BACKTRACE says.
std::panic::set_hook(Box::new(|info| {
eprintln!("weft-mount-helper: internal error: {info}");
}));
// A caller can start the helper with standard input, output or error
// closed; a file opened later would then take that number and be
// misdirected. They are opened on /dev/null first.
for fd in 0..=2 {
if unsafe { libc::fcntl(fd, libc::F_GETFD) } < 0
&& unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDWR) } != fd
{
std::process::abort();
}
Some("umount") => {
let mountpoint = args
.get(2)
.context("usage: weft-mount-helper umount <mountpoint>")?;
cmd_umount(Path::new(mountpoint))?;
}
// Errors are printed as messages only: a caller's RUST_BACKTRACE has no
// effect.
if let Err(e) = run() {
eprintln!("weft-mount-helper: {e:#}");
std::process::exit(1);
}
}
fn run() -> anyhow::Result<()> {
let args: Vec<String> = std::env::args().collect();
match (args.get(1).map(String::as_str), args.len()) {
(Some("mount"), 6) => {
require_root()?;
cmd_mount(
Path::new(&args[2]),
Path::new(&args[3]),
&args[4],
Path::new(&args[5]),
)
}
(Some("umount"), 3) => {
require_root()?;
cmd_umount(Path::new(&args[2]))
}
_ => {
eprintln!("usage:");
@ -32,42 +81,228 @@ fn main() -> anyhow::Result<()> {
std::process::exit(1);
}
}
Ok(())
}
fn effective_uid() -> Option<u32> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
status
.lines()
.find(|l| l.starts_with("Uid:"))
.and_then(|l| l.split_whitespace().nth(2))
.and_then(|s| s.parse().ok())
}
fn require_root() -> anyhow::Result<()> {
match effective_uid() {
Some(0) => Ok(()),
Some(uid) => anyhow::bail!("weft-mount-helper must run as root (euid={uid})"),
None => {
anyhow::bail!("weft-mount-helper must run as root (could not read /proc/self/status)")
}
let euid = unsafe { libc::geteuid() };
if euid != 0 {
bail!("weft-mount-helper must run as root (euid={euid})");
}
Ok(())
}
fn real_ids() -> (libc::uid_t, libc::gid_t) {
unsafe { (libc::getuid(), libc::getgid()) }
}
/// A mountpoint that passed the checks, held open.
struct Mountpoint {
dir: OwnedFd,
uid: libc::uid_t,
name: String,
}
impl Mountpoint {
/// The directory as a path the kernel resolves to the open directory.
fn proc_path(&self) -> String {
format!("/proc/self/fd/{}", self.dir.as_raw_fd())
}
/// The device-mapper name, from the user and the mountpoint's name,
/// which weft-appd chooses at random, so concurrent sessions get
/// distinct devices and no user can name another user's.
fn device_name(&self) -> String {
format!("{}{}", device_prefix(self.uid), self.name)
}
}
fn device_name(mountpoint: &Path) -> String {
let s = mountpoint.to_string_lossy();
let sanitized: String = s
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let suffix: String = sanitized
.trim_matches('-')
.chars()
.take(26)
.collect::<String>()
.trim_end_matches('-')
.to_string();
format!("weft-{suffix}")
fn device_prefix(uid: libc::uid_t) -> String {
format!("weft-{uid}-")
}
/// The names of the device-mapper devices, from the kernel's own list.
fn device_names() -> anyhow::Result<Vec<String>> {
let mut names = Vec::new();
for entry in std::fs::read_dir("/sys/block").context("cannot list block devices")? {
let path = entry
.context("cannot list block devices")?
.path()
.join("dm/name");
match std::fs::read_to_string(&path) {
Ok(name) => names.push(name.trim_end().to_owned()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
Ok(names)
}
/// Serializes device creation, so the per-user limit holds against
/// concurrent mounts. The lock lives in a directory only root can write.
fn lock_devices() -> anyhow::Result<File> {
let lock = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open("/run/weft-mount-helper.lock")
.context("cannot open the device lock")?;
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 {
bail!(
"cannot lock the devices: {}",
std::io::Error::last_os_error()
);
}
Ok(lock)
}
/// A mountpoint name: what weft-appd's random tokens are made of.
fn is_mountpoint_name(name: &str) -> bool {
(1..=64).contains(&name.len())
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// A dm-verity root hash in hex, as `veritysetup format` prints it.
fn is_root_hash(text: &str) -> bool {
(64..=128).contains(&text.len())
&& text.len().is_multiple_of(2)
&& text.bytes().all(|b| b.is_ascii_hexdigit())
}
fn openat_dir(parent: Option<&OwnedFd>, name: &Path) -> std::io::Result<OwnedFd> {
let name = CString::new(name.as_os_str().as_encoded_bytes())
.map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
let dirfd = parent.map_or(libc::AT_FDCWD, |p| p.as_raw_fd());
let fd = unsafe {
libc::openat(
dirfd,
name.as_ptr(),
libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
fn fstat(fd: &OwnedFd) -> std::io::Result<libc::stat> {
let mut st: libc::stat = unsafe { std::mem::zeroed() };
if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(st)
}
/// Opens `mountpoint`, which must be `<run_user>/<uid>/weft/mnt/<name>`.
/// Every directory from `<uid>` on must belong to `uid` and not be writable
/// by others; for a mount, the mountpoint itself too, and it must be empty.
fn open_mountpoint(
run_user: &Path,
uid: libc::uid_t,
mountpoint: &Path,
for_mount: bool,
) -> anyhow::Result<Mountpoint> {
let base = run_user.join(uid.to_string()).join("weft/mnt");
let name = mountpoint
.strip_prefix(&base)
.ok()
.filter(|rest| {
let mut components = rest.components();
matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
})
.and_then(|rest| rest.to_str())
.filter(|name| is_mountpoint_name(name))
.with_context(|| {
format!(
"{} is not a mountpoint in {}",
mountpoint.display(),
base.display()
)
})?
.to_owned();
let mut dir = openat_dir(None, run_user)
.with_context(|| format!("cannot open {}", run_user.display()))?;
let uid_dir = uid.to_string();
let components = [uid_dir.as_str(), "weft", "mnt", name.as_str()];
for (i, component) in components.iter().enumerate() {
dir = openat_dir(Some(&dir), Path::new(component))
.with_context(|| format!("cannot open {component} in the path to the mountpoint"))?;
// For an unmount the last one is the mounted filesystem's root.
if i == components.len() - 1 && !for_mount {
break;
}
let st = fstat(&dir)?;
if st.st_uid != uid || st.st_mode & 0o022 != 0 {
bail!("{component} in the path to the mountpoint is not the user's own directory");
}
}
let mountpoint = Mountpoint { dir, uid, name };
if for_mount
&& std::fs::read_dir(mountpoint.proc_path())
.context("cannot read the mountpoint")?
.next()
.is_some()
{
bail!("the mountpoint is not empty");
}
Ok(mountpoint)
}
/// Opens `path` with the real user's permissions, as a regular file.
fn open_as_user(path: &Path, uid: libc::uid_t, gid: libc::gid_t) -> anyhow::Result<File> {
let euid = unsafe { libc::geteuid() };
let egid = unsafe { libc::getegid() };
if unsafe { libc::setegid(gid) } != 0 || unsafe { libc::seteuid(uid) } != 0 {
let error = std::io::Error::last_os_error();
restore_ids(euid, egid);
bail!("cannot take the user's permissions: {error}");
}
let opened = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path);
restore_ids(euid, egid);
let file = opened.with_context(|| format!("cannot open {}", path.display()))?;
if !file.metadata()?.file_type().is_file() {
bail!("{} is not a regular file", path.display());
}
Ok(file)
}
/// Returns to the helper's own effective IDs; continuing without them is
/// not safe, so failing aborts.
fn restore_ids(euid: libc::uid_t, egid: libc::gid_t) {
if unsafe { libc::seteuid(euid) } != 0 || unsafe { libc::setegid(egid) } != 0 {
std::process::abort();
}
}
/// Lets a child process inherit `file`.
fn inheritable(file: &File) -> anyhow::Result<String> {
let fd = file.as_raw_fd();
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } < 0 {
bail!("cannot pass a file on: {}", std::io::Error::last_os_error());
}
Ok(format!("/proc/self/fd/{fd}"))
}
fn veritysetup(args: &[&str]) -> anyhow::Result<()> {
let status = std::process::Command::new(VERITYSETUP)
.env_clear()
.args(args)
.stdin(std::process::Stdio::null())
.status()
.with_context(|| format!("cannot run {VERITYSETUP}"))?;
if !status.success() {
bail!("veritysetup {} failed with {status}", args[0]);
}
Ok(())
}
fn cmd_mount(
@ -76,66 +311,87 @@ fn cmd_mount(
root_hash: &str,
mountpoint: &Path,
) -> anyhow::Result<()> {
require_root()?;
let dev_name = device_name(mountpoint);
let status = std::process::Command::new("veritysetup")
.args([
"open",
&img.to_string_lossy(),
&dev_name,
&hash_dev.to_string_lossy(),
root_hash,
])
.status()
.context("spawn veritysetup; ensure cryptsetup-bin is installed")?;
if !status.success() {
anyhow::bail!("veritysetup open failed with status {status}");
if !is_root_hash(root_hash) {
bail!("the root hash is not a hex digest");
}
let (uid, gid) = real_ids();
let target = open_mountpoint(Path::new(RUN_USER), uid, mountpoint, true)?;
let image = open_as_user(img, uid, gid)?;
let hash_tree = open_as_user(hash_dev, uid, gid)?;
let dev_name = target.device_name();
let _lock = lock_devices()?;
let names = device_names()?;
// A device left by a mount interrupted before it was mounted here; the
// empty mountpoint shows it is not in use.
if names.contains(&dev_name) {
veritysetup(&["close", &dev_name])?;
}
let prefix = device_prefix(uid);
let open = names
.iter()
.filter(|name| name.starts_with(&prefix) && **name != dev_name)
.count();
if open >= MAX_DEVICES_PER_USER {
bail!("too many package images are open ({MAX_DEVICES_PER_USER})");
}
let mapper_dev = format!("/dev/mapper/{dev_name}");
let status = std::process::Command::new("mount")
.args([
"-t",
"erofs",
"-o",
"ro",
&mapper_dev,
&mountpoint.to_string_lossy(),
])
.status()
.context("spawn mount")?;
if !status.success() {
let _ = std::process::Command::new("veritysetup")
.args(["close", &dev_name])
.status();
anyhow::bail!("mount failed with status {status}");
}
veritysetup(&[
"open",
&inheritable(&image)?,
&dev_name,
&inheritable(&hash_tree)?,
root_hash,
])?;
let source = CString::new(format!("/dev/mapper/{dev_name}"))?;
let path = CString::new(target.proc_path())?;
let fstype = CString::new("erofs")?;
// Packages hold components and UI files, which are read, never run.
let flags = libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC;
let mounted = unsafe {
libc::mount(
source.as_ptr(),
path.as_ptr(),
fstype.as_ptr(),
flags,
std::ptr::null(),
)
};
if mounted != 0 {
let error = std::io::Error::last_os_error();
let _ = veritysetup(&["close", &dev_name]);
bail!("mount failed: {error}");
}
eprintln!("mounted: {} -> {}", img.display(), mountpoint.display());
Ok(())
}
fn cmd_umount(mountpoint: &Path) -> anyhow::Result<()> {
require_root()?;
let dev_name = device_name(mountpoint);
let status = std::process::Command::new("umount")
.arg(mountpoint)
.status()
.context("spawn umount")?;
if !status.success() {
anyhow::bail!("umount failed with status {status}");
let (uid, _) = real_ids();
let target = open_mountpoint(Path::new(RUN_USER), uid, mountpoint, false)?;
let mut fs: libc::statfs = unsafe { std::mem::zeroed() };
if unsafe { libc::fstatfs(target.dir.as_raw_fd(), &mut fs) } != 0 {
bail!(
"cannot inspect the mountpoint: {}",
std::io::Error::last_os_error()
);
}
let status = std::process::Command::new("veritysetup")
.args(["close", &dev_name])
.status()
.context("spawn veritysetup close; ensure cryptsetup-bin is installed")?;
if !status.success() {
anyhow::bail!("veritysetup close failed with status {status}");
if fs.f_type as libc::c_long != EROFS_SUPER_MAGIC {
// A mount interrupted after its device opened leaves the device and
// an empty mountpoint; the device is the caller's own.
let dev_name = target.device_name();
if device_names()?.contains(&dev_name) {
veritysetup(&["close", &dev_name])?;
eprintln!("closed the unmounted device for {}", mountpoint.display());
return Ok(());
}
bail!("no package image is mounted at {}", mountpoint.display());
}
let path = CString::new(target.proc_path())?;
if unsafe { libc::umount2(path.as_ptr(), 0) } != 0 {
bail!("umount failed: {}", std::io::Error::last_os_error());
}
veritysetup(&["close", &target.device_name()])?;
eprintln!("unmounted: {}", mountpoint.display());
Ok(())
}
@ -143,20 +399,136 @@ fn cmd_umount(mountpoint: &Path) -> anyhow::Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn device_name_sanitizes_path() {
let mp = Path::new("/run/weft/mounts/com.example.myapp");
let name = device_name(mp);
assert!(name.starts_with("weft-"));
assert!(name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'));
assert!(name.len() <= 31);
struct Layout {
root: std::path::PathBuf,
uid: libc::uid_t,
}
impl Layout {
fn new(tag: &str) -> Self {
let root = std::env::temp_dir()
.join(format!("weft_mount_helper_{tag}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let uid = unsafe { libc::getuid() };
let mnt = root.join(uid.to_string()).join("weft/mnt");
std::fs::create_dir_all(&mnt).unwrap();
for dir in [
root.join(uid.to_string()),
root.join(format!("{uid}/weft")),
mnt,
] {
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
}
Layout { root, uid }
}
fn mnt(&self) -> std::path::PathBuf {
self.root.join(self.uid.to_string()).join("weft/mnt")
}
}
impl Drop for Layout {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn device_name_truncates_long_paths() {
let mp = Path::new("/run/weft/mounts/com.example.averylongappidthatexceedsthemaximum");
let name = device_name(mp);
assert!(name.len() <= 31);
fn an_empty_directory_of_the_user_is_a_mountpoint() {
let layout = Layout::new("ok");
let point = layout.mnt().join("0123abcd");
std::fs::create_dir(&point).unwrap();
let target = open_mountpoint(&layout.root, layout.uid, &point, true).unwrap();
assert_eq!(
target.device_name(),
format!("weft-{}-0123abcd", layout.uid)
);
// The open directory is the mountpoint.
assert_eq!(
std::fs::canonicalize(target.proc_path()).unwrap(),
std::fs::canonicalize(&point).unwrap()
);
}
#[test]
fn mountpoints_elsewhere_are_refused() {
let layout = Layout::new("elsewhere");
let mnt = layout.mnt();
std::fs::create_dir(mnt.join("ok")).unwrap();
for path in [
std::path::PathBuf::from("/etc"),
layout.root.join("other"),
mnt.clone(),
mnt.join("ok/deeper"),
mnt.join("../mnt/ok"),
mnt.join("bad.name"),
mnt.join("x".repeat(65)),
// Another user's directory.
layout
.root
.join((layout.uid + 1).to_string())
.join("weft/mnt/ok"),
] {
assert!(
open_mountpoint(&layout.root, layout.uid, &path, true).is_err(),
"{}",
path.display()
);
}
}
#[test]
fn symbolic_links_and_shared_directories_are_refused() {
let layout = Layout::new("links");
let mnt = layout.mnt();
// The mountpoint is a link to a directory elsewhere.
let elsewhere = layout.root.join("elsewhere");
std::fs::create_dir(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, mnt.join("link")).unwrap();
assert!(open_mountpoint(&layout.root, layout.uid, &mnt.join("link"), true).is_err());
assert!(open_mountpoint(&layout.root, layout.uid, &mnt.join("link"), false).is_err());
// A directory others may write to.
std::fs::create_dir(mnt.join("shared")).unwrap();
std::fs::set_permissions(mnt.join("shared"), std::fs::Permissions::from_mode(0o777))
.unwrap();
assert!(open_mountpoint(&layout.root, layout.uid, &mnt.join("shared"), true).is_err());
// A link in the path above the mountpoint.
let weft = layout.root.join(format!("{}/weft", layout.uid));
std::fs::rename(&weft, layout.root.join("moved")).unwrap();
std::os::unix::fs::symlink(layout.root.join("moved"), &weft).unwrap();
std::fs::create_dir(layout.root.join("moved/mnt/ok")).unwrap();
assert!(open_mountpoint(&layout.root, layout.uid, &mnt.join("ok"), true).is_err());
}
#[test]
fn a_mountpoint_must_be_empty_and_the_users_own() {
let layout = Layout::new("full");
let point = layout.mnt().join("full");
std::fs::create_dir(&point).unwrap();
std::fs::write(point.join("file"), b"x").unwrap();
assert!(open_mountpoint(&layout.root, layout.uid, &point, true).is_err());
// Unmounting looks at the mounted filesystem, not its contents.
assert!(open_mountpoint(&layout.root, layout.uid, &point, false).is_ok());
// The same layout seen as another user's.
let other = layout.uid + 1;
let theirs = layout.root.join(other.to_string());
std::fs::rename(layout.root.join(layout.uid.to_string()), &theirs).unwrap();
std::fs::remove_file(theirs.join("weft/mnt/full/file")).unwrap();
assert!(open_mountpoint(&layout.root, other, &theirs.join("weft/mnt/full"), true).is_err());
std::fs::rename(&theirs, layout.root.join(layout.uid.to_string())).unwrap();
}
#[test]
fn root_hashes_are_hex_digests() {
assert!(is_root_hash(&"a".repeat(64)));
assert!(is_root_hash(&"0F".repeat(64)));
for bad in ["", "-a", &"g".repeat(64), &"a".repeat(65), &"a".repeat(130)] {
assert!(!is_root_hash(bad), "{bad:?}");
}
}
}

View file

@ -9,12 +9,14 @@ name = "weft-pack"
path = "src/main.rs"
[dependencies]
weft-ipc-types = { path = "../weft-ipc-types" }
anyhow = "1.0"
serde = { version = "1", features = ["derive"] }
toml = "0.8"
ed25519-dalek = { version = "2", features = ["rand_core"] }
sha2 = "0.10"
rand = "0.8"
hex = "0.4"
tar = "0.4"
zstd = "0.13"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }

File diff suppressed because it is too large Load diff

View file

@ -10,9 +10,9 @@ path = "src/main.rs"
[features]
default = []
wasmtime-runtime = ["dep:wasmtime", "dep:wasmtime-wasi", "dep:cap-std"]
wasmtime-runtime = ["dep:wasmtime", "dep:wasmtime-wasi", "dep:cap-std", "dep:libc"]
seccomp = ["dep:seccompiler", "dep:libc"]
net-fetch = ["dep:ureq"]
net-fetch = ["dep:ureq", "dep:url"]
[dependencies]
anyhow = "1.0"
@ -24,3 +24,5 @@ cap-std = { version = "3", optional = true }
seccompiler = { version = "0.4", optional = true }
libc = { version = "0.2", optional = true }
ureq = { version = "2", optional = true }
url = { version = "2", optional = true }
weft-ipc-types = { path = "../weft-ipc-types" }

View file

@ -0,0 +1,269 @@
//! The desktop services behind the clipboard and notification imports.
//!
//! Each import runs a helper program (`wl-paste`, `wl-copy`,
//! `notify-send`) with a bounded input, a bounded output and a deadline,
//! after which the helper is killed and the call fails. A notification
//! names the application that sent it, so an app cannot pass one off as
//! the system's.
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
/// How long a helper may run.
const HELPER_TIMEOUT: Duration = Duration::from_secs(5);
/// The most clipboard text read or written, in bytes.
pub const MAX_CLIPBOARD: usize = 1024 * 1024;
/// The longest notification title and body, in bytes.
pub const MAX_TITLE: usize = 256;
pub const MAX_BODY: usize = 4096;
/// What a helper's output streams are connected to.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Output {
/// Read: up to the limit from standard output, and standard error for
/// the failure message.
Captured,
/// Standard output discarded and standard error read only when the
/// helper fails, for a helper that leaves a process running which
/// keeps its streams open after succeeding, as `wl-copy` does to
/// serve the selection; it fails, if at all, before that.
ErrorsOnly,
}
/// Runs `command` with `input` on its standard input and returns at most
/// `max_output` bytes of its standard output, or why it failed.
fn run(
mut command: Command,
input: Option<Vec<u8>>,
max_output: usize,
output: Output,
) -> Result<Vec<u8>, String> {
let program = command.get_program().to_string_lossy().into_owned();
let mut child = command
.stdin(if input.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(match output {
Output::Captured => Stdio::piped(),
Output::ErrorsOnly => Stdio::null(),
})
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot run {program}: {e}"))?;
if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) {
std::thread::spawn(move || {
let _ = stdin.write_all(&input);
});
}
let reader = |stream: Option<Box<dyn Read + Send>>, limit: usize| {
std::thread::spawn(move || {
let mut data = Vec::new();
if let Some(stream) = stream {
let _ = stream.take(limit as u64 + 1).read_to_end(&mut data);
}
data
})
};
let stdout = reader(
child
.stdout
.take()
.map(|s| Box::new(s) as Box<dyn Read + Send>),
max_output,
);
let stderr = reader(
child
.stderr
.take()
.map(|s| Box::new(s) as Box<dyn Read + Send>),
4096,
);
let deadline = Instant::now() + HELPER_TIMEOUT;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
Ok(None) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"{program} did not finish within {} s",
HELPER_TIMEOUT.as_secs()
));
}
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(e.to_string());
}
}
};
let output = stdout.join().unwrap_or_default();
// Checked first: a helper whose output is cut off at the limit may die
// of the broken pipe.
if output.len() > max_output {
return Err(format!("{program} returned more than {max_output} bytes"));
}
if !status.success() {
let message = String::from_utf8_lossy(&stderr.join().unwrap_or_default())
.trim()
.to_owned();
return Err(if message.is_empty() {
format!("{program} exited with {status}")
} else {
format!("{program}: {message}")
});
}
Ok(output)
}
pub fn clipboard_read() -> Result<String, String> {
let mut command = Command::new("wl-paste");
// Any text type; the content must still be UTF-8.
command.args(["--no-newline", "--type", "text"]);
let data = run(command, None, MAX_CLIPBOARD, Output::Captured)?;
String::from_utf8(data).map_err(|_| "the clipboard does not hold UTF-8 text".to_owned())
}
pub fn clipboard_write(text: &str) -> Result<(), String> {
if text.len() > MAX_CLIPBOARD {
return Err(format!("clipboard text exceeds {MAX_CLIPBOARD} bytes"));
}
let mut command = Command::new("wl-copy");
command.args(["--type", "text/plain;charset=utf-8"]);
run(
command,
Some(text.as_bytes().to_vec()),
0,
Output::ErrorsOnly,
)
.map(|_| ())
}
/// Checks a notification before it is sent.
pub fn check_notification(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
if title.len() > MAX_TITLE {
return Err(format!("notification title exceeds {MAX_TITLE} bytes"));
}
if body.len() > MAX_BODY {
return Err(format!("notification body exceeds {MAX_BODY} bytes"));
}
// Only icon theme names: a path or URL would let the app show any file
// or reach the network through the notification service.
if let Some(icon) = icon
&& !is_icon_name(icon)
{
return Err("a notification icon must be an icon theme name".to_owned());
}
Ok(())
}
fn is_icon_name(icon: &str) -> bool {
!icon.is_empty()
&& icon.len() <= 64
&& !icon.starts_with('.')
&& icon
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
}
fn escape_markup(text: &str) -> String {
text.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
/// Sends a notification attributed to `app_id`.
pub fn notify(app_id: &str, title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
check_notification(title, body, icon)?;
let mut command = Command::new("notify-send");
command.arg(format!("--app-name={app_id}"));
if let Some(icon) = icon {
command.arg(format!("--icon={icon}"));
}
// Notification servers may render markup in the body, including links
// and images, so it is sent as plain text.
command.arg("--").arg(title).arg(escape_markup(body));
run(command, None, 0, Output::Captured).map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn notification_bodies_are_plain_text() {
assert_eq!(
escape_markup("<a href=\"x\">a & b</a>"),
"&lt;a href=\"x\"&gt;a &amp; b&lt;/a&gt;"
);
}
#[test]
fn notifications_are_bounded_and_icons_are_theme_names() {
assert!(check_notification("t", "b", None).is_ok());
assert!(check_notification("t", "b", Some("dialog-information")).is_ok());
assert!(check_notification(&"t".repeat(MAX_TITLE + 1), "b", None).is_err());
assert!(check_notification("t", &"b".repeat(MAX_BODY + 1), None).is_err());
for icon in [
"/etc/passwd",
"file:///x.png",
"https://x/i.png",
"../x",
"",
"a b",
] {
assert!(check_notification("t", "b", Some(icon)).is_err(), "{icon}");
}
}
#[test]
fn helpers_are_bounded_in_time_and_output() {
let mut slow = Command::new("sleep");
slow.arg("30");
let started = Instant::now();
let error = run(slow, None, 0, Output::Captured).unwrap_err();
assert!(error.contains("did not finish"), "{error}");
assert!(started.elapsed() < HELPER_TIMEOUT + Duration::from_secs(2));
let mut chatty = Command::new("head");
// Far more than a pipe holds, so the cut-off kills the writer.
chatty.args(["-c", "10000000", "/dev/zero"]);
assert!(
run(chatty, None, 1000, Output::Captured)
.unwrap_err()
.contains("more than 1000 bytes")
);
let echo = Command::new("cat");
assert_eq!(
run(echo, Some(b"text".to_vec()), 100, Output::Captured).unwrap(),
b"text"
);
// A helper that leaves a process behind returns once it exits
// itself when its streams are discarded.
let mut forking = Command::new("sh");
forking.args(["-c", "sleep 30 & exit 0"]);
let started = Instant::now();
assert!(run(forking, None, 0, Output::ErrorsOnly).is_ok());
assert!(started.elapsed() < Duration::from_secs(2));
let mut failing = Command::new("sh");
failing.args(["-c", "echo no display >&2; exit 1"]);
assert_eq!(
run(failing, None, 0, Output::ErrorsOnly).unwrap_err(),
"sh: no display"
);
let failing = Command::new("false");
assert!(
run(failing, None, 0, Output::Captured)
.unwrap_err()
.contains("exited")
);
}
}

View file

@ -0,0 +1,336 @@
//! The effective grants weft-appd derived for this session.
//!
//! weft-appd passes each host-import capability as `--grant <capability>` and
//! each filesystem capability as `--preopen HOST::GUEST::ro|rw`. Nothing here
//! reads the package manifest: the runtime enforces what the supervisor
//! granted, not what the package asks for.
use anyhow::Context;
use weft_ipc_types::capability::{Access, Capability, FetchScope};
/// Grants for the host imports in the `weft:app` world.
#[derive(Debug, Default)]
pub struct Grants {
fetch: Vec<FetchScope>,
notifications: bool,
clipboard_read: bool,
clipboard_write: bool,
}
// The checks are used by the import implementations, which only exist with
// the wasmtime-runtime feature.
#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))]
impl Grants {
/// Adds a `--grant` argument. Filesystem capabilities arrive as preopens
/// and hardware capabilities have no import, so both are refused here.
pub fn add(&mut self, spec: &str) -> anyhow::Result<()> {
match spec.parse::<Capability>()? {
Capability::Fetch(scope) => self.fetch.push(scope),
Capability::Notifications => self.notifications = true,
Capability::ClipboardRead => self.clipboard_read = true,
Capability::ClipboardWrite => self.clipboard_write = true,
other => anyhow::bail!("'{other}' is not granted through --grant"),
}
Ok(())
}
pub fn notifications(&self) -> Result<(), String> {
granted(self.notifications, "sys:notifications")
}
pub fn clipboard_read(&self) -> Result<(), String> {
granted(self.clipboard_read, "sys:clipboard:read")
}
pub fn clipboard_write(&self) -> Result<(), String> {
granted(self.clipboard_write, "sys:clipboard:write")
}
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
/// Whether a request to `host` is covered by a fetch grant, and which
/// addresses it may reach. `host` is the URL's host in the lowercase form
/// URL parsing produces.
pub fn fetch_host(&self, host: &str) -> Result<Reach, String> {
if self.fetch.is_empty() {
return Err("capability net:fetch is not granted".to_owned());
}
// An address named in a grant is reached as declared, wherever it
// is; a name, or any host, reaches only public addresses, so a
// granted name cannot be pointed at this machine or the local
// network through DNS.
if host.parse::<std::net::Ipv4Addr>().is_ok()
&& self
.fetch
.iter()
.any(|scope| matches!(scope, FetchScope::Host(granted) if granted == host))
{
return Ok(Reach::Declared);
}
let covered = self.fetch.iter().any(|scope| match scope {
FetchScope::AnyHost => true,
FetchScope::Host(granted) => granted == host,
});
if covered {
Ok(Reach::Public)
} else {
Err(format!("capability net:fetch:{host} is not granted"))
}
}
/// Whether any fetch grant exists, before a URL is examined.
pub fn fetch_any(&self) -> Result<(), String> {
granted(!self.fetch.is_empty(), "net:fetch")
}
}
#[cfg_attr(not(feature = "wasmtime-runtime"), allow(dead_code))]
fn granted(present: bool, capability: &str) -> Result<(), String> {
if present {
Ok(())
} else {
Err(format!("capability {capability} is not granted"))
}
}
/// A directory made visible to the component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Preopen {
pub host: String,
pub guest: String,
pub access: Access,
}
impl Preopen {
/// Parses `HOST::GUEST::ro` or `HOST::GUEST::rw`.
pub fn parse(spec: &str) -> anyhow::Result<Self> {
let (rest, mode) = spec
.rsplit_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?;
// Guest paths are fixed names without `::`; splitting from the right
// keeps a host path containing `::` whole.
let (host, guest) = rest
.rsplit_once("::")
.context("--preopen expects HOST::GUEST::ro|rw")?;
let access = match mode {
"ro" => Access::Read,
"rw" => Access::ReadWrite,
other => anyhow::bail!("--preopen mode must be ro or rw, not '{other}'"),
};
anyhow::ensure!(
!host.is_empty() && guest.starts_with('/'),
"--preopen needs a host path and an absolute guest path"
);
Ok(Self {
host: host.to_owned(),
guest: guest.to_owned(),
access,
})
}
}
/// The addresses a granted request may connect to.
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reach {
/// Only public addresses.
Public,
/// The address the grant names, public or not.
Declared,
}
/// Whether `ip` is a public unicast address: not loopback, unspecified,
/// private, shared (CGNAT), link-local, multicast, broadcast, reserved,
/// documentation or benchmarking space, nor an IPv6 form of one.
#[cfg_attr(not(feature = "net-fetch"), allow(dead_code))]
pub fn is_public(ip: std::net::IpAddr) -> bool {
use std::net::IpAddr;
match ip {
IpAddr::V4(v4) => {
let [a, b, c, _] = v4.octets();
!(v4.is_unspecified()
|| v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_multicast()
|| v4.is_broadcast()
|| v4.is_documentation()
|| a == 0
|| a >= 240
|| (a == 100 && (64..128).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| (a == 198 && (18..20).contains(&b)))
}
IpAddr::V6(v6) => {
let seg = v6.segments();
let embedded = |high: u16, low: u16| {
IpAddr::V4(std::net::Ipv4Addr::new(
(high >> 8) as u8,
high as u8,
(low >> 8) as u8,
low as u8,
))
};
// Forms that carry an IPv4 address are judged by that address:
// mapped and compatible addresses, 6to4 and NAT64.
if let Some(v4) = v6.to_ipv4_mapped() {
return is_public(IpAddr::V4(v4));
}
// IPv4-translated (::ffff:0:a.b.c.d).
if seg[..6] == [0, 0, 0, 0, 0xffff, 0] {
return is_public(embedded(seg[6], seg[7]));
}
if seg[..6] == [0; 6] && !(seg[6] == 0 && seg[7] <= 1) {
return is_public(embedded(seg[6], seg[7]));
}
if seg[0] == 0x2002 {
return is_public(embedded(seg[1], seg[2]));
}
if seg[..6] == [0x0064, 0xff9b, 0, 0, 0, 0] {
return is_public(embedded(seg[6], seg[7]));
}
!(v6.is_unspecified()
|| v6.is_loopback()
|| v6.is_multicast()
// Unique local, link-local and the deprecated site-local.
|| (seg[0] & 0xfe00) == 0xfc00
|| (seg[0] & 0xffc0) == 0xfe80
|| (seg[0] & 0xffc0) == 0xfec0
// NAT64 for local use, discard-only.
|| (seg[0] == 0x0064 && seg[1] == 0xff9b)
|| (seg[0] == 0x0100 && seg[1..4] == [0, 0, 0])
// Teredo, benchmarking, ORCHID and documentation.
|| (seg[0] == 0x2001 && seg[1] == 0)
|| (seg[0] == 0x2001 && seg[1] == 0x0002 && seg[2] == 0)
|| (seg[0] == 0x2001 && matches!(seg[1] & 0xfff0, 0x0010 | 0x0020))
|| (seg[0] == 0x2001 && seg[1] == 0x0db8)
|| (seg[0] == 0x3fff && (seg[1] & 0xf000) == 0))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn imports_are_denied_without_grants() {
let grants = Grants::default();
assert!(grants.notifications().is_err());
assert!(grants.clipboard_read().is_err());
assert!(grants.clipboard_write().is_err());
assert!(grants.fetch_any().is_err());
assert!(grants.fetch_host("example.org").is_err());
}
#[test]
fn each_grant_opens_only_its_import() {
let mut grants = Grants::default();
grants.add("sys:clipboard:read").unwrap();
assert!(grants.clipboard_read().is_ok());
assert!(grants.clipboard_write().is_err());
assert!(grants.notifications().is_err());
}
#[test]
fn named_and_wildcard_grants_reach_only_public_addresses() {
let mut grants = Grants::default();
grants.add("net:fetch:api.example.org").unwrap();
grants.add("net:fetch:127.0.0.1").unwrap();
assert_eq!(grants.fetch_host("api.example.org"), Ok(Reach::Public));
// An address named in a grant is reached as declared.
assert_eq!(grants.fetch_host("127.0.0.1"), Ok(Reach::Declared));
let mut any = Grants::default();
any.add("net:fetch:*").unwrap();
assert_eq!(any.fetch_host("10.0.0.1"), Ok(Reach::Public));
}
#[test]
fn only_public_unicast_addresses_are_public() {
// NAT64 and 6to4 forms of a public address are public, so DNS64
// networks keep working.
for public in [
"93.184.216.34",
"1.1.1.1",
"2606:4700::1111",
"64:ff9b::5db8:d822",
"2002:5db8:d822::1",
"3ffe::1",
] {
assert!(is_public(public.parse().unwrap()), "{public}");
}
for local in [
"127.0.0.1",
"0.0.0.0",
"10.1.2.3",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"100.64.0.1",
"224.0.0.1",
"255.255.255.255",
"192.0.2.1",
"198.18.0.1",
"240.0.0.1",
"::1",
"::",
"fd00::1",
"fe80::1",
"ff02::1",
"::ffff:127.0.0.1",
"::ffff:10.0.0.1",
"64:ff9b::a00:1",
"64:ff9b:1::1",
"64:ff9b:0:0:1::1",
"::ffff:0:a00:1",
"2001:20::1",
"2001:db8::1",
"fec0::1",
"::7f00:1",
"2002:7f00:1::",
"2002:a00:1::",
"2001::1",
"2001:2::1",
"2001:10::1",
"3fff::1",
"100::1",
] {
assert!(!is_public(local.parse().unwrap()), "{local}");
}
}
#[test]
fn host_fetch_grants_match_exact_hosts() {
let mut grants = Grants::default();
grants.add("net:fetch:api.example.org").unwrap();
assert!(grants.fetch_any().is_ok());
assert!(grants.fetch_host("api.example.org").is_ok());
assert!(grants.fetch_host("example.org").is_err());
assert!(grants.fetch_host("evil.api.example.org").is_err());
grants.add("net:fetch:*").unwrap();
assert!(grants.fetch_host("example.org").is_ok());
}
#[test]
fn filesystem_and_unknown_grants_are_refused() {
let mut grants = Grants::default();
assert!(grants.add("fs:rw:app-data").is_err());
assert!(grants.add("hw:gpu:compute").is_err());
assert!(grants.add("sys:everything").is_err());
}
#[test]
fn preopens_carry_their_mode() {
let preopen = Preopen::parse("/home/u/data::/data::ro").unwrap();
assert_eq!(preopen.host, "/home/u/data");
assert_eq!(preopen.guest, "/data");
assert_eq!(preopen.access, Access::Read);
assert_eq!(
Preopen::parse("/a::/b::rw").unwrap().access,
Access::ReadWrite
);
assert_eq!(Preopen::parse("/a::/b::/data::ro").unwrap().host, "/a::/b");
for bad in ["/a::/b", "/a", "/a::/b::wx", "::/b::ro", "/a::b::ro"] {
assert!(Preopen::parse(bad).is_err(), "{bad} accepted");
}
}
}

View file

@ -0,0 +1,297 @@
//! The component's connection to its session's IPC relay in weft-appd.
//!
//! Messages are single lines. A message is at most `MAX_MESSAGE` bytes, the
//! limit weft-appd applies to app messages, and cannot contain a line break,
//! which would split it into several messages. Received data is buffered
//! up to one message; a peer that sends a longer line, or closes the
//! connection, ends it for good.
//!
//! The connection is the session: once it has ended, by weft-appd closing
//! it or stopping, the runtime exits, whatever the component is doing, and
//! a runtime that cannot connect does not start, so no runtime outlives the
//! weft-appd that started it.
use std::io::{Read, Write};
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
/// The longest message in either direction, in bytes.
pub const MAX_MESSAGE: usize = 64 * 1024;
/// How long one write of a message may block before the connection is
/// given up.
const SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Checks a message the component wants to send.
pub fn check_payload(payload: &str) -> Result<(), String> {
if payload.len() > MAX_MESSAGE {
return Err(format!("message exceeds {MAX_MESSAGE} bytes"));
}
if payload.contains(['\n', '\r']) {
return Err("message contains a line break".to_owned());
}
Ok(())
}
pub struct IpcState {
socket: UnixStream,
recv_buf: Vec<u8>,
/// Why the connection ended, once it has.
closed: Option<&'static str>,
}
impl IpcState {
pub fn connect(path: &str) -> Option<Self> {
let socket = UnixStream::connect(path).ok()?;
Self::new(socket)
}
/// Exits the process once the connection has ended.
pub fn exit_on_hangup(&self) -> std::io::Result<()> {
let socket = self.socket.try_clone()?;
std::thread::Builder::new()
.name("ipc-hangup".into())
.spawn(move || {
wait_for_hangup(&socket);
tracing::info!("the session's IPC connection ended; exiting");
std::process::exit(0);
})?;
Ok(())
}
fn new(socket: UnixStream) -> Option<Self> {
socket.set_nonblocking(true).ok()?;
Some(Self {
socket,
recv_buf: Vec::new(),
closed: None,
})
}
pub fn send(&mut self, payload: &str) -> Result<(), String> {
check_payload(payload)?;
if let Some(reason) = self.closed {
return Err(format!("IPC connection {reason}"));
}
let mut line = payload.to_owned();
line.push('\n');
let result = self
.socket
.set_nonblocking(false)
.and_then(|()| self.socket.set_write_timeout(Some(SEND_TIMEOUT)))
.and_then(|()| self.socket.write_all(line.as_bytes()));
let restored = self.socket.set_nonblocking(true);
match result.and(restored) {
Ok(()) => Ok(()),
// Part of the line may have been written; anything sent after it
// would join it, so the connection ends.
Err(e) => {
self.close("failed");
Err(e.to_string())
}
}
}
/// The next complete message, if one has arrived.
pub fn recv(&mut self) -> Option<String> {
if let Some(message) = self.take_line() {
return Some(message);
}
if self.closed.is_some() {
return None;
}
let mut chunk = [0u8; 4096];
loop {
match self.socket.read(&mut chunk) {
Ok(0) => {
self.close("closed by weft-appd");
break;
}
Ok(n) => {
self.recv_buf.extend_from_slice(&chunk[..n]);
if self.recv_buf.contains(&b'\n') {
break;
}
if self.recv_buf.len() > MAX_MESSAGE + 2 {
self.overlong();
break;
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => {
self.close("failed");
break;
}
}
}
self.take_line()
}
/// Ends the connection for both sides: weft-appd sees it close and
/// ends the session, as it does when the component closes it.
fn close(&mut self, reason: &'static str) {
tracing::warn!(reason, "IPC connection ended");
self.closed = Some(reason);
let _ = self.socket.shutdown(std::net::Shutdown::Both);
}
fn overlong(&mut self) {
self.close("ended by a message over the size limit");
self.recv_buf.clear();
}
/// Removes the first complete line from the buffer. A line that is not
/// UTF-8 is dropped; one longer than a message ends the connection.
fn take_line(&mut self) -> Option<String> {
loop {
let pos = self.recv_buf.iter().position(|&b| b == b'\n')?;
let raw: Vec<u8> = self.recv_buf.drain(..=pos).collect();
let text = raw.strip_suffix(b"\n").unwrap_or(&raw);
let text = text.strip_suffix(b"\r").unwrap_or(text);
if text.len() > MAX_MESSAGE {
self.overlong();
return None;
}
match String::from_utf8(text.to_vec()) {
Ok(message) => return Some(message),
Err(_) => tracing::warn!("IPC message that is not UTF-8 dropped"),
}
}
}
}
/// The peer shutting down its side; elsewhere only a full hangup is seen.
#[cfg(any(target_os = "linux", target_os = "android"))]
const PEER_SHUTDOWN: libc::c_short = libc::POLLRDHUP;
#[cfg(not(any(target_os = "linux", target_os = "android")))]
const PEER_SHUTDOWN: libc::c_short = 0;
/// Blocks until the peer has closed `socket` or it was shut down. Data
/// waiting to be read neither wakes it nor is consumed.
fn wait_for_hangup(socket: &UnixStream) {
let mut pfd = libc::pollfd {
fd: socket.as_raw_fd(),
events: PEER_SHUTDOWN,
revents: 0,
};
loop {
let ready = unsafe { libc::poll(&mut pfd, 1, -1) };
if ready < 0 {
if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
return;
}
if pfd.revents & (PEER_SHUTDOWN | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0 {
return;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_hangup_is_seen_and_pending_data_is_not() {
let (ours, mut theirs) = UnixStream::pair().unwrap();
let (done_tx, done_rx) = std::sync::mpsc::channel();
let watched = ours.try_clone().unwrap();
std::thread::spawn(move || {
wait_for_hangup(&watched);
let _ = done_tx.send(());
});
theirs.write_all(b"message\n").unwrap();
assert!(
done_rx
.recv_timeout(std::time::Duration::from_millis(300))
.is_err()
);
drop(theirs);
done_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("the hangup was not seen");
// The message is still there to read.
let mut ipc = IpcState::new(ours).unwrap();
assert_eq!(ipc.recv().as_deref(), Some("message"));
}
fn pair() -> (IpcState, UnixStream) {
let (ours, theirs) = UnixStream::pair().unwrap();
(IpcState::new(ours).unwrap(), theirs)
}
#[test]
fn payloads_that_would_break_framing_are_refused() {
assert!(check_payload("ok").is_ok());
assert!(check_payload("two\nmessages").is_err());
assert!(check_payload("carriage\rreturn").is_err());
assert!(check_payload(&"x".repeat(MAX_MESSAGE)).is_ok());
assert!(check_payload(&"x".repeat(MAX_MESSAGE + 1)).is_err());
let (mut ipc, _peer) = pair();
assert!(ipc.send("a\nb").is_err());
}
#[test]
fn messages_arrive_one_at_a_time() {
let (mut ipc, mut peer) = pair();
assert_eq!(ipc.recv(), None);
peer.write_all(b"first\nsecond\r\npart").unwrap();
assert_eq!(ipc.recv().as_deref(), Some("first"));
assert_eq!(ipc.recv().as_deref(), Some("second"));
assert_eq!(ipc.recv(), None);
peer.write_all(b"ial\n").unwrap();
assert_eq!(ipc.recv().as_deref(), Some("partial"));
}
#[test]
fn an_overlong_line_ends_the_connection_without_unbounded_buffering() {
let (mut ipc, mut peer) = pair();
peer.write_all(&vec![b'x'; MAX_MESSAGE + 4097]).unwrap();
while ipc.closed.is_none() {
assert_eq!(ipc.recv(), None);
}
assert!(ipc.recv_buf.len() <= MAX_MESSAGE + 4096);
assert!(ipc.send("after").is_err());
// The peer sees the connection end.
let mut rest = Vec::new();
assert_eq!(peer.read_to_end(&mut rest).unwrap(), 0);
}
#[test]
fn a_message_at_the_limit_arrives_and_one_over_it_ends_the_connection() {
let (mut ipc, mut peer) = pair();
let mut at_limit = vec![b'x'; MAX_MESSAGE];
at_limit.push(b'\n');
peer.write_all(&at_limit).unwrap();
let mut received = None;
while received.is_none() {
received = ipc.recv();
}
assert_eq!(received.map(|m| m.len()), Some(MAX_MESSAGE));
// One byte over, with its newline in the same read.
let mut over = vec![b'x'; MAX_MESSAGE + 1];
over.extend_from_slice(b"\nnext\n");
peer.write_all(&over).unwrap();
while ipc.closed.is_none() {
assert_eq!(ipc.recv(), None);
}
assert_eq!(ipc.recv(), None);
}
#[test]
fn a_line_that_is_not_utf8_is_dropped() {
let (mut ipc, mut peer) = pair();
peer.write_all(b"\xff\xfe\nafter\n").unwrap();
assert_eq!(ipc.recv().as_deref(), Some("after"));
}
#[test]
fn a_closed_connection_is_reported_to_senders() {
let (mut ipc, peer) = pair();
drop(peer);
assert_eq!(ipc.recv(), None);
let error = ipc.send("hello").unwrap_err();
assert!(error.contains("closed"), "{error}");
}
}

View file

@ -0,0 +1,127 @@
//! The memory and table limits of a component's store.
//!
//! The limit on linear memory covers all of a component's memories
//! together: a component made of several core modules cannot multiply it
//! by declaring more memories. A memory or table that would grow past its
//! limit does not grow, and the component sees an allocation failure.
/// The most table elements across all of a component's tables.
const MAX_TABLE_ELEMENTS: usize = 1_000_000;
/// The most core instances, memories and tables in one store.
const MAX_INSTANCES: usize = 1_000;
const MAX_MEMORIES: usize = 100;
const MAX_TABLES: usize = 1_000;
pub struct Limits {
max_memory: usize,
memory: usize,
table_elements: usize,
}
impl Limits {
/// Limits a store's linear memory to `max_memory` bytes in total.
pub fn new(max_memory: usize) -> Self {
Self {
max_memory,
memory: 0,
table_elements: 0,
}
}
}
/// Accounts a growth from `current` to `desired` against `used` of `max`.
/// A growth past the memory's or table's own `maximum` fails anyway, so it
/// is refused without being counted.
fn grow(
used: &mut usize,
max: usize,
current: usize,
desired: usize,
maximum: Option<usize>,
) -> bool {
if maximum.is_some_and(|m| desired > m) {
return false;
}
let added = desired.saturating_sub(current);
match used.checked_add(added) {
Some(total) if total <= max => {
*used = total;
true
}
_ => false,
}
}
impl wasmtime::ResourceLimiter for Limits {
fn memory_growing(
&mut self,
current: usize,
desired: usize,
maximum: Option<usize>,
) -> anyhow::Result<bool> {
Ok(grow(
&mut self.memory,
self.max_memory,
current,
desired,
maximum,
))
}
fn table_growing(
&mut self,
current: usize,
desired: usize,
maximum: Option<usize>,
) -> anyhow::Result<bool> {
Ok(grow(
&mut self.table_elements,
MAX_TABLE_ELEMENTS,
current,
desired,
maximum,
))
}
fn instances(&self) -> usize {
MAX_INSTANCES
}
fn memories(&self) -> usize {
MAX_MEMORIES
}
fn tables(&self) -> usize {
MAX_TABLES
}
}
#[cfg(test)]
mod tests {
use super::*;
use wasmtime::ResourceLimiter;
#[test]
fn the_limit_covers_all_memories_together() {
let mut limits = Limits::new(100);
assert!(limits.memory_growing(0, 60, None).unwrap());
// A second memory gets only what the first left.
assert!(!limits.memory_growing(0, 60, None).unwrap());
assert!(limits.memory_growing(0, 40, None).unwrap());
// Growing the first one further no longer fits.
assert!(!limits.memory_growing(60, 61, None).unwrap());
assert_eq!(limits.memory, 100);
}
#[test]
fn a_refused_growth_is_not_counted() {
let mut limits = Limits::new(100);
assert!(!limits.memory_growing(0, 101, None).unwrap());
assert!(limits.memory_growing(0, 100, None).unwrap());
assert!(!limits.memory_growing(0, usize::MAX, None).unwrap());
// Past a memory's own maximum: refused and not counted.
let mut limits = Limits::new(100);
assert!(!limits.memory_growing(0, 50, Some(40)).unwrap());
assert!(limits.memory_growing(0, 100, None).unwrap());
}
}

View file

@ -2,8 +2,25 @@ use std::path::PathBuf;
use anyhow::Context;
#[cfg(feature = "wasmtime-runtime")]
mod desktop;
mod grants;
#[cfg(feature = "wasmtime-runtime")]
mod ipc;
#[cfg(feature = "wasmtime-runtime")]
mod limits;
/// The default limit on a component's linear memory, in MiB.
const DEFAULT_MAX_MEMORY_MIB: usize = 256;
use grants::{Grants, Preopen};
fn main() -> anyhow::Result<()> {
// Standard output carries the readiness line to weft-appd, which keeps
// standard error as the process's log.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
@ -13,8 +30,9 @@ fn main() -> anyhow::Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
anyhow::bail!(
"usage: weft-runtime <app_id> <session_id> \
[--preopen HOST::GUEST]... [--ipc-socket PATH]"
"usage: weft-runtime <app_id> <session_id> --module PATH \
[--preopen HOST::GUEST::ro|rw]... [--grant CAPABILITY]... [--ipc-socket PATH] \
[--max-memory-mib N]"
);
}
let app_id = &args[1];
@ -22,8 +40,11 @@ fn main() -> anyhow::Result<()> {
.parse()
.with_context(|| format!("invalid session_id: {}", args[2]))?;
let mut preopen: Vec<(String, String)> = Vec::new();
let mut preopen: Vec<Preopen> = Vec::new();
let mut grants = Grants::default();
let mut ipc_socket: Option<String> = None;
let mut module: Option<PathBuf> = None;
let mut max_memory_mib = DEFAULT_MAX_MEMORY_MIB;
let mut i = 3usize;
while i < args.len() {
@ -31,11 +52,28 @@ fn main() -> anyhow::Result<()> {
"--preopen" => {
i += 1;
let spec = args.get(i).context("--preopen requires an argument")?;
if let Some((host, guest)) = spec.split_once("::") {
preopen.push((host.to_string(), guest.to_string()));
} else {
preopen.push((spec.clone(), spec.clone()));
}
preopen.push(Preopen::parse(spec)?);
}
"--grant" => {
i += 1;
grants.add(args.get(i).context("--grant requires an argument")?)?;
}
"--module" => {
i += 1;
module = Some(PathBuf::from(
args.get(i).context("--module requires an argument")?,
));
}
"--max-memory-mib" => {
i += 1;
let value = args
.get(i)
.context("--max-memory-mib requires an argument")?;
max_memory_mib = value
.parse::<usize>()
.ok()
.filter(|&mib| mib > 0 && mib <= 1 << 20)
.with_context(|| format!("invalid --max-memory-mib: {value}"))?;
}
"--ipc-socket" => {
i += 1;
@ -55,47 +93,56 @@ fn main() -> anyhow::Result<()> {
tracing::info!(session_id, %app_id, "weft-runtime starting");
let pkg_dir = resolve_package(app_id)?;
tracing::info!(path = %pkg_dir.display(), "package resolved");
let wasm_path = pkg_dir.join("app.wasm");
if !wasm_path.exists() {
anyhow::bail!("app.wasm not found at {}", wasm_path.display());
}
// weft-appd resolves the package and passes the component it selected;
// the runtime never looks for the package itself.
let wasm_path = module.context("--module is required")?;
tracing::info!(session_id, %app_id, wasm = %wasm_path.display(), "executing module");
run_module(&wasm_path, &preopen, ipc_socket.as_deref())?;
run_module(
app_id,
&wasm_path,
&preopen,
grants,
ipc_socket.as_deref(),
max_memory_mib << 20,
)?;
tracing::info!(session_id, %app_id, "exiting");
Ok(())
}
fn resolve_package(app_id: &str) -> anyhow::Result<PathBuf> {
for store_root in package_store_roots() {
let pkg_dir = store_root.join(app_id);
let manifest = pkg_dir.join("wapp.toml");
if manifest.exists() {
return Ok(pkg_dir);
}
/// The readiness line for weft-appd: `READY <token>` with the session token
/// from `WEFT_READY_TOKEN`, or `READY` when run without appd.
#[cfg(feature = "wasmtime-runtime")]
fn ready_line() -> String {
match std::env::var("WEFT_READY_TOKEN") {
Ok(token) => format!("READY {token}"),
Err(_) => "READY".to_owned(),
}
anyhow::bail!("package '{}' not found in any package store", app_id)
}
#[cfg(not(feature = "wasmtime-runtime"))]
fn run_module(
_app_id: &str,
_wasm_path: &std::path::Path,
_preopen: &[(String, String)],
_preopen: &[Preopen],
_grants: Grants,
_ipc_socket: Option<&str>,
_max_memory: usize,
) -> anyhow::Result<()> {
println!("READY");
Ok(())
anyhow::bail!(
"weft-runtime was built without the wasmtime-runtime feature and cannot execute components"
)
}
#[cfg(feature = "wasmtime-runtime")]
fn run_module(
app_id: &str,
wasm_path: &std::path::Path,
preopen: &[(String, String)],
preopen: &[Preopen],
grants: Grants,
ipc_socket: Option<&str>,
max_memory: usize,
) -> anyhow::Result<()> {
use std::sync::{Arc, Mutex};
use wasmtime::{
@ -106,65 +153,12 @@ fn run_module(
DirPerms, FilePerms, IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView,
add_to_linker_sync, bindings::sync::Command,
};
struct IpcState {
socket: std::os::unix::net::UnixStream,
recv_buf: Vec<u8>,
}
impl IpcState {
fn connect(path: &str) -> Option<Self> {
let socket = std::os::unix::net::UnixStream::connect(path).ok()?;
socket.set_nonblocking(true).ok()?;
Some(Self {
socket,
recv_buf: Vec::new(),
})
}
fn send(&mut self, payload: &str) -> Result<(), String> {
use std::io::Write;
let _ = self.socket.set_nonblocking(false);
let mut line = payload.to_owned();
line.push('\n');
let result = self
.socket
.write_all(line.as_bytes())
.map_err(|e| e.to_string());
let _ = self.socket.set_nonblocking(true);
result
}
fn recv(&mut self) -> Option<String> {
use std::io::Read;
let mut chunk = [0u8; 4096];
loop {
match self.socket.read(&mut chunk) {
Ok(0) => break,
Ok(n) => self.recv_buf.extend_from_slice(&chunk[..n]),
Err(e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut =>
{
break;
}
Err(_) => break,
}
}
if let Some(pos) = self.recv_buf.iter().position(|&b| b == b'\n') {
let raw: Vec<u8> = self.recv_buf.drain(..=pos).collect();
return String::from_utf8(raw)
.ok()
.map(|s| s.trim_end_matches('\n').trim_end_matches('\r').to_owned());
}
None
}
}
use weft_ipc_types::capability::Access;
struct State {
ctx: WasiCtx,
table: ResourceTable,
ipc: Arc<Mutex<Option<IpcState>>>,
limits: limits::Limits,
}
impl IoView for State {
@ -186,9 +180,10 @@ fn run_module(
let component = Component::from_file(&engine, wasm_path)
.with_context(|| format!("load component {}", wasm_path.display()))?;
let grants = Arc::new(grants);
let mut linker: Linker<State> = Linker::new(&engine);
add_to_linker_sync(&mut linker).context("add WASI to linker")?;
let ipc_state: Arc<Mutex<Option<IpcState>>> = Arc::new(Mutex::new(None));
let ipc_state: Arc<Mutex<Option<ipc::IpcState>>> = Arc::new(Mutex::new(None));
{
let ipc_send = Arc::clone(&ipc_state);
@ -197,7 +192,7 @@ fn run_module(
.instance("weft:app/notify@0.1.0")
.context("define weft:app/notify instance")?
.func_wrap("ready", |_: wasmtime::StoreContextMut<'_, State>, ()| {
println!("READY");
println!("{}", ready_line());
Ok::<(), wasmtime::Error>(())
})
.context("define weft:app/notify#ready")?;
@ -212,6 +207,9 @@ fn run_module(
move |_: wasmtime::StoreContextMut<'_, State>,
(payload,): (String,)|
-> wasmtime::Result<(Result<(), String>,)> {
if let Err(e) = ipc::check_payload(&payload) {
return Ok((Err(e),));
}
let mut guard = ipc_send.lock().unwrap_or_else(|p| p.into_inner());
match guard.as_mut() {
Some(ipc) => Ok((ipc.send(&payload),)),
@ -234,34 +232,36 @@ fn run_module(
.context("define weft:app/ipc#recv")?;
}
// Every import below checks the session's grants on each call; an
// ungranted call returns an error to the component.
let fetch_grants = Arc::clone(&grants);
linker
.instance("weft:app/fetch@0.1.0")
.context("define weft:app/fetch instance")?
.func_wrap(
"fetch",
|_: wasmtime::StoreContextMut<'_, State>,
(url, method, headers, body): (
String,
String,
Vec<(String, String)>,
Option<Vec<u8>>,
)|
-> wasmtime::Result<(Result<(u16, String, Vec<u8>), String>,)> {
let result = host_fetch(&url, &method, &headers, body.as_deref());
move |_: wasmtime::StoreContextMut<'_, State>,
(url, method, headers, body): FetchRequest|
-> wasmtime::Result<(FetchResult,)> {
let result = host_fetch(&fetch_grants, &url, &method, &headers, body.as_deref());
Ok((result,))
},
)
.context("define weft:app/fetch#fetch")?;
let notify_grants = Arc::clone(&grants);
let notify_app = app_id.to_owned();
linker
.instance("weft:app/notifications@0.1.0")
.context("define weft:app/notifications instance")?
.func_wrap(
"notify",
|_: wasmtime::StoreContextMut<'_, State>,
(title, body, icon): (String, String, Option<String>)|
-> wasmtime::Result<(Result<(), String>,)> {
let result = host_notify(&title, &body, icon.as_deref());
move |_: wasmtime::StoreContextMut<'_, State>,
(title, body, icon): (String, String, Option<String>)|
-> wasmtime::Result<(Result<(), String>,)> {
let result = notify_grants
.notifications()
.and_then(|()| desktop::notify(&notify_app, &title, &body, icon.as_deref()));
Ok((result,))
},
)
@ -271,23 +271,29 @@ fn run_module(
let mut clipboard = linker
.instance("weft:app/clipboard@0.1.0")
.context("define weft:app/clipboard instance")?;
let read_grants = Arc::clone(&grants);
clipboard
.func_wrap(
"read",
|_: wasmtime::StoreContextMut<'_, State>,
()|
-> wasmtime::Result<(Result<String, String>,)> {
Ok((host_clipboard_read(),))
move |_: wasmtime::StoreContextMut<'_, State>,
()|
-> wasmtime::Result<(Result<String, String>,)> {
Ok((read_grants
.clipboard_read()
.and_then(|()| desktop::clipboard_read()),))
},
)
.context("define weft:app/clipboard#read")?;
let write_grants = Arc::clone(&grants);
clipboard
.func_wrap(
"write",
|_: wasmtime::StoreContextMut<'_, State>,
(text,): (String,)|
-> wasmtime::Result<(Result<(), String>,)> {
Ok((host_clipboard_write(&text),))
move |_: wasmtime::StoreContextMut<'_, State>,
(text,): (String,)|
-> wasmtime::Result<(Result<(), String>,)> {
Ok((write_grants
.clipboard_write()
.and_then(|()| desktop::clipboard_write(&text)),))
},
)
.context("define weft:app/clipboard#write")?;
@ -298,21 +304,24 @@ fn run_module(
if let Some(socket_path) = ipc_socket {
ctx_builder.env("WEFT_IPC_SOCKET", socket_path);
if let Some(ipc) = IpcState::connect(socket_path) {
if let Some(ipc) = ipc::IpcState::connect(socket_path) {
ipc.exit_on_hangup().context("watch the IPC connection")?;
*ipc_state.lock().unwrap_or_else(|p| p.into_inner()) = Some(ipc);
} else {
tracing::warn!("weft:app/ipc: could not connect to IPC socket {socket_path}");
// Without its connection the session cannot be reached or
// ended; the runtime would only be left behind.
anyhow::bail!("cannot connect to the IPC socket {socket_path}");
}
}
if let Ok(portal_socket) = std::env::var("WEFT_FILE_PORTAL_SOCKET") {
ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket);
}
for (host_path, guest_path) in preopen {
for dir in preopen {
let (dir_perms, file_perms) = match dir.access {
Access::Read => (DirPerms::READ, FilePerms::READ),
Access::ReadWrite => (DirPerms::all(), FilePerms::all()),
};
ctx_builder
.preopened_dir(host_path, guest_path, DirPerms::all(), FilePerms::all())
.with_context(|| format!("preopen dir {host_path}"))?;
.preopened_dir(&dir.host, &dir.guest, dir_perms, file_perms)
.with_context(|| format!("preopen dir {}", dir.host))?;
}
let ctx = ctx_builder.build();
@ -321,9 +330,10 @@ fn run_module(
State {
ctx,
table: ResourceTable::new(),
ipc: ipc_state,
limits: limits::Limits::new(max_memory),
},
);
store.limiter(|state| &mut state.limits);
let command =
Command::instantiate(&mut store, &component, &linker).context("instantiate component")?;
@ -335,90 +345,168 @@ fn run_module(
.map_err(|()| anyhow::anyhow!("wasm component run exited with error"))
}
/// Arguments of `weft:app/fetch#fetch`: URL, method, headers and body.
#[cfg(feature = "wasmtime-runtime")]
type FetchRequest = (String, String, Vec<(String, String)>, Option<Vec<u8>>);
/// `weft:app/fetch.response`.
#[cfg(feature = "wasmtime-runtime")]
#[derive(
wasmtime::component::ComponentType, wasmtime::component::Lift, wasmtime::component::Lower,
)]
#[component(record)]
struct FetchResponse {
status: u16,
#[component(name = "content-type")]
content_type: String,
body: Vec<u8>,
}
/// Result of `weft:app/fetch#fetch`.
#[cfg(feature = "wasmtime-runtime")]
type FetchResult = Result<FetchResponse, String>;
/// Request headers a component may not set.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
const FORBIDDEN_FETCH_HEADERS: &[&str] = &[
"host",
"content-length",
"transfer-encoding",
"connection",
"keep-alive",
"proxy-authorization",
"proxy-connection",
"te",
"trailer",
"upgrade",
];
/// Longest response body returned to a component.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
const MAX_FETCH_RESPONSE: u64 = 16 * 1024 * 1024;
/// Performs a granted HTTP request. Redirects are returned to the component
/// as responses rather than followed, so every destination it reaches is
/// checked against its grants. HTTP error statuses are responses too; only
/// policy and transport failures are errors.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
fn host_fetch(
grants: &Grants,
url: &str,
method: &str,
headers: &[(String, String)],
body: Option<&[u8]>,
) -> Result<(u16, String, Vec<u8>), String> {
) -> FetchResult {
use std::io::Read;
let mut req = ureq::request(method, url);
use std::time::Duration;
grants.fetch_any()?;
let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(format!("unsupported URL scheme '{}'", parsed.scheme()));
}
let host = parsed.host_str().ok_or("URL has no host")?;
let reach = grants.fetch_host(host)?;
// Credentials are never taken from a URL; a component that needs them
// sends them in a header to the host it is granted.
if !parsed.username().is_empty() || parsed.password().is_some() {
return Err(
"URLs with credentials are not supported; send an Authorization header".to_owned(),
);
}
// The method is written into the request line as given, so only known
// methods are accepted.
if !matches!(
method,
"GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"
) {
return Err(format!("unsupported HTTP method '{method}'"));
}
// The destination and message framing belong to the runtime: a component
// must not redirect a granted request to another host through `Host` or
// change how the body is delimited.
for (name, _) in headers {
if FORBIDDEN_FETCH_HEADERS
.iter()
.any(|forbidden| name.eq_ignore_ascii_case(forbidden))
{
return Err(format!("header '{name}' is set by the runtime"));
}
}
let agent = ureq::AgentBuilder::new()
.resolver(GrantedResolver(reach))
// A proxy would be connected to instead of the checked address.
.try_proxy_from_env(false)
.redirects(0)
.timeout_connect(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.build();
let mut req = agent.request_url(method, &parsed);
for (name, value) in headers {
req = req.set(name, value);
}
let response = match body {
Some(b) => req.send_bytes(b),
None => req.call(),
}
.map_err(|e| e.to_string())?;
};
let response = match response {
Ok(response) | Err(ureq::Error::Status(_, response)) => response,
Err(e) => return Err(e.to_string()),
};
let status = response.status();
let content_type = response.content_type().to_owned();
let mut body_bytes = Vec::new();
response
.into_reader()
.take(MAX_FETCH_RESPONSE + 1)
.read_to_end(&mut body_bytes)
.map_err(|e| e.to_string())?;
Ok((status, content_type, body_bytes))
if body_bytes.len() as u64 > MAX_FETCH_RESPONSE {
return Err(format!("response body exceeds {MAX_FETCH_RESPONSE} bytes"));
}
Ok(FetchResponse {
status,
content_type,
body: body_bytes,
})
}
/// Resolves a fetch destination and keeps only the addresses its grant
/// may reach; the connection is made to those addresses alone, so the
/// check cannot be bypassed by a second, different DNS answer.
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
struct GrantedResolver(grants::Reach);
#[cfg(all(feature = "wasmtime-runtime", feature = "net-fetch"))]
impl ureq::Resolver for GrantedResolver {
fn resolve(&self, netloc: &str) -> std::io::Result<Vec<std::net::SocketAddr>> {
use std::net::ToSocketAddrs;
let addresses: Vec<_> = netloc
.to_socket_addrs()?
.filter(|a| self.0 == grants::Reach::Declared || grants::is_public(a.ip()))
.collect();
if addresses.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!(
"{netloc} resolves only to addresses on this machine or a local network, \
which only a grant naming that address covers"
),
));
}
Ok(addresses)
}
}
#[cfg(all(feature = "wasmtime-runtime", not(feature = "net-fetch")))]
fn host_fetch(
grants: &Grants,
_url: &str,
_method: &str,
_headers: &[(String, String)],
_body: Option<&[u8]>,
) -> Result<(u16, String, Vec<u8>), String> {
Err("net-fetch capability not compiled in".to_owned())
}
#[cfg(feature = "wasmtime-runtime")]
fn host_clipboard_read() -> Result<String, String> {
let out = std::process::Command::new("wl-paste")
.arg("--no-newline")
.output()
.map_err(|e| e.to_string())?;
if out.status.success() {
String::from_utf8(out.stdout).map_err(|e| e.to_string())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_owned())
}
}
#[cfg(feature = "wasmtime-runtime")]
fn host_clipboard_write(text: &str) -> Result<(), String> {
use std::io::Write;
let mut child = std::process::Command::new("wl-copy")
.stdin(std::process::Stdio::piped())
.spawn()
.map_err(|e| e.to_string())?;
if let Some(stdin) = child.stdin.as_mut() {
stdin
.write_all(text.as_bytes())
.map_err(|e| e.to_string())?;
}
let status = child.wait().map_err(|e| e.to_string())?;
if status.success() {
Ok(())
} else {
Err(format!("wl-copy exited with {status}"))
}
}
#[cfg(feature = "wasmtime-runtime")]
fn host_notify(title: &str, body: &str, icon: Option<&str>) -> Result<(), String> {
let mut cmd = std::process::Command::new("notify-send");
if let Some(i) = icon {
cmd.arg("--icon").arg(i);
}
cmd.arg("--").arg(title).arg(body);
cmd.status().map_err(|e| e.to_string()).and_then(|s| {
if s.success() {
Ok(())
} else {
Err(format!("notify-send exited with {s}"))
}
})
) -> FetchResult {
grants.fetch_any()?;
Err("this runtime was built without network fetch support".to_owned())
}
#[cfg(feature = "seccomp")]
@ -480,100 +568,21 @@ fn apply_seccomp_filter() -> anyhow::Result<()> {
Ok(())
}
fn package_store_roots() -> Vec<PathBuf> {
if let Ok(explicit) = std::env::var("WEFT_APP_STORE") {
return vec![PathBuf::from(explicit)];
}
let mut roots = Vec::new();
if let Ok(home) = std::env::var("HOME") {
roots.push(
PathBuf::from(home)
.join(".local")
.join("share")
.join("weft")
.join("apps"),
);
}
roots.push(PathBuf::from("/usr/share/weft/apps"));
roots
}
#[cfg(test)]
#[cfg(all(test, not(feature = "wasmtime-runtime")))]
mod tests {
use super::*;
#[test]
fn package_store_roots_includes_system_path() {
let roots = package_store_roots();
assert!(
roots
.iter()
.any(|p| p == &PathBuf::from("/usr/share/weft/apps"))
);
}
#[test]
fn package_store_roots_uses_weft_app_store_when_set() {
// SAFETY: test binary is single-threaded at this point.
unsafe { std::env::set_var("WEFT_APP_STORE", "/custom/store") };
let roots = package_store_roots();
assert_eq!(roots, vec![PathBuf::from("/custom/store")]);
unsafe { std::env::remove_var("WEFT_APP_STORE") };
}
#[test]
fn resolve_package_finds_installed_package() {
use std::fs;
let store =
std::env::temp_dir().join(format!("weft_runtime_resolve_{}", std::process::id()));
let pkg_dir = store.join("com.example.resolve");
fs::create_dir_all(&pkg_dir).unwrap();
fs::write(
pkg_dir.join("wapp.toml"),
"[package]\nid=\"com.example.resolve\"\n",
fn engine_disabled_build_refuses_to_run_components() {
let err = run_module(
"org.weft.test",
std::path::Path::new("app.wasm"),
&[],
Grants::default(),
None,
DEFAULT_MAX_MEMORY_MIB << 20,
)
.unwrap();
let prior = std::env::var("WEFT_APP_STORE").ok();
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
let result = resolve_package("com.example.resolve");
unsafe {
match prior {
Some(v) => std::env::set_var("WEFT_APP_STORE", v),
None => std::env::remove_var("WEFT_APP_STORE"),
}
}
let _ = fs::remove_dir_all(&store);
assert!(result.is_ok());
assert!(result.unwrap().ends_with("com.example.resolve"));
}
#[test]
fn resolve_package_errors_on_unknown_id() {
let store =
std::env::temp_dir().join(format!("weft_runtime_resolve_empty_{}", std::process::id()));
let _ = std::fs::create_dir_all(&store);
let prior = std::env::var("WEFT_APP_STORE").ok();
unsafe { std::env::set_var("WEFT_APP_STORE", &store) };
let result = resolve_package("com.does.not.exist");
unsafe {
match prior {
Some(v) => std::env::set_var("WEFT_APP_STORE", v),
None => std::env::remove_var("WEFT_APP_STORE"),
}
}
let _ = std::fs::remove_dir_all(&store);
assert!(result.is_err());
.expect_err("a build without wasmtime-runtime must not report success");
assert!(err.to_string().contains("wasmtime-runtime"));
}
}

View file

@ -21,8 +21,8 @@ interface ipc {
recv: func() -> option<string>;
}
/// Host interface for outbound HTTP requests. Requires the net:fetch
/// capability to be declared in wapp.toml.
/// Host interface for outbound HTTP requests. Requires a net:fetch:<host>
/// or net:fetch:* capability in wapp.toml covering the request's host.
interface fetch {
record response {
status: u16,

View file

@ -27,7 +27,7 @@ tungstenite = "0.24"
[dependencies.servo]
git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft"
rev = "e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
optional = true
default-features = false

View file

@ -2,13 +2,29 @@
## Current pin
| Field | Value |
|---------|------------------------------------------------------------------------------------|
| Source | <https://github.com/marcoallegretti/servo> (fork of servo/servo) |
| Branch | `servo-weft` |
| Rev | `04ca254f843ed650d3e5b14e5693ad51a60cc84b` (servo-weft tip, 2026-03-11) |
| Crate | `servo` (package name as of 2026-03-11; previously `libservo`) |
| Feature | `servo-embed` (optional; off by default) |
The selected revisions are the ones recorded in the workspace `Cargo.lock`.
| Dependency | Source | Revision | Selected by |
|------------|--------|----------|-------------|
| Servo (`servo` crate) | <https://github.com/marcoallegretti/servo> | `e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163` | `rev` in both shell crates' `Cargo.toml` |
| Stylo (`stylo`, `selectors`, `servo_arc`, ...) | <https://github.com/marcoallegretti/stylo> | `f1ba4969536d63f2e319a561e466c03e78b4a076` | `[patch."https://github.com/servo/stylo"]` in the root `Cargo.toml` |
The Servo revision is `servo-weft` commit `8e7dc40` (backdrop-filter rendering),
plus `f0bb1aa`, which fixes that commit's `servo-layout` build errors, plus
`b87e5a6` and `e5d9a51`, which keep compiled classic scripts traced until
they run, and `5d90f51`, which withholds `navigator.servo` from
`about:blank` and `about:srcdoc` documents. It lives
on the fork branch `fix/root-pending-classic-scripts`, which is based on
`fix/backdrop-filter-build-errors`, until both are merged into `servo-weft`;
keep those branches until then so the revisions stay fetchable.
Servo's own `[patch]` table for Stylo does not apply to WEFT, because Cargo
only honours patches in the root workspace. Without the root override, WEFT
resolves upstream Stylo `dca3934`, where `backdrop-filter` is still gated
behind `layout.unimplemented`. Remove the override once the selected Servo
revision depends on a Stylo that parses the property for Servo.
The feature is `servo-embed` (optional; off by default).
## Cargo dependencies
@ -25,7 +41,7 @@ servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer"]
[dependencies.servo]
git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft"
rev = "e5d9a518ebddb5ebd6af404d1fd4e00ea0f77163"
optional = true
default-features = false
@ -63,84 +79,112 @@ Install with: `sudo zypper install -y libglvnd-devel libopenssl-devel dbus-1-dev
## Rendering approach
Default: `SoftwareRenderingContext` (CPU rasterisation) blitted to a
`softbuffer`-backed winit window.
Each frame is painted with `WebView::paint` and then presented:
EGL path: set `WEFT_EGL_RENDERING=1` at runtime. The embedder attempts
`WindowRenderingContext::new` using the winit display and window handles.
If construction fails it falls back to software automatically.
When the EGL path is active Servo presents directly to the EGL surface via
surfman's `eglSwapBuffers`; the softbuffer blit is skipped. Mesa handles
DMA-BUF buffer sharing with the compositor transparently.
- **Software (default):** Servo renders into a `SoftwareRenderingContext`.
The host reads the painted frame back with `read_to_image`, presents the
context and copies the pixels into a persistent `softbuffer` surface on the
winit window.
- **EGL:** with `WEFT_EGL_RENDERING=1` the host creates a
`WindowRenderingContext` from winit's display and window handles and
presents it directly. If that fails it falls back to software.
Neither host presents anything before Servo's first repaint request; the
first frames can still be blank or unstyled while the document loads. Both
enable Servo's `layout_grid_enabled` preference, because the system UI and
application pages use CSS Grid, which Servo disables by default.
`weft-app-shell` prints `READY` after it presents a frame once the document
has loaded and Servo reports its rendering settled: on load completion it
requests `WebView::take_screenshot`, whose callback runs only after `load` has
fired in every frame, render-blocking resources, images and web fonts are done
and the rendering is up to date. `weft-appd` does not read this signal yet; it
treats the runtime's `READY` as session readiness. Neither host prints `READY`
when built without `servo-embed`; both exit with an error instead.
`tests/frame/check_frame.py` checks this on a real display path: it runs
`weft-compositor` nested on Xvfb and checks the pixels each host presents for
`tests/frame/reference.html`. For the app host it requires the page on screen
within two seconds of `READY`; `--slow-style` delays a render-blocking
stylesheet that reveals the page, which makes premature readiness visible. A
build that printed `READY` on its first presented frame failed every
`--slow-style 4` run; that build was a local experiment, not part of history.
## Known limitations at this pin
- **Wayland input events**: ~~not forwarded to Servo~~ **Resolved** — keyboard and
mouse events forwarded via `webview.notify_input_event`; key mapping in `keyutils.rs`.
- **Wayland surface sharing**: ~~`ZweftShellWindowV1` created with `surface = null`~~ **Resolved** —
`ShellClient::connect_with_display(display_ptr, surface_ptr)` uses
`Backend::from_foreign_display` to share winit's `wl_display` connection; the winit
`wl_surface` pointer is passed directly to `create_window`, associating the compositor
shell slot with the actual rendered surface. `ShellClient` is now constructed inside
`resumed()` after the winit window exists, not before the event loop. EGL path and
per-frame event dispatch are unchanged.
Protocol note: `wayland-scanner 0.31` generates `_type` (not `r#type`) for the
`navigation_gesture` event arg named `type`.
- **WebGPU on Mesa**: adapter may fail CTS — validation task, requires Mesa GPU hardware.
- **CSS layout features**: ~~CSS Grid~~ **Grid resolved** (Taffy-backed, fully wired).
~~CSS `backdrop-filter` unimplemented~~ **`backdrop-filter` resolved** (servo/servo issue
[#41567](https://github.com/servo/servo/issues/41567)). Implemented across two commits:
- `marcoallegretti/stylo` `servo-weft` `f1ba496`: removed `servo_pref = "layout.unimplemented"`
from `backdrop-filter` in `style/properties/longhands.toml` (enables parsing).
- `marcoallegretti/servo` `servo-weft` `8e7dc40`: `Cargo.toml` patched to use the stylo fork;
`style_ext.rs` adds `backdrop-filter` to `establishes_stacking_context` and
`establishes_containing_block_for_all_descendants`; `stacking_context.rs` guards the
WebRender stacking-context early-return on `backdrop_filter.0.is_empty()`; `display_list/mod.rs`
adds `BuilderForBoxFragment::build_backdrop_filter` calling `push_backdrop_filter` before
background paint.
- **Per-app process isolation**: ~~not implemented~~ **Resolved** — each app runs in a separate
`weft-app-shell` and `weft-runtime` OS process pair supervised by `weft-appd`. OS-level
isolation does not require Servo's multi-process constellation architecture.
- **SpiderMonkey sandbox**: SpiderMonkey is not sandbox-isolated beyond process-level isolation.
JIT-compiled JS runs with the same memory permissions as the Servo process. WEFT relies on
SpiderMonkey's own security properties for the JavaScript execution boundary. See
`docs/security.md` for the full bounded statement. Not addressed.
Status is stated against executed evidence; code that exists but has not been
exercised is listed as unverified.
- **Verified rendering path:** both hosts present the reference page through
`weft-compositor`'s winit backend on Xvfb with Mesa 25.2.8 llvmpipe, using
the software path (Ubuntu 24.04, x86_64; `check_frame.py --host system`,
`--host app` and `--host app --slow-style 3`, five runs each). The EGL path,
DRM sessions, resize, output scale and idle wakeup are unverified.
- **Input:** `tests/frame/check_input.py` verifies, on the same nested
setup, that left clicks 6 px either side of a boundary reach the element
under the pointer, and that `a` and `Shift+a` key presses reach the page with
the right key value and modifier, using real X input that `weft-compositor`
routes to `weft-servo-shell` (three runs). The harness gives the compositor's
X window input focus, as a window manager would; the client's keyboard focus
comes from the compositor's click-to-focus. Unverified: key release and
repeat, pointer motion, enter/leave and button release events, other buttons,
wheel, focus loss, non-US layouts, non-ASCII text, scale changes and
`weft-app-shell` input.
- **`backdrop-filter`**: the parsing (Stylo `f1ba496`) and rendering (Servo
`8e7dc40`, `f0bb1aa`) patches are selected by the lockfile; rendering is
unverified.
- **Resources:** the hosts install no Servo resource reader, so Servo logs
`Resource reader not set` and uses empty resources: the public suffix list,
HSTS preload list, Bluetooth blocklist, certificate and network error pages,
crash and directory-listing pages and media controls. Servo falls back to its
built-in placeholder image.
- **Window decorations:** `weft-compositor` offers no server-side decorations,
so winit draws a client-side title bar on both hosts' windows, including the
system panel.
- **Shell surface association**: the shells pass winit's `wl_display` and
`wl_surface` to `zweft_shell_manager_v1.create_window` through a shared
connection; unverified.
- **WebGPU on Mesa**: not evaluated.
- **Process separation**: each app runs as separate `weft-app-shell` and
`weft-runtime` processes supervised by `weft-appd`. Separate processes alone
do not confine the renderer; see `docs/security.md`.
- **SpiderMonkey**: JIT-compiled JavaScript runs with the Servo process's
permissions; WEFT relies on SpiderMonkey's own security properties for the
JavaScript boundary. See `docs/security.md`.
## Update policy
The `servo-weft` branch is the working branch for WEFT-specific Servo patches.
Upstream servo/servo changes are merged into it periodically.
`servo-weft` in `marcoallegretti/servo` and `servo-weft` in
`marcoallegretti/stylo` carry WEFT-specific patches. WEFT pins exact revisions
rather than tracking a branch, so a rebuild selects the same code. A pinned
revision must stay reachable from a published branch: never force-push,
rebase or delete a branch that contains a revision a WEFT lockfile selects.
Today Servo `e5d9a51` is reachable only from `fix/root-pending-classic-scripts`
and Stylo `f1ba496` only from Stylo's `servo-weft`.
To rebase onto a new upstream commit:
To move to new revisions:
1. In the `marcoallegretti/servo` repo: `git fetch upstream && git rebase upstream/main` on `servo-weft`.
2. Force-push `servo-weft`.
3. Update `Rev` in this file to the new tip SHA.
4. Run `cargo update -p servo` in the WEFT OS workspace.
5. Confirm the compositor and shell tests still pass.
1. Land the Servo or Stylo change on the fork and note its commit.
2. Update the `rev` values in `crates/weft-servo-shell/Cargo.toml`,
`crates/weft-app-shell/Cargo.toml` and, for Stylo, the root `[patch]`.
3. Run `cargo update -p servo` (and `cargo update -p stylo` for a Stylo-only change).
4. Confirm with `grep -A2 'name = "servo"' Cargo.lock` and
`grep -A2 'name = "stylo"' Cargo.lock` that the lockfile selects them, that
`cargo metadata --locked` succeeds, and that `grep -c servo/stylo Cargo.lock`
prints `0`, which shows the override applies to every Stylo crate.
5. Recompute the `outputHashes` in `infra/nixos/weft-packages.nix` for each
changed git source.
6. Run `cargo check -p weft-servo-shell --features servo-embed --locked` and
`cargo check -p weft-app-shell --features servo-embed --locked`, plus the
rendering checks for any behavior the change claims, and update the tables
in this file.
To submit patches upstream: open a PR from `servo-weft` (or a topic branch) to `servo/servo`.
Each fork patch keeps its purpose, upstream status and removal condition here.
## Stylo fork
The Stylo CSS engine is a separate repo (`servo/stylo`) pinned at rev `dca3934667dae76c49bb579b268c5eb142d09c6a`
in `Cargo.toml`. To patch it for WEFT-specific changes (e.g. enabling `backdrop-filter`):
1. Fork `servo/stylo` to `marcoallegretti/stylo`, create branch `servo-weft`.
2. Make changes on that branch.
3. Add to this fork's `Cargo.toml` workspace `[patch]` section:
```toml
[patch."https://github.com/servo/stylo"]
stylo = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_atoms = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_dom = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_malloc_size_of = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_static_prefs = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_traits = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
selectors = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
servo_arc = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
```
1. Run `cargo update` to resolve the new stylo deps.
2. Commit both the `Cargo.toml` and `Cargo.lock` changes to `servo-weft`.
| Patch | Fork commit | Purpose | Upstream status | Remove when |
|-------|-------------|---------|-----------------|-------------|
| Stylo: parse `backdrop-filter` for Servo | stylo `f1ba496` | Remove the `layout.unimplemented` gate | Not submitted | Upstream Stylo parses it for Servo |
| Servo: render `backdrop-filter` | servo `8e7dc40` | Stacking context and display list support | servo/servo issue [#41567](https://github.com/servo/servo/issues/41567) | Equivalent upstream support |
| Servo: fix `build_backdrop_filter` types | servo `f0bb1aa` | Make `servo-layout` compile | Part of the patch above | Same as above |
| Servo: trace compiled classic scripts | servo `b87e5a6`, `e5d9a51` | A parser-blocking script waiting for a stylesheet was freed by a garbage collection and crashed the content process when it ran | Not submitted | Upstream traces `ClassicScript::record` |
| Servo: no `navigator.servo` for blank and srcdoc documents | servo `5d90f51` | An application's `about:srcdoc` frame could change engine preferences | Not submitted | Upstream limits `ServoInternals` exposure the same way |

View file

@ -1,20 +1,22 @@
#![cfg(feature = "servo-embed")]
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate,
DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent,
MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
NavigationRequest, RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl,
UserContentManager, UserScript, WebViewBuilder, WebViewDelegate,
};
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland},
raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId},
};
@ -54,31 +56,149 @@ impl ServoDelegate for WeftServoDelegate {
// ── WebView delegate ──────────────────────────────────────────────────────────
/// Frame and load progress reported by Servo, shared with the event loop.
#[derive(Default)]
struct FrameSignals {
/// A new frame is waiting to be painted.
redraw: AtomicBool,
/// Servo has requested at least one repaint.
content: AtomicBool,
}
struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
/// The system UI document; the only one the webview may show.
document: String,
}
impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested
.store(true, std::sync::atomic::Ordering::Relaxed);
self.signals.content.store(true, Ordering::Relaxed);
self.signals.redraw.store(true, Ordering::Relaxed);
}
/// The system UI holds appd's system credential, so its webview never
/// leaves the system UI document.
fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) {
if same_document(request.url.as_str(), &self.document) {
request.allow();
} else {
tracing::warn!(url = %request.url, "navigation away from the system UI denied");
request.deny();
}
}
}
// ── Rendering context abstraction (GAP-2) ───────────────────────────────────
/// Whether two URLs name the same document, ignoring any fragment.
fn same_document(a: &str, b: &str) -> bool {
fn document(url: &str) -> &str {
url.split_once('#').map_or(url, |(document, _)| document)
}
document(a) == document(b)
}
/// `value` as a single-quoted JavaScript string literal.
fn js_string(value: &str) -> String {
let mut literal = String::with_capacity(value.len() + 2);
literal.push('\'');
for c in value.chars() {
match c {
' '..='~' if c != '\'' && c != '\\' => literal.push(c),
_ => literal.push_str(&format!("\\u{{{:x}}}", u32::from(c))),
}
}
literal.push('\'');
literal
}
/// Servo preferences shared by the WEFT hosts.
fn host_preferences() -> servo::Preferences {
servo::Preferences {
// The system UI and application pages lay out with CSS Grid, which
// Servo disables by default.
layout_grid_enabled: true,
..Default::default()
}
}
// ── Rendering ───────────────────────────────────────────────────────────────
type BlitSurface = softbuffer::Surface<Arc<Window>, Arc<Window>>;
enum RenderingCtx {
Software(Rc<servo::SoftwareRenderingContext>),
/// Servo renders offscreen; each frame is read back and copied to the window.
Software {
context: Rc<servo::SoftwareRenderingContext>,
surface: BlitSurface,
},
/// Servo renders directly to the window's EGL surface.
Egl(Rc<servo::WindowRenderingContext>),
}
impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> {
fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(context) => Rc::clone(context) as Rc<dyn RenderingContext>,
}
}
/// Paints the webview into this context and presents the frame on the window.
fn paint_and_present(&mut self, webview: &servo::WebView) -> Result<(), String> {
match self {
Self::Software { context, surface } => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
let size = context.size();
let rect = DeviceIntRect::from_size(DeviceIntSize::new(
size.width as i32,
size.height as i32,
));
let image = context.read_to_image(rect);
context.present();
let image = image.ok_or("frame readback failed")?;
blit(surface, &image)
}
Self::Egl(context) => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
context.present();
Ok(())
}
}
}
}
/// Copies an RGBA frame into the window's software surface and presents it.
fn blit(surface: &mut BlitSurface, image: &RgbaImage) -> Result<(), String> {
let (width, height) = image.dimensions();
let (Some(w), Some(h)) = (NonZeroU32::new(width), NonZeroU32::new(height)) else {
return Ok(());
};
surface.resize(w, h).map_err(|e| format!("resize: {e}"))?;
let mut buffer = surface.buffer_mut().map_err(|e| format!("buffer: {e}"))?;
for (dst, src) in buffer.iter_mut().zip(image.as_raw().chunks_exact(4)) {
*dst = u32::from(src[0]) << 16 | u32::from(src[1]) << 8 | u32::from(src[2]);
}
buffer.present().map_err(|e| format!("present: {e}"))
}
/// Returns winit's `wl_display` and `wl_surface` pointers when running on Wayland.
fn wayland_handles(
event_loop: &ActiveEventLoop,
window: &Window,
) -> Option<(*mut std::ffi::c_void, *mut std::ffi::c_void)> {
let RawDisplayHandle::Wayland(display) = event_loop.display_handle().ok()?.as_raw() else {
return None;
};
let RawWindowHandle::Wayland(surface) = window.window_handle().ok()?.as_raw() else {
return None;
};
Some((display.display.as_ptr(), surface.surface.as_ptr()))
}
// ── Application state ─────────────────────────────────────────────────────────
@ -90,13 +210,56 @@ struct App {
servo: Option<servo::Servo>,
webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker,
shutting_down: bool,
modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>,
cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>,
gesture_thread: Option<std::thread::JoinHandle<()>>,
/// weft-appd's WebSocket port and system token, once both are available.
endpoint: Option<AppdEndpoint>,
next_endpoint_check: std::time::Instant,
}
/// How the system UI reaches weft-appd.
#[derive(Clone, PartialEq)]
struct AppdEndpoint {
port: u16,
token: String,
}
/// How often the shell rereads weft-appd's port and token files, which change
/// when weft-appd restarts.
const ENDPOINT_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);
/// Reads weft-appd's port (`WEFT_APPD_WS_PORT`, then `appd.wsport`, then
/// `default_port`) and its system token from `appd.systoken`. Only a token of
/// 32 lowercase hex characters is accepted, so it can be placed in a script.
fn appd_endpoint(default_port: u16) -> Option<AppdEndpoint> {
let dir = PathBuf::from(std::env::var("XDG_RUNTIME_DIR").ok()?).join("weft");
let token = std::fs::read_to_string(dir.join("appd.systoken")).ok()?;
let token = token.trim();
if token.len() != 32
|| !token
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return None;
}
let port = std::env::var("WEFT_APPD_WS_PORT")
.ok()
.and_then(|p| p.trim().parse().ok())
.or_else(|| {
std::fs::read_to_string(dir.join("appd.wsport"))
.ok()
.and_then(|p| p.trim().parse().ok())
})
.unwrap_or(default_port);
Some(AppdEndpoint {
port,
token: token.to_owned(),
})
}
impl App {
@ -108,51 +271,106 @@ impl App {
servo: None,
webview: None,
rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
signals: Arc::default(),
waker,
shutting_down: false,
modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(),
cursor_pos: DevicePoint::origin(),
shell_client: None,
gesture_thread: None,
endpoint: None,
next_endpoint_check: std::time::Instant::now(),
}
}
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) {
match ctx {
RenderingCtx::Software(rc) => Self::blit_software(window, rc),
RenderingCtx::Egl(_) => {}
/// Rereads the appd endpoint and hands it to the system UI. The page's
/// `weftAppdEndpoint` reconnects only when the endpoint changed, so
/// repeating the call also covers page reloads.
fn deliver_endpoint(&mut self, event_loop: &ActiveEventLoop) {
let now = std::time::Instant::now();
if now < self.next_endpoint_check {
return;
}
}
fn blit_software(window: &Arc<Window>, rendering_context: &servo::SoftwareRenderingContext) {
let size = window.inner_size();
let Some(pixels) = rendering_context.read_pixels() else {
self.next_endpoint_check = now + ENDPOINT_CHECK_INTERVAL;
event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(
self.next_endpoint_check,
));
self.endpoint = appd_endpoint(self.ws_port);
let Some(endpoint) = &self.endpoint else {
return;
};
let Ok(ctx) = softbuffer::Context::new(Arc::clone(window)) else {
tracing::warn!("softbuffer context creation failed; skipping frame");
return;
};
let Ok(mut surface) = softbuffer::Surface::new(&ctx, Arc::clone(window)) else {
tracing::warn!("softbuffer surface creation failed; skipping frame");
return;
};
let _ = surface.resize(
std::num::NonZeroU32::new(size.width).unwrap_or(std::num::NonZeroU32::MIN),
std::num::NonZeroU32::new(size.height).unwrap_or(std::num::NonZeroU32::MIN),
// The credential goes only to the system UI document.
let call = format!(
"window.weftAppdEndpoint({}, '{}')",
endpoint.port, endpoint.token
);
let Ok(mut buf) = surface.buffer_mut() else {
self.call_system_ui("weftAppdEndpoint", &call);
}
/// Runs `call` in the system UI document if it defines the function
/// `name`. Navigation away from the document is denied; the script
/// checks the document again because a load can still be under way when
/// it runs.
fn call_system_ui(&self, name: &str, call: &str) {
let Some(webview) = &self.webview else {
return;
};
for (dst, src) in buf.iter_mut().zip(pixels.chunks(4)) {
*dst = u32::from_be_bytes([0, src[0], src[1], src[2]]);
if !webview
.url()
.is_some_and(|url| same_document(url.as_str(), self.url.as_str()))
{
return;
}
let _ = buf.present();
let document = js_string(self.url.as_str().split('#').next().unwrap_or_default());
webview.evaluate_javascript(
format!(
"window === window.top && \
location.href.split('#')[0] === {document} && \
typeof window.{name} === 'function' && \
{call}"
),
|_| {},
);
}
/// Paints and presents once Servo has requested its first repaint.
///
/// Nothing is presented before that request; the first frames can still be
/// blank or unstyled while the document loads.
fn render_frame(&mut self) {
if !self.signals.content.load(Ordering::Relaxed) {
return;
}
let (Some(webview), Some(context)) = (&self.webview, &mut self.rendering_context) else {
return;
};
if let Err(e) = context.paint_and_present(webview) {
tracing::warn!("frame not presented: {e}");
}
}
/// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
fn shut_down(&mut self) {
self.shutting_down = true;
self.webview = None;
self.servo = None;
}
}
impl ApplicationHandler<ServoWake> for App {
/// Releases everything that holds Wayland objects of winit's display
/// (Servo, the rendering context, whose software and EGL paths keep
/// their own proxies on it, the shell protocol client and the window)
/// while that display is still connected; dropped after the event loop,
/// they would be destroyed on a display that is gone. A panic unwinding
/// out of a handler skips this.
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
self.shut_down();
self.rendering_context = None;
self.shell_client = None;
self.window = None;
}
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
@ -170,18 +388,17 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size();
self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() {
if let (Some(disp), Some(surf)) =
(event_loop.wayland_display(), window.wayland_surface())
{
match crate::shell_client::ShellClient::connect_with_display(disp, surf) {
Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
if self.shell_client.is_none()
&& let Some((disp, surf)) = wayland_handles(event_loop, &window)
{
match crate::shell_client::ShellClient::connect_with_display(disp, surf) {
Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
}
let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone()))
.build();
@ -197,18 +414,14 @@ impl ApplicationHandler<ServoWake> for App {
if let Some(kit_js) = load_ui_kit_script() {
user_content_manager.add_script(Rc::new(UserScript::new(kit_js, None)));
}
let bridge_js = format!(
r#"(function(){{var ws=new WebSocket('ws://127.0.0.1:{p}');var q=[];var r=false;ws.onopen=function(){{r=true;q.forEach(function(m){{ws.send(JSON.stringify(m))}});q.length=0}};window.weftIpc={{send:function(m){{if(r)ws.send(JSON.stringify(m));else q.push(m)}},onmessage:null}};ws.onmessage=function(e){{if(window.weftIpc.onmessage)window.weftIpc.onmessage(JSON.parse(e.data))}}}})()"#,
p = self.ws_port
);
user_content_manager.add_script(Rc::new(UserScript::new(bridge_js, None)));
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested),
signals: Arc::clone(&self.signals),
document: self.url.as_str().to_owned(),
}))
.user_content_manager(Rc::clone(&user_content_manager))
.url(self.url.clone())
.url(self.url.clone().into_url())
.build();
self.servo = Some(servo);
@ -227,14 +440,10 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit();
return;
}
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() {
Ok(false) => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Ok(false) => compositor_closed = true,
Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {}
}
@ -245,29 +454,36 @@ impl ApplicationHandler<ServoWake> for App {
.as_ref()
.map(|h| h.is_finished())
.unwrap_or(true);
if prev_done {
let ws_port = self.ws_port;
if let (true, Some(endpoint)) = (prev_done, self.endpoint.clone()) {
self.gesture_thread = Some(std::thread::spawn(move || {
forward_gestures_to_appd(ws_port, &gestures);
forward_gestures_to_appd(&endpoint, &gestures);
}));
} else {
} else if !prev_done {
tracing::debug!(
count = gestures.len(),
"gesture forwarding in progress; dropping batch"
);
} else {
tracing::debug!(
count = gestures.len(),
"weft-appd endpoint unknown; dropping gestures"
);
}
}
}
if compositor_closed {
self.shut_down();
event_loop.exit();
return;
}
self.deliver_endpoint(event_loop);
if let Some(servo) = &self.servo {
servo.spin_event_loop();
}
if self
.redraw_requested
.swap(false, std::sync::atomic::Ordering::Relaxed)
if self.signals.redraw.swap(false, Ordering::Relaxed)
&& let Some(w) = &self.window
{
if let Some(w) = &self.window {
w.request_redraw();
}
w.request_redraw();
}
}
@ -278,23 +494,23 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent,
) {
match event {
WindowEvent::RedrawRequested => {
if let (Some(window), Some(servo)) = (&self.window, &self.servo) {
if let Some(rc) = &self.rendering_context {
Self::render_frame(window, rc);
}
servo.spin_event_loop();
}
}
WindowEvent::RedrawRequested => self.render_frame(),
WindowEvent::Resized(new_size) => {
let sz = servo::euclid::Size2D::new(new_size.width, new_size.height);
if new_size.width == 0 || new_size.height == 0 {
return;
}
if let Some(wv) = &self.webview {
wv.resize(sz);
wv.resize(new_size);
}
}
WindowEvent::ModifiersChanged(mods) => {
self.modifiers = mods.state();
}
// Servo does not tell the page when its window loses keyboard
// focus; the system UI closes its launcher then.
WindowEvent::Focused(false) => {
self.call_system_ui("weftShellBlurred", "window.weftShellBlurred()");
}
WindowEvent::KeyboardInput { event, .. } => {
if let Some(wv) = &self.webview {
let ev = super::keyutils::keyboard_event_from_winit(&event, self.modifiers);
@ -302,10 +518,11 @@ impl ApplicationHandler<ServoWake> for App {
}
}
WindowEvent::CursorMoved { position, .. } => {
let pt = servo::euclid::default::Point2D::new(position.x as f32, position.y as f32);
let pt = DevicePoint::new(position.x as f32, position.y as f32);
self.cursor_pos = pt;
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt)));
let _ = wv
.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt.into())));
}
}
WindowEvent::MouseInput { state, button, .. } => {
@ -316,22 +533,19 @@ impl ApplicationHandler<ServoWake> for App {
_ => return,
};
let action = match state {
ElementState::Pressed => MouseButtonAction::Click,
ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up,
};
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action,
btn,
self.cursor_pos.cast_unit(),
self.cursor_pos.into(),
)));
}
}
WindowEvent::CloseRequested => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
self.shut_down();
event_loop.exit();
}
_ => {}
@ -344,7 +558,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx(
event_loop: &ActiveEventLoop,
window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>,
size: PhysicalSize<u32>,
) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle();
@ -356,16 +570,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc)));
}
Err(e) => {
tracing::warn!("EGL rendering context failed ({e}), falling back to software");
tracing::warn!(
"EGL rendering context failed ({e:?}), falling back to software"
);
}
}
}
}
match servo::SoftwareRenderingContext::new(servo::euclid::Size2D::new(size.width, size.height))
{
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
let context = match servo::SoftwareRenderingContext::new(size) {
Ok(rc) => Rc::new(rc),
Err(e) => {
tracing::error!("SoftwareRenderingContext failed: {e}");
tracing::error!("SoftwareRenderingContext failed: {e:?}");
return None;
}
};
let surface = softbuffer::Context::new(Arc::clone(window))
.and_then(|display| softbuffer::Surface::new(&display, Arc::clone(window)));
match surface {
Ok(surface) => Some(RenderingCtx::Software { context, surface }),
Err(e) => {
tracing::error!("software presentation surface failed: {e}");
None
}
}
@ -432,9 +656,12 @@ pub fn run(html_path: &Path, ws_port: u16) -> anyhow::Result<()> {
.map_err(|e| anyhow::anyhow!("event loop run: {e}"))
}
fn forward_gestures_to_appd(ws_port: u16, gestures: &[crate::shell_client::PendingGesture]) {
fn forward_gestures_to_appd(
endpoint: &AppdEndpoint,
gestures: &[crate::shell_client::PendingGesture],
) {
use std::net::TcpStream;
let addr = format!("127.0.0.1:{ws_port}");
let addr = format!("127.0.0.1:{}", endpoint.port);
let stream = match TcpStream::connect(&addr) {
Ok(s) => s,
Err(e) => {
@ -450,6 +677,11 @@ fn forward_gestures_to_appd(ws_port: u16, gestures: &[crate::shell_client::Pendi
return;
}
};
let hello = serde_json::json!({ "type": "HELLO", "role": "system", "token": endpoint.token });
if let Err(e) = ws.send(tungstenite::Message::Text(hello.to_string())) {
tracing::warn!("gesture forward: authentication failed: {e}");
return;
}
for g in gestures {
let json = format!(
r#"{{"type":"PANEL_GESTURE","gesture_type":{},"fingers":{},"dx":{},"dy":{}}}"#,

View file

@ -1,5 +1,3 @@
#![cfg(feature = "servo-embed")]
use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use winit::event::ElementState;
use winit::keyboard::{Key as WinitKey, KeyLocation, ModifiersState, NamedKey, PhysicalKey};
@ -14,10 +12,11 @@ pub fn keyboard_event_from_winit(
};
let key = match &event.logical_key {
WinitKey::Named(NamedKey::Space) => Key::Character(" ".to_string()),
WinitKey::Named(n) => Key::Named(named_key(*n)),
WinitKey::Character(c) => Key::Character(c.to_string().into()),
WinitKey::Unidentified(_) => Key::Unidentified,
WinitKey::Dead(c) => Key::Dead(*c),
WinitKey::Character(c) => Key::Character(c.to_string()),
WinitKey::Unidentified(_) => Key::Named(servo::NamedKey::Unidentified),
WinitKey::Dead(_) => Key::Named(servo::NamedKey::Dead),
};
let code = match event.physical_key {
@ -46,15 +45,7 @@ pub fn keyboard_event_from_winit(
mods |= Modifiers::META;
}
KeyboardEvent {
state,
key,
code,
location,
modifiers: mods,
repeat: event.repeat,
is_composing: false,
}
KeyboardEvent::new_without_event(state, key, code, location, mods, event.repeat, false)
}
fn named_key(n: NamedKey) -> servo::NamedKey {
@ -66,7 +57,8 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::Control => S::Control,
NamedKey::Fn => S::Fn,
NamedKey::FnLock => S::FnLock,
NamedKey::Meta => S::Meta,
// winit names the Super keys Super; the DOM names them Meta.
NamedKey::Meta | NamedKey::Super => S::Meta,
NamedKey::NumLock => S::NumLock,
NamedKey::ScrollLock => S::ScrollLock,
NamedKey::Shift => S::Shift,
@ -74,7 +66,6 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::SymbolLock => S::SymbolLock,
NamedKey::Enter => S::Enter,
NamedKey::Tab => S::Tab,
NamedKey::Space => S::Space,
NamedKey::ArrowDown => S::ArrowDown,
NamedKey::ArrowLeft => S::ArrowLeft,
NamedKey::ArrowRight => S::ArrowRight,

View file

@ -37,12 +37,17 @@ fn run() -> anyhow::Result<()> {
embed_servo(&wayland_display, &html_path, ws_port)
}
/// Where the weft-servo-shell package installs the system UI page;
/// `infra/systemd/servo-shell.service` relies on it.
const PACKAGED_SYSTEM_UI: &str =
"/packages/system/weft-servo-shell/active/share/weft/shell/system-ui.html";
fn system_ui_html_path() -> anyhow::Result<PathBuf> {
if let Ok(p) = std::env::var("WEFT_SYSTEM_UI_HTML") {
return Ok(PathBuf::from(p));
}
let packaged = PathBuf::from("/packages/system/servo-shell/active/share/weft/system-ui.html");
let packaged = PathBuf::from(PACKAGED_SYSTEM_UI);
if packaged.exists() {
return Ok(packaged);
}

View file

@ -9,6 +9,11 @@ use crate::protocols::{
client::{zweft_shell_manager_v1, zweft_shell_window_v1},
};
/// Height in logical pixels of the taskbar strip the system UI draws along
/// the bottom of the output; it matches `--taskbar-height` in
/// `infra/shell/system-ui.html`.
pub const TASKBAR_HEIGHT: i32 = 48;
// ── Window state ──────────────────────────────────────────────────────────────
pub struct ShellWindowState {
@ -72,7 +77,7 @@ impl Dispatch<wl_registry::WlRegistry, ()> for AppData {
} = event
&& interface == "zweft_shell_manager_v1"
{
let mgr = registry.bind::<ZweftShellManagerV1, _, _>(name, version.min(2), qh, ());
let mgr = registry.bind::<ZweftShellManagerV1, _, _>(name, version.min(3), qh, ());
state.manager = Some(mgr);
}
}
@ -213,6 +218,11 @@ impl ShellClient {
&qh,
(),
);
// The taskbar's strip at the bottom of the output is kept free of
// application windows.
if window.version() >= 3 {
window.set_exclusive_zone(zweft_shell_window_v1::Edge::Bottom, TASKBAR_HEIGHT);
}
data.window = Some(window);
event_queue
@ -239,10 +249,6 @@ impl ShellClient {
Ok(!self.data.window_state.closed)
}
pub fn window_state(&self) -> &ShellWindowState {
&self.data.window_state
}
pub fn take_pending_gestures(&mut self) -> Vec<PendingGesture> {
std::mem::take(&mut self.data.pending_gestures)
}

View file

@ -8,35 +8,35 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
### weft-compositor
Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Supports DRM/KMS and winit (software/dev) backends.
Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). The compositor owns stacking and focus: the system shell's panel is sized to the output and starts beneath application windows, and clicking it brings it to the front as the shell's home, with its launcher, until an application is activated or opens its first window; layout changes keep the stacking order, and a window that maps without taking focus goes beneath the window in front; a session's first window, a clicked window and an activated one are raised, marked activated and given keyboard focus, and when the focused window closes the topmost remaining application window gets focus. Alt+F4 is the compositor's: it asks the focused application window to close (never the panel), and the app shell then exits and its session ends. The Super keys are the compositor's too and never reach an application: a Super tap, pressed and released without another key or a pointer button, brings the panel (the first registered) to the front with keyboard focus and then delivers the tap to it, so the shell's launcher is reachable from any application; keys pressed while Super is held reach the focused window with the Super modifier, but Super's own key events do not. A session's later windows are shown without taking focus. The panel reserves a strip along an output edge for the taskbar with `set_exclusive_zone` (weft-servo-shell reserves 48 logical pixels at the bottom), and the compositor lays every application window out to fill the remaining work area. weft-appd's `ACTIVATE_APP` request, which the taskbar sends, asks the compositor to activate a running session's window. Supports DRM/KMS and winit (software/dev) backends.
### weft-servo-shell
System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket.
System UI host. Renders one WebView pointing at `system-ui.html` using the embedded Servo engine (feature-gated behind `servo-embed`). Connects to the compositor as window type `panel`. Dispatches the `zweft_shell_manager_v1` event queue each frame. Forwards navigation gestures received from the compositor to `weft-appd` over WebSocket. Reads the appd WebSocket port and system token from `$XDG_RUNTIME_DIR/weft/` and hands both to the page through `window.weftAppdEndpoint(port, token)`; the shell hands the token only to the system UI document and denies top-level navigation away from it, and the launcher shows package names as text, never markup. The system UI works from the keyboard: a Super tap opens or closes the launcher, which lists installed apps by name and keeps focus while open (Tab moves between apps, Enter opens one, Escape closes it and returns focus to the Apps button, with the shell's home still in front); every taskbar entry and its close button is a button reachable with Tab, and Enter on an entry brings its app back. The shell tells the page through `window.weftShellBlurred()` when it loses keyboard focus, which Servo does not report to the document, and the launcher closes. The page has no transitions or animations, since Servo does not evaluate `prefers-reduced-motion`.
### weft-app-shell
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>` and `<session_id>` as arguments. Resolves `weft-app://<app_id>/ui/index.html` and injects the `weftIpc` WebSocket bridge into the page. Registers with the compositor as window type `application`. Exits when the appd session ends.
Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signals READY. Takes `<app_id>`, `<session_id>` and `--ui <path>`, the UI document weft-appd resolved from the package; it never looks for the package itself. Injects the `weftIpc` WebSocket bridge into the page. The bridge authenticates with the per-session token from `WEFT_BRIDGE_TOKEN` and can only exchange messages with its own session. It is installed only in top-level documents inside the application's UI directory, and top-level navigation outside that directory is denied; framed documents never receive the bridge. Every resource the page loads (subresources, `fetch()`, XHR, workers and WebSocket handshakes) is checked by the shell: the page may load files inside its UI directory, also after symbolic links are resolved, inline `data:` and `blob:` resources, `about:blank` and the session bridge; any other local file or network destination, and every redirect, fails with a network error. Loads Servo does not attribute to the webview, such as `navigator.sendBeacon()`, are all refused. Network access belongs to the Wasm component, under its fetch grants. Servo's privileged `navigator.servo` interface, which can change engine preferences, is not exposed to `about:blank` or `about:srcdoc` documents (a fork patch; see `crates/weft-servo-shell/SERVO_PIN.md`). Registers with the compositor as window type `application`, over the one Wayland connection weft-appd created for its session and passed as standard input (`WAYLAND_SOCKET=0`). Exits when the appd session ends.
### weft-appd
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). For each session: spawns `weft-runtime`, waits for READY, spawns `weft-app-shell`, manages the per-session IPC relay, and supervises child processes. Handles graceful termination and cgroup resource limits (via systemd-run when available).
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. The two children log to stderr, which appd records at info level; their stdout carries the readiness line, and anything else printed there is recorded only at debug level. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd asks the compositor to close the session's windows and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it. The session stays `running` while the application answers (appd replies with that state), and enters `stopping` only once it is ending. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); its window is brought to the front and the session keeps running. A repeated request while the application answers changes nothing, and a session being asked to close is still restored at the next start if appd stops meanwhile. `TERMINATE_APP` with `"force": true` terminates the session without asking; the taskbar offers it, as Force quit, for an app still running once it has had time to answer. The stop reason records what happened: a close on request with a clean exit, a failure while closing, the timeout, or a forced stop; `stopped` is broadcast once the session has settled. A session still starting is stopped at once, also when the request races its readiness, and when appd itself shuts down its sessions are terminated without a close. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
### weft-runtime
WASI Preview 2 + Component Model execution host (Wasmtime 30). Loads `app.wasm` from the installed package directory. Provides host imports for `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard`. Preopens filesystem paths according to capabilities declared in `wapp.toml`.
WASI Preview 2 + Component Model execution host (Wasmtime 30). Runs the component weft-appd passes with `--module <path>`, the package's `[runtime].module`. Provides host imports for `weft:app/notify`, `weft:app/ipc`, `weft:app/fetch`, `weft:app/notifications`, and `weft:app/clipboard`. Preopens filesystem paths according to capabilities declared in `wapp.toml`.
### weft-pack
Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module), `sign` (Ed25519 signature), `verify` (verify signature), `generate-key`, `install`, `uninstall`, `list`, `build-image` (EROFS dm-verity), `info`.
Package management CLI. Subcommands: `check` (validate wapp.toml, entries and package content), `sign` (Ed25519 signature over every file), `verify` (verify signature), `generate-key`, `install` (requires a signature by a trusted key unless `--dev`; records the app ID's owner; installs or updates, see [Installing and updating](#installing-and-updating)), `uninstall`, `rollback`, `approve` (approve the app's declared capabilities, or those listed; `install --approve` does so at installation), `list`, `build-image` (EROFS dm-verity), `info`.
### weft-file-portal
Per-session file proxy. Runs as a separate process with a path allowlist derived from preopened directories. Accepts JSON-lines requests over a Unix socket. Blocks path traversal. Used by apps that require file access without direct WASI preopens.
Per-session file proxy. Runs as a separate process with the session's directory grants; read-only grants (`--allow-read`) refuse writes. Every operation is resolved beneath the granted directory's descriptor by the kernel (see security.md), with bounded file, listing and request sizes. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access.
### weft-mount-helper
Setuid helper binary. Calls `veritysetup` and mounts EROFS images for dm-verity-protected packages.
Setuid-root helper that mounts the EROFS images of dm-verity protected packages for weft-appd and unmounts them. Since its caller controls every argument and the environment, it mounts only at an empty directory `/run/user/<uid>/weft/mnt/<name>` of the real user (weft-appd names it with a random token in `$XDG_RUNTIME_DIR/weft/mnt`, so `XDG_RUNTIME_DIR` must be `/run/user/<uid>`), with every component from `<uid>` on owned by that user, not writable by others and opened without following symbolic links, and mounts through the opened directory. It opens the image and hash tree with the real user's permissions, mounts read-only with `nosuid`, `nodev` and `noexec`, unmounts only an EROFS filesystem at such a directory, and runs `veritysetup` from the absolute path fixed at build time (`WEFT_VERITYSETUP`, `/usr/sbin/veritysetup` by default) with an empty environment. Its device-mapper device is `weft-<uid>-<name>`, so a user can only reach their own devices; a device left by an interrupted mount is closed by the next mount or unmount at that directory, and a user may have at most 64 open.
## Process Topology
@ -46,9 +46,9 @@ systemd
├── weft-servo-shell (user, after compositor)
└── weft-appd (user, after compositor + servo-shell)
└── per-session:
├── weft-runtime <app_id> <session_id> [--preopen ...] [--ipc-socket ...]
├── weft-app-shell <app_id> <session_id>
└── weft-file-portal <socket> [--allow ...]
├── weft-runtime <app_id> <session_id> --ipc-socket <path> --module <path> [--preopen HOST::GUEST::ro|rw]... [--grant CAP]... [--max-memory-mib N]
├── weft-app-shell <app_id> <session_id> --ui <path>
└── weft-file-portal <socket> [--allow ...] [--allow-read ...]
```
## IPC
@ -56,21 +56,45 @@ systemd
| Channel | Protocol | Purpose |
|---|---|---|
| weft-appd Unix socket | MessagePack | appd ↔ other system daemons |
| weft-appd WebSocket (:7410) | JSON | system-ui.html ↔ appd (gesture events, app lifecycle) |
| weft-appd WebSocket (:7410) | JSON | system-ui.html and servo-shell ↔ appd (system role: gestures, app lifecycle); app pages ↔ their session (app role) |
| per-session IPC socket | newline-delimited JSON | weft-runtime ↔ weft-app-shell (weft:app/ipc) |
| weft-file-portal socket | JSON-lines | weft-runtime ↔ file proxy |
### WebSocket roles
Every WebSocket connection must complete the upgrade and send `HELLO` as its first message within 5 seconds, or appd closes it; a first message that is not a valid `HELLO` is answered with an error (code 401) before the connection is closed. Messages are limited to 1 MiB.
- `{"type":"HELLO","role":"system","token":"<hex>"}` — the token is the content of `$XDG_RUNTIME_DIR/weft/appd.systoken` (mode 0600), regenerated each time appd starts. A system client may launch, terminate and query sessions. It receives lifecycle broadcasts but never application messages, and cannot inject them (`IPC_FORWARD` is refused with code 403).
- `{"type":"HELLO","role":"app","session_id":<n>,"token":"<hex>"}` — the token is the session's bridge token, passed to `weft-app-shell` in `WEFT_BRIDGE_TOKEN` and distinct from its readiness token. An app client may only send `{"type":"APP_MESSAGE","payload":"<string>"}` (at most 64 KiB, no newlines); the payload goes to its own session's Wasm component. It receives only its own session's replies, as `APP_MESSAGE`, and is disconnected when the session stops.
## Capability Enforcement
Capabilities are declared in `wapp.toml` under `[package] capabilities`. `weft-pack check` validates that only known capabilities are listed. At runtime, `weft-appd` reads capabilities and maps them to WASI preopened directories and host function availability:
Capabilities are declared in `wapp.toml` under `[package] capabilities`. One vocabulary (`weft_ipc_types::capability`) is used by `weft-pack check`, which rejects unknown strings, by `weft-appd`, which derives the session's effective grants, and by `weft-runtime`, which enforces them.
`weft-appd` derives grants once, before a session exists. `LAUNCH_APP` is answered with an error and nothing starts when the app ID is malformed (code 400), the package is not installed (404), a declared capability is unknown, unsupported on this host or cannot be satisfied (403), app data exists in both the current and the earlier location (409), or the host cannot provide the resources (500, for example without `HOME`). All capabilities are checked before the app's data directory is created. Without `WEFT_RUNTIME_BIN`, appd starts no processes and derives no grants. The runtime does not read the manifest; it receives the grants as arguments:
- `--preopen HOST::GUEST::ro|rw` for each directory, with the access mode the capability names;
- `--grant <capability>` for each host-import capability.
Each capability-controlled host import (fetch, notifications, clipboard) checks its grant on every call and returns an error naming the missing capability when it is not granted. `notify` and `ipc` need no capability.
| Capability | Effect |
|---|---|
| `fs:rw:app-data` | Preopen `~/.local/share/weft/apps/<id>/data` as `/data` |
| `fs:read:app-data` | Same, read-only |
| `fs:rw:xdg-documents` | Preopen `~/Documents` as `/xdg/documents` |
| `net:fetch` | Enables `weft:app/fetch` host function |
| `sys:notifications` | Enables `weft:app/notifications` host function |
| `fs:read:app-data` / `fs:rw:app-data` | Preopen the app's data directory (see *App data*) as `/data`, read-only or read-write |
| `fs:read:xdg-documents` / `fs:rw:xdg-documents` | Preopen the documents directory from the XDG user-dirs configuration (`XDG_DOCUMENTS_DIR`) as `/xdg/documents`; the launch fails when none is configured |
| `net:fetch:<host>` | `weft:app/fetch` to that exact host (a lowercase DNS name or dotted IPv4 address) over HTTP or HTTPS, on any port |
| `net:fetch:*` | `weft:app/fetch` to any host at a public address |
| `sys:notifications` | `weft:app/notifications` |
| `sys:clipboard:read` / `sys:clipboard:write` | `weft:app/clipboard#read` / `#write` |
| `hw:gpu:compute` / `hw:gpu:render` | Not supported; the launch fails |
Clipboard and notifications run `wl-paste`, `wl-copy` and `notify-send` from the runtime's environment, each bounded to 5 seconds, after which the helper is killed and the call fails. Clipboard text is UTF-8, of any text type, and at most 1 MiB in either direction. A notification's title is at most 256 bytes and its body 4096, sent as plain text with markup escaped; its icon must be an icon theme name, not a path or URL; and it is sent with the app's ID as the application name, so an app cannot pass a notification off as the system's. Where a helper is not installed the call fails with that error.
Fetch does not follow redirects: a redirect is returned to the component as a response, so every destination it requests is checked against its grants. HTTP error statuses are responses too; only policy and transport failures are errors. Only the methods GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are accepted, and a component cannot set `Host`, `Content-Length`, `Transfer-Encoding` or other hop-by-hop headers. Connecting times out after 10 seconds and the whole request after 30 seconds, not counting DNS resolution; response bodies are limited to 16 MiB. Fetch requires a runtime built with the `net-fetch` feature.
The runtime resolves a fetch destination itself and connects only to the addresses it allows. A grant for a name, and `net:fetch:*`, reach only public unicast addresses: loopback, unspecified, private, shared (100.64/10), link-local, multicast, broadcast, reserved, documentation and benchmarking addresses, and their IPv6 counterparts (unique local, site-local, Teredo and others), are refused, and an IPv6 address that carries an IPv4 address (mapped, compatible, translated, 6to4, NAT64) is judged by that address, so DNS cannot point a granted name at this machine or the local network. An IPv4 address named in a grant, such as `net:fetch:127.0.0.1`, is reached as declared. Fetch never goes through a proxy. Ports are not restricted. Credentials in a URL are refused; a component sends credentials in a header, and only to a host it is granted, since redirects are not followed. IPv6 literals cannot be granted.
`tests/runtime/check_grants.py` runs the real runtime on a probe component (`tests/components/grants-probe`) under each kind of grant.
## Package Format
@ -80,7 +104,7 @@ Capabilities are declared in `wapp.toml` under `[package] capabilities`. `weft-p
app.wasm — WASI Component Model binary
ui/
index.html — entry point served by weft-app-shell
signature.sig — Ed25519 signature over SHA-256 of (wapp.toml + app.wasm)
signature.sig — Ed25519 signature over the content digest of every other file (see security.md)
```
Package store roots (in priority order):
@ -88,12 +112,55 @@ Package store roots (in priority order):
2. `~/.local/share/weft/apps/`
3. `/usr/share/weft/apps/`
### Package resolution
`weft-appd` resolves a launch once. A verified image in any store root takes precedence over a directory install in any root, so a user's directory cannot shadow a system image; otherwise the first root with a directory install is used:
- **Verified image:** `<root>/<id>.app.img` with its dm-verity hash tree `<id>.app.hash` and root hash `<id>.app.roothash`, the names `weft-pack build-image` and `build-verity` produce. When any of the three exists, the image must mount through `weft-mount-helper`; a missing companion, a malformed root hash, a missing helper or a failed mount refuses the launch, and appd never falls back to a directory install. The root hash is read from the store next to the image and is not yet authenticated, so dm-verity detects corruption but not a store whose image, hash tree and root hash were replaced together. The mount belongs to the session and is released when the session stops.
- **Directory install:** `<root>/<id>`, a link to the active revision `.revisions/<id>/<digest>` written by `weft-pack`, or, for a store written before revisions, a package directory. A link is followed only in exactly that form, to one of the app's own revisions; any other link is refused (403). The session runs from the revision directory itself and holds a shared lock on it until it stops, so it keeps its bytes while an update or rollback switches the link.
The package root must be a directory and its manifest a regular file, neither a symbolic link, and the manifest must declare the requested ID. `[runtime].module` and `[ui].entry` must be relative paths of plain components, without symbolic links, naming regular files inside that root. The component, the UI document and the capabilities all come from that one manifest. A refused launch reports 400 (invalid ID), 404 (not installed), 403 (invalid package, image or image metadata) or 500 (the host cannot read the package or mount the image).
A directory install can still be changed by its owner while a session runs; for a verified owner, appd checks its content against the signature at launch, with the limits security.md describes.
### Installing and updating
`weft-pack install` copies the package into a staging directory in the store and checks, verifies and admits that copy, so the bytes that are checked are the bytes that are installed. The copy is flushed to disk and renamed to an immutable revision named by its content digest, `<root>/.revisions/<id>/<digest>`; installing the same content again reuses it. One rename of the link `<root>/<id>` then makes it active. The rename of the link is the commit point. An installation that fails before it leaves the previously active revision active, or, for a first installation, nothing installed; a failed first installation also removes the owner record it created, while one interrupted by a crash leaves that record until `weft-pack uninstall <id>` releases it. After the commit point the update stands, and what an interruption leaves to tidy is collected later. A revision is reused only when it still holds the same content and signature file; otherwise the new copy replaces it in one exchange, unless a running session uses it. Such a replacement, for the same content with another signature file, is visible under the revision's name at once, even if the installation then fails. A package directory from before revisions is replaced in one exchange with the new link, only while no session runs from it and only after the app data an earlier weft-appd kept in its `data` directory has been moved to the app data directory, under the same rules as for uninstall; otherwise the update stops before replacing anything. Data moved this way stays in the app data directory even if the update is then refused.
The revision active before an update is kept for `weft-pack rollback <id>`, which makes it active again, keeping the revision it replaces in turn; it is checked against the owner record again, so a revision whose publisher key was withdrawn is not rolled back to. Other revisions are removed by each install, rollback or uninstall of the app, except those a session still runs from; those stay until a later operation on the app finds them unused. Temporary links of interrupted activations are removed then too, and staging, unpacking and removal directories once they are an hour old. `weft-pack uninstall` removes the link, so new launches no longer find the app, and the kept revision; running sessions continue on their revisions. Apart from that move of data from the earlier layout, app data is never touched by these operations. Package revisions and app data are independent: rolling back a package does not roll back its data.
A launch is refused (500, try again) while a package operation holds the revision it would run from, rather than waiting for it. Only sessions started by this weft-appd hold their revisions: a session left from an earlier version, or processes that outlive weft-appd, do not, and a package directory from before revisions such sessions run from can be replaced under them. Package operations on one app are serialised by the owner lock in the data home of the user running them; the store itself is not locked against users with other data homes.
## Closing an application
A user closes an application from the taskbar, which sends `TERMINATE_APP`, or with Alt+F4 in the compositor; both ask the application's window to close. What happens next is the application's declared unsaved-change policy, `[ui].close` in `wapp.toml`:
- `immediate` (the default): the app shell exits at once.
- `ask`: the app shell dispatches a cancelable `weftclose` event on the page's top-level window and waits up to 2 seconds for it to be handled. If no listener calls `preventDefault()`, or the page does not answer in time, the app shell exits. Otherwise the close is declined: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session keeps running. The page then lets the user decide, and closes itself with `window.close()`, which Servo allows while the top-level document has a single history entry. A clean exit after a close request, including one the page makes after declining, is recorded as a close on request. A report still unread when a new request arrives can answer that request early; the app shell still closes a page that does not answer.
Notes uses `ask`: with unsaved changes it offers "Save and close", which closes only after the save is acknowledged and stays open with the error shown when the save fails, "Close without saving", and Cancel.
The close timeout of weft-appd still applies to a close that is not declined: an app shell that neither exits nor declines within 5 seconds is terminated, and the stop reason says so. An application can decline every close, so a forced stop never asks it: it is the user's way to end an application that will not close. A forced stop, the timeout, a crash and appd's own shutdown are never reported as a close on request, and say nothing about whether the application saved.
## App data
Each app's private data lives in `$XDG_DATA_HOME/weft/app-data/<id>` (`~/.local/share/weft/app-data/<id>` by default), apart from installed packages. Installing, updating or uninstalling a package never removes it. `weft-appd` creates the directory when a session with an app-data capability starts and makes it accessible only to the user (mode 0700); a symbolic link in its place is refused rather than followed. `weft-appd` and `weft-pack` must run with the same `HOME` and `XDG_DATA_HOME` to agree on this location; the systemd unit allows `weft-appd` to write under `~/.local/share/weft`.
Earlier versions kept app data inside the user package store, in `~/.local/share/weft/apps/<id>/data`, for apps declaring an app-data capability. That directory is moved to the new location in a single rename, which never replaces an existing directory:
- by `weft-appd`, on the first launch with an app-data capability;
- by `weft-pack uninstall` and `weft-pack install`, before they touch a package directory in the user store (however its path is spelled). `uninstall` moves it when the package declares an app-data capability or its manifest cannot be read, and otherwise stops without removing anything; a `data` directory is never deleted with a package.
A package directory left empty by the move is removed. Nothing is moved, and `weft-pack` stops or the launch is refused, when the new location already exists, even empty (error 409), when the old one is not a plain directory, or when the two are on different filesystems (error 500); the message names both locations so the user can keep one copy and remove the other. The system UI shows such refusals. Packages cannot contain a top-level `data` entry, so package content is never taken for app data. `tests/frame/check_app_data.py` checks that existing Notes data arrives byte for byte, that the Notes session then reads and saves it, and that a conflict is refused.
## Environment Variables
| Variable | Default | Description |
|---|---|---|
| `WEFT_RUNTIME_BIN` | — | Path to `weft-runtime` binary |
| `WEFT_APP_SHELL_BIN` | — | Path to `weft-app-shell` binary |
| `WEFT_APP_SHELL_BIN` | — | Path to `weft-app-shell` binary; required to launch apps |
| `WEFT_READY_TOKEN` | set by appd | Per-session readiness token passed to `weft-runtime` and `weft-app-shell` |
| `WEFT_BRIDGE_TOKEN` | set by appd | Per-session token `weft-app-shell` uses to join its session on the appd WebSocket |
| `WEFT_FILE_PORTAL_BIN` | — | Path to `weft-file-portal` binary |
| `WEFT_MOUNT_HELPER` | — | Path to `weft-mount-helper` binary |
| `WEFT_APP_STORE` | — | Override package store root |
@ -101,5 +168,4 @@ Package store roots (in priority order):
| `WEFT_APPD_WS_PORT` | `7410` | WebSocket port for weft-appd |
| `WEFT_EGL_RENDERING` | — | Set to `1` to use EGL rendering in Servo shell |
| `WEFT_DISABLE_CGROUP` | — | Set to disable systemd-run cgroup wrapping |
| `WEFT_FILE_PORTAL_SOCKET` | — | Path forwarded to app runtime for file portal |
| `XDG_RUNTIME_DIR` | — | Standard XDG runtime dir (sockets written here) |

View file

@ -2,7 +2,7 @@
## Prerequisites
Linux (x86_64 or aarch64). Building on Windows is supported for workspace validation only; runtime components require Linux kernel interfaces.
Linux (x86_64 or aarch64). WEFT OS is built and validated on Linux only; runtime components require Linux kernel interfaces.
System packages (openSUSE):
@ -34,7 +34,7 @@ cargo build -p weft-servo-shell
cargo build -p weft-app-shell
```
Without `--features servo-embed`, the servo-shell and app-shell stubs compile and print READY without running an actual WebView. This is the default and the CI baseline.
Without `--features servo-embed`, the servo-shell and app-shell binaries compile for type and lint checks but exit with an error at startup; they never report readiness. This is the default and the CI baseline.
## Servo embedding (optional, slow)
@ -43,17 +43,73 @@ cargo build -p weft-servo-shell --features servo-embed
cargo build -p weft-app-shell --features servo-embed
```
This fetches and compiles the Servo fork (`github.com/marcoallegretti/servo`, branch `servo-weft`). Expect 30–60 minutes on a clean build. Servo's dependencies include SpiderMonkey (C++), which requires `clang` and `python3`.
This fetches and compiles the Servo and Stylo forks at the revisions recorded in `Cargo.lock` (see `crates/weft-servo-shell/SERVO_PIN.md`). Expect 30–60 minutes on a clean build. Servo's dependencies include SpiderMonkey (C++), which requires `clang` and `python3`.
## Frame check
`tests/frame/check_frame.py` runs `weft-compositor` nested on Xvfb with the
winit backend, starts a Servo host showing `tests/frame/reference.html`, and
checks the presented pixels. It needs `Xvfb`, `xwd`, ImageMagick's `convert`
and a Mesa OpenGL driver (llvmpipe is sufficient).
```sh
cargo build -p weft-compositor
cargo build -p weft-servo-shell -p weft-app-shell \
--features weft-servo-shell/servo-embed,weft-app-shell/servo-embed
python3 tests/frame/check_frame.py --host system
python3 tests/frame/check_frame.py --host app
python3 tests/frame/check_frame.py --host app --slow-style 3
```
`--host app` also requires the page on screen within two seconds of
`weft-app-shell` printing `READY`; `--slow-style` delays a stylesheet that
reveals the page so premature readiness becomes visible. The stylesheet is a
file next to the page that the harness keeps from being opened with a file
lease, so the delay must stay below `/proc/sys/fs/lease-break-time`.
Logs and the last capture are written to `target/frame-check`.
`tests/frame/check_input.py` uses the same nested desktop to send real X
pointer and keyboard input (with `xdotool`) through `weft-compositor` to
`weft-servo-shell` showing `tests/frame/input.html`, and checks that the
page reacts to clicks on either side of a boundary and to the `a` and
`Shift+a` keys. Logs and the last capture are written to `target/input-check`.
```sh
python3 tests/frame/check_input.py
```
The application checks run `weft-appd` with `weft-runtime` (built with
`wasmtime-runtime`) and `weft-app-shell` (built with `servo-embed`) on the
same nested desktop and drive the demo apps with real keyboard input:
```sh
python3 tests/frame/check_counter.py # Counter round trip through the session bridge
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves, asks before closing unsaved text
python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept
python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge
python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus
python3 tests/frame/check_system_ui.py # the system UI's launcher and taskbar work from the keyboard alone, reached with a Super tap
python3 tests/frame/check_update.py # updates leave running sessions on their revision; failed updates, rollback and uninstall
```
## Demo apps (wasm32-wasip2)
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed. To rebuild:
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed; they are reproducible with the toolchain pinned in `rust-toolchain.toml`. To rebuild:
```sh
rustup target add wasm32-wasip2
cd examples/org.weft.demo.counter
cargo build --release
# output: target/wasm32-wasip2/release/app.wasm
cp target/wasm32-wasip2/release/app.wasm app.wasm
rm -rf target
```
The signature covers every file in the package directory, so remove the crate's `target` directory before signing it again. The demo packages are signed with the test key in `examples/keys`, which is a fixture, not a signing authority:
```sh
weft-pack sign examples/org.weft.demo.notes --key examples/keys/weft-sign.key
```
## weft-runtime with Wasmtime
@ -62,7 +118,7 @@ cargo build --release
cargo build -p weft-runtime --features wasmtime-runtime,net-fetch
```
Without `--features wasmtime-runtime`, the runtime prints READY and exits (stub mode, used in CI on platforms without Linux system dependencies).
Without `--features wasmtime-runtime`, the runtime compiles for type, lint and unit checks (the portable CI configuration) but exits with an error when asked to run a component; it never reports readiness.
## Signing packages
@ -72,6 +128,16 @@ weft-pack sign ./examples/org.weft.demo.counter --key ./keys/weft-sign.key
weft-pack verify ./examples/org.weft.demo.counter --key ./keys/weft-sign.pub
```
Installation requires a signature by a trusted key. To install the demos with the demo key, trust it for your user (the key is a test fixture; do not trust it on a system you depend on):
```sh
mkdir -p ~/.config/weft/trusted-keys
cp examples/keys/weft-sign.pub ~/.config/weft/trusted-keys/weft-demo.pub
weft-pack install examples/org.weft.demo.notes
```
Unsigned packages under development install with `weft-pack install <dir> --dev`, recorded as development content and marked `(development)` by `weft-pack list`. See `docs/security.md` for the trust store and app ID ownership.
## NixOS VM (requires Nix with flakes)
Build the VM image:
@ -86,12 +152,21 @@ Run with QEMU:
bash infra/vm/run.sh
```
See `infra/nixos/weft-packages.nix` for the package derivations. The `outputHashes` entry for the Servo git dependency must be filled in before the `servo-embed` packages will build under Nix.
See `infra/nixos/weft-packages.nix` for the package derivations. Its `outputHashes` hold one hash per git source in `Cargo.lock` (the Servo and Stylo forks); every package vendors them, so they must match the pinned revisions for any Nix package to build.
Logging in on tty1 starts the user target `weft-session.target`, which binds `graphical-session.target` (that one refuses a manual start) and wants `weft-compositor`, then `weft-servo-shell` with the system UI page its package installs, and `weft-appd` with the runtime, app shell, file portal and mount helper packages. Run as a systemd user service, the compositor publishes its socket as `WAYLAND_DISPLAY` to the user manager before reporting readiness, so the units after it, and the app shells weft-appd starts, connect to it. The units in `infra/systemd/` are the same session for an installation outside Nix, as user units under `weft-session.target`. The image is not yet bootable to a working desktop:
- the Servo source hash in `outputHashes` is still a placeholder, so no package builds until a Nix build reports it;
- the shell packages do not enable `servo-embed`, so `weft-servo-shell` and `weft-app-shell` exit at startup.
The VM opens a graphics window; `tty0` is its primary console and the serial console a secondary one. `weft-mount-helper` is installed setuid root through `security.wrappers` at `/run/wrappers/bin/weft-mount-helper`, built to run cryptsetup's `veritysetup`.
## CI
Three jobs run on every push to `main` and on pull requests:
Jobs run on every push to `main` and on pull requests:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows (excludes Wayland crates)
- `portable` — fmt, clippy, tests for the crates that need no Linux system libraries (excludes Wayland crates)
- `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell`
- `runtime-grants` — clippy and a build of `weft-runtime` with `wasmtime-runtime,net-fetch`, then `tests/runtime/check_grants.py`, which runs a probe component under each kind of capability grant
- `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell
- `contributor-toolkit` — `python .agents/scripts/verify.py toolkit`

View file

@ -6,21 +6,33 @@ WEFT OS enforces a capability-based security model. No capability is granted by
## Capability Verification
`weft-pack check` validates capability strings against a known set (`KNOWN_CAPS`) before installation. Unknown capability strings are rejected. The validated capability list is read by `weft-appd` at session start to map capabilities to concrete resource grants.
`weft-pack check` validates capability strings against the shared vocabulary in `weft_ipc_types::capability`. Unknown capability strings are rejected. At launch, `weft-appd` derives the session's grants from the manifest and refuses to start a package with a capability that is unknown, unsupported or unsatisfiable. `weft-runtime` enforces the grants it is given: read-only directories are preopened read-only, and each host import checks its grant on every call. See the capability table in `architecture.md`.
A package gets only the capabilities the user approved. `weft-pack install --approve` approves those the installed package declares. `weft-pack approve <id>` approves those of the package weft-appd would launch, the first store in weft-appd's order that holds the app, which also covers packages in the system store. `weft-pack approve <id> <capability>...` adds the listed capabilities to the app's approval; for a package weft-pack can read they must be ones it declares. Listing them is the only way to approve an app installed as a verified image, since weft-pack cannot read an image's manifest; for the same reason, approvals for an image are not reduced when it is updated, and uninstalling a directory copy of the app removes them although the image remains. Without approval, `install` and `rollback` list what still needs it.
The approval is recorded per user, in `$XDG_DATA_HOME/weft/approvals/<id>`; weft-pack and weft-appd must use the same data home, as for owner records. An installation by another user, such as root installing into the system store, approves nothing for this user. weft-appd refuses to launch an app that declares a capability the record does not hold (403, naming the capabilities), after refusing unknown and unsupported capabilities and before preparing anything for the session. An approval covers what the installed package declares: an update or rollback drops approvals for capabilities the package no longer declares, so a capability declared again later, or newly, needs approval again. Uninstalling the app forgets its approval unless another store still holds the app. Approvals are keyed by app ID, not by store or publisher. Private app data (`fs:read:app-data`, `fs:rw:app-data`) is a minimal execution resource and needs no approval. Signature verification and approval are separate decisions: a trusted signature approves nothing.
## Process Isolation
Each app session runs as a separate OS process (`weft-runtime`). When systemd is available, the process is wrapped in a systemd scope (`weft-apps.slice`) with `CPUQuota=200%` and `MemoryMax=512M`.
Each app session runs as a separate OS process (`weft-runtime`). When systemd is available, the process is wrapped in a systemd scope (`weft-apps.slice`) with `CPUQuota=200%`, `MemoryMax=512M` and `TasksMax=512` (threads included; the runtime runs a few per CPU). Independently of systemd, the runtime limits the component's linear memory to 256 MiB in total, across all its memories (`--max-memory-mib` changes it), and bounds its tables, memories and core instances: a memory or table that would grow past its limit does not grow, and the component sees an allocation failure. App messages over `weft:app/ipc` are single lines of at most 64 KiB, the limit weft-appd applies; a component's message that is longer or contains a line break is refused, a longer line from weft-appd, or a failed send, or a write that blocks for 10 seconds, ends the connection for both sides, so weft-appd ends the session as it does when the component closes the connection. CPU time within the quota is not limited per component.
## Filesystem Isolation
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process enforces path allowlists and blocks `..` traversal for apps that use the portal protocol.
Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed when it sends or accepts no data for 60 seconds. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them.
## Package Signing
## Package Signing and Trust
Packages are signed with Ed25519 (`ed25519-dalek`). The signature covers the SHA-256 hash of `wapp.toml` and `app.wasm`. `weft-pack verify` checks the signature before installation.
Packages are signed with Ed25519 over their content digest: the SHA-256 of an inventory listing every file in the package except the root `signature.sig`, one `<path>\t<sha-256>` line per file sorted by path. Every file is covered, including the UI. Names must be UTF-8 without control characters, so no name can imitate other inventory lines. Packages may hold only directories and regular files; a symbolic link or special file makes `weft-pack check`, `sign`, `verify` and `install` refuse the package. The committed demo signatures verify under this rule.
For verified read-only package storage, `weft-pack build-image` produces an EROFS image protected with dm-verity. Mounting requires the setuid `weft-mount-helper` which calls `veritysetup`.
`weft-pack install` admits a package only when its signature verifies with a key in the trust store: `*.pub` files (64 hex digits) in `$XDG_CONFIG_HOME/weft/trusted-keys` and `/etc/weft/trusted-keys`, or only in `$WEFT_TRUSTED_KEYS` when that is set. A malformed key file is an error, not skipped. An unsigned or untrusted package is refused unless the developer passes `--dev`, which installs it as development content. The package is copied into the store first and checked on that copy, which is then renamed into place, so the bytes that are verified are the bytes that are installed. The copy holds each source directory open and opens its entries relative to it, never following links, so replacing a directory with a link while the copy runs cannot redirect it. Each entry must keep the type, device and inode it had when it was examined just before it was opened, and a FIFO is never waited on. A device node hard-linked in place of a file in that interval is opened before it is refused; `fs.protected_hardlinks`, on by default, prevents such links to devices unless the attacker owns them or holds CAP_FOWNER. Installed files are set to 0644, or 0755 when the source is executable, and directories to 0755, whatever the umask, so no installed file is writable by other users; a store, and any of its parents, that does not exist yet is created at 0755. The app ID is read from the staged copy. Archives are unpacked into a fresh private directory in the store, which is always removed.
The first installation of an app ID records its owner in `$XDG_DATA_HOME/weft/owners/<id>`: the publisher key, or development. Installations and uninstallations of one ID under one data home hold a per-ID lock, so concurrent installations cannot leave a placed package without its record. Every later installation of that ID must have the same owner, so neither another trusted publisher nor a development build can take over an ID, and with it the app's data. The record survives uninstall while the app's data remains; uninstalling with no data left frees the ID. App data with no recorded owner, as left by installations from before owner records, is given to a new owner only with `--claim-data`. A record is written under a temporary name and linked into place, so it is never partial, and a record created by an installation that then fails to place its package is removed. A record left by an installation that was killed before placing its package is released by `weft-pack uninstall <id>` once no data remains. A record is only released while no known store (the user store, the system store and `$WEFT_APP_STORE`) holds the package; a package installed into another custom store is uninstalled with that store selected. The demo key in `examples/keys` is a test fixture, not a signing authority.
`weft-appd` checks every package again before a session starts. A package recorded as a publisher's runs only while that key is still trusted and its signature covers the package's current content. A package with no record runs only when a trusted key signed it, and that key is then recorded as its owner; if app data already exists for the ID without a recorded owner, in the current layout or the earlier one that is migrated at launch, the launch is refused rather than handing the data to that publisher; `weft-pack install` applies the same rule unless given `--claim-data`. The record is written before the session starts, so it remains even if that first launch then fails; `weft-pack uninstall` releases it once no data exists in either layout and no known store holds the package. Finding earlier-layout data needs `HOME`: without an absolute `HOME`, a first launch is refused (500), a first install fails unless it claims the data, and uninstall keeps the record. While an ID is recorded as development content, whatever package is found for it runs unverified, from any store. A changed package, or one whose key was removed from the trust store, is refused with code 403; a damaged trust store or owner record is a host error, 500. The manifest is read once and its bytes must be the ones in the verified inventory, so a session's capabilities and entries come from the signed manifest. The module and UI files are read again when the session starts, so a directory install changed by its owning user after the check, or while the session runs, is not detected; verified images are not writable.
Not yet covered: key rotation and ownership transfer have no workflow, and removing a key is the only revocation; and capabilities are granted at launch without asking the user, independently of the signature.
For verified read-only package storage, `weft-pack build-image` produces an EROFS image protected with dm-verity. Mounting requires the setuid-root `weft-mount-helper`, which calls `veritysetup`. Its callers can mount only images they can read, at their own runtime directory, read-only, without set-user-ID programs, devices or executables, at most 64 at a time (see `architecture.md`). A user can therefore have the kernel parse an EROFS image of their own making: the EROFS driver's handling of crafted images is part of the attack surface wherever the helper is installed. The NixOS image installs it through a `security.wrappers` entry that only the `users` group may run. The image's root hash is not yet authenticated.
## Seccomp
@ -28,7 +40,9 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF
## Wayland Surface Isolation
Each app registers its surface with the compositor via `zweft_shell_manager_v1`. The compositor enforces that each surface belongs to the session that created it. The app cannot render outside its assigned surface slot.
Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the compositor connection is lost before the session's connection is handed over, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients.
Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; close is not yet decided by the compositor per session; there is no user placement or resizing, since application windows fill the work area the panel leaves, one in front at a time; only the first window a session maps in its lifetime takes keyboard focus when it maps, and a client connected through the display socket takes focus on map only while no other such window is mapped; and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. Such a client registered as a panel would also be raised and focused by a Super tap; the compositor picks the first panel registered.
## JavaScript Engine (SpiderMonkey)

View file

@ -1 +1 @@
e781544104eee4538e17f953ea3223903e2b2a46a78705cd1ffa8d6946a62d0385c76eab2cc1c2533eecbeff7600e76a4205abc66915be8851fe2e71316ebc0d
3c5155af4973c453e5c09b04aa0eaf71e943b6564d9aaa81a5fb023fe3ebea091a793ef493234a5a862b9752acf7cafbb0d11a2ec9c962331606ebde75c7b803

View file

@ -7,31 +7,195 @@ wit_bindgen::generate!({
},
});
use serde_json::{Value, json};
use weft::app::{ipc, notify};
const NOTES_PATH: &str = "/data/notes.txt";
/// Held while a save checks the revision and replaces the file, so saves
/// from two Notes windows cannot interleave.
const LOCK_PATH: &str = "/data/.notes.lock";
/// A lock older than this was left by a session that ended mid-save.
const STALE_LOCK: std::time::Duration = std::time::Duration::from_secs(10);
/// Largest note accepted, in bytes; the page also keeps each request under
/// the 64 KiB app message limit.
const MAX_NOTES: usize = 60 * 1024;
fn load_notes() -> String {
std::fs::read_to_string(NOTES_PATH).unwrap_or_default()
/// A revision names the exact stored bytes. A save must name the revision
/// it was edited from, so a save based on stale content is refused instead
/// of silently replacing changes made in another window.
fn revision(bytes: &[u8]) -> String {
// FNV-1a, 64-bit.
let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
});
format!("{hash:016x}")
}
fn save_notes(text: &str) -> Result<(), String> {
std::fs::write(NOTES_PATH, text).map_err(|e| e.to_string())
fn stored() -> Result<Vec<u8>, String> {
match std::fs::read(NOTES_PATH) {
Ok(bytes) => Ok(bytes),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(e) => Err(format!("cannot read notes: {e}")),
}
}
fn json_text(text: &str) -> String {
let escaped = text
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t");
format!("{{\"text\":\"{escaped}\"}}")
fn load() -> Value {
let bytes = match stored() {
Ok(bytes) => bytes,
Err(message) => return json!({ "op": "error", "message": message }),
};
match String::from_utf8(bytes) {
Ok(text) => json!({ "op": "loaded", "rev": revision(text.as_bytes()), "text": text }),
Err(_) => json!({ "op": "error", "message": "stored notes are not valid UTF-8" }),
}
}
fn json_error(msg: &str) -> String {
let escaped = msg.replace('"', "\\\"");
format!("{{\"error\":\"{escaped}\"}}")
/// A value unique to this process and moment, for lock ownership and
/// staging file names.
fn unique() -> String {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default();
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("{nanos}-{n}")
}
/// Exclusive access to the notes file for one save. The lock file holds an
/// owner token, so a save only ever removes its own lock.
struct SaveLock {
token: String,
}
impl SaveLock {
fn acquire() -> Result<Self, String> {
use std::io::Write;
let token = unique();
for _ in 0..50 {
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(LOCK_PATH)
{
Ok(mut file) => {
if let Err(e) = file.write_all(token.as_bytes()) {
let _ = std::fs::remove_file(LOCK_PATH);
return Err(format!("cannot lock notes: {e}"));
}
return Ok(SaveLock { token });
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// A lock older than STALE_LOCK was left by an ended session
// (wasmtime-wasi reports modification times, so an unknown
// age does not occur in practice). Renaming it away is
// atomic, so only one save can take it over. Two saves that
// both see it stale within the same instant could still
// both proceed; that needs an abandoned lock and two
// windows saving at once.
let stale = std::fs::metadata(LOCK_PATH)
.and_then(|m| m.modified())
.map(|t| t.elapsed().is_ok_and(|age| age > STALE_LOCK))
.unwrap_or(true);
let taken = format!("/data/.notes.lock.{token}.stale");
if stale && std::fs::rename(LOCK_PATH, &taken).is_ok() {
let _ = std::fs::remove_file(&taken);
} else {
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
Err(e) => return Err(format!("cannot lock notes: {e}")),
}
}
Err("notes are being saved by another window; try again".to_owned())
}
}
impl Drop for SaveLock {
fn drop(&mut self) {
if std::fs::read_to_string(LOCK_PATH).is_ok_and(|t| t == self.token) {
let _ = std::fs::remove_file(LOCK_PATH);
}
}
}
/// Removes staging files left by saves that ended before their rename, and
/// stale locks whose removal failed. Only
/// called with the lock held, when no other save is in progress.
fn remove_abandoned_staging() {
let Ok(entries) = std::fs::read_dir("/data") else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
let abandoned = (name.starts_with(".notes.txt.") && name.ends_with(".saving"))
|| (name.starts_with(".notes.lock.") && name.ends_with(".stale"));
if abandoned {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// Writes `text` to a staging file unique to this save, syncs it and renames
/// it over the notes, so the stored notes are always either the previous or
/// the new text in full.
fn replace_notes(text: &str) -> std::io::Result<()> {
use std::io::Write;
let staging = format!("/data/.notes.txt.{}.saving", unique());
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&staging)?;
let written = file
.write_all(text.as_bytes())
.and_then(|()| file.sync_all())
.and_then(|()| std::fs::rename(&staging, NOTES_PATH));
if written.is_err() {
let _ = std::fs::remove_file(&staging);
}
written
}
fn save(seq: &Value, base: &str, text: &str) -> Value {
let error = |conflict: bool, message: String| json!({ "op": "error", "seq": seq, "conflict": conflict, "message": message });
if text.len() > MAX_NOTES {
return error(false, format!("notes are limited to {MAX_NOTES} bytes"));
}
let _lock = match SaveLock::acquire() {
Ok(lock) => lock,
Err(message) => return error(false, message),
};
remove_abandoned_staging();
let current = match stored() {
Ok(bytes) => revision(&bytes),
Err(message) => return error(false, message),
};
if current != base {
return error(true, "the notes were changed elsewhere".to_owned());
}
match replace_notes(text) {
Ok(()) => json!({ "op": "saved", "seq": seq, "rev": revision(text.as_bytes()) }),
Err(e) => error(false, format!("cannot save notes: {e}")),
}
}
/// Every request gets a reply, so the page never waits on one that was not
/// understood.
fn handle(raw: &str) -> Value {
let Ok(request) = serde_json::from_str::<Value>(raw) else {
return json!({ "op": "error", "message": "request is not valid JSON" });
};
let seq = request.get("seq").cloned().unwrap_or(Value::Null);
let field = |name: &str| request.get(name).and_then(Value::as_str);
match field("op") {
Some("load") => load(),
Some("save") => match (field("base"), field("text")) {
(Some(base), Some(text)) => save(&seq, base, text),
_ => json!({ "op": "error", "seq": seq, "message": "malformed save request" }),
},
_ => json!({ "op": "error", "seq": seq, "message": "unknown request" }),
}
}
fn main() {
@ -39,19 +203,7 @@ fn main() {
loop {
if let Some(raw) = ipc::recv() {
let raw = raw.trim().to_owned();
let reply = if raw == "load" {
json_text(&load_notes())
} else if let Some(rest) = raw.strip_prefix("save:") {
let text = rest.replace("\\n", "\n");
match save_notes(&text) {
Ok(()) => json_text(&text),
Err(e) => json_error(&e),
}
} else {
continue;
};
let _ = ipc::send(&reply);
let _ = ipc::send(&handle(&raw).to_string());
} else {
std::thread::sleep(std::time::Duration::from_millis(10));
}

View file

@ -80,6 +80,15 @@
font-size: 12px;
color: #444;
}
#closing {
display: none;
align-items: center;
gap: 8px;
flex-shrink: 0;
font-size: 13px;
}
#closing.shown { display: flex; }
#closing span { flex: 1; }
#charcount {
font-size: 12px;
color: #444;
@ -95,6 +104,12 @@
<button class="primary" id="save">Save</button>
</div>
</header>
<div id="closing" role="alertdialog" aria-label="Unsaved changes">
<span>These notes have unsaved changes.</span>
<button class="primary" id="close-save">Save and close</button>
<button id="close-discard">Close without saving</button>
<button id="close-cancel">Cancel</button>
</div>
<textarea id="editor" placeholder="Start typing…" spellcheck="false"></textarea>
<footer>
<span id="status">connecting…</span>
@ -103,60 +118,196 @@
<script>
(function () {
// The component stores the text exactly as typed. Messages are JSON; each
// save names the revision it was edited from and is acknowledged by its
// sequence number, so a reply never replaces text typed after it was sent.
// The editor is read-only until it holds the stored text, so nothing typed
// before a load completes can be saved over notes the user never saw.
var MAX_MESSAGE = 65536; // weft-appd's limit for one app message, in bytes
var REPLY_TIMEOUT = 10000;
var editor = document.getElementById('editor');
var statusEl = document.getElementById('status');
var charEl = document.getElementById('charcount');
var saveButton = document.getElementById('save');
var saved = '';
var rev = null;
var seq = 0;
var pending = null;
var lastSent = null;
var loading = null; // timer of the outstanding load, if any
var encoder = new TextEncoder();
var closing = document.getElementById('closing');
var closeAfterSave = false;
function setStatus(msg) { statusEl.textContent = msg; }
function countChars() { charEl.textContent = editor.value.length + ' chars'; }
function send(message) { window.weftIpc.send(JSON.stringify(message)); }
function setLoaded(loaded) {
editor.readOnly = !loaded;
saveButton.disabled = !loaded || pending !== null;
}
editor.addEventListener('input', function () {
charEl.textContent = editor.value.length + ' chars';
editor.addEventListener('input', countChars);
function finishSave() {
if (pending) clearTimeout(pending.timer);
pending = null;
setLoaded(rev !== null);
}
// Close policy ("ask" in wapp.toml): when the window is asked to close
// with unsaved changes, the close is cancelled and the user chooses to
// save first, close without saving, or keep editing. The window closes
// after a save only once the save is acknowledged, saving again first if
// the text changed meanwhile; a failed save keeps it open with the error
// shown. Text typed while the notes are not loaded cannot be saved, so it
// does not hold the window open.
function unsaved() {
return pending !== null || (rev !== null && editor.value !== saved);
}
function hideClosing() {
closing.classList.remove('shown');
closeAfterSave = false;
}
window.addEventListener('weftclose', function (e) {
if (!unsaved()) return;
e.preventDefault();
// Asked again while the prompt is up, keep the user's choice so far.
closing.classList.add('shown');
});
document.getElementById('save').addEventListener('click', function () {
if (!window.weftIpc) return;
var text = editor.value.replace(/\n/g, '\\n');
window.weftIpc.send('save:' + text);
document.getElementById('close-save').addEventListener('click', function () {
closeAfterSave = true;
if (!pending) saveButton.click();
// The save could not start (status says why): stay open.
if (!pending) hideClosing();
});
document.getElementById('close-discard').addEventListener('click', function () {
window.close();
});
document.getElementById('close-cancel').addEventListener('click', hideClosing);
saveButton.addEventListener('click', function () {
if (pending) return;
if (!window.weftIpc) {
setStatus('not saved: not connected');
return;
}
if (rev === null) {
setStatus('the notes have not loaded; use Discard to reload them');
return;
}
var request = { op: 'save', seq: seq + 1, base: rev, text: editor.value };
try {
encodeURIComponent(request.text);
} catch (_) {
setStatus('not saved: the text contains characters that cannot be stored');
return;
}
if (encoder.encode(JSON.stringify(request)).length > MAX_MESSAGE) {
setStatus('not saved: the notes are too long');
return;
}
seq += 1;
lastSent = { seq: seq, text: request.text };
pending = {
seq: seq,
text: request.text,
timer: setTimeout(function () {
finishSave();
hideClosing();
setStatus('not saved: no reply; try again');
}, REPLY_TIMEOUT),
};
setLoaded(true);
send(request);
setStatus('saving…');
});
// Loads the stored notes into a read-only editor. Only one load is
// outstanding at a time; a failed or unanswered load can be retried with
// Discard.
function load(status) {
rev = null;
lastSent = null;
setLoaded(false);
loading = setTimeout(function () {
loading = null;
setStatus('the notes did not load; use Discard to retry');
}, REPLY_TIMEOUT);
send({ op: 'load' });
setStatus(status);
}
function finishLoad() {
clearTimeout(loading);
loading = null;
}
// Discard reloads the stored notes, replacing unsaved edits.
document.getElementById('discard').addEventListener('click', function () {
if (!window.weftIpc || pending || loading) return;
editor.value = saved;
charEl.textContent = saved.length + ' chars';
setStatus('discarded');
setTimeout(function () { setStatus(''); }, 1500);
countChars();
load('reloading…');
});
document.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault();
document.getElementById('save').click();
saveButton.click();
}
});
function setupIpc() {
if (!window.weftIpc) { setTimeout(setupIpc, 50); return; }
window.weftIpc.onmessage = function (raw) {
try {
var msg = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (typeof msg.error === 'string') {
setStatus('error: ' + msg.error);
return;
}
if (typeof msg.text === 'string') {
var text = msg.text.replace(/\\n/g, '\n');
editor.value = text;
saved = text;
charEl.textContent = text.length + ' chars';
setStatus('');
}
} catch (_) {}
};
setStatus('');
window.weftIpc.send('load');
function onMessage(raw) {
var msg;
try { msg = JSON.parse(raw); } catch (_) { return; }
if (msg.op === 'loaded') {
// Only the reply to the outstanding load applies; the editor is
// read-only until it arrives, so it never replaces newer text.
if (!loading) return;
finishLoad();
editor.value = msg.text;
countChars();
saved = msg.text;
rev = msg.rev;
setLoaded(true);
setStatus('');
} else if (msg.op === 'saved' && !loading && lastSent && msg.seq === lastSent.seq) {
// Also accepts an acknowledgement that arrives after the timeout.
saved = lastSent.text;
rev = msg.rev;
finishSave();
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
if (closeAfterSave) {
if (editor.value === saved) window.close();
// Text typed after this save began is saved before closing.
else saveButton.click();
if (!pending && editor.value !== saved) hideClosing();
}
} else if (msg.op === 'error') {
if (pending && msg.seq === pending.seq) {
finishSave();
hideClosing();
}
if (loading && msg.seq === undefined) finishLoad();
setStatus(msg.conflict
? 'not saved: changed in another window. Copy your text, then Discard to reload.'
: 'error: ' + msg.message);
}
}
function setupIpc() {
if (!window.weftIpc) { setTimeout(setupIpc, 50); return; }
window.weftIpc.onmessage = onMessage;
load('loading…');
}
setLoaded(false);
setupIpc();
})();
</script>

View file

@ -11,3 +11,4 @@ module = "app.wasm"
[ui]
entry = "ui/index.html"
close = "ask"

View file

@ -18,8 +18,10 @@
fsType = "ext4";
};
# The session is graphical: tty0 is the primary console, and the serial
# console stays available as a secondary one for debugging.
virtualisation = {
graphics = false;
graphics = true;
memorySize = 4096;
cores = 4;
diskSize = 20480;
@ -27,7 +29,7 @@
hardware.graphics = {
enable = true;
extraPackages = with pkgs; [ mesa.drivers virglrenderer ];
extraPackages = with pkgs; [ mesa virglrenderer ];
};
networking = {
@ -48,6 +50,18 @@
services.getty.autologinUser = "weft";
security.polkit.enable = true;
# weft-mount-helper mounts verified package images and must run as root;
# the Nix store cannot hold set-user-ID programs. Only the session user's
# group may run it, and it mounts only in the caller's own runtime
# directory (see crates/weft-mount-helper).
security.wrappers.weft-mount-helper = {
source = "${pkgs.weft.weft-mount-helper}/bin/weft-mount-helper";
owner = "root";
group = "users";
setuid = true;
permissions = "u+rx,g+x";
};
services.dbus.enable = true;
services.udev.packages = [ pkgs.libinput ];
@ -75,15 +89,28 @@
})
];
# graphical-session.target refuses a manual start; the login shell starts
# this target, which binds it, as Wayland compositors' session targets do.
systemd.user.targets.weft-session = {
description = "WEFT OS session";
bindsTo = [ "graphical-session.target" ];
wants = [ "graphical-session-pre.target" ];
after = [ "graphical-session-pre.target" ];
};
systemd.user.services = {
weft-compositor = {
description = "WEFT OS Wayland Compositor";
after = [ "graphical-session.target" ];
before = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
wantedBy = [ "graphical-session.target" ];
wantedBy = [ "weft-session.target" ];
serviceConfig = {
Type = "notify";
ExecStart = "${pkgs.weft.weft-compositor}/bin/weft-compositor";
# The compositor publishes WAYLAND_DISPLAY to the user manager for the
# units after it; a restarted compositor must not inherit it, or an
# X11 DISPLAY, or it would pick the nested backend.
UnsetEnvironment = "WAYLAND_DISPLAY DISPLAY";
Restart = "on-failure";
RestartSec = "1";
};
@ -93,9 +120,10 @@
description = "WEFT OS System Shell";
requires = [ "weft-compositor.service" ];
after = [ "weft-compositor.service" ];
wantedBy = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
wantedBy = [ "weft-session.target" ];
environment = {
WAYLAND_DISPLAY = "wayland-1";
WEFT_SYSTEM_UI_HTML = "${pkgs.weft.weft-servo-shell}/share/weft/shell/system-ui.html";
};
serviceConfig = {
Type = "simple";
@ -109,6 +137,8 @@
description = "WEFT Application Daemon";
requires = [ "weft-compositor.service" ];
after = [ "weft-compositor.service" "weft-servo-shell.service" ];
partOf = [ "graphical-session.target" ];
wantedBy = [ "weft-session.target" ];
serviceConfig = {
Type = "notify";
ExecStart = "${pkgs.weft.weft-appd}/bin/weft-appd";
@ -116,8 +146,9 @@
RestartSec = "1s";
Environment = [
"WEFT_RUNTIME_BIN=${pkgs.weft.weft-runtime}/bin/weft-runtime"
"WEFT_APP_SHELL_BIN=${pkgs.weft.weft-app-shell}/bin/weft-app-shell"
"WEFT_FILE_PORTAL_BIN=${pkgs.weft.weft-file-portal}/bin/weft-file-portal"
"WEFT_MOUNT_HELPER=${pkgs.weft.weft-mount-helper}/bin/weft-mount-helper"
"WEFT_MOUNT_HELPER=/run/wrappers/bin/weft-mount-helper"
];
};
};
@ -125,7 +156,7 @@
programs.bash.loginShellInit = ''
if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ] && [ "$(tty)" = "/dev/tty1" ]; then
systemctl --user start graphical-session.target
systemctl --user start weft-session.target
fi
'';

View file

@ -10,20 +10,24 @@ let
cargoLock = {
lockFile = ../../Cargo.lock;
# One hash per git source in Cargo.lock: the Servo fork and the Stylo fork
# (keyed by its `selectors` crate). Every package vendors both, so both must
# match the pinned revisions. Recompute them whenever a revision changes.
# The Servo hash is not yet known for e5d9a51; a Nix build reports it.
outputHashes = {
"servo-0.0.1" = "0b803qankr0rs4hi0md26dydf2cvpd6v5x2bxxypzsga0jwfdd26";
"selectors-0.36.0" = "1x5g61cadq700yhl1wwrjd043grlpdviqqn4n9cm5k68gbx0if81";
"servo-0.0.1" = pkgs.lib.fakeHash;
"selectors-0.36.0" = "13y6pa19j4w2zsxfhv6mrl03wsa0frazlsssbqkzpwci8k9gzl4i";
};
};
commonArgs = {
inherit src cargoLock;
version = "0.1.0";
version = "0.0.1-alpha.0";
nativeBuildInputs = with pkgs; [ pkg-config ];
};
mkWeftPkg = { pname, extraBuildInputs ? [], extraNativeBuildInputs ? [], cargoFlags ? [], extraEnv ? {}, preBuild ? "" }: rustPlatform.buildRustPackage (commonArgs // {
inherit pname preBuild;
mkWeftPkg = { pname, extraBuildInputs ? [], extraNativeBuildInputs ? [], cargoFlags ? [], extraEnv ? {}, preBuild ? "", postInstall ? "" }: rustPlatform.buildRustPackage (commonArgs // {
inherit pname preBuild postInstall;
cargoBuildFlags = [ "--package" pname ] ++ cargoFlags;
cargoTestFlags = [ "--package" pname ];
buildInputs = extraBuildInputs;
@ -46,6 +50,10 @@ in {
weft-servo-shell = mkWeftPkg {
pname = "weft-servo-shell";
# The system UI page, at the path the shell's units name.
postInstall = ''
install -Dm644 infra/shell/system-ui.html $out/share/weft/shell/system-ui.html
'';
};
weft-app-shell = mkWeftPkg {
@ -74,5 +82,9 @@ in {
weft-mount-helper = mkWeftPkg {
pname = "weft-mount-helper";
extraBuildInputs = with pkgs; [ cryptsetup ];
# The helper runs setuid and takes no program from its caller's PATH.
extraEnv = {
WEFT_VERITYSETUP = "${pkgs.cryptsetup}/bin/veritysetup";
};
};
}

View file

@ -9,10 +9,12 @@
color-scheme: dark;
--surface-bg: rgba(255, 255, 255, 0.07);
--surface-border: rgba(255, 255, 255, 0.12);
/* weft-servo-shell reserves this strip (TASKBAR_HEIGHT); keep them equal. */
--taskbar-height: 48px;
--text-primary: rgba(255, 255, 255, 0.92);
--text-secondary: rgba(255, 255, 255, 0.55);
--accent: #5b8af5;
--focus-ring: #9db8ff;
}
*, *::before, *::after {
@ -62,19 +64,30 @@
-webkit-backdrop-filter: blur(20px);
}
weft-taskbar-launcher {
button {
font: inherit;
color: inherit;
border: 0;
margin: 0;
background: transparent;
cursor: pointer;
}
:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
#launcher-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 8px;
cursor: pointer;
background: transparent;
transition: background 0.15s;
}
weft-taskbar-launcher:hover {
#launcher-btn:hover {
background: var(--surface-border);
}
@ -110,55 +123,56 @@
margin: 0 auto;
}
weft-app-icon {
.app-icon {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
padding: 12px 8px;
border-radius: 12px;
cursor: pointer;
color: var(--text-primary);
font-size: 12px;
text-align: center;
word-break: break-word;
transition: background 0.15s;
}
weft-app-icon:hover {
.app-icon:hover {
background: var(--surface-border);
}
weft-app-icon svg {
.app-icon svg {
flex-shrink: 0;
}
weft-taskbar-app {
display: inline-flex;
align-items: center;
gap: 4px;
gap: 2px;
font-size: 12px;
color: var(--text-secondary);
padding: 0 4px 0 6px;
cursor: pointer;
border-radius: 6px;
transition: background 0.15s;
}
weft-taskbar-app:hover {
background: var(--surface-border);
}
weft-taskbar-app .task-activate {
padding: 4px 2px 4px 6px;
border-radius: 6px;
}
weft-taskbar-app .task-close {
opacity: 0;
font-size: 11px;
line-height: 1;
padding: 1px 3px;
padding: 3px 4px;
border-radius: 3px;
transition: opacity 0.1s, background 0.1s;
}
weft-taskbar-app:hover .task-close {
/* Shown on hover and whenever the entry has keyboard focus. */
weft-taskbar-app:hover .task-close,
weft-taskbar-app:focus-within .task-close {
opacity: 1;
}
@ -166,6 +180,10 @@
background: rgba(255,80,80,0.3);
}
weft-taskbar-app .task-close.force {
color: #ff6b6b;
}
weft-notification-center {
position: fixed;
top: 8px;
@ -187,7 +205,8 @@
<weft-desktop>
<weft-wallpaper></weft-wallpaper>
<weft-taskbar>
<weft-taskbar-launcher id="launcher-btn" title="Apps">
<button id="launcher-btn" type="button" title="Apps" aria-label="Apps"
aria-haspopup="dialog" aria-expanded="false" aria-controls="launcher">
<svg width="18" height="18" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<rect x="1" y="1" width="6" height="6" rx="1.5"
@ -199,15 +218,15 @@
<rect x="11" y="11" width="6" height="6" rx="1.5"
fill="rgba(255,255,255,0.7)" />
</svg>
</weft-taskbar-launcher>
</button>
<weft-taskbar-clock id="clock"></weft-taskbar-clock>
</weft-taskbar>
</weft-desktop>
<weft-launcher hidden id="launcher">
<weft-launcher hidden id="launcher" tabindex="-1" role="dialog" aria-modal="true" aria-label="Apps">
<weft-app-grid id="app-grid"></weft-app-grid>
</weft-launcher>
<weft-notification-center id="notifications"></weft-notification-center>
<weft-notification-center id="notifications" role="status" aria-live="polite"></weft-notification-center>
<script>
(function () {
@ -221,67 +240,141 @@
updateClock();
setInterval(updateClock, 10000);
document.getElementById('launcher-btn').addEventListener('click', function () {
var launcher = document.getElementById('launcher');
if (launcher.hasAttribute('hidden')) {
launcher.removeAttribute('hidden');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
}
} else {
launcher.setAttribute('hidden', '');
var launcher = document.getElementById('launcher');
var launcherBtn = document.getElementById('launcher-btn');
var appGrid = document.getElementById('app-grid');
function launcherOpen() {
return !launcher.hasAttribute('hidden');
}
// Opening the launcher moves keyboard focus into it; closing it
// returns focus to the Apps button.
function openLauncher() {
launcher.removeAttribute('hidden');
launcherBtn.setAttribute('aria-expanded', 'true');
focusInLauncher(null);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
}
}
function closeLauncher() {
if (!launcherOpen()) return;
launcher.setAttribute('hidden', '');
launcherBtn.setAttribute('aria-expanded', 'false');
launcherBtn.focus();
}
// Focuses the icon of `appId`, else the first one, else the dialog.
function focusInLauncher(appId) {
var icons = appGrid.querySelectorAll('.app-icon');
var target = null;
icons.forEach(function (icon) {
if (icon.dataset.appId === appId) target = icon;
});
(target || icons[0] || launcher).focus();
}
launcherBtn.addEventListener('click', function () {
if (launcherOpen()) closeLauncher(); else openLauncher();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
document.getElementById('launcher').setAttribute('hidden', '');
// The compositor brings the shell to the front when a Super key is
// tapped, then delivers the tap here; it opens or closes the
// launcher.
if (e.key === 'Meta' && !e.repeat && !e.altKey && !e.ctrlKey && !e.shiftKey) {
e.preventDefault();
if (launcherOpen()) closeLauncher(); else openLauncher();
} else if (e.key === 'Escape' && launcherOpen()) {
e.preventDefault();
closeLauncher();
} else if (e.key === 'Tab' && launcherOpen()) {
// The launcher is modal: Tab cycles through its apps, and Escape
// leaves it.
var icons = Array.prototype.slice.call(appGrid.querySelectorAll('.app-icon'));
e.preventDefault();
if (icons.length === 0) { launcher.focus(); return; }
var at = icons.indexOf(document.activeElement);
var next = at === -1 ? 0 : (at + (e.shiftKey ? icons.length - 1 : 1)) % icons.length;
icons[next].focus();
}
});
document.getElementById('launcher').addEventListener('click', function (e) {
// weft-servo-shell calls this when the shell loses keyboard focus, as
// when an application window is clicked; the launcher closes, so the
// next Super tap opens it.
window.weftShellBlurred = closeLauncher;
launcher.addEventListener('click', function (e) {
if (e.target === this) {
this.setAttribute('hidden', '');
closeLauncher();
}
});
var APPD_WS_PORT = window.WEFT_APPD_WS_PORT || 7410;
// weft-servo-shell supplies weft-appd's port and system token through
// window.weftAppdEndpoint once weft-appd is running, and again after it
// restarts. Nothing connects before then.
var appd = null;
var ws = null;
var wsReconnectDelay = 1000;
var wsReconnectTimer = null;
window.weftAppdEndpoint = function (port, token) {
if (appd && appd.port === port && appd.token === token) return;
appd = { port: port, token: token };
wsReconnectDelay = 1000;
if (ws) {
// The close handler reconnects with the new endpoint.
ws.close();
} else {
clearTimeout(wsReconnectTimer);
wsReconnectTimer = null;
appdConnect();
}
};
function appdConnect() {
wsReconnectTimer = null;
if (!appd || ws) return;
var endpoint = appd;
var socket;
try {
ws = new WebSocket('ws://127.0.0.1:' + APPD_WS_PORT + '/appd');
socket = new WebSocket('ws://127.0.0.1:' + endpoint.port + '/appd');
} catch (e) {
scheduleReconnect();
return;
}
ws = socket;
ws.addEventListener('open', function () {
socket.addEventListener('open', function () {
if (ws !== socket) return;
wsReconnectDelay = 1000;
document.querySelectorAll('weft-taskbar-app').forEach(function (el) { el.remove(); });
ws.send(JSON.stringify({ type: 'QUERY_RUNNING' }));
ws.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
socket.send(JSON.stringify({ type: 'HELLO', role: 'system', token: endpoint.token }));
document.querySelectorAll('weft-taskbar-app').forEach(removeEntryElement);
socket.send(JSON.stringify({ type: 'QUERY_RUNNING' }));
socket.send(JSON.stringify({ type: 'QUERY_INSTALLED_APPS' }));
});
ws.addEventListener('message', function (ev) {
socket.addEventListener('message', function (ev) {
if (ws !== socket) return;
var msg;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
handleAppdMessage(msg);
});
ws.addEventListener('close', function () {
// A failed socket also fires close, so reconnection is handled there.
socket.addEventListener('close', function () {
if (ws !== socket) return;
ws = null;
scheduleReconnect();
});
ws.addEventListener('error', function () {
ws = null;
});
}
function scheduleReconnect() {
setTimeout(appdConnect, wsReconnectDelay);
if (wsReconnectTimer !== null) return;
wsReconnectTimer = setTimeout(appdConnect, wsReconnectDelay);
wsReconnectDelay = Math.min(wsReconnectDelay * 2, 16000);
}
@ -294,6 +387,8 @@
} else if (msg.type === 'APP_STATE') {
if (msg.state === 'stopped') {
removeTaskbarEntry(msg.session_id);
} else if (msg.state === 'stopping') {
setTaskbarEntryClosing(msg.session_id);
}
} else if (msg.type === 'RUNNING_APPS') {
msg.sessions.forEach(function (s) {
@ -311,42 +406,61 @@
},
}));
} else if (msg.type === 'ERROR') {
// Launch refusals (missing package, capability or data conflict)
// must reach the user; the launcher otherwise looks unresponsive.
console.warn('appd error', msg.code, msg.message);
showNotification('Cannot open: ' + msg.message);
}
}
function renderLauncher(apps) {
var grid = document.getElementById('app-grid');
var grid = appGrid;
// Replacing the icons would drop keyboard focus; it returns to the
// same app's new icon.
var focused = grid.contains(document.activeElement) ? document.activeElement.dataset.appId : null;
var active = document.activeElement;
var refocus = launcherOpen() && (!active || active === document.body || launcher.contains(active));
grid.innerHTML = '';
if (apps.length === 0) {
var empty = document.createElement('p');
empty.textContent = 'No apps installed';
empty.style.cssText = 'color:var(--text-secondary);font-size:13px;';
grid.appendChild(empty);
if (refocus) focusInLauncher(null);
return;
}
apps.forEach(function (app) {
var icon = document.createElement('weft-app-icon');
var icon = document.createElement('button');
icon.type = 'button';
icon.className = 'app-icon';
icon.dataset.appId = app.app_id;
icon.title = app.app_id + (app.version ? ' v' + app.version : '');
// Names come from package manifests; they are set as text, never markup.
icon.innerHTML =
'<svg width="40" height="40" viewBox="0 0 40 40" fill="none"' +
' xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
'<rect width="40" height="40" rx="10" fill="rgba(91,138,245,0.25)"/>' +
'<text x="20" y="27" text-anchor="middle" font-size="18" fill="rgba(255,255,255,0.8)">' +
(app.name ? app.name.charAt(0).toUpperCase() : '?') +
'</text></svg>' +
'<span>' + (app.name || app.app_id) + '</span>';
'</text></svg><span></span>';
icon.querySelector('text').textContent = app.name ? app.name.charAt(0).toUpperCase() : '?';
icon.querySelector('span').textContent = app.name || app.app_id;
icon.setAttribute('aria-label', 'Open ' + (app.name || app.app_id));
icon.addEventListener('click', function () {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'LAUNCH_APP', app_id: app.app_id, surface_id: 0 }));
}
document.getElementById('launcher').setAttribute('hidden', '');
closeLauncher();
});
grid.appendChild(icon);
});
if (refocus) focusInLauncher(focused);
}
// Longer than weft-appd's close timeout, so an app that neither closes
// nor declines has already been terminated.
var FORCE_QUIT_DELAY = 6000;
var FORCE_QUIT_OFFER = 20000;
function ensureTaskbarEntry(sessionId, appId) {
var id = 'task-' + sessionId;
if (document.getElementById(id)) { return; }
@ -355,29 +469,96 @@
el.id = id;
el.dataset.sessionId = sessionId;
if (appId) { el.dataset.appId = appId; }
el.setAttribute('role', 'group');
el.setAttribute('aria-label', label);
el.title = appId ? appId + ' (session ' + sessionId + ')' : 'Session ' + sessionId;
var span = document.createElement('span');
var span = document.createElement('button');
span.type = 'button';
span.className = 'task-activate';
span.textContent = '● ' + label;
var close = document.createElement('span');
span.setAttribute('aria-label', 'Show ' + label);
var close = document.createElement('button');
close.type = 'button';
close.className = 'task-close';
close.textContent = '×';
close.title = 'Terminate';
close.title = 'Close';
close.setAttribute('aria-label', 'Close ' + label);
// The first click asks the app to close; it may decline, for example
// to offer saving. An app still running once it has had time to
// answer can then be force quit, losing what it has not saved.
var closeTimer = null;
close.addEventListener('click', function (e) {
e.stopPropagation();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId }));
}
if (!ws || ws.readyState !== WebSocket.OPEN) { return; }
var force = close.dataset.force === '1';
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId, force: force }));
if (force || close.dataset.asked) { return; }
close.dataset.asked = '1';
closeTimer = setTimeout(function () {
if (!document.getElementById(el.id) || el.dataset.closing) { return; }
close.dataset.force = '1';
close.textContent = 'Force quit';
close.title = 'Force quit: changes the app has not saved are lost';
close.setAttribute('aria-label', 'Force quit ' + label + '; changes it has not saved are lost');
close.classList.add('force');
showNotification(label + ' did not close; its close button now force quits it');
// Offered only for a while: an app that declined to let the user
// keep working is closed normally next time.
closeTimer = setTimeout(resetClose, FORCE_QUIT_OFFER);
}, FORCE_QUIT_DELAY);
});
function resetClose() {
clearTimeout(closeTimer);
closeTimer = null;
delete close.dataset.asked;
delete close.dataset.force;
close.textContent = '×';
close.title = 'Close';
close.setAttribute('aria-label', 'Close ' + label);
close.classList.remove('force');
}
el.appendChild(span);
el.appendChild(close);
// Choosing the entry brings the app's window to the front.
el.addEventListener('click', function () {
if (el.dataset.closing) { return; }
resetClose();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId }));
}
});
var taskbar = document.querySelector('weft-taskbar');
var clock = document.getElementById('clock');
taskbar.insertBefore(el, clock);
}
// The session is ending; its entry stays until it has stopped.
function setTaskbarEntryClosing(sessionId) {
var el = document.getElementById('task-' + sessionId);
if (!el || el.dataset.closing) { return; }
el.dataset.closing = '1';
el.style.opacity = '0.5';
el.title += ' (closing)';
var activate = el.querySelector('.task-activate');
activate.setAttribute('aria-disabled', 'true');
activate.setAttribute('aria-label', activate.getAttribute('aria-label') + ' (closing)');
var close = el.querySelector('.task-close');
if (close) {
if (document.activeElement === close) { activate.focus(); }
close.style.display = 'none';
}
}
function removeTaskbarEntry(sessionId) {
var el = document.getElementById('task-' + sessionId);
if (el) { el.remove(); }
if (el) { removeEntryElement(el); }
}
// Focus on a removed entry would be lost; it moves to the Apps button.
function removeEntryElement(el) {
var hadFocus = el.contains(document.activeElement);
el.remove();
if (hadFocus) { launcherBtn.focus(); }
}
function showNotification(text) {
@ -398,7 +579,6 @@
setTimeout(function () { note.remove(); }, 4000);
}
appdConnect();
}());
</script>
</body>

View file

@ -3,15 +3,16 @@ Description=WEFT OS Servo Shell
Documentation=https://github.com/weft-os/weft
Requires=weft-compositor.service
After=weft-compositor.service
PartOf=graphical-session.target
[Service]
Type=simple
PassEnvironment=WAYLAND_DISPLAY XDG_RUNTIME_DIR DISPLAY
Environment=WEFT_APPD_WS_PORT=7410
ExecStart=/packages/system/weft-servo-shell/active/bin/weft-servo-shell \
/packages/system/weft-servo-shell/active/share/weft/shell/system-ui.html
# The page is the package's share/weft/shell/system-ui.html; set
# WEFT_SYSTEM_UI_HTML to use another.
ExecStart=/packages/system/weft-servo-shell/active/bin/weft-servo-shell
Restart=on-failure
RestartSec=2
[Install]
WantedBy=graphical.target
WantedBy=weft-session.target

View file

@ -3,6 +3,7 @@ Description=WEFT Application Daemon
Documentation=https://github.com/weft-os/weft
Requires=weft-compositor.service
After=weft-compositor.service servo-shell.service
PartOf=graphical-session.target
[Service]
Type=notify
@ -10,13 +11,12 @@ Environment=WEFT_RUNTIME_BIN=/packages/system/weft-runtime/active/bin/weft-runti
Environment=WEFT_APP_SHELL_BIN=/packages/system/weft-app-shell/active/bin/weft-app-shell
Environment=WEFT_FILE_PORTAL_BIN=/packages/system/weft-file-portal/active/bin/weft-file-portal
Environment=WEFT_MOUNT_HELPER=/packages/system/weft-mount-helper/active/bin/weft-mount-helper
PassEnvironment=WAYLAND_DISPLAY XDG_RUNTIME_DIR DISPLAY
ExecStart=/packages/system/weft-appd/active/bin/weft-appd
Restart=on-failure
RestartSec=1s
ProtectSystem=strict
PrivateTmp=true
ReadWritePaths=%t
# No ProtectSystem= or PrivateTmp=: in the user manager they imply
# PrivateUsers=yes, under which the setuid weft-mount-helper cannot mount
# verified images. Each session's runtime runs in its own systemd scope.
[Install]
WantedBy=graphical.target
WantedBy=weft-session.target

View file

@ -1,15 +1,19 @@
[Unit]
Description=WEFT OS Wayland Compositor
Documentation=https://github.com/weft-os/weft
After=systemd-logind.service
Before=graphical-session.target
PartOf=graphical-session.target
[Service]
Type=notify
ExecStart=/packages/system/weft-compositor/active/bin/weft-compositor
Restart=on-failure
RestartSec=1
# The socket path is posted to the environment by the compositor itself.
# Downstream services (servo-shell.service) should declare After=weft-compositor.service.
# A user unit: the compositor publishes its socket as WAYLAND_DISPLAY in the
# user manager before reporting readiness, for the services ordered
# After=weft-compositor.service. It must not inherit that value, or an X11
# DISPLAY, on restart, or it would pick the nested backend.
UnsetEnvironment=WAYLAND_DISPLAY DISPLAY
[Install]
WantedBy=graphical.target
WantedBy=weft-session.target

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