Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Add SSH key settings and improve System Monitor

oxydizer1eefb41770ff
diff --git a/TESTING.md b/TESTING.md
index 75d59ed..d068d0c 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -32,6 +32,15 @@ wayland-protocols and GLES2; D-Bus suites also need PyGObject,
App checks include [calculator](tests/calculator.py), [editor](tests/editor.py)
and [editor visuals](tests/editor_visuals.py).
+SSH keys: `zig build test-keys` and
+`dbus-run-session -- python3 tests/keys_settings.py` (repeat with
+`REDIWM_TEST_SCALE=1.5`). Fixtures generate OpenSSH and legacy RSA keys in a
+scratch home, compare fingerprints with OpenSSH, verify passphrase changes,
+and exercise the real Settings fields. They never use the host's keys or
+agent. Requires OpenSSH, OpenSSL and `gio`; `GIO_USE_VFS=local` keeps Trash
+within the fixture. `--helper-only` skips the compositor; `--bin-dir` selects
+the helper and compositor builds together.
+
## Isolation and harness
- Use a private headless compositor, temporary home/XDG directories and private
diff --git a/build.zig b/build.zig
index 8dd3ad7..84399e7 100644
--- a/build.zig
+++ b/build.zig
@@ -272,6 +272,7 @@ pub fn build(b: *std.Build) void {
const session_supervisor = session.session_supervisor;
const zig_tests = tests.addZig(ctx, session);
+ @import("build/keys.zig").add(ctx, zig_tests.test_step, &.{ compositor.root_module, zig_tests.ui_tests_module });
const ui_tests_module = zig_tests.ui_tests_module;
const ipc_tests_module = zig_tests.ipc_tests_module;
const files_tests = zig_tests.files_tests;
diff --git a/build/keys.zig b/build/keys.zig
new file mode 100644
index 0000000..f8f85a4
--- /dev/null
+++ b/build/keys.zig
@@ -0,0 +1,20 @@
+//! The unprivileged key helper and its standalone parser tests.
+const std = @import("std");
+const Context = @import("context.zig").Context;
+pub fn add(ctx: Context, test_step: *std.Build.Step, hosts: []const *std.Build.Module) void {
+ const b = ctx.b;
+ const module = b.createModule(.{ .root_source_file = b.path("src/keys/mod.zig"), .target = ctx.target, .optimize = ctx.optimize, .link_libc = true });
+ module.addImport("c", ctx.c.libc);
+ module.addImport("platform", ctx.platform_mod);
+ for (hosts) |host| host.addImport("keys", module);
+ const helper = b.addExecutable(.{ .name = "rediwm-keys", .root_module = b.createModule(.{ .root_source_file = b.path("src/keys_main.zig"), .target = ctx.target, .optimize = ctx.optimize, .link_libc = true }), .use_llvm = ctx.use_llvm, .use_lld = ctx.use_llvm });
+ helper.root_module.addImport("keys", module);
+ helper.root_module.addImport("platform", ctx.platform_mod);
+ helper.root_module.addImport("c", ctx.c.libc);
+ helper.root_module.addCSourceFile(.{ .file = b.path("src/platform/key_scan.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ b.installArtifact(helper);
+ const tests = b.addTest(.{ .root_module = module });
+ const run = b.addRunArtifact(tests);
+ b.step("test-keys", "Test key metadata parsers and operation plans").dependOn(&run.step);
+ test_step.dependOn(&run.step);
+}
diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.md
index aed795a..a2374eb 100644
--- a/docs/agent-notes/map.md
+++ b/docs/agent-notes/map.md
@@ -31,6 +31,7 @@ or a lowercase directory named after a TitleCase host (`Dock.zig` → `dock/`).
| `rediwm-dm` | `src/dm/main.zig` | display manager, runs as root (`dm/AGENTS.md`) |
| `rediwm-accounts-helper` | `src/accounts_helper/main.zig` | root account helper (`accounts_helper/AGENTS.md`) |
| `rediwm-theme` | `src/theme_main.zig` | theme archive helper (`theme_helper/`) |
+| `rediwm-keys` | `src/keys_main.zig` | unprivileged SSH metadata and operations (`keys/`, `keys_helper.zig`); Settings uses `keys/client.zig` |
`build.zig` holds the options, the shared modules, the compositor and
`rediwm-msg`; `build/` the rest: `apps.zig` (the programs above), `data.zig`
@@ -44,6 +45,8 @@ No compositor imports (`build.zig` enforces the direction): `ui` (`src/ui/`:
widgets, layout, text, theme, animation), `config` (`src/config/`: parsing and
saving `config.toml`), `dbus`, `i18n`, `memory` and `protocol`
(`src/ipc/protocol.zig`, the IPC wire format shared with `rediwm-msg`). Also
+`keys` (`src/keys/mod.zig`: public identity model, bounded key metadata parsers,
+inventory and operation protocol; parsers run in `rediwm-keys`) and
`platform` (`src/platform/`, std only): child-process handles, directory
watching, the program's own path, system helper lookup (`tool.zig`) and
syscall filters (`seccomp.zig`), the
diff --git a/docs/plans/keys-certificates.md b/docs/plans/keys-certificates.md
index 0a590b8..d08d1b2 100644
--- a/docs/plans/keys-certificates.md
+++ b/docs/plans/keys-certificates.md
@@ -1,7 +1,42 @@
# Keys & Certificates plan
-Status: draft, 2026-11-10. Nothing built. Decisions D1–D8 are open; each has a
-recommendation. Start with Phase 0.
+Status: SSH implementation, 2026-11-10, on `feat/settings-ssh-keys`.
+D1, D4 and D8 follow the recommendations below for the initial SSH page.
+Agent integration, certificates, whole-home discovery, vault operations and
+trust stores remain later phases; their decisions are still open.
+
+The initial page inventories regular, owned files directly in `~/.ssh` by
+content, groups copies by public fingerprint, and shows encryption, weak-key,
+permission, missing-public and mismatched-public badges. It supports details,
+copy public key, Ed25519 generation, passphrase/comment/label changes,
+recreating a missing `.pub`, permissions and confirmed Trash of a selected
+location plus its matching public companion. Users links to the page; global
+search reaches it without starting its helper.
+
+Supported metadata: OpenSSH private keys (including encrypted headers),
+Ed25519/RSA/DSA/NIST ECDSA public keys, and unencrypted RSA PKCS#1/PKCS#8 PEM.
+Encrypted legacy PEM, SSH certificates, security-key formats, PuTTY and other
+certificate/container formats are skipped with an explanation for now. No
+agent or host/reference inventory is implied by the SSH view. Trash confirms
+the selected path and fingerprint and warns about references; enumerating
+those references belongs to Phase 2.
+
+The helper has bounded reads/replies, memory/CPU limits, no core dumps and a
+read-only scanner sandbox (seccomp on Linux, preopened read capabilities and
+Capsicum on FreeBSD). OpenSSH operations run on staged files; passphrase and
+comment changes verify identity and unchanged source bytes before publishing.
+The FreeBSD path has been cross-compiled; runtime qualification is still needed.
+Passphrases use locked buffers and an inherited pipe to a private askpass mode,
+with no external askpass IPC. Scan results refresh explicitly; no idle watches.
+
+Generated fixtures cover the SSH portion of Phase 0 and the initial page:
+fingerprint comparisons with OpenSSH, duplicate locations, hostile/truncated
+armor/DER, encrypted keys, missing/mismatched companions, unsafe files and
+permissions, failed/successful writes, labels, Trash and UI secrets. Whole-home
+timings, X.509 corpus/tooling surveys and oldest-supported-OpenSSH qualification
+remain prerequisites for their later phases. The metadata format follows
+[OpenSSH's key specification](https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key);
+operations use [ssh-keygen](https://man.openbsd.org/ssh-keygen).
Add a **Keys & Certificates** page to Settings: one place that shows every SSH
key, certificate and private key the user owns, wherever it lies, says what
diff --git a/docs/system-monitor.md b/docs/system-monitor.md
index d81f599..860640c 100644
--- a/docs/system-monitor.md
+++ b/docs/system-monitor.md
@@ -2,7 +2,9 @@
Open **System Monitor** from the launcher, with **Ctrl+Alt+Del**, or by
running `rediwm-monitor`. The shortcut restores and focuses an existing
-window, including one on another workspace.
+window, including one on another workspace. It dismisses open shell popups,
+the window switcher and screenshot selection, and takes focus even when a
+client has inhibited compositor shortcuts.
CPU and RAM summary cards show large current percentages and shaded 60-second
graphs. CPU includes its reported frequency and logical CPU count; RAM includes
@@ -14,14 +16,18 @@ New processes and the first sample after resuming show an em dash until
there is a second CPU measurement. Unavailable data also shows an em dash.
Nonlocal account names fall back to their numeric UID.
-The bottom bar groups CPU, RAM, swap, network, uptime and CPU temperature
+The bottom bar groups CPU, RAM, swap, network, uptime and CPU/GPU temperatures
beside the process actions. It wraps the readouts and actions at smaller
window sizes. CPU shows online logical CPUs and CPU 0's reported frequency;
RAM and swap show used/total capacity and a percentage. Network arrows show
total upload/download rates across non-loopback interfaces (virtual interfaces
can count the same traffic again). The first sample after resume or an interface
-change shows a dash. Temperature is the hottest supported CPU sensor, never a
-disk or GPU reading. Missing metrics show a dash; FreeBSD currently provides
+change shows a dash. Temperature has separate **CPU** and **GPU** rows. CPU
+shows the hottest supported CPU sensor. GPU shows the hottest reported GPU die
+or package temperature, using Linux hwmon for AMD, Intel and Nouveau, or the
+optional NVIDIA management library for the proprietary driver. GPU junction
+and memory channels are excluded. NVIDIA telemetry is released while paused
+or minimized. Missing metrics show a dash; FreeBSD currently provides
CPU count, frequency and uptime, with network and temperature unavailable.
The list starts with your processes, sorted by CPU usage. Click a column to
@@ -89,8 +95,8 @@ For explicit workspace overrides, use the existing section:
"Ctrl+Alt+Delete" = "open_system_monitor"
```
-Shortcut inhibition and lock/greeter rules still apply. The app gets its
-own application scope when scope management is enabled.
+Lock, greeter, authentication prompts and shortcut editing keep priority.
+The app gets its own application scope when scope management is enabled.
## Building and testing
diff --git a/po/de.po b/po/de.po
index b0d6244..526d51c 100644
--- a/po/de.po
+++ b/po/de.po
@@ -1374,10 +1374,6 @@ msgstr "Druckeroption konnte nicht angewendet werden."
msgid "Could not apply this choice. Please try again."
msgstr "Diese Auswahl konnte nicht angewendet werden. Versuche es erneut."
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr "Anfrage konnte nicht erstellt werden."
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr "Zugriffsrechte konnten nicht geändert werden"
@@ -7735,3 +7731,283 @@ msgstr ""
#: src/control_center/search_index.zig
msgid "mouse touchpad trackball default custom inherit"
msgstr ""
+
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "A file already exists at that location. Choose another name."
+msgstr "An diesem Ort existiert bereits eine Datei. Wähle einen anderen Namen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr "Ohne Passphrase bleibt der private Schlüssel unverschlüsselt."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Back to SSH keys"
+msgstr "Zurück zu SSH-Schlüsseln"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase"
+msgstr "Passphrase ändern"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase…"
+msgstr "Passphrase ändern…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Comment"
+msgstr "Kommentar"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Confirm passphrase"
+msgstr "Passphrase bestätigen"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Copy public key"
+msgstr "Öffentlichen Schlüssel kopieren"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys."
+msgstr "Die Schlüsselhilfe konnte nicht gestartet werden."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not start the key operation."
+msgstr "Die Schlüsselaktion konnte nicht gestartet werden."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Current passphrase"
+msgstr "Aktuelle Passphrase"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit comment…"
+msgstr "Kommentar bearbeiten…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit label…"
+msgstr "Bezeichnung bearbeiten…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Enter a filename without slashes or a leading dot."
+msgstr "Gib einen Dateinamen ohne Schrägstriche oder führenden Punkt ein."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Filename in ~/.ssh"
+msgstr "Dateiname in ~/.ssh"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Fix permissions"
+msgstr "Berechtigungen korrigieren"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Generate key"
+msgstr "Schlüssel erzeugen"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install OpenSSH to generate or change keys."
+msgstr "Installiere OpenSSH, um Schlüssel zu erzeugen oder zu ändern."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install gio to move keys to Trash."
+msgstr "Installiere gio, um Schlüssel in den Papierkorb zu verschieben."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Keys & Certificates"
+msgstr "Schlüssel & Zertifikate"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Label"
+msgstr "Bezeichnung"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr "Bezeichnungen gelten für alle Kopien mit diesem öffentlichen Fingerabdruck."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr "Verwalte die Schlüssel des aktuellen Benutzers in ~/.ssh."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Missing .pub file"
+msgstr ".pub-Datei fehlt"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move this key to Trash?"
+msgstr "Diesen Schlüssel in den Papierkorb verschieben?"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move to Trash…"
+msgstr "In den Papierkorb verschieben…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New Ed25519 key"
+msgstr "Neuer Ed25519-Schlüssel"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New SSH key"
+msgstr "Neuer SSH-Schlüssel"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New key…"
+msgstr "Neuer Schlüssel…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase"
+msgstr "Neue Passphrase"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase (optional)"
+msgstr "Neue Passphrase (optional)"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No passphrase"
+msgstr "Keine Passphrase"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No supported SSH keys found."
+msgstr "Keine unterstützten SSH-Schlüssel gefunden."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Passphrase protected"
+msgstr "Mit Passphrase geschützt"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public file does not match"
+msgstr "Öffentliche Datei stimmt nicht überein"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key copied."
+msgstr "Öffentlicher Schlüssel kopiert."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key only"
+msgstr "Nur öffentlicher Schlüssel"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Recreate missing .pub file"
+msgstr "Fehlende .pub-Datei neu erstellen"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "SSH keys"
+msgstr "SSH-Schlüssel"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr "Einige Dateien wurden übersprungen: nicht unterstützt, unlesbar, zu groß oder unsicher zu öffnen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr "Das Verzeichnis .ssh ist für andere Benutzer zugänglich. Korrigiere die Berechtigungen in den Schlüsseldetails."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr "Der Schlüssel wurde seit der Auswahl geändert. Aktualisiere die Ansicht und versuche es erneut."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key could not be changed. Check the current passphrase."
+msgstr "Der Schlüssel konnte nicht geändert werden. Prüfe die aktuelle Passphrase."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr "Die Schlüsselhilfe ist fehlgeschlagen. Aktualisiere die Ansicht, um es erneut zu versuchen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr "Zeitüberschreitung der Schlüsselhilfe. Aktualisiere die Ansicht, um es erneut zu versuchen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr "Die Schlüsselaktion konnte nicht abgeschlossen werden. Aktualisiere die Ansicht und versuche es erneut."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The passphrases do not match. Enter them again."
+msgstr "Die Passphrasen stimmen nicht überein. Gib sie erneut ein."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr "Diese Datei und ihre passende .pub-Datei werden in den Papierkorb verschoben. Andere Kopien bleiben erhalten. Verweise in der SSH-Konfiguration und auf Servern benötigen diesen Schlüssel möglicherweise noch."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Unsafe permissions"
+msgstr "Unsichere Berechtigungen"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr "Verwende höchstens 512 Bytes ohne Zeilenumbrüche oder Steuerzeichen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Weak algorithm or key size"
+msgstr "Schwacher Algorithmus oder zu kurzer Schlüssel"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Your SSH keys, public identities and passphrases."
+msgstr "Deine SSH-Schlüssel, öffentlichen Identitäten und Passphrasen."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "copy public permissions label comment delete trash"
+msgstr "kopieren öffentlich berechtigungen bezeichnung kommentar löschen papierkorb"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "generate ed25519 passphrase"
+msgstr "erzeugen ed25519 passphrase"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr "ssh sicherheit öffentlich privat identität fingerabdruck passphrase"
+
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr "GPU"
diff --git a/po/es.po b/po/es.po
index 9912bb6..a99953d 100644
--- a/po/es.po
+++ b/po/es.po
@@ -1371,10 +1371,6 @@ msgstr "No se pudo aplicar la opción de impresora."
msgid "Could not apply this choice. Please try again."
msgstr "No se pudo aplicar esta opción. Inténtalo de nuevo."
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr "No se pudo crear la solicitud."
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr "No se pudieron cambiar los permisos"
@@ -7732,3 +7728,283 @@ msgstr ""
#: src/control_center/search_index.zig
msgid "mouse touchpad trackball default custom inherit"
msgstr ""
+
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "A file already exists at that location. Choose another name."
+msgstr "Ya existe un archivo en esa ubicación. Elige otro nombre."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr "Una frase de contraseña vacía deja la clave privada sin cifrar."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Back to SSH keys"
+msgstr "Volver a las claves SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase"
+msgstr "Cambiar frase de contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase…"
+msgstr "Cambiar frase de contraseña…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Comment"
+msgstr "Comentario"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Confirm passphrase"
+msgstr "Confirmar frase de contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Copy public key"
+msgstr "Copiar clave pública"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys."
+msgstr "No se pudo iniciar el asistente de claves."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not start the key operation."
+msgstr "No se pudo iniciar la operación de la clave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Current passphrase"
+msgstr "Frase de contraseña actual"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit comment…"
+msgstr "Editar comentario…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit label…"
+msgstr "Editar etiqueta…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Enter a filename without slashes or a leading dot."
+msgstr "Introduce un nombre de archivo sin barras ni un punto inicial."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Filename in ~/.ssh"
+msgstr "Nombre de archivo en ~/.ssh"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Fix permissions"
+msgstr "Corregir permisos"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Generate key"
+msgstr "Generar clave"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install OpenSSH to generate or change keys."
+msgstr "Instala OpenSSH para generar o modificar claves."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install gio to move keys to Trash."
+msgstr "Instala gio para mover claves a la papelera."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Keys & Certificates"
+msgstr "Claves y certificados"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Label"
+msgstr "Etiqueta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr "Las etiquetas se aplican a todas las copias con esta huella pública."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr "Gestiona las claves del usuario actual en ~/.ssh."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Missing .pub file"
+msgstr "Falta el archivo .pub"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move this key to Trash?"
+msgstr "¿Mover esta clave a la papelera?"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move to Trash…"
+msgstr "Mover a la papelera…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New Ed25519 key"
+msgstr "Nueva clave Ed25519"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New SSH key"
+msgstr "Nueva clave SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New key…"
+msgstr "Nueva clave…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase"
+msgstr "Nueva frase de contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase (optional)"
+msgstr "Nueva frase de contraseña (opcional)"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No passphrase"
+msgstr "Sin frase de contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No supported SSH keys found."
+msgstr "No se encontraron claves SSH compatibles."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Passphrase protected"
+msgstr "Protegida con frase de contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public file does not match"
+msgstr "El archivo público no coincide"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key copied."
+msgstr "Clave pública copiada."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key only"
+msgstr "Solo clave pública"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Recreate missing .pub file"
+msgstr "Recrear el archivo .pub que falta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "SSH keys"
+msgstr "Claves SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr "Se omitieron algunos archivos: no compatibles, ilegibles, demasiado grandes o inseguros para abrir."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr "Otros usuarios pueden acceder al directorio .ssh. Corrige los permisos desde los detalles de una clave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr "La clave cambió desde que se seleccionó. Actualiza e inténtalo de nuevo."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key could not be changed. Check the current passphrase."
+msgstr "No se pudo modificar la clave. Comprueba la frase de contraseña actual."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr "El asistente de claves falló. Actualiza para intentarlo de nuevo."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr "El asistente de claves agotó el tiempo de espera. Actualiza para intentarlo de nuevo."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr "No se pudo completar la operación de la clave. Actualiza e inténtalo de nuevo."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The passphrases do not match. Enter them again."
+msgstr "Las frases de contraseña no coinciden. Introdúcelas de nuevo."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr "Esta ubicación y su archivo .pub correspondiente se moverán a la papelera. Las otras copias permanecerán donde están. Las referencias en la configuración SSH y en los servidores pueden seguir necesitando esta clave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Unsafe permissions"
+msgstr "Permisos inseguros"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr "Usa como máximo 512 bytes sin saltos de línea ni caracteres de control."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Weak algorithm or key size"
+msgstr "Algoritmo o tamaño de clave débil"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Your SSH keys, public identities and passphrases."
+msgstr "Tus claves SSH, identidades públicas y frases de contraseña."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "copy public permissions label comment delete trash"
+msgstr "copiar pública permisos etiqueta comentario eliminar papelera"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "generate ed25519 passphrase"
+msgstr "generar ed25519 frase contraseña"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr "ssh seguridad pública privada identidad huella frase contraseña"
+
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr "GPU"
diff --git a/po/fr.po b/po/fr.po
index b4417ad..cb3449f 100644
--- a/po/fr.po
+++ b/po/fr.po
@@ -1374,10 +1374,6 @@ msgstr "Impossible d'appliquer l'option d'imprimante."
msgid "Could not apply this choice. Please try again."
msgstr "Impossible d'appliquer ce choix. Réessayez."
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr "Impossible de construire la requête."
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr "Impossible de modifier les permissions"
@@ -7735,3 +7731,283 @@ msgstr ""
#: src/control_center/search_index.zig
msgid "mouse touchpad trackball default custom inherit"
msgstr ""
+
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "A file already exists at that location. Choose another name."
+msgstr "Un fichier existe déjà à cet emplacement. Choisissez un autre nom."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr "Une phrase secrète vide laisse la clé privée non chiffrée."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Back to SSH keys"
+msgstr "Retour aux clés SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase"
+msgstr "Modifier la phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase…"
+msgstr "Modifier la phrase secrète…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Comment"
+msgstr "Commentaire"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Confirm passphrase"
+msgstr "Confirmer la phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Copy public key"
+msgstr "Copier la clé publique"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys."
+msgstr "Impossible de démarrer l’assistant de clés."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not start the key operation."
+msgstr "Impossible de lancer l’opération sur la clé."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Current passphrase"
+msgstr "Phrase secrète actuelle"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit comment…"
+msgstr "Modifier le commentaire…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit label…"
+msgstr "Modifier le libellé…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Enter a filename without slashes or a leading dot."
+msgstr "Saisissez un nom de fichier sans barre oblique ni point initial."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Filename in ~/.ssh"
+msgstr "Nom du fichier dans ~/.ssh"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Fix permissions"
+msgstr "Corriger les permissions"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Generate key"
+msgstr "Générer la clé"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install OpenSSH to generate or change keys."
+msgstr "Installez OpenSSH pour générer ou modifier des clés."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install gio to move keys to Trash."
+msgstr "Installez gio pour déplacer les clés vers la corbeille."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Keys & Certificates"
+msgstr "Clés et certificats"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Label"
+msgstr "Libellé"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr "Les libellés s’appliquent à toutes les copies de cette empreinte publique."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr "Gérez les clés de l’utilisateur actuel dans ~/.ssh."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Missing .pub file"
+msgstr "Fichier .pub manquant"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move this key to Trash?"
+msgstr "Déplacer cette clé vers la corbeille ?"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move to Trash…"
+msgstr "Déplacer vers la corbeille…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New Ed25519 key"
+msgstr "Nouvelle clé Ed25519"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New SSH key"
+msgstr "Nouvelle clé SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New key…"
+msgstr "Nouvelle clé…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase"
+msgstr "Nouvelle phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase (optional)"
+msgstr "Nouvelle phrase secrète (facultative)"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No passphrase"
+msgstr "Sans phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No supported SSH keys found."
+msgstr "Aucune clé SSH prise en charge trouvée."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Passphrase protected"
+msgstr "Protégée par une phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public file does not match"
+msgstr "Le fichier public ne correspond pas"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key copied."
+msgstr "Clé publique copiée."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key only"
+msgstr "Clé publique uniquement"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Recreate missing .pub file"
+msgstr "Recréer le fichier .pub manquant"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "SSH keys"
+msgstr "Clés SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr "Certains fichiers ont été ignorés : format non pris en charge, illisibles, trop volumineux ou dangereux à ouvrir."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr "Le dossier .ssh est accessible aux autres utilisateurs. Corrigez ses permissions depuis les détails d’une clé."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr "La clé a changé depuis sa sélection. Actualisez et réessayez."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key could not be changed. Check the current passphrase."
+msgstr "Impossible de modifier la clé. Vérifiez la phrase secrète actuelle."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr "L’assistant de clés a échoué. Actualisez pour réessayer."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr "Le délai de l’assistant de clés a expiré. Actualisez pour réessayer."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr "Impossible de terminer l’opération sur la clé. Actualisez et réessayez."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The passphrases do not match. Enter them again."
+msgstr "Les phrases secrètes ne correspondent pas. Saisissez-les à nouveau."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr "Ce fichier et son fichier .pub correspondant seront déplacés vers la corbeille. Les autres copies resteront à leur emplacement. Les références dans la configuration SSH et les serveurs peuvent encore nécessiter cette clé."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Unsafe permissions"
+msgstr "Permissions non sûres"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr "Utilisez au plus 512 octets sans saut de ligne ni caractère de contrôle."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Weak algorithm or key size"
+msgstr "Algorithme ou taille de clé faible"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Your SSH keys, public identities and passphrases."
+msgstr "Vos clés SSH, identités publiques et phrases secrètes."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "copy public permissions label comment delete trash"
+msgstr "copier publique permissions libellé commentaire supprimer corbeille"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "generate ed25519 passphrase"
+msgstr "générer ed25519 phrase secrète"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr "ssh sécurité publique privée identité empreinte phrase secrète"
+
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr "GPU"
diff --git a/po/pt_BR.po b/po/pt_BR.po
index 7f78a31..3b2639b 100644
--- a/po/pt_BR.po
+++ b/po/pt_BR.po
@@ -1371,10 +1371,6 @@ msgstr "Não foi possível aplicar a opção da impressora."
msgid "Could not apply this choice. Please try again."
msgstr "Não foi possível aplicar esta opção. Tente novamente."
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr "Não foi possível criar a solicitação."
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr "Não foi possível alterar as permissões"
@@ -7732,3 +7728,283 @@ msgstr ""
#: src/control_center/search_index.zig
msgid "mouse touchpad trackball default custom inherit"
msgstr ""
+
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "A file already exists at that location. Choose another name."
+msgstr "Já existe um arquivo nesse local. Escolha outro nome."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr "Uma frase secreta vazia deixa a chave privada sem criptografia."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Back to SSH keys"
+msgstr "Voltar às chaves SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase"
+msgstr "Alterar frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase…"
+msgstr "Alterar frase secreta…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Comment"
+msgstr "Comentário"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Confirm passphrase"
+msgstr "Confirmar frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Copy public key"
+msgstr "Copiar chave pública"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys."
+msgstr "Não foi possível iniciar o auxiliar de chaves."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not start the key operation."
+msgstr "Não foi possível iniciar a operação da chave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Current passphrase"
+msgstr "Frase secreta atual"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit comment…"
+msgstr "Editar comentário…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit label…"
+msgstr "Editar rótulo…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Enter a filename without slashes or a leading dot."
+msgstr "Digite um nome de arquivo sem barras nem ponto inicial."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Filename in ~/.ssh"
+msgstr "Nome do arquivo em ~/.ssh"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Fix permissions"
+msgstr "Corrigir permissões"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Generate key"
+msgstr "Gerar chave"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install OpenSSH to generate or change keys."
+msgstr "Instale o OpenSSH para gerar ou alterar chaves."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install gio to move keys to Trash."
+msgstr "Instale o gio para mover chaves para a lixeira."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Keys & Certificates"
+msgstr "Chaves e certificados"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Label"
+msgstr "Rótulo"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr "Os rótulos se aplicam a todas as cópias desta impressão digital pública."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr "Gerencie as chaves do usuário atual em ~/.ssh."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Missing .pub file"
+msgstr "Arquivo .pub ausente"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move this key to Trash?"
+msgstr "Mover esta chave para a lixeira?"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move to Trash…"
+msgstr "Mover para a lixeira…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New Ed25519 key"
+msgstr "Nova chave Ed25519"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New SSH key"
+msgstr "Nova chave SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New key…"
+msgstr "Nova chave…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase"
+msgstr "Nova frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase (optional)"
+msgstr "Nova frase secreta (opcional)"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No passphrase"
+msgstr "Sem frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No supported SSH keys found."
+msgstr "Nenhuma chave SSH compatível encontrada."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Passphrase protected"
+msgstr "Protegida por frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public file does not match"
+msgstr "O arquivo público não corresponde"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key copied."
+msgstr "Chave pública copiada."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key only"
+msgstr "Somente chave pública"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Recreate missing .pub file"
+msgstr "Recriar arquivo .pub ausente"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "SSH keys"
+msgstr "Chaves SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr "Alguns arquivos foram ignorados: incompatíveis, ilegíveis, muito grandes ou inseguros para abrir."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr "O diretório .ssh está acessível a outros usuários. Corrija as permissões nos detalhes de uma chave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr "A chave mudou desde que foi selecionada. Atualize e tente novamente."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key could not be changed. Check the current passphrase."
+msgstr "Não foi possível alterar a chave. Verifique a frase secreta atual."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr "O auxiliar de chaves falhou. Atualize para tentar novamente."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr "O tempo do auxiliar de chaves se esgotou. Atualize para tentar novamente."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr "Não foi possível concluir a operação da chave. Atualize e tente novamente."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The passphrases do not match. Enter them again."
+msgstr "As frases secretas não coincidem. Digite-as novamente."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr "Este local e seu arquivo .pub correspondente serão movidos para a lixeira. As outras cópias permanecerão onde estão. Referências na configuração SSH e nos servidores ainda podem precisar desta chave."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Unsafe permissions"
+msgstr "Permissões inseguras"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr "Use no máximo 512 bytes sem quebras de linha nem caracteres de controle."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Weak algorithm or key size"
+msgstr "Algoritmo ou tamanho de chave fraco"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Your SSH keys, public identities and passphrases."
+msgstr "Suas chaves SSH, identidades públicas e frases secretas."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "copy public permissions label comment delete trash"
+msgstr "copiar pública permissões rótulo comentário excluir lixeira"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "generate ed25519 passphrase"
+msgstr "gerar ed25519 frase secreta"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr "ssh segurança pública privada identidade impressão digital frase secreta"
+
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr "GPU"
diff --git a/po/rediwm.pot b/po/rediwm.pot
index 965718e..7e95b67 100644
--- a/po/rediwm.pot
+++ b/po/rediwm.pot
@@ -127,6 +127,10 @@ msgstr ""
msgid "A USB character device is not applicable to this connection."
msgstr ""
+#: src/control_center/sections/keys.zig
+msgid "A file already exists at that location. Choose another name."
+msgstr ""
+
#: src/files/app_opening.zig
msgid "A file operation is already running"
msgstr ""
@@ -331,6 +335,10 @@ msgstr ""
msgid "An application is already being added"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr ""
+
#: src/control_center/sections/services.zig
msgid "Analyze"
msgstr ""
@@ -619,6 +627,10 @@ msgstr ""
msgid "Back"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Back to SSH keys"
+msgstr ""
+
#: src/files/open_with.zig
msgid "Back to recommended apps"
msgstr ""
@@ -1035,6 +1047,14 @@ msgstr ""
msgid "Change connection…"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Change passphrase"
+msgstr ""
+
+#: src/control_center/sections/keys_details.zig
+msgid "Change passphrase…"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Change password · {name}"
msgstr ""
@@ -1363,6 +1383,10 @@ msgstr ""
msgid "Colour: {colour}"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Comment"
+msgstr ""
+
#: src/files/app_torrent_rows.zig
msgid "Complete"
msgstr ""
@@ -1407,6 +1431,10 @@ msgstr ""
msgid "Confirm new password"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Confirm passphrase"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Confirm password"
msgstr ""
@@ -1501,6 +1529,10 @@ msgstr ""
msgid "Copy diagnostic report"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Copy public key"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "Corner radius"
msgstr ""
@@ -1545,10 +1577,6 @@ msgstr ""
msgid "Could not apply this choice. Please try again."
msgstr ""
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr ""
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr ""
@@ -1597,6 +1625,14 @@ msgstr ""
msgid "Could not forget the connection."
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Could not load SSH keys."
+msgstr ""
+
+#: src/control_center/sections/keys_ssh.zig
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr ""
+
#: src/files/app_dialogs.zig
msgid "Could not load applications"
msgstr ""
@@ -1909,6 +1945,10 @@ msgstr ""
msgid "Could not start the connection."
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Could not start the key operation."
+msgstr ""
+
#: src/session/power_requests.zig
msgid "Could not start the power command."
msgstr ""
@@ -1989,6 +2029,10 @@ msgstr ""
msgid "Current font"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Current passphrase"
+msgstr ""
+
#: src/control_center/sections/power.zig
msgid "Current power mode: {mode}"
msgstr ""
@@ -2475,6 +2519,14 @@ msgstr ""
msgid "Edge glow"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Edit comment…"
+msgstr ""
+
+#: src/control_center/sections/keys_details.zig
+msgid "Edit label…"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "Edit settings…"
msgstr ""
@@ -2551,6 +2603,10 @@ msgstr ""
msgid "Enter a filename or an absolute path."
msgstr ""
+#: src/control_center/sections/keys.zig
+msgid "Enter a filename without slashes or a leading dot."
+msgstr ""
+
#: src/images/app_dialogs.zig
msgid "Enter a filename."
msgstr ""
@@ -2799,6 +2855,10 @@ msgstr ""
msgid "File operation failed"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Filename in ~/.ssh"
+msgstr ""
+
#: src/dock/items.zig
msgid "Files"
msgstr ""
@@ -2875,6 +2935,10 @@ msgstr ""
msgid "Five applications already pinned"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Fix permissions"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "Fixed desktop icons"
msgstr ""
@@ -3075,6 +3139,10 @@ msgstr ""
msgid "Fully Charged"
msgstr ""
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr ""
+
#: src/control_center/sections/appearance_colors.zig
msgid "GTK colors applied. Restart GTK apps. Apps with their own styles or sandbox settings may differ."
msgstr ""
@@ -3091,6 +3159,10 @@ msgstr ""
msgid "General"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Generate key"
+msgstr ""
+
#: src/files/app_layout.zig
msgid "Git"
msgstr ""
@@ -3295,6 +3367,14 @@ msgstr ""
msgid "Install"
msgstr ""
+#: src/control_center/sections/keys.zig
+msgid "Install OpenSSH to generate or change keys."
+msgstr ""
+
+#: src/control_center/sections/keys.zig
+msgid "Install gio to move keys to Trash."
+msgstr ""
+
#: src/control_center/sections/appearance_colors.zig
msgid "Install qt5ct for Qt 5 apps or qt6ct for Qt 6 apps, then apply again."
msgstr ""
@@ -3483,6 +3563,10 @@ msgstr ""
msgid "Keyboard shortcuts"
msgstr ""
+#: src/control_center/panel.zig
+msgid "Keys & Certificates"
+msgstr ""
+
#: src/files/app_torrent_rows.zig
msgid "Known peers: {value}"
msgstr ""
@@ -3491,10 +3575,18 @@ msgstr ""
msgid "LEFT"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Label"
+msgstr ""
+
#: src/control_center/sections/printers_details.zig
msgid "Label printer and advanced test tools"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr ""
+
#: src/control_center/sections/region.zig
msgid "Language"
msgstr ""
@@ -3611,6 +3703,10 @@ msgstr ""
msgid "Loaded paper width"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr ""
+
#: src/start_menu/search.zig
msgid "Loading applications…"
msgstr ""
@@ -3631,7 +3727,7 @@ msgstr ""
msgid "Loading services…"
msgstr ""
-#: src/files/properties.zig
+#: src/control_center/sections/keys_details.zig
msgid "Location"
msgstr ""
@@ -3727,6 +3823,10 @@ msgstr ""
msgid "Manage and analyze systemd services."
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr ""
+
#: src/control_center/sections/printers_details.zig
msgid "Manage…"
msgstr ""
@@ -3843,6 +3943,10 @@ msgstr ""
msgid "Mini map position"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Missing .pub file"
+msgstr ""
+
#: src/files/app_layout.zig
msgid "Modified"
msgstr ""
@@ -3915,7 +4019,11 @@ msgstr ""
msgid "Move this image to Trash?"
msgstr ""
-#: src/delete_dialog.zig
+#: src/control_center/sections/keys_forms.zig
+msgid "Move this key to Trash?"
+msgstr ""
+
+#: src/control_center/sections/keys_forms.zig
msgid "Move to Trash"
msgstr ""
@@ -3923,6 +4031,10 @@ msgstr ""
msgid "Move to Trash?"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Move to Trash…"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Move to workspace."
msgstr ""
@@ -4043,6 +4155,10 @@ msgstr ""
msgid "New Branch"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "New Ed25519 key"
+msgstr ""
+
#: src/desktop/app_actions.zig
msgid "New File"
msgstr ""
@@ -4059,10 +4175,26 @@ msgstr ""
msgid "New Folder"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "New SSH key"
+msgstr ""
+
#: src/files/app_git_sidebar.zig
msgid "New branch"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "New key…"
+msgstr ""
+
+#: src/control_center/sections/keys_forms.zig
+msgid "New passphrase"
+msgstr ""
+
+#: src/control_center/sections/keys_forms.zig
+msgid "New passphrase (optional)"
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "New password"
msgstr ""
@@ -4207,6 +4339,10 @@ msgstr ""
msgid "No paired devices. Choose Pair New Device to get started."
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "No passphrase"
+msgstr ""
+
#: src/control_center/sections/input.zig
msgid "No pointer devices connected."
msgstr ""
@@ -4247,6 +4383,10 @@ msgstr ""
msgid "No sources available."
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "No supported SSH keys found."
+msgstr ""
+
#: src/control_center/tree.zig
msgid "No supported backlight"
msgstr ""
@@ -4667,6 +4807,10 @@ msgstr ""
msgid "Pass"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Passphrase protected"
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "Password"
msgstr ""
@@ -5083,6 +5227,18 @@ msgstr ""
msgid "Proxy"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Public file does not match"
+msgstr ""
+
+#: src/control_center/sections/keys_details.zig
+msgid "Public key copied."
+msgstr ""
+
+#: src/control_center/sections/keys_ssh.zig
+msgid "Public key only"
+msgstr ""
+
#: src/control_center/sections/shortcuts.zig
msgid "Put the computer to sleep."
msgstr ""
@@ -5207,6 +5363,10 @@ msgstr ""
msgid "Recommended Apps"
msgstr ""
+#: src/control_center/sections/keys_details.zig
+msgid "Recreate missing .pub file"
+msgstr ""
+
#: src/files/app.zig
msgid "RediWM Files"
msgstr ""
@@ -5231,7 +5391,7 @@ msgstr ""
msgid "Reduced motion"
msgstr ""
-#: src/control_center/sections/printers.zig
+#: src/control_center/sections/keys_ssh.zig
msgid "Refresh"
msgstr ""
@@ -5549,6 +5709,10 @@ msgstr ""
msgid "SOUND"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "SSH keys"
+msgstr ""
+
#: src/system_monitor/app_footer.zig
msgid "SWAP"
msgstr ""
@@ -6105,6 +6269,10 @@ msgstr ""
msgid "Some could not be restored"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr ""
+
#: src/control_center/sections/users.zig
msgid "Some groups cannot be safely shown; group changes are disabled."
msgstr ""
@@ -6485,6 +6653,10 @@ msgstr ""
msgid "That file is open in another tab. Choose a different name."
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr ""
+
#: src/files/appimage.zig
msgid "The AppImage contains more than one application launcher"
msgstr ""
@@ -6593,6 +6765,18 @@ msgstr ""
msgid "The filename is too long."
msgstr ""
+#: src/control_center/sections/keys.zig
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr ""
+
+#: src/control_center/sections/keys.zig
+msgid "The key could not be changed. Check the current passphrase."
+msgstr ""
+
+#: src/control_center/sections/keys.zig
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr ""
+
#: src/printing/ladder.zig
msgid "The last job has not completed."
msgstr ""
@@ -6629,6 +6813,10 @@ msgstr ""
msgid "The network printer did not answer."
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "The passphrases do not match. Enter them again."
+msgstr ""
+
#: src/printing/ladder.zig
msgid "The printer answered an IPP request."
msgstr ""
@@ -6781,6 +6969,10 @@ msgstr ""
msgid "This is a label printer"
msgstr ""
+#: src/control_center/sections/keys_forms.zig
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr ""
+
#: src/control_center/sections/display.zig
msgid "This output does not advertise editable display modes."
msgstr ""
@@ -7129,6 +7321,10 @@ msgstr ""
msgid "Unpin from dock"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Unsafe permissions"
+msgstr ""
+
#: src/images/app_dialogs.zig
msgid "Unsaved edits will be discarded."
msgstr ""
@@ -7193,6 +7389,10 @@ msgstr ""
msgid "Use a .png filename to save a PNG copy."
msgstr ""
+#: src/control_center/sections/keys.zig
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr ""
+
#: src/control_center/folder_picker.zig
msgid "Use folder"
msgstr ""
@@ -7317,6 +7517,10 @@ msgstr ""
msgid "Weak"
msgstr ""
+#: src/control_center/sections/keys_ssh.zig
+msgid "Weak algorithm or key size"
+msgstr ""
+
#: src/control_center/sections/region.zig
msgid "Wednesday"
msgstr ""
@@ -7445,7 +7649,7 @@ msgstr ""
msgid "Word Wrap"
msgstr ""
-#: src/images/app_dialogs.zig
+#: src/control_center/sections/keys_ssh.zig
msgid "Working…"
msgstr ""
@@ -7529,6 +7733,10 @@ msgstr ""
msgid "You're online."
msgstr ""
+#: src/control_center/panel.zig
+msgid "Your SSH keys, public identities and passphrases."
+msgstr ""
+
#: src/control_center/sections/network.zig
msgid "Your account is not allowed to change network connections."
msgstr ""
@@ -7677,6 +7885,10 @@ msgstr ""
msgid "colors colours dark light preset"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "copy public permissions label comment delete trash"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "date weekday"
msgstr ""
@@ -7749,6 +7961,10 @@ msgstr ""
msgid "gaps tiling"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "generate ed25519 passphrase"
+msgstr ""
+
#: src/files/git.zig
msgid "git switch failed"
msgstr ""
@@ -8033,6 +8249,10 @@ msgstr ""
msgid "speakers headphones sound default"
msgstr ""
+#: src/control_center/search_index.zig
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr ""
+
#: src/control_center/search_index.zig
msgid "start menu spacing"
msgstr ""
diff --git a/po/ru.po b/po/ru.po
index 0f57c16..1484e3a 100644
--- a/po/ru.po
+++ b/po/ru.po
@@ -1375,10 +1375,6 @@ msgstr "Не удалось применить параметр принтера
msgid "Could not apply this choice. Please try again."
msgstr "Не удалось применить этот выбор. Попробуйте ещё раз."
-#: src/session/power_requests.zig
-msgid "Could not build the request."
-msgstr "Не удалось сформировать запрос."
-
#: src/files/properties.zig
msgid "Could not change permissions"
msgstr "Не удалось изменить права доступа"
@@ -7749,3 +7745,283 @@ msgstr ""
#: src/control_center/search_index.zig
msgid "mouse touchpad trackball default custom inherit"
msgstr ""
+
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "A file already exists at that location. Choose another name."
+msgstr "В этом расположении уже есть файл. Выберите другое имя."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "An empty passphrase leaves the private key unencrypted."
+msgstr "Без парольной фразы закрытый ключ останется незашифрованным."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Back to SSH keys"
+msgstr "Назад к ключам SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase"
+msgstr "Изменить парольную фразу"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Change passphrase…"
+msgstr "Изменить парольную фразу…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Comment"
+msgstr "Комментарий"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Confirm passphrase"
+msgstr "Подтвердите парольную фразу"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Copy public key"
+msgstr "Копировать открытый ключ"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys."
+msgstr "Не удалось запустить помощник управления ключами."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not start the key operation."
+msgstr "Не удалось начать операцию с ключом."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Current passphrase"
+msgstr "Текущая парольная фраза"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit comment…"
+msgstr "Изменить комментарий…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Edit label…"
+msgstr "Изменить метку…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Enter a filename without slashes or a leading dot."
+msgstr "Введите имя файла без косых черт и точки в начале."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Filename in ~/.ssh"
+msgstr "Имя файла в ~/.ssh"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Fix permissions"
+msgstr "Исправить права доступа"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Generate key"
+msgstr "Создать ключ"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install OpenSSH to generate or change keys."
+msgstr "Установите OpenSSH для создания и изменения ключей."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Install gio to move keys to Trash."
+msgstr "Установите gio для перемещения ключей в корзину."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Keys & Certificates"
+msgstr "Ключи и сертификаты"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Label"
+msgstr "Метка"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Labels apply to every copy of this public fingerprint."
+msgstr "Метки применяются ко всем копиям с этим открытым отпечатком."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Manage the current user's keys in ~/.ssh."
+msgstr "Управляйте ключами текущего пользователя в ~/.ssh."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Missing .pub file"
+msgstr "Отсутствует файл .pub"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move this key to Trash?"
+msgstr "Переместить этот ключ в корзину?"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Move to Trash…"
+msgstr "Переместить в корзину…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New Ed25519 key"
+msgstr "Новый ключ Ed25519"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New SSH key"
+msgstr "Новый ключ SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New key…"
+msgstr "Новый ключ…"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase"
+msgstr "Новая парольная фраза"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "New passphrase (optional)"
+msgstr "Новая парольная фраза (необязательно)"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No passphrase"
+msgstr "Без парольной фразы"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "No supported SSH keys found."
+msgstr "Поддерживаемые ключи SSH не найдены."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Passphrase protected"
+msgstr "Защищён парольной фразой"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public file does not match"
+msgstr "Открытый файл не соответствует ключу"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key copied."
+msgstr "Открытый ключ скопирован."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Public key only"
+msgstr "Только открытый ключ"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Recreate missing .pub file"
+msgstr "Восстановить отсутствующий файл .pub"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "SSH keys"
+msgstr "Ключи SSH"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Some files were skipped: unsupported, unreadable, too large or unsafe to open."
+msgstr "Некоторые файлы пропущены: неподдерживаемые, недоступные для чтения, слишком большие или небезопасные для открытия."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The .ssh directory is accessible to other users. Fix permissions from a key's details."
+msgstr "Каталог .ssh доступен другим пользователям. Исправьте права доступа в сведениях о ключе."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key changed since it was selected. Refresh and try again."
+msgstr "Ключ изменился после выбора. Обновите список и повторите попытку."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key could not be changed. Check the current passphrase."
+msgstr "Не удалось изменить ключ. Проверьте текущую парольную фразу."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Could not load SSH keys. Refresh to try again."
+msgstr "Сбой помощника управления ключами. Обновите список для повторной попытки."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Loading SSH keys timed out. Refresh to try again."
+msgstr "Истекло время ожидания помощника управления ключами. Обновите список для повторной попытки."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The key operation could not be completed. Refresh and try again."
+msgstr "Не удалось завершить операцию с ключом. Обновите список и повторите попытку."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "The passphrases do not match. Enter them again."
+msgstr "Парольные фразы не совпадают. Введите их ещё раз."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."
+msgstr "Этот файл и соответствующий файл .pub будут перемещены в корзину. Остальные копии останутся на месте. Ссылки в настройках SSH и на серверах могут по-прежнему требовать этот ключ."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Unsafe permissions"
+msgstr "Небезопасные права доступа"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Use at most 512 bytes without line breaks or control characters."
+msgstr "Используйте не более 512 байт без переводов строк и управляющих символов."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Weak algorithm or key size"
+msgstr "Слабый алгоритм или размер ключа"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "Your SSH keys, public identities and passphrases."
+msgstr "Ваши ключи SSH, открытые идентификаторы и парольные фразы."
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "copy public permissions label comment delete trash"
+msgstr "копировать открытый права метка комментарий удалить корзина"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "generate ed25519 passphrase"
+msgstr "создать ed25519 парольная фраза"
+
+#. SSH settings draft; native review pending.
+#, fuzzy
+msgid "ssh security public private identity fingerprint passphrase"
+msgstr "ssh безопасность открытый закрытый идентификатор отпечаток парольная фраза"
+
+#: src/system_monitor/app_footer.zig
+msgid "GPU"
+msgstr "GPU"
diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zig
index 49e3703..28d5c1b 100644
--- a/src/config_runtime/actions.zig
+++ b/src/config_runtime/actions.zig
@@ -82,6 +82,30 @@ pub fn focusedToplevel(server: *Server) ?*Toplevel {
fn openSystemMonitor(server: *Server) void {
if (server.greeter_mode or server.locker != null or server.polkit_dialog != null) return;
+ // Remove transient input owners before focusing either the existing app
+ // or the one about to map. Releasing Alt must not accept an old switcher.
+ var keyboards = server.input.keyboards.iterator(.forward);
+ while (keyboards.next()) |keyboard| {
+ keyboard.stopRepeat();
+ keyboard.stopShellRepeat();
+ keyboard.stopSwitcherRepeat();
+ }
+ _ = server.input.shortcuts_inhibit.revoke();
+ _ = server.input.cancelDrag();
+ server.input.clearGrab();
+ server.input.pan_session = null;
+ server.screenshot_selector.cancel();
+ server.switcher.cancel();
+ server.input.window_menu.close();
+ if (server.tray) |tray| tray.closeMenu();
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| {
+ output.closeStartMenu();
+ output.closePowerMenu();
+ output.closeWifi();
+ output.closeBattery();
+ output.closeCalendar();
+ }
var it = server.world.toplevels.iterator(.forward);
while (it.next()) |top| {
if (!top.in_world or !std.mem.eql(u8, top.appId(), "rediwm-monitor")) continue;
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index 93196f2..ce024c9 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -78,6 +78,17 @@ helpers (and `panel.ControlCenter`); `sections/` one file per page.
* `sections/users_helper.zig` owns the account helper request and authorization
lifetime; `users.zig` owns the account UI.
+* **Keys & Certificates** (`sections/keys*.zig`) owns a `keys/client.zig` only
+ while selected. The unprivileged sibling `rediwm-keys` reads key files; the
+ compositor receives metadata and public keys only. The client's single
+ in-flight request has an absolute deadline and owns a child process group;
+ hide/close/lock cancels it, and idle has no worker or timer. Copy snapshots
+ into the section arena before retaining widget strings. Secret fields use
+ locked storage and requests are encoded with the secure allocator, wiped on
+ submit, cancellation, page changes and lock. Never put a passphrase in tool
+ argv, environment, a section arena or logs. See `docs/plans/keys-certificates.md`
+ for the currently supported SSH formats and the later agent/certificate phases.
+
## Network page
* **The page is `sections/network*.zig`:** `network.zig` (section state, the
diff --git a/src/control_center/ControlCenter.zig b/src/control_center/ControlCenter.zig
index 038f184..3126e91 100644
--- a/src/control_center/ControlCenter.zig
+++ b/src/control_center/ControlCenter.zig
@@ -153,6 +153,7 @@ network: network_section.Section = .{},
bluetooth: bluetooth_section.Section = .{},
services: services_section.Section = .{},
printers: printers_section.Section = .{},
+key_settings: @import("sections/keys.zig").Section = .{},
power_settings: @import("sections/power.zig").Section = .{},
systemd_client: ?*systemd.Client = null,
@@ -250,6 +251,7 @@ pub fn destroy(cc: *ControlCenter) void {
cc.input.arena.deinit();
cc.services.deinit();
cc.printers.deinit();
+ cc.key_settings.deinit();
if (cc.server.network) |m| m.cancelUnlock();
cc.network.deinit();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |m| m.closed();
diff --git a/src/control_center/keys.zig b/src/control_center/keys.zig
index 4c11b9b..bd7c5c2 100644
--- a/src/control_center/keys.zig
+++ b/src/control_center/keys.zig
@@ -28,6 +28,7 @@ pub fn selectSearchPage(cc: *ControlCenter, page: Page) void {
// The service list is only kept live while its page is on screen.
if (cc.page == .services and page != .services) if (cc.systemd_client) |client| client.hide();
if (cc.page == .printers and page != .printers) cc.printers.hide();
+ if (cc.page == .keys and page != .keys) cc.key_settings.hide();
if (cc.page == .network and page != .network) cc.network.clearForm();
if (cc.page == .bluetooth and page != .bluetooth) {
if (cc.server.bluetooth) |m| m.closed();
@@ -83,7 +84,7 @@ pub fn focusSearch(cc: *ControlCenter) void {
pub fn selectKey(cc: *ControlCenter, key: ui.input.Key, shift: bool) bool {
if (settings_search.key(cc, key, shift)) return true;
- if (cc.page != .input and cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .printers and cc.page != .network and cc.page != .bluetooth and cc.page != .region and cc.page != .power) return false;
+ if (cc.page != .input and cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .printers and cc.page != .network and cc.page != .bluetooth and cc.page != .region and cc.page != .power and cc.page != .keys) return false;
const dispatcher = &ui.input.current;
if (cc.page == .appearance) {
if (appearance_section.itemKey(&cc.appearance, key)) return true;
@@ -100,8 +101,12 @@ pub fn selectKey(cc: *ControlCenter, key: ui.input.Key, shift: bool) bool {
}
}
}
- if (cc.is_welcome or cc.page == .input or cc.page == .users or cc.page == .services or cc.page == .printers or cc.page == .network or cc.page == .bluetooth or cc.page == .region or cc.page == .power) {
+ if (cc.is_welcome or cc.page == .input or cc.page == .users or cc.page == .services or cc.page == .printers or cc.page == .network or cc.page == .bluetooth or cc.page == .region or cc.page == .power or cc.page == .keys) {
const focused = dispatcher.focused;
+ if (cc.page == .keys and key == .escape and cc.key_settings.form != .none) {
+ @import("sections/keys.zig").cancel(cc, 0);
+ return true;
+ }
if (cc.page == .bluetooth and bluetooth_section.key(cc, key)) return true;
if (cc.page == .network and (focused == null or focused.?.kind != .select or !focused.?.kind.select.open)) {
if (network_section.key(cc, key)) return true;
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 702ad49..02a7abd 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -51,7 +51,7 @@ pub const default_height = 640;
const theme = @import("ui").theme;
pub const Page = @import("search_index.zig").Page;
-pub const page_labels = [_]i18n.Message{ i18n.msg("General"), i18n.msg("Input"), i18n.msg("Displays"), i18n.msg("Audio"), i18n.msg("Network"), i18n.msg("Appearance"), i18n.msg("Keyboard Shortcuts"), i18n.msg("Desktop"), i18n.msg("Bluetooth"), i18n.msg("Region & Language"), i18n.msg("Users"), i18n.msg("Printers"), i18n.msg("Services"), i18n.msg("Power & Battery") };
+pub const page_labels = [_]i18n.Message{ i18n.msg("General"), i18n.msg("Input"), i18n.msg("Displays"), i18n.msg("Audio"), i18n.msg("Network"), i18n.msg("Appearance"), i18n.msg("Keyboard Shortcuts"), i18n.msg("Desktop"), i18n.msg("Bluetooth"), i18n.msg("Region & Language"), i18n.msg("Users"), i18n.msg("Printers"), i18n.msg("Services"), i18n.msg("Power & Battery"), i18n.msg("Keys & Certificates") };
/// Refreshed when a page rebuilds; storage outlives retained widget trees.
/// Each comptime descriptor list owns its own stable slice.
pub fn translatedLabels(comptime messages: []const i18n.Message) []const []const u8 {
@@ -74,7 +74,7 @@ pub fn pageLabel(id: usize) []const u8 {
return page_labels[id].get();
}
-pub const page_names = [_][]const u8{ "general", "input", "displays", "audio", "network", "appearance", "shortcuts", "desktop", "bluetooth", "region", "users", "printers", "services", "power" };
+pub const page_names = [_][]const u8{ "general", "input", "displays", "audio", "network", "appearance", "shortcuts", "desktop", "bluetooth", "region", "users", "printers", "services", "power", "keys" };
pub const page_descriptions = [_]i18n.Message{
i18n.msg("Everyday controls, all in one place."), i18n.msg("Make your mouse and keyboard feel right."),
i18n.msg("Arrangement, resolution, refresh rate and scaling."), i18n.msg("Volume, microphones and output devices."),
@@ -83,8 +83,9 @@ pub const page_descriptions = [_]i18n.Message{
i18n.msg("Connect and manage your Bluetooth devices."), i18n.msg("Your language, regional formats and calendar preferences."),
i18n.msg("Review login accounts and automatic-login settings."), i18n.msg("Printer status, jobs and connection diagnostics."),
i18n.msg("Manage and analyze systemd services."), i18n.msg("Screen, sleep and power-source preferences."),
+ i18n.msg("Your SSH keys, public identities and passphrases."),
};
-pub const page_icons = [_]layout.IconId{ .settings, .mouse, .display, .music, .wifi, .settings, .keyboard, .squares, .bluetooth, .globe, .users, .print, .settings, .battery };
+pub const page_icons = [_]layout.IconId{ .settings, .mouse, .display, .music, .wifi, .settings, .keyboard, .squares, .bluetooth, .globe, .users, .print, .settings, .battery, .lock };
pub const max_devices = 16;
pub fn palette() theme.Theme {
diff --git a/src/control_center/relayout.zig b/src/control_center/relayout.zig
index fb154fb..e07323e 100644
--- a/src/control_center/relayout.zig
+++ b/src/control_center/relayout.zig
@@ -162,6 +162,7 @@ pub fn layoutContent(cc: *ControlCenter) void {
if (cc.page == .network) network_section.restoreFocus(&cc.network, cc);
if (cc.page == .bluetooth) bluetooth_section.restoreFocus(&cc.bluetooth, cc);
if (cc.page == .printers) cc.printers.restoreFocus(cc);
+ if (cc.page == .keys) cc.key_settings.restoreFocus(cc);
}
settings_search.reveal(cc);
cc.dirty = true;
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index b7dde41..da29f4c 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -2,7 +2,7 @@
const std = @import("std");
const fold = @import("ui").fold;
const i18n = @import("i18n");
-pub const Page = enum { general, input, displays, audio, network, appearance, shortcuts, desktop, bluetooth, region, users, printers, services, power };
+pub const Page = enum { general, input, displays, audio, network, appearance, shortcuts, desktop, bluetooth, region, users, printers, services, power, keys };
pub const Entry = struct {
page: Page,
title: []const u8,
@@ -19,6 +19,9 @@ const SourceEntry = struct {
};
const source_entries = [_]SourceEntry{
+ .{ .page = .keys, .title = i18n.msg("Keys & Certificates"), .keywords = i18n.msg("ssh security public private identity fingerprint passphrase") },
+ .{ .page = .keys, .title = i18n.msg("New SSH key"), .target = "keys_new", .keywords = i18n.msg("generate ed25519 passphrase") },
+ .{ .page = .keys, .title = i18n.msg("SSH keys"), .target = "keys_refresh", .keywords = i18n.msg("copy public permissions label comment delete trash") },
.{ .page = .power, .title = i18n.msg("Power & Battery"), .target = "", .keywords = i18n.msg("sleep battery charging energy") },
.{ .page = .power, .title = i18n.msg("Keyboard backlight"), .target = "power_keyboard", .keywords = i18n.msg("brightness plugged battery") },
.{ .page = .power, .title = i18n.msg("Charging limit"), .target = "power_charge_limit", .keywords = i18n.msg("battery health threshold") },
diff --git a/src/control_center/sections/keys.zig b/src/control_center/sections/keys.zig
new file mode 100644
index 0000000..8a6981c
--- /dev/null
+++ b/src/control_center/sections/keys.zig
@@ -0,0 +1,160 @@
+//! SSH view state. File contents never enter the compositor: the helper
+//! publishes public identities, paths and health metadata only.
+const std = @import("std");
+const i18n = @import("i18n");
+const ui = @import("ui");
+const panel = @import("../panel.zig");
+const client = @import("../../keys/client.zig");
+const model = @import("keys").model;
+const secure = @import("../../network/secure_allocator.zig").allocator;
+const gpa = @import("../../main.zig").gpa;
+pub const W = ui.layout.Widget;
+pub const A = std.mem.Allocator;
+pub const Form = enum { none, generate, passphrase, comment, label, trash };
+pub const Field = enum { name, comment, label };
+pub const field_names = [_][]const u8{ "keys_name", "keys_comment", "keys_label" };
+const Input = struct { widget: ?*W = null, data: ?ui.layout.TextInputData = null };
+pub const Section = struct {
+ arena: std.heap.ArenaAllocator = .init(gpa),
+ root: W = undefined,
+ client: ?*client.Client = null,
+ items: []const model.Item = &.{},
+ selected: [64]u8 = undefined,
+ selected_len: usize = 0,
+ location: usize = 0,
+ form: Form = .none,
+ message: []const u8 = "",
+ fields: [field_names.len]Input = @splat(.{}),
+ old: ui.widgets.secret_input.Input = .{ .storage = @constCast(&[_]u8{}) },
+ password: ui.widgets.secret_input.Input = .{ .storage = @constCast(&[_]u8{}) },
+ confirm: ui.widgets.secret_input.Input = .{ .storage = @constCast(&[_]u8{}) },
+ focused: [64]u8 = undefined,
+ focused_len: usize = 0,
+ pub fn clearSecrets(self: *Section) void {
+ self.old.clear();
+ self.password.clear();
+ self.confirm.clear();
+ }
+ fn saveFields(self: *Section) void {
+ for (&self.fields) |*field| {
+ if (field.widget) |widget| field.data = widget.kind.text_input;
+ field.widget = null;
+ }
+ }
+ pub fn capture(self: *Section) void {
+ self.focused_len = 0;
+ if (ui.input.current.focused) |widget| if (widget.name) |name| {
+ if (std.mem.startsWith(u8, name, "keys_") and name.len <= self.focused.len) {
+ @memcpy(self.focused[0..name.len], name);
+ self.focused_len = name.len;
+ }
+ };
+ }
+ pub fn restoreFocus(self: *Section, cc: *panel.ControlCenter) void {
+ if (self.focused_len > 0) if (find(&self.root, self.focused[0..self.focused_len])) |widget| ui.input.current.focus(&cc.root, widget);
+ }
+ pub fn hide(self: *Section) void {
+ self.clearSecrets();
+ self.saveFields();
+ if (self.client) |worker| worker.destroy();
+ self.client = null;
+ self.form = .none;
+ self.focused_len = 0;
+ self.items = &.{};
+ self.message = "";
+ }
+ pub fn deinit(self: *Section) void {
+ self.hide();
+ for (self.fields) |field| if (field.data) |data| gpa.free(data.value);
+ for ([_]*ui.widgets.secret_input.Input{ &self.old, &self.password, &self.confirm }) |input| if (input.storage.len > 0) secure.free(input.storage);
+ self.arena.deinit();
+ }
+};
+fn find(root: *W, name: []const u8) ?*W {
+ if (root.name) |value| if (std.mem.eql(u8, name, value)) return root;
+ for (root.children) |*child| if (find(child, name)) |found| return found;
+ return null;
+}
+pub fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+pub fn text(value: []const u8, dim: bool) W {
+ const t = panel.palette();
+ return .{ .kind = .{ .text = .{ .content = value, .font_size = t.app_text_size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } }, .width = .{ .percent = 1 } };
+}
+pub fn group(a: A, items: []const W) !W {
+ return .{ .kind = .container, .direction = .column, .gap = 10, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };
+}
+pub fn card(a: A, items: []const W) !W {
+ return panel.card(try a.dupe(W, items));
+}
+pub fn actions(a: A, items: []const W) !W {
+ var row = try group(a, items);
+ row.direction = .row;
+ for (row.children) |*child| child.width = .{ .flex = 1 };
+ return row;
+}
+pub fn button(cc: *panel.ControlCenter, name: []const u8, label: []const u8, id: usize, disabled: bool, callback: *const fn (?*anyopaque, usize) void) W {
+ return .{ .name = name, .kind = .{ .button = .{ .label = label, .owner = cc, .id = id, .on_click = callback, .state = if (disabled) .disabled else .idle } }, .height = .{ .fixed = 34 }, .width = .{ .percent = 1 } };
+}
+pub fn chosen(self: *const Section) ?model.Item {
+ for (self.items) |item| if (std.mem.eql(u8, item.fingerprint, self.selected[0..self.selected_len])) return item;
+ return null;
+}
+pub fn location(self: *const Section, item: model.Item) model.Location {
+ return item.locations[@min(self.location, item.locations.len - 1)];
+}
+pub fn busy(self: *const Section) bool {
+ return if (self.client) |worker| worker.busy else false;
+}
+fn changed(raw: *anyopaque) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw));
+ cc.key_settings.clearSecrets();
+ cc.refresh();
+}
+pub fn build(self: *Section, cc: *panel.ControlCenter) void {
+ self.saveFields();
+ _ = self.arena.reset(.retain_capacity);
+ self.items = &.{};
+ self.root = @import("keys_ssh.zig").tree(self, cc, self.arena.allocator()) catch panel.outOfMemory();
+ const width = @max(80, @as(f32, @floatFromInt(cc.panel_box.width)) - panel.sidebarWidth(cc) - 80);
+ wrap(self.arena.allocator(), &self.root, width) catch {};
+}
+fn wrap(a: A, widget: *W, width: f32) !void {
+ const inner = @max(40, width - widget.padding.left - widget.padding.right);
+ if (widget.kind == .text and ui.measure.textNatural(widget.kind.text.content, .sans, widget.kind.text.weight, widget.kind.text.font_size).w > inner) {
+ const style = widget.kind.text;
+ const name = widget.name;
+ widget.* = try panel.paragraph(a, style.content, inner, style.font_size, style.weight < 600);
+ widget.name = name;
+ for (widget.children) |*child| child.kind.text.color = style.color;
+ return;
+ }
+ const share = if (widget.direction == .row and widget.children.len > 0) (inner - widget.gap * @as(f32, @floatFromInt(widget.children.len - 1))) / @as(f32, @floatFromInt(widget.children.len)) else inner;
+ for (widget.children) |*child| try wrap(a, child, share);
+}
+pub fn start(self: *Section, cc: *panel.ControlCenter) !void {
+ if (cc.server.greeter_mode) return error.Greeter;
+ if (self.client == null) self.client = try client.Client.create(cc.server.io, cc.server.wl_server.getEventLoop(), cc, changed);
+}
+pub fn copyInventory(self: *Section, a: A, inventory: model.Inventory) !void {
+ const items = try a.dupe(model.Item, inventory.items);
+ for (items) |*item| {
+ inline for (.{ "fingerprint", "algorithm", "public_key", "comment", "label" }) |field| @field(item, field) = try a.dupe(u8, @field(item, field));
+ const locations = try a.dupe(model.Location, item.locations);
+ for (locations) |*place| place.path = try a.dupe(u8, place.path);
+ item.locations = locations;
+ }
+ self.items = items;
+}
+pub fn failure(value: []const u8) []const u8 {
+ if (std.mem.eql(u8, value, "KeygenFailed")) return i18n.tr("The key could not be changed. Check the current passphrase.");
+ if (std.mem.eql(u8, value, "PathAlreadyExists")) return i18n.tr("A file already exists at that location. Choose another name.");
+ if (std.mem.eql(u8, value, "FileChanged")) return i18n.tr("The key changed since it was selected. Refresh and try again.");
+ if (std.mem.eql(u8, value, "InvalidPath")) return i18n.tr("Enter a filename without slashes or a leading dot.");
+ if (std.mem.eql(u8, value, "MissingKeygen")) return i18n.tr("Install OpenSSH to generate or change keys.");
+ if (std.mem.eql(u8, value, "InvalidText") or std.mem.eql(u8, value, "InvalidPassphrase")) return i18n.tr("Use at most 512 bytes without line breaks or control characters.");
+ if (std.mem.eql(u8, value, "MissingTrashTool")) return i18n.tr("Install gio to move keys to Trash.");
+ return i18n.tr("The key operation could not be completed. Refresh and try again.");
+}
+pub const cancel = @import("keys_forms.zig").cancel;
diff --git a/src/control_center/sections/keys_details.zig b/src/control_center/sections/keys_details.zig
new file mode 100644
index 0000000..8f614a8
--- /dev/null
+++ b/src/control_center/sections/keys_details.zig
@@ -0,0 +1,65 @@
+const std = @import("std");
+const i18n = @import("i18n");
+const panel = @import("../panel.zig");
+const model = @import("keys").model;
+const s = @import("keys.zig");
+const forms = @import("keys_forms.zig");
+
+pub fn build(self: *s.Section, cc: *panel.ControlCenter, a: s.A, widgets: *std.ArrayList(s.W), item: model.Item) !void {
+ const place = s.location(self, item);
+ const busy = s.busy(self);
+ const keygen = self.client.?.current.?.value.inventory.keygen;
+ const trash = self.client.?.current.?.value.inventory.trash;
+ try widgets.append(a, s.button(cc, "keys_back", i18n.tr("Back to SSH keys"), 0, busy, back));
+ try widgets.append(a, panel.sectionTitle(if (item.label.len > 0) item.label else if (item.comment.len > 0) item.comment else std.fs.path.basename(place.path)));
+ try widgets.append(a, @import("keys_ssh.zig").named(s.text(item.fingerprint, false), "keys_fingerprint"));
+ try widgets.append(a, s.text(try std.fmt.allocPrint(a, "{s} · {d}", .{ item.algorithm, item.bits }), true));
+ try widgets.append(a, s.text(try @import("keys_ssh.zig").health(a, item), false));
+ const paths = try a.alloc([]const u8, item.locations.len);
+ for (item.locations, paths) |location, *path| path.* = location.path;
+ try widgets.append(a, s.text(i18n.tr("Location"), true));
+ try widgets.append(a, .{ .name = "keys_location", .kind = .{ .select = .{ .labels = paths, .selected = @min(self.location, paths.len - 1), .disabled = busy or self.form != .none, .owner = cc, .on_change = selectLocation } }, .height = .{ .fixed = 36 }, .width = .{ .percent = 1 } });
+ try widgets.append(a, s.button(cc, "keys_copy", i18n.tr("Copy public key"), 0, busy, copy));
+ if (self.form != .none) {
+ try widgets.append(a, try forms.build(self, cc, a));
+ return;
+ }
+ try widgets.append(a, try s.group(a, &.{
+ s.button(cc, "keys_edit_label", i18n.tr("Edit label…"), @backingInt(s.Form.label), busy, forms.open),
+ s.button(cc, "keys_passphrase", i18n.tr("Change passphrase…"), @backingInt(s.Form.passphrase), busy or !place.private or !keygen, forms.open),
+ s.button(cc, "keys_edit_comment", i18n.tr("Edit comment…"), @backingInt(s.Form.comment), busy or !place.private or !keygen, forms.open),
+ s.button(cc, "keys_recreate", i18n.tr("Recreate missing .pub file"), @backingInt(@import("keys").protocol.Action.recreate_public), busy or !place.private or !place.missing_public, act),
+ s.button(cc, "keys_permissions", i18n.tr("Fix permissions"), @backingInt(@import("keys").protocol.Action.permissions), busy, act),
+ s.button(cc, "keys_delete", i18n.tr("Move to Trash…"), @backingInt(s.Form.trash), busy or !trash, forms.open),
+ }));
+ if (!trash) try widgets.append(a, s.text(i18n.tr("Install gio to move keys to Trash."), true));
+}
+fn selectLocation(raw: ?*anyopaque, _: usize, index: usize) void {
+ const cc = s.owner(raw);
+ if (s.busy(&cc.key_settings) or cc.key_settings.form != .none) return;
+ cc.key_settings.location = index;
+ cc.key_settings.message = "";
+ cc.refresh();
+}
+fn copy(raw: ?*anyopaque, _: usize) void {
+ const cc = s.owner(raw);
+ const item = s.chosen(&cc.key_settings) orelse return;
+ @import("../../clipboard.zig").copyText(cc.server, item.public_key);
+ cc.key_settings.message = i18n.tr("Public key copied.");
+ cc.refresh();
+}
+fn back(raw: ?*anyopaque, _: usize) void {
+ const cc = s.owner(raw);
+ if (s.busy(&cc.key_settings)) return;
+ cc.key_settings.clearSecrets();
+ cc.key_settings.selected_len = 0;
+ cc.key_settings.form = .none;
+ cc.key_settings.message = "";
+ cc.refresh();
+}
+fn act(raw: ?*anyopaque, id: usize) void {
+ const cc = s.owner(raw);
+ const self = &cc.key_settings;
+ const item = s.chosen(self) orelse return;
+ forms.submitRequest(cc, .{ .action = @fromBackingInt(@intCast(id)), .path = s.location(self, item).path, .fingerprint = item.fingerprint });
+}
diff --git a/src/control_center/sections/keys_forms.zig b/src/control_center/sections/keys_forms.zig
new file mode 100644
index 0000000..4ec8eee
--- /dev/null
+++ b/src/control_center/sections/keys_forms.zig
@@ -0,0 +1,162 @@
+//! Shared text/secret widgets over persistent drafts and locked secret storage.
+const std = @import("std");
+const i18n = @import("i18n");
+const ui = @import("ui");
+const panel = @import("../panel.zig");
+const protocol = @import("keys").protocol;
+const s = @import("keys.zig");
+const gpa = @import("../../main.zig").gpa;
+const secure = @import("../../network/secure_allocator.zig").allocator;
+
+pub fn open(raw: ?*anyopaque, id: usize) void {
+ const cc = s.owner(raw);
+ const self = &cc.key_settings;
+ if (s.busy(self)) return;
+ const form: s.Form = @fromBackingInt(@intCast(id));
+ const item = s.chosen(self);
+ if (form != .generate and item == null) return;
+ self.clearSecrets();
+ self.message = "";
+ switch (form) {
+ .generate => {
+ setField(self, .name, "id_ed25519") catch return;
+ setField(self, .comment, "") catch return;
+ },
+ .comment => setField(self, .comment, item.?.comment) catch return,
+ .label => setField(self, .label, item.?.label) catch return,
+ else => {},
+ }
+ self.form = form;
+ cc.refresh();
+}
+pub fn cancel(raw: ?*anyopaque, _: usize) void {
+ const cc = s.owner(raw);
+ cc.key_settings.clearSecrets();
+ cc.key_settings.form = .none;
+ cc.key_settings.message = "";
+ cc.refresh();
+}
+fn secret(input: *ui.widgets.secret_input.Input, name: []const u8, placeholder: []const u8) !s.W {
+ if (input.storage.len == 0) {
+ input.storage = try secure.alloc(u8, 1024);
+ @memset(input.storage, 0);
+ }
+ return .{ .name = name, .kind = .{ .secret_input = .{ .placeholder = placeholder, .input = input } }, .height = .{ .fixed = 36 }, .width = .{ .percent = 1 } };
+}
+pub fn build(self: *s.Section, cc: *panel.ControlCenter, a: s.A) !s.W {
+ var widgets: std.ArrayList(s.W) = .empty;
+ const item = s.chosen(self);
+ const encrypted = if (item) |key| s.location(self, key).encrypted else false;
+ switch (self.form) {
+ .generate => {
+ try widgets.append(a, panel.sectionTitle(i18n.tr("New Ed25519 key")));
+ try widgets.append(a, try entry(self, cc, a, .name, i18n.tr("Filename in ~/.ssh")));
+ try widgets.append(a, try entry(self, cc, a, .comment, i18n.tr("Comment")));
+ },
+ .passphrase => try widgets.append(a, panel.sectionTitle(i18n.tr("Change passphrase"))),
+ .comment => try widgets.append(a, try entry(self, cc, a, .comment, i18n.tr("Comment"))),
+ .label => {
+ try widgets.append(a, try entry(self, cc, a, .label, i18n.tr("Label")));
+ try widgets.append(a, s.text(i18n.tr("Labels apply to every copy of this public fingerprint."), true));
+ },
+ .trash => {
+ try widgets.append(a, panel.sectionTitle(i18n.tr("Move this key to Trash?")));
+ try widgets.append(a, s.text(item.?.fingerprint, false));
+ try widgets.append(a, try panel.paragraph(a, s.location(self, item.?).path, 420, panel.palette().app_text_size, true));
+ try widgets.append(a, try panel.paragraph(a, i18n.tr("This location and its matching .pub file will move to Trash. Other copies stay where they are. References in SSH configuration and servers may still need this key."), 420, panel.palette().app_text_size, true));
+ },
+ .none => {},
+ }
+ if ((self.form == .passphrase or self.form == .comment) and encrypted) {
+ try widgets.append(a, s.text(i18n.tr("Current passphrase"), true));
+ try widgets.append(a, try secret(&self.old, "keys_old_passphrase", i18n.tr("Current passphrase")));
+ }
+ if (self.form == .generate or self.form == .passphrase) {
+ try widgets.append(a, s.text(i18n.tr("New passphrase (optional)"), true));
+ try widgets.append(a, try secret(&self.password, "keys_new_passphrase", i18n.tr("New passphrase")));
+ try widgets.append(a, s.text(i18n.tr("Confirm passphrase"), true));
+ try widgets.append(a, try secret(&self.confirm, "keys_confirm_passphrase", i18n.tr("Confirm passphrase")));
+ try widgets.append(a, s.text(i18n.tr("An empty passphrase leaves the private key unencrypted."), true));
+ }
+ try widgets.append(a, try s.actions(a, &.{
+ s.button(cc, "keys_submit", if (self.form == .generate) i18n.tr("Generate key") else if (self.form == .trash) i18n.tr("Move to Trash") else i18n.tr("Save"), 0, s.busy(self), submit),
+ s.button(cc, "keys_cancel", i18n.tr("Cancel"), 0, false, cancel),
+ }));
+ return s.card(a, widgets.items);
+}
+fn submit(raw: ?*anyopaque, _: usize) void {
+ const cc = s.owner(raw);
+ const self = &cc.key_settings;
+ if (s.busy(self)) return;
+ defer self.clearSecrets();
+ if ((self.form == .generate or self.form == .passphrase) and !std.mem.eql(u8, self.password.value(), self.confirm.value())) {
+ self.message = i18n.tr("The passphrases do not match. Enter them again.");
+ cc.refresh();
+ return;
+ }
+ var req: protocol.Request = .{ .old_passphrase = self.old.value(), .new_passphrase = self.password.value() };
+ if (self.form != .generate) {
+ const item = s.chosen(self) orelse return;
+ req.path = s.location(self, item).path;
+ req.fingerprint = item.fingerprint;
+ }
+ switch (self.form) {
+ .generate => {
+ req.action = .generate;
+ req.path = value(self, .name);
+ req.text = value(self, .comment);
+ },
+ .comment => {
+ req.action = .comment;
+ req.text = value(self, .comment);
+ },
+ .label => {
+ req.action = .label;
+ req.text = value(self, .label);
+ },
+ .passphrase => req.action = .passphrase,
+ .trash => req.action = .trash,
+ .none => return,
+ }
+ submitRequest(cc, req);
+}
+pub fn submitRequest(cc: *panel.ControlCenter, req: protocol.Request) void {
+ const self = &cc.key_settings;
+ const client = self.client orelse return;
+ client.act(req) catch {
+ self.message = i18n.tr("Could not start the key operation.");
+ cc.refresh();
+ return;
+ };
+ self.form = .none;
+ self.message = "";
+ cc.refresh();
+}
+fn value(self: *const s.Section, id: s.Field) []const u8 {
+ const field = self.fields[@backingInt(id)];
+ return if (field.widget) |widget| widget.kind.text_input.value else if (field.data) |data| data.value else "";
+}
+fn setField(self: *s.Section, id: s.Field, content: []const u8) !void {
+ const field = &self.fields[@backingInt(id)];
+ const bytes = try gpa.dupe(u8, content);
+ if (field.widget) |widget| field.data = widget.kind.text_input;
+ if (field.data) |*data| {
+ gpa.free(data.value);
+ data.value = bytes;
+ data.cursor_pos = bytes.len;
+ data.selection_anchor = null;
+ if (field.widget) |widget| widget.kind.text_input = data.*;
+ } else field.data = .{ .owner = null, .id = @backingInt(id), .placeholder = "", .value = bytes, .cursor_pos = bytes.len, .on_change = edited };
+}
+fn entry(self: *s.Section, cc: *panel.ControlCenter, a: s.A, id: s.Field, label: []const u8) !s.W {
+ const field = &self.fields[@backingInt(id)];
+ if (field.data == null) try setField(self, id, "");
+ var data = field.data.?;
+ data.owner = cc;
+ data.placeholder = label;
+ const widget: s.W = .{ .name = s.field_names[@backingInt(id)], .kind = .{ .text_input = data }, .height = .{ .fixed = 36 }, .width = .{ .percent = 1 } };
+ const row = try s.group(a, &.{ s.text(label, true), widget });
+ field.widget = &row.children[1];
+ return row;
+}
+fn edited(_: ?*anyopaque, _: usize, _: []const u8) void {}
diff --git a/src/control_center/sections/keys_ssh.zig b/src/control_center/sections/keys_ssh.zig
new file mode 100644
index 0000000..50e93c8
--- /dev/null
+++ b/src/control_center/sections/keys_ssh.zig
@@ -0,0 +1,102 @@
+//! SSH inventory and selection. Later certificate/agent phases add views here.
+const std = @import("std");
+const i18n = @import("i18n");
+const panel = @import("../panel.zig");
+const s = @import("keys.zig");
+const forms = @import("keys_forms.zig");
+const details = @import("keys_details.zig");
+pub fn tree(self: *s.Section, cc: *panel.ControlCenter, a: s.A) !s.W {
+ s.start(self, cc) catch return s.text(i18n.tr("Could not load SSH keys."), true);
+ const client = self.client.?;
+ var widgets: std.ArrayList(s.W) = .empty;
+ try widgets.append(a, panel.sectionTitle(i18n.tr("SSH keys")));
+ try widgets.append(a, s.text(i18n.tr("Manage the current user's keys in ~/.ssh."), true));
+ const keygen = if (client.current) |current| current.value.inventory.keygen else false;
+ try widgets.append(a, try s.actions(a, &.{
+ s.button(cc, "keys_new", i18n.tr("New key…"), @backingInt(s.Form.generate), client.busy or !keygen, forms.open),
+ s.button(cc, "keys_refresh", i18n.tr("Refresh"), 0, client.busy, refresh),
+ }));
+ if (!keygen and !client.busy) try widgets.append(a, s.text(i18n.tr("Install OpenSSH to generate or change keys."), true));
+ if (client.busy) try widgets.append(a, named(s.text(i18n.tr("Working…"), true), "keys_status"));
+ if (client.failure) try widgets.append(a, named(s.text(if (client.timed_out) i18n.tr("Loading SSH keys timed out. Refresh to try again.") else i18n.tr("Could not load SSH keys. Refresh to try again."), false), "keys_error"));
+ if (client.current) |current| {
+ const reply = current.value;
+ try s.copyInventory(self, a, reply.inventory);
+ if (!client.busy) if (reply.failure) |err| try widgets.append(a, named(s.text(s.failure(err), false), "keys_error"));
+ if (reply.inventory.directory_permissions) try widgets.append(a, s.text(i18n.tr("The .ssh directory is accessible to other users. Fix permissions from a key's details."), false));
+ if (reply.inventory.skipped > 0) try widgets.append(a, s.text(i18n.tr("Some files were skipped: unsupported, unreadable, too large or unsafe to open."), true));
+ }
+ if (self.message.len > 0) try widgets.append(a, named(s.text(self.message, false), "keys_message"));
+ if (self.form == .generate) {
+ try widgets.append(a, try forms.build(self, cc, a));
+ } else if (s.chosen(self)) |item| {
+ try details.build(self, cc, a, &widgets, item);
+ } else {
+ self.selected_len = 0;
+ if (self.items.len == 0 and !client.busy and !client.failure) try widgets.append(a, s.text(i18n.tr("No supported SSH keys found."), true));
+ for (self.items, 0..) |item, i| {
+ const title = if (item.label.len > 0) item.label else if (item.comment.len > 0) item.comment else std.fs.path.basename(item.locations[0].path);
+ var path = item.locations[0].path;
+ for (item.locations) |place| if (place.private) {
+ path = place.path;
+ break;
+ };
+ try widgets.append(a, try s.card(a, &.{
+ s.button(cc, try std.fmt.allocPrint(a, "keys_item_{d}", .{i}), title, i, client.busy, select),
+ s.text(try std.fmt.allocPrint(a, "~/.ssh/{s}", .{std.fs.path.basename(path)}), true),
+ s.text(try std.fmt.allocPrint(a, "{s} · {d}", .{ item.algorithm, item.bits }), true),
+ named(s.text(item.fingerprint, true), "keys_fingerprint"),
+ s.text(try health(a, item), true),
+ }));
+ }
+ }
+ return s.group(a, widgets.items);
+}
+pub fn named(widget: s.W, name: []const u8) s.W {
+ var result = widget;
+ result.name = name;
+ return result;
+}
+pub fn health(a: s.A, item: @import("keys").model.Item) ![]const u8 {
+ var parts: std.ArrayList([]const u8) = .empty;
+ var private = false;
+ var unencrypted = false;
+ var permissions = false;
+ var missing = false;
+ var mismatch = false;
+ for (item.locations) |place| {
+ private = private or place.private;
+ unencrypted = unencrypted or (place.private and !place.encrypted);
+ permissions = permissions or place.permissions;
+ missing = missing or place.missing_public;
+ mismatch = mismatch or place.mismatched_public;
+ }
+ if (private) try parts.append(a, if (unencrypted) i18n.tr("No passphrase") else i18n.tr("Passphrase protected")) else try parts.append(a, i18n.tr("Public key only"));
+ if (permissions) try parts.append(a, i18n.tr("Unsafe permissions"));
+ if (missing) try parts.append(a, i18n.tr("Missing .pub file"));
+ if (mismatch) try parts.append(a, i18n.tr("Public file does not match"));
+ if (item.weak()) try parts.append(a, i18n.tr("Weak algorithm or key size"));
+ return std.mem.join(a, " · ", parts.items);
+}
+fn refresh(raw: ?*anyopaque, _: usize) void {
+ const cc = s.owner(raw);
+ if (cc.key_settings.client) |client| client.act(.{}) catch {};
+ cc.key_settings.message = "";
+ cc.refresh();
+}
+fn select(raw: ?*anyopaque, id: usize) void {
+ const cc = s.owner(raw);
+ const self = &cc.key_settings;
+ if (id >= self.items.len or s.busy(self)) return;
+ const item = self.items[id];
+ self.selected_len = item.fingerprint.len;
+ @memcpy(self.selected[0..self.selected_len], item.fingerprint);
+ self.location = 0;
+ for (item.locations, 0..) |place, i| if (place.private) {
+ self.location = i;
+ break;
+ };
+ self.message = "";
+ self.form = .none;
+ cc.refresh();
+}
diff --git a/src/control_center/sections/users.zig b/src/control_center/sections/users.zig
index c0a1d6f..6b829b6 100644
--- a/src/control_center/sections/users.zig
+++ b/src/control_center/sections/users.zig
@@ -116,6 +116,8 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
}
rows[count] = actionButton(cc, i18n.tr("Add user…"), 0, addUserClicked, !s.unlocked or s.auth != null or s.form != .none);
count += 1;
+ rows[count] = .{ .name = "users_keys", .kind = .{ .button = .{ .label = i18n.tr("Keys & Certificates"), .owner = cc, .id = @intFromEnum(panel.Page.keys), .on_click = panel.pageClicked } }, .height = .{ .fixed = 34 } };
+ count += 1;
switch (s.form) {
.add => {
rows[count] = try buildAddForm(s, cc, a);
diff --git a/src/control_center/tree.zig b/src/control_center/tree.zig
index 8ae40ff..7de9e9c 100644
--- a/src/control_center/tree.zig
+++ b/src/control_center/tree.zig
@@ -67,6 +67,7 @@ pub fn buildTree(cc: *ControlCenter) void {
cc.shortcuts.cancel();
if (cc.page == .services) if (cc.systemd_client) |client| client.hide();
if (cc.page == .printers) cc.printers.hide();
+ if (cc.page == .keys) cc.key_settings.hide();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |manager| manager.closed();
} else {
cc.search.restore_scroll = true;
@@ -77,6 +78,7 @@ pub fn buildTree(cc: *ControlCenter) void {
if (cc.page == .bluetooth and cc.built_page == .bluetooth) cc.bluetooth.capture();
if (cc.page == .network and cc.built_page == .network) cc.network.captureFocus();
if (cc.page == .printers and cc.built_page == .printers) cc.printers.capture();
+ if (cc.page == .keys and cc.built_page == .keys) cc.key_settings.capture();
if (cc.page == .appearance) appearance_section.captureItemFocus(&cc.appearance);
ui.input.reset();
const has_services = if (cc.systemd_client) |client| client.available() else false;
@@ -155,6 +157,10 @@ pub fn buildTree(cc: *ControlCenter) void {
}
if (cc.search.unavailable) cc.append(label(i18n.tr("This setting is unavailable on this device or in the current mode."), t.settings_description_size, true));
switch (cc.page) {
+ .keys => {
+ @import("sections/keys.zig").build(&cc.key_settings, cc);
+ cc.append(cc.key_settings.root);
+ },
.power => {
@import("sections/power.zig").build(&cc.power_settings, cc);
cc.append(cc.power_settings.root);
diff --git a/src/input/AGENTS.md b/src/input/AGENTS.md
index 6b6c92a..0c71b37 100644
--- a/src/input/AGENTS.md
+++ b/src/input/AGENTS.md
@@ -25,7 +25,9 @@
`candidate`. `sendDeactivated` destroys oneshots synchronously: clear
`active` first.
* **Shortcuts inhibit** gates only the switcher, screenshot shortcuts and
- final dispatch; hardware keys, VT switching and open panels still win.
+ final dispatch; hardware keys, VT switching, System Monitor and open panels
+ still win. System Monitor dismisses transient input owners and revokes the
+ focused client's inhibitor; lock/auth and shortcut capture keep priority.
* **Drag dodge** (`drag_dodge.zig`) slides a file manager aside through
`Toplevel.setDodge`, a presentation-only offset added in
`applyVisualTransform`. Never fold it into `x`/`y`/`move_x` (it would grow
diff --git a/src/input/shortcuts_inhibit.zig b/src/input/shortcuts_inhibit.zig
index 9daedf1..b455dd8 100644
--- a/src/input/shortcuts_inhibit.zig
+++ b/src/input/shortcuts_inhibit.zig
@@ -8,8 +8,8 @@
//! The inhibitor on the keyboard-focused surface is granted without a prompt,
//! as sway does. While it is active compositor bindings and modifier gestures
//! (modifier-drag pan, Alt+wheel zoom) belong to the client. Hardware keys,
-//! Ctrl+Alt+F<n>, the lock screen and authentication dialogs still come
-//! first, and the `restore_shortcuts` binding (Super+Escape) revokes the
+//! Ctrl+Alt+F<n>, System Monitor, the lock screen and authentication dialogs
+//! still come first, and the `restore_shortcuts` binding (Super+Escape) revokes the
//! grant until focus leaves the surface or the client asks again, so a
//! client that also locks the pointer can never trap the user.
const wl = @import("wayland").server.wl;
diff --git a/src/keyboard/process.zig b/src/keyboard/process.zig
index 5ff791d..27570f2 100644
--- a/src/keyboard/process.zig
+++ b/src/keyboard/process.zig
@@ -156,6 +156,24 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
return;
}
+ // System Monitor is the session's escape hatch: dispatch its configured
+ // binding before overlays and client shortcut inhibitors. Lock/auth and
+ // shortcut capture above still own their input. Swallow the release even
+ // if a new overlay opens before it arrives.
+ if (state == .released and event_keycode < keyboard.shortcut_consumed.len and keyboard.shortcut_consumed[event_keycode]) {
+ keyboard.shortcut_consumed[event_keycode] = false;
+ return;
+ }
+ if (state == .pressed) {
+ for (keyboard.bindingSyms(keycode)) |sym| {
+ const action = keyboard.server.config.lookupKeybind(wlr_keyboard.getModifiers(), sym) orelse continue;
+ if (action != .open_system_monitor) continue;
+ if (event_keycode < keyboard.shortcut_consumed.len) keyboard.shortcut_consumed[event_keycode] = true;
+ keyboard.server.executeAction(action);
+ return;
+ }
+ }
+
if (event_keycode < keyboard.battery_consumed.len and state == .released and keyboard.battery_consumed[event_keycode]) {
keyboard.battery_consumed[event_keycode] = false;
return;
@@ -181,11 +199,6 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (keyboard.switcher_code == event_keycode) keyboard.stopSwitcherRepeat();
return;
}
- if (state == .released and event_keycode < keyboard.shortcut_consumed.len and keyboard.shortcut_consumed[event_keycode]) {
- keyboard.shortcut_consumed[event_keycode] = false;
- return;
- }
-
// A VM or remote desktop inhibiting shortcuts gets every binding below
// (shell panels it didn't open still take their keys) except the one
// that takes them back. Hardware keys and VT switching were handled above.
diff --git a/src/keys/client.zig b/src/keys/client.zig
new file mode 100644
index 0000000..711b200
--- /dev/null
+++ b/src/keys/client.zig
@@ -0,0 +1,144 @@
+//! Selected-page-only, event-driven helper lifetime. A single request is in
+//! flight: no refresh can overtake an action, and idle has no timer or worker.
+const std = @import("std");
+const wl = @import("wayland").server.wl;
+const c = @import("c");
+const platform = @import("platform");
+const Child = @import("../session/child.zig");
+const keys = @import("keys");
+const secure = @import("../network/secure_allocator.zig").allocator;
+const a = std.heap.c_allocator;
+
+pub const Client = struct {
+ io: std.Io,
+ loop: *wl.EventLoop,
+ owner: *anyopaque,
+ changed: *const fn (*anyopaque) void,
+ child: ?*Child = null,
+ source: ?*wl.EventSource = null,
+ timer: ?*wl.EventSource = null,
+ fd: c_int = -1,
+ bytes: std.ArrayList(u8) = .empty,
+ current: ?std.json.Parsed(keys.protocol.Reply) = null,
+ busy: bool = false,
+ failure: bool = false,
+ timed_out: bool = false,
+
+ pub fn create(io: std.Io, loop: *wl.EventLoop, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Client {
+ const self = try a.create(Client);
+ self.* = .{ .io = io, .loop = loop, .owner = owner, .changed = changed };
+ errdefer self.destroy();
+ try self.act(.{});
+ return self;
+ }
+ pub fn destroy(self: *Client) void {
+ self.cancel();
+ if (self.current) |*value| value.deinit();
+ self.bytes.deinit(a);
+ a.destroy(self);
+ }
+ pub fn cancel(self: *Client) void {
+ if (self.source) |source| source.remove();
+ self.source = null;
+ if (self.timer) |timer| timer.remove();
+ self.timer = null;
+ if (self.fd >= 0) _ = c.close(self.fd);
+ self.fd = -1;
+ if (self.child) |child| {
+ // The watch kills the process group before reaping its leader.
+ child.signal(.KILL);
+ child.detach();
+ }
+ self.child = null;
+ self.busy = false;
+ }
+ pub fn act(self: *Client, req: keys.protocol.Request) !void {
+ if (self.busy) return error.Busy;
+ const bytes = try std.json.Stringify.valueAlloc(secure, req, .{});
+ defer secure.free(bytes);
+ if (bytes.len > 16383) return error.RequestTooLarge;
+ var sockets: [2]c_int = undefined;
+ if (c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &sockets) != 0) return error.PipeFailed;
+ defer {
+ _ = c.close(sockets[0]);
+ _ = c.close(sockets[1]);
+ }
+ var path_buf: [4096]u8 = undefined;
+ const executable = platform.exe.sibling(&path_buf, "rediwm-keys") orelse return error.NoExecutable;
+ var process = try std.process.spawn(self.io, .{
+ .argv = &.{ executable, if (req.action == .scan) "scan" else "op" },
+ .stdin = .{ .file = .{ .handle = sockets[0], .flags = .{ .nonblocking = false } } },
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .pgid = 0,
+ });
+ errdefer process.kill(self.io);
+ errdefer self.cancel();
+ self.fd = process.stdout.?.handle;
+ process.stdout = null;
+ const flags = c.fcntl(self.fd, c.F_GETFL);
+ if (flags < 0 or c.fcntl(self.fd, c.F_SETFL, flags | c.O_NONBLOCK) < 0) return error.PipeFailed;
+ self.source = try self.loop.addFd(*Client, self.fd, .{ .readable = true }, readable, self);
+ self.timer = try self.loop.addTimer(*Client, timeout, self);
+ try self.timer.?.timerUpdate(45000);
+ self.child = try Child.watch(a, self.loop, process.id.?, self, exited);
+ self.child.?.kill_group = true;
+ process.id = null;
+ const sent = c.send(sockets[1], bytes.ptr, bytes.len, c.MSG_DONTWAIT | c.MSG_NOSIGNAL);
+ if (sent != bytes.len or c.shutdown(sockets[1], c.SHUT_WR) != 0) return error.RequestWriteFailed;
+ self.bytes.clearRetainingCapacity();
+ self.failure = false;
+ self.timed_out = false;
+ self.busy = true;
+ }
+ fn drain(self: *Client) void {
+ var buffer: [8192]u8 = undefined;
+ while (true) {
+ const n = c.read(self.fd, &buffer, buffer.len);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n < 0 and std.posix.errno(n) == .AGAIN) return;
+ if (n < 0) self.failure = true;
+ if (n <= 0) {
+ if (self.source) |source| source.remove();
+ self.source = null;
+ return;
+ }
+ const count: usize = @intCast(n);
+ if (self.bytes.items.len + count > keys.model.max_reply) {
+ self.failure = true;
+ self.child.?.signal(.KILL);
+ return;
+ }
+ self.bytes.appendSlice(a, buffer[0..count]) catch {
+ self.failure = true;
+ self.child.?.signal(.KILL);
+ return;
+ };
+ }
+ }
+ fn readable(_: c_int, _: wl.EventMask, self: *Client) c_int {
+ self.drain();
+ return 0;
+ }
+ fn timeout(self: *Client) c_int {
+ self.timed_out = true;
+ self.failure = true;
+ if (self.child) |child| child.signal(.KILL);
+ return 0;
+ }
+ fn exited(raw: ?*anyopaque, _: *Child, status: ?u32) void {
+ const self: *Client = @ptrCast(@alignCast(raw.?));
+ self.drain();
+ self.child = null;
+ self.cancel();
+ if (status == null or status.? != 0) self.failure = true;
+ if (!self.failure) {
+ const next = std.json.parseFromSlice(keys.protocol.Reply, a, self.bytes.items, .{ .allocate = .alloc_always, .max_value_len = 65536 }) catch null;
+ if (next) |value| {
+ if (self.current) |*previous| previous.deinit();
+ self.current = value;
+ } else self.failure = true;
+ }
+ self.changed(self.owner);
+ }
+};
diff --git a/src/keys/der.zig b/src/keys/der.zig
new file mode 100644
index 0000000..b524821
--- /dev/null
+++ b/src/keys/der.zig
@@ -0,0 +1,48 @@
+//! Bounded DER envelopes for legacy RSA metadata. No private-key arithmetic.
+const std = @import("std");
+pub const Reader = struct {
+ bytes: []const u8,
+ pub fn value(self: *Reader, tag: u8) ![]const u8 {
+ if (self.bytes.len < 2 or self.bytes[0] != tag) return error.InvalidDer;
+ var len: usize = self.bytes[1];
+ var start: usize = 2;
+ if (len & 0x80 != 0) {
+ const count = len & 0x7f;
+ if (count == 0 or count > 4 or self.bytes.len < 2 + count) return error.InvalidDer;
+ len = 0;
+ for (self.bytes[2 .. 2 + count]) |byte| len = (len << 8) | byte;
+ start += count;
+ }
+ if (len > self.bytes.len - start) return error.InvalidDer;
+ const result = self.bytes[start .. start + len];
+ self.bytes = self.bytes[start + len ..];
+ return result;
+ }
+};
+pub fn rsaPublic(a: std.mem.Allocator, raw: []const u8, pkcs8: bool) ![]const u8 {
+ var outer: Reader = .{ .bytes = raw };
+ var sequence: Reader = .{ .bytes = try outer.value(0x30) };
+ if (outer.bytes.len != 0) return error.InvalidDer;
+ if (pkcs8) {
+ if (!std.mem.eql(u8, try sequence.value(2), "\x00")) return error.InvalidDer;
+ var algorithm: Reader = .{ .bytes = try sequence.value(0x30) };
+ if (!std.mem.eql(u8, try algorithm.value(6), "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01")) return error.UnsupportedKey;
+ if (algorithm.bytes.len > 0 and (try algorithm.value(5)).len != 0) return error.InvalidDer;
+ if (algorithm.bytes.len != 0) return error.InvalidDer;
+ return rsaPublic(a, try sequence.value(4), false);
+ }
+ if (!std.mem.eql(u8, try sequence.value(2), "\x00")) return error.UnsupportedKey;
+ const modulus = try sequence.value(2);
+ const exponent = try sequence.value(2);
+ for (0..6) |_| _ = try sequence.value(2);
+ if (sequence.bytes.len != 0) return error.InvalidDer;
+ const parts = [_][]const u8{ "ssh-rsa", exponent, modulus };
+ var blob: std.ArrayList(u8) = .empty;
+ for (parts) |part| {
+ var len: [4]u8 = undefined;
+ std.mem.writeInt(u32, &len, @intCast(part.len), .big);
+ try blob.appendSlice(a, &len);
+ try blob.appendSlice(a, part);
+ }
+ return blob.toOwnedSlice(a);
+}
diff --git a/src/keys/mod.zig b/src/keys/mod.zig
new file mode 100644
index 0000000..9381c69
--- /dev/null
+++ b/src/keys/mod.zig
@@ -0,0 +1,10 @@
+//! Unprivileged key metadata and operation protocol. No compositor dependencies.
+pub const model = @import("model.zig");
+pub const openssh = @import("openssh.zig");
+pub const pem = @import("pem.zig");
+pub const scan = @import("scan.zig");
+pub const protocol = @import("protocol.zig");
+pub const ops = @import("ops.zig");
+test {
+ _ = @import("parser_tests.zig");
+}
diff --git a/src/keys/model.zig b/src/keys/model.zig
new file mode 100644
index 0000000..42dcda0
--- /dev/null
+++ b/src/keys/model.zig
@@ -0,0 +1,34 @@
+const std = @import("std");
+pub const max_file = 1 << 20;
+pub const max_reply = 4 << 20;
+pub const max_items = 1024;
+
+pub const Location = struct {
+ path: []const u8,
+ private: bool,
+ encrypted: bool = false,
+ permissions: bool = false,
+ missing_public: bool = false,
+ mismatched_public: bool = false,
+};
+pub const Item = struct {
+ fingerprint: []const u8,
+ algorithm: []const u8,
+ bits: u32,
+ public_key: []const u8,
+ comment: []const u8 = "",
+ label: []const u8 = "",
+ locations: []const Location = &.{},
+
+ pub fn weak(self: Item) bool {
+ return std.mem.eql(u8, self.algorithm, "ssh-dss") or
+ (std.mem.eql(u8, self.algorithm, "ssh-rsa") and self.bits < 2048);
+ }
+};
+pub const Inventory = struct {
+ items: []const Item = &.{},
+ skipped: usize = 0,
+ directory_permissions: bool = false,
+ keygen: bool = false,
+ trash: bool = false,
+};
diff --git a/src/keys/openssh.zig b/src/keys/openssh.zig
new file mode 100644
index 0000000..22e0901
--- /dev/null
+++ b/src/keys/openssh.zig
@@ -0,0 +1,134 @@
+//! Public wire-format parsing, including the unencrypted header in encrypted
+//! openssh-key-v1 files. Private components never leave this module.
+const std = @import("std");
+const pem = @import("pem.zig");
+const model = @import("model.zig");
+const A = std.mem.Allocator;
+pub const Parsed = struct { item: model.Item, private: bool = false, encrypted: bool = false };
+pub const Reader = struct {
+ bytes: []const u8,
+ pub fn int(self: *Reader) !u32 {
+ if (self.bytes.len < 4) return error.Truncated;
+ const value = std.mem.readInt(u32, self.bytes[0..4], .big);
+ self.bytes = self.bytes[4..];
+ return value;
+ }
+ pub fn string(self: *Reader) ![]const u8 {
+ const len = try self.int();
+ if (len > self.bytes.len) return error.Truncated;
+ const value = self.bytes[0..len];
+ self.bytes = self.bytes[len..];
+ return value;
+ }
+};
+
+fn mpBits(bytes: []const u8) !u32 {
+ if (bytes.len == 0 or bytes[0] & 0x80 != 0) return error.InvalidInteger;
+ const n = std.mem.trimStart(u8, bytes, "\x00");
+ if (n.len == 0 or n.len > 2048) return error.InvalidInteger;
+ return @intCast(n.len * 8 - @clz(n[0]));
+}
+pub fn publicBlob(a: A, blob: []const u8, comment: []const u8) !model.Item {
+ if (blob.len > 32768) return error.KeyTooLarge;
+ var r: Reader = .{ .bytes = blob };
+ const algorithm = try r.string();
+ const bits: u32 = if (std.mem.eql(u8, algorithm, "ssh-ed25519")) blk: {
+ if ((try r.string()).len != 32) return error.InvalidKey;
+ break :blk 256;
+ } else if (std.mem.eql(u8, algorithm, "ssh-rsa")) blk: {
+ _ = try mpBits(try r.string());
+ break :blk try mpBits(try r.string());
+ } else if (std.mem.eql(u8, algorithm, "ssh-dss")) blk: {
+ const n = try mpBits(try r.string());
+ for (0..3) |_| _ = try mpBits(try r.string());
+ break :blk n;
+ } else if (std.mem.startsWith(u8, algorithm, "ecdsa-sha2-")) blk: {
+ const curve = try r.string();
+ const n: u32 = if (std.mem.eql(u8, curve, "nistp256")) 256 else if (std.mem.eql(u8, curve, "nistp384")) 384 else if (std.mem.eql(u8, curve, "nistp521")) 521 else return error.UnsupportedKey;
+ if (!std.mem.eql(u8, algorithm[11..], curve)) return error.InvalidKey;
+ const point = try r.string();
+ if (point.len != 1 + 2 * ((n + 7) / 8) or point[0] != 4) return error.InvalidKey;
+ break :blk n;
+ } else return error.UnsupportedKey;
+ if (r.bytes.len != 0) return error.InvalidKey;
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(blob, &digest, .{});
+ var fp: [43]u8 = undefined;
+ _ = std.base64.standard_no_pad.Encoder.encode(&fp, &digest);
+ const b64 = try a.alloc(u8, std.base64.standard.Encoder.calcSize(blob.len));
+ defer a.free(b64);
+ _ = std.base64.standard.Encoder.encode(b64, blob);
+ // Only displayable metadata crosses the helper boundary.
+ const safe_comment = if (comment.len <= 1024 and cleanText(comment)) comment else "";
+ return .{
+ .algorithm = try a.dupe(u8, algorithm),
+ .bits = bits,
+ .fingerprint = try std.fmt.allocPrint(a, "SHA256:{s}", .{fp}),
+ .public_key = try std.fmt.allocPrint(a, "{s} {s}{s}{s}\n", .{ algorithm, b64, if (safe_comment.len > 0) " " else "", safe_comment }),
+ .comment = try a.dupe(u8, safe_comment),
+ };
+}
+pub fn cleanText(value: []const u8) bool {
+ if (!std.unicode.utf8ValidateSlice(value)) return false;
+ for (value) |ch| if (ch < 32 or ch == 127) return false;
+ return true;
+}
+pub fn publicLine(a: A, bytes: []const u8) !model.Item {
+ const line = std.mem.trim(u8, bytes, " \t\r\n");
+ if (std.mem.indexOfAny(u8, line, "\r\n") != null) return error.InvalidKey;
+ var words = std.mem.tokenizeAny(u8, line, " \t");
+ const algorithm = words.next() orelse return error.InvalidKey;
+ const b64 = words.next() orelse return error.InvalidKey;
+ const decoder = std.base64.standard.Decoder;
+ const blob = try a.alloc(u8, try decoder.calcSizeForSlice(b64));
+ defer a.free(blob);
+ try decoder.decode(blob, b64);
+ const item = try publicBlob(a, blob, std.mem.trim(u8, words.rest(), " \t"));
+ if (!std.mem.eql(u8, algorithm, item.algorithm)) return error.InvalidKey;
+ return item;
+}
+pub fn parse(a: A, bytes: []const u8) !Parsed {
+ const trimmed = std.mem.trim(u8, bytes, " \t\r\n");
+ const pkcs1 = std.mem.startsWith(u8, trimmed, "-----BEGIN RSA PRIVATE KEY-----");
+ const pkcs8 = std.mem.startsWith(u8, trimmed, "-----BEGIN PRIVATE KEY-----");
+ if (pkcs1 or pkcs8) {
+ const raw = try pem.decode(a, trimmed, if (pkcs1) "RSA PRIVATE KEY" else "PRIVATE KEY");
+ defer {
+ std.crypto.secureZero(u8, raw);
+ a.free(raw);
+ }
+ const blob = try @import("der.zig").rsaPublic(a, raw, pkcs8);
+ defer a.free(blob);
+ return .{ .item = try publicBlob(a, blob, ""), .private = true };
+ }
+ if (!std.mem.startsWith(u8, trimmed, "-----BEGIN OPENSSH PRIVATE KEY-----")) return .{ .item = try publicLine(a, trimmed) };
+ const raw = try pem.decode(a, trimmed, "OPENSSH PRIVATE KEY");
+ defer {
+ std.crypto.secureZero(u8, raw);
+ a.free(raw);
+ }
+ const magic = "openssh-key-v1\x00";
+ if (!std.mem.startsWith(u8, raw, magic)) return error.InvalidKey;
+ var r: Reader = .{ .bytes = raw[magic.len..] };
+ const cipher = try r.string();
+ const kdf = try r.string();
+ const options = try r.string();
+ const encrypted = !std.mem.eql(u8, cipher, "none");
+ if (!encrypted and (!std.mem.eql(u8, kdf, "none") or options.len != 0)) return error.InvalidKey;
+ if (encrypted and (std.mem.eql(u8, kdf, "none") or cipher.len == 0)) return error.InvalidKey;
+ if (try r.int() != 1) return error.UnsupportedKey;
+ var item = try publicBlob(a, try r.string(), "");
+ var private: Reader = .{ .bytes = try r.string() };
+ // AEAD formats carry a tag after the private string. Never interpret it.
+ if (!encrypted) {
+ const check = try private.int();
+ if (check != try private.int()) return error.InvalidKey;
+ if (!std.mem.eql(u8, try private.string(), item.algorithm)) return error.InvalidKey;
+ const count: usize = if (std.mem.eql(u8, item.algorithm, "ssh-ed25519")) 2 else if (std.mem.eql(u8, item.algorithm, "ssh-rsa")) 6 else if (std.mem.eql(u8, item.algorithm, "ssh-dss")) 5 else 3;
+ for (0..count) |_| _ = try private.string();
+ const comment = try private.string();
+ if (comment.len <= 1024 and cleanText(comment)) item.comment = try a.dupe(u8, comment);
+ for (private.bytes, 0..) |byte, i| if (byte != (i + 1) % 256) return error.InvalidKey;
+ }
+ return .{ .item = item, .private = true, .encrypted = encrypted };
+}
diff --git a/src/keys/ops.zig b/src/keys/ops.zig
new file mode 100644
index 0000000..8b1207c
--- /dev/null
+++ b/src/keys/ops.zig
@@ -0,0 +1,19 @@
+//! Fixed argv plans contain public metadata only. No shell and no -N/-P.
+const std = @import("std");
+const protocol = @import("protocol.zig");
+const openssh = @import("openssh.zig");
+pub fn validate(req: protocol.Request) !void {
+ if (req.text.len > 512 or !openssh.cleanText(req.text)) return error.InvalidText;
+ for ([_][]const u8{ req.old_passphrase, req.new_passphrase }) |secret| {
+ if (secret.len > 512 or !openssh.cleanText(secret)) return error.InvalidPassphrase;
+ }
+}
+pub fn argv(a: std.mem.Allocator, executable: []const u8, req: protocol.Request, staged: []const u8) ![]const []const u8 {
+ try validate(req);
+ return switch (req.action) {
+ .generate => try a.dupe([]const u8, &.{ executable, "-q", "-t", "ed25519", "-C", req.text, "-f", staged }),
+ .passphrase => try a.dupe([]const u8, &.{ executable, "-q", "-p", "-f", staged }),
+ .comment => try a.dupe([]const u8, &.{ executable, "-q", "-c", "-C", req.text, "-f", staged }),
+ else => error.InvalidAction,
+ };
+}
diff --git a/src/keys/parser_tests.zig b/src/keys/parser_tests.zig
new file mode 100644
index 0000000..0449ed0
--- /dev/null
+++ b/src/keys/parser_tests.zig
@@ -0,0 +1,53 @@
+const std = @import("std");
+const ssh = @import("openssh.zig");
+const ops = @import("ops.zig");
+
+test "public fingerprints are over the wire blob and malformed lengths fail" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const blob = "\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const key = try ssh.publicBlob(a, blob, "test");
+ try std.testing.expectEqualStrings("ssh-ed25519", key.algorithm);
+ const round = try ssh.publicLine(a, key.public_key);
+ try std.testing.expectEqualStrings(key.fingerprint, round.fingerprint);
+ try std.testing.expectError(error.Truncated, ssh.publicBlob(a, blob[0 .. blob.len - 1], ""));
+ try std.testing.expectError(error.InvalidKey, ssh.publicBlob(a, blob ++ "\x00", ""));
+ try std.testing.expectError(error.InvalidKey, ssh.publicLine(a, try std.fmt.allocPrint(a, "{s}{s}", .{ key.public_key, key.public_key })));
+}
+test "operation plans never carry passphrases" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const actions = @import("protocol.zig").Action;
+ for ([_]actions{ .generate, .passphrase, .comment }) |action| {
+ const argv = try ops.argv(arena.allocator(), "/bin/ssh-keygen", .{ .action = action, .text = "example", .old_passphrase = "super-secret-old", .new_passphrase = "super-secret-new" }, "/tmp/stage/key");
+ for (argv) |arg| {
+ try std.testing.expect(std.mem.indexOf(u8, arg, "super-secret") == null);
+ try std.testing.expect(!std.mem.eql(u8, arg, "-N") and !std.mem.eql(u8, arg, "-P"));
+ }
+ }
+}
+test "truncated hostile corpus never succeeds as a private key" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var rng = std.Random.DefaultPrng.init(42);
+ var bytes: [256]u8 = undefined;
+ for (0..1024) |i| {
+ rng.random().bytes(&bytes);
+ const raw = bytes[0 .. i % bytes.len];
+ if (ssh.parse(arena.allocator(), raw)) |_| return error.UnexpectedKey else |_| {}
+ var encoded: [344]u8 = undefined;
+ const b64 = std.base64.standard.Encoder.encode(&encoded, raw);
+ for ([_][]const u8{ "OPENSSH PRIVATE KEY", "RSA PRIVATE KEY", "PRIVATE KEY" }) |label| {
+ const armored = try std.fmt.allocPrint(arena.allocator(), "-----BEGIN {s}-----\n{s}\n-----END {s}-----\n", .{ label, b64, label });
+ if (ssh.parse(arena.allocator(), armored)) |_| return error.UnexpectedKey else |_| {}
+ }
+ }
+}
+test "DER rejects indefinite, overflowing and truncated lengths" {
+ const Reader = @import("der.zig").Reader;
+ for ([_][]const u8{ "\x30\x80", "\x30\x85\xff\xff\xff\xff\xff", "\x30\x84\xff\xff\xff\xff", "\x30\x03\x00" }) |bytes| {
+ var reader: Reader = .{ .bytes = bytes };
+ try std.testing.expectError(error.InvalidDer, reader.value(0x30));
+ }
+}
diff --git a/src/keys/pem.zig b/src/keys/pem.zig
new file mode 100644
index 0000000..d71f99e
--- /dev/null
+++ b/src/keys/pem.zig
@@ -0,0 +1,22 @@
+const std = @import("std");
+pub fn decode(a: std.mem.Allocator, bytes: []const u8, label: []const u8) ![]u8 {
+ const begin = try std.fmt.allocPrint(a, "-----BEGIN {s}-----", .{label});
+ defer a.free(begin);
+ const end = try std.fmt.allocPrint(a, "-----END {s}-----", .{label});
+ defer a.free(end);
+ const trimmed = std.mem.trim(u8, bytes, " \t\r\n");
+ if (!std.mem.startsWith(u8, trimmed, begin)) return error.InvalidArmor;
+ const stop = std.mem.indexOf(u8, trimmed, end) orelse return error.InvalidArmor;
+ if (std.mem.trim(u8, trimmed[stop + end.len ..], " \t\r\n").len != 0) return error.InvalidArmor;
+ var encoded: std.ArrayList(u8) = .empty;
+ defer encoded.deinit(a);
+ for (trimmed[begin.len..stop]) |ch| {
+ if (std.ascii.isWhitespace(ch)) continue;
+ try encoded.append(a, ch);
+ }
+ const decoder = std.base64.standard.Decoder;
+ const out = try a.alloc(u8, try decoder.calcSizeForSlice(encoded.items));
+ errdefer a.free(out);
+ try decoder.decode(out, encoded.items);
+ return out;
+}
diff --git a/src/keys/protocol.zig b/src/keys/protocol.zig
new file mode 100644
index 0000000..379a5db
--- /dev/null
+++ b/src/keys/protocol.zig
@@ -0,0 +1,16 @@
+const model = @import("model.zig");
+pub const Action = enum { scan, generate, passphrase, comment, label, recreate_public, permissions, trash };
+/// Only old_passphrase and new_passphrase are sensitive. Encode/decode this
+/// structure in locked memory, never an arena, argv, environment or log.
+pub const Request = struct {
+ action: Action = .scan,
+ path: []const u8 = "",
+ fingerprint: []const u8 = "",
+ text: []const u8 = "",
+ old_passphrase: []const u8 = "",
+ new_passphrase: []const u8 = "",
+};
+pub const Reply = struct {
+ inventory: model.Inventory = .{},
+ failure: ?[]const u8 = null,
+};
diff --git a/src/keys/scan.zig b/src/keys/scan.zig
new file mode 100644
index 0000000..4f56247
--- /dev/null
+++ b/src/keys/scan.zig
@@ -0,0 +1,123 @@
+//! Only regular, owned, non-symlink files directly in ~/.ssh are candidates.
+//! Names/extensions never decide whether a file contains a key.
+const std = @import("std");
+const c = @import("c");
+const model = @import("model.zig");
+const openssh = @import("openssh.zig");
+const A = std.mem.Allocator;
+pub const File = struct {
+ bytes: []u8,
+ mode: u32,
+ ino: u64,
+ dev: u64,
+ pub fn deinit(self: File, a: A) void {
+ std.crypto.secureZero(u8, self.bytes);
+ a.free(self.bytes);
+ }
+};
+pub fn read(a: A, path: []const u8) !File {
+ return readAt(a, c.AT_FDCWD, path);
+}
+pub fn readAt(a: A, directory: c_int, path: []const u8) !File {
+ const z = try a.dupeSentinel(u8, path, 0);
+ defer a.free(z);
+ const fd = c.openat(directory, z.ptr, c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW | c.O_NONBLOCK);
+ if (fd < 0) return error.UnreadableFile;
+ defer _ = c.close(fd);
+ var stat: c.struct_stat = undefined;
+ if (c.fstat(fd, &stat) != 0 or stat.st_mode & std.c.S.IFMT != std.c.S.IFREG or stat.st_uid != std.c.getuid()) return error.UnsafeFile;
+ if (stat.st_size <= 0 or stat.st_size > model.max_file) return error.FileTooLarge;
+ const bytes = try a.alloc(u8, @intCast(stat.st_size));
+ errdefer a.free(bytes);
+ var offset: usize = 0;
+ while (offset < bytes.len) {
+ const n = c.read(fd, bytes.ptr + offset, bytes.len - offset);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n <= 0) return error.FileChanged;
+ offset += @intCast(n);
+ }
+ var extra: [1]u8 = undefined;
+ if (c.read(fd, &extra, 1) != 0) return error.FileChanged;
+ return .{ .bytes = bytes, .mode = stat.st_mode, .ino = @intCast(stat.st_ino), .dev = @intCast(stat.st_dev) };
+}
+pub fn sshDir(a: A, env: std.process.Environ) ![]const u8 {
+ const home = env.getPosix("HOME") orelse return error.NoHome;
+ if (!std.fs.path.isAbsolute(home)) return error.NoHome;
+ return std.fs.path.join(a, &.{ home, ".ssh" });
+}
+pub fn validName(name: []const u8) bool {
+ if (name.len == 0 or name.len > 200 or name[0] == '.' or !openssh.cleanText(name)) return false;
+ return std.mem.indexOfAny(u8, name, "/\\\x00") == null;
+}
+/// A write target is always one plain filename in the standard directory.
+pub fn target(a: A, env: std.process.Environ, path: []const u8) ![]const u8 {
+ const dir = try sshDir(a, env);
+ if (!std.mem.eql(u8, std.fs.path.dirname(path) orelse "", dir) or !validName(std.fs.path.basename(path))) return error.InvalidPath;
+ return dir;
+}
+pub fn inventory(a: A, io: std.Io, env: std.process.Environ, opened: ?std.Io.Dir) !model.Inventory {
+ const path = try sshDir(a, env);
+ var result: model.Inventory = .{};
+ const dir = opened orelse return result;
+ var st: c.struct_stat = undefined;
+ if (c.fstat(dir.handle, &st) != 0 or st.st_uid != std.c.getuid()) return error.UnsafeDirectory;
+ result.directory_permissions = st.st_mode & 0o077 != 0;
+ var items: std.ArrayList(model.Item) = .empty;
+ var it = dir.iterate();
+ var examined: usize = 0;
+ while (try it.next(io)) |entry| {
+ examined += 1;
+ if (examined > 4096 or items.items.len >= model.max_items) {
+ result.skipped += 1;
+ break;
+ }
+ if (entry.name[0] == '.' or std.mem.eql(u8, entry.name, "config") or std.mem.startsWith(u8, entry.name, "known_hosts") or std.mem.startsWith(u8, entry.name, "authorized_keys")) continue;
+ if (entry.kind != .file or !validName(entry.name)) {
+ result.skipped += 1;
+ continue;
+ }
+ const full = try std.fs.path.join(a, &.{ path, entry.name });
+ const file = readAt(a, dir.handle, entry.name) catch {
+ result.skipped += 1;
+ continue;
+ };
+ defer file.deinit(a);
+ const parsed = openssh.parse(a, file.bytes) catch {
+ result.skipped += 1;
+ continue;
+ };
+ var location: model.Location = .{ .path = full, .private = parsed.private, .encrypted = parsed.encrypted, .permissions = parsed.private and file.mode & 0o077 != 0 };
+ if (parsed.private) {
+ const pub_path = try std.fmt.allocPrint(a, "{s}.pub", .{entry.name});
+ const public = readAt(a, dir.handle, pub_path) catch null;
+ if (public) |pub_file| {
+ defer pub_file.deinit(a);
+ const pub_item = openssh.publicLine(a, pub_file.bytes) catch null;
+ location.mismatched_public = if (pub_item) |p| !std.mem.eql(u8, p.fingerprint, parsed.item.fingerprint) else true;
+ } else location.missing_public = true;
+ }
+ var found: ?*model.Item = null;
+ for (items.items) |*item| if (std.mem.eql(u8, item.fingerprint, parsed.item.fingerprint)) {
+ found = item;
+ break;
+ };
+ if (found) |item| {
+ item.locations = try std.mem.concat(a, model.Location, &.{ item.locations, &.{location} });
+ if (!parsed.private and parsed.item.comment.len > 0) {
+ item.comment = parsed.item.comment;
+ item.public_key = parsed.item.public_key;
+ }
+ } else {
+ var item = parsed.item;
+ item.locations = try a.dupe(model.Location, &.{location});
+ try items.append(a, item);
+ }
+ }
+ std.mem.sort(model.Item, items.items, {}, struct {
+ fn less(_: void, x: model.Item, y: model.Item) bool {
+ return std.mem.lessThan(u8, x.locations[0].path, y.locations[0].path);
+ }
+ }.less);
+ result.items = try items.toOwnedSlice(a);
+ return result;
+}
diff --git a/src/keys_helper.zig b/src/keys_helper.zig
new file mode 100644
index 0000000..0c42b47
--- /dev/null
+++ b/src/keys_helper.zig
@@ -0,0 +1,234 @@
+//! Disposable helper operations. Tools see only staged files; passphrases
+//! reach askpass through an inherited pipe, never argv or environment values.
+const std = @import("std");
+const c = @import("c");
+const platform = @import("platform");
+const keys = @import("keys");
+const secure = @import("network/secure_allocator.zig").allocator;
+const Request = keys.protocol.Request;
+const A = std.mem.Allocator;
+
+pub fn writeAll(fd: c_int, bytes: []const u8) !void {
+ var offset: usize = 0;
+ while (offset < bytes.len) {
+ const n = c.write(fd, bytes.ptr + offset, bytes.len - offset);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n <= 0) return error.WriteFailed;
+ offset += @intCast(n);
+ }
+}
+fn readAll(fd: c_int, bytes: []u8) !void {
+ var offset: usize = 0;
+ while (offset < bytes.len) {
+ const n = c.read(fd, bytes.ptr + offset, bytes.len - offset);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n <= 0) return error.ReadFailed;
+ offset += @intCast(n);
+ }
+}
+pub fn askpass(env: std.process.Environ, prompt: []const u8) !void {
+ const fd = try std.fmt.parseInt(c_int, env.getPosix("REDIWM_KEYS_ASKPASS_FD") orelse return error.NoPipe, 10);
+ if (fd <= 2) return error.NoPipe;
+ var header: [9]u8 = undefined;
+ try readAll(fd, &header);
+ const old_len = std.mem.readInt(u32, header[0..4], .big);
+ const new_len = std.mem.readInt(u32, header[4..8], .big);
+ if (old_len > 512 or new_len > 512) return error.InvalidPassphrase;
+ const secrets = try secure.alloc(u8, old_len + new_len);
+ defer secure.free(secrets);
+ try readAll(fd, secrets);
+ const old = secrets[0..old_len];
+ const new = secrets[old_len..];
+ const value = if (std.mem.startsWith(u8, prompt, "Enter old passphrase")) old else if (std.mem.startsWith(u8, prompt, "Enter new passphrase") or std.mem.startsWith(u8, prompt, "Enter same passphrase")) new else if (std.mem.startsWith(u8, prompt, "Enter passphrase")) (if (header[8] == 1) new else old) else return error.UnexpectedPrompt;
+ try writeAll(1, value);
+ try writeAll(1, "\n");
+}
+
+fn tool(a: A, io: std.Io, req: Request, staged: []const u8) !void {
+ const executable = platform.tool.system(io, "ssh-keygen") orelse return error.MissingKeygen;
+ const argv = try keys.ops.argv(a, executable, req, staged);
+ var pipes: [2]c_int = undefined;
+ if (c.pipe(&pipes) != 0) return error.PipeFailed;
+ defer {
+ _ = c.close(pipes[0]);
+ if (pipes[1] >= 0) _ = c.close(pipes[1]);
+ }
+ if (c.fcntl(pipes[0], c.F_SETFD, @as(c_int, c.FD_CLOEXEC)) < 0 or c.fcntl(pipes[1], c.F_SETFD, @as(c_int, c.FD_CLOEXEC)) < 0 or c.fcntl(pipes[1], c.F_SETFL, @as(c_int, c.O_NONBLOCK)) < 0) return error.PipeFailed;
+ var header: [9]u8 = undefined;
+ std.mem.writeInt(u32, header[0..4], @intCast(req.old_passphrase.len), .big);
+ std.mem.writeInt(u32, header[4..8], @intCast(req.new_passphrase.len), .big);
+ header[8] = @intFromBool(req.action == .generate);
+ // At most 3099 bytes, with a nonblocking write end. Each askpass
+ // invocation consumes exactly one packet.
+ for (0..3) |_| {
+ try writeAll(pipes[1], &header);
+ try writeAll(pipes[1], req.old_passphrase);
+ try writeAll(pipes[1], req.new_passphrase);
+ }
+ _ = c.close(pipes[1]);
+ pipes[1] = -1;
+ var self_buf: [4096]u8 = undefined;
+ const self = platform.exe.path(&self_buf) orelse return error.NoExecutable;
+ var env = std.process.Environ.Map.init(a);
+ defer env.deinit();
+ // A minimal environment excludes agent sockets and user askpass hooks.
+ try env.put("LC_ALL", "C");
+ try env.put("SSH_ASKPASS", self);
+ try env.put("SSH_ASKPASS_REQUIRE", "force");
+ try env.put("REDIWM_KEYS_ASKPASS_FD", try std.fmt.allocPrint(a, "{d}", .{pipes[0]}));
+ const file: std.Io.File = .{ .handle = pipes[0], .flags = .{ .nonblocking = false } };
+ var child = try std.process.spawn(io, .{ .argv = argv, .environ_map = &env, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, .inherit_files = &.{file} });
+ defer child.kill(io);
+ const term = try child.wait(io);
+ if (term != .exited or term.exited != 0) return error.KeygenFailed;
+}
+pub fn dataDir(a: A, env: std.process.Environ) ![]const u8 {
+ const data = env.getPosix("XDG_DATA_HOME") orelse try std.fs.path.join(a, &.{ env.getPosix("HOME") orelse return error.NoHome, ".local/share" });
+ if (!std.fs.path.isAbsolute(data)) return error.InvalidPath;
+ return std.fs.path.join(a, &.{ data, "rediwm/keys" });
+}
+const Label = struct { fingerprint: []const u8, label: []const u8 };
+pub fn indexPath(a: A, env: std.process.Environ) ![]const u8 {
+ return std.fs.path.join(a, &.{ try dataDir(a, env), "index.json" });
+}
+fn labels(a: A, env: std.process.Environ) ![]const Label {
+ const path = try indexPath(a, env);
+ const file = keys.scan.read(a, path) catch return &.{};
+ defer file.deinit(a);
+ return (try std.json.parseFromSlice([]const Label, a, file.bytes, .{ .allocate = .alloc_always, .max_value_len = 1024 })).value;
+}
+pub fn applyLabels(a: A, bytes: []const u8, inventory: *keys.model.Inventory) !void {
+ const index = (std.json.parseFromSlice([]const Label, a, bytes, .{ .allocate = .alloc_always, .max_value_len = 1024 }) catch return).value;
+ for (@constCast(inventory.items)) |*item| for (index) |entry| {
+ if (std.mem.eql(u8, item.fingerprint, entry.fingerprint) and entry.label.len <= 512 and keys.openssh.cleanText(entry.label)) item.label = entry.label;
+ };
+}
+fn saveLabel(a: A, io: std.Io, env: std.process.Environ, req: Request) !void {
+ const directory = try dataDir(a, env);
+ try std.Io.Dir.cwd().createDirPath(io, directory);
+ const dz = try a.dupeSentinel(u8, directory, 0);
+ if (c.chmod(dz.ptr, 0o700) != 0) return error.WriteFailed;
+ const old = try labels(a, env);
+ var entries: std.ArrayList(Label) = .empty;
+ for (old) |entry| if (!std.mem.eql(u8, entry.fingerprint, req.fingerprint)) try entries.append(a, entry);
+ if (req.text.len > 0) try entries.append(a, .{ .fingerprint = req.fingerprint, .label = req.text });
+ const bytes = try std.json.Stringify.valueAlloc(a, entries.items, .{});
+ const temp = try std.fmt.allocPrintSentinel(a, "{s}/.index-XXXXXX", .{directory}, 0);
+ const fd = c.mkstemp(temp.ptr);
+ if (fd < 0) return error.WriteFailed;
+ defer _ = c.close(fd);
+ defer _ = c.unlink(temp.ptr);
+ try writeAll(fd, bytes);
+ if (c.fsync(fd) != 0) return error.WriteFailed;
+ const final = try std.fmt.allocPrintSentinel(a, "{s}/index.json", .{directory}, 0);
+ if (c.rename(temp.ptr, final.ptr) != 0) return error.WriteFailed;
+}
+fn writeNew(a: A, path: []const u8, bytes: []const u8, mode: c.mode_t) !void {
+ const z = try a.dupeSentinel(u8, path, 0);
+ const fd = c.open(z.ptr, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_CLOEXEC | c.O_NOFOLLOW, mode);
+ if (fd < 0) return error.PathAlreadyExists;
+ defer _ = c.close(fd);
+ errdefer _ = c.unlink(z.ptr);
+ try writeAll(fd, bytes);
+ if (c.fsync(fd) != 0) return error.WriteFailed;
+}
+fn unchanged(a: A, path: []const u8, original: keys.scan.File) !void {
+ const current = try keys.scan.read(a, path);
+ defer current.deinit(a);
+ if (current.ino != original.ino or current.dev != original.dev or !std.mem.eql(u8, current.bytes, original.bytes)) return error.FileChanged;
+}
+pub fn perform(a: A, io: std.Io, env: std.process.Environ, req: Request) !void {
+ try keys.ops.validate(req);
+ if (req.action == .scan) return;
+ const directory = if (req.action == .generate) blk: {
+ if (!keys.scan.validName(req.path) or std.mem.endsWith(u8, req.path, ".pub")) return error.InvalidPath;
+ break :blk try keys.scan.sshDir(a, env);
+ } else try keys.scan.target(a, env, req.path);
+ if (req.action == .generate) try std.Io.Dir.cwd().createDirPath(io, directory);
+ // Reject a symlinked standard directory before any write.
+ var dir = try std.Io.Dir.cwd().openDir(io, directory, .{ .iterate = true, .follow_symlinks = false });
+ defer dir.close(io);
+ var stat: c.struct_stat = undefined;
+ if (c.fstat(dir.handle, &stat) != 0 or stat.st_uid != std.c.getuid()) return error.UnsafeDirectory;
+ const path = if (req.action == .generate) try std.fs.path.join(a, &.{ directory, req.path }) else req.path;
+ const original = if (req.action == .generate) null else try keys.scan.read(a, path);
+ defer if (original) |file| file.deinit(a);
+ const parsed = if (original) |file| try keys.openssh.parse(a, file.bytes) else null;
+ if (parsed) |key| if (!std.mem.eql(u8, key.item.fingerprint, req.fingerprint)) return error.FileChanged;
+ if (req.action == .label) return saveLabel(a, io, env, req);
+ if (req.action == .recreate_public) {
+ if (!parsed.?.private) return error.InvalidAction;
+ return writeNew(a, try std.fmt.allocPrint(a, "{s}.pub", .{path}), parsed.?.item.public_key, 0o644);
+ }
+ if (req.action == .permissions) {
+ const z = try a.dupeSentinel(u8, path, 0);
+ const fd = c.open(z.ptr, c.O_RDONLY | c.O_NOFOLLOW | c.O_CLOEXEC | c.O_NONBLOCK);
+ if (fd < 0) return error.UnreadableFile;
+ defer _ = c.close(fd);
+ if (c.fstat(fd, &stat) != 0 or stat.st_ino != original.?.ino or stat.st_dev != original.?.dev) return error.FileChanged;
+ if (c.fchmod(fd, @as(c.mode_t, if (parsed.?.private) 0o600 else 0o644)) != 0 or c.fchmod(dir.handle, 0o700) != 0) return error.WriteFailed;
+ return;
+ }
+ if (req.action == .trash) {
+ const gio = platform.tool.system(io, "gio") orelse return error.MissingTrashTool;
+ var argv: std.ArrayList([]const u8) = .empty;
+ try argv.appendSlice(a, &.{ gio, "trash", "--", path });
+ // Only trash the companion when it still belongs to this identity.
+ if (parsed.?.private) {
+ const public = try std.fmt.allocPrint(a, "{s}.pub", .{path});
+ if (keys.scan.read(a, public)) |file| {
+ defer file.deinit(a);
+ const pub_key = keys.openssh.publicLine(a, file.bytes) catch null;
+ if (pub_key) |key| if (std.mem.eql(u8, key.fingerprint, req.fingerprint)) try argv.append(a, public);
+ } else |_| {}
+ }
+ try unchanged(a, path, original.?);
+ const result = try std.process.run(a, io, .{ .argv = argv.items, .stdout_limit = .limited(4096), .stderr_limit = .limited(4096), .timeout = .{ .duration = .{ .raw = .fromSeconds(10), .clock = .awake } } });
+ if (result.term != .exited or result.term.exited != 0) return error.TrashFailed;
+ return;
+ }
+ if (parsed) |key| if (!key.private) return error.InvalidAction;
+ if (c.fchmod(dir.handle, 0o700) != 0) return error.WriteFailed;
+ const stage = try std.fmt.allocPrintSentinel(a, "{s}/.rediwm-keys-XXXXXX", .{directory}, 0);
+ if (c.mkdtemp(stage.ptr) == null) return error.StageFailed;
+ defer std.Io.Dir.cwd().deleteTree(io, stage) catch {};
+ const staged = try std.fs.path.join(a, &.{ stage, "key" });
+ if (original) |file| try writeNew(a, staged, file.bytes, 0o600);
+ try tool(a, io, req, staged);
+ const output = try keys.scan.read(a, staged);
+ defer output.deinit(a);
+ const checked = try keys.openssh.parse(a, output.bytes);
+ if (!checked.private) return error.InvalidKey;
+ if (parsed) |key| if (!std.mem.eql(u8, key.item.fingerprint, checked.item.fingerprint)) return error.FileChanged;
+ const from = try a.dupeSentinel(u8, staged, 0);
+ const to = try a.dupeSentinel(u8, path, 0);
+ if (original) |file| {
+ try unchanged(a, path, file);
+ if (c.rename(from.ptr, to.ptr) != 0) return error.WriteFailed;
+ } else {
+ const public = try std.fmt.allocPrint(a, "{s}.pub", .{path});
+ const check_path = try a.dupeSentinel(u8, public, 0);
+ if (c.access(check_path.ptr, c.F_OK) == 0) return error.PathAlreadyExists;
+ try platform.fs.renameNoReplace(from.ptr, to.ptr);
+ const generated_pub = try keys.scan.read(a, try std.fmt.allocPrint(a, "{s}.pub", .{staged}));
+ defer generated_pub.deinit(a);
+ try writeNew(a, public, generated_pub.bytes, 0o644);
+ }
+ if (req.action == .comment) {
+ // ssh-keygen -c also updates the public file. Preserve a missing or
+ // mismatched companion; the UI reports it for an explicit repair.
+ const public = try std.fmt.allocPrint(a, "{s}.pub", .{path});
+ if (keys.scan.read(a, public)) |file| {
+ defer file.deinit(a);
+ const old_public = keys.openssh.publicLine(a, file.bytes) catch return;
+ if (std.mem.eql(u8, old_public.fingerprint, req.fingerprint)) {
+ const new_public = try keys.scan.read(a, try std.fmt.allocPrint(a, "{s}.pub", .{staged}));
+ defer new_public.deinit(a);
+ try unchanged(a, public, file);
+ const pub_from = try std.fmt.allocPrintSentinel(a, "{s}.pub", .{staged}, 0);
+ const pub_to = try a.dupeSentinel(u8, public, 0);
+ if (c.rename(pub_from.ptr, pub_to.ptr) != 0) return error.WriteFailed;
+ }
+ } else |_| {}
+ }
+}
diff --git a/src/keys_main.zig b/src/keys_main.zig
new file mode 100644
index 0000000..0aaf620
--- /dev/null
+++ b/src/keys_main.zig
@@ -0,0 +1,83 @@
+//! No privileges, no compositor imports, and no private bytes in replies.
+const std = @import("std");
+const c = @import("c");
+const keys = @import("keys");
+const platform = @import("platform");
+const helper = @import("keys_helper.zig");
+const secure = @import("network/secure_allocator.zig").allocator;
+
+fn run(init: std.process.Init) !void {
+ try platform.process.denyDumps();
+ platform.process.ignoreBrokenPipes();
+ platform.process.dieWithParent(.KILL);
+ if (std.c.geteuid() == 0) return error.RunAsDesktopUser;
+ try std.posix.setrlimit(.AS, .{ .cur = 256 << 20, .max = 256 << 20 });
+ try std.posix.setrlimit(.CPU, .{ .cur = 10, .max = 10 });
+ const args = init.minimal.args.vector;
+ if (args.len != 2) return error.Usage;
+ const verb = std.mem.span(args[1]);
+ const env = init.minimal.environ;
+ if (!std.mem.eql(u8, verb, "scan") and !std.mem.eql(u8, verb, "op")) return helper.askpass(env, verb);
+ _ = c.umask(0o077);
+ var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var reply: keys.protocol.Reply = .{};
+ if (std.mem.eql(u8, verb, "op")) {
+ const buffer = try secure.alloc(u8, 16384);
+ defer secure.free(buffer);
+ var used: usize = 0;
+ while (true) {
+ if (used == buffer.len) return error.RequestTooLarge;
+ const n = c.read(0, buffer.ptr + used, buffer.len - used);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n < 0) return error.ReadFailed;
+ if (n == 0) break;
+ used += @intCast(n);
+ }
+ const request = try std.json.parseFromSlice(keys.protocol.Request, secure, buffer[0..used], .{ .allocate = .alloc_always, .max_value_len = 4096 });
+ defer request.deinit();
+ helper.perform(a, init.io, env, request.value) catch |err| {
+ reply.failure = @errorName(err);
+ };
+ }
+ const keygen = platform.tool.system(init.io, "ssh-keygen") != null;
+ const trash = platform.tool.system(init.io, "gio") != null;
+ const directory = std.Io.Dir.cwd().openDir(init.io, try keys.scan.sshDir(a, env), .{ .iterate = true, .follow_symlinks = false }) catch |err| blk: {
+ if (err != error.FileNotFound) reply.failure = @errorName(err);
+ break :blk null;
+ };
+ defer if (directory) |dir| dir.close(init.io);
+ // Preopen the two read capabilities before entering the FreeBSD sandbox.
+ const index_path = try a.dupeSentinel(u8, try helper.indexPath(a, env), 0);
+ const index_fd = c.open(index_path.ptr, c.O_RDONLY | c.O_NOFOLLOW | c.O_CLOEXEC | c.O_NONBLOCK);
+ defer if (index_fd >= 0) {
+ _ = c.close(index_fd);
+ };
+ // After the operation, even the refresh runs with read-only syscalls.
+ try platform.key_scan.enter(if (directory) |dir| dir.handle else -1, index_fd);
+ reply.inventory = keys.scan.inventory(a, init.io, env, directory) catch |err| blk: {
+ if (reply.failure == null) reply.failure = @errorName(err);
+ break :blk .{};
+ };
+ reply.inventory.keygen = keygen;
+ reply.inventory.trash = trash;
+ if (index_fd >= 0) {
+ var info: c.struct_stat = undefined;
+ if (c.fstat(index_fd, &info) == 0 and info.st_uid == std.c.getuid() and info.st_mode & c.S_IFMT == c.S_IFREG and info.st_size > 0 and info.st_size <= keys.model.max_file) {
+ const index_bytes = try a.alloc(u8, @intCast(info.st_size));
+ const count = c.read(index_fd, index_bytes.ptr, index_bytes.len);
+ if (count == index_bytes.len) try helper.applyLabels(a, index_bytes, &reply.inventory);
+ }
+ }
+ const bytes = try std.json.Stringify.valueAlloc(a, reply, .{});
+ if (bytes.len > keys.model.max_reply) return error.ResponseTooLarge;
+ try helper.writeAll(1, bytes);
+}
+pub fn main(init: std.process.Init) void {
+ run(init) catch |err| {
+ // Error names are metadata: tool output and requests are never logged.
+ std.debug.print("rediwm-keys: {s}\n", .{@errorName(err)});
+ std.process.exit(1);
+ };
+}
diff --git a/src/platform/key_scan.c b/src/platform/key_scan.c
new file mode 100644
index 0000000..73d58fc
--- /dev/null
+++ b/src/platform/key_scan.c
@@ -0,0 +1,23 @@
+/* Capabilities for the disposable scanner. No write, create or execute rights. */
+#ifdef __FreeBSD__
+#include <sys/capsicum.h>
+#include <unistd.h>
+
+int rediwm_key_scan_capsicum(int directory, int index) {
+ cap_rights_t rights;
+ if (directory >= 0) {
+ cap_rights_init(&rights, CAP_READ, CAP_LOOKUP, CAP_FSTAT, CAP_SEEK,
+ CAP_FCNTL);
+ if (cap_rights_limit(directory, &rights) < 0) return -1;
+ }
+ if (index >= 0) {
+ cap_rights_init(&rights, CAP_READ, CAP_FSTAT, CAP_SEEK);
+ if (cap_rights_limit(index, &rights) < 0) return -1;
+ }
+ cap_rights_init(&rights, CAP_WRITE, CAP_FSTAT);
+ if (cap_rights_limit(STDOUT_FILENO, &rights) < 0 ||
+ cap_rights_limit(STDERR_FILENO, &rights) < 0) return -1;
+ close(STDIN_FILENO);
+ return cap_enter();
+}
+#endif
diff --git a/src/platform/key_scan.zig b/src/platform/key_scan.zig
new file mode 100644
index 0000000..febbc5f
--- /dev/null
+++ b/src/platform/key_scan.zig
@@ -0,0 +1,51 @@
+//! Read-only metadata scanner policy. Kept here with the other OS interfaces.
+const std = @import("std");
+const builtin = @import("builtin");
+const seccomp = @import("seccomp.zig");
+const process = @import("process.zig");
+
+pub fn program(buf: []seccomp.Insn) ![]const seccomp.Insn {
+ var b = try seccomp.Builder.init(buf);
+ // O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_APPEND | __O_TMPFILE.
+ const write_flags: u64 = 3 | 0o100 | 0o200 | 0o1000 | 0o2000 | 0o20000000;
+ try b.ruleArg(seccomp.number("openat").?, seccomp.allow, .{ .index = 2, .value = 0, .mask = write_flags });
+ if (seccomp.number("open")) |nr| try b.ruleArg(nr, seccomp.allow, .{ .index = 1, .value = 0, .mask = write_flags });
+ for ([_]u64{ 1, 2 }) |fd| try b.ruleArg(seccomp.number("write").?, seccomp.allow, .{ .index = 0, .value = fd });
+ inline for (.{ "read", "close", "pread64", "lseek", "fstat", "getdents64", "fcntl", "mmap", "mprotect", "munmap", "mremap", "brk", "madvise", "rt_sigaction", "rt_sigprocmask", "rt_sigreturn", "clock_gettime", "getpid", "getuid", "geteuid", "futex", "exit", "exit_group" }) |name| try b.rule(seccomp.number(name).?, seccomp.allow);
+ inline for (.{ "newfstatat", "statx", "stat", "lstat", "getdents", "futex_time64", "clock_gettime64", "restart_syscall" }) |name| if (seccomp.number(name)) |nr| try b.rule(nr, seccomp.allow);
+ return b.finish(seccomp.errno(.PERM));
+}
+extern "c" fn rediwm_key_scan_capsicum(c_int, c_int) c_int;
+pub fn enter(directory: c_int, index: c_int) !void {
+ try process.noNewPrivileges();
+ if (builtin.os.tag == .linux) {
+ var buf: [256]seccomp.Insn = undefined;
+ try seccomp.install(try program(&buf));
+ } else if (rediwm_key_scan_capsicum(directory, index) != 0) return error.ScannerSandboxUnavailable;
+}
+
+test "key scanner denies writes, execution and networking" {
+ if (builtin.os.tag != .linux) return;
+ var buf: [256]seccomp.Insn = undefined;
+ const p = try program(&buf);
+ var call: std.os.linux.SECCOMP.data = .{ .nr = 0, .arch = seccomp.audit_arch, .instruction_pointer = 0, .arg0 = 0, .arg1 = 0, .arg2 = 0, .arg3 = 0, .arg4 = 0, .arg5 = 0 };
+ inline for (.{ "execve", "execveat", "socket", "connect", "unlink", "unlinkat", "renameat", "fchmod", "clone", "openat2" }) |name| {
+ if (seccomp.number(name)) |nr| {
+ call.nr = @bitCast(nr);
+ try std.testing.expectEqual(seccomp.errno(.PERM), seccomp.evaluate(p, call));
+ }
+ }
+ call.nr = @bitCast(seccomp.number("openat").?);
+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call));
+ for ([_]u64{ 1, 2, 0o100, 0o1000, 0o20000000 }) |flags| {
+ call.arg2 = flags;
+ try std.testing.expectEqual(seccomp.errno(.PERM), seccomp.evaluate(p, call));
+ }
+ call.nr = @bitCast(seccomp.number("write").?);
+ for ([_]u64{ 0, 3, 17 }) |fd| {
+ call.arg0 = fd;
+ try std.testing.expectEqual(seccomp.errno(.PERM), seccomp.evaluate(p, call));
+ }
+ call.arg0 = 1;
+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call));
+}
diff --git a/src/platform/mod.zig b/src/platform/mod.zig
index a541282..5450494 100644
--- a/src/platform/mod.zig
+++ b/src/platform/mod.zig
@@ -22,6 +22,7 @@ pub const watch = @import("watch.zig");
pub const seccomp = @import("seccomp.zig");
pub const system = @import("system.zig");
pub const tool = @import("tool.zig");
+pub const key_scan = @import("key_scan.zig");
test {
_ = login_process;
@@ -35,6 +36,7 @@ test {
_ = wake;
_ = system;
_ = tool;
+ _ = key_scan;
_ = watch;
_ = @import("seccomp_tests.zig");
}
diff --git a/src/session/lock.zig b/src/session/lock.zig
index d9ae92c..60fb454 100644
--- a/src/session/lock.zig
+++ b/src/session/lock.zig
@@ -138,7 +138,12 @@ pub const Lock = struct {
server.screenshot_selector.cancel();
server.locker = self;
if (server.bluetooth) |bluetooth| bluetooth.closed();
- if (server.input.open_control_center) |cc| cc.bluetooth.clearPin();
+ if (server.input.open_control_center) |cc| {
+ cc.bluetooth.clearPin();
+ cc.key_settings.clearSecrets();
+ if (cc.key_settings.client) |client| client.cancel();
+ cc.refresh();
+ }
@import("../extra_protocols.zig").rediwm_protocols_revoke(server.extra_protocols);
server.world.mini_map.hide();
if (server.ipc) |ipc| ipc.wait_mgr.failAll("SessionLocked");
diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.md
index 18f6bd8..aa9e4d2 100644
--- a/src/system_monitor/AGENTS.md
+++ b/src/system_monitor/AGENTS.md
@@ -11,6 +11,9 @@
`/proc` outside a backend; a new OS needs `Process`, `List`, `cpuTotals`,
`memoryTotals`, `systemStats` and `ticksPerSecond`. Optional footer telemetry
lives in `proc_linux_system.zig`; rates reset with the worker generation.
+ CPU and GPU temperatures stay separate; GPU hwmon reads only the die/package
+ channel. Optional NVIDIA NVML (`proc_gpu.zig`) is owned by the active worker,
+ released on pause/minimize and shutdown, and never starts a subprocess.
The Linux parsers are pure and tested
everywhere through `proc_linux.zig`.
`descendants` also supplies the supervisor's teardown tree: Linux walks
diff --git a/src/system_monitor/app_footer.zig b/src/system_monitor/app_footer.zig
index 577292b..32875cb 100644
--- a/src/system_monitor/app_footer.zig
+++ b/src/system_monitor/app_footer.zig
@@ -120,13 +120,23 @@ fn paintMetric(self: *App, cr: *c.cairo_t, index: usize, cell: Rect) void {
app.textBox(cr, value, content, cairo.textSize(), false, theme.global.window_fg);
},
5 => {
- const value = if (system.temperature_c) |temp| std.fmt.bufPrint(&buf, "{d:.0}°C", .{temp}) catch "—" else "—";
- app.textBox(cr, value, content, cairo.textSize(), false, colors[index]);
+ content.y -= 4;
+ content.h = 18;
+ app.textBox(cr, temperatureLabel(&buf, tr("CPU"), system.temperature_c), content, cairo.statusSize(), false, colors[index]);
+ content.y += 17;
+ app.textBox(cr, temperatureLabel(&buf, tr("GPU"), system.gpu_temperature_c), content, cairo.statusSize(), false, colors[index]);
},
else => unreachable,
}
}
+fn temperatureLabel(buf: []u8, label: []const u8, temperature: ?f64) []const u8 {
+ return if (temperature) |value|
+ std.fmt.bufPrint(buf, "{s} {d:.0}°C", .{ label, value }) catch "—"
+ else
+ std.fmt.bufPrint(buf, "{s} —", .{label}) catch "—";
+}
+
fn memory(cr: *c.cairo_t, content: Rect, used: ?u64, total: ?u64, color: [4]f32) void {
if (used == null or total == null) return app.textBox(cr, "—", content, cairo.textSize(), false, theme.global.window_fg);
const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };
diff --git a/src/system_monitor/collector.zig b/src/system_monitor/collector.zig
index 9a05baa..69c76d9 100644
--- a/src/system_monitor/collector.zig
+++ b/src/system_monitor/collector.zig
@@ -4,6 +4,7 @@ const std = @import("std");
const proc = @import("proc.zig");
const c = proc.c;
const a = std.heap.c_allocator;
+const GpuReader = @import("proc_gpu.zig").Reader;
pub const Process = struct {
identity: proc.Identity,
@@ -164,6 +165,9 @@ pub const Worker = struct {
return result;
}
fn run(self: *Worker) void {
+ var gpu: ?GpuReader = null;
+ defer if (gpu) |*reader| reader.deinit();
+ var gpu_attempted = false;
var previous: std.AutoHashMapUnmanaged(i32, Baseline) = .empty;
defer previous.deinit(a);
var last_at: u64 = 0;
@@ -183,10 +187,17 @@ pub const Worker = struct {
deadline = 0;
}
if (self.active.load(.acquire) and proc.nowNs() >= deadline) {
+ if (!gpu_attempted) {
+ gpu = GpuReader.init();
+ gpu_attempted = true;
+ }
const snap = sample(&self.generation, generation) catch {
deadline = proc.nowNs() + 1_000_000_000;
continue;
};
+ if (gpu) |*reader| if (reader.sample()) |temperature| {
+ snap.system.gpu_temperature_c = @max(snap.system.gpu_temperature_c orelse temperature, temperature);
+ };
if (self.generation.load(.acquire) != generation) {
snap.deinit();
continue;
@@ -216,6 +227,11 @@ pub const Worker = struct {
} else snap.deinit();
self.mutex.unlock(self.io);
}
+ if (!self.active.load(.acquire)) {
+ if (gpu) |*reader| reader.deinit();
+ gpu = null;
+ gpu_attempted = false;
+ }
var fd = c.struct_pollfd{ .fd = self.wake_fd, .events = c.POLLIN, .revents = 0 };
const timeout: c_int = if (!self.active.load(.acquire)) -1 else @intCast(@min(1000, (deadline -| proc.nowNs() + 999_999) / 1_000_000));
_ = c.poll(&fd, 1, timeout);
diff --git a/src/system_monitor/proc_common.zig b/src/system_monitor/proc_common.zig
index eee0a5c..35a2c3f 100644
--- a/src/system_monitor/proc_common.zig
+++ b/src/system_monitor/proc_common.zig
@@ -44,6 +44,7 @@ pub const System = struct {
frequency_ghz: ?f64 = null,
uptime_seconds: ?u64 = null,
temperature_c: ?f64 = null,
+ gpu_temperature_c: ?f64 = null,
network: ?Network = null,
};
pub const Network = struct { received: u64 = 0, sent: u64 = 0, interfaces: u64 = 0 };
diff --git a/src/system_monitor/proc_gpu.zig b/src/system_monitor/proc_gpu.zig
new file mode 100644
index 0000000..7f07e3d
--- /dev/null
+++ b/src/system_monitor/proc_gpu.zig
@@ -0,0 +1,88 @@
+//! Optional NVIDIA telemetry. The collector owns this handle only while active;
+//! no subprocess, timer, mandatory driver library or process-lifetime cache.
+const std = @import("std");
+const builtin = @import("builtin");
+
+const Device = ?*opaque {};
+const Init = *const fn () callconv(.c) c_uint;
+const Count = *const fn (*c_uint) callconv(.c) c_uint;
+const Handle = *const fn (c_uint, *Device) callconv(.c) c_uint;
+const Temperature = *const fn (Device, c_uint, *c_uint) callconv(.c) c_uint;
+
+pub const Reader = struct {
+ library: ?std.DynLib = null,
+ shutdown: Init,
+ count: Count,
+ handle: Handle,
+ temperature: Temperature,
+
+ pub fn init() ?Reader {
+ if (builtin.os.tag != .linux) return null;
+ var library = std.DynLib.open("libnvidia-ml.so.1") catch return null;
+ var keep = false;
+ defer if (!keep) library.close();
+ const initialize = library.lookup(Init, "nvmlInit_v2") orelse return null;
+ const shutdown = library.lookup(Init, "nvmlShutdown") orelse return null;
+ const count = library.lookup(Count, "nvmlDeviceGetCount_v2") orelse return null;
+ const handle = library.lookup(Handle, "nvmlDeviceGetHandleByIndex_v2") orelse return null;
+ const temperature = library.lookup(Temperature, "nvmlDeviceGetTemperature") orelse return null;
+ if (initialize() != 0) return null;
+ keep = true;
+ return .{ .library = library, .shutdown = shutdown, .count = count, .handle = handle, .temperature = temperature };
+ }
+
+ pub fn deinit(self: *Reader) void {
+ _ = self.shutdown();
+ if (self.library) |*library| library.close();
+ self.library = null;
+ }
+
+ pub fn sample(self: *const Reader) ?f64 {
+ var count: c_uint = 0;
+ if (self.count(&count) != 0) return null;
+ var hottest: ?f64 = null;
+ for (0..@min(count, 64)) |index| {
+ var device: Device = null;
+ if (self.handle(@intCast(index), &device) != 0 or device == null) continue;
+ var degrees: c_uint = 0;
+ // NVML_TEMPERATURE_GPU = 0; NVML reports whole degrees Celsius.
+ if (self.temperature(device, 0, &degrees) != 0 or degrees > 200) continue;
+ const value: f64 = @floatFromInt(degrees);
+ hottest = @max(hottest orelse value, value);
+ }
+ return hottest;
+ }
+};
+
+test "GPU queries skip unsupported devices, select hottest valid die and release NVML" {
+ const Fake = struct {
+ var stopped: bool = false;
+ fn shutdown() callconv(.c) c_uint {
+ stopped = true;
+ return 0;
+ }
+ fn count(value: *c_uint) callconv(.c) c_uint {
+ value.* = 4;
+ return 0;
+ }
+ fn handle(index: c_uint, value: *Device) callconv(.c) c_uint {
+ value.* = @ptrFromInt(index + 1);
+ return 0;
+ }
+ fn temperature(device: Device, sensor: c_uint, value: *c_uint) callconv(.c) c_uint {
+ if (sensor != 0) return 1;
+ const id = @intFromPtr(device.?);
+ if (id == 1) return 3; // Unsupported; another GPU still works.
+ value.* = switch (id) {
+ 2 => 61,
+ 3 => 74,
+ else => 999,
+ };
+ return 0;
+ }
+ };
+ var reader: Reader = .{ .shutdown = Fake.shutdown, .count = Fake.count, .handle = Fake.handle, .temperature = Fake.temperature };
+ try std.testing.expectEqual(@as(?f64, 74), reader.sample());
+ reader.deinit();
+ try std.testing.expect(Fake.stopped);
+}
diff --git a/src/system_monitor/proc_linux_system.zig b/src/system_monitor/proc_linux_system.zig
index b045e88..83807c3 100644
--- a/src/system_monitor/proc_linux_system.zig
+++ b/src/system_monitor/proc_linux_system.zig
@@ -21,7 +21,9 @@ pub fn sample(buf: []u8) common.System {
if (common.readAt(c.AT_FDCWD, "/proc/net/dev", buf)) |bytes| {
result.network = parseNetwork(bytes);
} else |_| {}
- result.temperature_c = temperature(buf);
+ const temperatures = readTemperatures("/sys/class/hwmon", "/sys/class/thermal", buf);
+ result.temperature_c = temperatures.cpu;
+ result.gpu_temperature_c = temperatures.gpu;
return result;
}
@@ -54,43 +56,55 @@ fn number(path: [*:0]const u8, buf: []u8) ?f64 {
return if (std.math.isFinite(value)) value else null;
}
-/// Only CPU sensors: do not silently substitute a disk, GPU or ACPI sensor.
-fn temperature(buf: []u8) ?f64 {
- var hottest: ?f64 = null;
- const dir = c.opendir("/sys/class/hwmon") orelse return thermalTemperature(buf);
+pub const Temperatures = struct { cpu: ?f64 = null, gpu: ?f64 = null };
+
+/// Keep CPU and GPU sensors separate; never substitute disk or ACPI readings.
+pub fn readTemperatures(hwmon: [:0]const u8, thermal: [:0]const u8, buf: []u8) Temperatures {
+ var result: Temperatures = .{};
+ hwmonTemperatures(hwmon, buf, &result);
+ if (result.cpu == null) result.cpu = thermalTemperature(thermal, buf);
+ return result;
+}
+
+fn hwmonTemperatures(root: [:0]const u8, buf: []u8, result: *Temperatures) void {
+ const dir = c.opendir(root) orelse return;
defer _ = c.closedir(dir);
while (c.readdir(dir)) |entry| {
const name = std.mem.sliceTo(entry.*.d_name[0..], 0);
if (!std.mem.startsWith(u8, name, "hwmon")) continue;
var path_buf: [512]u8 = undefined;
- const driver_path = std.fmt.bufPrintSentinel(&path_buf, "/sys/class/hwmon/{s}/name", .{name}, 0) catch continue;
+ const driver_path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}/name", .{ root, name }, 0) catch continue;
const driver = std.mem.trim(u8, common.readAt(c.AT_FDCWD, driver_path, buf) catch continue, " \n");
- if (!std.mem.eql(u8, driver, "coretemp") and !std.mem.eql(u8, driver, "k10temp") and !std.mem.eql(u8, driver, "zenpower")) continue;
- const path = std.fmt.bufPrintSentinel(&path_buf, "/sys/class/hwmon/{s}", .{name}, 0) catch continue;
+ const cpu = std.mem.eql(u8, driver, "coretemp") or std.mem.eql(u8, driver, "k10temp") or std.mem.eql(u8, driver, "zenpower");
+ const gpu = std.mem.eql(u8, driver, "amdgpu") or std.mem.eql(u8, driver, "radeon") or std.mem.eql(u8, driver, "nouveau") or std.mem.eql(u8, driver, "i915") or std.mem.eql(u8, driver, "xe");
+ if (!cpu and !gpu) continue;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ root, name }, 0) catch continue;
const sensors = c.opendir(path) orelse continue;
defer _ = c.closedir(sensors);
while (c.readdir(sensors)) |sensor| {
const file = std.mem.sliceTo(sensor.*.d_name[0..], 0);
if (!std.mem.startsWith(u8, file, "temp") or !std.mem.endsWith(u8, file, "_input")) continue;
- const input = std.fmt.bufPrintSentinel(&path_buf, "/sys/class/hwmon/{s}/{s}", .{ name, file }, 0) catch continue;
- keepTemperature(&hottest, number(input, buf));
+ // GPU temp1 is the die/package (AMD edge); later channels can
+ // describe junction or VRAM and must not silently replace it.
+ if (gpu and !std.mem.eql(u8, file, "temp1_input")) continue;
+ const input = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}/{s}", .{ root, name, file }, 0) catch continue;
+ keepTemperature(if (cpu) &result.cpu else &result.gpu, number(input, buf));
}
}
- return hottest orelse thermalTemperature(buf);
}
-fn thermalTemperature(buf: []u8) ?f64 {
+fn thermalTemperature(root: [:0]const u8, buf: []u8) ?f64 {
var hottest: ?f64 = null;
- const dir = c.opendir("/sys/class/thermal") orelse return null;
+ const dir = c.opendir(root) orelse return null;
defer _ = c.closedir(dir);
while (c.readdir(dir)) |entry| {
const name = std.mem.sliceTo(entry.*.d_name[0..], 0);
if (!std.mem.startsWith(u8, name, "thermal_zone")) continue;
var path_buf: [512]u8 = undefined;
- const type_path = std.fmt.bufPrintSentinel(&path_buf, "/sys/class/thermal/{s}/type", .{name}, 0) catch continue;
+ const type_path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}/type", .{ root, name }, 0) catch continue;
const kind = std.mem.trim(u8, common.readAt(c.AT_FDCWD, type_path, buf) catch continue, " \n");
if (!std.mem.eql(u8, kind, "x86_pkg_temp") and !std.mem.eql(u8, kind, "cpu-thermal") and !std.mem.startsWith(u8, kind, "cpu_thermal")) continue;
- const input = std.fmt.bufPrintSentinel(&path_buf, "/sys/class/thermal/{s}/temp", .{name}, 0) catch continue;
+ const input = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}/temp", .{ root, name }, 0) catch continue;
keepTemperature(&hottest, number(input, buf));
}
return hottest;
diff --git a/src/system_monitor/proc_temperature_tests.zig b/src/system_monitor/proc_temperature_tests.zig
new file mode 100644
index 0000000..fee5e9b
--- /dev/null
+++ b/src/system_monitor/proc_temperature_tests.zig
@@ -0,0 +1,47 @@
+const std = @import("std");
+const linux = @import("proc_linux_system.zig");
+
+test "CPU and GPU temperatures stay separate, reject invalid sensors and handle disappearance" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const files = .{
+ .{ "hwmon/hwmon0/name", "coretemp\n" },
+ .{ "hwmon/hwmon0/temp1_input", "51000\n" },
+ .{ "hwmon/hwmon0/temp2_input", "63000\n" },
+ .{ "hwmon/hwmon1/name", "amdgpu\n" },
+ .{ "hwmon/hwmon1/temp1_input", "72000\n" },
+ .{ "hwmon/hwmon1/temp2_input", "99000\n" }, // Junction.
+ .{ "hwmon/hwmon1/temp3_input", "105000\n" }, // VRAM.
+ .{ "hwmon/hwmon2/name", "nvme\n" },
+ .{ "hwmon/hwmon2/temp1_input", "120000\n" },
+ .{ "hwmon/hwmon3/name", "i915\n" },
+ .{ "hwmon/hwmon3/temp1_input", "80000\n" },
+ .{ "hwmon/hwmon4/name", "nouveau\n" },
+ .{ "hwmon/hwmon4/temp1_input", "nan\n" },
+ .{ "thermal/thermal_zone0/type", "acpitz\n" },
+ .{ "thermal/thermal_zone0/temp", "110000\n" },
+ .{ "thermal/thermal_zone1/type", "x86_pkg_temp\n" },
+ .{ "thermal/thermal_zone1/temp", "65000\n" },
+ };
+ inline for (files) |file| {
+ try tmp.dir.createDirPath(io, std.fs.path.dirname(file[0]).?);
+ try tmp.dir.writeFile(io, .{ .sub_path = file[0], .data = file[1] });
+ }
+ const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);
+ defer std.testing.allocator.free(root);
+ var hwmon_buf: [1024]u8 = undefined;
+ var thermal_buf: [1024]u8 = undefined;
+ const hwmon = try std.fmt.bufPrintSentinel(&hwmon_buf, "{s}/hwmon", .{root}, 0);
+ const thermal = try std.fmt.bufPrintSentinel(&thermal_buf, "{s}/thermal", .{root}, 0);
+ var buf: [4096]u8 = undefined;
+ try std.testing.expectEqual(linux.Temperatures{ .cpu = 63, .gpu = 80 }, linux.readTemperatures(hwmon, thermal, &buf));
+ try tmp.dir.writeFile(io, .{ .sub_path = "hwmon/hwmon0/temp1_input", .data = "-999999\n" });
+ try tmp.dir.writeFile(io, .{ .sub_path = "hwmon/hwmon0/temp2_input", .data = "garbage\n" });
+ try tmp.dir.writeFile(io, .{ .sub_path = "hwmon/hwmon3/temp1_input", .data = "201000\n" });
+ try std.testing.expectEqual(linux.Temperatures{ .cpu = 65, .gpu = 72 }, linux.readTemperatures(hwmon, thermal, &buf));
+ try tmp.dir.deleteTree(io, "hwmon");
+ try std.testing.expectEqual(linux.Temperatures{ .cpu = 65 }, linux.readTemperatures(hwmon, thermal, &buf));
+ try tmp.dir.deleteTree(io, "thermal/thermal_zone1");
+ try std.testing.expectEqual(linux.Temperatures{}, linux.readTemperatures(hwmon, thermal, &buf));
+}
diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zig
index 0122130..b04794a 100644
--- a/src/system_monitor_tests.zig
+++ b/src/system_monitor_tests.zig
@@ -8,6 +8,8 @@ const actions = @import("system_monitor/actions.zig");
test {
_ = @import("system_monitor/proc_system_tests.zig");
+ _ = @import("system_monitor/proc_gpu.zig");
+ _ = @import("system_monitor/proc_temperature_tests.zig");
}
test "monitor backend lists and describes this process and the machine" {
diff --git a/tests/keys_settings.py b/tests/keys_settings.py
new file mode 100644
index 0000000..51b001e
--- /dev/null
+++ b/tests/keys_settings.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+"""SSH metadata/helper and real Settings checks, using only generated keys.
+
+Every file and operation uses scratch HOME/XDG directories. No host agent,
+trust store or real credentials are accessed. Run under dbus-run-session.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import time
+
+from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process
+from ui_driver import UIDriver
+
+
+def wait(predicate, description, seconds=12):
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ result = predicate()
+ if result:
+ return result
+ time.sleep(.08)
+ raise AssertionError(description)
+
+
+def environment(root):
+ env = dict(os.environ, HOME=str(root / 'home'),
+ XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ XDG_CACHE_HOME=str(root / 'cache'), XDG_STATE_HOME=str(root / 'state'),
+ XDG_RUNTIME_DIR=str(root), SSH_AUTH_SOCK='', REDIWM_APP_SCOPES='0', GIO_USE_VFS='local',
+ PULSE_SERVER='unix:/nonexistent-rediwm-keys-audio', PIPEWIRE_RUNTIME_DIR=str(root),
+ DBUS_SYSTEM_BUS_ADDRESS='unix:path=/nonexistent-rediwm-keys-system-bus')
+ env.pop('REDIWM_SOCKET', None)
+ env.pop('WAYLAND_DISPLAY', None)
+ for key in ('HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_STATE_HOME'):
+ Path(env[key]).mkdir(mode=0o700, exist_ok=True)
+ return env
+
+
+def helper_checks(root, env, binary):
+ ssh = Path(env['HOME']) / '.ssh'
+ ssh.mkdir(mode=0o700)
+
+ def generate(name, password='', algorithm='ed25519', bits=None):
+ argv = ['ssh-keygen', '-q', '-t', algorithm, '-N', password, '-C', 'fixture ' + name, '-f', str(ssh / name)]
+ if bits:
+ argv += ['-b', str(bits)]
+ subprocess.run(argv, check=True, env=env, capture_output=True)
+
+ def invoke(action='scan', **fields):
+ result = subprocess.run([str(binary), 'scan' if action == 'scan' else 'op'],
+ input=None if action == 'scan' else json.dumps(dict(action=action, **fields)).encode(),
+ capture_output=True, check=True, env=env, timeout=20)
+ assert b'PRIVATE KEY' not in result.stdout
+ return json.loads(result.stdout)
+
+ def identity(reply, name):
+ return next(item for item in reply['inventory']['items'] if any(Path(p['path']).name == name for p in item['locations']))
+
+ generate('extensionless')
+ generate('protected', 'old secret')
+ generate('weak', algorithm='rsa', bits=1024)
+ generate('ecdsa', algorithm='ecdsa', bits=256)
+ subprocess.run(['ssh-keygen', '-q', '-t', 'rsa', '-b', '2048', '-m', 'PEM', '-N', '', '-f', str(ssh / 'cloud.pem')], check=True, env=env, capture_output=True)
+ subprocess.run(['openssl', 'pkey', '-in', str(ssh / 'cloud.pem'), '-out', str(ssh / 'pkcs8.key')], check=True, env=env, capture_output=True)
+ shutil.copyfile(ssh / 'extensionless', ssh / 'duplicate')
+ (ssh / 'duplicate').chmod(0o600)
+ (ssh / 'extensionless.pub').unlink()
+ (ssh / 'extensionless').chmod(0o644)
+ (ssh / 'link').symlink_to(ssh / 'protected')
+ os.mkfifo(ssh / 'fifo', 0o600)
+ (ssh / 'bad').write_text('-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA/w==\n-----END OPENSSH PRIVATE KEY-----\n')
+ reply = invoke()
+ assert reply['failure'] is None, reply
+ assert len(reply['inventory']['items']) == 5, reply
+ legacy = identity(reply, 'cloud.pem')
+ assert len(legacy['locations']) == 3
+ item = identity(reply, 'extensionless')
+ assert len(item['locations']) == 2, item
+ location = next(p for p in item['locations'] if Path(p['path']).name == 'extensionless')
+ assert location['missing_public'] and location['permissions'] and not location['encrypted']
+ encrypted = identity(reply, 'protected')
+ assert any(p['private'] and p['encrypted'] for p in encrypted['locations'])
+ # Compare every supported algorithm against OpenSSH's fingerprint oracle.
+ for row in reply['inventory']['items']:
+ path = next((p['path'] for p in row['locations'] if not p['private']), row['locations'][0]['path'])
+ reference = subprocess.run(['ssh-keygen', '-lf', path], env=env, check=True, capture_output=True).stdout.decode()
+ assert row['fingerprint'] in reference, (row, reference)
+ target = dict(path=str(ssh / 'extensionless'), fingerprint=item['fingerprint'])
+ assert invoke('recreate_public', **target)['failure'] is None
+ assert (ssh / 'extensionless.pub').read_text().startswith('ssh-ed25519 ')
+ assert invoke('recreate_public', **target)['failure'] == 'PathAlreadyExists'
+ assert invoke('permissions', **target)['failure'] is None
+ assert (ssh / 'extensionless').stat().st_mode & 0o777 == 0o600
+ assert ssh.stat().st_mode & 0o777 == 0o700
+ legacy_target = dict(path=str(ssh / 'cloud.pem'), fingerprint=legacy['fingerprint'])
+ legacy_change = invoke('passphrase', new_passphrase='legacy secret', **legacy_target)
+ assert legacy_change['failure'] is None, legacy_change
+ assert subprocess.run(['ssh-keygen', '-y', '-P', 'legacy secret', '-f', str(ssh / 'cloud.pem')], env=env, capture_output=True).returncode == 0
+ assert invoke('label', text='Work laptop', **target)['failure'] is None
+ assert identity(invoke(), 'duplicate')['label'] == 'Work laptop'
+ encrypted_target = dict(path=str(ssh / 'protected'), fingerprint=encrypted['fingerprint'])
+ original = (ssh / 'protected').read_bytes()
+ assert invoke('passphrase', old_passphrase='wrong', new_passphrase='unused', **encrypted_target)['failure'] == 'KeygenFailed'
+ assert (ssh / 'protected').read_bytes() == original
+ changed = invoke('passphrase', old_passphrase='old secret', new_passphrase='new secret', **encrypted_target)
+ assert changed['failure'] is None, changed
+ verified = subprocess.run(['ssh-keygen', '-y', '-P', 'new secret', '-f', str(ssh / 'protected')], env=env, capture_output=True)
+ assert verified.returncode == 0, verified.stderr
+ assert invoke('comment', old_passphrase='new secret', text='Changed comment', **encrypted_target)['failure'] is None
+ assert identity(invoke(), 'protected')['comment'] == 'Changed comment'
+ assert invoke('passphrase', old_passphrase='new secret', new_passphrase='', **encrypted_target)['failure'] is None
+ assert not next(p for p in identity(invoke(), 'protected')['locations'] if p['private'])['encrypted']
+ generated = invoke('generate', path='new-key', text='Generated key', new_passphrase='generated secret')
+ assert generated['failure'] is None, generated
+ assert invoke('generate', path='new-key', new_passphrase='')['failure'] == 'PathAlreadyExists'
+ assert invoke('generate', path='../escape')['failure'] == 'InvalidPath'
+ assert invoke('permissions', path=str(ssh / 'link'), fingerprint=encrypted['fingerprint'])['failure'] is not None
+ assert invoke('trash', path=target['path'], fingerprint='SHA256:stale')['failure'] == 'FileChanged'
+ # A mismatched public file remains untouched by comment/passphrase actions.
+ shutil.copyfile(ssh / 'weak.pub', ssh / 'protected.pub')
+ mismatch = identity(invoke(), 'protected')
+ assert any(p['mismatched_public'] for p in mismatch['locations'])
+ before_public = (ssh / 'protected.pub').read_bytes()
+ assert invoke('comment', text='New comment', **encrypted_target)['failure'] is None
+ assert (ssh / 'protected.pub').read_bytes() == before_public
+ shutil.copyfile(ssh / 'extensionless.pub', ssh / 'protected.pub')
+ # Trash preserves unrelated public files and other copies of the key.
+ assert invoke('trash', **target)['failure'] is None
+ assert not (ssh / 'extensionless').exists() and not (ssh / 'extensionless.pub').exists()
+ assert (ssh / 'duplicate').exists()
+ assert list((Path(env['XDG_DATA_HOME']) / 'Trash' / 'files').iterdir())
+ # Leave a small, predictable fixture for the real page test.
+ for entry in ssh.iterdir():
+ if entry.name not in ('duplicate', 'protected', 'weak', 'weak.pub'):
+ entry.unlink()
+ assert not list(ssh.glob('.rediwm-keys-*'))
+ print('helper: inventory, fingerprints, deduplication, unsafe files, actions and Trash passed')
+
+
+def page_checks(root, env, binary):
+ proc, log = spawn_compositor(root, scale=os.environ.get('REDIWM_TEST_SCALE', '1'), env_extra=env, binary=binary)
+ try:
+ with IPCClient(root, timeout=20) as ipc:
+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)
+ ui = UIDriver(ipc)
+
+ def click(name):
+ ui.click(ui.scroll_into_view(name), panel='control_center')
+ ui.wait_settled('control_center')
+
+ def idle():
+ return not any(w.get('name') == 'keys_status' for w in ui.widgets())
+
+ def enter(name, value):
+ click(name)
+ ipc.key_down_up(107) # End
+ for _ in range(30):
+ ipc.key_down_up(14) # Backspace
+ ipc.type_text(value)
+
+ ipc.open_control_center()
+ ui.wait_settled('control_center')
+ ui.click('keys', panel='control_center')
+ wait(lambda: any(w.get('name') == 'keys_item_0' for w in ui.widgets()) and idle(), 'key inventory')
+ if preview := os.environ.get('REDIWM_KEYS_SETTINGS_PREVIEW'):
+ ui.wait_settled('control_center')
+ ipc.screenshot(preview)
+ click('keys_item_0')
+ assert any(w.get('name') == 'keys_fingerprint' for w in ui.widgets())
+ click('keys_copy')
+ assert ui.find('keys_message')['label'] == 'Public key copied.'
+ click('keys_edit_label')
+ enter('keys_label', 'UI label')
+ click('keys_submit')
+ wait(lambda: idle() and any(w.get('label') == 'UI label' for w in ui.widgets()), 'label saved')
+ click('keys_back')
+ click('keys_new')
+ enter('keys_name', 'ui-generated')
+ enter('keys_comment', 'UI generated')
+ click('keys_new_passphrase')
+ ipc.type_text('ui secret')
+ click('keys_confirm_passphrase')
+ ipc.type_text('ui secret')
+ # Secret widget inspection must not disclose entered text.
+ assert 'ui secret' not in json.dumps(ui.widgets())
+ click('keys_submit')
+ key_path = Path(env['HOME']) / '.ssh' / 'ui-generated'
+ wait(lambda: key_path.exists() and idle(), 'generated from Settings')
+ result = subprocess.run(['ssh-keygen', '-y', '-P', 'ui secret', '-f', str(key_path)], env=env, capture_output=True)
+ assert result.returncode == 0, result.stderr
+ assert not any(w.get('name') == 'keys_error' for w in ui.widgets()), ui.widgets()
+ # Leaving and returning starts a fresh scan and keeps the section usable.
+ ui.click('general', panel='control_center')
+ ui.wait_settled('control_center')
+ ui.click('keys', panel='control_center')
+ wait(lambda: idle() and any(w.get('label') == 'UI generated' for w in ui.widgets()), 'reopened inventory')
+ click('keys_new')
+ click('keys_new_passphrase')
+ ipc.type_text('cancelled secret')
+ ipc.key_down_up(1) # Escape cancels and wipes the form.
+ ui.wait_settled('control_center')
+ assert not any(w.get('name') == 'keys_new_passphrase' for w in ui.widgets())
+ window = next(w for w in ipc.get_windows() if w.get('app_id') == 'rediwm-settings')
+ ipc.close_window(window['id'])
+ ui.wait_absent('control_center')
+ except Exception:
+ log.flush()
+ print(Path(log.name).read_text()[-6000:])
+ raise
+ finally:
+ stop_process(proc)
+ log.close()
+ print('Settings: inventory, copy, label, secret generation, navigation and cancellation passed')
+
+
+def cancellation_check(root, env, binary):
+ """A noninstalled fixture proves that hiding kills a pending helper group."""
+ local_bin = root / 'fixture-bin'
+ local_bin.mkdir()
+ shutil.copy2(binary, local_bin / 'rediwm')
+ pid_file = root / 'helper-pids'
+ helper = local_bin / 'rediwm-keys'
+ helper.write_text('#!/bin/sh\n/bin/sleep 120 &\nprintf "%s %s\\n" "$$" "$!" > ' + str(pid_file) + '\nwait\n')
+ helper.chmod(0o700)
+ proc, log = spawn_compositor(root, env_extra=env, binary=local_bin / 'rediwm')
+ try:
+ with IPCClient(root, timeout=20) as ipc:
+ ipc.open_control_center()
+ ui = UIDriver(ipc)
+ ui.wait_settled('control_center')
+ assert not pid_file.exists(), 'hidden section started its helper'
+ ui.click('keys', panel='control_center')
+ wait(pid_file.exists, 'fixture helper start')
+ helper_pid, descendant = map(int, pid_file.read_text().split())
+ ui.click('general', panel='control_center')
+ ui.wait_settled('control_center')
+
+ def stopped(pid):
+ try:
+ os.kill(pid, 0)
+ return False
+ except ProcessLookupError:
+ return True
+
+ wait(lambda: stopped(helper_pid), 'helper did not stop on hide')
+ # A just-killed grandchild can briefly remain a zombie awaiting its
+ # adopter; it must never remain a running sleeper after page hide.
+ result = subprocess.run(['ps', '-o', 'stat=', '-p', str(descendant)], capture_output=True, text=True)
+ assert not result.stdout.strip() or result.stdout.strip().startswith('Z'), result.stdout
+ finally:
+ stop_process(proc)
+ log.close()
+ print('Settings: hidden page starts nothing; hide cancels the helper and its descendants')
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--helper-only', action='store_true')
+ parser.add_argument('--bin-dir', type=Path, default=ROOT / 'zig-out/bin')
+ args = parser.parse_args()
+ with tempfile.TemporaryDirectory(prefix='rediwm-keys-') as directory:
+ root = Path(directory)
+ root.chmod(0o700)
+ env = environment(root)
+ helper_checks(root, env, args.bin_dir / 'rediwm-keys')
+ if not args.helper_only:
+ page_checks(root, env, args.bin_dir / 'rediwm')
+ cancellation_root = root / 'cancellation'
+ cancellation_root.mkdir(mode=0o700)
+ cancellation_check(cancellation_root, environment(cancellation_root), (args.bin_dir / 'rediwm').resolve())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/shortcuts_inhibit.py b/tests/shortcuts_inhibit.py
index ebcd971..a03ac7a 100644
--- a/tests/shortcuts_inhibit.py
+++ b/tests/shortcuts_inhibit.py
@@ -128,10 +128,6 @@ def run():
vm.send("inhibit")
vm.expect_count("active", 1)
binding_inhibited(vm)
- deletes = vm.count("key 111 1")
- chord(29, KEY_LEFTALT, 111)
- vm.expect_count("key 111 1", deletes + 1)
- assert window("rediwm-monitor") is None, "System Monitor bypassed shortcut inhibition"
vm_id = window("rediwm.vm")["id"]
tabs = vm.count(f"key {KEY_TAB} 1")
chord(KEY_LEFTALT, KEY_TAB)
@@ -139,6 +135,12 @@ def run():
assert input_state()["keyboard_focused_window_id"] == vm_id, "Alt+Tab switched away from the VM"
# Super-drag pan belongs to the client's Super too.
def super_drag():
+ w = window("rediwm.vm")
+ result = action('wait_for', {
+ "condition": {"window_geometry_settled": {"id": w["id"]}},
+ "timeout_ms": 5000,
+ })
+ assert not result.get("timed_out"), result
w = window("rediwm.vm")
action('move_cursor', {"x": w["x"] + 40, "y": w["y"] + 40})
key(KEY_LEFTMETA, True)
@@ -204,6 +206,21 @@ def run():
vm.expect_count("active", 5)
print("PASS: destroyed inhibitor restores bindings; a new request is granted")
+ # System Monitor is always reachable, even from a grabbed VM.
+ deletes = vm.count("key 111 1")
+ releases = vm.count("key 111 0")
+ chord(29, KEY_LEFTALT, 111)
+ wait_for(lambda: window("rediwm-monitor"), "System Monitor blocked by inhibition")
+ monitor_id = window("rediwm-monitor")["id"]
+ wait_for(lambda: input_state()["keyboard_focused_window_id"] == monitor_id,
+ "System Monitor did not take keyboard focus")
+ vm.expect_count("inactive", 4)
+ vm.expect_count("key 111 1", deletes)
+ vm.expect_count("key 111 0", releases)
+ focus("rediwm.vm")
+ vm.expect_count("active", 6)
+ print("PASS: System Monitor takes focus and consumes its chord under inhibition")
+
# A client dying while inhibiting must hand the bindings back.
vm.process.kill(); vm.process.wait(timeout=5)
wait_for(lambda: window("rediwm.vm") is None, "vm window did not go away")
diff --git a/tests/system_monitor.py b/tests/system_monitor.py
index a4c556f..9f20292 100644
--- a/tests/system_monitor.py
+++ b/tests/system_monitor.py
@@ -74,7 +74,8 @@ int main(int argc, char **argv) {
def run(scale, workspace):
with tempfile.TemporaryDirectory(prefix="rediwm-monitor-") as directory:
tmp = Path(directory)
- config = ('[compositor]\nxwayland = false\n' +
+ config = ('[compositor]\nxwayland = false\n'
+ 'taskbar_items = ["battery", "volume", "wifi", "clock"]\n' +
('desktop_mode = "workspaces"\n' if workspace else '') +
'[theme]\napp_bg = "#203040"\napp_item_hover = "#4a6076"\n'
'app_item_selected = "#62768a"\n')
@@ -88,6 +89,12 @@ def run(scale, workspace):
targets.write_text(f"{os.getpid()}\n")
check_signal_guard(tmp, guard, targets)
env.update(LD_PRELOAD=str(guard), REDIWM_TEST_MONITOR_TARGETS=str(targets))
+ subprocess.run(["cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror",
+ str(ROOT / "tests/system_monitor_gpu.c"), "-o", str(tmp / "libnvidia-ml.so.1")], check=True)
+ gpu_state, gpu_trace = tmp / "gpu-state", tmp / "gpu-trace"
+ gpu_state.write_text("74\n")
+ env.update(LD_LIBRARY_PATH=str(tmp), REDIWM_TEST_GPU_STATE=str(gpu_state),
+ REDIWM_TEST_GPU_TRACE=str(gpu_trace))
compositor, log = spawn_compositor(tmp, scale=str(scale), config_content=config, env_extra=env,
binary=os.environ.get("REDIWM_TEST_BINARY"))
fixtures = []
@@ -141,6 +148,16 @@ def run(scale, workspace):
delta = switches(monitor_pid) - before
assert delta <= 2, f"{label}: monitor kept waking ({delta} context switches)"
+ def taskbar_popup(name, target):
+ bar = ipc.get_shell_state()["taskbars"][0]
+ anchor = next(item["box"] for item in bar["right_items"] if item["name"] == name)
+ x = anchor["x"] + anchor["width"] // 2
+ ipc.click_at(x, anchor["y"] + anchor["height"] // 2)
+ point = x, bar["box"]["y"] - 40
+ assert ipc.hit_test(*point)["target_type"] == target
+ return point
+
+ wifi_point = taskbar_popup("wifi", "wifi_popup")
for _ in range(3):
chord(29, 56, 111) # Ctrl+Alt+Delete, including activation while starting
ipc.wait_for("window_mapped", app_id="rediwm-monitor", timeout_ms=15000)
@@ -148,11 +165,46 @@ def run(scale, workspace):
assert len(windows()) == 1, windows()
window_id = monitor()["id"]
monitor_pid = monitor()["pid"]
+ assert ipc.hit_test(*wifi_point)["target_type"] != "wifi_popup"
+ assert ipc.get_input_state()["keyboard_focused_window_id"] == window_id
+
+ # Every transient owner yields to the monitor binding, including
+ # restoration while a popup has consumed the keyboard.
+ for name, target in (("wifi", "wifi_popup"), ("clock", "calendar")):
+ ipc.minimize(window_id)
+ point = taskbar_popup(name, target)
+ chord(29, 56, 111)
+ wait_for(lambda: not monitor()["is_minimized"], f"{target} blocked restore")
+ assert ipc.hit_test(*point)["target_type"] != target
+ assert ipc.get_input_state()["keyboard_focused_window_id"] == window_id
+ for panel, opener in (("start_menu", ipc.open_start_menu), ("power_menu", ipc.open_power_menu)):
+ opener()
+ ipc.wait_for(panel + "_opened")
+ chord(29, 56, 111)
+ ipc.wait_for(panel + "_closed")
+ assert ipc.get_input_state()["keyboard_focused_window_id"] == window_id
+
+ ipc.open_control_center()
+ # The switcher stays open only while Alt is held.
+ ipc.key(56, True)
+ ipc.key_down_up(15)
+ chord(29, 111)
+ ipc.key(56, False) # Must not accept the switcher's old selection.
+ assert ipc.get_input_state()["keyboard_focused_window_id"] == window_id
+ chord(29, 42, 31) # Ctrl+Shift+S: region screenshot selection.
+ chord(29, 56, 111)
+ assert ipc.get_input_state()["keyboard_focused_window_id"] == window_id
+ assert len(windows()) == 1 and monitor()["id"] == window_id
+ settings = next(w for w in ipc.get_windows() if w["backend"] == "shell")
+ ipc.close_window(settings["id"])
+ ipc.wait_for("window_closed", window_id=settings["id"])
+ settled()
time.sleep(1.2)
debug = ipc.get_window_debug(window_id)
assert debug["buffer_scale"] == 1, debug
assert abs(debug["buffer_width"] - round(debug["client_box"]["width"] * scale)) <= 1, debug
assert shot("initial").getpixel((4, 4)) == (32, 48, 64)
+ assert "temperature" in gpu_trace.read_text().splitlines(), "GPU telemetry was not sampled"
# Background collection follows visibility, independently of keyboard focus.
ipc.open_control_center()
@@ -161,12 +213,14 @@ def run(scale, workspace):
assert switches(monitor_pid) - before >= 3, "collection stopped on focus loss"
settings = next(w for w in ipc.get_windows() if w["backend"] == "shell")
ipc.close_window(settings["id"])
+ ipc.wait_for("window_closed", window_id=settings["id"])
ipc.focus_window(window_id)
settled()
# Pause has no recurring worker or theme-stat timer.
click(box()["width"] - 80, 171)
idle("paused")
+ assert gpu_trace.read_text().splitlines()[-1] == "shutdown", "paused monitor retained NVIDIA telemetry"
paused = shot("paused", True)
time.sleep(1.2)
assert ImageChops.difference(paused, shot("still-paused", True)).getbbox() is None
@@ -210,6 +264,11 @@ def run(scale, workspace):
wait_for(lambda: shot("theme").getpixel((4, 4)) == (48, 64, 80), "live app theme did not update")
click(box()["width"] - 80, 171)
time.sleep(1.2)
+ assert gpu_trace.read_text().splitlines()[-1] == "temperature", "resumed monitor did not restart GPU telemetry"
+ gpu_state.write_text("-1\n")
+ wait_for(lambda: gpu_trace.read_text().splitlines()[-1] == "unavailable", "GPU loss was not handled")
+ shot("gpu-unavailable")
+ gpu_state.write_text("74\n")
# Minimize is a real xdg-shell v6 suspended configure. Restore
# starts a fresh interval and repeated activation keeps this ID.
@@ -362,7 +421,7 @@ def run(scale, workspace):
child.stdin.close()
stop_process(compositor)
log.close()
- errors = (tmp / "compositor.log").read_text()
+ errors = Path(log.name).read_text()
if "panic" in errors or "error(gpa)" in errors:
print(errors[-6000:], file=sys.stderr)
raise AssertionError("compositor or monitor reported a panic/leak")
diff --git a/tests/system_monitor_gpu.c b/tests/system_monitor_gpu.c
new file mode 100644
index 0000000..ba2efc6
--- /dev/null
+++ b/tests/system_monitor_gpu.c
@@ -0,0 +1,34 @@
+/* Optional NVML peer for the isolated monitor suite. No host GPU is queried. */
+#include <stdio.h>
+#include <stdlib.h>
+
+static void trace(const char *event) {
+ const char *path = getenv("REDIWM_TEST_GPU_TRACE");
+ if (!path) return;
+ FILE *out = fopen(path, "a");
+ if (!out) return;
+ fprintf(out, "%s\n", event);
+ fclose(out);
+}
+
+unsigned nvmlInit_v2(void) { trace("init"); return 0; }
+unsigned nvmlShutdown(void) { trace("shutdown"); return 0; }
+unsigned nvmlDeviceGetCount_v2(unsigned *count) { *count = 1; return 0; }
+unsigned nvmlDeviceGetHandleByIndex_v2(unsigned index, void **device) {
+ if (index) return 2;
+ *device = (void *)1;
+ return 0;
+}
+unsigned nvmlDeviceGetTemperature(void *device, unsigned sensor, unsigned *degrees) {
+ if (device != (void *)1 || sensor) return 2;
+ const char *path = getenv("REDIWM_TEST_GPU_STATE");
+ FILE *in = path ? fopen(path, "r") : NULL;
+ if (!in) return 3;
+ int value = -1;
+ int read = fscanf(in, "%d", &value);
+ fclose(in);
+ if (read != 1 || value < 0) { trace("unavailable"); return 3; }
+ *degrees = (unsigned)value;
+ trace("temperature");
+ return 0;
+}