Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

App mode: quit, shortcuts, keymap and Lock fixes, error codes; keyring broker op for .lpk apps; vault comments in English; Raspberry Pi 5 bring-up fixes (NetworkManager coexistence, KMS hotplug retry, archive key)

Federico Pereirab55e109fe864
diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.json
index 6b8a433..31e45db 100644
--- a/assets/locales/en/errors.json
+++ b/assets/locales/en/errors.json
@@ -7,6 +7,13 @@
"admin.tooMany": "Too many actions in progress; try again in a moment",
"admin.unavailable": "The administration helper is not available",
"admin.unknownAction": "Unknown administration action",
+ "app.badFd": "Invalid file handle",
+ "app.clipboardDenied": "This app has no permission to read the clipboard",
+ "app.loadFailed": "Could not read the app's code",
+ "app.noSuchFile": "The app does not include that file",
+ "app.outsideFolder": "That location is outside the app's folder",
+ "app.readFailed": "Could not read the file",
+ "app.writeFailed": "Could not write the file",
"backup.alreadyRunning": "A backup is already running",
"backup.badConfig": "Invalid backup settings",
"backup.badDest": "Invalid destination",
@@ -214,6 +221,14 @@
"ipsec.noVici": "strongSwan (charon) did not open its control socket",
"ipsec.pskShort": "The pre-shared key needs at least 8 characters",
"ipsec.viciFailed": "strongSwan rejected {cmd}: {detail}",
+ "keyring.badRequest": "The keyring request is not valid",
+ "keyring.busy": "Too many keyring requests at once; try again",
+ "keyring.failed": "The keyring could not complete the request",
+ "keyring.locked": "The session keyring is locked",
+ "keyring.noKeyring": "There is no session keyring (sign in with a password to create it)",
+ "keyring.notFound": "The item is not in the keyring",
+ "keyring.notShared": "That keyring item belongs to another app and was not shared with this one",
+ "keyring.saveFailed": "The keyring could not be saved",
"lang.invalidCode": "Invalid language code: {code}",
"locale.notGenerated": "Region {name} is not installed",
"locale.unsupported": "Unsupported region: {name}",
diff --git a/assets/locales/en/privacy.json b/assets/locales/en/privacy.json
index 52a1412..003a33c 100644
--- a/assets/locales/en/privacy.json
+++ b/assets/locales/en/privacy.json
@@ -11,6 +11,8 @@
"ask.listen": "“{app}” wants to accept network connections",
"ask.usb": "“{app}” wants to use USB devices",
"ask.bluetooth": "“{app}” wants to use Bluetooth",
+ "ask.keyring": "“{app}” wants to use a password that “{owner}” saved in the keyring",
+ "ask.keyringNote": "Only this item is shared, and only with this app.",
"ask.where": "You can change this later in Settings → Privacy.",
"allow": "Allow",
"deny": "Don’t allow",
diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.json
index b55c1a5..a84f6e1 100644
--- a/assets/locales/es/errors.json
+++ b/assets/locales/es/errors.json
@@ -7,6 +7,13 @@
"admin.tooMany": "Hay demasiadas acciones en curso; probá de nuevo en un momento",
"admin.unavailable": "El ayudante de administración no está disponible",
"admin.unknownAction": "Acción de administración desconocida",
+ "app.badFd": "Descriptor de archivo no válido",
+ "app.clipboardDenied": "Esta app no tiene permiso para leer el portapapeles",
+ "app.loadFailed": "No se pudo leer el código de la app",
+ "app.noSuchFile": "La app no incluye ese archivo",
+ "app.outsideFolder": "Esa ubicación está fuera de la carpeta de la app",
+ "app.readFailed": "No se pudo leer el archivo",
+ "app.writeFailed": "No se pudo escribir el archivo",
"backup.alreadyRunning": "Ya hay una copia en curso",
"backup.badConfig": "Configuración de copias inválida",
"backup.badDest": "Destino inválido",
@@ -214,6 +221,14 @@
"ipsec.noVici": "strongSwan (charon) no abrió su socket de control",
"ipsec.pskShort": "La clave compartida necesita al menos 8 caracteres",
"ipsec.viciFailed": "strongSwan rechazó {cmd}: {detail}",
+ "keyring.badRequest": "El pedido al llavero no es válido",
+ "keyring.busy": "Demasiados pedidos al llavero a la vez; probá de nuevo",
+ "keyring.failed": "El llavero no pudo completar el pedido",
+ "keyring.locked": "El llavero de la sesión está bloqueado",
+ "keyring.noKeyring": "No hay llavero de la sesión (se crea al ingresar con contraseña)",
+ "keyring.notFound": "El elemento no está en el llavero",
+ "keyring.notShared": "Ese elemento del llavero es de otra app y no se compartió con esta",
+ "keyring.saveFailed": "No se pudo guardar el llavero",
"lang.invalidCode": "Código de idioma inválido: {code}",
"locale.notGenerated": "La región {name} no está instalada",
"locale.unsupported": "Región no admitida: {name}",
diff --git a/assets/locales/es/privacy.json b/assets/locales/es/privacy.json
index e2f5770..14cde2e 100644
--- a/assets/locales/es/privacy.json
+++ b/assets/locales/es/privacy.json
@@ -11,6 +11,8 @@
"ask.listen": "«{app}» quiere aceptar conexiones de red",
"ask.usb": "«{app}» quiere usar dispositivos USB",
"ask.bluetooth": "«{app}» quiere usar Bluetooth",
+ "ask.keyring": "«{app}» quiere usar una contraseña que «{owner}» guardó en el llavero",
+ "ask.keyringNote": "Se comparte solo este elemento y solo con esta app.",
"ask.where": "Lo podés cambiar después en Ajustes → Privacidad.",
"allow": "Permitir",
"deny": "No permitir",
diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.json
index d505f73..174f100 100644
--- a/assets/locales/pt/errors.json
+++ b/assets/locales/pt/errors.json
@@ -7,6 +7,13 @@
"admin.tooMany": "Há ações demais em andamento; tente novamente em instantes",
"admin.unavailable": "O assistente de administração não está disponível",
"admin.unknownAction": "Ação de administração desconhecida",
+ "app.badFd": "Descritor de arquivo inválido",
+ "app.clipboardDenied": "Este app não tem permissão para ler a área de transferência",
+ "app.loadFailed": "Não foi possível ler o código do app",
+ "app.noSuchFile": "O app não inclui esse arquivo",
+ "app.outsideFolder": "Esse local está fora da pasta do app",
+ "app.readFailed": "Não foi possível ler o arquivo",
+ "app.writeFailed": "Não foi possível gravar o arquivo",
"backup.alreadyRunning": "Já há um backup em andamento",
"backup.badConfig": "Configuração de backup inválida",
"backup.badDest": "Destino inválido",
@@ -214,6 +221,14 @@
"ipsec.noVici": "O strongSwan (charon) não abriu o socket de controle",
"ipsec.pskShort": "A chave compartilhada precisa de pelo menos 8 caracteres",
"ipsec.viciFailed": "O strongSwan rejeitou {cmd}: {detail}",
+ "keyring.badRequest": "O pedido ao chaveiro não é válido",
+ "keyring.busy": "Pedidos demais ao chaveiro ao mesmo tempo; tente de novo",
+ "keyring.failed": "O chaveiro não conseguiu concluir o pedido",
+ "keyring.locked": "O chaveiro da sessão está bloqueado",
+ "keyring.noKeyring": "Não há chaveiro da sessão (ele é criado ao entrar com senha)",
+ "keyring.notFound": "O item não está no chaveiro",
+ "keyring.notShared": "Esse item do chaveiro é de outro app e não foi compartilhado com este",
+ "keyring.saveFailed": "Não foi possível salvar o chaveiro",
"lang.invalidCode": "Código de idioma inválido: {code}",
"locale.notGenerated": "A região {name} não está instalada",
"locale.unsupported": "Região não suportada: {name}",
diff --git a/assets/locales/pt/privacy.json b/assets/locales/pt/privacy.json
index 1842a83..a3226b8 100644
--- a/assets/locales/pt/privacy.json
+++ b/assets/locales/pt/privacy.json
@@ -11,6 +11,8 @@
"ask.listen": "“{app}” quer aceitar conexões de rede",
"ask.usb": "“{app}” quer usar dispositivos USB",
"ask.bluetooth": "“{app}” quer usar Bluetooth",
+ "ask.keyring": "“{app}” quer usar uma senha que “{owner}” salvou no chaveiro",
+ "ask.keyringNote": "Só este item é compartilhado, e só com este app.",
"ask.where": "Você pode mudar isso depois em Ajustes → Privacidade.",
"allow": "Permitir",
"deny": "Não permitir",
diff --git a/docs/NETWORK.md b/docs/NETWORK.md
index 64b0cb3..3113ca3 100644
--- a/docs/NETWORK.md
+++ b/docs/NETWORK.md
@@ -115,6 +115,7 @@ enabled. `lordos.service` now has `DelegateSubgroup=supervisor`.
| Static IP | address/prefix, gateway and DNS | ✅ |
| DNS | With systemd-resolved: `resolvectl` per interface. Without resolved: `/etc/resolv.conf`. | ✅ resolved |
| Coexistence with systemd-networkd | System interfaces are shown but not touched. `net-manage` hands them to LordOS and `net-unmanage` gives them back. | ✅ with a test interface |
+| Coexistence with NetworkManager | Interfaces with `managed=true` in `/run/NetworkManager/devices/<ifindex>` (read without D-Bus) are system interfaces too: lord-netd doesn't start DHCP or wpa_supplicant on them. `net-manage` only knows how to take them from systemd-networkd. | ✅ code; found on a Raspberry Pi OS board (2026-10-18), where lord-netd had started a second DHCP client and wpa_supplicant |
| Wi-Fi WPA2-Personal and open networks | wpa_supplicant (Debian) through its control socket. The PSK is computed with PBKDF2. | ✅ scan, wrong key, connection and DHCP, reconnection on restart, forget (with mac80211_hwsim + hostapd) |
| Wi-Fi WPA3 (SAE) | `sae_password` and `key_mgmt WPA-PSK SAE` | ⚠️ untested: the test hostapd is WPA2 |
| WireGuard | Our own generic netlink (`WG_CMD_SET_DEVICE`/`GET_DEVICE`) and our own X25519 keys | ✅ against the official `wg`: split and full tunnel (0.0.0.0/0 with fwmark and rules like wg-quick), DNS, status |
diff --git a/docs/PASSWORDS.md b/docs/PASSWORDS.md
index 9d17ec4..9bc0b5b 100644
--- a/docs/PASSWORDS.md
+++ b/docs/PASSWORDS.md
@@ -259,14 +259,57 @@ await keyring.list('mail'); // without secrets
asking app itself.
- **Trust boundary:** built-in apps run in the shell's JavaScript context, so for them the owner
string is passed by trusted system code, not enforced by a process boundary. For isolated `.lpk`
- apps the owner must be set by `lord-server` from the broker (the app id it already verifies);
- that broker op is still to do. The Passwords app process manages the keyring over its own
- vault channel, which only the system `passwords` package receives.
+ apps the owner is set by `lord-server` from the broker (see below). The Passwords app process
+ manages the keyring over its own vault channel, which only the system `passwords` package
+ receives.
- **Settings → Network** now stores Wi-Fi passwords (`wifi:<ssid>`) and VPN credentials
(`vpn:<name>`) in the keyring when you join or save, and offers them back with the 🔑 button.
The root-owned copy that `wpa_supplicant`/the VPN daemons need to connect at boot is still
written by the closed `admin.c` actions (as NetworkManager does with system connections).
+### Keyring for isolated .lpk apps
+
+An isolated app (`lord-server --app <id>`) has no `lord.vault`; the same SDK calls go through the
+broker instead, and the `app` argument is ignored:
+
+```js
+import { keyring } from '@lordos/sdk';
+await keyring.set(lord.appId, { service: 'sync.example.org', account: 'ana', secret: token, label: 'Sync' });
+const item = await keyring.get(lord.appId, { service: 'sync.example.org', account: 'ana' }); // { secret, … } | null
+await keyring.remove(lord.appId, { service: 'sync.example.org', account: 'ana' });
+await keyring.list(lord.appId); // own items and items shared with it, no secrets
+```
+
+How it works (`sec/brokerkr.c`, `ui/js_vault.c`):
+
+- The app calls `lord.keyring.request(op, service, account, label, secret)`, a broker request
+ (`BOP_KEYRING`, payload `op\0service\0account\0label\0secret`; op is `get`, `set`, `delete`
+ or `list`). Service, account and label are at most 255 bytes, the secret at most 64 KiB.
+- `lord-server` builds the `kr-*` request itself with **owner = `app.<id>`**, where `<id>` is the
+ app id it verified when it spawned the process. The app never sends an owner, and the `app.`
+ prefix keeps a package called `mail` away from the desktop's own `mail` items.
+- The request goes to `lord-vault` on lord-server's control-side channel as a *private request*
+ (`vc_request_private`): its reply goes to a queue that only lord-server's C code reads, never
+ to the desktop's JavaScript. lord-server does not use `vc_attach_app` for these apps, because an
+ attached channel is the Passwords app's and may manage every item. Nothing waits: the reply
+ wakes the main loop (an eventfd) and is sent back to the app; buffers that held a secret are
+ wiped.
+- An app sees only its own items. If it asks (`get`) for an item another app saved, lord-vault
+ answers `not-shared` and lord-server shows the **system consent prompt** («"Notes" wants to use a
+ password that "Sync" saved in the keyring», `privacy.ask.keyring`). If the user allows it,
+ lord-server records the share for that one item (`kr-share`) and asks again; if not, the app
+ gets `keyring.notShared`, and lord-server does not ask again for that app and item until the
+ session ends (an app cannot keep the prompt on screen by asking in a loop). A shared item can be read, never changed or deleted, by the other
+ app; for `set`, `delete` and `list` another app's items simply do not exist.
+- Errors are code lines (docs/LANGUAGES.md): `keyring.locked`, `keyring.noKeyring`,
+ `keyring.notFound`, `keyring.notShared`, `keyring.badRequest`, `keyring.saveFailed`,
+ `keyring.busy`, `keyring.failed`, `vault.unavailable`. The SDK keeps the short codes of the
+ shell (`e.code` = `locked`, `not-found`…, `e.errorCode` = the full code), so the same app code
+ works in both places.
+- Test: `make -C server build/brokerkr-e2e && server/build/brokerkr-e2e` (needs `build/lord-vault`;
+ isolation between two app ids, the prompt denied (and not asked again) and allowed, a desktop owner a package cannot
+ reach, a missing item, bad requests, a locked keyring and an app that closed mid-request).
+
### Autofill in native apps
`<AutofillButton app service|url|ssid onFill />` is a small 🔑 button next to a login field. It
diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md
index db4a22e..5bdf995 100644
--- a/docs/PRIVACY.md
+++ b/docs/PRIVACY.md
@@ -84,6 +84,7 @@ checked in `lord-server`:
| `broker.device(kind, on)` | turns the camera/microphone indicator on/off, only if that permission is granted |
| `broker.pick(save, name)` | **powerbox**: lord-server draws the open/save dialog and passes the app **only the fd** of the chosen file (SCM_RIGHTS); the app doesn't see the folder |
| `broker.menus(json)` | publishes the app's menus for the system menu bar; clicks come back as an event |
+| `keyring.request(op, …)` | the session keyring (`BOP_KEYRING`, `sec/brokerkr.c`): lord-server sets the owner to `app.<id>` from the verified app id; another app's item only after a **system prompt** (docs/PASSWORDS.md, "Keyring for isolated .lpk apps") |
In addition, lord-server sends the app, unrequested, the **live state** (`BOP_EVENT`): the theme
tokens (light/dark, accent, background), the language and direction (RTL), the keyboard layout,
@@ -542,3 +543,27 @@ Also fixed while testing: the app's event loop now drains broker events that arr
synchronous RPC (`js_broker_pending`), events are NUL-terminated before `JS_ParseJSON` (a
`revoke` could be dropped), and an isolated app no longer inherits `lord-server`'s blocked
`SIGTERM`/`SIGINT`.
+
+### Quitting, shortcuts and the keyboard layout
+
+- **Quit** (❖Q, or Dock → Quit): the session sends a `quit` event through the broker
+ (`brokersrv_quit`, `lord.broker.quit(app)`); the app host closes every window with `wm.close`, so
+ close guards still apply, and the process ends when the last window is gone. Other apps quit the
+ same way, by closing every window of their Dock entry (`quitApp` in `sdk/dock.js`).
+- **❖ shortcuts:** `appspawn.c` records the app process's real pid (the intermediate child reports
+ it through a pipe), so the compositor knows which Wayland client is an isolated LordOS app
+ (`brokersrv_app_of_pid`). That client also receives ❖ combinations (❖N, ❖C, ❖A, ❖W…) together
+ with the ❖ key itself, as an app inside the theme would. The system keeps ❖L, ❖⌃Q, ❖Q,
+ ❖Space, ❖⌥Space, ❖V, ❖., ❖Tab, ❖`, ❖Esc, ❖⇧3/4/5 and ❖F1–F12 (`system_meta_key` in
+ `wl/wl.c`); a Linux app still gets no ❖ combination.
+- **Keyboard layout:** the app compiles the keymap that the compositor sends over
+ `wl_keyboard.keymap` (`kb_set_keymap_string`), which is already expanded and reads no files.
+ `kb_set()` inside the sandbox failed, because Landlock hides `/usr/share/X11/xkb`
+ (`xkbcommon: ERROR … rules 'evdev'`); the broker now only moves the active group.
+
+![an isolated app's menu open in the system menu bar](appmode-menu.png)
+
+Tested in headless sessions on VM 116 (`lord-server --headless` as `lord`, real pointer and keys
+through the remote desktop socket): the app's menu opens from the menu bar and its
+items run in the app (File → New entry), ❖N/❖A/❖C/❖W reach the app while ❖V opens the clipboard
+history, and ❖Q and Dock → Quit end the process.
diff --git a/docs/RASPBERRY.md b/docs/RASPBERRY.md
index 152ee6b..95a2989 100644
--- a/docs/RASPBERRY.md
+++ b/docs/RASPBERRY.md
@@ -3,9 +3,13 @@
Since M8, ARM64 is an official LordOS platform, with the **Raspberry Pi 5** as the reference board.
This document gathers what's needed to build the image, write it, develop on the board and test it.
-> **Status (2026-10-16):** prepared in the code and tools, **not yet tested on a board**. The user's
-> 16 GB Pi 5 isn't on the network. Nothing below is verified on hardware: don't claim it works until
-> the test checklist below has been passed with screenshots.
+> **Status (2026-10-18):** first bring-up on a real **Raspberry Pi 5 (16 GB, SD card)** running
+> Raspberry Pi OS-style Debian 13 (kernel `6.18.50+rpt-rpi-2712`, 16K pages, no monitor attached).
+> Verified on the board: native build, the headless test suites, NEON, the arm64 `.deb`, lord-sessiond
+> and the login screen starting on vc4 without a monitor, and `build-img.sh` (see "Results on the
+> board"). **Not verified yet:** anything with a monitor on HDMI (KMS modeset, GPU composition on
+> screen, hardware cursor, FPS), the desktop session, remote-desktop screenshots, and booting the
+> image that `build-img.sh` produced.
## Models
@@ -65,14 +69,14 @@ SD card or an NVMe, and the same image boots on the Pi 5 and the Pi 4.
Researched as of October 2026 (confirm on the board):
-- **Debian 13's kernel** (`linux-image-arm64`, 6.12) boots on the Pi 4 with Debian's
+- **Debian 13's kernel** (`linux-image-arm64`, 6.12 at release) boots on the Pi 4 with Debian's
`raspi-firmware`. On the Pi 5 it lacks full board support: the RP1 chip (USB, Ethernet, GPIO) and
the BCM2712's display part reached Linux after 6.12, so without keyboard, network or HDMI it's no
use.
Also, Debian's `raspi-firmware` regenerates `config.txt` and `cmdline.txt` with every kernel, and
would overwrite LordOS's configuration.
-- **The Raspberry Pi kernel** (`linux-image-rpi-2712`, 6.12 with its patches) is the one from
+- **The Raspberry Pi kernel** (`linux-image-rpi-2712`; 6.18 with its patches as of October 2026, it was 6.12 at trixie's release) is the one from
Raspberry Pi OS Trixie. It has everything: RP1, vc4 with HDMI 4K60, v3d, the HEVC decoder, PCIe
gen 3 and the fan.
@@ -134,10 +138,17 @@ Variables:
**Before the first build:** check the fingerprint of the Raspberry Pi archive key
(`gpg --show-keys raspberrypi.gpg.key`) against an official source. The one in the script
-(`CF8A1AF5…7FA3303E`) was written down from memory and hasn't been verified.
+(`CF8A1AF5…7FA3303E`) was checked on 2026-10-18: it is the same fingerprint as the key in the signed
+`raspberrypi-archive-keyring` package (2025.1+rpt1) installed on a Raspberry Pi OS board.
-`build-img.sh` hasn't been run yet. Estimate: on x86-64 with qemu, 30–60 minutes the first time;
-natively on the Pi 5 with NVMe, about 10.
+The loose `raspberrypi.gpg.key` at the archive root still carries its 2012 SHA-1 binding signatures,
+and apt's `sqv` rejects them since 2026-02-01 ("SHA1 is not considered secure": `InRelease is not
+signed`). So `build-img.sh` takes the key from the archive's `raspberrypi-archive-keyring` package
+(re-signed with SHA-512), found through the `Packages` index; trust still comes only from the
+fingerprint check. `RPI_KEY_URL=<url>` uses another key file instead.
+
+Estimate: on x86-64 with qemu, 30–60 minutes the first time. Natively on the Pi 5 it was run on
+2026-10-18 from the SD card (see "Results on the board").
### Writing it
@@ -198,7 +209,7 @@ Options in `cmdline.txt` (a single line), as on the ISO:
| Option | What it does |
|---|---|
| `lordos.gpu=0` | safe mode: everything on the CPU |
-| `lordos.lang=en` / `pt` | first-boot language |
+| `lordos.lang=es` / `pt` | first-boot language (English by default, like the ISO) |
| `video=HDMI-A-1:1920x1080@60` | pins the mode, for example on a 4K monitor (on the CPU, 4K is heavy: see below) |
## Display and GPU on the Pi 5
@@ -392,11 +403,57 @@ Each item, with a screenshot or the pasted output, in this document.
| 11 | Temperature | `vcgencmd measure_temp`, `vcgencmd get_throttled`, LordOS Monitor (`cpu_thermal` and the fan) | <75 °C with the Active Cooler under load; `throttled=0x0` |
| 12 | NEON | `server/build/canvas-test` | "NEON matches C"; NEON faster than C |
| 13 | Headless tests | `make -C server test` and each `build/*-test` | all pass, as on x86 (WASM: the full wg-2.0 suite) |
-| 14 | App isolation | open a `.lpk`; `sandbox[...]:` in the log; `cat /sys/kernel/security/lsm` | seccomp=1 and Landlock if the kernel has it (the Raspberry Pi one might not) |
+| 14 | App isolation | open a `.lpk`; `sandbox[...]:` in the log; `cat /sys/kernel/security/lsm` | seccomp=1. **The Raspberry Pi kernel has no Landlock** (`# CONFIG_SECURITY_LANDLOCK is not set` in 6.18.50+rpt): seccomp only |
| 15 | Remote desktop | Settings → Sharing, `https://<ip>:5673` from the development machine | visible and controllable; screenshots for this document |
| 16 | Network and sound | Wi-Fi (brcmfmac), Ethernet, HDMI audio via PipeWire | IP from our own DHCP; `wpctl status` shows HDMI |
| 17 | Pi 4 | the same image | boots with `kernel8.img`; note what fails |
+## Results on the board (2026-10-18)
+
+Raspberry Pi 5, 16 GB, 32 GB SD card, no fan load, **no monitor on HDMI** (both HDMI connectors
+`disconnected`). Raspberry Pi OS-style Debian 13 with kernel `6.18.50+rpt-rpi-2712` (16K pages), GCC
+14.2, Mesa 26.2.2 from the Raspberry Pi archive, FFmpeg 7.1.5+rpt. Tree copied with rsync; themes built
+on the development machine.
+
+| What | Result |
+|---|---|
+| `make -C server -j4` (GPU=1, NEON=1) | ✅ every binary: lord-server, lord-sessiond, lord-netd, lord-netperm (BPF with clang), lord-doc, lord-media, lord-vault, lord-maild. 1 min 02 s. One GCC 14 `-Wformat-truncation` warning (`apps.c`), fixed: now 0 warnings |
+| `make -C server test` | ✅ `23 passed, 0 failed, 0 skipped` (with skkdic, rime-data-pinyin-simp, unicode-data and libthai-dev installed), plus engine-test 2642 checks, backup-test 220, vault-test 74, import-test 150 |
+| NEON (`build/canvas-test`) | ✅ "NEON matches C". blit 9.90 → 4.33 ms/screen, mask 11.09 → 5.49 ms/screen (2.0–2.3×) |
+| `make -C server test-full` | ⚠️ media-test probe/wave/sandbox ✅. `doc_evil.sh` 20/25: the 5 failures are the filesystem confinement checks (`~/.ssh`, home, `/tmp`), because **the Raspberry Pi kernel has no Landlock** (`# CONFIG_SECURITY_LANDLOCK is not set`, `/sys/kernel/security/lsm` = `capability`). seccomp works on aarch64 (`seccomp=1(tsync)`, no sockets, no fork). `sandbox-test` skipped for the same reason |
+| arm64 `.deb` (`DEB_ARCH=arm64 tools/iso/mkdeb.sh`) | ✅ 5.0 MB; dependencies resolve on Raspberry Pi OS (its `+rpt` FFmpeg keeps the Debian package names) |
+| lordos.service | ✅ `lord-sessiond: display: /dev/dri/card1` (vc4; v3d is card0, `drmcard.h` picks the right one). With nothing connected the login screen stays headless (`kms: no monitor connected`) instead of crash-looping. lord-server now keeps the lent card and retries on the next DRM uevent (`main.c`, parked fds): **compiled, not yet tried with a monitor** |
+| Idle (login screen, headless) | lord-server 36 MB RSS, 0.6 % CPU; lord-sessiond 4.4 + 2.5 MB; system total 450 MB used of 16 GB; 38–43 °C, `throttled=0x0`, 2.4 GHz |
+| EGL/GBM | `V3D 7.1.10.2`, OpenGL ES 3.1 (`eglinfo -p gbm`). LordOS's GPU path on screen not exercised (no monitor) |
+| Video (FFmpeg CLI) | HEVC 1080p30 through `rpi-hevc-dec` (`/dev/video19`, `-hwaccel drm -hwaccel_output_format drm_prime`): 300 frames in 0.54 s with 0.12 s of CPU. Software, 4 threads: HEVC 1080p 251 fps, H.264 1080p ~420 fps (synthetic `testsrc2` clip: real content is heavier). lord-media only knows VA-API, so inside LordOS HEVC is software for now |
+| `build-img.sh` natively on the Pi | ✅ after the key fix (above): 7 min 58 s from the SD card. `/var/tmp/lordos-rpi/out/lordos-0.7.0-rpi5-arm64.img.xz`, 500 MB (2651 MB uncompressed, system 1412 MB). Kernel 6.18.50+rpt, `kernel_2712.img`/`kernel8.img`, initramfs, 386 overlays. **The image hasn't been booted yet** (the board's only SD is the running system) |
+
+Found and fixed on the board:
+
+- **lord-netd vs NetworkManager.** Raspberry Pi OS uses NetworkManager (with netplan). lord-netd only
+ knew systemd-networkd and ifupdown, so it saw `eth0` and `wlan0` as free and started its own DHCP
+ client and a second `wpa_supplicant` on them, plus duplicate default routes. `managed_by_system()`
+ (`net/state.c`) now also reads `/run/NetworkManager/devices/<ifindex>` (`managed=true`); `net-test
+ state` shows both as `"managed":"system"`. The LordOS image has no NetworkManager, so there
+ lord-netd still owns the network.
+- **The Raspberry Pi archive key** (SHA-1 signatures rejected by apt; see "Building it").
+- **Default language** of the image and first boot: now English, like the ISO (it was Spanish).
+
+Notes for the image:
+
+- Raspberry Pi OS boots with `cgroup_disable=memory`; the image's `cmdline.txt` already has
+ `cgroup_enable=memory` (per-app memory limits need it).
+- `lsm=landlock,…` in the image's `cmdline.txt` does nothing on this kernel: Landlock isn't compiled
+ in. App and helper isolation on the Pi is seccomp + cgroups + no-new-privs only, until LordOS ships
+ a kernel with `CONFIG_SECURITY_LANDLOCK=y`.
+- The image takes Mesa (25.0.7) and FFmpeg (7.1.5) from Debian. Debian's FFmpeg has no V4L2-request
+ decoding, so the hardware HEVC seen above needs the Raspberry Pi FFmpeg pinned (option 1 in
+ "Video").
+
+Still to do on the board: everything in the checklist that needs a monitor (items 1, 2, 4–8, 10, 15
+with screenshots, 16 HDMI audio, 17), the desktop session, and booting the built image from a
+second SD card or an NVMe.
+
## Server portability audit (aarch64)
A review of `server/` on the development machine, without compiling for Linux ARM. The changed files were checked
diff --git a/docs/appmode-menu.png b/docs/appmode-menu.png
new file mode 100644
index 0000000..88f4eac
Binary files /dev/null and b/docs/appmode-menu.png differ
diff --git a/runtime/app-host.js b/runtime/app-host.js
index dcd219e..5da2c0f 100644
--- a/runtime/app-host.js
+++ b/runtime/app-host.js
@@ -109,6 +109,11 @@ globalThis.__lordBrokerEvent = (kind, data) => {
else if (data.type === 'focus') wm.focus(id);
}
else if (kind === 'window' && data && data.new) wm.open(APP, { new: true }); // Dock → «New window»
+ else if (kind === 'quit') {
+ // ❖Q or Dock → Quit: close every window; a close guard can still keep one open (unsaved
+ // changes). The process ends when the last window closes (appclient.c).
+ for (const w of [...windows.get()].reverse()) wm.close(w.id);
+ }
};
const revokeListeners = new Set();
globalThis.__lordOnRevoke = (fn) => { revokeListeners.add(fn); return () => revokeListeners.delete(fn); };
diff --git a/sdk/dock.js b/sdk/dock.js
index 13585a5..e79b8e3 100644
--- a/sdk/dock.js
+++ b/sdk/dock.js
@@ -9,6 +9,7 @@
// An app can add its own items to the menu (the Terminal: New Window, New Tab…):
// registerDockMenu('terminal', (entry) => [{ label: '…', onClick }])
import { createElement as h } from 'react';
+import { addListener } from '@lordos/runtime';
import { settings } from './settings.js';
import { useStore } from './store.js';
import { useWindows, wm, windowTitle, appIdOf, getApp, windows } from './windows.js';
@@ -123,7 +124,25 @@ export function dockActivate(e) {
wm.focus(next.id);
}
-const closeWindow = (w) => wm.close(w.id);
+// Quits an app: every window of its Dock entry closes, and each close guard still applies (it can
+// keep a window with unsaved changes open). An isolated app (its own process) is asked through
+// the broker, so its process closes its own windows and then ends.
+export function quitApp(wins) {
+ const iso = wins.find((w) => w.args?.pkg && w.args?.appId);
+ if (iso && typeof lord !== 'undefined' && lord.broker && typeof lord.broker.quit === 'function' && lord.broker.quit(iso.args.appId)) return;
+ for (const w of [...wins]) wm.close(w.id);
+}
+
+// ❖Q quits the app in front (only in the session: an isolated app never receives ❖Q).
+addListener('keydown', (e) => {
+ if (!e.meta || e.ctrl || e.alt || e.shift || e.repeat) return;
+ if (String(e.base || e.key || '').toLowerCase() !== 'q') return;
+ if (typeof lord !== 'undefined' && typeof lord.appId === 'string') return;
+ const top = wm.get(wm.focused());
+ if (!top) return;
+ const key = launcherIdOf(top);
+ quitApp(windows.get().filter((w) => launcherIdOf(w) === key));
+});
export function dockMenu(e) {
const top = wm.focused();
@@ -147,7 +166,7 @@ export function dockMenu(e) {
items.push(
{ label: t('shell.dock.showAll'), onClick: () => { for (const w of e.windows) wm.focus(w.id); } },
{ label: t('shell.dock.hide'), onClick: () => { for (const w of e.windows) wm.minimize(w.id); } },
- { label: t('shell.dock.quit'), onClick: () => { for (const w of [...e.windows]) closeWindow(w); } },
+ { label: t('shell.dock.quit'), onClick: () => quitApp(e.windows) },
);
} else items.push({ label: t('shell.dock.open'), onClick: () => launchApp(e.id) });
while (items[items.length - 1] === '-') items.pop();
diff --git a/sdk/index.js b/sdk/index.js
index f72848e..43f342d 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -39,7 +39,7 @@ export { logs } from './logs.js';
export { LordOSLogo } from './logo.js';
export { DesktopWidgets, registerWidgetType, setWidgets, desktopWidgets } from './widgets.js';
export { Markdown, markdownHeadings, parseMarkdown, parseInline, toggleTask } from './markdown.jsx';
-export { dock, useDockEntries, dockActivate, dockMenu, registerDockMenu, launcherIdOf, dockPrefs, DOCK_DEFAULTS } from './dock.js';
+export { dock, useDockEntries, dockActivate, dockMenu, registerDockMenu, launcherIdOf, dockPrefs, DOCK_DEFAULTS, quitApp } from './dock.js';
export { sound, useSound, useSoundPeak, soundState, defaultSink, defaultSource, microphones } from './sound.js';
export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, MONITOR_HISTORY, firewall, firewallState } from './monitor.js';
export { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';
diff --git a/sdk/privacy.js b/sdk/privacy.js
index 3aaae6d..e30b90c 100644
--- a/sdk/privacy.js
+++ b/sdk/privacy.js
@@ -54,7 +54,8 @@ if (typeof globalThis !== 'undefined') {
globalThis.__lordBroker = (kind, data) => {
try {
if (kind === 'prompt') {
- queue.set((q) => [...q, { id: seq++, app: data.app, perm: data.perm, broker: data.reqid }]);
+ // perm 'keyring': the app asks for an item another app saved (owner); see docs/PASSWORDS.md
+ queue.set((q) => [...q, { id: seq++, app: data.app, perm: data.perm, owner: data.owner, broker: data.reqid }]);
} else if (kind === 'menu') {
if (typeof globalThis.__lordApplyAppMenus === 'function') globalThis.__lordApplyAppMenus(data.app);
} else if (kind === 'pick') {
@@ -84,7 +85,8 @@ export function PermissionPrompt() {
if (!q.length) return null;
const item = q[0];
const name = appName(getApp(item.app)) || item.app;
- const msg = t(`privacy.ask.${item.perm}`, { app: name });
+ const owner = item.owner ? appName(getApp(item.owner)) || item.owner : '';
+ const msg = t(`privacy.ask.${item.perm}`, { app: name, owner });
return h(View, { style: { position: 'absolute', ...mainBox(), alignItems: 'center', justifyContent: 'flex-start',
backgroundColor: 'rgba(0,0,0,0.35)', zIndex: 100000 } },
h(View, { style: { marginTop: 80, width: 320, borderRadius: 14, padding: 20, gap: 14, backgroundColor: '#2b2b30',
@@ -92,7 +94,7 @@ export function PermissionPrompt() {
h(View, { style: { width: 44, height: 44, borderRadius: 10, backgroundColor: item.perm === 'camera' ? '#30d158' : item.perm === 'microphone' ? '#ff9f0a' : '#0a84ff',
alignItems: 'center', justifyContent: 'center' } }, h(Text, { style: { fontSize: 22 } }, glyph(item.perm))),
h(Text, { style: { fontSize: 14, fontWeight: 700, color: '#f5f5f7', textAlign: 'center', lineHeight: 1.4 } }, msg),
- h(Text, { style: { fontSize: 11, color: 'rgba(235,235,245,0.55)', textAlign: 'center' } }, t('privacy.ask.where')),
+ h(Text, { style: { fontSize: 11, color: 'rgba(235,235,245,0.55)', textAlign: 'center' } }, t(item.perm === 'keyring' ? 'privacy.ask.keyringNote' : 'privacy.ask.where')),
h(View, { style: { flexDirection: 'row', gap: 10, marginTop: 4 } },
h(Btn, { label: t('privacy.deny'), onClick: () => answer(item, false) }),
h(Btn, { primary: true, label: t('privacy.allow'), onClick: () => answer(item, true) }))));
@@ -104,7 +106,7 @@ function Btn({ label, primary, onClick }) {
h(Text, { style: { fontSize: 13, fontWeight: 600, color: '#fff' } }, label));
}
-const glyph = (p) => (p === 'camera' ? '📷' : p === 'microphone' ? '🎙' : p === 'screen' ? '▦' : p === 'network' ? '⇅' : '●');
+const glyph = (p) => (p === 'camera' ? '📷' : p === 'microphone' ? '🎙' : p === 'screen' ? '▦' : p === 'network' ? '⇅' : p === 'keyring' ? '🔑' : '●');
// ---- camera/microphone indicators ----
// Own source (isolated .lpk apps: the broker knows and reflects it here with markDeviceUse) +
diff --git a/sdk/vault.js b/sdk/vault.js
index 8848510..3ffee7b 100644
--- a/sdk/vault.js
+++ b/sdk/vault.js
@@ -6,7 +6,8 @@
// vaultRequest(op, args, { files }) → promise with the reply ({ ok, … }) or an error with .code
// onVaultEvent(fn) events: locked, unlocked, changed, touch, ss-prompt, keyring-mismatch, crash
// keyring.set(app, { service, account, secret, label }) / get(app, { service, account }) / remove / list
-// the session keyring, per app: an app only sees its own items (unless the user shares them)
+// the session keyring, per app: an app only sees its own items (unless the user shares them);
+// inside an isolated .lpk app it goes through the broker and the owner is the app's own id
// autofill(app, { url | service }) → [{ id, title, username }] from Passwords (if it is unlocked)
// <KeyringPrompt /> system prompt to unlock the keyring (mounted by startShell)
// <AutofillButton app service|url|ssid onFill /> "fill from Passwords" next to a login field
@@ -73,17 +74,38 @@ export function onVaultEvent(fn) {
}
// ---- the session keyring, per app ----
+// In an isolated .lpk app (lord-server --app <id>) there is no lord.vault: lord.keyring goes through
+// the broker, and lord-server sets the owner from the verified app id ("app.<id>"), so the `app`
+// argument is ignored there. Reading another app's item makes the system ask the user first.
+// Errors carry the same short codes in both cases (locked, no-keyring, not-found, not-shared,
+// unavailable); `errorCode` keeps the full code (keyring.locked…) and `message` is translated.
+
+const hasAppKeyring = () => typeof lord !== 'undefined' && !has() && lord.keyring && typeof lord.keyring.request === 'function';
+const KR_SHORT = { 'keyring.locked': 'locked', 'keyring.noKeyring': 'no-keyring', 'keyring.notFound': 'not-found',
+ 'keyring.notShared': 'not-shared', 'keyring.badRequest': 'bad-request', 'keyring.saveFailed': 'save', 'vault.unavailable': 'unavailable' };
+
+function appKeyring(op, service = '', account = '', label = '', secret) {
+ return Promise.resolve().then(() => {
+ try { return JSON.parse(lord.keyring.request(op, String(service), String(account), String(label), secret == null ? '' : String(secret))); }
+ catch (e) { throw Object.assign(e, { errorCode: e.code, code: KR_SHORT[e.code] || 'error' }); }
+ });
+}
export const keyring = {
- set: (app, { service, account = '', secret, label = '' }) => vaultRequest('kr-set', { owner: app, service, account, secret: String(secret ?? ''), label }),
+ set: (app, { service, account = '', secret, label = '' }) => (hasAppKeyring()
+ ? appKeyring('set', service, account, label, String(secret ?? ''))
+ : vaultRequest('kr-set', { owner: app, service, account, secret: String(secret ?? ''), label })),
get: async (app, { service, account = '' }) => {
- try { const r = await vaultRequest('kr-get', { owner: app, service, account }); return r.item; }
+ try { const r = hasAppKeyring() ? await appKeyring('get', service, account) : await vaultRequest('kr-get', { owner: app, service, account }); return r.item; }
catch (e) { if (e.code === 'not-found') return null; throw e; }
},
- remove: (app, { service, account = '' }) => vaultRequest('kr-del', { owner: app, service, account }),
- list: async (app) => (await vaultRequest('kr-list', { owner: app })).items || [],
- // the user agreed that `app` may use another app's item (the system asks, not the app)
- share: (id, app, allow = true) => vaultRequest('kr-share', { admin: true, id, app, allow }),
+ remove: (app, { service, account = '' }) => (hasAppKeyring() ? appKeyring('delete', service, account) : vaultRequest('kr-del', { owner: app, service, account })),
+ list: async (app) => (hasAppKeyring() ? await appKeyring('list') : await vaultRequest('kr-list', { owner: app })).items || [],
+ // the user agreed that `app` may use another app's item (the system asks, not the app); not
+ // available inside an isolated app: there lord-server asks the user by itself on get
+ share: (id, app, allow = true) => (hasAppKeyring()
+ ? Promise.reject(Object.assign(new Error('denied'), { code: 'denied' }))
+ : vaultRequest('kr-share', { admin: true, id, app, allow })),
};
// ---- autofill in the login fields of native apps ----
diff --git a/sdk/wayland.js b/sdk/wayland.js
index eaa334a..3cece0f 100644
--- a/sdk/wayland.js
+++ b/sdk/wayland.js
@@ -56,9 +56,11 @@ globalThis.__lordWayland = (sid, type, d = {}) => {
const area = pointerWorkArea(); // on the display under the pointer (docs/DISPLAYS.md)
const w = Math.min(area.w, d.width + c.w), hh = Math.min(area.h, d.height + c.h);
const n = windows.get().length;
+ // cascaded, but always inside the work area (never under the Dock)
+ const x = Math.round(area.x + (area.w - w) / 2 + (n % 5) * 24), y = Math.round(area.y + Math.max(8, (area.h - hh) / 2 - 30) + (n % 5) * 24);
wm.open('linux', {
instance: String(sid),
- frame: { w, h: hh, x: Math.round(area.x + (area.w - w) / 2 + (n % 5) * 24), y: Math.round(area.y + Math.max(8, (area.h - hh) / 2 - 30) + (n % 5) * 24) },
+ frame: { w, h: hh, x: Math.max(area.x, Math.min(x, area.x + area.w - w)), y: Math.max(area.y, Math.min(y, area.y + area.h - hh)) },
args: { surface: sid, csd: !!d.csd, appId: d.appId || '', pkg: !!(d.appId && (getApp(d.appId)?.package || getApp(d.appId)?.isolated)) },
});
// app .lpk aislada: su nombre (del manifest) en vez del id
@@ -70,7 +72,12 @@ globalThis.__lordWayland = (sid, type, d = {}) => {
break;
}
case 'unmap': if (win) wm.close(id, true); break;
- case 'title': if (win) wm.setTitle(id, d.title || null); break;
+ case 'title': { // an isolated app keeps its name when the title is just its id
+ if (!win) break;
+ const pkg = win.args?.pkg ? getApp(win.args.appId) : null;
+ wm.setTitle(id, pkg && (!d.title || d.title === win.args.appId) ? (pkg.isolated ? appName(pkg) : pkg.name) : (d.title || null));
+ break;
+ }
case 'geometry': { // la app cambió su tamaño por su cuenta
if (!win || win.maximized) break;
const c = win.args?.csd ? { w: 0, h: 0 } : windowChrome();
diff --git a/sdk/windows.js b/sdk/windows.js
index 4b351ef..c671490 100644
--- a/sdk/windows.js
+++ b/sdk/windows.js
@@ -101,13 +101,18 @@ export const workArea = (d) => workAreaOf(d);
function place(appId, count, frame) {
if (frame) return { ...frame, minimized: false, maximized: false };
- const [w, h] = registry.get(appId)?.size || [640, 420];
+ const [sw, sh] = registry.get(appId)?.size || [640, 420];
const offset = (count % 6) * 30;
const area = workAreaOf(pointerDisplay()); // where the pointer is (docs/DISPLAYS.md)
+ // the whole window stays inside the work area: a cascaded window must not slide under the
+ // Dock, which would cover (and take the clicks of) its bottom edge
+ const w = Math.min(sw, area.w), h = Math.min(sh, area.h);
+ const x = Math.round(area.x + (area.w - w) / 2 - 60 + offset);
+ const y = Math.round(Math.max(area.y + 16, area.y + (area.h - h) / 2 - 40 + offset));
return {
w, h, minimized: false, maximized: false,
- x: Math.round(area.x + (area.w - w) / 2 - 60 + offset),
- y: Math.round(Math.max(area.y + 16, area.y + (area.h - h) / 2 - 40 + offset)),
+ x: Math.max(area.x, Math.min(x, area.x + area.w - w)),
+ y: Math.max(area.y, Math.min(y, area.y + area.h - h)),
};
}
diff --git a/server/Makefile b/server/Makefile
index c86c6a3..eae895f 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -51,7 +51,7 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)
MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.
MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c
-SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c
+SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c
# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)
APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c
SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/ime.c src/wl/wl.c \
diff --git a/server/mk/vault-ctap.mk b/server/mk/vault-ctap.mk
index 5b42802..f361a15 100644
--- a/server/mk/vault-ctap.mk
+++ b/server/mk/vault-ctap.mk
@@ -1,7 +1,7 @@
-# FIDO2 de Contraseñas (src/vault/ctap2.c, p256.c, cbor.c, fidodev.c; docs/PASSWORDS.md).
-# ctap-test corre con `make test`; softfido y fido-e2e necesitan root (uhid): ver
-# ../tests/fido-soft/run-pw-116.sh. Los prerrequisitos van escritos a mano (este archivo se
-# incluye antes que mk/vault.mk).
+# FIDO2 for Passwords (src/vault/ctap2.c, p256.c, cbor.c, fidodev.c; docs/PASSWORDS.md).
+# ctap-test runs with `make test`; softfido and fido-e2e need root (uhid): see
+# ../tests/fido-soft/run-pw-116.sh. The prerequisites are written by hand (this file is
+# included before mk/vault.mk).
CTAP_SRC := src/vault/ctap2.c src/vault/p256.c src/vault/cbor.c src/vault/fidodev.c src/vault/vcrypto.c src/pkg/crypto.c
CTAP_HDR := src/vault/ctap2.h src/vault/p256.h src/vault/cbor.h src/vault/fidodev.h src/vault/vcrypto.h src/pkg/crypto.h
build/ctap-test: tests/ctap_test.c $(CTAP_SRC) $(CTAP_HDR)
diff --git a/server/mk/vault-dbus.mk b/server/mk/vault-dbus.mk
index 42ed188..8e498d9 100644
--- a/server/mk/vault-dbus.mk
+++ b/server/mk/vault-dbus.mk
@@ -1,6 +1,6 @@
-# Secret Service (org.freedesktop.secrets) con D-Bus propio: src/vault/dbus.c y secretsvc.c
-# (docs/PASSWORDS.md). dbus-test corre en make test; secretsvc-demo se prueba con
-# tests/secretsvc/run-pw-116.sh contra el bus real y secret-tool.
+# Secret Service (org.freedesktop.secrets) with our own D-Bus: src/vault/dbus.c and secretsvc.c
+# (docs/PASSWORDS.md). dbus-test runs in make test; secretsvc-demo is tested with
+# tests/secretsvc/run-pw-116.sh against the real bus and secret-tool.
SS_SRC := src/vault/dbus.c src/vault/secretsvc.c src/vault/smem.c src/vault/vcrypto.c src/pkg/crypto.c
SS_HDR := src/vault/dbus.h src/vault/secretsvc.h src/vault/smem.h src/vault/vcrypto.h src/pkg/crypto.h
SS_SAN := $(shell echo 'int main(void){return 0;}' | $(CC) -fsanitize=address,undefined -x c - -o /dev/null 2>/dev/null && echo -fsanitize=address,undefined -fno-omit-frame-pointer)
diff --git a/server/mk/vault-import.mk b/server/mk/vault-import.mk
index 102b82f..eb0a23d 100644
--- a/server/mk/vault-import.mk
+++ b/server/mk/vault-import.mk
@@ -1,5 +1,5 @@
-# Importar/exportar contraseñas (src/vault/vimport.c, csvp.c, kdbx.c, xmlmini.c; docs/PASSWORDS.md).
-# La prueba usa smem sobre malloc (tests/import_smem_shim.c) para que ASan/LSan vean cada bloque.
+# Importing/exporting passwords (src/vault/vimport.c, csvp.c, kdbx.c, xmlmini.c; docs/PASSWORDS.md).
+# The test uses smem over malloc (tests/import_smem_shim.c) so ASan/LSan see every block.
IMPORT_SRC := src/vault/vimport.c src/vault/csvp.c src/vault/kdbx.c src/vault/xmlmini.c
IMPORT_HDR := src/vault/vimport.h src/vault/csvp.h src/vault/kdbx.h src/vault/xmlmini.h src/vault/vjson.h src/vault/smem.h src/vault/vstb.h src/vault/vcrypto.h
IMPORT_SAN := $(shell echo 'int main(void){return 0;}' | $(CC) -fsanitize=address,undefined -x c - -o /dev/null 2>/dev/null && echo -fsanitize=address,undefined -fno-omit-frame-pointer)
diff --git a/server/mk/vault-qr.mk b/server/mk/vault-qr.mk
index 573f474..48ffda2 100644
--- a/server/mk/vault-qr.mk
+++ b/server/mk/vault-qr.mk
@@ -1,5 +1,5 @@
-# Códigos QR propios (src/vault/qr.c): respuestas conocidas (segno), ida y vuelta, corrección de
-# errores, imágenes reales (tests/qr/) y fuzz. Con ASan/UBSan si el compilador los tiene.
+# Our own QR codes (src/vault/qr.c): known answers (segno), round trip, error
+# correction, real images (tests/qr/) and fuzz. With ASan/UBSan if the compiler has them.
QR_SAN := $(shell echo 'int main(void){return 0;}' | $(CC) -fsanitize=address,undefined -x c -o /dev/null - 2>/dev/null && echo -fsanitize=address,undefined)
build/qr-test: tests/qr_test.c src/vault/qr.c src/vault/qr.h src/vault/smem.c src/vault/smem.h tests/qr/qr_ref.h build/obj/vault/vstb.o
@mkdir -p build
diff --git a/server/mk/vault.mk b/server/mk/vault.mk
index ef7a482..8d79cff 100644
--- a/server/mk/vault.mk
+++ b/server/mk/vault.mk
@@ -1,18 +1,18 @@
-# Contraseñas y llavero del sistema (src/vault, docs/PASSWORDS.md). Monocypher 4.0.2 vendorizado
-# (CC0) en ../third_party/monocypher. Cada parte agrega sus pruebas en mk/vault-*.mk.
+# Passwords and the system keyring (src/vault, docs/PASSWORDS.md). Monocypher 4.0.2 vendored
+# (CC0) in ../third_party/monocypher. Each part adds its tests in mk/vault-*.mk.
MC_DIR := ../third_party/monocypher
VAULT_CPP := -isystem $(MC_DIR)
build/obj/vault/monocypher.o: $(MC_DIR)/monocypher.c $(MC_DIR)/monocypher.h
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) -w -c -o $@ $<
-# Vectores oficiales de Monocypher (tests/test.c + tests/vectors.h del tar de la versión)
+# Monocypher's official vectors (tests/test.c + tests/vectors.h from the release tarball)
build/monocypher-test: $(MC_DIR)/tests/test.c $(MC_DIR)/tests/utils.c $(MC_DIR)/tests/utils.h $(MC_DIR)/tests/vectors.h $(MC_DIR)/monocypher.c $(MC_DIR)/monocypher-ed25519.c
@mkdir -p build
$(CC) $(CFLAGS) -w -std=c11 -I$(MC_DIR) -I$(MC_DIR)/tests -o $@ $(MC_DIR)/tests/test.c $(MC_DIR)/tests/utils.c $(MC_DIR)/monocypher.c $(MC_DIR)/monocypher-ed25519.c
./$@ > build/monocypher-test.log || { cat build/monocypher-test.log; rm -f $@; exit 1; }
@tail -n 3 build/monocypher-test.log
test: build/monocypher-test
-# Primitivas comunes de la bóveda (AES, SHA-1, HMAC, HKDF, arena de secretos, stb con la arena)
+# Common vault primitives (AES, SHA-1, HMAC, HKDF, secrets arena, stb on the arena)
VAULT_BASE := src/vault/smem.c src/vault/vcrypto.c src/pkg/crypto.c
build/obj/vault/vstb.o: src/vault/vstb.c src/vault/vstb.h src/vault/smem.h
@mkdir -p $(dir $@)
@@ -22,7 +22,7 @@ build/vcrypto-test: tests/vcrypto_test.c $(VAULT_BASE) src/vault/vcrypto.h src/v
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/vcrypto_test.c $(VAULT_BASE) -lpthread
./$@ || { rm -f $@; exit 1; }
test: build/vcrypto-test
-# Listas embebidas en lord-vault (palabras de la EFF, contraseñas comunes): ../third_party/wordlists
+# Lists embedded in lord-vault (EFF words, common passwords): ../third_party/wordlists
build/obj/vault/lists.o: ../third_party/wordlists/eff_large_wordlist.txt ../third_party/wordlists/10k-most-common.txt
@mkdir -p build/gen/vault build/obj/vault
cp ../third_party/wordlists/eff_large_wordlist.txt build/gen/vault/words.txt
@@ -31,32 +31,35 @@ build/obj/vault/lists.o: ../third_party/wordlists/eff_large_wordlist.txt ../thir
VAULT_CORE := src/vault/smem.c src/vault/vcrypto.c src/vault/vjson.c src/vault/vfile.c src/vault/vmodel.c src/vault/vgen.c \
src/vault/totp.c src/vault/vwire.c src/pkg/crypto.c
VAULT_HDR := $(wildcard src/vault/*.h) src/sec/sandbox.h
-# formato, modelo, TOTP, generador, JSON y protocolo (tests/vault_test.c)
+# format, model, TOTP, generator, JSON and protocol (tests/vault_test.c)
build/vault-test: tests/vault_test.c $(VAULT_CORE) build/obj/vault/monocypher.o build/obj/vault/lists.o $(VAULT_HDR)
@mkdir -p build
$(CC) $(CPPFLAGS) $(VAULT_CPP) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/vault_test.c $(VAULT_CORE) build/obj/vault/monocypher.o build/obj/vault/lists.o -lpthread -lm
./$@ || { rm -f $@; exit 1; }
test: build/vault-test
-# lord-vault: el ayudante encerrado de Contraseñas y del llavero (src/vault/vault.c)
+# lord-vault: the confined Passwords and keyring helper (src/vault/vault.c)
LV_SRC := $(VAULT_CORE) src/vault/vault.c src/vault/keyring.c src/vault/vimport.c src/vault/csvp.c src/vault/kdbx.c src/vault/xmlmini.c \
src/vault/qr.c src/vault/ctap2.c src/vault/p256.c src/vault/cbor.c src/vault/secretsvc.c src/vault/dbus.c \
src/sec/sandbox.c src/sec/cgroup.c
build/lord-vault: $(LV_SRC) build/obj/vault/monocypher.o build/obj/vault/vstb.o build/obj/vault/lists.o $(VAULT_HDR)
@mkdir -p build
$(CC) $(CPPFLAGS) $(VAULT_CPP) $(CFLAGS) $(WARN) -std=c11 -o $@ $(LV_SRC) build/obj/vault/monocypher.o build/obj/vault/vstb.o build/obj/vault/lists.o -lpthread -lm
-# (solo cuando están todas sus partes, así el árbol compila siempre)
+# (only when all its parts are there, so the tree always builds)
LV_READY := $(and $(wildcard src/vault/secretsvc.c),$(wildcard src/vault/dbus.c),$(wildcard src/vault/vimport.c),$(wildcard src/vault/kdbx.c),$(wildcard src/vault/csvp.c),$(wildcard src/vault/xmlmini.c))
ifneq ($(LV_READY),)
all: build/lord-vault
endif
-# Lado de lord-server: lanzar lord-vault, su canal y lord.vault (src/vault/vclient.c, src/ui/js_vault.c).
-# Se suman a build/lord-server como prerrequisitos ($^ los incluye en el enlace).
+# lord-server side: launching lord-vault, its channel and lord.vault (src/vault/vclient.c, src/ui/js_vault.c).
+# They are added to build/lord-server as prerequisites ($^ includes them in the link).
VC_OBJ := build/obj/vault/vclient.o build/obj/vault/vwire.o build/obj/vault/fidodev.o build/obj/ui/js_vault.o
build/lord-server: $(VC_OBJ)
$(VC_OBJ): $(wildcard src/vault/vclient.h src/vault/vwire.h src/vault/fidodev.h src/ui/js_vault.h)
-# lord-vault de punta a punta con el cliente de lord-server (necesita build/lord-vault; no corre solo)
+# lord-vault end to end with lord-server's client (needs build/lord-vault; does not run by itself)
build/vault-e2e: tests/vault_e2e.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c src/vault/vjson.c src/vault/smem.c $(VAULT_HDR) build/lord-vault
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/vault_e2e.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c src/vault/vjson.c src/vault/smem.c -lpthread
-# bóveda de demostración para las capturas (no es una prueba)
+# the keyring op of isolated .lpk apps (src/sec/brokerkr.c) against lord-vault (needs build/lord-vault)
+build/brokerkr-e2e: tests/brokerkr_e2e.c src/sec/brokerkr.c src/sec/json.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c src/sec/broker_int.h src/sec/broker.h $(VAULT_HDR) build/lord-vault
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/brokerkr_e2e.c src/sec/brokerkr.c src/sec/json.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c -lpthread
+# demo vault for the screenshots (not a test)
build/vault-demo: tests/vault_demo.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c src/vault/vjson.c src/vault/smem.c $(VAULT_HDR)
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/vault_demo.c src/vault/vclient.c src/vault/vwire.c src/vault/fidodev.c src/vault/vjson.c src/vault/smem.c -lpthread
diff --git a/server/src/app/app.h b/server/src/app/app.h
index c0e09c0..e29a18e 100644
--- a/server/src/app/app.h
+++ b/server/src/app/app.h
@@ -1,15 +1,15 @@
-/* app.h — «modo app» de lord-server: correr una app .lpk como su propio proceso aislado y
- * cliente Wayland del compositor (ver appclient.c, docs/PRIVACY.md). */
+/* app.h — lord-server's "app mode": running an .lpk app as its own isolated process and a
+ * Wayland client of the compositor (see appclient.c, docs/PRIVACY.md). */
#ifndef LORD_APP_H
#define LORD_APP_H
#include <stddef.h>
-/* `lord-server --app <id>`: corre la app instalada <id>. Devuelve el código de salida. */
+/* `lord-server --app <id>`: runs the installed app <id>. Returns the exit code. */
int app_main(const char *id, const char *theme_bundle, const char *fonts);
-/* Desde lord-server (el compositor): lanza la app <id> como proceso aislado y registra su broker.
- * 0 si lanzó. El id tiene que ser de un paquete instalado (se valida). */
+/* From lord-server (the compositor): launches app <id> as an isolated process and registers its
+ * broker. 0 if it started. The id must be an installed package (it is validated). */
int app_spawn(const char *id);
/* Package folder of app <id>. A system app shipped with LordOS (<assets>/sysapps/<id>, owned by
diff --git a/server/src/app/appclient.c b/server/src/app/appclient.c
index 4a31d40..7f64c15 100644
--- a/server/src/app/appclient.c
+++ b/server/src/app/appclient.c
@@ -379,20 +379,38 @@ static void gestures_setup(void) {
zwp_pointer_gesture_swipe_v1_add_listener(zwp_pointer_gestures_v1_get_swipe_gesture(gestures, pointer), &swipe_listener, NULL);
}
-static void k_keymap(void *d, struct wl_keyboard *k, uint32_t fmt, int32_t fd, uint32_t sz) { (void)d; (void)k; (void)fmt; (void)sz; if (fd >= 0) close(fd); }
+/* The compositor's keymap (the user's layouts, already expanded): compiling it reads no files,
+ * so it also works inside the sandbox (keyboard.c kb_set_keymap_string). */
+static void k_keymap(void *d, struct wl_keyboard *k, uint32_t fmt, int32_t fd, uint32_t sz) {
+ (void)d; (void)k;
+ if (fd < 0) return;
+ if (fmt == WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 && sz > 1 && sz < (16u << 20)) {
+ char *m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (m != MAP_FAILED) {
+ if (!memchr(m, 0, sz) || m[sz - 1] == 0) {
+ char *txt = strndup(m, sz);
+ if (txt) { kb_set_keymap_string(txt); free(txt); }
+ }
+ munmap(m, sz);
+ }
+ }
+ close(fd);
+}
/* keyboard focus moved to one of our windows: the app host raises it (wm.focus) */
static void k_enter(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf, struct wl_array *keys) {
(void)d; (void)k; (void)s; (void)keys;
AppWin *w = win_by_surface(sf);
+ kb_reset_state(); /* keys released while another window had the keyboard */
if (w && w != kbd_win) { kbd_win = w; win_event(w, "focus"); }
}
-static void k_leave(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf) { (void)d; (void)k; (void)s; (void)sf; }
+static void k_leave(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf) { (void)d; (void)k; (void)s; (void)sf; kb_reset_state(); }
static void k_key(void *d, struct wl_keyboard *k, uint32_t s, uint32_t t, uint32_t key, uint32_t st) {
(void)d; (void)k; (void)s; (void)t;
js_key((int)key, st == WL_KEYBOARD_KEY_STATE_PRESSED ? 1 : 0);
}
static void k_mods(void *d, struct wl_keyboard *k, uint32_t s, uint32_t dep, uint32_t lat, uint32_t lock, uint32_t grp) {
- (void)d; (void)k; (void)s; (void)dep; (void)lat; (void)lock; (void)grp; /* los modificadores salen de las propias teclas */
+ (void)d; (void)k; (void)s; (void)dep; (void)lat; (void)lock; /* modifiers come from the keys themselves */
+ kb_set_group((int)grp); /* the active layout follows the compositor */
}
static void k_repeat(void *d, struct wl_keyboard *k, int32_t rate, int32_t delay) { (void)d; (void)k; (void)rate; (void)delay; }
static const struct wl_keyboard_listener k_listener = { k_keymap, k_enter, k_leave, k_key, k_mods, k_repeat };
@@ -439,7 +457,7 @@ static int manifest_pair(const char *dir, const char *key, int *w, int *h) {
}
int app_main(const char *id, const char *theme_bundle, const char *fonts) {
- if (!lpk_valid_id(id)) { fprintf(stderr, "lord-server --app: id inválido\n"); return 2; }
+ if (!lpk_valid_id(id)) { fprintf(stderr, "lord-server --app: invalid id\n"); return 2; }
char dir[PATH_MAX];
{
/* <assets> = the parent of the fonts folder; a system app there wins over a user .lpk */
@@ -448,7 +466,7 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
char *sl = strrchr(assets, '/');
if (sl) *sl = 0;
if (app_package_dir(id, assets, dir, sizeof dir) < 0) {
- fprintf(stderr, "lord-server --app: la app '%s' no está instalada\n", id);
+ fprintf(stderr, "lord-server --app: app '%s' is not installed\n", id);
return 2;
}
}
@@ -460,16 +478,16 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
snprintf(data, sizeof data, "%s/%.40s", parent, id);
mkdir(data, 0700);
- if (text_init(fonts)) { fprintf(stderr, "lord-server --app: sin fuentes\n"); return 1; }
+ if (text_init(fonts)) { fprintf(stderr, "lord-server --app: no fonts\n"); return 1; }
{ char a[PATH_MAX * 2]; snprintf(a, sizeof a, "%.*s/..", (int)(sizeof a - 4), fonts); js_sys_set_assets(a); }
kb_set("us", "");
dpy = wl_display_connect(NULL);
- if (!dpy) { fprintf(stderr, "lord-server --app: no se pudo conectar al compositor\n"); return 1; }
+ if (!dpy) { fprintf(stderr, "lord-server --app: could not connect to the compositor\n"); return 1; }
struct wl_registry *reg = wl_display_get_registry(dpy);
wl_registry_add_listener(reg, &reg_listener, NULL);
wl_display_roundtrip(dpy);
- if (!comp || !shm || !wm) { fprintf(stderr, "lord-server --app: el compositor no ofrece lo necesario\n"); return 1; }
+ if (!comp || !shm || !wm) { fprintf(stderr, "lord-server --app: the compositor lacks a required interface\n"); return 1; }
app_id_str = id;
int mw = 640, mh = 480, nw = 0, nh = 0;
@@ -493,7 +511,7 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
SandboxConfig sb = { .id = id, .pkg_dir = dir, .data_dir = data, .runtime_dir = getenv("XDG_RUNTIME_DIR"), .ro_extra = ro, .network = net };
sandbox_apply(&sb);
- if (js_init_app(theme_bundle, id)) { fprintf(stderr, "lord-server --app: no se pudo cargar la app\n"); return 1; }
+ if (js_init_app(theme_bundle, id)) { fprintf(stderr, "lord-server --app: could not load the app\n"); return 1; }
int wfd = wl_display_get_fd(dpy);
double start = now_ms();
diff --git a/server/src/app/appspawn.c b/server/src/app/appspawn.c
index f88e55c..bc3fdfc 100644
--- a/server/src/app/appspawn.c
+++ b/server/src/app/appspawn.c
@@ -1,8 +1,8 @@
-/* appspawn.c — lord-server lanza una app .lpk como su propio proceso aislado
- * (`lord-server --app <id>`), la tercera excepción acotada a «el servidor no ejecuta comandos»
- * (ver AGENTS.md). El único argumento es un id VALIDADO de un paquete instalado; nunca argumentos
- * del llamador. Se crea el socket del broker (socketpair) y se le pasa al hijo; el extremo del
- * servidor queda registrado en brokersrv.c. */
+/* appspawn.c — lord-server launches an .lpk app as its own isolated process
+ * (`lord-server --app <id>`), the third narrow exception to "the server does not run commands"
+ * (see AGENTS.md). The only argument is a VALIDATED id of an installed package, never caller
+ * arguments. The broker socket (socketpair) is created here and handed to the child; the server
+ * end is registered in brokersrv.c together with the app process's real pid. */
#include "app.h"
#include "../lpk.h"
#include "../sec/broker.h"
@@ -41,7 +41,7 @@ int app_package_dir(const char *id, const char *assets, char *out, size_t n) {
/* System apps that get their own channel to lord-vault (vc_attach_app): only Passwords. */
static int wants_vault(const char *id, int system) { return system == 1 && !strcmp(id, "passwords"); }
-/* 0 si lanzó el proceso (y registró el broker). El id tiene que ser de un paquete instalado. */
+/* 0 if the process was started (and its broker registered). The id must be an installed package. */
int app_spawn(const char *id) {
if (!lpk_valid_id(id)) return -1;
char dir[PATH_MAX];
@@ -57,15 +57,20 @@ int app_spawn(const char *id) {
int sv[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv)) return -1;
- /* el extremo del hijo NO es CLOEXEC: lo hereda el proceso de la app */
+ /* the child's end is NOT close-on-exec: the app process inherits it */
fcntl(sv[1], F_SETFD, 0);
+ /* the intermediate child reports the app's real pid here (so the compositor can tell which
+ * Wayland client is this app: wl.c routes its ❖ shortcuts to it) */
+ int pp[2];
+ if (pipe2(pp, O_CLOEXEC)) { close(sv[0]); close(sv[1]); return -1; }
/* Passwords talks to lord-vault on its own channel: decrypted data never passes through here */
int vfd = wants_vault(id, sys) ? vc_attach_app() : -1;
pid_t pid = fork();
if (pid == 0) {
setsid();
- if (fork() != 0) _exit(0); /* nieto huérfano, como el lanzador de apps Linux */
+ pid_t g = fork(); /* orphaned grandchild, like the Linux app launcher */
+ if (g != 0) { if (g > 0 && write(pp[1], &g, sizeof g) != (ssize_t)sizeof g) _exit(1); _exit(0); }
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
sigset_t none; /* lord-server blocks SIGINT/SIGTERM (signalfd): not the app */
@@ -82,17 +87,21 @@ int app_spawn(const char *id) {
} else unsetenv("LORD_VAULT_FD");
int null = open("/dev/null", O_RDWR);
if (null >= 0) { dup2(null, 0); if (null > 2) close(null); }
- /* el id lo pasa lord-server, ya validado; no hay argumentos del llamador */
+ /* lord-server passes the id, already validated; there are no caller arguments */
char *const argv[] = { self, (char *)"--app", (char *)id, NULL };
execve("/proc/self/exe", argv, environ); /* not `self`: after a package upgrade it is "<path> (deleted)" */
_exit(127);
}
close(sv[1]);
+ close(pp[1]);
if (vfd >= 0) close(vfd);
- if (pid < 0) { close(sv[0]); return -1; }
- waitpid(pid, NULL, 0); /* el hijo intermedio sale enseguida */
- if (brokersrv_add(sv[0], id, pid)) { close(sv[0]); return -1; }
+ if (pid < 0) { close(sv[0]); close(pp[0]); return -1; }
+ waitpid(pid, NULL, 0); /* the intermediate child exits right away */
+ pid_t app = -1;
+ if (read(pp[0], &app, sizeof app) != (ssize_t)sizeof app || app <= 0) app = -1;
+ close(pp[0]);
+ if (brokersrv_add(sv[0], id, (int)app)) { close(sv[0]); return -1; }
if (vfd >= 0) brokersrv_set_vault(sv[0]); /* this app may also ask for the FIDO2 device */
- fprintf(stderr, "lord-server: app '%s' lanzada como proceso aislado\n", id);
+ fprintf(stderr, "lord-server: app '%s' started as an isolated process (pid %d)\n", id, (int)app);
return 0;
}
diff --git a/server/src/apps.c b/server/src/apps.c
index 32d3ade..cad2a01 100644
--- a/server/src/apps.c
+++ b/server/src/apps.c
@@ -275,8 +275,8 @@ int apps_list(const char *lang, const DesktopApp **out) {
if (!valid_id(id) || seen(id, ids, nids)) continue;
if (nids < MAX_APPS * 2) snprintf(ids[nids++], sizeof ids[0], "%s", id); /* it also shadows if hidden */
char file[PATH_MAX * 2];
- snprintf(file, sizeof file, "%s/%s", dirs[d], de->d_name);
- if (strlen(file) >= PATH_MAX || parse_desktop(file, lang, e)) continue;
+ int flen = snprintf(file, sizeof file, "%s/%s", dirs[d], de->d_name);
+ if (flen < 0 || flen >= PATH_MAX || parse_desktop(file, lang, e)) continue;
if (!e->is_app || e->hidden || e->nodisplay || e->terminal || !e->has_name || !e->exec[0]) continue;
if (e->only[0] && !list_has(e->only, "LordOS")) continue;
if (e->not_[0] && list_has(e->not_, "LordOS")) continue;
diff --git a/server/src/hw/display.c b/server/src/hw/display.c
index 17e1104..b180bb6 100644
--- a/server/src/hw/display.c
+++ b/server/src/hw/display.c
@@ -642,7 +642,11 @@ void display_attached(void) {
void display_detached(void) { D.off = 0; D.soft = D.soft && D.kelvin != NIGHT_K_MAX; memset(&D.cur, 0, sizeof D.cur); }
+static unsigned hotplug_seq;
+unsigned display_hotplug_seq(void) { return hotplug_seq; }
+
void display_hotplug(void) {
+ hotplug_seq++;
Kms *k = kms();
if (k) {
KmsOutput outs[KMS_MAX_OUTPUTS];
diff --git a/server/src/hw/display.h b/server/src/hw/display.h
index 3df7f51..7003e8b 100644
--- a/server/src/hw/display.h
+++ b/server/src/hw/display.h
@@ -59,6 +59,9 @@ void display_resync_done(int ok, const DisplayPlan *applied);
void display_attached(void); /* the session got the monitor (or started on it) */
void display_detached(void);
void display_hotplug(void); /* DRM uevent: connectors may have changed */
+/* Counts DRM uevents, also without a monitor: main.c retries a lent card that had nothing connected
+ * (a board booted headless, the monitor plugged in later). */
+unsigned display_hotplug_seq(void);
/* JSON for lord.display.list(). Returns a malloc'd string. */
char *display_list_json(void);
diff --git a/server/src/keyboard.c b/server/src/keyboard.c
index b0fbbe6..6fd9175 100644
--- a/server/src/keyboard.c
+++ b/server/src/keyboard.c
@@ -56,6 +56,36 @@ int kb_set(const char *layouts, const char *variants) {
return state ? 0 : -1;
}
+/* App mode (appclient.c): the keymap the compositor sends over wl_keyboard, already fully
+ * expanded, so compiling it reads no files (the sandbox blocks /usr/share/X11/xkb). The compose
+ * table is kept from the kb_set() made before the sandbox. */
+int kb_set_keymap_string(const char *text) {
+ if (!text || !text[0]) return -1;
+ if (!ctx && !(ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS))) return -1;
+ struct xkb_keymap *km = xkb_keymap_new_from_string(ctx, text, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
+ if (!km) return -1;
+ struct xkb_state *st = xkb_state_new(km);
+ if (!st) { xkb_keymap_unref(km); return -1; }
+ if (state) xkb_state_unref(state);
+ if (keymap) xkb_keymap_unref(keymap);
+ keymap = km;
+ state = st;
+ return 0;
+}
+
+/* Forget the keys held down (app mode: the keyboard focus left or came back, and the releases
+ * that happened meanwhile were never seen). Keeps the active layout. */
+void kb_reset_state(void) {
+ if (!keymap || !state) return;
+ int g = kb_group();
+ struct xkb_state *st = xkb_state_new(keymap);
+ if (!st) return;
+ xkb_state_unref(state);
+ state = st;
+ altgr_down = 0;
+ kb_set_group(g);
+}
+
int kb_ready(void) { return state != NULL; }
const char *kb_layouts(void) { return cur_layouts; }
const char *kb_variants(void) { return cur_variants; }
diff --git a/server/src/keyboard.h b/server/src/keyboard.h
index 6a93175..4e6a6b4 100644
--- a/server/src/keyboard.h
+++ b/server/src/keyboard.h
@@ -12,6 +12,8 @@ typedef struct {
} KeyInfo;
int kb_set(const char *layouts, const char *variants); /* "us,latam", ",abnt2" */
+int kb_set_keymap_string(const char *text); /* app mode: the compositor's keymap */
+void kb_reset_state(void); /* forget held keys (app mode) */
int kb_ready(void);
const char *kb_layouts(void);
const char *kb_variants(void);
diff --git a/server/src/main.c b/server/src/main.c
index 6892827..5da78be 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -699,20 +699,43 @@ static void remote_input_add(const int *fds, int n) {
if (input_add_fds(&s->input, fds, n)) wl_input_devices_changed();
}
+/* A lent card with no monitor connected (a Raspberry Pi booted headless, a laptop lid closed on a
+ * dock): the fds are kept and display_attach is tried again on the next DRM uevent, so plugging in the
+ * monitor later shows the session without restarting anything. RP_UNDISPLAY drops them. */
+#define PARK_MAX 40
+static int parked_fd[PARK_MAX], parked_n;
+static unsigned parked_seq;
+static void parked_drop(void) {
+ for (int i = 0; i < parked_n; i++) close(parked_fd[i]);
+ parked_n = 0;
+}
+
static void display_attach(const int *fds, int n) {
Server *s = remote_server;
+ parked_drop(); /* a new RP_DISPLAY replaces what was waiting */
if (!s->headless || n < 1) { for (int i = 0; i < n; i++) close(fds[i]); return; }
Out *o0 = &s->out[0];
out_free(o0);
memset(o0, 0, sizeof *o0);
o0->gpu = -1;
+ int card = dup(fds[0]); /* kms_attach closes its fd when it fails */
if (kms_attach(&o0->kms, fds[0])) {
- fprintf(stderr, "monitor: could not use the card\n");
o0->kms.fd = -1;
- for (int i = 1; i < n; i++) close(fds[i]);
+ if (card >= 0 && n <= PARK_MAX) {
+ fprintf(stderr, "monitor: nothing connected to the card; waiting for a monitor (hotplug)\n");
+ parked_fd[0] = card;
+ for (int i = 1; i < n; i++) parked_fd[i] = fds[i];
+ parked_n = n;
+ parked_seq = display_hotplug_seq();
+ } else {
+ fprintf(stderr, "monitor: could not use the card\n");
+ if (card >= 0) close(card);
+ for (int i = 1; i < n; i++) close(fds[i]);
+ }
set_size(s, s->W, s->H); /* back to the frame in memory */
return;
}
+ if (card >= 0) close(card);
if (input_open_fds(&s->input, fds + 1, n - 1)) fprintf(stderr, "monitor: no keyboard or mouse\n");
wl_input_devices_changed(); /* is there a touch screen? (wl_seat touch) */
s->headless = 0;
@@ -744,6 +767,7 @@ static void display_attach(const int *fds, int n) {
static void display_detach(void) {
Server *s = remote_server;
+ parked_drop();
if (s->headless) return;
gpu_tex_free(s->cursor_tex);
s->cursor_tex = NULL;
@@ -1583,6 +1607,12 @@ int main(int argc, char **argv) {
if (nabr) brokersrv_audio_dispatch(pfd + abr, nabr);
if (nmed) media_dispatch(pfd + medbase, nmed);
if (nhw) hw_dispatch(pfd + hwbase, nhw);
+ if (parked_n && s.headless && display_hotplug_seq() != parked_seq) { /* a monitor may have appeared */
+ int f[PARK_MAX], fn = parked_n;
+ memcpy(f, parked_fd, sizeof(int) * (size_t)fn);
+ parked_n = 0;
+ display_attach(f, fn);
+ }
hw_events();
media_events(js_media_event);
brokersrv_events(js_broker_event); /* avisos de permiso e indicadores → tema */
diff --git a/server/src/net/state.c b/server/src/net/state.c
index 4354785..8e49e4c 100644
--- a/server/src/net/state.c
+++ b/server/src/net/state.c
@@ -67,10 +67,28 @@ static int ifupdown_manages_file(const char *path, const char *ifname, int depth
return found;
}
+/* NetworkManager (Raspberry Pi OS, most desktop distributions, netplan with renderer NetworkManager)
+ * writes one keyfile per device under /run/NetworkManager/devices/<ifindex> with "managed=true" while it
+ * drives it. Read without D-Bus; if NetworkManager isn't running the folder is gone (it lives in /run). */
+static int networkmanager_manages(int ifindex) {
+ char path[64], line[128];
+ snprintf(path, sizeof path, "/run/NetworkManager/devices/%d", ifindex);
+ FILE *f = fopen(path, "r");
+ if (!f) return 0;
+ int managed = 0;
+ while (fgets(line, sizeof line, f)) {
+ line[strcspn(line, "\n")] = 0;
+ if (!strcmp(line, "managed=true")) managed = 1;
+ }
+ fclose(f);
+ return managed;
+}
+
int managed_by_system(const char *ifname) {
if (!strcmp(ifname, "lo")) return 1;
int idx = (int)if_nametoindex(ifname);
if (idx && networkd_manages(idx)) return 1;
+ if (idx && networkmanager_manages(idx)) return 1;
/* /etc/network/interfaces only counts if ifupdown is installed (live-boot writes that
* file even without ifupdown: the interface would be left with nobody configuring it) */
if (access("/sbin/ifup", X_OK) && access("/usr/sbin/ifup", X_OK)) return 0;
diff --git a/server/src/sec/broker.h b/server/src/sec/broker.h
index a42a152..1d1cec7 100644
--- a/server/src/sec/broker.h
+++ b/server/src/sec/broker.h
@@ -39,6 +39,9 @@ enum BrokerOp {
* "name"; the app never gets the device (docs/PASSWORDS.md) */
BOP_CLIP_SECRET, /* payload "seconds\0text": a secret to the clipboard, marked sensitive (out of
* the history, x-kde-passwordManagerHint) and cleared after `seconds` if unchanged */
+ BOP_KEYRING, /* payload "op\0service\0account\0label\0secret" (op: get | set | delete | list) → the
+ * app's own session-keyring items, owner = the verified app id (brokerkr.c,
+ * docs/PASSWORDS.md). Error replies carry an error code line (keyring.*) */
BOP_EVENT = 100, /* server → app, unrequested (reqid 0): payload "type\0json" */
};
@@ -72,6 +75,11 @@ int brokersrv_count(void);
void brokersrv_set_vault(int fd);
/* The app <id> is running: ask it for a new window. 0 if sent, -1 if it is not running. */
int brokersrv_new_window(const char *id);
+/* Quit app <id> (❖Q, Dock → Quit): the app host closes all its windows, its close guards still
+ * apply, and the process ends when the last one closes. 0 if sent, -1 if it is not running. */
+int brokersrv_quit(const char *id);
+/* The id of the isolated app whose process is `pid` (a Wayland client's pid), or NULL. */
+const char *brokersrv_app_of_pid(int pid);
/* The theme publishes its state (type "theme" or "locale", JSON) and it's forwarded live to every
* isolated app; it's also kept for the ones that start later (BOP_STATE). */
int brokersrv_publish(const char *kind, const char *json, size_t len);
diff --git a/server/src/sec/broker_int.h b/server/src/sec/broker_int.h
index 50ab4ab..ceabd8f 100644
--- a/server/src/sec/broker_int.h
+++ b/server/src/sec/broker_int.h
@@ -1,5 +1,5 @@
-/* broker_int.h — internals shared by the broker's server-side files (brokersrv.c and
- * brokercam.c). Not for the rest of lord-server: use broker.h. */
+/* broker_int.h — internals shared by the broker's server-side files (brokersrv.c,
+ * brokercam.c and brokerkr.c). Not for the rest of lord-server: use broker.h. */
#ifndef LORD_SEC_BROKER_INT_H
#define LORD_SEC_BROKER_INT_H
@@ -16,6 +16,16 @@ void brokersrv_device(const char *app, const char *kind, int on);
/* System save dialog (powerbox) for `app`; the answer comes back as brokersrv_pick_result(reqid). */
void brokersrv_powerbox_save(uint32_t reqid, const char *app, const char *suggest);
+/* A system consent prompt (privacy.js draws it; the answer comes back as brokersrv_resolve). */
+void brokersrv_prompt_event(const char *json);
+
+/* ---- brokerkr.c: the session keyring of isolated apps (BOP_KEYRING) ---- */
+void brokerkr_handle(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len);
+int brokerkr_resolve(uint32_t prompt, int allow); /* 1 if it was a keyring prompt */
+void brokerkr_conn_closed(int conn);
+void brokerkr_tick(void);
+int brokerkr_pollfd(void); /* lord-vault replies waiting, or -1 */
+
/* ---- brokercam.c: the camera of isolated apps ---- */
void brokercam_handle(int conn, int fd, uint32_t reqid, const char *payload, uint32_t len);
int brokercam_pick_result(uint32_t reqid, const char *path); /* 1 if it was a camera save */
diff --git a/server/src/sec/brokerkr.c b/server/src/sec/brokerkr.c
new file mode 100644
index 0000000..55d3e8d
--- /dev/null
+++ b/server/src/sec/brokerkr.c
@@ -0,0 +1,246 @@
+/* brokerkr.c — the session keyring for isolated .lpk apps (BOP_KEYRING, see broker.h and
+ * docs/PASSWORDS.md, "Keyring for .lpk apps").
+ *
+ * The app sends "op\0service\0account\0label\0secret"; lord-server builds the lord-vault request
+ * itself, with owner = "app.<id>", where <id> is the app id lord-server verified when it spawned
+ * the process (brokersrv_add). The app never chooses the owner, and the "app." prefix keeps
+ * isolated apps apart from the owners the desktop's own apps use ("mail", "settings"…).
+ *
+ * The request goes to lord-vault on lord-server's system channel as a private request
+ * (vc_request_private): the reply never reaches the desktop's JS. lord-vault only lets an owner
+ * see its own items; when an app asks for an item that belongs to another app (lord-vault answers
+ * "not-shared"), lord-server shows the system consent prompt (privacy.js, "keyring") and, only if
+ * the user allows it, records the share (kr-share) and asks again. Nothing here blocks: replies
+ * and the user's answer arrive later (brokerkr_tick, brokerkr_resolve). Buffers that may hold
+ * a secret are wiped before they are freed. */
+#include "broker_int.h"
+#include "json.h"
+#include "../vault/vclient.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define KR_MAX 32
+#define KR_FIELD_MAX 255 /* service, account, label (bytes) */
+#define KR_SECRET_MAX (64 * 1024)
+#define KR_PROMPT_TAG 0xC0000000u /* prompt ids: never a small app reqid */
+
+enum { ST_FREE, ST_REQ, ST_PROMPT, ST_SHARE, ST_RETRY };
+
+typedef struct {
+ int st, conn, fd, dead;
+ uint32_t reqid; /* the app's request */
+ int vid; /* lord-vault request id */
+ uint32_t prompt;
+ char op; /* 'g' get, 's' set, 'd' delete, 'l' list */
+ char owner[64], item[40];
+ char service[KR_FIELD_MAX + 1], account[KR_FIELD_MAX + 1];
+} KrReq;
+
+static KrReq rq[KR_MAX];
+static uint32_t prompt_seq;
+
+/* Items the user refused to share with an app, for the rest of this session: the app cannot keep
+ * the prompt on screen by asking again in a loop. */
+#define KR_DENY_MAX 64
+static struct { char owner[64], item[40]; } denied[KR_DENY_MAX];
+static int ndenied;
+
+static int was_denied(const char *owner, const char *item) {
+ for (int i = 0; i < ndenied; i++) if (!strcmp(denied[i].owner, owner) && !strcmp(denied[i].item, item)) return 1;
+ return 0;
+}
+static void remember_denied(const char *owner, const char *item) {
+ if (was_denied(owner, item)) return;
+ int i = ndenied < KR_DENY_MAX ? ndenied++ : (int)(prompt_seq % KR_DENY_MAX); /* full: overwrite one */
+ snprintf(denied[i].owner, sizeof denied[i].owner, "%s", owner);
+ snprintf(denied[i].item, sizeof denied[i].item, "%s", item);
+}
+
+/* lord-vault's error code → the code line the app gets (assets/locales/<lang>/errors.json) */
+static const char *map_code(const char *v) {
+ if (!v) return "keyring.failed";
+ if (!strcmp(v, "locked")) return "keyring.locked";
+ if (!strcmp(v, "no-keyring")) return "keyring.noKeyring";
+ if (!strcmp(v, "not-found")) return "keyring.notFound";
+ if (!strcmp(v, "not-shared")) return "keyring.notShared";
+ if (!strcmp(v, "bad-request") || !strcmp(v, "bad-owner") || !strcmp(v, "bad-json")) return "keyring.badRequest";
+ if (!strcmp(v, "save")) return "keyring.saveFailed";
+ if (!strcmp(v, "crash")) return "vault.unavailable";
+ return "keyring.failed";
+}
+
+static void reply_code(KrReq *r, int status, const char *code) {
+ if (!r->dead) brokersrv_reply(r->fd, r->reqid, status, code, (uint32_t)strlen(code), -1);
+}
+
+static void finish(KrReq *r) {
+ explicit_bzero(r, sizeof *r);
+ r->st = ST_FREE;
+}
+
+/* the JSON text of s, in a malloc'd buffer big enough for any escaping */
+static char *quote(const char *s) {
+ size_t n = strlen(s) * 6 + 8;
+ char *q = malloc(n);
+ if (q) json_quote(q, n, s);
+ return q;
+}
+
+static void free_wiped(char *s) { if (s) { explicit_bzero(s, strlen(s)); free(s); } }
+
+/* Builds and sends a kr-* request; 0 if sent (r->vid set). `extra` is appended as is (trusted). */
+static int send_vault(KrReq *r, const char *op, const char *label, const char *secret, const char *extra) {
+ char *qo = quote(r->owner), *qs = quote(r->service), *qa = quote(r->account);
+ char *ql = quote(label ? label : ""), *qx = quote(secret ? secret : "");
+ int rc = -1;
+ if (qo && qs && qa && ql && qx) {
+ size_t n = strlen(qo) + strlen(qs) + strlen(qa) + strlen(ql) + strlen(qx) + (extra ? strlen(extra) : 0) + 128;
+ char *j = malloc(n);
+ if (j) {
+ int len = snprintf(j, n, "{\"op\":\"%s\",\"owner\":%s,\"service\":%s,\"account\":%s%s%s%s%s%s}", op, qo, qs, qa,
+ secret ? ",\"label\":" : "", secret ? ql : "", secret ? ",\"secret\":" : "", secret ? qx : "",
+ extra ? extra : "");
+ if (len > 0 && (size_t)len < n) { r->vid = vc_request_private(j, (size_t)len); rc = r->vid > 0 ? 0 : -1; }
+ explicit_bzero(j, n);
+ free(j);
+ }
+ }
+ free_wiped(qo); free_wiped(qs); free_wiped(qa); free_wiped(ql); free_wiped(qx);
+ return rc;
+}
+
+/* The kr-share lord-server sends after the user allowed it (the only "admin" request built here). */
+static int send_share(KrReq *r) {
+ char *qi = quote(r->item), *qo = quote(r->owner);
+ int rc = -1;
+ if (qi && qo) {
+ char j[256];
+ int len = snprintf(j, sizeof j, "{\"op\":\"kr-share\",\"admin\":true,\"id\":%s,\"app\":%s,\"allow\":true}", qi, qo);
+ if (len > 0 && (size_t)len < sizeof j) { r->vid = vc_request_private(j, (size_t)len); rc = r->vid > 0 ? 0 : -1; }
+ }
+ free(qi); free(qo);
+ return rc;
+}
+
+/* Field k of the payload (NUL-separated, inside len bytes; payload[len] is 0): NULL if missing
+ * or longer than max. Trailing fields may be left out (they read as ""). */
+static const char *field(const char *p, uint32_t len, int k, size_t max) {
+ uint32_t at = 0;
+ for (int i = 0; i < k && at < len; i++) {
+ const char *z = memchr(p + at, 0, len - at);
+ at = z ? (uint32_t)(z - p) + 1 : len;
+ }
+ return strlen(p + at) > max ? NULL : p + at;
+}
+
+void brokerkr_handle(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len) {
+ KrReq *r = NULL;
+ for (int i = 0; i < KR_MAX && !r; i++) if (rq[i].st == ST_FREE) r = &rq[i];
+ const char *op = field(payload, len, 0, 8), *service = field(payload, len, 1, KR_FIELD_MAX);
+ const char *account = field(payload, len, 2, KR_FIELD_MAX), *label = field(payload, len, 3, KR_FIELD_MAX);
+ const char *secret = field(payload, len, 4, KR_SECRET_MAX);
+ /* the secret is the last field and runs to the end: a NUL inside it is not accepted */
+ if (secret && (size_t)(secret - payload) + strlen(secret) != len) secret = NULL;
+ char o = !op ? 0 : !strcmp(op, "get") ? 'g' : !strcmp(op, "set") ? 's' : !strcmp(op, "delete") ? 'd' : !strcmp(op, "list") ? 'l' : 0;
+ const char *bad = NULL;
+ if (!app || !app[0] || strlen(app) > 40) bad = "keyring.badRequest";
+ else if (!o || !service || !account || !label || !secret) bad = "keyring.badRequest";
+ else if (o != 'l' && !service[0]) bad = "keyring.badRequest";
+ else if (!r) bad = "keyring.busy";
+ if (bad) {
+ brokersrv_reply(fd, reqid, BST_ERROR, bad, (uint32_t)strlen(bad), -1);
+ explicit_bzero(payload, len);
+ return;
+ }
+ *r = (KrReq){ .st = ST_REQ, .conn = conn, .fd = fd, .reqid = reqid, .op = o };
+ snprintf(r->owner, sizeof r->owner, "app.%s", app);
+ snprintf(r->service, sizeof r->service, "%s", service);
+ snprintf(r->account, sizeof r->account, "%s", account);
+ int sent = o == 's' ? send_vault(r, "kr-set", label, secret, NULL)
+ : send_vault(r, o == 'g' ? "kr-get" : o == 'd' ? "kr-del" : "kr-list", NULL, NULL, NULL);
+ explicit_bzero(payload, len);
+ if (sent) { reply_code(r, BST_ERROR, "vault.unavailable"); finish(r); }
+}
+
+/* lord-vault answered request r: `rep` is its JSON ({"ok":true,…} | {"error":…}) */
+static void on_reply(KrReq *r, char *rep, size_t len) {
+ if (r->dead) { finish(r); return; }
+ if (!strncmp(rep, "{\"ok\":true", 10)) {
+ if (r->st == ST_SHARE) { /* shared: ask again, now it can see it */
+ r->st = ST_RETRY;
+ if (send_vault(r, "kr-get", NULL, NULL, NULL)) { reply_code(r, BST_ERROR, "vault.unavailable"); finish(r); }
+ return;
+ }
+ brokersrv_reply(r->fd, r->reqid, BST_OK, rep, (uint32_t)len, -1); /* item(s) as lord-vault sent them */
+ finish(r);
+ return;
+ }
+ /* an error reply has no secret in it */
+ JDoc d;
+ char code[32] = "", item[40] = "", other[72] = "";
+ if (!json_parse(rep, len, &d, NULL, 0)) {
+ const char *e = json_str(d.root, "error"), *it = json_str(d.root, "item"), *w = json_str(d.root, "itemOwner");
+ if (e) snprintf(code, sizeof code, "%s", e);
+ if (it) snprintf(item, sizeof item, "%s", it);
+ if (w) snprintf(other, sizeof other, "%s", w);
+ json_free(&d);
+ }
+ if (!strcmp(code, "not-shared") && r->op == 'g' && r->st == ST_REQ && item[0] && !was_denied(r->owner, item)) {
+ /* another app's item: the system asks the user (the app never draws this). The other
+ * app is shown by its plain id ("app.notes" → "notes"). */
+ char qa[64], qw[96], ev[256]; /* ids are short: [a-z0-9._-], at most 71 bytes */
+ json_quote(qw, sizeof qw, !strncmp(other, "app.", 4) ? other + 4 : other);
+ json_quote(qa, sizeof qa, r->owner + 4);
+ snprintf(r->item, sizeof r->item, "%s", item);
+ r->prompt = KR_PROMPT_TAG | (++prompt_seq & 0x3fffffff);
+ r->st = ST_PROMPT;
+ snprintf(ev, sizeof ev, "{\"reqid\":%u,\"app\":%s,\"perm\":\"keyring\",\"owner\":%s}", r->prompt, qa, qw);
+ brokersrv_prompt_event(ev);
+ return;
+ }
+ /* another app's item can only be read, after consent: for set/delete/list it does not exist */
+ if (!strcmp(code, "not-shared") && r->op != 'g') snprintf(code, sizeof code, "not-found");
+ reply_code(r, !strcmp(code, "not-shared") ? BST_DENIED : BST_ERROR, map_code(code[0] ? code : NULL));
+ finish(r);
+}
+
+void brokerkr_tick(void) {
+ uint32_t id;
+ size_t len;
+ char *rep;
+ while ((rep = vc_take_private(&id, &len))) {
+ for (int i = 0; i < KR_MAX; i++)
+ if ((rq[i].st == ST_REQ || rq[i].st == ST_SHARE || rq[i].st == ST_RETRY) && rq[i].vid == (int)id) { on_reply(&rq[i], rep, len); break; }
+ explicit_bzero(rep, len);
+ free(rep);
+ }
+}
+
+int brokerkr_resolve(uint32_t prompt, int allow) {
+ if ((prompt & KR_PROMPT_TAG) != KR_PROMPT_TAG) return 0;
+ for (int i = 0; i < KR_MAX; i++) {
+ KrReq *r = &rq[i];
+ if (r->st != ST_PROMPT || r->prompt != prompt) continue;
+ if (r->dead) { finish(r); return 1; }
+ if (!allow) { remember_denied(r->owner, r->item); reply_code(r, BST_DENIED, "keyring.notShared"); finish(r); return 1; }
+ r->st = ST_SHARE;
+ if (send_share(r)) { reply_code(r, BST_ERROR, "vault.unavailable"); finish(r); }
+ return 1;
+ }
+ return 1; /* a keyring prompt whose app is gone */
+}
+
+void brokerkr_conn_closed(int conn) {
+ for (int i = 0; i < KR_MAX; i++) {
+ if (rq[i].st == ST_FREE || rq[i].conn != conn) continue;
+ rq[i].dead = 1; /* the vault reply is still drained */
+ if (rq[i].st == ST_PROMPT) finish(&rq[i]);
+ }
+}
+
+int brokerkr_pollfd(void) {
+ for (int i = 0; i < KR_MAX; i++) if (rq[i].st == ST_REQ || rq[i].st == ST_SHARE || rq[i].st == ST_RETRY) return vc_private_fd();
+ return -1;
+}
diff --git a/server/src/sec/brokersrv.c b/server/src/sec/brokersrv.c
index fd3cb3e..f45f8e7 100644
--- a/server/src/sec/brokersrv.c
+++ b/server/src/sec/brokersrv.c
@@ -143,6 +143,7 @@ void brokersrv_revoke(const char *app, const char *perm) {
void brokersrv_tick(void) {
brokercam_tick();
+ brokerkr_tick();
clip_secret_tick();
char kb[512];
keyboard_json(kb, sizeof kb);
@@ -177,6 +178,20 @@ int brokersrv_new_window(const char *id) {
return -1;
}
+int brokersrv_quit(const char *id) {
+ static const char json[] = "{}";
+ int sent = -1;
+ for (int i = 0; i < MAX_APPS; i++)
+ if (apps[i].used && !strcmp(apps[i].id, id) && !send_event(&apps[i], "quit", json, sizeof json - 1)) sent = 0;
+ return sent;
+}
+
+const char *brokersrv_app_of_pid(int pid) {
+ if (pid <= 0) return NULL;
+ for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && apps[i].pid == pid) return apps[i].id;
+ return NULL;
+}
+
void brokersrv_set_vault(int fd) { for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && apps[i].fd == fd) apps[i].vault = 1; }
/* A secret an isolated app put on the clipboard: cleared at `deadline` if it is still there
@@ -199,6 +214,7 @@ int brokersrv_count(void) { int n = 0; for (int i = 0; i < MAX_APPS; i++) n += a
static void drop(AppConn *a) {
brokercam_conn_closed((int)(a - apps));
+ brokerkr_conn_closed((int)(a - apps));
/* los indicadores de esta app se apagan */
queue_evt("device", "{\"app\":\"%s\",\"off\":true}", a->id);
if (a->mic) { maudio_close(a->mic); a->mic = NULL; }
@@ -317,7 +333,7 @@ static void handle(AppConn *a, BrokerHdr *h, char *payload) {
int p = perm_from_name(payload);
if (p < 0) { send_reply(fd, h->reqid, BST_DENIED, NULL, 0); break; }
PermState st = perm_get(a->id, (Perm)p);
- fprintf(stderr, "broker[%s]: permiso %s = %s\n", a->id, payload, st == PERM_ALLOW ? "allow" : st == PERM_DENY ? "deny" : "ask→aviso");
+ fprintf(stderr, "broker[%s]: permission %s = %s\n", a->id, payload, st == PERM_ALLOW ? "allow" : st == PERM_DENY ? "deny" : "ask (prompt)");
if (st == PERM_ALLOW) { send_reply(fd, h->reqid, BST_OK, "1", 1); break; }
if (st == PERM_DENY) { send_reply(fd, h->reqid, BST_OK, "0", 1); break; }
/* preguntar: el aviso lo dibuja el sistema; se responde cuando el usuario decide */
@@ -421,6 +437,9 @@ static void handle(AppConn *a, BrokerHdr *h, char *payload) {
else send_reply(fd, h->reqid, BST_OK, name, (uint32_t)strlen(name));
break;
}
+ case BOP_KEYRING:
+ brokerkr_handle((int)(a - apps), fd, h->reqid, a->id, payload, h->len);
+ break;
case BOP_QUIT:
send_reply(fd, h->reqid, BST_OK, NULL, 0);
break;
@@ -434,6 +453,7 @@ static void handle(AppConn *a, BrokerHdr *h, char *payload) {
}
void brokersrv_resolve(uint32_t reqid, int allow) {
+ if (brokerkr_resolve(reqid, allow)) return;
for (int i = 0; i < MAX_PENDING; i++) if (pend[i].used && pend[i].reqid == reqid) {
perm_set(pend[i].id, pend[i].perm, allow ? PERM_ALLOW : PERM_DENY);
send_reply(pend[i].fd, reqid, BST_OK, allow ? "1" : "0", 1);
@@ -445,6 +465,9 @@ void brokersrv_resolve(uint32_t reqid, int allow) {
int brokersrv_pollfds(struct pollfd *pfd, int max) {
int n = 0;
for (int i = 0; i < MAX_APPS && n < max; i++) if (apps[i].used) { pfd[n].fd = apps[i].fd; pfd[n].events = POLLIN; pfd[n].revents = 0; n++; }
+ /* last: wakes the loop when lord-vault answers a keyring request (brokersrv_tick reads it) */
+ int kf = brokerkr_pollfd();
+ if (kf >= 0 && n < max) { pfd[n].fd = kf; pfd[n].events = POLLIN; pfd[n].revents = 0; n++; }
return n;
}
@@ -505,6 +528,8 @@ int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32
return send_reply_fd(fd, reqid, status, data, len, passfd);
}
+void brokersrv_prompt_event(const char *json) { queue_evt("prompt", "%s", json); }
+
void brokersrv_device(const char *app, const char *kind, int on) {
queue_evt("device", "{\"app\":\"%s\",\"kind\":\"%s\",\"on\":%s}", app, kind, on ? "true" : "false");
}
diff --git a/server/src/ui/js_broker.c b/server/src/ui/js_broker.c
index 65b911b..f2b1ac6 100644
--- a/server/src/ui/js_broker.c
+++ b/server/src/ui/js_broker.c
@@ -11,6 +11,7 @@
#include "../keyboard.h"
#include "js.h"
#include "js_sys.h"
+#include "js_err.h"
#include <dirent.h>
@@ -85,11 +86,17 @@ static int rpc(int op, const void *payload, uint32_t len, int *status, char **ou
/* Un evento: "tipo\0json". El teclado se aplica acá (keyboard.c); el resto va a JS
* (__lordBrokerEvent: tokens del tema, idioma, estado completo). */
+/* The layout itself comes from the compositor's keymap (wl_keyboard.keymap, appclient.c):
+ * kb_set() here would run inside the sandbox, where xkbcommon cannot read its rules. Only the
+ * active group is taken from the broker. */
+static void apply_kb_state(const JVal *kb) {
+ const char *l = json_str(kb, "layouts");
+ if (l && l[0]) kb_set_group((int)json_num(kb, "group", 0));
+}
static void apply_keyboard(const char *json, size_t len) {
JDoc d;
if (json_parse(json, len, &d, NULL, 0)) return;
- const char *l = json_str(d.root, "layouts"), *v = json_str(d.root, "variants");
- if (l && l[0]) { kb_set(l, v ? v : ""); kb_set_group((int)json_num(d.root, "group", 0)); }
+ apply_kb_state(d.root);
json_free(&d);
}
@@ -104,10 +111,7 @@ static void dispatch_event(const char *buf, size_t n) {
JDoc d;
if (!json_parse(json, jl, &d, NULL, 0)) {
const JVal *kb = json_get(d.root, "keyboard");
- if (kb && kb->type == J_OBJ) {
- const char *l = json_str(kb, "layouts"), *v = json_str(kb, "variants");
- if (l && l[0]) { kb_set(l, v ? v : ""); kb_set_group((int)json_num(kb, "group", 0)); }
- }
+ if (kb && kb->type == J_OBJ) apply_kb_state(kb);
json_free(&d);
}
}
@@ -180,7 +184,7 @@ static JSValue f_fs_read(JSContext *c, JSValueConst t, int argc, JSValueConst *a
int r = p ? rpc(BOP_FS_READ, p, (uint32_t)strlen(p), &st, &out, &len) : -1;
if (p) JS_FreeCString(c, p);
if (mode) JS_FreeCString(c, mode);
- if (r || st != BST_OK) { free(out); return JS_ThrowTypeError(c, st == BST_DENIED ? "acceso denegado" : "no se pudo leer"); }
+ if (r || st != BST_OK) { free(out); return st == BST_DENIED ? js_throw_code(c, "app.outsideFolder", NULL) : js_throw_code(c, "app.readFailed", NULL); }
JSValue v = binary ? JS_NewArrayBufferCopy(c, (uint8_t *)out, len) : JS_NewStringLen(c, out, len);
free(out);
return v;
@@ -203,7 +207,7 @@ static JSValue f_fs_write(JSContext *c, JSValueConst t, int argc, JSValueConst *
free(buf);
JS_FreeCString(c, p);
if (dyn) JS_FreeCString(c, dyn);
- if (r || st != BST_OK) return JS_ThrowTypeError(c, st == BST_DENIED ? "fuera de la carpeta de la app" : "no se pudo escribir");
+ if (r || st != BST_OK) return st == BST_DENIED ? js_throw_code(c, "app.outsideFolder", NULL) : js_throw_code(c, "app.writeFailed", NULL);
return JS_UNDEFINED;
}
@@ -224,7 +228,7 @@ static JSValue f_fs_list(JSContext *c, JSValueConst t, int argc, JSValueConst *a
static JSValue f_clip_get(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t; (void)argc; (void)argv;
int st = BST_ERROR; char *out = NULL; uint32_t len = 0;
- if (rpc(BOP_CLIP_GET, NULL, 0, &st, &out, &len) || st != BST_OK) { free(out); return JS_ThrowTypeError(c, "sin permiso de portapapeles"); }
+ if (rpc(BOP_CLIP_GET, NULL, 0, &st, &out, &len) || st != BST_OK) { free(out); return js_throw_code(c, "app.clipboardDenied", NULL); }
JSValue v = JS_NewStringLen(c, out, len);
free(out);
return v;
@@ -333,11 +337,11 @@ static JSValue f_fd_read(JSContext *c, JSValueConst t, int argc, JSValueConst *a
(void)t; (void)argc;
int32_t fd = -1;
JS_ToInt32(c, &fd, argv[0]);
- if (fd < 0) return JS_ThrowTypeError(c, "fd inválido");
+ if (fd < 0) return js_throw_code(c, "app.badFd", NULL);
size_t cap = 1 << 20, len = 0;
char *buf = malloc(cap);
for (;;) {
- if (len == cap) { cap *= 2; if (cap > 64u << 20) { free(buf); close(fd); return JS_ThrowRangeError(c, "archivo demasiado grande"); } char *nb = realloc(buf, cap); if (!nb) { free(buf); close(fd); return JS_ThrowOutOfMemory(c); } buf = nb; }
+ if (len == cap) { cap *= 2; if (cap > 64u << 20) { free(buf); close(fd); return js_throw_code(c, "fs.tooLarge", "max", "64 MB", NULL); } char *nb = realloc(buf, cap); if (!nb) { free(buf); close(fd); return JS_ThrowOutOfMemory(c); } buf = nb; }
ssize_t r = read(fd, buf + len, cap - len);
if (r < 0 && errno == EINTR) continue;
if (r <= 0) break;
@@ -457,8 +461,7 @@ static JSValue f_broker_state(JSContext *c, JSValueConst t, int argc, JSValueCon
JDoc d;
if (!json_parse(out, len, &d, NULL, 0)) {
const JVal *kb = json_get(d.root, "keyboard");
- const char *l = json_str(kb, "layouts"), *v = json_str(kb, "variants");
- if (l && l[0]) { kb_set(l, v ? v : ""); kb_set_group((int)json_num(kb, "group", 0)); }
+ if (kb && kb->type == J_OBJ) apply_kb_state(kb);
json_free(&d);
}
JSValue r = JS_ParseJSON(c, out, len, "<estado>");
@@ -595,7 +598,7 @@ static JSValue f_pkg_file(JSContext *c, JSValueConst t, int argc, JSValueConst *
size_t len = 0;
char *buf = rel ? pkg_read(rel, 32u * 1024 * 1024, &len) : NULL;
if (rel) JS_FreeCString(c, rel);
- if (!buf) return JS_ThrowTypeError(c, "archivo inexistente en la app");
+ if (!buf) return js_throw_code(c, "app.noSuchFile", NULL);
JSValue v = JS_NewArrayBufferCopy(c, (uint8_t *)buf, len);
free(buf);
return v;
@@ -606,7 +609,7 @@ static JSValue f_load_app(JSContext *c, JSValueConst t, int argc, JSValueConst *
(void)t; (void)argc; (void)argv;
size_t len = 0;
char *src = pkg_read("app.js", 16u * 1024 * 1024, &len);
- if (!src) return JS_ThrowTypeError(c, "no se pudo leer la app");
+ if (!src) return js_throw_code(c, "app.loadFailed", NULL);
JSValue r = JS_Eval(c, src, len, "app.js", JS_EVAL_TYPE_GLOBAL);
free(src);
if (JS_IsException(r)) return r;
diff --git a/server/src/ui/js_sec.c b/server/src/ui/js_sec.c
index 4f75b87..6452537 100644
--- a/server/src/ui/js_sec.c
+++ b/server/src/ui/js_sec.c
@@ -203,12 +203,22 @@ static JSValue f_broker_menu_click(JSContext *c, JSValueConst t, int argc, JSVal
if (item) JS_FreeCString(c, item);
return JS_UNDEFINED;
}
+/* lord.broker.quit(app) → true if the isolated app is running and was asked to quit (❖Q, Dock →
+ * Quit). The app closes its own windows, so its close guards still apply. */
+static JSValue f_broker_quit(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *app = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ int ok = app && lpk_valid_id(app) && brokersrv_quit(app) == 0;
+ if (app) JS_FreeCString(c, app);
+ return JS_NewBool(c, ok);
+}
static const JSCFunctionListEntry broker_funcs[] = {
JS_CFUNC_DEF("resolve", 2, f_broker_resolve),
JS_CFUNC_DEF("publish", 2, f_broker_publish),
JS_CFUNC_DEF("pickResult", 2, f_broker_pick_result),
JS_CFUNC_DEF("menus", 1, f_broker_menus),
JS_CFUNC_DEF("menuClick", 2, f_broker_menu_click),
+ JS_CFUNC_DEF("quit", 1, f_broker_quit),
};
void js_sec_register(JSContext *c, JSValue lord) {
diff --git a/server/src/ui/js_vault.c b/server/src/ui/js_vault.c
index 6b9abba..a75e9f1 100644
--- a/server/src/ui/js_vault.c
+++ b/server/src/ui/js_vault.c
@@ -23,6 +23,7 @@
#include "../vault/fidodev.h"
#include "../vault/vwire.h"
#include "js_broker.h"
+#include "../sec/broker.h"
#include <errno.h>
#include <fcntl.h>
@@ -310,9 +311,62 @@ static const JSCFunctionListEntry vault_app_funcs[] = {
JS_CFUNC_DEF("promptDone", 2, fa_noop),
};
+/* ---- lord.keyring of an isolated .lpk app (any app without its own vault channel) ----
+ * lord.keyring.request(op, service, account, label, secret) → JSON text of lord-vault's reply
+ * op: 'get' | 'set' | 'delete' | 'list'. It goes through the broker (BOP_KEYRING); lord-server
+ * sets the owner from the verified app id, so the app only reaches its own items (or those
+ * the user agreed to share with it). Errors are thrown as codes (keyring.*, vault.unavailable).
+ * The reply buffer may hold a secret: it is wiped once it is a JS string. */
+
+static JSValue fk_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *v[5] = { 0 };
+ size_t l[5] = { 0 }, total = 0;
+ for (int i = 0; i < 5; i++) {
+ if (i < argc && !JS_IsUndefined(argv[i]) && !JS_IsNull(argv[i])) {
+ v[i] = JS_ToCStringLen(c, &l[i], argv[i]);
+ if (!v[i]) { for (int k = 0; k < i; k++) if (v[k]) JS_FreeCString(c, v[k]); return JS_EXCEPTION; }
+ }
+ total += l[i] + 1;
+ }
+ char *p = total <= BROKER_MAX_MSG ? malloc(total) : NULL;
+ size_t o = 0;
+ for (int i = 0; i < 5 && p; i++) {
+ if (l[i] && memchr(v[i], 0, l[i])) { explicit_bzero(p, total); free(p); p = NULL; break; } /* no NUL inside a field */
+ if (l[i]) memcpy(p + o, v[i], l[i]);
+ o += l[i];
+ if (i < 4) p[o++] = 0;
+ }
+ for (int i = 0; i < 5; i++) if (v[i]) JS_FreeCString(c, v[i]);
+ if (!p) return js_throw_code(c, "keyring.badRequest", NULL);
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t ol = 0;
+ int r = js_broker_rpc(BOP_KEYRING, p, (uint32_t)o, &st, &out, &ol);
+ explicit_bzero(p, total);
+ free(p);
+ if (r) { free(out); return js_throw_code(c, "vault.unavailable", NULL); }
+ JSValue res;
+ if (st == BST_OK) res = JS_NewStringLen(c, out ? out : "{}", out ? ol : 2);
+ else {
+ char line[128];
+ snprintf(line, sizeof line, "%.*s", (int)(out && ol < sizeof line ? ol : 0), out ? out : "");
+ res = js_throw_line(c, lerr_is(line) ? line : "keyring.failed");
+ }
+ if (out) { explicit_bzero(out, ol); free(out); }
+ return res;
+}
+
+static const JSCFunctionListEntry keyring_app_funcs[] = { JS_CFUNC_DEF("request", 5, fk_request) };
+
void js_vault_register_app(JSContext *c, JSValue lord) {
const char *s = getenv("LORD_VAULT_FD");
- if (!s) return; /* only the app spawned with a vault channel */
+ if (!s) { /* a .lpk app: its own keyring items only */
+ JSValue k = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, k, keyring_app_funcs, sizeof keyring_app_funcs / sizeof keyring_app_funcs[0]);
+ JS_SetPropertyStr(c, lord, "keyring", k);
+ return;
+ }
app_fd = atoi(s);
if (app_fd <= 2) { app_fd = -1; return; }
fcntl(app_fd, F_SETFD, FD_CLOEXEC);
diff --git a/server/src/vault/cbor.c b/server/src/vault/cbor.c
index 22beec6..669e2a2 100644
--- a/server/src/vault/cbor.c
+++ b/server/src/vault/cbor.c
@@ -1,9 +1,9 @@
-/* cbor.c — CBOR estricto para CTAP2 (ver cbor.h). */
+/* cbor.c — strict CBOR for CTAP2 (see cbor.h). */
#include "cbor.h"
#include <string.h>
-/* ================= escritor ================= */
+/* ================= writer ================= */
void cbw_init(CbW *w, uint8_t *buf, size_t cap) { w->p = buf; w->n = 0; w->cap = cap; w->err = 0; }
@@ -35,7 +35,7 @@ void cbw_map(CbW *w, size_t n) { head(w, 5, n); }
void cbw_bool(CbW *w, int v) { uint8_t b = v ? 0xf5 : 0xf4; cbw_raw(w, &b, 1); }
void cbw_null(CbW *w) { uint8_t b = 0xf6; cbw_raw(w, &b, 1); }
-/* ================= lector ================= */
+/* ================= reader ================= */
typedef struct { const uint8_t *d; size_t len, p; CbItem *it; int n, max; } R;
@@ -68,9 +68,9 @@ static int item(R *r, int depth) {
v = 0;
for (size_t i = 0; i < k; i++) v = v << 8 | r->d[r->p + i];
r->p += k;
- /* codificación mínima (canónica): si cabía en menos, es inválida */
+ /* minimal (canonical) encoding: if it fit in fewer bytes, it is invalid */
if ((ai == 24 && v < 24) || (ai == 25 && v <= 0xff) || (ai == 26 && v <= 0xffff) || (ai == 27 && v <= 0xffffffffu)) return -1;
- } else return -1; /* 28-30 reservados, 31 indefinido */
+ } else return -1; /* 28-30 reserved, 31 indefinite */
int k = r->n++;
CbItem *it = &r->it[k];
memset(it, 0, sizeof *it);
@@ -89,13 +89,13 @@ static int item(R *r, int depth) {
it->type = major == 4 ? CB_ARRAY : CB_MAP;
it->v = v;
uint64_t sub = major == 4 ? v : v * 2;
- if (v > (uint64_t)r->max || sub > r->len - r->p) return -1; /* cada ítem ocupa ≥ 1 byte */
+ if (v > (uint64_t)r->max || sub > r->len - r->p) return -1; /* each item takes >= 1 byte */
for (uint64_t i = 0; i < sub; i++) if (item(r, depth + 1)) return -1;
break;
}
- case 6: return -1; /* etiquetas: no en CTAP2 */
+ case 6: return -1; /* tags: not in CTAP2 */
default:
- if (ai >= 24) return -1; /* flotantes y simples de 1 byte */
+ if (ai >= 24) return -1; /* floats and 1-byte simple values */
if (v == 20) it->type = CB_FALSE;
else if (v == 21) it->type = CB_TRUE;
else if (v == 22) it->type = CB_NULL;
diff --git a/server/src/vault/cbor.h b/server/src/vault/cbor.h
index dffa53b..d16a60f 100644
--- a/server/src/vault/cbor.h
+++ b/server/src/vault/cbor.h
@@ -1,11 +1,11 @@
-/* cbor.h — CBOR (RFC 8949) chico y estricto para CTAP2: enteros, bytes, texto, arreglos, mapas,
- * true/false/null. Sin flotantes, etiquetas ni largos indefinidos.
+/* cbor.h — small, strict CBOR (RFC 8949) for CTAP2: integers, bytes, text, arrays, maps,
+ * true/false/null. No floats, tags or indefinite lengths.
*
- * Escritor: sobre un búfer fijo; las claves de los mapas las escribe quien llama ya en el orden
- * canónico de CTAP2 (más cortas primero, después por bytes: 1, 2, 3 … -1, -2; "id" < "name").
- * Lector: arma un arreglo de ítems en orden (sin copiar), cada uno con dónde termina su subárbol;
- * rechaza codificaciones no mínimas («overlong»), valores simples reservados, UTF-8 inválido y
- * anidamiento de más de 16 niveles. */
+ * Writer: over a fixed buffer; the caller writes the map keys already in CTAP2 canonical order
+ * (shorter first, then bytewise: 1, 2, 3 … -1, -2; "id" < "name").
+ * Reader: builds an array of items in order (no copying), each with where its subtree ends;
+ * rejects non-minimal encodings ("overlong"), reserved simple values, invalid UTF-8 and
+ * nesting deeper than 16 levels. */
#ifndef LORD_VAULT_CBOR_H
#define LORD_VAULT_CBOR_H
@@ -23,28 +23,28 @@ void cbw_array(CbW *w, size_t n);
void cbw_map(CbW *w, size_t n);
void cbw_bool(CbW *w, int v);
void cbw_null(CbW *w);
-void cbw_raw(CbW *w, const void *d, size_t n); /* un ítem ya codificado */
+void cbw_raw(CbW *w, const void *d, size_t n); /* an already-encoded item */
enum { CB_UINT = 1, CB_NINT, CB_BYTES, CB_TEXT, CB_ARRAY, CB_MAP, CB_FALSE, CB_TRUE, CB_NULL, CB_UNDEF };
typedef struct {
uint8_t type;
- uint64_t v; /* UINT: el valor; NINT: el valor es -1 - v; ARRAY/MAP: cantidad */
- const uint8_t *ptr; /* BYTES/TEXT: los datos */
+ uint64_t v; /* UINT: the value; NINT: the value is -1 - v; ARRAY/MAP: count */
+ const uint8_t *ptr; /* BYTES/TEXT: the data */
size_t len;
- int next; /* índice del ítem que sigue a este subárbol */
+ int next; /* index of the item following this subtree */
} CbItem;
typedef struct { const CbItem *it; int n; size_t used; } Cb;
-/* Lee un ítem de d. items: arreglo del llamador (max ítems). Con allow_trailing, sobra lo que
- * venga después (c->used dice cuántos bytes ocupó); si no, tiene que terminar justo. 0 bien. */
+/* Reads one item from d. items: caller's array (max items). With allow_trailing, whatever
+ * follows is left over (c->used says how many bytes it took); otherwise it must end exactly. 0 = ok. */
int cb_parse(Cb *c, const uint8_t *d, size_t len, CbItem *items, int max, int allow_trailing);
-int cb_type(const Cb *c, int i); /* 0 si i < 0 */
-int cb_map_int(const Cb *c, int map, int64_t key); /* índice del valor, o -1 */
+int cb_type(const Cb *c, int i); /* 0 if i < 0 */
+int cb_map_int(const Cb *c, int map, int64_t key); /* index of the value, or -1 */
int cb_map_text(const Cb *c, int map, const char *key);
-int cb_at(const Cb *c, int arr, int k); /* k-ésimo elemento, o -1 */
-int cb_int(const Cb *c, int i, int64_t *out); /* UINT/NINT que entre en int64: 0 bien */
+int cb_at(const Cb *c, int arr, int k); /* k-th element, or -1 */
+int cb_int(const Cb *c, int i, int64_t *out); /* UINT/NINT that fits in int64: 0 = ok */
int cb_text_eq(const Cb *c, int i, const char *s);
#endif
diff --git a/server/src/vault/csvp.c b/server/src/vault/csvp.c
index 09fb524..76074e1 100644
--- a/server/src/vault/csvp.c
+++ b/server/src/vault/csvp.c
@@ -1,4 +1,4 @@
-/* csvp.c — lector de CSV (ver csvp.h). */
+/* csvp.c — CSV reader (see csvp.h). */
#include "csvp.h"
#include "smem.h"
@@ -44,7 +44,7 @@ int csv_next(Csv *c, CsvRow *row) {
const char *s = c->s;
for (;;) {
if (c->p >= c->len) return 0;
- /* fila vacía */
+ /* empty row */
if (s[c->p] == '\n') { c->p++; continue; }
if (s[c->p] == '\r') { c->p++; if (c->p < c->len && s[c->p] == '\n') c->p++; continue; }
break;
@@ -63,7 +63,7 @@ int csv_next(Csv *c, CsvRow *row) {
}
if (push(row, s, a, p, 1)) { csv_row_free(row); return -1; }
p++;
- /* basura entre la comilla de cierre y el separador: se ignora (como los exportadores flojos) */
+ /* garbage between the closing quote and the separator: ignored (like sloppy exporters) */
while (p < c->len && s[p] != ',' && s[p] != '\n' && s[p] != '\r') p++;
} else {
size_t a = p;
diff --git a/server/src/vault/csvp.h b/server/src/vault/csvp.h
index a02aca4..4186b59 100644
--- a/server/src/vault/csvp.h
+++ b/server/src/vault/csvp.h
@@ -1,6 +1,6 @@
-/* csvp.h — lector de CSV (RFC 4180) para los importadores: campos entre comillas con "" adentro,
- * saltos de línea dentro de un campo, CRLF o LF, BOM de UTF-8 al principio. Los campos se copian
- * a la arena de secretos (smem.h): un CSV de contraseñas nunca pasa por el montón de la libc. */
+/* csvp.h — CSV reader (RFC 4180) for the importers: quoted fields with "" inside,
+ * line breaks inside a field, CRLF or LF, UTF-8 BOM at the start. Fields are copied
+ * into the secrets arena (smem.h): a password CSV never goes through the libc heap. */
#ifndef LORD_VAULT_CSVP_H
#define LORD_VAULT_CSVP_H
@@ -10,13 +10,13 @@ typedef struct { char **f; int n, cap; } CsvRow;
typedef struct { const char *s; size_t len, p; int bad; } Csv;
void csv_init(Csv *c, const char *s, size_t len);
-/* Próxima fila en row (se reusa: libera la anterior). 1 = hay fila, 0 = fin, -1 = comillas sin
- * cerrar o sin memoria. Las filas vacías se saltean. */
+/* Next row into row (reused: frees the previous one). 1 = row read, 0 = end, -1 = unclosed quote
+ * or out of memory. Empty rows are skipped. */
int csv_next(Csv *c, CsvRow *row);
void csv_row_free(CsvRow *row);
-/* Columna del encabezado con ese nombre (sin distinguir mayúsculas, sin espacios alrededor), o -1. */
+/* Header column with that name (case-insensitive, ignoring surrounding spaces), or -1. */
int csv_col(const CsvRow *hdr, const char *name);
-/* Campo i de la fila, o "" si no existe. */
+/* Field i of the row, or "" if it does not exist. */
const char *csv_get(const CsvRow *row, int i);
#endif
diff --git a/server/src/vault/ctap2.c b/server/src/vault/ctap2.c
index 0199aa0..8b0fc88 100644
--- a/server/src/vault/ctap2.c
+++ b/server/src/vault/ctap2.c
@@ -1,8 +1,8 @@
-/* ctap2.c — cliente FIDO2 propio: CTAPHID sobre hidraw + CTAP2 con hmac-secret (ver ctap2.h).
+/* ctap2.c — our own FIDO2 client: CTAPHID over hidraw + CTAP2 with hmac-secret (see ctap2.h).
*
- * Solo read/write/poll sobre el fd que llega abierto (corre encerrado en lord-vault). Un
- * reporte HID es de 64 bytes; al escribir va precedido por el número de reporte 0 (65 bytes),
- * como pide hidraw para los dispositivos sin ids de reporte. */
+ * Only read/write/poll on the fd that arrives already open (runs sandboxed in lord-vault). An
+ * HID report is 64 bytes; when writing it is prefixed by report number 0 (65 bytes),
+ * as hidraw requires for devices without report ids. */
#include "ctap2.h"
#include "cbor.h"
#include "p256.h"
@@ -30,7 +30,7 @@
#define CMD_GET_INFO 0x04
#define CMD_CLIENT_PIN 0x06
-/* canal en uso (para fido_cancel desde otro hilo) */
+/* channel in use (for fido_cancel from another thread) */
static volatile int cur_fd = -1;
static volatile uint32_t cur_cid;
static volatile int cancel_flag;
@@ -41,7 +41,7 @@ static long long now_ms(void) {
return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
-/* ---- reportes ---- */
+/* ---- reports ---- */
static int pkt_write(int fd, const uint8_t pkt[PKT]) {
uint8_t b[PKT + 1];
@@ -57,7 +57,7 @@ static int pkt_write(int fd, const uint8_t pkt[PKT]) {
return FIDO_ERR_IO;
}
-/* 0 bien, FIDO_ERR_TIMEOUT si no llegó nada en ms, FIDO_ERR_IO */
+/* 0 = ok, FIDO_ERR_TIMEOUT if nothing arrived within ms, FIDO_ERR_IO */
static int pkt_read(int fd, uint8_t pkt[PKT], int ms) {
struct pollfd p = { fd, POLLIN, 0 };
int r = poll(&p, 1, ms < 0 ? 0 : ms);
@@ -68,7 +68,7 @@ static int pkt_read(int fd, uint8_t pkt[PKT], int ms) {
ssize_t n = read(fd, b, sizeof b);
if (n < 0) return errno == EAGAIN || errno == EINTR ? FIDO_ERR_TIMEOUT : FIDO_ERR_IO;
if (n == PKT) { memcpy(pkt, b, PKT); return 0; }
- if (n == PKT + 1 && b[0] == 0) { memcpy(pkt, b + 1, PKT); return 0; } /* con número de reporte */
+ if (n == PKT + 1 && b[0] == 0) { memcpy(pkt, b + 1, PKT); return 0; } /* with report number */
return FIDO_ERR_IO;
}
@@ -102,14 +102,14 @@ static int hid_send(int fd, uint32_t cid, uint8_t cmd, const uint8_t *data, size
static int hid_err(uint8_t code) {
switch (code) {
- case 0x01: return FIDO_ERR_NO_HMAC; /* ERR_INVALID_CMD: no habla CBOR */
+ case 0x01: return FIDO_ERR_NO_HMAC; /* ERR_INVALID_CMD: does not speak CBOR */
case 0x05: return FIDO_ERR_TIMEOUT; /* ERR_MSG_TIMEOUT */
case 0x06: return FIDO_ERR_IO; /* ERR_CHANNEL_BUSY */
default: return FIDO_ERR_PROTOCOL;
}
}
-/* Recibe la respuesta del canal cid. Ignora otros canales; KEEPALIVE avisa por cb. */
+/* Receives the response on channel cid. Ignores other channels; KEEPALIVE notifies via cb. */
static int hid_recv(int fd, uint32_t cid, uint8_t *cmd, uint8_t *buf, size_t cap, size_t *len,
long long deadline, FidoStatusCb cb, void *ud) {
uint8_t pkt[PKT];
@@ -137,7 +137,7 @@ static int hid_recv(int fd, uint32_t cid, uint8_t *cmd, uint8_t *buf, size_t cap
got = k;
seq = 0;
} else {
- if (seq < 0) continue; /* continuación suelta: se descarta */
+ if (seq < 0) continue; /* stray continuation: discarded */
if (pkt[4] != seq) return FIDO_ERR_PROTOCOL;
size_t k = total - got < PKT - 5 ? total - got : PKT - 5;
memcpy(buf + got, pkt + 5, k);
@@ -148,12 +148,12 @@ static int hid_recv(int fd, uint32_t cid, uint8_t *cmd, uint8_t *buf, size_t cap
}
}
-/* CTAPHID_INIT por el canal de difusión: canal propio y capacidades. */
+/* CTAPHID_INIT on the broadcast channel: own channel and capabilities. */
static int hid_init(int fd, uint32_t *cid, uint8_t *caps) {
uint8_t nonce[8], resp[64];
- if (fd != cur_fd) cancel_flag = 0; /* un cancelar viejo no corta un pedido nuevo */
+ if (fd != cur_fd) cancel_flag = 0; /* a stale cancel does not abort a new request */
if (vc_random(nonce, sizeof nonce)) return FIDO_ERR_IO;
- /* descartar lo que haya quedado de antes */
+ /* discard whatever is left over from before */
uint8_t junk[PKT];
for (int i = 0; i < 32 && pkt_read(fd, junk, 0) == 0; i++) {}
int rc = hid_send(fd, 0xffffffffu, HID_INIT, nonce, sizeof nonce);
@@ -165,7 +165,7 @@ static int hid_init(int fd, uint32_t *cid, uint8_t *caps) {
rc = hid_recv(fd, 0xffffffffu, &cmd, resp, sizeof resp, &len, deadline, NULL, NULL);
if (rc) return rc;
if (cmd != HID_INIT || len < 17) continue;
- if (memcmp(resp, nonce, 8)) continue; /* respuesta a otro INIT */
+ if (memcmp(resp, nonce, 8)) continue; /* response to another INIT */
*cid = get_cid(resp + 8);
if (caps) *caps = resp[16];
if (*cid == 0 || *cid == 0xffffffffu) return FIDO_ERR_PROTOCOL;
@@ -189,8 +189,8 @@ int ctaphid_command(int fd, uint8_t cmd, const uint8_t *data, size_t len,
static int ctap_status(uint8_t s) {
switch (s) {
case 0x00: return FIDO_OK;
- case 0x01: return FIDO_ERR_NO_HMAC; /* comando inválido: no es CTAP2 */
- case 0x2b: return FIDO_ERR_NO_HMAC; /* extensión no soportada */
+ case 0x01: return FIDO_ERR_NO_HMAC; /* invalid command: not CTAP2 */
+ case 0x2b: return FIDO_ERR_NO_HMAC; /* unsupported extension */
case 0x2d: return FIDO_ERR_CANCELLED; /* KEEPALIVE_CANCEL */
case 0x2e: return FIDO_ERR_NO_CREDENTIAL;
case 0x2f: return FIDO_ERR_TIMEOUT; /* USER_ACTION_TIMEOUT */
@@ -199,7 +199,7 @@ static int ctap_status(uint8_t s) {
case 0x31: return FIDO_ERR_PIN_INVALID;
case 0x32: return FIDO_ERR_PIN_BLOCKED;
case 0x33: return FIDO_ERR_PIN_INVALID; /* PIN_AUTH_INVALID */
- case 0x34: return FIDO_ERR_PIN_BLOCKED; /* PIN_AUTH_BLOCKED (hay que reconectar) */
+ case 0x34: return FIDO_ERR_PIN_BLOCKED; /* PIN_AUTH_BLOCKED (must reconnect) */
case 0x35: return FIDO_ERR_PIN_REQUIRED; /* PIN_NOT_SET */
case 0x36: return FIDO_ERR_PIN_REQUIRED;
case 0x37: return FIDO_ERR_PIN_INVALID; /* PIN_POLICY_VIOLATION */
@@ -213,11 +213,11 @@ static int dev_open(Dev *d, int fd) {
d->fd = fd;
int rc = hid_init(fd, &d->cid, &d->caps);
if (rc) return rc;
- if (!(d->caps & CAP_CBOR)) return FIDO_ERR_NO_HMAC; /* solo U2F */
+ if (!(d->caps & CAP_CBOR)) return FIDO_ERR_NO_HMAC; /* U2F only */
return 0;
}
-/* Comando CTAP2: req (CBOR) → resp (CBOR, sin el byte de estado). */
+/* CTAP2 command: req (CBOR) → resp (CBOR, without the status byte). */
static int ctap_cmd(Dev *d, uint8_t c, const uint8_t *req, size_t reqlen, uint8_t *resp, size_t cap, size_t *resplen,
int timeout_ms, FidoStatusCb cb, void *ud) {
uint8_t msg[MSG_MAX];
@@ -234,7 +234,7 @@ static int ctap_cmd(Dev *d, uint8_t c, const uint8_t *req, size_t reqlen, uint8_
size_t len = 0;
rc = hid_recv(d->fd, d->cid, &cmd, msg, sizeof msg, &len, now_ms() + timeout_ms, cb, ud);
if (rc == FIDO_ERR_TIMEOUT || rc == FIDO_ERR_CANCELLED) {
- /* cortar la espera en la llave y escuchar su respuesta un rato */
+ /* abort the wait on the key and listen to its response for a while */
uint8_t pkt[PKT];
memset(pkt, 0, PKT);
put_cid(pkt, d->cid);
@@ -330,12 +330,12 @@ int fido_get_info(int fd, FidoInfo *info) {
if (rc == FIDO_ERR_NO_HMAC) { memset(info, 0, sizeof *info); info->client_pin = -1; info->pin_retries = -1; return 0; }
if (rc) return rc;
rc = get_info(&d, info);
- if (rc == FIDO_ERR_NO_HMAC) return 0; /* llave U2F: hmac_secret queda en 0 */
+ if (rc == FIDO_ERR_NO_HMAC) return 0; /* U2F key: hmac_secret stays 0 */
if (rc == 0 && info->client_pin == 1) info->pin_retries = pin_retries(&d);
return rc;
}
-/* ---- protocolo de PIN 1 ---- */
+/* ---- PIN protocol 1 ---- */
static void cose_key(CbW *w, const uint8_t x[32], const uint8_t y[32]) {
cbw_map(w, 5);
@@ -346,7 +346,7 @@ static void cose_key(CbW *w, const uint8_t x[32], const uint8_t y[32]) {
cbw_int(w, -3); cbw_bytes(w, y, 32);
}
-/* Acuerdo de claves con la llave: shared = SHA-256(x de ECDH); mx/my = nuestra clave pública. */
+/* Key agreement with the key: shared = SHA-256(x of ECDH); mx/my = our public key. */
static int key_agreement(Dev *d, uint8_t shared[32], uint8_t mx[32], uint8_t my[32]) {
uint8_t req[16], resp[256];
CbW w;
@@ -463,10 +463,10 @@ static int parse_authdata(const uint8_t *a, size_t n, AuthData *o) {
if (n < 37) return FIDO_ERR_PROTOCOL;
uint8_t rph[32];
sha256(FIDO_RP_ID, strlen(FIDO_RP_ID), rph);
- if (memcmp(a, rph, 32)) return FIDO_ERR_PROTOCOL; /* no es de nuestro rp.id */
+ if (memcmp(a, rph, 32)) return FIDO_ERR_PROTOCOL; /* not from our rp.id */
o->flags = a[32];
size_t p = 37;
- if (o->flags & 0x40) { /* AT: datos de la credencial */
+ if (o->flags & 0x40) { /* AT: credential data */
if (n < p + 18) return FIDO_ERR_PROTOCOL;
p += 16; /* aaguid */
size_t cl = (size_t)a[p] << 8 | a[p + 1];
@@ -477,10 +477,10 @@ static int parse_authdata(const uint8_t *a, size_t n, AuthData *o) {
p += cl;
CbItem it[32];
Cb c;
- if (cb_parse(&c, a + p, n - p, it, 32, 1) || cb_type(&c, 0) != CB_MAP) return FIDO_ERR_PROTOCOL; /* clave COSE */
+ if (cb_parse(&c, a + p, n - p, it, 32, 1) || cb_type(&c, 0) != CB_MAP) return FIDO_ERR_PROTOCOL; /* COSE key */
p += c.used;
}
- if (o->flags & 0x80) { /* ED: extensiones */
+ if (o->flags & 0x80) { /* ED: extensions */
CbItem it[16];
Cb c;
if (cb_parse(&c, a + p, n - p, it, 16, 1) || cb_type(&c, 0) != CB_MAP) return FIDO_ERR_PROTOCOL;
@@ -498,7 +498,7 @@ static int prepare(int fd, Dev *d, const char *pin, int need_pin_for_make) {
rc = get_info(d, &info);
if (rc) return rc;
if (!info.hmac_secret) return FIDO_ERR_NO_HMAC;
- if (pin && info.client_pin != 1) return FIDO_ERR_PIN_INVALID; /* PIN de más: la llave no tiene */
+ if (pin && info.client_pin != 1) return FIDO_ERR_PIN_INVALID; /* extra PIN: the key has none */
if (need_pin_for_make && info.client_pin == 1 && !pin) return FIDO_ERR_PIN_REQUIRED;
return 0;
}
@@ -545,7 +545,7 @@ int fido_make_credential(int fd, const char *pin, uint8_t *cred, size_t *cred_le
AuthData a;
if ((rc = parse_authdata(c.it[ad].ptr, c.it[ad].len, &a))) return rc;
if (!a.cred) return FIDO_ERR_PROTOCOL;
- /* la llave tiene que confirmar hmac-secret en las extensiones */
+ /* the key must confirm hmac-secret in the extensions */
int ok = 0;
if (a.ext) {
CbItem e[16];
diff --git a/server/src/vault/ctap2.h b/server/src/vault/ctap2.h
index 02cdf0b..fede47c 100644
--- a/server/src/vault/ctap2.h
+++ b/server/src/vault/ctap2.h
@@ -1,77 +1,77 @@
-/* ctap2.h — cliente FIDO2 propio (CTAP 2.0/2.1 sobre USB HID) para desbloquear la bóveda con una
- * llave de seguridad (ver docs/PASSWORDS.md, «Llave de seguridad FIDO2»).
+/* ctap2.h — our own FIDO2 client (CTAP 2.0/2.1 over USB HID) to unlock the vault with a
+ * security key (see docs/PASSWORDS.md, "FIDO2 security key").
*
- * Usa la extensión `hmac-secret`: la llave guarda un secreto por credencial (CredRandom) y, dado
- * un «salt» de 32 bytes, devuelve HMAC-SHA256(CredRandom, salt). Ese resultado es la clave que
- * envuelve la clave de la bóveda: sin la llave física (y su toque) no se puede abrir.
+ * Uses the `hmac-secret` extension: the key stores a per-credential secret (CredRandom) and, given
+ * a 32-byte "salt", returns HMAC-SHA256(CredRandom, salt). That result is the key that
+ * wraps the vault key: without the physical key (and its touch) the vault cannot be opened.
*
- * Corre en lord-vault, encerrado: recibe el fd de /dev/hidrawN ya abierto por lord-server
- * (después del permiso del usuario) y solo hace read/write de reportes de 64 bytes, sin ioctl.
- * Protocolo: CTAPHID (INIT con nonce, canal propio, CBOR, KEEPALIVE, CANCEL, ERROR) +
- * authenticatorGetInfo, authenticatorClientPIN (getKeyAgreement y getPinToken, protocolo de PIN 1:
- * ECDH P-256 + SHA-256 + AES-256-CBC), authenticatorMakeCredential y authenticatorGetAssertion
- * con hmac-secret. El acuerdo de claves usa P-256 propio (p256.h). */
+ * Runs in lord-vault, sandboxed: it receives the fd of /dev/hidrawN already opened by lord-server
+ * (after the user's permission) and only does read/write of 64-byte reports, no ioctl.
+ * Protocol: CTAPHID (INIT with nonce, own channel, CBOR, KEEPALIVE, CANCEL, ERROR) +
+ * authenticatorGetInfo, authenticatorClientPIN (getKeyAgreement and getPinToken, PIN protocol 1:
+ * ECDH P-256 + SHA-256 + AES-256-CBC), authenticatorMakeCredential and authenticatorGetAssertion
+ * with hmac-secret. The key agreement uses our own P-256 (p256.h). */
#ifndef LORD_VAULT_CTAP2_H
#define LORD_VAULT_CTAP2_H
#include <stddef.h>
#include <stdint.h>
-#define FIDO_RP_ID "contrasenas.lordos" /* rp.id de las credenciales de la bóveda */
+#define FIDO_RP_ID "contrasenas.lordos" /* rp.id of the vault credentials */
#define FIDO_CRED_MAX 255
enum {
FIDO_OK = 0,
- FIDO_ERR_IO = -1, /* el dispositivo no responde o se desenchufó */
- FIDO_ERR_TIMEOUT = -2, /* nadie tocó la llave a tiempo */
- FIDO_ERR_PROTOCOL = -3, /* respuesta inválida */
- FIDO_ERR_NO_HMAC = -4, /* la llave no tiene hmac-secret (solo U2F, o muy vieja) */
- FIDO_ERR_PIN_REQUIRED = -5,/* la llave tiene PIN y no se pasó */
+ FIDO_ERR_IO = -1, /* the device does not respond or was unplugged */
+ FIDO_ERR_TIMEOUT = -2, /* nobody touched the key in time */
+ FIDO_ERR_PROTOCOL = -3, /* invalid response */
+ FIDO_ERR_NO_HMAC = -4, /* the key has no hmac-secret (U2F only, or very old) */
+ FIDO_ERR_PIN_REQUIRED = -5,/* the key has a PIN and none was given */
FIDO_ERR_PIN_INVALID = -6,
FIDO_ERR_PIN_BLOCKED = -7,
- FIDO_ERR_NO_CREDENTIAL = -8,/* la credencial no es de esta llave (otra llave) */
+ FIDO_ERR_NO_CREDENTIAL = -8,/* the credential is not from this key (another key) */
FIDO_ERR_CANCELLED = -9,
- FIDO_ERR_DENIED = -10, /* la llave rechazó (CTAP2_ERR_OPERATION_DENIED…) */
+ FIDO_ERR_DENIED = -10, /* the key refused (CTAP2_ERR_OPERATION_DENIED…) */
};
typedef struct {
- int hmac_secret; /* anuncia la extensión */
- int client_pin; /* -1 no soporta PIN, 0 soporta y no tiene, 1 tiene PIN */
- int uv; /* verificación propia (huella) */
+ int hmac_secret; /* advertises the extension */
+ int client_pin; /* -1 no PIN support, 0 supported but not set, 1 has a PIN */
+ int uv; /* built-in user verification (fingerprint) */
uint8_t aaguid[16];
char versions[64]; /* "FIDO_2_0,FIDO_2_1,U2F_V2" */
- int pin_retries; /* -1 si no se sabe */
+ int pin_retries; /* -1 if unknown */
} FidoInfo;
-/* Avisos mientras se espera: FIDO_ST_TOUCH = la llave pide que la toquen (KEEPALIVE UPNEEDED). */
+/* Notices while waiting: FIDO_ST_TOUCH = the key asks to be touched (KEEPALIVE UPNEEDED). */
enum { FIDO_ST_PROCESSING = 1, FIDO_ST_TOUCH = 2 };
typedef void (*FidoStatusCb)(void *ud, int status);
-/* Todas: fd de hidraw abierto en lectura y escritura; timeout_ms para esperar el toque. */
+/* All: hidraw fd open for reading and writing; timeout_ms to wait for the touch. */
int fido_get_info(int fd, FidoInfo *info);
-/* Crea una credencial nueva con hmac-secret para la bóveda (pide un toque). cred recibe el id de
- * la credencial (hasta FIDO_CRED_MAX bytes). pin: NULL o el PIN de la llave (UTF-8). */
+/* Creates a new credential with hmac-secret for the vault (asks for a touch). cred receives the
+ * credential id (up to FIDO_CRED_MAX bytes). pin: NULL or the key's PIN (UTF-8). */
int fido_make_credential(int fd, const char *pin, uint8_t *cred, size_t *cred_len,
int timeout_ms, FidoStatusCb cb, void *ud);
-/* hmac-secret de esa credencial con salt (pide un toque): out = HMAC-SHA256(CredRandom, salt). */
+/* hmac-secret of that credential with salt (asks for a touch): out = HMAC-SHA256(CredRandom, salt). */
int fido_hmac_secret(int fd, const char *pin, const uint8_t *cred, size_t cred_len,
const uint8_t salt[32], uint8_t out[32], int timeout_ms, FidoStatusCb cb, void *ud);
-/* Corta una espera en curso (desde otro hilo): manda CTAPHID_CANCEL. */
+/* Aborts a wait in progress (from another thread): sends CTAPHID_CANCEL. */
void fido_cancel(int fd);
-const char *fido_strerror(int err); /* código corto en inglés: "timeout", "pin-required"… */
+const char *fido_strerror(int err); /* short code in English: "timeout", "pin-required"… */
-/* ---- agregados ----
- * Notas de uso:
- * - cred tiene que tener lugar para FIDO_CRED_MAX bytes (*cred_len es solo de salida).
- * - hmac-secret con PIN (pin != NULL → pinAuth, UV) y sin PIN (solo toque) pueden dar
- * resultados DISTINTOS en llaves CTAP 2.1 (CredRandomWithUV / WithoutUV): la bóveda tiene que
- * guardar en la ranura si se usó PIN y repetir lo mismo al desbloquear.
- * - Con PIN puesto en la llave, makeCredential exige el PIN (FIDO_ERR_PIN_REQUIRED). */
+/* ---- additions ----
+ * Usage notes:
+ * - cred must have room for FIDO_CRED_MAX bytes (*cred_len is output only).
+ * - hmac-secret with PIN (pin != NULL → pinAuth, UV) and without PIN (touch only) may give
+ * DIFFERENT results on CTAP 2.1 keys (CredRandomWithUV / WithoutUV): the vault must
+ * store in the slot whether a PIN was used and repeat the same when unlocking.
+ * - With a PIN set on the key, makeCredential requires the PIN (FIDO_ERR_PIN_REQUIRED). */
-/* Pone un PIN nuevo en una llave que no tiene (clientPIN setPIN, protocolo 1; 4–63 bytes). */
+/* Sets a new PIN on a key that has none (clientPIN setPIN, protocol 1; 4–63 bytes). */
int fido_set_pin(int fd, const char *pin);
-/* Transporte crudo: CTAPHID_INIT y un comando (cmd con el bit 0x80) con su respuesta. Para
- * pruebas y comandos del fabricante. Devuelve 0 y *resp_len, o un FIDO_ERR_*. */
+/* Raw transport: CTAPHID_INIT and a command (cmd with the 0x80 bit) with its response. For
+ * tests and vendor commands. Returns 0 and *resp_len, or a FIDO_ERR_*. */
int ctaphid_command(int fd, uint8_t cmd, const uint8_t *data, size_t len,
uint8_t *resp, size_t cap, size_t *resp_len, int timeout_ms);
diff --git a/server/src/vault/dbus.c b/server/src/vault/dbus.c
index d6d3975..36f92be 100644
--- a/server/src/vault/dbus.c
+++ b/server/src/vault/dbus.c
@@ -1,4 +1,4 @@
-/* dbus.c — cliente D-Bus propio y mínimo (ver dbus.h). */
+/* dbus.c — own minimal D-Bus client (see dbus.h). */
#include "dbus.h"
#include <errno.h>
@@ -12,7 +12,7 @@
#include <time.h>
#include <unistd.h>
-/* ================= firmas ================= */
+/* ================= signatures ================= */
static int align_of(char c) {
switch (c) {
@@ -91,7 +91,7 @@ int dbus_name_valid(const char *n) {
return dots >= 1 && !start;
}
-/* ================= validación del cuerpo ================= */
+/* ================= body validation ================= */
typedef struct { const uint8_t *b; size_t len, pos; int be; } V;
@@ -103,7 +103,7 @@ static uint32_t rd32(const uint8_t *p, int be) {
static int v_align(V *v, int a) {
size_t np = (v->pos + (size_t)a - 1) & ~((size_t)a - 1);
if (np > v->len) return -1;
- for (size_t i = v->pos; i < np; i++) if (v->b[i]) return -1; /* relleno en cero */
+ for (size_t i = v->pos; i < np; i++) if (v->b[i]) return -1; /* zero padding */
v->pos = np;
return 0;
}
@@ -210,7 +210,7 @@ int dbus_body_valid(const char *sig, const uint8_t *body, size_t len, int big_en
return v.pos == len;
}
-/* ================= mensajes ================= */
+/* ================= messages ================= */
long dbus_msg_size(const uint8_t *buf, size_t len) {
if (len < 16) return 0;
@@ -246,14 +246,14 @@ int dbus_msg_parse(const uint8_t *buf, size_t len, DMsg *m) {
m->serial = serial;
uint32_t flen = rd32(buf + 12, be);
size_t hend = 16 + flen;
- /* validar a(yv) desde el byte 12 con la alineación del mensaje */
+ /* validate a(yv) from byte 12 with the message alignment */
V v = { m->raw, hend, 12, be };
size_t u;
if (v_type(&v, "a(yv)", &u, 0) || v.pos != hend) goto bad;
- /* relleno hasta 8 en cero */
+ /* zero padding up to 8 */
size_t bstart = (hend + 7) & ~(size_t)7;
for (size_t i = hend; i < bstart; i++) if (m->raw[i]) goto bad;
- /* recorrer los campos */
+ /* walk the fields */
size_t p = 16;
uint32_t got_fds = 0;
while (p < hend) {
@@ -288,14 +288,14 @@ int dbus_msg_parse(const uint8_t *buf, size_t len, DMsg *m) {
}
}
} else {
- /* campo desconocido: saltearlo (ya validado) */
+ /* unknown field: skip it (already validated) */
V w = { m->raw, hend, p, be };
size_t k;
if (v_type(&w, vs, &k, 1)) goto bad;
p = w.pos;
}
}
- if (got_fds) goto bad; /* no aceptamos fds */
+ if (got_fds) goto bad; /* we do not accept fds */
switch (type) {
case DBUS_CALL: if (!m->path || !m->member) goto bad; break;
case DBUS_RETURN: if (!m->reply_serial) goto bad; break;
@@ -326,7 +326,7 @@ void dbus_msg_free(DMsg *m) {
memset(m, 0, sizeof *m);
}
-/* ================= lector tipado ================= */
+/* ================= typed reader ================= */
void dr_init(DRd *r, const DMsg *m) { r->b = m->body; r->len = m->body_len; r->pos = 0; r->be = m->big_endian; r->err = 0; }
@@ -392,7 +392,7 @@ void dr_skip(DRd *r, const char *sig) {
r->pos = v.pos;
}
-/* ================= escritor ================= */
+/* ================= writer ================= */
void dw_init(DBuf *w) { memset(w, 0, sizeof *w); }
void dw_free(DBuf *w) { if (w->p) { explicit_bzero(w->p, w->cap); free(w->p); } memset(w, 0, sizeof *w); }
@@ -405,7 +405,7 @@ static int w_need(DBuf *w, size_t n) {
while (nc < w->n + n) nc *= 2;
uint8_t *p = malloc(nc);
if (!p) { w->oom = 1; return -1; }
- if (w->p) { memcpy(p, w->p, w->n); explicit_bzero(w->p, w->cap); free(w->p); } /* sin realloc: lo viejo se borra */
+ if (w->p) { memcpy(p, w->p, w->n); explicit_bzero(w->p, w->cap); free(w->p); } /* no realloc: the old data is wiped */
w->p = p;
w->cap = nc;
return 0;
@@ -493,7 +493,7 @@ int dbus_build(const DHdr *h, const DBuf *body, DBuf *out) {
return out->oom ? -1 : 0;
}
-/* ================= conexión ================= */
+/* ================= connection ================= */
int dbus_connect_session(void) {
struct sockaddr_un a = { .sun_family = AF_UNIX };
@@ -503,7 +503,7 @@ int dbus_connect_session(void) {
int abstract = 0;
path[0] = 0;
if (addr) {
- /* varias direcciones separadas por ';': la primera unix: que sirva */
+ /* several addresses separated by ';': the first usable unix: one */
const char *p = addr;
while (p && *p && !path[0]) {
const char *end = strchr(p, ';');
@@ -601,7 +601,7 @@ static int write_all(int fd, const void *buf, size_t n, double deadline) {
return 0;
}
-/* Una línea SASL ("...\r\n"), de a un byte para no comerse nada del protocolo binario. */
+/* One SASL line ("...\r\n"), one byte at a time so as not to swallow any of the binary protocol. */
static int read_line(int fd, char *out, size_t cap, double deadline) {
size_t n = 0;
for (;;) {
@@ -713,7 +713,7 @@ static int take(DConn *c, DMsg *m) {
memmove(c->in, c->in + sz, rest);
explicit_bzero(c->in + rest, (size_t)sz);
c->in_n = rest;
- if (r) { c->dead = 1; return -1; } /* el bus ya valida: algo inválido es un error grave */
+ if (r) { c->dead = 1; return -1; } /* the bus already validates: something invalid is a serious error */
return 1;
}
diff --git a/server/src/vault/dbus.h b/server/src/vault/dbus.h
index 86f2622..dd35b62 100644
--- a/server/src/vault/dbus.h
+++ b/server/src/vault/dbus.h
@@ -1,18 +1,18 @@
-/* dbus.h — cliente D-Bus propio y mínimo (sin libdbus ni sd-bus), lo justo para atender el
- * Secret Service (secretsvc.c) desde lord-vault. Ver docs/PASSWORDS.md, «Secret Service».
+/* dbus.h — own minimal D-Bus client (no libdbus or sd-bus), just enough to serve the
+ * Secret Service (secretsvc.c) from lord-vault. See docs/PASSWORDS.md, "Secret Service".
*
- * - Mensajes (especificación D-Bus 0.41): cabecera fija + campos a(yv) + cuerpo, alineación
- * por tipo, little endian al escribir y los dos órdenes al leer. Tipos: y b n q i u x t d s
- * o g a ( ) { } v (sin h: no se pasan fds).
- * - Lectura estricta: dbus_msg_parse valida TODO antes de entregar el mensaje (largos, firmas,
- * profundidad, textos terminados en NUL y sin NUL adentro, booleanos 0/1, rutas de objeto,
- * alineación y relleno en cero, tope de 128 MiB). Después el lector tipado (DRd) solo lee
- * lo ya validado y igual controla los límites.
- * - Conexión: SASL EXTERNAL sobre un socket YA conectado (lord-vault no puede abrir sockets:
- * se lo pasa lord-server), Hello, RequestName; envío sin bloquear con una cola de salida.
+ * - Messages (D-Bus specification 0.41): fixed header + a(yv) fields + body, per-type
+ * alignment, little endian when writing and both orders when reading. Types: y b n q i u x t d s
+ * o g a ( ) { } v (no h: fds are not passed).
+ * - Strict reading: dbus_msg_parse validates EVERYTHING before delivering the message (lengths, signatures,
+ * depth, NUL-terminated strings with no embedded NUL, booleans 0/1, object paths,
+ * zero alignment and padding, 128 MiB cap). After that the typed reader (DRd) only reads
+ * what was already validated and still checks the bounds.
+ * - Connection: SASL EXTERNAL over an ALREADY connected socket (lord-vault cannot open sockets:
+ * lord-server hands it over), Hello, RequestName; non-blocking send with an output queue.
*
- * Los búferes de la conexión son de malloc (no de la arena de secretos, que se borra entera al
- * bloquear) y se borran con explicit_bzero antes de soltarse o reusarse. */
+ * The connection buffers are malloc'd (not in the secrets arena, which is wiped entirely on
+ * lock) and are wiped with explicit_bzero before being released or reused. */
#ifndef LORD_VAULT_DBUS_H
#define LORD_VAULT_DBUS_H
@@ -20,38 +20,38 @@
#include <stdint.h>
#define DBUS_MAX_MSG (128u * 1024 * 1024)
-#define DBUS_MAX_DEPTH 32 /* contenedores anidados (la especificación permite 64) */
+#define DBUS_MAX_DEPTH 32 /* nested containers (the specification allows 64) */
enum { DBUS_CALL = 1, DBUS_RETURN = 2, DBUS_ERROR = 3, DBUS_SIGNAL = 4 };
enum { DBUS_NO_REPLY = 1, DBUS_NO_AUTOSTART = 2 };
-/* Un mensaje recibido. Los textos apuntan adentro de raw (terminados en NUL); NULL si no vino. */
+/* A received message. The strings point inside raw (NUL-terminated); NULL if absent. */
typedef struct {
uint8_t type, flags, big_endian;
uint32_t serial, reply_serial;
const char *path, *iface, *member, *error, *dest, *sender, *sig;
const uint8_t *body;
uint32_t body_len;
- uint8_t *raw; /* malloc; dbus_msg_free lo borra */
+ uint8_t *raw; /* malloc; dbus_msg_free wipes it */
size_t raw_len;
} DMsg;
-/* Largo total del mensaje que empieza en buf (al menos 16 bytes), 0 si faltan bytes para saberlo
- * o -1 si la cabecera es inválida o pasa el tope. */
+/* Total length of the message starting at buf (at least 16 bytes), 0 if more bytes are needed to know
+ * or -1 if the header is invalid or exceeds the cap. */
long dbus_msg_size(const uint8_t *buf, size_t len);
-/* Valida y arma m a partir de una COPIA de buf[0..len) (len = dbus_msg_size). 0 bien. */
+/* Validates and builds m from a COPY of buf[0..len) (len = dbus_msg_size). 0 ok. */
int dbus_msg_parse(const uint8_t *buf, size_t len, DMsg *m);
void dbus_msg_free(DMsg *m);
-/* Validaciones sueltas */
-int dbus_sig_valid(const char *sig); /* firma completa (varios tipos), ≤ 255 */
-int dbus_sig_single(const char *sig, size_t *n);/* largo de UN tipo completo al comienzo; 0 bien */
+/* Standalone validations */
+int dbus_sig_valid(const char *sig); /* complete signature (several types), ≤ 255 */
+int dbus_sig_single(const char *sig, size_t *n);/* length of ONE complete type at the start; 0 ok */
int dbus_path_valid(const char *p);
-int dbus_name_valid(const char *n); /* nombre de interfaz/bus (sin ':' único) */
-/* Valida un cuerpo con esa firma (alineación relativa a 'base', que tiene que estar alineado a 8). */
+int dbus_name_valid(const char *n); /* interface/bus name (no unique ':') */
+/* Validates a body with that signature (alignment relative to 'base', which must be 8-aligned). */
int dbus_body_valid(const char *sig, const uint8_t *body, size_t len, int big_endian);
-/* ---- lector tipado del cuerpo ---- */
+/* ---- typed body reader ---- */
typedef struct {
const uint8_t *b;
size_t len, pos;
@@ -63,48 +63,48 @@ int dr_bool(DRd *r);
uint32_t dr_u32(DRd *r);
int32_t dr_i32(DRd *r);
uint64_t dr_u64(DRd *r);
-const char *dr_str(DRd *r, uint32_t *len); /* s, o (y g con dr_sig) */
+const char *dr_str(DRd *r, uint32_t *len); /* s, or (y g with dr_sig) */
const char *dr_sig(DRd *r);
-/* ay: puntero a los bytes y largo */
+/* ay: pointer to the bytes and length */
const uint8_t *dr_bytes(DRd *r, uint32_t *len);
-/* arreglo: dr_arr devuelve el fin; mientras dr_more(r, fin) hay elementos. elem_align: 1/4/8 */
+/* array: dr_arr returns the end; while dr_more(r, end) there are elements. elem_align: 1/4/8 */
size_t dr_arr(DRd *r, int elem_align);
int dr_more(DRd *r, size_t end);
-void dr_struct(DRd *r); /* alinea a 8 */
-/* v: firma del contenido (para comparar) */
+void dr_struct(DRd *r); /* aligns to 8 */
+/* v: signature of the content (to compare) */
const char *dr_variant(DRd *r);
-/* Saltea un valor de tipo completo sig (ya validado). */
+/* Skips a value of complete type sig (already validated). */
void dr_skip(DRd *r, const char *sig);
-/* ---- escritor ---- */
+/* ---- writer ---- */
typedef struct { uint8_t *p; size_t n, cap; int oom; } DBuf;
void dw_init(DBuf *w);
-void dw_free(DBuf *w); /* borra y libera */
+void dw_free(DBuf *w); /* wipes and frees */
void dw_align(DBuf *w, int a);
void dw_u8(DBuf *w, uint8_t v);
void dw_bool(DBuf *w, int v);
void dw_u32(DBuf *w, uint32_t v);
void dw_i32(DBuf *w, int32_t v);
void dw_u64(DBuf *w, uint64_t v);
-void dw_str(DBuf *w, const char *s); /* s u o */
+void dw_str(DBuf *w, const char *s); /* s or o */
void dw_strn(DBuf *w, const char *s, size_t n);
void dw_sig(DBuf *w, const char *s); /* g */
void dw_bytes(DBuf *w, const uint8_t *p, size_t n); /* ay */
-size_t dw_arr_begin(DBuf *w, int elem_align); /* devuelve una marca para dw_arr_end */
+size_t dw_arr_begin(DBuf *w, int elem_align); /* returns a mark for dw_arr_end */
void dw_arr_end(DBuf *w, size_t mark);
-void dw_struct(DBuf *w); /* alinea a 8 */
-void dw_variant(DBuf *w, const char *sig); /* escribe la firma; después el valor */
+void dw_struct(DBuf *w); /* aligns to 8 */
+void dw_variant(DBuf *w, const char *sig); /* writes the signature; then the value */
-/* Arma un mensaje completo (cabecera + cuerpo). Devuelve 0 bien; out en malloc. */
+/* Builds a complete message (header + body). Returns 0 ok; out in malloc. */
typedef struct {
uint8_t type, flags;
uint32_t serial, reply_serial;
const char *path, *iface, *member, *error, *dest, *sig;
- const char *sender; /* solo lo pone el bus (y las pruebas que hacen de bus) */
+ const char *sender; /* only set by the bus (and by tests acting as the bus) */
} DHdr;
int dbus_build(const DHdr *h, const DBuf *body, DBuf *out);
-/* ---- conexión ---- */
+/* ---- connection ---- */
typedef struct {
int fd;
uint32_t serial;
@@ -114,27 +114,27 @@ typedef struct {
int dead;
} DConn;
-/* Conecta (sin autenticar) al bus de la sesión: DBUS_SESSION_BUS_ADDRESS (unix:path= o
- * unix:abstract=) o $XDG_RUNTIME_DIR/bus. Para lord-server, fuera de la caja de arena. fd o -1. */
+/* Connects (without authenticating) to the session bus: DBUS_SESSION_BUS_ADDRESS (unix:path= or
+ * unix:abstract=) or $XDG_RUNTIME_DIR/bus. For lord-server, outside the sandbox. fd or -1. */
int dbus_connect_session(void);
/* System bus: DBUS_SYSTEM_BUS_ADDRESS (unix:path=) or /run/dbus/system_bus_socket. fd or -1. */
int dbus_connect_system(void);
-/* SASL EXTERNAL + Hello sobre un socket conectado (espera hasta timeout_ms). Deja el fd sin
- * bloquear. 0 bien. */
+/* SASL EXTERNAL + Hello over a connected socket (waits up to timeout_ms). Leaves the fd
+ * non-blocking. 0 ok. */
int dbus_open(DConn *c, int fd, int timeout_ms);
-void dbus_close(DConn *c); /* cierra el fd y borra los búferes */
-/* Encola un mensaje (h->serial se completa si es 0) y trata de mandarlo. Devuelve el serial o 0. */
+void dbus_close(DConn *c); /* closes the fd and wipes the buffers */
+/* Queues a message (h->serial is filled in if 0) and tries to send it. Returns the serial or 0. */
uint32_t dbus_send(DConn *c, DHdr *h, const DBuf *body);
-int dbus_flush(DConn *c); /* manda lo que se pueda; -1 si se cortó */
+int dbus_flush(DConn *c); /* sends what it can; -1 if disconnected */
int dbus_pending_out(const DConn *c);
-/* Lee lo que haya (sin bloquear) y entrega el próximo mensaje completo en m: 1 hay mensaje,
- * 0 no hay (por ahora), -1 se cortó o llegó algo inválido. */
+/* Reads what is available (non-blocking) and delivers the next complete message in m: 1 message,
+ * 0 none (for now), -1 disconnected or something invalid arrived. */
int dbus_next(DConn *c, DMsg *m);
-/* Espera bloqueando (hasta timeout_ms) la respuesta a serial; los demás mensajes se descartan.
- * Solo para el arranque. 1 respuesta (en m), 0 error D-Bus (en m), -1 corte o tiempo. */
+/* Blocks (up to timeout_ms) waiting for the reply to serial; other messages are discarded.
+ * Startup only. 1 reply (in m), 0 D-Bus error (in m), -1 disconnect or timeout. */
int dbus_wait_reply(DConn *c, uint32_t serial, DMsg *m, int timeout_ms);
-/* Respuestas y señales de conveniencia */
+/* Convenience replies and signals */
uint32_t dbus_reply(DConn *c, const DMsg *call, const char *sig, const DBuf *body);
uint32_t dbus_error(DConn *c, const DMsg *call, const char *name, const char *text);
uint32_t dbus_signal(DConn *c, const char *path, const char *iface, const char *member, const char *sig, const DBuf *body);
diff --git a/server/src/vault/fidodev.c b/server/src/vault/fidodev.c
index 8e4c48c..71b2020 100644
--- a/server/src/vault/fidodev.c
+++ b/server/src/vault/fidodev.c
@@ -1,4 +1,4 @@
-/* fidodev.c — llaves FIDO2 por hidraw (ver fidodev.h). */
+/* fidodev.c — FIDO2 keys over hidraw (see fidodev.h). */
#include "fidodev.h"
#include <dirent.h>
@@ -14,9 +14,9 @@ static const char *sysroot = "/sys/class/hidraw";
void fidodev_set_sysroot(const char *dir) { sysroot = dir ? dir : "/sys/class/hidraw"; }
-/* Ítems cortos del descriptor HID: prefijo (tag 4 bits, tipo 2, tamaño 2) + 0/1/2/4 bytes;
- * ítem largo 0xFE: tamaño, tag, datos. Se siguen Usage Page (global, con push/pop), Usage
- * (local, 16 o 32 bits) y Collection (main). */
+/* Short items of the HID descriptor: prefix (tag 4 bits, type 2, size 2) + 0/1/2/4 bytes;
+ * long item 0xFE: size, tag, data. We track Usage Page (global, with push/pop), Usage
+ * (local, 16 or 32 bits) and Collection (main). */
int fidodev_desc_is_fido(const uint8_t *d, size_t len) {
uint32_t page = 0, stack[8];
int sp = 0;
@@ -25,7 +25,7 @@ int fidodev_desc_is_fido(const uint8_t *d, size_t len) {
size_t p = 0;
while (p < len) {
uint8_t b = d[p++];
- if (b == 0xfe) { /* ítem largo */
+ if (b == 0xfe) { /* long item */
if (p + 2 > len) return 0;
size_t sz = d[p];
p += 2 + sz;
@@ -47,7 +47,7 @@ int fidodev_desc_is_fido(const uint8_t *d, size_t len) {
if (tag == 10 && v == 1) { /* Collection (Application) */
for (int i = 0; i < nusage; i++) if (usage[i] == 0xf1d00001u) return 1;
}
- nusage = 0; /* los locales valen hasta el próximo main */
+ nusage = 0; /* locals last until the next main */
}
}
return 0;
diff --git a/server/src/vault/fidodev.h b/server/src/vault/fidodev.h
index f6da81e..f089730 100644
--- a/server/src/vault/fidodev.h
+++ b/server/src/vault/fidodev.h
@@ -1,10 +1,10 @@
-/* fidodev.h — encontrar y abrir llaves FIDO2 (lado de lord-server, sin caja de arena).
+/* fidodev.h — find and open FIDO2 keys (lord-server side, outside the sandbox).
*
- * Recorre /sys/class/hidraw/hidraw*: un dispositivo es FIDO si su descriptor de reportes HID
- * (device/report_descriptor) declara una colección de aplicación con Usage Page 0xF1D0 (FIDO
- * Alliance) y Usage 0x01 (CTAPHID). El nombre y vid:pid salen de device/uevent (HID_NAME,
- * HID_ID). lord-server abre el elegido (después del permiso del usuario) y le pasa el fd a
- * lord-vault; ni la app ni lord-vault abren /dev. */
+ * Walks /sys/class/hidraw/hidraw*: a device is FIDO if its HID report descriptor
+ * (device/report_descriptor) declares an application collection with Usage Page 0xF1D0 (FIDO
+ * Alliance) and Usage 0x01 (CTAPHID). The name and vid:pid come from device/uevent (HID_NAME,
+ * HID_ID). lord-server opens the chosen one (after the user's permission) and passes the fd to
+ * lord-vault; neither the app nor lord-vault opens /dev. */
#ifndef LORD_VAULT_FIDODEV_H
#define LORD_VAULT_FIDODEV_H
@@ -17,14 +17,14 @@ typedef struct {
unsigned vid, pid;
} FidoDev;
-/* Hasta max llaves; devuelve cuántas. */
+/* Up to max keys; returns how many. */
int fidodev_list(FidoDev *out, int max);
-/* Abre path (tiene que ser /dev/hidrawN y una llave FIDO) con O_RDWR|O_CLOEXEC|O_NONBLOCK.
- * fd o -1 (errno). */
+/* Opens path (must be /dev/hidrawN and a FIDO key) with O_RDWR|O_CLOEXEC|O_NONBLOCK.
+ * fd or -1 (errno). */
int fidodev_open(const char *path);
-/* 1 si el descriptor HID declara la colección FIDO (para pruebas y para fidodev_list). */
+/* 1 if the HID descriptor declares the FIDO collection (for tests and for fidodev_list). */
int fidodev_desc_is_fido(const uint8_t *desc, size_t len);
-/* Para pruebas: otra raíz en vez de "/sys/class/hidraw" (NULL vuelve a la de siempre). */
+/* For tests: another root instead of "/sys/class/hidraw" (NULL restores the default). */
void fidodev_set_sysroot(const char *dir);
#endif
diff --git a/server/src/vault/kdbx.c b/server/src/vault/kdbx.c
index fe2b2ff..7b2cd14 100644
--- a/server/src/vault/kdbx.c
+++ b/server/src/vault/kdbx.c
@@ -1,7 +1,7 @@
-/* kdbx.c — lector de KDBX 3.1 y 4.x (ver kdbx.h).
+/* kdbx.c — KDBX 3.1 and 4.x reader (see kdbx.h).
*
- * Referencia del formato: el código de KeePass 2.x (KdbxFile.*) y KeePassXC (Kdbx3Reader,
- * Kdbx4Reader, KeePass2RandomStream). Todo lo descifrado va en la arena de secretos. */
+ * Format reference: the KeePass 2.x code (KdbxFile.*) and KeePassXC (Kdbx3Reader,
+ * Kdbx4Reader, KeePass2RandomStream). Everything decrypted goes in the secrets arena. */
#include "kdbx.h"
#include "smem.h"
#include "vcrypto.h"
@@ -27,7 +27,7 @@ static const uint8_t U_CHACHA[16] = { 0xd6,0x03,0x8a,0x2b,0x8b,0x6f,0x4c,0xb5,0x
static const uint8_t U_ARGON2D[16] = { 0xef,0x63,0x6d,0xdf,0x8c,0x29,0x44,0x4b,0x91,0xf7,0xa9,0xa4,0x03,0xe3,0x0a,0x0c };
static const uint8_t U_ARGON2ID[16] = { 0x9e,0x29,0x8b,0x19,0x56,0xdb,0x47,0x73,0xb2,0x3d,0xfc,0x3e,0xc6,0xf0,0xa1,0xe6 };
static const uint8_t U_AESKDF[16] = { 0xc9,0xd9,0xf3,0x9a,0x62,0x8a,0x44,0x60,0xbf,0x74,0x0d,0x08,0xc1,0x8a,0x4f,0xea };
-/* KeePassXC también escribe AES-KDF con este UUID («KDBX 4») */
+/* KeePassXC also writes AES-KDF with this UUID ("KDBX 4") */
static const uint8_t U_AESKDF4[16] = { 0x7c,0x02,0xbb,0x82,0x79,0xa7,0x4a,0xc0,0x92,0x7d,0x11,0x4a,0x00,0x64,0x82,0x38 };
static uint32_t rd16(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8; }
@@ -41,12 +41,12 @@ static int fail(ImpList *l, const char *code) { snprintf(l->err, sizeof l->err,
int kdbx_is(const uint8_t *d, size_t len) { return len >= 8 && !memcmp(d, SIG, 8); }
-/* ---- archivo llave ---- */
+/* ---- key file ---- */
static int hexv(int c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; }
int kdbx_keyfile_key(const uint8_t *kf, size_t n, uint8_t out[32]) {
- /* XML de KeePass (1.0: base64; 2.0: hex con Hash = primeros 4 bytes del SHA-256) */
+ /* KeePass XML (1.0: base64; 2.0: hex with Hash = first 4 bytes of the SHA-256) */
if (n > 8 && n < 65536 && memmem(kf, n, "<KeyFile", 8)) {
XNode *x = xml_parse((const char *)kf, n, NULL);
if (x && !strcmp(x->name, "KeyFile")) {
@@ -59,7 +59,7 @@ int kdbx_keyfile_key(const uint8_t *kf, size_t n, uint8_t out[32]) {
const char *t = xml_text(data);
for (; *t && m < 64; t++) {
int v = hexv((unsigned char)*t);
- if (v < 0) continue; /* espacios y saltos de línea */
+ if (v < 0) continue; /* spaces and line breaks */
if (m % 2 == 0) k[m / 2] = (uint8_t)(v << 4); else k[m / 2] |= (uint8_t)v;
m++;
}
@@ -97,7 +97,7 @@ int kdbx_keyfile_key(const uint8_t *kf, size_t n, uint8_t out[32]) {
return 0;
}
-/* ---- flujo interno (valores protegidos) ---- */
+/* ---- inner stream (protected values) ---- */
typedef struct { int kind; uint8_t key[32], nonce[12], buf[64]; int pos; uint64_t ctr; } Stream;
@@ -124,7 +124,7 @@ static void salsa20_block(const uint8_t key[32], const uint8_t nonce[8], uint64_
static const uint8_t SALSA_IV[8] = { 0xe8, 0x30, 0x09, 0x4b, 0x97, 0x20, 0x5d, 0x2a };
-/* id: 2 Salsa20, 3 ChaCha20 (0 = sin protección) */
+/* id: 2 Salsa20, 3 ChaCha20 (0 = no protection) */
static int stream_init(Stream *s, uint32_t id, const uint8_t *key, size_t klen) {
memset(s, 0, sizeof *s);
s->pos = 64;
@@ -156,7 +156,7 @@ static void stream_xor(Stream *s, uint8_t *p, size_t n) {
}
}
-/* ---- cabecera ---- */
+/* ---- header ---- */
typedef struct {
int major, minor;
@@ -197,7 +197,7 @@ static int read_header(const uint8_t *d, size_t len, Hdr *h, ImpList *l) {
case 9: if (sz != 32) return fail(l, "corrupt"); h->start = v; break;
case 10: if (sz != 4) return fail(l, "corrupt"); h->inner_id = rd32(v); h->have_inner = 1; break;
case 11: h->kdf = v; h->kdflen = sz; break;
- default: break; /* 12: datos públicos, y lo que venga */
+ default: break; /* 12: public data, and whatever else comes */
}
}
done:
@@ -211,12 +211,12 @@ done:
return 0;
}
-/* VariantDictionary (KDF de KDBX 4) */
+/* VariantDictionary (KDBX 4 KDF) */
typedef struct { uint8_t uuid[16]; const uint8_t *salt, *key, *ad; size_t saltlen, keylen, adlen; uint64_t rounds, iter, mem; uint32_t par, ver; int have_uuid; } Kdf;
static int read_kdf(const uint8_t *v, size_t n, Kdf *k) {
memset(k, 0, sizeof *k);
- if (n < 2 || v[1] != 1) return -1; /* versión 1.x */
+ if (n < 2 || v[1] != 1) return -1; /* version 1.x */
size_t p = 2;
for (;;) {
if (p >= n) return -1;
@@ -244,12 +244,12 @@ static int read_kdf(const uint8_t *v, size_t n, Kdf *k) {
}
}
-/* ---- AES-KDF rápido ----
- * KeePassXC crea con keepassxc-cli bases KDBX 3.1 con AES-KDF calibrado a 1 s con AES-NI: unos
- * 30 millones de rondas (60 millones de bloques). El AES por bytes de vcrypto.c tarda un minuto en
- * eso, así que acá va un camino propio solo para cifrar: AES-NI en x86-64 si la CPU lo tiene
- * (se pregunta al ejecutar) y si no, tablas T (como el AES «rápido» clásico, ~10 veces el de bytes).
- * Las claves de ronda salen de aes_init (vcrypto.c). */
+/* ---- fast AES-KDF ----
+ * keepassxc-cli creates KDBX 3.1 databases with AES-KDF calibrated to 1 s with AES-NI: about
+ * 30 million rounds (60 million blocks). The bytewise AES in vcrypto.c takes a minute on
+ * that, so here is a dedicated path for encryption only: AES-NI on x86-64 if the CPU has it
+ * (checked at run time) and otherwise T-tables (like the classic "fast" AES, ~10 times the bytewise one).
+ * The round keys come from aes_init (vcrypto.c). */
static uint32_t T0[256], T1[256], T2[256], T3[256];
static uint8_t SBX[256];
static int tables_ready;
@@ -258,7 +258,7 @@ static uint8_t gf_mul2(uint8_t x) { return (uint8_t)((x << 1) ^ ((x >> 7) * 0x1b
static void make_tables(void) {
if (tables_ready) return;
- /* S-box de AES: inverso en GF(2^8) (con logaritmos de base 3) + transformación afín */
+ /* AES S-box: inverse in GF(2^8) (with base-3 logarithms) + affine transform */
uint8_t lg[256] = { 0 }, ex[256];
uint8_t x = 1;
for (int i = 0; i < 255; i++) { ex[i] = x; lg[x] = (uint8_t)i; x = (uint8_t)(x ^ gf_mul2(x)); }
@@ -315,7 +315,7 @@ static void aesni_kdf(const uint8_t rkb[15][16], uint8_t k[32], uint64_t rounds)
}
#endif
-int kdbx_aes_kdf_mode = 0; /* 0 automático, 1 forzar tablas (pruebas) */
+int kdbx_aes_kdf_mode = 0; /* 0 automatic, 1 force tables (tests) */
static int aes_kdf(const uint8_t comp[32], const uint8_t seed[32], uint64_t rounds, uint8_t out[32]) {
Aes a;
@@ -340,7 +340,7 @@ static int aes_kdf(const uint8_t comp[32], const uint8_t seed[32], uint64_t roun
return 0;
}
-/* referencia (vcrypto.c) para comparar en las pruebas */
+/* reference (vcrypto.c) to compare in tests */
int kdbx_aes_kdf_ref(const uint8_t comp[32], const uint8_t seed[32], uint64_t rounds, uint8_t out[32]) {
Aes a;
if (aes_init(&a, seed, 256)) return -1;
@@ -368,7 +368,7 @@ static int transform(const Hdr *h, const uint8_t comp[32], uint8_t out[32], ImpL
}
int alg = !memcmp(k.uuid, U_ARGON2D, 16) ? CRYPTO_ARGON2_D : !memcmp(k.uuid, U_ARGON2ID, 16) ? CRYPTO_ARGON2_ID : -1;
if (alg < 0) return fail(l, "unsupported-kdf");
- if (k.ver != 0x13) return fail(l, "unsupported-kdf"); /* Monocypher: solo Argon2 1.3 */
+ if (k.ver != 0x13) return fail(l, "unsupported-kdf"); /* Monocypher: only Argon2 1.3 */
if (!k.salt || k.saltlen < 8 || k.saltlen > 0xffffffffu || k.par < 1 || k.par > 0xffffff || k.iter < 1 || k.iter > 0xffffffffu)
return fail(l, "corrupt");
uint64_t kib = k.mem / 1024;
@@ -401,7 +401,7 @@ static int composite(const char *password, const uint8_t *kf, size_t kflen, uint
return 0;
}
-/* ---- descifrado del cuerpo ---- */
+/* ---- body decryption ---- */
static uint8_t *decrypt(const Hdr *h, const uint8_t key[32], const uint8_t *ct, size_t n, size_t *outlen, int *badpad) {
*badpad = 0;
@@ -424,7 +424,7 @@ static uint8_t *decrypt(const Hdr *h, const uint8_t key[32], const uint8_t *ct,
return out;
}
-/* ---- XML de KeePass ---- */
+/* ---- KeePass XML ---- */
typedef struct { const uint8_t *data; size_t len; uint8_t *own; } Bin;
typedef struct {
@@ -545,7 +545,7 @@ static int walk_entry(Walk *w, const XNode *en, const char *group) {
sm_free(own);
}
}
- /* TOTP en formatos viejos de KeePassXC y en el de KeePass 2.47+ → URI otpauth */
+ /* TOTP in old KeePassXC formats and in KeePass 2.47+ → otpauth URI */
if (!e->otp && (totp_seed || to_secret)) {
VjB b;
vb_init(&b);
@@ -594,12 +594,12 @@ static int walk_group(Walk *w, const XNode *g, const char *path, int depth) {
sm_free(np);
if (r) return -1;
}
- /* History, Times, Name…: no son entradas */
+ /* History, Times, Name…: not entries */
}
return 0;
}
-/* Descifra en orden de documento todos los valores Protected="True". */
+/* Decrypts, in document order, all Protected="True" values. */
static int unprotect(XNode *n, Stream *s) {
if (is_true(xml_attr(n, "Protected"))) {
size_t m = 0;
@@ -611,7 +611,7 @@ static int unprotect(XNode *n, Stream *s) {
memcpy(t, b, m);
t[m] = 0;
sm_free(b);
- xml_set_text(n, t, strlen(t)); /* hasta un NUL interno: como texto */
+ xml_set_text(n, t, strlen(t)); /* up to an embedded NUL: as text */
}
for (int i = 0; i < n->nkids; i++) if (unprotect(n->kids[i], s)) return -1;
return 0;
@@ -631,7 +631,7 @@ static int parse_xml(const uint8_t *xml, size_t xlen, Stream *s, Bin *bins, int
if (meta) {
const char *rb = xml_text(xml_child(meta, "RecycleBinUUID"));
if (strcmp(rb, "AAAAAAAAAAAAAAAAAAAAAA==")) snprintf(w.recycle, sizeof w.recycle, "%s", rb);
- /* KDBX 3.1: hash de la cabecera adentro del XML */
+ /* KDBX 3.1: header hash inside the XML */
const char *hh = xml_text(xml_child(meta, "HeaderHash"));
if (!v4 && *hh) {
uint8_t want[32];
@@ -642,7 +642,7 @@ static int parse_xml(const uint8_t *xml, size_t xlen, Stream *s, Bin *bins, int
sm_free(b);
if (!ok) { xml_free(root); return fail(l, "corrupt"); }
}
- /* KDBX 3.1: adjuntos en Meta/Binaries (ID, Compressed) */
+ /* KDBX 3.1: attachments in Meta/Binaries (ID, Compressed) */
XNode *bs = xml_child(meta, "Binaries");
if (!v4 && bs && bs->nkids) {
int maxid = -1;
@@ -680,7 +680,7 @@ static int parse_xml(const uint8_t *xml, size_t xlen, Stream *s, Bin *bins, int
return rc;
}
-/* ---- lectura completa ---- */
+/* ---- full read ---- */
static int read_v4(const uint8_t *d, size_t len, const Hdr *h, const uint8_t comp[32], ImpList *l) {
size_t p = h->hdr_end;
@@ -740,7 +740,7 @@ static int read_v4(const uint8_t *d, size_t len, const Hdr *h, const uint8_t com
if (!plain) { fail(l, "corrupt"); goto out; }
body = plain;
}
- /* encabezado interno */
+ /* inner header */
Bin *bins = NULL;
int nbins = 0;
uint32_t sid = 0;
@@ -793,7 +793,7 @@ static int read_v3(const uint8_t *d, size_t len, const Hdr *h, const uint8_t com
pt = decrypt(h, mk, d + h->hdr_end, len - h->hdr_end, &ptn, &badpad);
if (!pt) { fail(l, badpad ? ((len - h->hdr_end) % 16 ? "truncated" : "bad-password") : "memory"); goto out; }
if (ptn < 32 || !vc_equal(pt, h->start, 32)) { fail(l, "bad-password"); goto out; }
- /* bloques con hash: índice u32, SHA-256, largo u32, datos */
+ /* hashed blocks: u32 index, SHA-256, u32 length, data */
size_t p = 32, bn = 0;
blocks = sm_alloc(ptn);
if (!blocks) { fail(l, "memory"); goto out; }
diff --git a/server/src/vault/kdbx.h b/server/src/vault/kdbx.h
index 5c17b66..d4a0b86 100644
--- a/server/src/vault/kdbx.h
+++ b/server/src/vault/kdbx.h
@@ -1,12 +1,12 @@
-/* kdbx.h — lector propio de bases de KeePass 2.x / KeePassXC (.kdbx), para importar (ver
- * vimport.h y docs/PASSWORDS.md, «Importar y exportar»).
+/* kdbx.h — own reader for KeePass 2.x / KeePassXC databases (.kdbx), for importing (see
+ * vimport.h and docs/PASSWORDS.md, "Import and export").
*
- * Versiones: KDBX 4.0/4.1 (cabecera con SHA-256 y HMAC, bloques HMAC-SHA256, encabezado interno
- * con los adjuntos) y KDBX 3.1 (bloques con SHA-256, adjuntos en Meta/Binaries). KDF: Argon2d,
- * Argon2id (versión 0x13, Monocypher) y AES-KDF; cifrados: AES-256-CBC y ChaCha20 (Twofish no:
- * "unsupported-cipher"); flujo interno de valores protegidos: ChaCha20 (4.x) y Salsa20 (3.1).
- * Clave compuesta: contraseña y/o archivo llave (XML 1.0/2.0, 32 bytes, 64 hex o SHA-256 del
- * archivo). Errores en ImpList.err, como imp_parse. */
+ * Versions: KDBX 4.0/4.1 (header with SHA-256 and HMAC, HMAC-SHA256 blocks, inner header
+ * with the attachments) and KDBX 3.1 (SHA-256 blocks, attachments in Meta/Binaries). KDF: Argon2d,
+ * Argon2id (version 0x13, Monocypher) and AES-KDF; ciphers: AES-256-CBC and ChaCha20 (not Twofish:
+ * "unsupported-cipher"); inner stream for protected values: ChaCha20 (4.x) and Salsa20 (3.1).
+ * Composite key: password and/or key file (XML 1.0/2.0, 32 bytes, 64 hex or SHA-256 of the
+ * file). Errors go in ImpList.err, as in imp_parse. */
#ifndef LORD_VAULT_KDBX_H
#define LORD_VAULT_KDBX_H
@@ -14,21 +14,21 @@
#include <stdint.h>
#include "vimport.h"
-int kdbx_is(const uint8_t *d, size_t len); /* 1 si empieza con la firma de KDBX 2.x+ */
-/* password NULL o "" con archivo llave = sin contraseña en la clave compuesta. */
+int kdbx_is(const uint8_t *d, size_t len); /* 1 if it starts with the KDBX 2.x+ signature */
+/* password NULL or "" with a key file = no password in the composite key. */
int kdbx_parse(const uint8_t *d, size_t len, const char *password, const uint8_t *keyfile, size_t kflen, ImpList *l);
-/* Clave de 32 bytes de un archivo llave de KeePass. 0 bien, -1 si es un XML de llave inválido
- * (con Hash que no coincide). */
+/* 32-byte key from a KeePass key file. 0 ok, -1 if it is an invalid key XML
+ * (with a mismatching Hash). */
int kdbx_keyfile_key(const uint8_t *kf, size_t n, uint8_t out[32]);
-/* Topes contra archivos que piden un KDF desmedido (se rechazan con "too-big").
- * Por defecto 500 millones de rondas de AES-KDF y 2 GiB de memoria para Argon2. */
+/* Limits against files requesting an excessive KDF (rejected with "too-big").
+ * Default: 500 million AES-KDF rounds and 2 GiB of memory for Argon2. */
extern uint64_t kdbx_max_aes_rounds;
extern uint64_t kdbx_max_argon_kib;
-/* AES-KDF (transformar la clave compuesta): AES-NI si la CPU lo tiene, si no tablas T.
- * kdbx_aes_kdf_mode = 1 fuerza las tablas; kdbx_aes_kdf_ref usa el AES por bytes de vcrypto.c
- * (para comparar en las pruebas). */
+/* AES-KDF (transforming the composite key): AES-NI if the CPU has it, otherwise T-tables.
+ * kdbx_aes_kdf_mode = 1 forces the tables; kdbx_aes_kdf_ref uses the bytewise AES from vcrypto.c
+ * (to compare in tests). */
extern int kdbx_aes_kdf_mode;
int kdbx_aes_kdf(const uint8_t comp[32], const uint8_t seed[32], uint64_t rounds, uint8_t out[32]);
int kdbx_aes_kdf_ref(const uint8_t comp[32], const uint8_t seed[32], uint64_t rounds, uint8_t out[32]);
diff --git a/server/src/vault/p256.c b/server/src/vault/p256.c
index 124e83f..7631a55 100644
--- a/server/src/vault/p256.c
+++ b/server/src/vault/p256.c
@@ -1,10 +1,10 @@
-/* p256.c — NIST P-256 propia (ver p256.h). */
+/* p256.c — our own NIST P-256 (see p256.h). */
#include "p256.h"
#include "vcrypto.h"
#include <string.h>
-typedef struct { uint32_t v[8]; } Fe; /* palabras little-endian */
+typedef struct { uint32_t v[8]; } Fe; /* little-endian words */
typedef struct { uint32_t m[8]; uint32_t minv; Fe r2, one; } Mod;
@@ -21,10 +21,10 @@ static const uint8_t GY[32] = {
0x2b,0xce,0x33,0x57,0x6b,0x31,0x5e,0xce,0xcb,0xb6,0x40,0x68,0x37,0xbf,0x51,0xf5 };
static Mod MP;
-static Fe B_M; /* b en forma de Montgomery */
+static Fe B_M; /* b in Montgomery form */
static int ready;
-/* ---- enteros de 256 bits ---- */
+/* ---- 256-bit integers ---- */
static void from_bytes(Fe *r, const uint8_t b[32]) {
for (int i = 0; i < 8; i++)
@@ -37,7 +37,7 @@ static void to_bytes(uint8_t b[32], const Fe *a) {
}
}
-/* r = a - b; devuelve el préstamo (0 o 1) */
+/* r = a - b; returns the borrow (0 or 1) */
static uint32_t sub_raw(uint32_t r[8], const uint32_t a[8], const uint32_t b[8]) {
uint64_t borrow = 0;
for (int i = 0; i < 8; i++) {
@@ -52,7 +52,7 @@ static uint32_t add_raw(uint32_t r[8], const uint32_t a[8], const uint32_t b[8])
for (int i = 0; i < 8; i++) { c += (uint64_t)a[i] + b[i]; r[i] = (uint32_t)c; c >>= 32; }
return (uint32_t)c;
}
-/* r = sel ? a : b, sin ramas */
+/* r = sel ? a : b, branch-free */
static void cmov(uint32_t r[8], const uint32_t a[8], const uint32_t b[8], uint32_t sel) {
uint32_t m = (uint32_t)0 - (sel & 1);
for (int i = 0; i < 8; i++) r[i] = (a[i] & m) | (b[i] & ~m);
@@ -71,7 +71,7 @@ static void mod_sub(Fe *r, const Fe *a, const Fe *b, const Mod *M) {
cmov(r->v, t, s, br);
}
-/* Multiplicación de Montgomery (CIOS): r = a*b*R^-1 mod m */
+/* Montgomery multiplication (CIOS): r = a*b*R^-1 mod m */
static void mont_mul(Fe *r, const Fe *a, const Fe *b, const Mod *M) {
uint32_t t[10] = { 0 };
for (int i = 0; i < 8; i++) {
@@ -125,7 +125,7 @@ static void fmul(Fe *r, const Fe *a, const Fe *b) { mont_mul(r, a, b, &MP); }
static void fadd(Fe *r, const Fe *a, const Fe *b) { mod_add(r, a, b, &MP); }
static void fsub(Fe *r, const Fe *a, const Fe *b) { mod_sub(r, a, b, &MP); }
-/* a^(p-2) (el exponente es público) */
+/* a^(p-2) (the exponent is public) */
static void finv(Fe *r, const Fe *a) {
uint32_t e[8];
uint32_t two[8] = { 2 };
@@ -141,7 +141,7 @@ static void finv(Fe *r, const Fe *a) {
static int fe_is_zero(const Fe *a) { uint32_t z = 0; for (int i = 0; i < 8; i++) z |= a->v[i]; return z == 0; }
static int lt(const uint32_t a[8], const uint32_t m[8]) { uint32_t t[8]; return (int)sub_raw(t, a, m); }
-/* ---- puntos proyectivos (X:Y:Z), Montgomery ---- */
+/* ---- projective points (X:Y:Z), Montgomery ---- */
typedef struct { Fe x, y, z; } Pt;
@@ -199,11 +199,11 @@ static void pt_cswap(Pt *a, Pt *b, uint32_t bit) {
for (size_t i = 0; i < sizeof(Pt) / 4; i++) { uint32_t t = (pa[i] ^ pb[i]) & m; pa[i] ^= t; pb[i] ^= t; }
}
-/* r = k * p (k big-endian, 256 bits), escalera de Montgomery */
+/* r = k * p (k big-endian, 256 bits), Montgomery ladder */
static void pt_mul(Pt *r, const uint8_t k[32], const Pt *p) {
Pt r0, r1 = *p;
memset(&r0, 0, sizeof r0);
- r0.y = MP.one; /* infinito (0:1:0) */
+ r0.y = MP.one; /* infinity (0:1:0) */
for (int i = 255; i >= 0; i--) {
uint32_t bit = (k[31 - i / 8] >> (i % 8)) & 1;
pt_cswap(&r0, &r1, bit);
@@ -229,7 +229,7 @@ static int pt_affine(const Pt *p, uint8_t x[32], uint8_t y[32]) {
return 0;
}
-/* (x, y) en afín (bytes) → punto validado */
+/* (x, y) in affine form (bytes) → validated point */
static int pt_load(Pt *r, const uint8_t xb[32], const uint8_t yb[32]) {
Fe x, y;
from_bytes(&x, xb);
diff --git a/server/src/vault/p256.h b/server/src/vault/p256.h
index d980a5e..ece2f45 100644
--- a/server/src/vault/p256.h
+++ b/server/src/vault/p256.h
@@ -1,26 +1,26 @@
-/* p256.h — curva NIST P-256 propia, solo lo que pide CTAP2: el acuerdo de claves ECDH del
- * protocolo de PIN 1 y de la extensión hmac-secret (COSE alg -25, ECDH-ES+HKDF-256).
+/* p256.h — our own NIST P-256 curve, only what CTAP2 needs: the ECDH key agreement of
+ * PIN protocol 1 and of the hmac-secret extension (COSE alg -25, ECDH-ES+HKDF-256).
*
- * Aritmética de Montgomery con palabras de 32 bits (para p y n), coordenadas proyectivas con las
- * fórmulas COMPLETAS de Renes–Costello–Batina (2016, alg. 4, a = -3: sin casos especiales para
- * el infinito ni para P = Q) y escalera de Montgomery con intercambio condicional sin ramas.
- * No hay ECDSA: nuestro cliente nunca verifica firmas (la clave que sale de hmac-secret se
- * comprueba sola al descifrar la bóveda). Escalares y coordenadas en big-endian de 32 bytes. */
+ * Montgomery arithmetic with 32-bit words (for p and n), projective coordinates with the
+ * COMPLETE formulas of Renes–Costello–Batina (2016, alg. 4, a = -3: no special cases for
+ * infinity or P = Q) and a Montgomery ladder with branch-free conditional swap.
+ * There is no ECDSA: our client never verifies signatures (the key coming out of hmac-secret
+ * checks itself when decrypting the vault). Scalars and coordinates are 32-byte big-endian. */
#ifndef LORD_VAULT_P256_H
#define LORD_VAULT_P256_H
#include <stdint.h>
-/* Par de claves al azar (getrandom). 0 bien. */
+/* Random key pair (getrandom). 0 = ok. */
int p256_keypair(uint8_t priv[32], uint8_t x[32], uint8_t y[32]);
-/* Clave pública de priv (1 <= priv < n). 0 bien, -1 si priv no es válida. */
+/* Public key of priv (1 <= priv < n). 0 = ok, -1 if priv is invalid. */
int p256_public(const uint8_t priv[32], uint8_t x[32], uint8_t y[32]);
-/* x de priv * (px, py). -1 si el punto no está en la curva o el resultado es el infinito. */
+/* x of priv * (px, py). -1 if the point is not on the curve or the result is infinity. */
int p256_ecdh(const uint8_t priv[32], const uint8_t px[32], const uint8_t py[32], uint8_t shared_x[32]);
-/* 1 si (x, y) es un punto de la curva (con x, y < p). */
+/* 1 if (x, y) is a point on the curve (with x, y < p). */
int p256_on_curve(const uint8_t x[32], const uint8_t y[32]);
-/* Para las pruebas: k * G en afín; -1 si da el infinito (k = 0 o múltiplo de n). k puede ser
- * cualquier número de 256 bits (no se exige k < n). */
+/* For tests: k * G in affine form; -1 if it yields infinity (k = 0 or a multiple of n). k may be
+ * any 256-bit number (k < n is not required). */
int p256_mul_base(const uint8_t k[32], uint8_t x[32], uint8_t y[32]);
#endif
diff --git a/server/src/vault/qr.c b/server/src/vault/qr.c
index 4258188..e6963da 100644
--- a/server/src/vault/qr.c
+++ b/server/src/vault/qr.c
@@ -1,22 +1,22 @@
-/* qr.c — códigos QR propios: generar y leer (ver qr.h). ISO/IEC 18004.
+/* qr.c — our own QR codes: encode and decode (see qr.h). ISO/IEC 18004.
*
- * Generar: elige el modo más compacto (numérico, alfanumérico o byte) y la versión más chica en
- * la que entra con la corrección pedida; Reed-Solomon sobre GF(256) (polinomio 0x11d), bloques
- * intercalados, patrones de función, información de formato y de versión (BCH) y las 8 máscaras
- * con la penalización de la norma.
+ * Encode: picks the most compact mode (numeric, alphanumeric or byte) and the smallest version
+ * that fits with the requested correction level; Reed-Solomon over GF(256) (polynomial 0x11d),
+ * interleaved blocks, function patterns, format and version information (BCH) and the 8 masks
+ * with the standard's penalty.
*
- * Leer: luminancia → binarización (Otsu global y umbral local de Bradley, normal e invertida) →
- * patrones de posición por la proporción 1:1:3:1:1 en filas, confirmados en columnas → los tres
- * mejores (triángulo rectángulo) → lado por el patrón de temporización y la información de
- * versión → grilla (afín, o perspectiva con el patrón de alineación) → formato, máscara,
- * palabras, Reed-Solomon (Berlekamp-Massey + Chien + Forney) → segmentos. */
+ * Decode: luminance → binarization (global Otsu and Bradley local threshold, normal and inverted) →
+ * finder patterns by the 1:1:3:1:1 ratio in rows, confirmed in columns → the three
+ * best (right triangle) → side from the timing pattern and the version
+ * information → grid (affine, or perspective with the alignment pattern) → format, mask,
+ * codewords, Reed-Solomon (Berlekamp-Massey + Chien + Forney) → segments. */
#include "qr.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
-/* ================= tablas ================= */
+/* ================= tables ================= */
static const int8_t ECC_PER_BLOCK[4][41] = {
{ -1, 7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30 },
@@ -30,7 +30,7 @@ static const int8_t NUM_BLOCKS[4][41] = {
{ -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68 },
{ -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81 },
};
-static const int FORMAT_ECC_BITS[4] = { 1, 0, 3, 2 }; /* L M Q H en la información de formato */
+static const int FORMAT_ECC_BITS[4] = { 1, 0, 3, 2 }; /* L M Q H in the format information */
static const char ALNUM[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
static int raw_modules(int ver) {
@@ -59,7 +59,7 @@ static int cc_bits(int mode, int ver) {
return t[mode == 1 ? 0 : mode == 2 ? 1 : 2][g];
}
-/* ================= GF(256) y Reed-Solomon ================= */
+/* ================= GF(256) and Reed-Solomon ================= */
static uint8_t GEXP[512], GLOG[256];
static int gf_ready;
@@ -73,7 +73,7 @@ static void gf_init(void) {
static uint8_t gmul(uint8_t a, uint8_t b) { return a && b ? GEXP[GLOG[a] + GLOG[b]] : 0; }
static uint8_t gdiv(uint8_t a, uint8_t b) { return a ? GEXP[(GLOG[a] + 255 - GLOG[b]) % 255] : 0; }
-/* Generador de grado d: (x - a^0)(x - a^1)…; coeficientes sin el principal (1). */
+/* Generator of degree d: (x - a^0)(x - a^1)…; coefficients without the leading one (1). */
static void rs_gen(int d, uint8_t *g) {
memset(g, 0, (size_t)d);
g[d - 1] = 1;
@@ -93,7 +93,7 @@ static void rs_rem(const uint8_t *data, int n, const uint8_t *g, int d, uint8_t
}
}
-/* Corrige el bloque c de n bytes con ne de corrección. 0 bien (o sin errores), -1 si no se puede. */
+/* Corrects block c of n bytes with ne correction bytes. 0 = ok (or no errors), -1 if it cannot. */
static int rs_correct(uint8_t *c, int n, int ne) {
uint8_t S[64], L[64], B[64], T[64], O[64];
int any = 0;
@@ -122,14 +122,14 @@ static int rs_correct(uint8_t *c, int n, int ne) {
if (Ld > ne / 2) return -1;
/* Omega = S * Lambda mod x^ne */
for (int i = 0; i < ne; i++) { uint8_t v = 0; for (int j = 0; j <= i && j <= Ld; j++) v ^= gmul(L[j], S[i - j]); O[i] = v; }
- /* Chien: posiciones p = 0..n-1 (potencia), arreglo k = n-1-p */
+ /* Chien: positions p = 0..n-1 (power), array index k = n-1-p */
int found = 0;
for (int p = 0; p < n; p++) {
uint8_t xinv = GEXP[(255 - p) % 255];
uint8_t v = 0, xp = 1;
for (int i = 0; i <= Ld; i++) { v ^= gmul(L[i], xp); xp = gmul(xp, xinv); }
if (v) continue;
- /* Forney (primera raíz 0): e = X * Omega(X^-1) / Lambda'(X^-1) */
+ /* Forney (first root 0): e = X * Omega(X^-1) / Lambda'(X^-1) */
uint8_t om = 0, dl = 0; xp = 1;
for (int i = 0; i < ne; i++) { om ^= gmul(O[i], xp); xp = gmul(xp, xinv); }
xp = 1;
@@ -148,7 +148,7 @@ static int rs_correct(uint8_t *c, int n, int ne) {
return 0;
}
-/* ================= armado de la matriz ================= */
+/* ================= building the matrix ================= */
typedef struct { int size; uint8_t *m, *fn; } Grid;
#define AT(g, x, y) (g)->m[(y) * (g)->size + (x)]
@@ -205,7 +205,7 @@ static void draw_functions(Grid *g, int ver) {
if ((i == 0 && j == 0) || (i == 0 && j == na - 1) || (i == na - 1 && j == 0)) continue;
draw_align(g, pos[i], pos[j]);
}
- draw_format(g, 0); /* reserva; se escribe después */
+ draw_format(g, 0); /* reserve; written later */
if (ver >= 7) {
int bits = version_bits(ver);
for (int i = 0; i < 18; i++) {
@@ -233,7 +233,7 @@ static void apply_mask(Grid *g, int mask) {
if (!FN(g, x, y) && mask_bit(mask, x, y)) AT(g, x, y) ^= 1;
}
-/* Recorrido en zigzag de los módulos de datos: llama fn para cada uno, en orden. */
+/* Zigzag traversal of the data modules: calls fn for each one, in order. */
typedef void (*ZigFn)(Grid *g, int x, int y, void *ud);
static void zigzag(Grid *g, ZigFn fn, void *ud) {
int s = g->size;
@@ -257,14 +257,14 @@ static void zig_get(Grid *g, int x, int y, void *ud) {
z->i++;
}
-/* Penalización de la norma (N1=3, N2=3, N3=40, N4=10). */
+/* Penalty from the standard (N1=3, N2=3, N3=40, N4=10). */
static long run_finder_count(const int *h) {
int n = h[1];
int core = n > 0 && h[2] == n && h[3] == n * 3 && h[4] == n && h[5] == n;
return (core && h[0] >= n * 4 && h[6] >= n) + (core && h[6] >= n * 4 && h[0] >= n);
}
static void run_push(int *h, int len, int s) {
- if (h[0] == 0) len += s; /* zona en blanco a la izquierda */
+ if (h[0] == 0) len += s; /* blank area on the left */
memmove(h + 1, h, 6 * sizeof(int));
h[0] = len;
}
@@ -284,7 +284,7 @@ static long penalty(Grid *g) {
run = 1;
}
}
- /* final de la línea */
+ /* end of the line */
if (color) { run_push(h, run, s); run = 0; }
run += s;
run_push(h, run, s);
@@ -303,7 +303,7 @@ static long penalty(Grid *g) {
return r;
}
-/* Bits de los datos: modo + largo + contenido. Devuelve el largo en bits (o -1 si no entra). */
+/* Data bits: mode + length + content. Returns the length in bits (or -1 if it does not fit). */
typedef struct { uint8_t *b; int n, cap; } Bits;
static void bput(Bits *bb, unsigned v, int nb) {
for (int i = nb - 1; i >= 0; i--) {
@@ -361,7 +361,7 @@ int qr_encode_ex(const uint8_t *data, size_t len, int ecc, int mask, int minver,
bput(&bb, 0, (8 - bb.n % 8) % 8);
for (int pad = 0xec; bb.n < cap; pad ^= 0xec ^ 0x11) bput(&bb, (unsigned)pad, 8);
- /* bloques y corrección, intercalados */
+ /* blocks and correction, interleaved */
int nb = NUM_BLOCKS[ecc][ver], ne = ECC_PER_BLOCK[ecc][ver];
int raw = raw_modules(ver) / 8, nshort = nb - raw % nb, shortlen = raw / nb;
uint8_t gen[30], blocks[81][160];
@@ -412,11 +412,11 @@ int qr_encode(const uint8_t *data, size_t len, int ecc, uint8_t *modules, int *s
return qr_encode_ex(data, len, ecc, -1, 1, modules, size, NULL);
}
-/* ================= lectura: de la grilla a los bytes ================= */
+/* ================= decoding: from the grid to the bytes ================= */
static int popc(unsigned v) { int n = 0; while (v) { n += v & 1; v >>= 1; } return n; }
-/* formato: (ecc, máscara) con la distancia de Hamming más chica (≤ 3) */
+/* format: (ecc, mask) with the smallest Hamming distance (≤ 3) */
static int decode_format(int bits, int *ecc, int *mask) {
int best = 99;
for (int e = 0; e < 4; e++) for (int m = 0; m < 8; m++) {
@@ -431,7 +431,7 @@ static int decode_version(int bits) {
return best <= 3 ? v : -1;
}
-/* Lee la información de formato de las dos copias de la grilla g (ya muestreada). */
+/* Reads the format information from the two copies in grid g (already sampled). */
static int read_format(Grid *g, int *ecc, int *mask) {
int s = g->size, a = 0, b = 0;
for (int i = 0; i <= 5; i++) a |= AT(g, 8, i) << i;
@@ -461,7 +461,7 @@ static int brd(BR *r, int k) {
return v;
}
-/* Segmentos → bytes. */
+/* Segments → bytes. */
static int parse_segments(const uint8_t *d, int nbytes, int ver, uint8_t *out, size_t cap) {
BR r = { d, nbytes * 8, 0 };
size_t o = 0;
@@ -470,7 +470,7 @@ static int parse_segments(const uint8_t *d, int nbytes, int ver, uint8_t *out, s
if (r.n - r.p < 4) break;
int mode = brd(&r, 4);
if (mode == 0) break;
- if (mode == 7) { /* ECI: se saltea */
+ if (mode == 7) { /* ECI: skipped */
int f = brd(&r, 8);
if (f < 0) return -1;
if ((f & 0xc0) == 0x80) brd(&r, 8);
@@ -478,8 +478,8 @@ static int parse_segments(const uint8_t *d, int nbytes, int ver, uint8_t *out, s
else if (f & 0x80) return -1;
continue;
}
- if (mode == 3) { brd(&r, 16); continue; } /* anexo estructurado */
- if (mode == 5) continue; /* FNC1 primera posición */
+ if (mode == 3) { brd(&r, 16); continue; } /* structured append */
+ if (mode == 5) continue; /* FNC1 first position */
if (mode == 9) { brd(&r, 8); continue; }
int g = ver <= 9 ? 0 : ver <= 26 ? 1 : 2;
if (mode == 1) {
@@ -516,7 +516,7 @@ static int parse_segments(const uint8_t *d, int nbytes, int ver, uint8_t *out, s
return (int)o;
}
-/* Grilla muestreada (módulos de la versión ver) → bytes. */
+/* Sampled grid (modules of version ver) → bytes. */
static int decode_grid(uint8_t *mods, int ver, uint8_t *out, size_t cap) {
gf_init();
int s = ver * 4 + 17;
@@ -527,7 +527,7 @@ static int decode_grid(uint8_t *mods, int ver, uint8_t *out, size_t cap) {
if (!fn || !save) { free(fn); free(save); return -1; }
memcpy(save, mods, (size_t)s * s);
g.fn = fn;
- draw_functions(&g, ver); /* solo para marcar fn; se restauran los módulos */
+ draw_functions(&g, ver); /* only to mark fn; the modules are restored */
memcpy(mods, save, (size_t)s * s);
free(save);
apply_mask(&g, mask);
@@ -555,7 +555,7 @@ static int decode_grid(uint8_t *mods, int ver, uint8_t *out, size_t cap) {
return parse_segments(data, nd, ver, out, cap);
}
-/* ================= lectura: de la imagen a la grilla ================= */
+/* ================= decoding: from the image to the grid ================= */
typedef struct { double x, y, ms; int count; } Cand;
typedef struct { const uint8_t *bin; int w, h; Cand c[64]; int nc; } Img;
@@ -570,13 +570,13 @@ static int ratio_ok(const int *st) {
return fabs(m - st[0]) < v && fabs(m - st[1]) < v && fabs(3 * m - st[2]) < 3 * v && fabs(m - st[3]) < v && fabs(m - st[4]) < v;
}
-/* Cuenta las corridas en una dirección desde (x, y), que tiene que ser oscuro. */
+/* Counts the runs in one direction from (x, y), which must be dark. */
static int cross(Img *im, double fx, double fy, int dx, int dy, int maxc, double *center, double *ms) {
int x0 = (int)fx, y0 = (int)fy;
if (x0 < 0 || y0 < 0 || x0 >= im->w || y0 >= im->h || !PX(im, x0, y0)) return 0;
int st[5] = { 0 };
int x = x0, y = y0;
- /* hacia atrás: centro (oscuro), blanco, oscuro */
+ /* backwards: center (dark), white, dark */
while (x >= 0 && y >= 0 && x < im->w && y < im->h && PX(im, x, y)) { st[2]++; x -= dx; y -= dy; }
while (x >= 0 && y >= 0 && x < im->w && y < im->h && !PX(im, x, y) && st[1] <= maxc) { st[1]++; x -= dx; y -= dy; }
while (x >= 0 && y >= 0 && x < im->w && y < im->h && PX(im, x, y) && st[0] <= maxc) { st[0]++; x -= dx; y -= dy; }
@@ -585,7 +585,7 @@ static int cross(Img *im, double fx, double fy, int dx, int dy, int maxc, double
int ex;
while (x >= 0 && y >= 0 && x < im->w && y < im->h && !PX(im, x, y) && st[3] <= maxc) { st[3]++; x += dx; y += dy; }
while (x >= 0 && y >= 0 && x < im->w && y < im->h && PX(im, x, y) && st[4] <= maxc) { st[4]++; x += dx; y += dy; }
- ex = dx ? x : y; /* fin (exclusivo) en la coordenada que se mueve */
+ ex = dx ? x : y; /* end (exclusive) on the coordinate that moves */
if (!ratio_ok(st)) return 0;
*center = ex - st[4] - st[3] - st[2] / 2.0;
*ms = (st[0] + st[1] + st[2] + st[3] + st[4]) / 7.0;
@@ -615,7 +615,7 @@ static void found(Img *im, const int *st, int y, int xend) {
if (!cross(im, cx, cy, 1, 0, st[2], &cx2, &msh)) return;
double ms = (msv + msh) / 2;
if (msv * 7 > total * 2 || msv * 7 * 2 < total) return;
- /* diagonal (descarta rayas) */
+ /* diagonal (discards stripes) */
double dc, dms;
if (!cross(im, cx2, cy, 1, 1, st[2] * 2, &dc, &dms)) return;
add_cand(im, cx2, cy, ms);
@@ -648,7 +648,7 @@ static void find_finders(Img *im) {
static double dist(const Cand *a, const Cand *b) { return hypot(a->x - b->x, a->y - b->y); }
-/* Homografía: de (u, v) en módulos a (x, y) en la imagen, por 4 puntos (sistema 8x8). */
+/* Homography: from (u, v) in modules to (x, y) in the image, from 4 points (8x8 system). */
typedef struct { double a[9]; } Hom;
static int hom_solve(const double *u, const double *v, const double *x, const double *y, Hom *H) {
double M[8][9];
@@ -685,7 +685,7 @@ static int sample(Img *im, double x, double y) {
return PX(im, ix, iy);
}
-/* Patrón de alineación cerca de (ex, ey): un módulo oscuro rodeado de un anillo claro y uno oscuro. */
+/* Alignment pattern near (ex, ey): a dark module surrounded by a light ring and a dark one. */
static int find_align(Img *im, double ex, double ey, double ms, double *ax, double *ay) {
int r = (int)(ms * 4 + 2), best = 0;
double bd = 1e18;
@@ -693,7 +693,7 @@ static int find_align(Img *im, double ex, double ey, double ms, double *ax, doub
if (y < 0 || y >= im->h) continue;
for (int x = (int)ex - r; x <= (int)ex + r; x++) {
if (x < 0 || x >= im->w || !PX(im, x, y)) continue;
- /* corridas horizontales y verticales: oscuro (~1), claro (~1) a cada lado, oscuro afuera */
+ /* horizontal and vertical runs: dark (~1), light (~1) on each side, dark outside */
int ok = 1;
double c[2];
for (int d = 0; d < 2 && ok; d++) {
@@ -718,7 +718,7 @@ static int find_align(Img *im, double ex, double ey, double ms, double *ax, doub
return best;
}
-/* Cuenta las corridas del patrón de temporización entre p0 y p1 (en píxeles). */
+/* Counts the runs of the timing pattern between p0 and p1 (in pixels). */
static int timing_runs(Img *im, double x0, double y0, double x1, double y1, double ms) {
double len = hypot(x1 - x0, y1 - y0);
int steps = (int)(len / (ms / 4)) + 1, runs = 0, prev = -1;
@@ -735,7 +735,7 @@ static int try_grid(Img *im, const Cand *B, const Cand *A, const Cand *C, int ve
double ms = (A->ms + B->ms + C->ms) / 3;
double u[4] = { 3.5, s - 3.5, 3.5, 0 }, v[4] = { 3.5, 3.5, s - 3.5, 0 };
double x[4] = { B->x, A->x, C->x, 0 }, y[4] = { B->y, A->y, C->y, 0 };
- /* cuarto punto: esquina afín (o el patrón de alineación) */
+ /* fourth point: affine corner (or the alignment pattern) */
double k = (s - 6.5 - 3.5) / (s - 7.0);
u[3] = s - 6.5; v[3] = s - 6.5;
x[3] = B->x + (A->x - B->x) * k + (C->x - B->x) * k;
@@ -758,7 +758,7 @@ static int try_grid(Img *im, const Cand *B, const Cand *A, const Cand *C, int ve
if (ver >= 7) {
Grid g = { s, mods, NULL };
int vv = read_version_bits(&g);
- if (vv > 0 && vv != ver) { free(mods); return -2 - vv; } /* versión distinta: probar esa */
+ if (vv > 0 && vv != ver) { free(mods); return -2 - vv; } /* different version: try that one */
}
n = decode_grid(mods, ver, out, cap);
free(mods);
@@ -769,7 +769,7 @@ static int try_triplet(Img *im, Cand B, Cand A, Cand C, uint8_t *out, size_t cap
double ms = (A.ms + B.ms + C.ms) / 3;
double dab = dist(&B, &A), dbc = dist(&B, &C);
int est = (int)lround((dab + dbc) / 2 / ms) + 7;
- /* patrón de temporización: fila 6 (de B a A) y columna 6 (de B a C) */
+ /* timing pattern: row 6 (from B to A) and column 6 (from B to C) */
double ux = (C.x - B.x) / dbc, uy = (C.y - B.y) / dbc, vx = (A.x - B.x) / dab, vy = (A.y - B.y) / dab;
int t1 = timing_runs(im, B.x + ux * 3 * ms, B.y + uy * 3 * ms, A.x + ux * 3 * ms, A.y + uy * 3 * ms, ms) + 12;
int t2 = timing_runs(im, B.x + vx * 3 * ms, B.y + vy * 3 * ms, C.x + vx * 3 * ms, C.y + vy * 3 * ms, ms) + 12;
@@ -788,7 +788,7 @@ static int try_triplet(Img *im, Cand B, Cand A, Cand C, uint8_t *out, size_t cap
int n = try_grid(im, &B, &A, &C, ver, 1, out, cap);
if (n == -1 && ver >= 2) n = try_grid(im, &B, &A, &C, ver, 0, out, cap);
if (n >= 0) return n;
- if (n <= -9) { ver = -2 - n; continue; } /* la información de versión dijo otra */
+ if (n <= -9) { ver = -2 - n; continue; } /* the version information said otherwise */
break;
}
}
@@ -798,7 +798,7 @@ static int try_triplet(Img *im, Cand B, Cand A, Cand C, uint8_t *out, size_t cap
static int decode_bin(Img *im, uint8_t *out, size_t cap) {
find_finders(im);
if (im->nc < 3) return -1;
- /* los más confirmados primero */
+ /* most confirmed first */
for (int i = 0; i < im->nc; i++) for (int j = i + 1; j < im->nc; j++)
if (im->c[j].count > im->c[i].count) { Cand t = im->c[i]; im->c[i] = im->c[j]; im->c[j] = t; }
int n = im->nc < 12 ? im->nc : 12;
@@ -827,7 +827,7 @@ enough:
for (int i = 0; i < nt; i++) for (int j = i + 1; j < nt; j++) if (tri[j].score < tri[i].score) { Tri t = tri[i]; tri[i] = tri[j]; tri[j] = t; }
for (int t = 0; t < nt && t < 6; t++) {
Cand B = im->c[tri[t].a], A = im->c[tri[t].b], C = im->c[tri[t].c];
- /* orientación: con y hacia abajo, (A-B) x (C-B) > 0 */
+ /* orientation: with y pointing down, (A-B) x (C-B) > 0 */
double cr = (A.x - B.x) * (C.y - B.y) - (A.y - B.y) * (C.x - B.x);
if (cr < 0) { Cand x = A; A = C; C = x; }
int r = try_triplet(im, B, A, C, out, cap);
@@ -847,7 +847,7 @@ int qr_decode(const uint32_t *argb, int w, int h, uint8_t *out, size_t outcap) {
uint32_t p = argb[i];
unsigned a = p >> 24, r = p >> 16 & 255, g = p >> 8 & 255, b = p & 255;
unsigned l = (r * 77 + g * 150 + b * 29) >> 8;
- l = (l * a + 255 * (255 - a)) / 255; /* sobre fondo blanco */
+ l = (l * a + 255 * (255 - a)) / 255; /* over a white background */
lum[i] = (uint8_t)l;
hist[l]++;
}
@@ -864,7 +864,7 @@ int qr_decode(const uint32_t *argb, int w, int h, uint8_t *out, size_t outcap) {
double mb = sumb / wb, mf = (sum - sumb) / wf, v = wb * wf * (mb - mf) * (mb - mf);
if (v > best) { best = v; th = i; }
}
- /* imagen integral para el umbral local */
+ /* integral image for the local threshold */
for (int x = 0; x <= w; x++) integ[x] = 0;
for (int y = 0; y < h; y++) {
uint32_t row = 0;
diff --git a/server/src/vault/qr.h b/server/src/vault/qr.h
index 7f265ac..65be568 100644
--- a/server/src/vault/qr.h
+++ b/server/src/vault/qr.h
@@ -1,11 +1,11 @@
-/* qr.h — códigos QR propios: generar (el QR de una red Wi-Fi para unirse desde el teléfono, la
- * clave de recuperación) y leer (agregar un código 2FA desde la imagen de un QR otpauth://).
+/* qr.h — our own QR codes: encode (the QR of a Wi-Fi network to join from a phone, the recovery
+ * key) and decode (add a 2FA code from the image of an otpauth:// QR).
*
- * Generar: modos byte/alfanumérico/numérico, versiones 1–40, corrección L/M/Q/H, las 8 máscaras
- * con la penalización de ISO/IEC 18004. Leer: imágenes limpias (capturas de pantalla, PNG/JPEG
- * exportados, fotos derechas y nítidas): binariza, encuentra los tres patrones de posición, arma
- * la grilla (con el patrón de alineación desde la versión 2), lee el formato, saca la máscara y
- * corrige errores con Reed-Solomon. No es un lector de cámara (sin perspectiva fuerte). */
+ * Encode: byte/alphanumeric/numeric modes, versions 1–40, L/M/Q/H error correction, all 8 masks
+ * with the ISO/IEC 18004 penalty. Decode: clean images (screenshots, exported PNG/JPEG, straight
+ * and sharp photos): binarizes, finds the three finder patterns, builds the grid (with the
+ * alignment pattern from version 2), reads the format, removes the mask and corrects errors
+ * with Reed-Solomon. It is not a camera reader (no strong perspective). */
#ifndef LORD_VAULT_QR_H
#define LORD_VAULT_QR_H
@@ -13,18 +13,18 @@
#include <stdint.h>
enum { QR_ECC_L = 0, QR_ECC_M, QR_ECC_Q, QR_ECC_H };
-#define QR_MAX_SIZE 177 /* lado de la versión 40 */
+#define QR_MAX_SIZE 177 /* side length of version 40 */
-/* Genera el QR de len bytes con la corrección pedida (sube de versión hasta que entre).
- * modules: QR_MAX_SIZE*QR_MAX_SIZE bytes (1 = oscuro), fila por fila con lado *size.
- * Devuelve la versión (1–40) o -1 si no entra. */
+/* Encodes len bytes as a QR with the requested correction level (raises the version until it fits).
+ * modules: QR_MAX_SIZE*QR_MAX_SIZE bytes (1 = dark), row by row with side *size.
+ * Returns the version (1–40) or -1 if it does not fit. */
int qr_encode(const uint8_t *data, size_t len, int ecc, uint8_t *modules, int *size);
-/* Lee un QR de una imagen 0xAARRGGBB (w*h). out recibe los bytes (con un 0 al final si entra).
- * Devuelve el largo o -1 si no se encontró/no se pudo leer. */
+/* Reads a QR from a 0xAARRGGBB image (w*h). out receives the bytes (with a trailing 0 if it fits).
+ * Returns the length or -1 if none was found/it could not be read. */
int qr_decode(const uint32_t *argb, int w, int h, uint8_t *out, size_t outcap);
-/* Igual que qr_encode con máscara fija (0–7; -1 = la mejor) y versión mínima; *mask_out la usada. */
+/* Same as qr_encode with a fixed mask (0–7; -1 = the best) and a minimum version; *mask_out is the one used. */
int qr_encode_ex(const uint8_t *data, size_t len, int ecc, int mask, int minver, uint8_t *modules, int *size, int *mask_out);
#endif
diff --git a/server/src/vault/secretsvc.c b/server/src/vault/secretsvc.c
index f0ec60c..b7e3d98 100644
--- a/server/src/vault/secretsvc.c
+++ b/server/src/vault/secretsvc.c
@@ -214,7 +214,7 @@ static Prompt *prompt_new(void) {
}
static Prompt *prompt_by_id(unsigned id) { for (int i = 0; i < NPROMPT; i++) if (prompts[i].used && prompts[i].id == id) return &prompts[i]; return NULL; }
-/* ================= rutas ================= */
+/* ================= paths ================= */
enum { O_NONE, O_NODE, O_SERVICE, O_COLL, O_ITEM, O_SESS, O_PROMPT };
@@ -295,7 +295,7 @@ static void write_paths(DBuf *w, char (*ids)[40], int n) {
dw_arr_end(w, mk);
}
-/* ================= secretos ================= */
+/* ================= secrets ================= */
static void encode_secret(DBuf *w, Sess *s, const uint8_t *sec, size_t len, const char *ctype) {
char sp[64];
@@ -444,7 +444,7 @@ static void introspect(const DMsg *m, int kind) {
free(x);
}
-/* ================= propiedades ================= */
+/* ================= properties ================= */
static const char *item_type(const SsItemInfo *in) {
for (int i = 0; in && i < in->nattrs; i++) if (in->attrs[i].name && !strcmp(in->attrs[i].name, "xdg:schema")) return in->attrs[i].value;
@@ -622,7 +622,7 @@ static void open_session(const DMsg *m) {
LOG("OpenSession %s → %s (%s)\n", ALG_DH, path, m->sender ? m->sender : "?");
dbus_reply(&C, m, "vo", &b);
} else {
- LOG("OpenSession %s: no soportado\n", alg);
+ LOG("OpenSession %s: not supported\n", alg);
dbus_error(&C, m, E_NOTSUP, "algorithm not supported");
}
dw_free(&b);
@@ -658,7 +658,7 @@ static void search_items(const DMsg *m, int service) {
write_paths(&b, ids, k);
dbus_reply(&C, m, "ao", &b);
}
- LOG("SearchItems (%d atributos) → %d%s\n", n, k, lk ? " (bloqueado)" : "");
+ LOG("SearchItems (%d attributes) → %d%s\n", n, k, lk ? " (locked)" : "");
dw_free(&b);
free(ids);
}
@@ -703,7 +703,7 @@ static void unlock(const DMsg *m) {
p->nobj = n;
char pp[64];
prompt_path(p->id, pp);
- LOG("Unlock → aviso %s\n", pp);
+ LOG("Unlock → prompt %s\n", pp);
reply_objs_o(m, objs, 0, pp);
}
@@ -818,7 +818,7 @@ static void create_item(const DMsg *m) {
if (rc || !id_ok(id, strlen(id))) { dbus_error(&C, m, E_FAILED, "cannot create item"); return; }
char p[128];
item_path(id, p);
- LOG("CreateItem «%s» (%d atributos) → %s\n", label, na, p);
+ LOG("CreateItem \"%s\" (%d attributes) → %s\n", label, na, p);
reply_oo(m, p, "/");
sig_path(COLL, I_COLL, "ItemCreated", p);
}
@@ -893,7 +893,7 @@ static void prompt_complete(Prompt *p) {
dw_arr_end(&b, mk);
dbus_signal(&C, pp, I_PROMPT, "Completed", "bv", &b);
dw_free(&b);
- LOG("aviso %s: %s\n", pp, p->unlocked ? "desbloqueado" : "cancelado");
+ LOG("prompt %s: %s\n", pp, p->unlocked ? "unlocked" : "cancelled");
p->used = 0;
}
@@ -1003,7 +1003,7 @@ int ss_start(int busfd, const SsBackend *be, void *ud) {
if (res != 1 && res != 4) { LOG("org.freedesktop.secrets already has an owner (%u)\n", res); dbus_close(&C); return 1; }
created_at = (uint64_t)time(NULL);
running = 1;
- LOG("atendiendo org.freedesktop.secrets como %s\n", C.unique);
+ LOG("serving org.freedesktop.secrets as %s\n", C.unique);
return 0;
}
diff --git a/server/src/vault/secretsvc.h b/server/src/vault/secretsvc.h
index 176ec4b..927e54a 100644
--- a/server/src/vault/secretsvc.h
+++ b/server/src/vault/secretsvc.h
@@ -1,12 +1,12 @@
-/* secretsvc.h — la API freedesktop Secret Service (org.freedesktop.secrets) sobre D-Bus, con un
- * cliente D-Bus propio y mínimo (dbus.h: sin libdbus ni sd-bus). Ver docs/PASSWORDS.md,
- * «Secret Service».
+/* secretsvc.h — the freedesktop Secret Service API (org.freedesktop.secrets) over D-Bus, with its
+ * own minimal D-Bus client (dbus.h: no libdbus or sd-bus). See docs/PASSWORDS.md,
+ * "Secret Service".
*
- * Así Chromium, Firefox, libsecret/secret-tool y las demás apps Linux guardan sus contraseñas en
- * el llavero de LordOS sin gnome-keyring ni kwallet. Corre en lord-vault: lord-server conecta el
- * socket del bus de la sesión y se lo pasa ya abierto (el ayudante no puede abrir sockets).
+ * This is how Chromium, Firefox, libsecret/secret-tool and other Linux apps store their passwords in
+ * the LordOS keyring without gnome-keyring or kwallet. Runs in lord-vault: lord-server connects the
+ * session bus socket and hands it over already open (the helper cannot open sockets).
*
- * Objetos:
+ * Objects:
* /org/freedesktop/secrets Service (OpenSession, SearchItems, Unlock,
* Lock, GetSecrets, ReadAlias, SetAlias,
* CreateCollection; prop. Collections)
@@ -14,8 +14,8 @@
* /org/freedesktop/secrets/collection/login/<id> Item
* /org/freedesktop/secrets/session/<n> Session (algoritmos "plain" y
* "dh-ietf1024-sha256-aes128-cbc-pkcs7")
- * /org/freedesktop/secrets/prompt/<n> Prompt (desbloquear con aviso del sistema)
- * El almacenamiento es del llavero (keyring.c), por la interfaz de abajo. */
+ * /org/freedesktop/secrets/prompt/<n> Prompt (unlock with a system notice)
+ * Storage belongs to the keyring (keyring.c), through the interface below. */
#ifndef LORD_VAULT_SECRETSVC_H
#define LORD_VAULT_SECRETSVC_H
@@ -25,63 +25,63 @@
typedef struct { const char *name, *value; } SsAttr;
typedef struct {
- char id[40]; /* id del ítem (hex, sin '/') */
- char *label; /* del backend; liberar con ss_info_free */
+ char id[40]; /* item id (hex, no '/') */
+ char *label; /* from the backend; free with ss_info_free */
SsAttr *attrs; int nattrs;
uint64_t created, modified;
} SsItemInfo;
-/* Lo que pone el llavero (keyring.c). Devuelven 0 bien, -1 error; los punteros que entregan
- * (ss_info, secretos) se liberan con free_info/free_secret del mismo backend. */
+/* What the keyring provides (keyring.c). They return 0 ok, -1 error; the pointers they hand out
+ * (ss_info, secrets) are freed with free_info/free_secret of the same backend. */
typedef struct {
- int (*locked)(void *ud); /* 1 si el llavero está bloqueado */
- /* Pedido de desbloqueo de una app: 0 = ya está desbloqueado, 1 = se mostró un aviso al
- * usuario (contestar después con ss_prompt_done), -1 = no se puede. */
+ int (*locked)(void *ud); /* 1 if the keyring is locked */
+ /* Unlock request from an app: 0 = already unlocked, 1 = a notice was shown to the
+ * user (answer later with ss_prompt_done), -1 = not possible. */
int (*request_unlock)(void *ud, unsigned prompt_id);
int (*lock)(void *ud);
- /* busca ítems cuyos atributos contienen todos los pedidos; ids[i] de hasta 40 bytes */
+ /* finds items whose attributes contain all the requested ones; ids[i] up to 40 bytes */
int (*search)(void *ud, const SsAttr *attrs, int nattrs, char (*ids)[40], int max);
int (*info)(void *ud, const char *id, SsItemInfo *out);
void (*free_info)(void *ud, SsItemInfo *in);
int (*get_secret)(void *ud, const char *id, uint8_t **secret, size_t *len, char ctype[64]);
void (*free_secret)(void *ud, uint8_t *secret, size_t len);
- /* crea (o reemplaza si replace y hay uno con los mismos atributos) → out_id */
+ /* creates (or replaces if replace and one exists with the same attributes) → out_id */
int (*create)(void *ud, const char *label, const SsAttr *attrs, int nattrs,
const uint8_t *secret, size_t len, const char *ctype, int replace, char out_id[40]);
int (*set_secret)(void *ud, const char *id, const uint8_t *secret, size_t len, const char *ctype);
int (*set_label)(void *ud, const char *id, const char *label);
int (*set_attrs)(void *ud, const char *id, const SsAttr *attrs, int nattrs);
int (*remove)(void *ud, const char *id);
- /* quién llama (nombre único del bus y su pid, si el bus lo dio): para el registro y avisos */
+ /* who is calling (unique bus name and its pid, if the bus provided it): for logging and notices */
void (*caller)(void *ud, const char *sender, uint32_t pid);
} SsBackend;
-/* Arranca sobre un socket ya conectado al bus de la sesión: SASL EXTERNAL, Hello y
- * RequestName("org.freedesktop.secrets", DO_NOT_QUEUE). 0 bien; 1 si el nombre ya es de otro
- * (gnome-keyring o kwallet andando): no se atiende; -1 error. */
+/* Starts on a socket already connected to the session bus: SASL EXTERNAL, Hello and
+ * RequestName("org.freedesktop.secrets", DO_NOT_QUEUE). 0 ok; 1 if the name already belongs to another
+ * (gnome-keyring or kwallet running): not served; -1 error. */
int ss_start(int busfd, const SsBackend *be, void *ud);
-int ss_fd(void); /* para poll(); -1 si no arrancó */
-/* Atiende lo que haya en el socket (no bloquea). -1 si el bus se cerró. */
+int ss_fd(void); /* for poll(); -1 if not started */
+/* Serves whatever is on the socket (does not block). -1 if the bus closed. */
int ss_dispatch(void);
-/* Resultado del aviso de desbloqueo prompt_id (1 desbloqueado, 0 cancelado): emite Completed. */
+/* Result of the unlock notice prompt_id (1 unlocked, 0 cancelled): emits Completed. */
void ss_prompt_done(unsigned prompt_id, int unlocked);
-/* Avisar a los clientes que cambió algo (señales ItemCreated/Changed/Deleted, prop. Locked). */
+/* Tell clients that something changed (ItemCreated/Changed/Deleted signals, Locked prop.). */
void ss_notify_locked(int locked);
-void ss_notify_item(const char *id, int what); /* 0 creado, 1 cambiado, 2 borrado */
+void ss_notify_item(const char *id, int what); /* 0 created, 1 changed, 2 deleted */
void ss_stop(void);
-/* ---- agregados ---- */
-int ss_pending_out(void); /* 1 si quedó algo por mandar: sumar POLLOUT al poll() */
-const char *ss_unique_name(void); /* ":1.42" del bus, o "" */
-/* Notas:
- * - El estado de la conexión usa malloc (borrado con explicit_bzero), no smem: sm_wipe_all() al
- * bloquear no la rompe. Los secretos de cada pedido pasan por smem y se borran en el acto.
- * - No llamar a ss_dispatch() al mismo tiempo que sm_wipe_all() desde otro hilo.
- * - ss_notify_item() es para cambios hechos desde otro lado (la app); los que llegan por D-Bus ya
- * emiten su señal. */
-/* Aritmética de la sesión DH (también para las pruebas): base^exp mod mod, todo big endian de
- * 128 bytes, mod impar y base < mod. 0 bien. */
+/* ---- additions ---- */
+int ss_pending_out(void); /* 1 if something is left to send: add POLLOUT to poll() */
+const char *ss_unique_name(void); /* ":1.42" of the bus, or "" */
+/* Notes:
+ * - The connection state uses malloc (wiped with explicit_bzero), not smem: sm_wipe_all() on
+ * lock does not break it. The secrets of each request go through smem and are wiped immediately.
+ * - Do not call ss_dispatch() at the same time as sm_wipe_all() from another thread.
+ * - ss_notify_item() is for changes made elsewhere (the app); those arriving over D-Bus already
+ * emit their signal. */
+/* DH session arithmetic (also for tests): base^exp mod mod, all 128-byte big endian,
+ * mod odd and base < mod. 0 ok. */
int ss_dh_modexp(const uint8_t base[128], const uint8_t exp[128], const uint8_t mod[128], uint8_t out[128]);
-const uint8_t *ss_dh_prime(void); /* el primo de 1024 bits del grupo 2 de RFC 2409 */
+const uint8_t *ss_dh_prime(void); /* the 1024-bit prime of RFC 2409 group 2 */
#endif
diff --git a/server/src/vault/smem.c b/server/src/vault/smem.c
index 59d2afd..898a3e9 100644
--- a/server/src/vault/smem.c
+++ b/server/src/vault/smem.c
@@ -1,4 +1,4 @@
-/* smem.c — arena de memoria para secretos (ver smem.h). */
+/* smem.c — memory arena for secrets (see smem.h). */
#include "smem.h"
#include <pthread.h>
@@ -13,15 +13,15 @@
#define MADV_WIPEONFORK 18
#endif
-#define NCLASS 9 /* 16, 32, …, 4096 bytes útiles */
-#define CHUNK (256u * 1024) /* los bloques chicos salen de trozos de 256 KB */
+#define NCLASS 9 /* 16, 32, …, 4096 usable bytes */
+#define CHUNK (256u * 1024) /* small blocks come from 256 KB chunks */
#define MAGIC_SMALL 0x534d454du
#define MAGIC_BIG 0x534d4542u
-typedef struct Hdr { uint32_t magic, cls; size_t size; } Hdr; /* 16 bytes antes del bloque */
+typedef struct Hdr { uint32_t magic, cls; size_t size; } Hdr; /* 16 bytes before the block */
typedef struct Free { struct Free *next; } Free;
typedef struct Chunk { struct Chunk *next; size_t size, used; int locked; } Chunk;
-typedef struct Big { struct Big *next, *prev; size_t map; int locked; } Big; /* + Hdr + datos */
+typedef struct Big { struct Big *next, *prev; size_t map; int locked; } Big; /* + Hdr + data */
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static Chunk *chunks;
@@ -36,7 +36,7 @@ void sm_harden_process(void) {
struct rlimit rl = { 0, 0 };
setrlimit(RLIMIT_CORE, &rl);
prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
- /* usar todo el mlock que el sistema permita (el límite blando sube hasta el duro) */
+ /* use as much mlock as the system allows (the soft limit is raised up to the hard one) */
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && rl.rlim_cur < rl.rlim_max) { rl.rlim_cur = rl.rlim_max; setrlimit(RLIMIT_MEMLOCK, &rl); }
}
@@ -69,7 +69,7 @@ static void *alloc_small(int cls) {
if (freel[cls]) {
Free *f = freel[cls];
freel[cls] = f->next;
- f->next = NULL; /* ya estaba en cero salvo el enlace */
+ f->next = NULL; /* already zero except for the link */
return f;
}
size_t need = sizeof(Hdr) + sz;
diff --git a/server/src/vault/smem.h b/server/src/vault/smem.h
index 7d603a9..9776842 100644
--- a/server/src/vault/smem.h
+++ b/server/src/vault/smem.h
@@ -1,33 +1,33 @@
-/* smem.h — memoria para secretos de lord-vault (ver docs/PASSWORDS.md, «Memoria»).
+/* smem.h — memory for lord-vault secrets (see docs/PASSWORDS.md, "Memory").
*
- * Todo lo descifrado (la bóveda, los campos, los pedidos y respuestas que llevan secretos) vive
- * en bloques de esta arena y no en el montón de la libc:
- * - mmap anónimo propio, con mlock (no va al swap) si RLIMIT_MEMLOCK alcanza;
- * - MADV_DONTDUMP (nunca en un core) y MADV_WIPEONFORK;
- * - sm_free borra el bloque antes de devolverlo; sm_wipe_all (al bloquear) borra TODO.
- * sm_harden_process() además apaga los core dumps del proceso (RLIMIT_CORE 0) y lo marca no
- * «dumpable» (PR_SET_DUMPABLE 0: tampoco se le puede hacer ptrace desde el mismo usuario).
+ * Everything decrypted (the vault, fields, requests and replies that carry secrets) lives
+ * in blocks of this arena and not in the libc heap:
+ * - own anonymous mmap, with mlock (not swapped out) if RLIMIT_MEMLOCK allows;
+ * - MADV_DONTDUMP (never in a core) and MADV_WIPEONFORK;
+ * - sm_free wipes the block before returning it; sm_wipe_all (on lock) wipes EVERYTHING.
+ * sm_harden_process() also disables the process core dumps (RLIMIT_CORE 0) and marks it not
+ * "dumpable" (PR_SET_DUMPABLE 0: it cannot be ptraced even by the same user).
*
- * Bloques chicos (hasta 4 KB) por clases de tamaño con listas libres, O(1); los grandes van en
- * su propio mmap. Seguro con hilos (un mutex). */
+ * Small blocks (up to 4 KB) use size classes with free lists, O(1); large ones get
+ * their own mmap. Thread-safe (one mutex). */
#ifndef LORD_VAULT_SMEM_H
#define LORD_VAULT_SMEM_H
#include <stddef.h>
void sm_harden_process(void);
-void *sm_alloc(size_t n); /* en cero; NULL si no hay memoria */
+void *sm_alloc(size_t n); /* zeroed; NULL if out of memory */
void *sm_realloc(void *p, size_t n);
-void sm_free(void *p); /* borra y libera (NULL no hace nada) */
+void sm_free(void *p); /* wipes and frees (NULL does nothing) */
char *sm_strdup(const char *s); /* NULL → NULL */
char *sm_strndup(const char *s, size_t n);
-size_t sm_size(const void *p); /* capacidad útil del bloque */
-void sm_wipe_all(void); /* bloquear: borra y suelta toda la arena */
+size_t sm_size(const void *p); /* usable capacity of the block */
+void sm_wipe_all(void); /* on lock: wipes and releases the whole arena */
typedef struct { size_t in_use, mapped, locked; int all_locked; } SmStats;
void sm_stats(SmStats *st);
-/* borrar memoria sin que el compilador lo saque (explicit_bzero) */
+/* wipe memory without the compiler optimizing it away (explicit_bzero) */
void sm_wipe(void *p, size_t n);
#endif
diff --git a/server/src/vault/totp.c b/server/src/vault/totp.c
index 0a4765f..f31f4f2 100644
--- a/server/src/vault/totp.c
+++ b/server/src/vault/totp.c
@@ -1,4 +1,4 @@
-/* totp.c — HOTP/TOTP, base32 y otpauth:// (ver totp.h). */
+/* totp.c — HOTP/TOTP, base32 and otpauth:// (see totp.h). */
#include "totp.h"
#include "vcrypto.h"
@@ -44,7 +44,7 @@ size_t base32_encode(const uint8_t *in, size_t n, char *out, size_t cap) {
return o;
}
-/* decodifica %XX de una URI en dst (cap bytes) */
+/* decodes %XX of a URI into dst (cap bytes) */
static void pct_decode(const char *s, size_t n, char *dst, size_t cap) {
size_t o = 0;
for (size_t i = 0; i < n && o + 1 < cap; i++) {
diff --git a/server/src/vault/totp.h b/server/src/vault/totp.h
index 19a9ef7..b8085db 100644
--- a/server/src/vault/totp.h
+++ b/server/src/vault/totp.h
@@ -1,6 +1,6 @@
-/* totp.h — códigos de un solo uso (2FA): HOTP (RFC 4226) y TOTP (RFC 6238) con SHA-1, SHA-256 y
- * SHA-512, base32 (RFC 4648) y URIs otpauth:// (el formato de Google Authenticator que traen los
- * QR de los sitios). El secreto nunca sale de lord-vault: la interfaz recibe solo el código. */
+/* totp.h — one-time codes (2FA): HOTP (RFC 4226) and TOTP (RFC 6238) with SHA-1, SHA-256 and
+ * SHA-512, base32 (RFC 4648) and otpauth:// URIs (the Google Authenticator format carried by
+ * the QR codes of websites). The secret never leaves lord-vault: the UI receives only the code. */
#ifndef LORD_VAULT_TOTP_H
#define LORD_VAULT_TOTP_H
@@ -13,22 +13,22 @@ typedef struct {
uint8_t key[128]; size_t keylen;
int algo; /* TOTP_* */
int digits; /* 6–10 */
- int period; /* segundos (30) */
- int hotp; /* 1 = otpauth://hotp (contador) */
+ int period; /* seconds (30) */
+ int hotp; /* 1 = otpauth://hotp (counter) */
uint64_t counter;
char issuer[128], account[128];
} Totp;
-/* base32 → bytes (ignora espacios, guiones y '='; mayúsculas o minúsculas). Largo o -1. */
+/* base32 → bytes (ignores spaces, dashes and '='; upper or lower case). Length or -1. */
long base32_decode(const char *s, uint8_t *out, size_t cap);
-size_t base32_encode(const uint8_t *in, size_t n, char *out, size_t cap); /* sin '=' */
+size_t base32_encode(const uint8_t *in, size_t n, char *out, size_t cap); /* without '=' */
-/* Lee un otpauth://totp/… o un secreto base32 suelto. 0 bien. */
+/* Reads an otpauth://totp/… or a bare base32 secret. 0 on success. */
int totp_parse(const char *text, Totp *t);
uint32_t hotp_code(const Totp *t, uint64_t counter);
-/* Código para la hora unix `now`; *remaining = segundos que le quedan. */
+/* Code for unix time `now`; *remaining = seconds left in the period. */
uint32_t totp_code(const Totp *t, uint64_t now, int *remaining);
-/* Código con los ceros de adelante: out de al menos 11 bytes. */
+/* Code with leading zeros: out of at least 11 bytes. */
void totp_format(const Totp *t, uint32_t code, char *out);
void totp_wipe(Totp *t);
diff --git a/server/src/vault/vault_int.h b/server/src/vault/vault_int.h
index bc1a121..b13be5b 100644
--- a/server/src/vault/vault_int.h
+++ b/server/src/vault/vault_int.h
@@ -1,5 +1,5 @@
-/* vault_int.h — lo que comparten las partes de lord-vault (vault.c: proceso, canales y pedidos;
- * keyring.c: el llavero del sistema y Secret Service). */
+/* vault_int.h — what the parts of lord-vault share (vault.c: process, channels and requests;
+ * keyring.c: the system keyring and Secret Service). */
#ifndef LORD_VAULT_INT_H
#define LORD_VAULT_INT_H
@@ -13,20 +13,20 @@
enum { V_MAIN = 0, V_LOGIN = 1, V_COUNT };
enum { ROLE_SYSTEM = 1, ROLE_APP = 2 };
-/* adjunto agregado y todavía no guardado (cifrado, en memoria) */
+/* attachment added and not yet saved (encrypted, in memory) */
typedef struct { uint8_t id[16], nonce[24], mac[16]; uint8_t *cipher; size_t len; } PendAtt;
typedef struct {
- const char *file; /* nombre en la carpeta de bóvedas */
+ const char *file; /* name in the vaults folder */
int unlocked;
- VHeader h; /* ranuras (también bloqueada, si el archivo existe) */
+ VHeader h; /* slots (also when locked, if the file exists) */
int exists;
- uint8_t *vk; /* 32 bytes en smem; NULL bloqueada */
+ uint8_t *vk; /* 32 bytes in smem; NULL when locked */
VModel m;
- int fd; /* archivo actual abierto (origen de los adjuntos) o -1 */
+ int fd; /* current file open (source of the attachments) or -1 */
PendAtt *pend; int npend;
double last_use;
- int autolock_s; /* 0 = nunca (el llavero de la sesión) */
+ int autolock_s; /* 0 = never (the session keyring) */
} Vault;
typedef struct { int fd, role; VwRx rx; } Chan;
@@ -34,21 +34,21 @@ typedef struct { int fd, role; VwRx rx; } Chan;
extern Vault vaults[V_COUNT];
extern int vault_dirfd;
-/* respuestas */
-void reply(Chan *c, uint32_t id, VjB *b); /* libera b */
+/* replies */
+void reply(Chan *c, uint32_t id, VjB *b); /* frees b */
void reply_err(Chan *c, uint32_t id, const char *code);
void reply_ok(Chan *c, uint32_t id);
-void broadcast_event(const char *json); /* a todos los canales */
+void broadcast_event(const char *json); /* to all channels */
-/* bóvedas */
-int vault_save(Vault *v); /* VF_OK o error */
+/* vaults */
+int vault_save(Vault *v); /* VF_OK or error */
void vault_lock(Vault *v);
int vault_unlock_with(Vault *v, int type, const VFactors *f, char *err, size_t errn);
int vault_create(Vault *v, int type, const VFactors *f, const VKdf *kdf, const char *label, const char *meta_json, char *recovery_out);
-/* llavero (keyring.c) */
-int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j); /* 1 si atendió el op */
-void keyring_session_password(const char *pass); /* al ingresar: abrir o crear login.lvault */
+/* keyring (keyring.c) */
+int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j); /* 1 if it handled the op */
+void keyring_session_password(const char *pass); /* on login: open or create login.lvault */
void keyring_start_bus(int busfd);
int keyring_bus_fd(void);
int keyring_bus_wants_out(void);
diff --git a/server/src/vault/vclient.c b/server/src/vault/vclient.c
index b85818b..3bbbda6 100644
--- a/server/src/vault/vclient.c
+++ b/server/src/vault/vclient.c
@@ -1,4 +1,4 @@
-/* vclient.c — lord-server habla con lord-vault (ver vclient.h). */
+/* vclient.c — lord-server talks to lord-vault (see vclient.h). */
#include "vclient.h"
#include "vwire.h"
#include "fidodev.h"
@@ -14,6 +14,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
+#include <sys/eventfd.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>
@@ -33,7 +34,21 @@ static int inflight;
static Ev *qhead, *qtail;
static char helper[PATH_MAX];
static int helper_ok = -1;
-static char *pending_pass; /* contraseña de la sesión que llegó antes que lord-vault */
+static char *pending_pass; /* session password that arrived before lord-vault was running */
+
+/* Private requests (the broker's keyring op, src/sec/brokerkr.c): their replies go to their own
+ * queue, read by lord-server's C code (vc_take_private), never to the JS queue (vc_poll). */
+#define VC_PRIV_MAX 64
+static uint32_t priv_ids[VC_PRIV_MAX];
+static int npriv;
+static Ev *phead, *ptail;
+static int priv_efd = -1;
+
+static int priv_take_id(uint32_t id) { /* with mu held: 1 if id was a private request */
+ for (int i = 0; i < npriv; i++) if (priv_ids[i] == id) { priv_ids[i] = priv_ids[--npriv]; return 1; }
+ return 0;
+}
+static void priv_wake(void) { if (priv_efd >= 0) { uint64_t one = 1; ssize_t r = write(priv_efd, &one, sizeof one); (void)r; } }
int vc_available(void) {
if (helper_ok < 0) {
@@ -47,7 +62,7 @@ int vc_available(void) {
*sl = 0;
snprintf(helper, sizeof helper, "%.*s/lord-vault", (int)(sizeof helper - 16), self);
struct stat st;
- /* del usuario o de root, y que nadie más lo pueda reemplazar */
+ /* owned by the user or root, and nobody else can replace it */
if (stat(helper, &st) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_IXUSR) && !(st.st_mode & S_IWOTH) &&
(st.st_uid == 0 || st.st_uid == getuid())) helper_ok = 1;
}
@@ -61,10 +76,12 @@ static void push(uint32_t id, uint32_t kind, char *json, size_t len) {
if (!e) { explicit_bzero(json, len); free(json); return; }
e->id = id; e->kind = kind; e->json = json; e->len = len;
pthread_mutex_lock(&mu);
- if (qtail) qtail->next = e; else qhead = e;
- qtail = e;
+ int priv = kind == VW_REP && priv_take_id(id);
+ if (priv) { if (ptail) ptail->next = e; else phead = e; ptail = e; }
+ else { if (qtail) qtail->next = e; else qhead = e; qtail = e; }
if (kind == VW_REP && inflight > 0) inflight--;
pthread_mutex_unlock(&mu);
+ if (priv) priv_wake();
}
static void *read_loop(void *arg) {
@@ -76,12 +93,19 @@ static void *read_loop(void *arg) {
for (int i = 0; i < m.nfds; i++) close(m.fds[i]);
push(m.id, m.kind, m.json, m.len);
}
- /* se cayó: los pedidos sin respuesta terminan con error */
+ /* it went away: requests without a reply end with an error */
pthread_mutex_lock(&mu);
int lost = inflight;
inflight = 0;
if (sock == s) sock = -1;
+ uint32_t orphans[VC_PRIV_MAX];
+ int norph = npriv;
+ memcpy(orphans, priv_ids, sizeof(uint32_t) * (size_t)npriv);
pthread_mutex_unlock(&mu);
+ for (int i = 0; i < norph; i++) { /* private requests get a "crash" reply */
+ char *cj = strdup("{\"error\":\"crash\"}");
+ if (cj) push(orphans[i], VW_REP, cj, strlen(cj));
+ }
char *j = strdup("{\"ev\":\"crash\"}");
if (j) push(0, VW_EVT, j, strlen(j));
(void)lost;
@@ -89,7 +113,7 @@ static void *read_loop(void *arg) {
return NULL;
}
-/* el socket del bus de la sesión (sin autenticar: lo hace lord-vault) */
+/* the session bus socket (unauthenticated: lord-vault does that) */
static int connect_bus(void) {
const char *a = getenv("DBUS_SESSION_BUS_ADDRESS");
struct sockaddr_un sa = { .sun_family = AF_UNIX };
@@ -136,7 +160,7 @@ int vc_start(void) {
if (running) return 0;
if (!vc_available() || is_greeter() || getuid() == 0) return -1;
if (pid > 0) { waitpid(pid, NULL, WNOHANG); pid = 0; }
- /* carpeta de las bóvedas */
+ /* vaults folder */
const char *home = getenv("HOME");
if (!home) return -1;
char dir[PATH_MAX];
@@ -180,12 +204,12 @@ int vc_start(void) {
if (vw_send(sv[0], VW_CTL, 0, "{\"op\":\"init\"}", 13, fds, nf)) { close(sv[0]); close(dfd); if (fds[1] >= 0) close(fds[1]); return -1; }
close(dfd);
if (fds[1] >= 0) close(fds[1]);
- /* la respuesta del init también pasa por la cola (id 0) */
+ /* the init reply also goes through the queue (id 0) */
pthread_mutex_lock(&mu);
sock = sv[0];
pthread_mutex_unlock(&mu);
if (pthread_create(&reader, NULL, read_loop, (void *)(intptr_t)sv[0]) == 0) { pthread_detach(reader); reader_on = 1; }
- fprintf(stderr, "lord-server: lord-vault lanzado (pid %d)\n", (int)p);
+ fprintf(stderr, "lord-server: lord-vault started (pid %d)\n", (int)p);
if (pending_pass) {
vc_session_password(pending_pass);
explicit_bzero(pending_pass, strlen(pending_pass));
@@ -195,24 +219,67 @@ int vc_start(void) {
return 0;
}
-static int send_kind(uint32_t kind, const char *json, size_t len, int *fds, int nfds) {
+static int send_kind_p(uint32_t kind, const char *json, size_t len, int *fds, int nfds, int priv) {
if (vc_start()) { for (int i = 0; i < nfds; i++) if (fds[i] >= 0) close(fds[i]); return -1; }
pthread_mutex_lock(&mu);
+ if (priv && npriv >= VC_PRIV_MAX) { pthread_mutex_unlock(&mu); return -1; }
uint32_t id = next_id++;
if (next_id > 0x7fffffff) next_id = 1;
int s = sock;
inflight++;
+ if (priv) priv_ids[npriv++] = id; /* registered before sending: the reply may come at once */
pthread_mutex_unlock(&mu);
int r = vw_send(s, kind, id, json, len, fds, nfds);
for (int i = 0; i < nfds; i++) if (fds[i] >= 0) close(fds[i]);
- if (r) { pthread_mutex_lock(&mu); if (inflight) inflight--; pthread_mutex_unlock(&mu); return -1; }
+ if (r) {
+ pthread_mutex_lock(&mu);
+ if (inflight) inflight--;
+ if (priv) priv_take_id(id);
+ pthread_mutex_unlock(&mu);
+ return -1;
+ }
return (int)id;
}
+static int send_kind(uint32_t kind, const char *json, size_t len, int *fds, int nfds) { return send_kind_p(kind, json, len, fds, nfds, 0); }
int vc_request(const char *json, size_t len, int *fds, int nfds) { return send_kind(VW_REQ, json, len, fds, nfds); }
static int ctl(const char *json, int *fds, int nfds) { return send_kind(VW_CTL, json, strlen(json), fds, nfds); }
-/* JSON del texto como cadena dentro de otra respuesta: data va tal cual (ya es JSON) */
+int vc_private_fd(void) {
+ pthread_mutex_lock(&mu);
+ if (priv_efd < 0) priv_efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
+ int f = priv_efd;
+ pthread_mutex_unlock(&mu);
+ return f;
+}
+
+int vc_request_private(const char *json, size_t len) {
+ vc_private_fd();
+ return send_kind_p(VW_REQ, json, len, NULL, 0, 1);
+}
+
+char *vc_take_private(uint32_t *id, size_t *len) {
+ pthread_mutex_lock(&mu);
+ Ev *e = phead;
+ if (e) { phead = e->next; if (!phead) ptail = NULL; }
+ else if (priv_efd >= 0) { uint64_t v; ssize_t r = read(priv_efd, &v, sizeof v); (void)r; } /* drained: re-arm */
+ pthread_mutex_unlock(&mu);
+ if (!e) return NULL;
+ char *j = e->json;
+ if (id) *id = e->id;
+ if (len) *len = e->len;
+ free(e);
+ return j;
+}
+
+int vc_private_pending(void) {
+ pthread_mutex_lock(&mu);
+ int n = npriv + (phead != NULL);
+ pthread_mutex_unlock(&mu);
+ return n;
+}
+
+/* JSON of the text as a string inside another reply: data goes as-is (it is already JSON) */
char *vc_poll(void) {
pthread_mutex_lock(&mu);
Ev *list = qhead;
@@ -275,7 +342,7 @@ static void json_escape(char *out, size_t n, const char *s) {
void vc_session_password(const char *pass) {
if (!pass || !pass[0]) return;
if (vc_start()) {
- /* todavía no se pudo lanzar (lord-server recién arranca): se guarda para cuando ande */
+ /* it could not be launched yet (lord-server is just starting): saved for when it is running */
if (!pending_pass && vc_available() && !is_greeter()) pending_pass = strdup(pass);
return;
}
diff --git a/server/src/vault/vclient.h b/server/src/vault/vclient.h
index 11f8cb2..511ee0e 100644
--- a/server/src/vault/vclient.h
+++ b/server/src/vault/vclient.h
@@ -1,31 +1,42 @@
-/* vclient.h — lado de lord-server de lord-vault (ver vault.c y docs/PASSWORDS.md).
+/* vclient.h — lord-server side of lord-vault (see vault.c and docs/PASSWORDS.md).
*
- * lord-server lanza el ayudante una vez por sesión (ruta fija: <carpeta de este binario>/lord-vault,
- * sin argumentos, entorno mínimo), le pasa la carpeta de las bóvedas
- * (~/.local/share/lordos/vault) y el socket ya conectado al bus de D-Bus de la sesión (para
- * Secret Service), y después le habla por el canal de control. Un hilo propio lee las respuestas
- * y los eventos y los deja en una cola que JS lee con vc_poll() (lord.vault.poll): el compositor
- * nunca espera a lord-vault. Lo descifrado que pasa por acá (lo que la interfaz muestra) se borra
- * de los búferes de C apenas se entrega. */
+ * lord-server launches the helper once per session (fixed path: <this binary's folder>/lord-vault,
+ * no arguments, minimal environment), hands it the vaults folder
+ * (~/.local/share/lordos/vault) and the socket already connected to the session D-Bus bus (for
+ * Secret Service), and then talks to it over the control channel. A dedicated thread reads the
+ * replies and events and leaves them in a queue that JS reads with vc_poll() (lord.vault.poll): the
+ * compositor never waits for lord-vault. Decrypted data passing through here (what the UI shows)
+ * is wiped from the C buffers as soon as it is delivered. */
#ifndef LORD_VAULT_VCLIENT_H
#define LORD_VAULT_VCLIENT_H
#include <stddef.h>
+#include <stdint.h>
-int vc_available(void); /* 1 si está el binario */
-int vc_start(void); /* lo lanza si no corre; 0 bien */
-/* Pedido (JSON) con fds opcionales (se quedan con ellos). Devuelve el id (> 0) o -1. */
+int vc_available(void); /* 1 if the binary is present */
+int vc_start(void); /* launches it if not running; 0 on success */
+/* Request (JSON) with optional fds (it takes ownership of them). Returns the id (> 0) or -1. */
int vc_request(const char *json, size_t len, int *fds, int nfds);
-/* Respuestas y eventos pendientes: [{"id":n,"kind":"rep"|"evt","data":{…}}] (malloc) o NULL. */
+/* Pending replies and events: [{"id":n,"kind":"rep"|"evt","data":{…}}] (malloc) or NULL. */
char *vc_poll(void);
-void vc_poll_free(char *s); /* borra y libera lo que devolvió vc_poll */
-int vc_pending(void); /* pedidos sin respuesta */
-/* Control (solo lord-server) */
+void vc_poll_free(char *s); /* wipes and frees what vc_poll returned */
+int vc_pending(void); /* requests without a reply */
+/* Control (lord-server only) */
void vc_lock_all(const char *why); /* "screen", "switch", "logout", "idle" */
-void vc_session_password(const char *pass); /* de lord-sessiond: abrir el llavero de la sesión */
-int vc_fido_attach(char *name, size_t n); /* abre la primera llave FIDO2 y se la pasa a lord-vault */
-void vc_prompt_done(unsigned prompt, int ok);/* resultado del aviso de desbloqueo de Secret Service */
-/* Canal propio para el proceso aislado de la app Contraseñas: devuelve el fd del otro extremo. */
+void vc_session_password(const char *pass); /* from lord-sessiond: open the session keyring */
+int vc_fido_attach(char *name, size_t n); /* opens the first FIDO2 key and hands it to lord-vault */
+void vc_prompt_done(unsigned prompt, int ok);/* result of the Secret Service unlock prompt */
+/* Dedicated channel for the sandboxed Passwords app process: returns the fd of the other end. */
int vc_attach_app(void);
+/* Private requests from lord-server's own C code (the broker's keyring op for .lpk apps,
+ * src/sec/brokerkr.c), on the system channel: the reply never reaches the JS queue (vc_poll).
+ * vc_request_private returns the id (> 0) or -1; vc_take_private returns the next reply (malloc'd,
+ * NUL-terminated; the caller wipes and frees it) or NULL; vc_private_fd becomes readable when a
+ * reply is waiting (for poll). If lord-vault dies, every open private request gets
+ * {"error":"crash"}. */
+int vc_request_private(const char *json, size_t len);
+char *vc_take_private(uint32_t *id, size_t *len);
+int vc_private_fd(void);
+int vc_private_pending(void); /* private requests without a reply, or replies not taken */
#endif
diff --git a/server/src/vault/vcrypto.c b/server/src/vault/vcrypto.c
index 2005d81..cb6e752 100644
--- a/server/src/vault/vcrypto.c
+++ b/server/src/vault/vcrypto.c
@@ -1,5 +1,5 @@
-/* vcrypto.c — AES, SHA-1, HMAC y HKDF propios (ver vcrypto.h). Código chico y directo: AES por
- * bytes (FIPS-197), SHA-1 (FIPS 180-4), HMAC (RFC 2104), HKDF (RFC 5869). */
+/* vcrypto.c — own AES, SHA-1, HMAC and HKDF (see vcrypto.h). Small, direct code: byte-wise
+ * AES (FIPS-197), SHA-1 (FIPS 180-4), HMAC (RFC 2104), HKDF (RFC 5869). */
#include "vcrypto.h"
#include "../pkg/crypto.h"
@@ -82,7 +82,7 @@ void aes_encrypt(const Aes *a, const uint8_t in[16], uint8_t out[16]) {
add_rk(s, a->rk);
for (int r = 1; r <= a->nr; r++) {
for (int i = 0; i < 16; i++) s[i] = SB[s[i]];
- /* ShiftRows: fila f se corre f lugares (estado en columnas de 4 bytes) */
+ /* ShiftRows: row f is shifted by f positions (state in 4-byte columns) */
for (int c = 0; c < 4; c++) for (int f = 0; f < 4; f++) t[4 * c + f] = s[4 * ((c + f) & 3) + f];
if (r != a->nr) {
for (int c = 0; c < 4; c++) {
@@ -275,7 +275,7 @@ int hkdf_sha256(const uint8_t *salt, size_t slen, const uint8_t *ikm, size_t ile
return 0;
}
-/* ================= varios ================= */
+/* ================= misc ================= */
int vc_random(void *buf, size_t n) {
uint8_t *p = buf;
diff --git a/server/src/vault/vcrypto.h b/server/src/vault/vcrypto.h
index 021c5a2..f6da421 100644
--- a/server/src/vault/vcrypto.h
+++ b/server/src/vault/vcrypto.h
@@ -1,10 +1,10 @@
-/* vcrypto.h — primitivas propias que Monocypher no trae y que piden los formatos ajenos:
- * - AES-128/256 (bloque, CBC): CTAP2 (protocolo de PIN 1), KDBX (AES-256-CBC y AES-KDF) y el
- * cifrado «dh-ietf1024-sha256-aes128-cbc-pkcs7» de Secret Service;
- * - SHA-1 y HMAC-SHA1 (TOTP, RFC 6238/4226), HMAC-SHA256 (CTAP2, KDBX, TOTP-SHA256),
- * HMAC-SHA512 (TOTP-SHA512) y HKDF-SHA256 (RFC 5869).
- * La bóveda propia usa solo Monocypher (XChaCha20-Poly1305, Argon2id, BLAKE2b).
- * SHA-256/512 son los de server/src/pkg/crypto.c. */
+/* vcrypto.h — own primitives that Monocypher lacks and that foreign formats require:
+ * - AES-128/256 (block, CBC): CTAP2 (PIN protocol 1), KDBX (AES-256-CBC and AES-KDF) and the
+ * "dh-ietf1024-sha256-aes128-cbc-pkcs7" encryption of Secret Service;
+ * - SHA-1 and HMAC-SHA1 (TOTP, RFC 6238/4226), HMAC-SHA256 (CTAP2, KDBX, TOTP-SHA256),
+ * HMAC-SHA512 (TOTP-SHA512) and HKDF-SHA256 (RFC 5869).
+ * The native vault uses only Monocypher (XChaCha20-Poly1305, Argon2id, BLAKE2b).
+ * SHA-256/512 are those of server/src/pkg/crypto.c. */
#ifndef LORD_VAULT_VCRYPTO_H
#define LORD_VAULT_VCRYPTO_H
@@ -12,15 +12,15 @@
#include <stdint.h>
/* ---- AES ---- */
-typedef struct { uint32_t rk[60]; int nr; } Aes; /* claves de ronda (cifrar y descifrar) */
-int aes_init(Aes *a, const uint8_t *key, int keybits); /* 128, 192 o 256; 0 bien */
+typedef struct { uint32_t rk[60]; int nr; } Aes; /* round keys (encrypt and decrypt) */
+int aes_init(Aes *a, const uint8_t *key, int keybits); /* 128, 192 or 256; 0 on success */
void aes_encrypt(const Aes *a, const uint8_t in[16], uint8_t out[16]);
void aes_decrypt(const Aes *a, const uint8_t in[16], uint8_t out[16]);
void aes_wipe(Aes *a);
-/* CBC sin relleno: len múltiplo de 16 (in y out pueden ser el mismo búfer). iv se actualiza. */
+/* CBC without padding: len a multiple of 16 (in and out may be the same buffer). iv is updated. */
int aes_cbc_encrypt(const Aes *a, uint8_t iv[16], const uint8_t *in, uint8_t *out, size_t len);
int aes_cbc_decrypt(const Aes *a, uint8_t iv[16], const uint8_t *in, uint8_t *out, size_t len);
-/* Quita el relleno PKCS#7 de un bloque ya descifrado: largo sin relleno o -1 si es inválido. */
+/* Strips PKCS#7 padding from an already decrypted block: unpadded length or -1 if invalid. */
long pkcs7_unpad(const uint8_t *buf, size_t len);
/* ---- SHA-1 ---- */
@@ -33,15 +33,15 @@ void sha1(const void *data, size_t len, uint8_t out[20]);
/* ---- HMAC ---- */
void hmac_sha1(const uint8_t *key, size_t klen, const uint8_t *msg, size_t len, uint8_t out[20]);
void hmac_sha256(const uint8_t *key, size_t klen, const uint8_t *msg, size_t len, uint8_t out[32]);
-/* HMAC-SHA256 de varias partes (KDBX: índice || largo || bloque). parts/lens terminan con NULL. */
+/* Multi-part HMAC-SHA256 (KDBX: index || length || block). parts/lens end with NULL. */
void hmac_sha256_v(const uint8_t *key, size_t klen, const uint8_t *const *parts, const size_t *lens, uint8_t out[32]);
void hmac_sha512(const uint8_t *key, size_t klen, const uint8_t *msg, size_t len, uint8_t out[64]);
-/* HKDF-SHA256 (RFC 5869); out de hasta 255*32 bytes. 0 bien. */
+/* HKDF-SHA256 (RFC 5869); out of up to 255*32 bytes. 0 on success. */
int hkdf_sha256(const uint8_t *salt, size_t slen, const uint8_t *ikm, size_t ilen,
const uint8_t *info, size_t infolen, uint8_t *out, size_t outlen);
-/* ---- varios ---- */
-int vc_random(void *buf, size_t n); /* getrandom; 0 bien */
-int vc_equal(const void *a, const void *b, size_t n); /* 1 si iguales (tiempo constante) */
+/* ---- misc ---- */
+int vc_random(void *buf, size_t n); /* getrandom; 0 on success */
+int vc_equal(const void *a, const void *b, size_t n); /* 1 if equal (constant time) */
#endif
diff --git a/server/src/vault/vfile.c b/server/src/vault/vfile.c
index 1141c16..d92fd31 100644
--- a/server/src/vault/vfile.c
+++ b/server/src/vault/vfile.c
@@ -1,4 +1,4 @@
-/* vfile.c — formato .lvault (ver vfile.h y docs/PASSWORDS.md). */
+/* vfile.c — .lvault format (see vfile.h and docs/PASSWORDS.md). */
#include "vfile.h"
#include "smem.h"
#include "vcrypto.h"
@@ -39,7 +39,7 @@ static uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
static uint32_t get32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; }
static uint64_t get64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = v << 8 | p[i]; return v; }
-/* ---- derivaciones ---- */
+/* ---- derivations ---- */
static void blake_kdf(const uint8_t *key, size_t klen, const char *ctx, const uint8_t *salt, size_t slen, uint8_t out[32]) {
crypto_blake2b_ctx c;
@@ -58,7 +58,7 @@ int vf_argon2id(const uint8_t *pass, size_t plen, const uint8_t salt[16], const
crypto_argon2_config cfg = { .algorithm = CRYPTO_ARGON2_ID, .nb_blocks = blocks, .nb_passes = p->t_cost, .nb_lanes = lanes };
crypto_argon2_inputs in = { .pass = pass, .salt = salt, .pass_size = (uint32_t)plen, .salt_size = 16 };
crypto_argon2(out, 32, work, cfg, in, crypto_argon2_no_extras);
- sm_free(work); /* se borra (los bloques derivan de la contraseña) */
+ sm_free(work); /* wiped (the blocks derive from the password) */
return 0;
}
@@ -91,7 +91,7 @@ void vf_recovery_new(char out[48]) {
sm_wipe(r, sizeof r);
}
-/* normaliza lo escrito (minúsculas, O→0, I/L→1, sin guiones ni espacios) a 25 bytes */
+/* normalizes what was typed (lowercase, O→0, I/L→1, no dashes or spaces) to 25 bytes */
static int recovery_bytes(const char *s, uint8_t out[25]) {
uint32_t acc = 0;
int bits = 0, n = 0;
@@ -110,7 +110,7 @@ static int recovery_bytes(const char *s, uint8_t out[25]) {
return n == 25 ? 0 : -1;
}
-/* KEK de una ranura con los factores; 0 bien, 1 si faltan factores para este tipo, -1 error */
+/* KEK of a slot from the factors; 0 ok, 1 if factors are missing for this type, -1 error */
static int slot_kek(const VSlot *s, const VFactors *f, uint8_t kek[32]) {
uint8_t a[32];
switch (s->type) {
@@ -143,7 +143,7 @@ static int slot_kek(const VSlot *s, const VFactors *f, uint8_t kek[32]) {
return -1;
}
-/* ---- serialización de ranuras ---- */
+/* ---- slot serialization ---- */
static size_t slot_body(const VSlot *s, uint8_t *p, int with_wrap) {
size_t o = 0;
@@ -165,7 +165,7 @@ static size_t slot_body(const VSlot *s, uint8_t *p, int with_wrap) {
return o;
}
-/* AD de la envoltura: magia + versión + id de la bóveda + tipo/kdf + la ranura sin la envoltura */
+/* AD of the wrapper: magic + version + vault id + type/kdf + the slot without the wrapper */
static size_t wrap_ad(const VHeader *h, const VSlot *s, uint8_t *ad) {
size_t o = 0;
memcpy(ad, VF_MAGIC, 8); o += 8;
@@ -266,7 +266,7 @@ int vf_parse(const uint8_t *d, size_t len, VHeader *h) {
if (o != hlen) return VF_EFORMAT;
h->nslots = ns;
h->hlen = hlen;
- /* cuerpo */
+ /* body */
if (o + 32 > len) return VF_ETRUNC;
uint64_t bl = get64(d + o + 24);
if (bl > VF_MAX_BODY) return VF_EFORMAT;
@@ -274,7 +274,7 @@ int vf_parse(const uint8_t *d, size_t len, VHeader *h) {
h->body_off = o;
h->body_len = bl;
o += 32 + bl + 16;
- /* adjuntos */
+ /* attachments */
if (o + 4 > len) return VF_ETRUNC;
uint32_t na = get32(d + o);
o += 4;
@@ -321,7 +321,7 @@ int vf_open_slot(const VHeader *h, int type, const VFactors *f, uint8_t vk[32],
}
int vf_make_slot(const VHeader *h, VSlot *s, int type, const VFactors *f, const uint8_t vk[32], const VKdf *kdf, const char *label) {
- VSlot keep = *s; /* conserva cred/hmac_salt/aaguid de FIDO2 si ya vienen */
+ VSlot keep = *s; /* keeps FIDO2 cred/hmac_salt/aaguid if already present */
memset(s, 0, sizeof *s);
s->type = (uint8_t)type;
s->kdf = (type == VS_PASSWORD || type == VS_PASSKEY || type == VS_SESSION) ? VK_ARGON2ID : VK_BLAKE2B;
@@ -395,7 +395,7 @@ int vf_att_open(const uint8_t vk[32], const uint8_t vault_id[16], const uint8_t
return r ? VF_ECORRUPT : VF_OK;
}
-/* ---- escribir ---- */
+/* ---- writing ---- */
static int write_all(int fd, const void *buf, size_t n) {
const uint8_t *p = buf;
@@ -473,8 +473,8 @@ int vf_save(int dirfd, const char *name, VHeader *h, const uint8_t vk[32], const
int r = vf_write_fd(fd, h, vk, plain, plen, atts, natts);
close(fd);
if (r != VF_OK) { unlinkat(dirfd, tmp, 0); h->saved = saved.saved; h->counter = saved.counter; return r; }
- /* la versión anterior queda como .bak: enlace duro (el archivo de ahora sigue entero) y
- * reemplazo atómico del .bak viejo; recién después el nuevo toma el nombre */
+ /* the previous version stays as .bak: hard link (the current file remains intact) and
+ * atomic replacement of the old .bak; only then does the new one take the name */
struct stat st;
if (fstatat(dirfd, name, &st, 0) == 0) {
unlinkat(dirfd, baknew, 0);
@@ -487,7 +487,7 @@ int vf_save(int dirfd, const char *name, VHeader *h, const uint8_t vk[32], const
return VF_OK;
}
-/* ---- calibrar ---- */
+/* ---- calibrate ---- */
static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
@@ -497,9 +497,9 @@ void vf_calibrate(int target_ms, VKdf *out, int *measured_ms) {
VKdf p = { 64 * 1024, 1, 1 };
double t0 = now_ms();
vf_argon2id((const uint8_t *)"calibrar", 8, salt, &p, o);
- double t1 = now_ms() - t0; /* una pasada con 64 MiB */
+ double t1 = now_ms() - t0; /* one pass with 64 MiB */
if (t1 < 1) t1 = 1;
- /* tope de memoria: un octavo de la RAM, entre 19 MiB y 256 MiB */
+ /* memory cap: one eighth of RAM, between 19 MiB and 256 MiB */
struct sysinfo si;
uint64_t cap = 256 * 1024;
if (sysinfo(&si) == 0) {
@@ -508,7 +508,7 @@ void vf_calibrate(int target_ms, VKdf *out, int *measured_ms) {
}
if (cap < 19 * 1024) cap = 19 * 1024;
uint32_t m = 64 * 1024;
- double per = t1; /* ms por pasada con m */
+ double per = t1; /* ms per pass with m */
while (m * 2 <= cap && per * 2 * 3 <= target_ms) { m *= 2; per *= 2; }
while (m / 2 >= 19 * 1024 && per * 2 > target_ms) { m /= 2; per /= 2; }
if (m > cap) { per = per * cap / m; m = (uint32_t)cap; }
diff --git a/server/src/vault/vfile.h b/server/src/vault/vfile.h
index e3c3341..e78b027 100644
--- a/server/src/vault/vfile.h
+++ b/server/src/vault/vfile.h
@@ -1,21 +1,21 @@
-/* vfile.h — el formato de archivo de la bóveda (.lvault), versión 1. Ver docs/PASSWORDS.md,
- * «El formato».
+/* vfile.h — the vault file format (.lvault), version 1. See docs/PASSWORDS.md,
+ * "The format".
*
- * cabecera "LORDVLT\x1a", versión, largo de cabecera, id de la bóveda, fechas, contador,
- * y las «ranuras» (una por forma de abrir: contraseña, archivo llave, contraseña +
- * archivo llave, llave FIDO2, clave de recuperación, contraseña de la sesión)
- * cuerpo nonce(24) largo(8) XChaCha20-Poly1305(contenido JSON) mac(16)
- * AD = la cabecera entera: cambiar una ranura o un parámetro se detecta al abrir
- * adjuntos cantidad(4) y por cada uno: id(16) nonce(24) largo(8) cifrado mac(16)
- * cola "LVLTEND\0" + largo total(8): un archivo cortado se reconoce
+ * header "LORDVLT\x1a", version, header length, vault id, dates, counter,
+ * and the "slots" (one per way of opening: password, key file, password +
+ * key file, FIDO2 key, recovery key, session password)
+ * body nonce(24) length(8) XChaCha20-Poly1305(JSON content) mac(16)
+ * AD = the whole header: changing a slot or a parameter is detected on open
+ * attachments count(4) and for each: id(16) nonce(24) length(8) ciphertext mac(16)
+ * trailer "LVLTEND\0" + total length(8): a truncated file is recognized
*
- * La clave de la bóveda (VK, 32 bytes al azar) nunca se deriva de la contraseña: cada ranura la
- * guarda envuelta (XChaCha20-Poly1305) con una clave derivada de su factor (Argon2id para lo que
- * escribe una persona, BLAKE2b para lo que ya tiene entropía: archivo llave, salida de la llave
- * FIDO2, clave de recuperación). Así se agregan o quitan formas de abrir sin volver a cifrar
- * todo, y cambiar la contraseña es reescribir una ranura.
+ * The vault key (VK, 32 random bytes) is never derived from the password: each slot
+ * stores it wrapped (XChaCha20-Poly1305) with a key derived from its factor (Argon2id for what
+ * a person types, BLAKE2b for what already has entropy: key file, FIDO2 key output,
+ * recovery key). This way ways of opening can be added or removed without re-encrypting
+ * everything, and changing the password is rewriting one slot.
*
- * Todo en little endian. */
+ * Everything is little endian. */
#ifndef LORD_VAULT_VFILE_H
#define LORD_VAULT_VFILE_H
@@ -33,8 +33,8 @@ enum { VS_PASSWORD = 1, VS_KEYFILE, VS_PASSKEY, VS_FIDO2, VS_RECOVERY, VS_SESSIO
enum { VK_ARGON2ID = 1, VK_BLAKE2B = 2 };
enum {
VF_OK = 0, VF_EIO = -1, VF_EFORMAT = -2, VF_EVERSION = -3, VF_ETRUNC = -4,
- VF_EBADKEY = -5, /* ningún factor abre una ranura (contraseña incorrecta, otra llave…) */
- VF_ECORRUPT = -6, /* abrió la ranura pero el cuerpo no autentica: alterado */
+ VF_EBADKEY = -5, /* no factor opens a slot (wrong password, another key…) */
+ VF_ECORRUPT = -6, /* opened the slot but the body fails authentication: tampered */
VF_ENOMEM = -7, VF_ENOSLOT = -8,
};
@@ -47,12 +47,12 @@ typedef struct {
VKdf p; /* VK_ARGON2ID */
uint8_t salt[16];
uint8_t cred[255]; uint8_t cred_len; uint8_t hmac_salt[32]; uint8_t aaguid[16]; /* VS_FIDO2 */
- uint8_t fido_pin; /* VS_FIDO2: 1 si se usó el PIN de la llave (cambia la salida de hmac-secret) */
+ uint8_t fido_pin; /* VS_FIDO2: 1 if the key's PIN was used (changes the hmac-secret output) */
uint64_t created;
uint8_t nonce[24], wrapped[32], mac[16];
} VSlot;
-typedef struct { uint8_t id[16]; uint64_t off, len; uint8_t nonce[24], mac[16]; } VAttLoc; /* en el archivo */
+typedef struct { uint8_t id[16]; uint64_t off, len; uint8_t nonce[24], mac[16]; } VAttLoc; /* in the file */
typedef struct {
uint8_t vault_id[16];
@@ -61,55 +61,55 @@ typedef struct {
uint16_t flags;
VSlot slots[VF_MAX_SLOTS];
int nslots;
- size_t hlen; /* bytes de cabecera (al leer) */
- /* al leer: dónde está el cuerpo y los adjuntos */
+ size_t hlen; /* header bytes (when reading) */
+ /* when reading: where the body and attachments are */
uint64_t body_off, body_len;
- VAttLoc *atts; int natts; /* malloc (no son secretos: ids y posiciones) */
+ VAttLoc *atts; int natts; /* malloc (not secrets: ids and positions) */
} VHeader;
-/* Factores que trae el usuario (los que no se usan, en NULL). */
+/* Factors supplied by the user (unused ones are NULL). */
typedef struct {
const char *password; /* VS_PASSWORD, VS_PASSKEY, VS_SESSION */
- const uint8_t *keyfile; /* 32 bytes: BLAKE2b del archivo llave (vf_keyfile_hash) */
- const uint8_t *fido; /* 32 bytes: salida hmac-secret de la llave */
- const char *recovery; /* la clave de recuperación tal como se escribió */
+ const uint8_t *keyfile; /* 32 bytes: BLAKE2b of the key file (vf_keyfile_hash) */
+ const uint8_t *fido; /* 32 bytes: hmac-secret output of the key */
+ const char *recovery; /* the recovery key as typed */
} VFactors;
-/* Lee la cabecera y la tabla del archivo (data = todo el archivo o al menos hasta la cola). */
+/* Reads the header and table of the file (data = whole file or at least up to the trailer). */
int vf_parse(const uint8_t *data, size_t len, VHeader *h);
void vf_header_free(VHeader *h);
-/* Prueba las ranuras del tipo `type` (0 = cualquiera que use los factores dados) y deja la VK.
- * *slot = índice de la que abrió. VF_EBADKEY si ninguna. */
+/* Tries the slots of type `type` (0 = any that uses the given factors) and yields the VK.
+ * *slot = index of the one that opened. VF_EBADKEY if none. */
int vf_open_slot(const VHeader *h, int type, const VFactors *f, uint8_t vk[32], int *slot);
-/* Descifra el cuerpo con la VK → texto en smem (sm_free). VF_ECORRUPT si no autentica. */
+/* Decrypts the body with the VK → text in smem (sm_free). VF_ECORRUPT if it fails authentication. */
int vf_read_body(const uint8_t *data, size_t len, const VHeader *h, const uint8_t vk[32], uint8_t **out, size_t *outlen);
-/* Arma una ranura nueva del tipo dado que envuelve la VK (deriva con los factores). */
+/* Builds a new slot of the given type that wraps the VK (derives with the factors). */
int vf_make_slot(const VHeader *h, VSlot *s, int type, const VFactors *f, const uint8_t vk[32], const VKdf *kdf, const char *label);
-/* Adjuntos: cifrar (al agregarlo) y descifrar (al pedirlo). id/nonce/mac quedan en el contenido. */
+/* Attachments: encrypt (when adding) and decrypt (when requested). id/nonce/mac stay in the content. */
int vf_att_seal(const uint8_t vk[32], const uint8_t vault_id[16], const uint8_t id[16], const uint8_t *plain, size_t len,
uint8_t *cipher, uint8_t nonce[24], uint8_t mac[16]);
int vf_att_open(const uint8_t vk[32], const uint8_t vault_id[16], const uint8_t id[16], const uint8_t *cipher, size_t len,
const uint8_t nonce[24], const uint8_t mac[16], uint8_t *plain);
-/* Un adjunto para escribir: los bytes cifrados vienen de memoria o del archivo viejo (fd, off). */
+/* An attachment to write: the encrypted bytes come from memory or from the old file (fd, off). */
typedef struct { uint8_t id[16], nonce[24], mac[16]; const uint8_t *cipher; int srcfd; uint64_t off, len; } VAttOut;
-/* Guarda la bóveda en dirfd/name de forma atómica: escribe name.tmp-<pid>, fsync, deja la versión
- * anterior como name.bak (enlace duro, reemplazado atómicamente) y renombra. h->saved y h->counter
- * se actualizan. Devuelve VF_OK o VF_EIO. */
+/* Saves the vault in dirfd/name atomically: writes name.tmp-<pid>, fsync, keeps the previous
+ * version as name.bak (hard link, replaced atomically) and renames. h->saved and h->counter
+ * are updated. Returns VF_OK or VF_EIO. */
int vf_save(int dirfd, const char *name, VHeader *h, const uint8_t vk[32], const uint8_t *plain, size_t plen,
const VAttOut *atts, int natts);
-/* Lo mismo pero a un fd ya abierto (exportar una copia): sin .bak ni renombrar. */
+/* Same but to an already open fd (exporting a copy): no .bak and no rename. */
int vf_write_fd(int fd, VHeader *h, const uint8_t vk[32], const uint8_t *plain, size_t plen, const VAttOut *atts, int natts);
-/* Cabecera nueva (id al azar). */
+/* New header (random id). */
void vf_header_new(VHeader *h);
-/* BLAKE2b-256 de un archivo llave. */
+/* BLAKE2b-256 of a key file. */
void vf_keyfile_hash(const uint8_t *data, size_t len, uint8_t out[32]);
-/* Clave de recuperación nueva: 40 caracteres base32 de Crockford en 8 grupos ("ABCDE-FGHJK-…"). */
+/* New recovery key: 40 Crockford base32 characters in 8 groups ("ABCDE-FGHJK-…"). */
void vf_recovery_new(char out[48]);
-/* Parámetros de Argon2id para tardar unos target_ms en esta máquina (mide). */
+/* Argon2id parameters to take about target_ms on this machine (measures). */
void vf_calibrate(int target_ms, VKdf *out, int *measured_ms);
-/* Deriva con Argon2id (memoria en smem). 0 bien. */
+/* Derives with Argon2id (memory in smem). 0 ok. */
int vf_argon2id(const uint8_t *pass, size_t plen, const uint8_t salt[16], const VKdf *p, uint8_t out[32]);
const char *vf_strerror(int err);
diff --git a/server/src/vault/vgen.c b/server/src/vault/vgen.c
index 0cb4f6c..5c06e43 100644
--- a/server/src/vault/vgen.c
+++ b/server/src/vault/vgen.c
@@ -1,4 +1,4 @@
-/* vgen.c — generador y fuerza de contraseñas (ver vgen.h). */
+/* vgen.c — password generator and strength (see vgen.h). */
#include "vgen.h"
#include "vcrypto.h"
#include "smem.h"
@@ -15,7 +15,7 @@ static const char **words;
static size_t nwords;
static const char *common_buf;
static size_t common_len;
-/* índice de la lista común: comienzo de cada línea (la lista está en orden de popularidad) */
+/* index of the common list: start of each line (the list is in popularity order) */
static const char **common;
static size_t ncommon;
@@ -42,7 +42,7 @@ void vg_set_lists(const char *w, size_t wlen, const char *c, size_t clen) {
common_len = clen;
ncommon = split_lines(c, clen, &common);
common_index();
- /* las palabras de la EFF: se terminan con '\n'; las copiamos sin él a un bloque propio */
+ /* the EFF words: they end with '\n'; we copy them without it into our own block */
for (size_t i = 0; i < nwords; i++) {
size_t l = line_len(words[i], w + wlen);
char *s = malloc(l + 1);
@@ -106,7 +106,7 @@ int vg_generate(const VGenOpts *o, char *out, size_t cap, double *bits) {
for (int tries = 0; tries < 1000; tries++) {
for (int i = 0; i < len; i++) out[i] = pool[rnd_below((uint32_t)pn)];
out[len] = 0;
- int ok = 1; /* al menos uno de cada clase pedida */
+ int ok = 1; /* at least one of each requested class */
for (int c = 0; c < ncls && ok; c++) if (!strpbrk(out, cls[c])) ok = 0;
if (ok || len < ncls) break;
}
@@ -115,11 +115,11 @@ int vg_generate(const VGenOpts *o, char *out, size_t cap, double *bits) {
return 0;
}
-/* ---- comunes ---- */
+/* ---- common ---- */
-/* tabla hash (direccionamiento abierto) de la lista común: búsqueda O(1) */
+/* hash table (open addressing) of the common list: O(1) lookup */
#define CHASH 32768
-static int32_t ctab[CHASH]; /* índice + 1, 0 = libre */
+static int32_t ctab[CHASH]; /* index + 1, 0 = free */
static uint32_t fnv(const char *s, size_t n) {
uint32_t h = 2166136261u;
@@ -157,7 +157,7 @@ int vg_common_rank(const char *pw) {
low[n] = 0;
int r = common_exact(pw, n);
if (!r) r = common_exact(low, n);
- /* sin lo de atrás que suele agregarse: password1!, qwerty2024 */
+ /* without the trailing part people usually add: password1!, qwerty2024 */
size_t m = n;
while (m > 3 && (isdigit((unsigned char)low[m - 1]) || ispunct((unsigned char)low[m - 1]))) m--;
if (!r && m < n) r = common_exact(low, m);
@@ -168,7 +168,7 @@ int vg_common_rank(const char *pw) {
}
unleet[m] = 0;
r = common_exact(unleet, m);
- if (!r) { /* 1 también puede ser l */
+ if (!r) { /* 1 can also be l */
for (size_t i = 0; i < m; i++) if (low[i] == '1') unleet[i] = 'l';
r = common_exact(unleet, m);
}
@@ -178,7 +178,7 @@ int vg_common_rank(const char *pw) {
return r;
}
-/* ---- fuerza (estimación simple al estilo zxcvbn: patrones que bajan la entropía) ---- */
+/* ---- strength (simple zxcvbn-style estimate: patterns that lower entropy) ---- */
static const char *ROWS[] = { "1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm", "qwertzuiop", "azertyuiop", NULL };
@@ -213,7 +213,7 @@ int vg_strength(const char *pw, double *bits_out) {
if (i && keyboard_adjacent(pw[i], pw[i - 1])) { bits += 2; continue; } /* qwerty */
bits += per;
}
- /* años (19xx/20xx) y fechas cuentan poco */
+ /* years (19xx/20xx) and dates count for little */
for (size_t i = 0; i + 4 <= n; i++)
if ((!strncmp(pw + i, "19", 2) || !strncmp(pw + i, "20", 2)) && isdigit((unsigned char)pw[i + 2]) && isdigit((unsigned char)pw[i + 3])) { bits -= 2 * per - 7; break; }
int rank = vg_common_rank(pw);
@@ -227,7 +227,7 @@ int vg_strength(const char *pw, double *bits_out) {
return 4;
}
-/* ---- HIBP local ---- */
+/* ---- local HIBP ---- */
long vg_hibp_lookup(int fd, const char *pw) {
struct stat st;
@@ -240,7 +240,7 @@ long vg_hibp_lookup(int fd, const char *pw) {
char buf[256];
for (int iter = 0; iter < 64 && lo < hi; iter++) {
off_t mid = lo + (hi - lo) / 2;
- /* ir al comienzo de la línea siguiente a mid (o mid si es 0) */
+ /* go to the start of the line after mid (or mid if it is 0) */
ssize_t r = pread(fd, buf, sizeof buf - 1, mid);
if (r <= 0) break;
buf[r] = 0;
@@ -258,7 +258,7 @@ long vg_hibp_lookup(int fd, const char *pw) {
if (c == 0) return buf[40] == ':' ? strtol(buf + 41, NULL, 10) : 1;
if (c < 0) lo = start + 1; else hi = mid;
}
- /* la búsqueda puede saltear la primera línea: mirarla aparte */
+ /* the search may skip the first line: check it separately */
ssize_t r = pread(fd, buf, sizeof buf - 1, 0);
if (r >= 41) { buf[r] = 0; if (!strncasecmp(buf, hex, 40)) return strtol(buf + 41, NULL, 10); }
return 0;
diff --git a/server/src/vault/vgen.h b/server/src/vault/vgen.h
index 0157fc2..ecedfad 100644
--- a/server/src/vault/vgen.h
+++ b/server/src/vault/vgen.h
@@ -1,7 +1,7 @@
-/* vgen.h — generador de contraseñas y frases de contraseña, y la estimación de fuerza que usa el
- * informe de seguridad. Todo sin red: la «filtración» se comprueba contra la lista de las 10 000
- * contraseñas más comunes que viene con LordOS (y, si el usuario lo elige, contra un archivo
- * local de Have I Been Pwned: SHA-1 ordenado por hash, búsqueda binaria en el archivo). */
+/* vgen.h — password and passphrase generator, and the strength estimate used by the
+ * security report. All offline: the "breach" check runs against the list of the 10,000
+ * most common passwords shipped with LordOS (and, if the user chooses, against a local
+ * Have I Been Pwned file: SHA-1 sorted by hash, binary search in the file). */
#ifndef LORD_VAULT_VGEN_H
#define LORD_VAULT_VGEN_H
@@ -9,24 +9,24 @@
#include <stdint.h>
typedef struct {
- int length; /* contraseña: 4–128 */
+ int length; /* password: 4–128 */
int upper, lower, digits, symbols;
- int no_ambiguous; /* sin Il1O0o */
- int words; /* frase: 3–12 palabras (0 = contraseña) */
- char sep[8]; /* separador de la frase ("-") */
- int capitalize, add_digit; /* frase: Mayúscula Inicial, un número en una palabra */
+ int no_ambiguous; /* without Il1O0o */
+ int words; /* passphrase: 3–12 words (0 = password) */
+ char sep[8]; /* passphrase separator ("-") */
+ int capitalize, add_digit; /* passphrase: Capitalize Words, a number in one word */
} VGenOpts;
-/* Listas embebidas (palabras de la EFF y contraseñas comunes), una por línea. */
+/* Embedded lists (EFF words and common passwords), one per line. */
void vg_set_lists(const char *words, size_t wlen, const char *common, size_t clen);
-int vg_generate(const VGenOpts *o, char *out, size_t cap, double *bits); /* 0 bien */
-/* Fuerza: 0 (muy débil) – 4 (muy fuerte) y bits estimados. */
+int vg_generate(const VGenOpts *o, char *out, size_t cap, double *bits); /* 0 on success */
+/* Strength: 0 (very weak) – 4 (very strong) and estimated bits. */
int vg_strength(const char *pw, double *bits);
-/* Posición en la lista de comunes (1 = la más común) o 0 si no está (también prueba sin
- * mayúsculas, sin números/símbolos al final y sin «leet»: p4ssw0rd → password). */
+/* Position in the common list (1 = the most common) or 0 if absent (also tries without
+ * capitals, without trailing digits/symbols and without "leet": p4ssw0rd → password). */
int vg_common_rank(const char *pw);
-/* Archivo HIBP local (fd de «pwned-passwords-sha1-ordered-by-hash», líneas "HASH:veces").
- * Devuelve las veces que aparece, 0 si no, -1 si el archivo no sirve. */
+/* Local HIBP file (fd of "pwned-passwords-sha1-ordered-by-hash", lines "HASH:count").
+ * Returns the number of times it appears, 0 if not, -1 if the file is unusable. */
long vg_hibp_lookup(int fd, const char *pw);
size_t vg_word_count(void);
diff --git a/server/src/vault/vimport.c b/server/src/vault/vimport.c
index 589f391..20520e7 100644
--- a/server/src/vault/vimport.c
+++ b/server/src/vault/vimport.c
@@ -47,7 +47,7 @@ static void free_entry(ImpEntry *e) {
memset(e, 0, sizeof *e);
}
-/* saca la última entrada (una fila que no se importa) */
+/* removes the last entry (a row that is not imported) */
static void drop_last(ImpList *l) { if (l->n) free_entry(&l->v[--l->n]); }
void imp_free(ImpList *l) {
@@ -57,10 +57,10 @@ void imp_free(ImpList *l) {
char err[sizeof l->err];
memcpy(err, l->err, sizeof err);
memset(l, 0, sizeof *l);
- memcpy(l->err, err, sizeof err); /* el código de error sobrevive a imp_free */
+ memcpy(l->err, err, sizeof err); /* the error code survives imp_free */
}
-/* ---- utilidades ---- */
+/* ---- utilities ---- */
static int64_t days_from_civil(int64_t y, unsigned m, unsigned d) {
y -= m <= 2;
@@ -119,7 +119,7 @@ static int add_field(ImpEntry *e, const char *k, const char *v, int type) {
return 0;
}
-/* separa por cualquiera de seps, recorta espacios, saltea vacíos */
+/* splits on any of seps, trims spaces, skips empties */
static int split_add(char ***arr, int *n, const char *s, const char *seps) {
while (s && *s) {
while (*s && (strchr(seps, *s) || *s == ' ')) s++;
@@ -138,7 +138,7 @@ static int split_add(char ***arr, int *n, const char *s, const char *seps) {
return 0;
}
-/* "https://www.ejemplo.com:8080/x" → "ejemplo.com" (título de los CSV de navegadores) */
+/* "https://www.example.com:8080/x" → "example.com" (title for the browser CSVs) */
static char *host_of(const char *url) {
if (!url || !*url) return NULL;
const char *p = strstr(url, "://");
@@ -154,7 +154,7 @@ static char *host_of(const char *url) {
static int istrue(const char *s) { return s && (!strcmp(s, "1") || !strcasecmp(s, "true") || !strcasecmp(s, "yes")); }
-/* ---- detección ---- */
+/* ---- detection ---- */
static int csv_kind(const CsvRow *h) {
#define HAS(x) (csv_col(h, x) >= 0)
@@ -236,7 +236,7 @@ static int parse_csv(int kind, const uint8_t *data, size_t len, ImpList *l) {
}
int rc = 0, nr;
while ((nr = csv_next(&c, &r)) == 1) {
- /* una fila con todo vacío no es una entrada */
+ /* a row with everything empty is not an entry */
int any = 0;
for (int i = 0; i < r.n; i++) if (r.f[i][0]) any = 1;
if (!any) continue;
@@ -249,7 +249,7 @@ static int parse_csv(int kind, const uint8_t *data, size_t len, ImpList *l) {
bad |= set(&e->notes, csv_get(&r, k.notes));
bad |= set(&e->otp, csv_get(&r, k.totp));
if (kind == IMP_BITWARDEN_CSV) {
- /* varias URIs separadas por coma; los campos son líneas "nombre: valor" */
+ /* several URIs separated by commas; the fields are "name: value" lines */
char **u = NULL;
int nu = 0;
bad |= split_add(&u, &nu, csv_get(&r, k.url), ",\n");
@@ -276,12 +276,12 @@ static int parse_csv(int kind, const uint8_t *data, size_t len, ImpList *l) {
bad |= set(&e->url, csv_get(&r, k.url));
}
if (kind == IMP_KEEPASSXC_CSV) {
- /* "Root/Internet/Bancos": el primer componente es la carpeta raíz de la base */
+ /* "Root/Internet/Banks": the first component is the root folder of the database */
const char *g = csv_get(&r, k.group);
const char *slash = strchr(g, '/');
g = slash ? slash + 1 : "";
if (!strcmp(g, "Recycle Bin") || !strncmp(g, "Recycle Bin/", 12) || !strcmp(g, "Papelera") || !strncmp(g, "Papelera/", 9)) {
- drop_last(l); /* lo borrado no se importa */
+ drop_last(l); /* deleted items are not imported */
continue;
}
bad |= set(&e->group, g);
@@ -293,7 +293,7 @@ static int parse_csv(int kind, const uint8_t *data, size_t len, ImpList *l) {
e->modified = (int64_t)(strtod(csv_get(&r, k.modified), NULL) / 1000);
if (e->created < 0) e->created = 0;
if (e->modified < 0) e->modified = 0;
- /* las entradas del "Never save" de Firefox vienen sin contraseña: igual se importan */
+ /* Firefox "Never save" entries come without a password: they are imported anyway */
}
if (kind == IMP_LORD_CSV) {
bad |= set(&e->group, csv_get(&r, k.group));
@@ -316,7 +316,7 @@ static int parse_csv(int kind, const uint8_t *data, size_t len, ImpList *l) {
sm_free(fk); sm_free(fv);
}
vj_free(&j);
- } /* campos ilegibles: se ignoran */
+ } /* unreadable fields: ignored */
}
}
if (kind == IMP_CHROME_CSV || kind == IMP_FIREFOX_CSV) {
@@ -360,7 +360,7 @@ static const char *folder_name(const Folder *f, int n, const char *id) {
return NULL;
}
-/* campo de un subobjeto de Bitwarden (card/identity/sshKey) como ImpField */
+/* field of a Bitwarden subobject (card/identity/sshKey) as an ImpField */
static int bw_sub(ImpEntry *e, const Vj *j, int o, const char *bw, const char *key, int type) {
char *v = vj_gets(j, o, bw);
int r = add_field(e, key, v, type);
@@ -456,14 +456,14 @@ static int parse_bitwarden(const uint8_t *data, size_t len, ImpList *l) {
for (int f = 0; f < j.t[fields].count; f++) {
int fo = vj_at(&j, fields, f);
int ft = (int)vj_getn(&j, fo, "type", 0);
- if (ft == 3) continue; /* «vinculado»: apunta a otro campo */
+ if (ft == 3) continue; /* "linked": points to another field */
char *fn = vj_gets(&j, fo, "name"), *fv = vj_gets(&j, fo, "value");
if (!fv) { int vt = vj_get(&j, fo, "value"); if (vj_type(&j, vt) == VJ_TRUE) fv = sm_strdup("true"); else if (vj_type(&j, vt) == VJ_FALSE) fv = sm_strdup("false"); }
bad |= add_field(e, fn, fv, ft == 1 ? IMPF_HIDDEN : IMPF_TEXT);
sm_free(fn); sm_free(fv);
}
}
- /* vacíos → NULL, como en los CSV */
+ /* empties → NULL, as in the CSVs */
char **strs[] = { &e->title, &e->notes, &e->username, &e->password, &e->otp };
for (size_t k = 0; k < sizeof strs / sizeof *strs; k++) if (*strs[k] && !**strs[k]) { sm_free(*strs[k]); *strs[k] = NULL; }
if (bad) rc = fail(l, "memory");
@@ -478,7 +478,7 @@ out:
return rc;
}
-/* ---- entrada ---- */
+/* ---- entry point ---- */
int imp_parse(int kind, const uint8_t *data, size_t len, const char *password,
const uint8_t *keyfile, size_t kflen, ImpList *l) {
@@ -497,11 +497,11 @@ int imp_parse(int kind, const uint8_t *data, size_t len, const char *password,
default:
return fail(l, "unknown-format");
}
- if (rc) imp_free(l); /* nada a medias; l->err queda */
+ if (rc) imp_free(l); /* nothing half-done; l->err stays */
return rc;
}
-/* ---- exportar ---- */
+/* ---- export ---- */
static void csv_field(VjB *b, const char *s, int last) {
if (!s) s = "";
diff --git a/server/src/vault/vimport.h b/server/src/vault/vimport.h
index 7931520..c15f520 100644
--- a/server/src/vault/vimport.h
+++ b/server/src/vault/vimport.h
@@ -1,17 +1,17 @@
-/* vimport.h — importar y exportar contraseñas de otros gestores (ver docs/PASSWORDS.md,
- * «Importar y exportar»). Corre adentro de lord-vault (encerrado, sin red): el archivo llega como
- * bytes ya leídos de un fd que abrió lord-server. Todo lo que se arma (textos, adjuntos) va en la
- * arena de secretos (smem.h) y imp_free lo borra.
+/* vimport.h — import and export passwords from other managers (see docs/PASSWORDS.md,
+ * "Import and export"). Runs inside lord-vault (confined, no network): the file arrives as
+ * bytes already read from an fd opened by lord-server. Everything built (strings, attachments) goes in
+ * the secrets arena (smem.h) and imp_free wipes it.
*
- * Formatos:
- * - KeePass/KeePassXC KDBX 4.x (lector propio: Argon2d/Argon2id/AES-KDF, AES-256-CBC o ChaCha20,
- * bloques HMAC-SHA256, gzip, flujo interno ChaCha20/Salsa20 y el XML de KeePass), con
- * contraseña y/o archivo llave; y el CSV que exporta KeePassXC.
- * - Bitwarden JSON (sin cifrar) y CSV.
+ * Formats:
+ * - KeePass/KeePassXC KDBX 4.x (own reader: Argon2d/Argon2id/AES-KDF, AES-256-CBC or ChaCha20,
+ * HMAC-SHA256 blocks, gzip, ChaCha20/Salsa20 inner stream and the KeePass XML), with
+ * password and/or key file; and the CSV exported by KeePassXC.
+ * - Bitwarden JSON (unencrypted) and CSV.
* - Chrome and other Chromium-based browsers, Firefox, and the generic
* Title,URL,Username,Password,Notes,OTPAuth CSV of other password managers.
- * - CSV propio de LordOS (el que escribe exp_csv).
- * Los parsers son robustos ante archivos rotos o maliciosos (pruebas «fuzz-ish» en tests/). */
+ * - LordOS own CSV (the one exp_csv writes).
+ * The parsers are robust against broken or malicious files ("fuzz-ish" tests in tests/). */
#ifndef LORD_VAULT_VIMPORT_H
#define LORD_VAULT_VIMPORT_H
@@ -20,7 +20,7 @@
enum {
IMP_UNKNOWN = 0,
- IMP_KDBX, /* KeePass 2.x / KeePassXC, .kdbx (versión 4; 3.1 si se puede) */
+ IMP_KDBX, /* KeePass 2.x / KeePassXC, .kdbx (version 4; 3.1 if possible) */
IMP_KEEPASSXC_CSV, /* "Group","Title","Username","Password","URL","Notes","TOTP","Icon","Last Modified","Created" */
IMP_BITWARDEN_JSON, /* {"encrypted":false,"folders":[...],"items":[...]} */
IMP_BITWARDEN_CSV, /* folder,favorite,type,name,notes,fields,reprompt,login_uri,login_username,login_password,login_totp */
@@ -30,7 +30,7 @@ enum {
IMP_LORD_CSV, /* category,title,username,password,url,notes,totp,tags,favorite,fields,urls,kind,created,modified (exp_csv) */
};
-/* Tipo de campo extra (coincide con los de la bóveda: vmodel.h) */
+/* Extra field type (matches the vault's: vmodel.h) */
enum { IMPF_TEXT = 0, IMPF_HIDDEN, IMPF_URL, IMPF_DATE, IMPF_NUMBER, IMPF_TOTP };
typedef struct { char *key; char *value; int type; } ImpField; /* IMPF_* */
@@ -38,42 +38,42 @@ typedef struct { char *name; uint8_t *data; size_t len; } ImpAttach;
typedef struct {
char *title, *username, *password, *url, *notes;
- char *otp; /* URI otpauth:// o el secreto en base32 tal cual venía */
- char *group; /* ruta de la categoría/carpeta, separada por '/' ("Internet/Bancos"); NULL = sin */
- char *kind; /* pista del tipo: "login", "card", "identity", "note", "wifi", "ssh"… o NULL */
+ char *otp; /* otpauth:// URI or the base32 secret exactly as it came */
+ char *group; /* category/folder path, separated by '/' ("Internet/Banks"); NULL = none */
+ char *kind; /* type hint: "login", "card", "identity", "note", "wifi", "ssh"… or NULL */
char **tags; int ntags;
- char **urls; int nurls; /* URLs adicionales (Bitwarden trae varias) */
+ char **urls; int nurls; /* additional URLs (Bitwarden carries several) */
ImpField *fields; int nfields;
ImpAttach *atts; int natts;
- int64_t created, modified; /* segundos Unix; 0 = no se sabe */
+ int64_t created, modified; /* Unix seconds; 0 = unknown */
int favorite;
} ImpEntry;
typedef struct {
ImpEntry *v; int n, cap;
- char **groups; int ngroups; /* carpetas que existían aunque estén vacías (KDBX, Bitwarden) */
- char err[160]; /* código corto en inglés para la interfaz: "bad-password", "unsupported-cipher"… */
+ char **groups; int ngroups; /* folders that existed even if empty (KDBX, Bitwarden) */
+ char err[160]; /* short English code for the UI: "bad-password", "unsupported-cipher"… */
} ImpList;
-/* Adivina el formato por el contenido (y el nombre del archivo, opcional). */
+/* Guesses the format from the content (and optionally the file name). */
int imp_detect(const uint8_t *data, size_t len, const char *name_hint);
-/* Lee el archivo. password/keyfile solo para KDBX (NULL si no hay). 0 bien; -1 con l->err:
- * "bad-password" (KDBX: la clave compuesta no abre), "corrupt", "truncated",
+/* Reads the file. password/keyfile only for KDBX (NULL if none). 0 ok; -1 with l->err:
+ * "bad-password" (KDBX: the composite key does not open it), "corrupt", "truncated",
* "unsupported-version", "unsupported-cipher", "unsupported-kdf", "encrypted-export"
- * (Bitwarden cifrado: pedir el JSON sin cifrar), "empty", "too-big", "memory", "bad-keyfile" (archivo llave XML de KeePass con
- * Hash que no coincide). */
+ * (encrypted Bitwarden: ask for the unencrypted JSON), "empty", "too-big", "memory", "bad-keyfile" (KeePass XML key file with a
+ * mismatching Hash). */
int imp_parse(int kind, const uint8_t *data, size_t len, const char *password,
const uint8_t *keyfile, size_t kflen, ImpList *l);
-void imp_free(ImpList *l); /* borra y libera todo (también l->v) */
+void imp_free(ImpList *l); /* wipes and frees everything (including l->v) */
-/* CSV propio (IMP_LORD_CSV), con encabezado; las entradas como las de ImpList. *out en smem. */
+/* LordOS own CSV (IMP_LORD_CSV), with header; entries as in ImpList. *out in smem. */
int exp_csv(const ImpList *l, char **out, size_t *outlen);
-/* Utilidades compartidas */
+/* Shared utilities */
char *imp_strdup(const char *s); /* en smem */
-ImpEntry *imp_add(ImpList *l); /* entrada nueva en cero, o NULL */
-/* Fecha ISO 8601 ("2024-03-05T10:20:30Z", con fracción u hora local que se toma como UTC; o solo
- * la fecha) → segundos Unix; 0 si no se entiende. */
+ImpEntry *imp_add(ImpList *l); /* new zeroed entry, or NULL */
+/* ISO 8601 date ("2024-03-05T10:20:30Z", with fraction or local time taken as UTC; or just
+ * the date) → Unix seconds; 0 if not understood. */
int64_t imp_parse_iso(const char *s);
#endif
diff --git a/server/src/vault/vjson.c b/server/src/vault/vjson.c
index be0fda9..29ed364 100644
--- a/server/src/vault/vjson.c
+++ b/server/src/vault/vjson.c
@@ -1,4 +1,4 @@
-/* vjson.c — JSON en la arena de secretos (ver vjson.h). */
+/* vjson.c — JSON in the secrets arena (see vjson.h). */
#include "vjson.h"
#include "smem.h"
@@ -7,7 +7,7 @@
#include <stdlib.h>
#include <string.h>
-/* ================= lector ================= */
+/* ================= reader ================= */
typedef struct { Vj *j; size_t p; int depth; } P;
@@ -40,7 +40,7 @@ static int parse_value(P *q);
static int parse_string(P *q) {
const char *s = q->j->s;
size_t len = q->j->len;
- q->p++; /* comilla */
+ q->p++; /* quote */
int k = tok_new(q, VJ_STR);
if (k < 0) return -1;
while (q->p < len) {
@@ -171,7 +171,7 @@ int vj_streq(const Vj *j, int tok, const char *s) {
if (vj_type(j, tok) != VJ_STR) return 0;
const VjTok *t = &j->t[tok];
size_t n = strlen(s);
- /* comparación rápida si no hay escapes */
+ /* fast comparison if there are no escapes */
if (t->end - t->start == n && !memchr(j->s + t->start, '\\', n)) return !memcmp(j->s + t->start, s, n);
char *d = vj_str(j, tok);
int r = d && !strcmp(d, s);
@@ -201,7 +201,7 @@ static size_t put_utf8(char *d, unsigned cp) {
return 4;
}
-/* Saca los escapes de s[a..b) en d (que tiene lugar para b-a bytes: nunca crece). */
+/* Unescapes s[a..b) into d (which has room for b-a bytes: it never grows). */
static size_t unescape(const char *s, size_t a, size_t b, char *d) {
size_t o = 0;
for (size_t i = a; i < b; i++) {
@@ -223,7 +223,7 @@ static size_t unescape(const char *s, size_t a, size_t b, char *d) {
if (lo >= 0xdc00 && lo < 0xe000) { cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); i += 6; }
else cp = 0xfffd;
} else if (cp >= 0xd800 && cp < 0xe000) cp = 0xfffd;
- if (cp == 0) cp = 0xfffd; /* sin NUL adentro de los textos */
+ if (cp == 0) cp = 0xfffd; /* no NUL inside texts */
o += put_utf8(d + o, cp);
break;
}
@@ -248,7 +248,7 @@ size_t vj_strbuf(const Vj *j, int tok, char *buf, size_t n) {
char *d = vj_str(j, tok);
if (!d) return 0;
size_t l = strlen(d);
- if (l >= n) { /* recortar sin partir un carácter UTF-8 */
+ if (l >= n) { /* truncate without splitting a UTF-8 character */
l = n - 1;
while (l > 0 && ((unsigned char)d[l] & 0xc0) == 0x80) l--;
}
@@ -283,7 +283,7 @@ size_t vj_getsbuf(const Vj *j, int obj, const char *key, char *buf, size_t n) {
double vj_getn(const Vj *j, int obj, const char *key, double def) { return vj_num(j, vj_get(j, obj, key), def); }
int vj_getb(const Vj *j, int obj, const char *key, int def) { return vj_bool(j, vj_get(j, obj, key), def); }
-/* ================= escritor ================= */
+/* ================= writer ================= */
void vb_init(VjB *b) { memset(b, 0, sizeof *b); b->first[0] = 1; }
void vb_free(VjB *b) { sm_free(b->p); memset(b, 0, sizeof *b); }
@@ -321,7 +321,7 @@ void vb_strn(VjB *b, const char *s, size_t n) {
else if (c == '\t') { *d++ = '\\'; *d++ = 't'; }
else if (c < 0x20 || c == 0x7f) { snprintf(d, 7, "\\u%04x", c); d += 6; }
else if (c >= 0x80) {
- /* UTF-8 válido pasa tal cual; un byte suelto se reemplaza por U+FFFD */
+ /* valid UTF-8 passes through as-is; a stray byte is replaced by U+FFFD */
int len = c >= 0xf0 && c < 0xf5 ? 4 : c >= 0xe0 ? 3 : c >= 0xc2 && c < 0xe0 ? 2 : 0;
int ok = len && i + (size_t)len <= n;
for (int k = 1; ok && k < len; k++) if (((unsigned char)s[i + k] & 0xc0) != 0x80) ok = 0;
diff --git a/server/src/vault/vjson.h b/server/src/vault/vjson.h
index 492be65..114e3cc 100644
--- a/server/src/vault/vjson.h
+++ b/server/src/vault/vjson.h
@@ -1,10 +1,10 @@
-/* vjson.h — JSON adentro de lord-vault sin pasar por el montón de la libc: un lector que marca
- * tokens sobre el texto (sin copiarlo) y un escritor que crece en la arena de secretos (smem.h).
- * Lo usan el protocolo con lord-server/la app, la carga útil de la bóveda y los importadores.
+/* vjson.h — JSON inside lord-vault without going through the libc heap: a reader that marks
+ * tokens over the text (without copying it) and a writer that grows in the secrets arena (smem.h).
+ * Used by the protocol with lord-server/the app, the vault payload and the importers.
*
- * Lector: vj_parse arma un arreglo de tokens en orden; cada uno sabe dónde termina su subárbol
- * (next), así recorrer un objeto es: for (k = o + 1; k < t[o].next; k = t[k + 1].next) { clave k,
- * valor k + 1 }. Estricto (RFC 8259), con un tope de profundidad (64). */
+ * Reader: vj_parse builds an array of tokens in order; each one knows where its subtree ends
+ * (next), so walking an object is: for (k = o + 1; k < t[o].next; k = t[k + 1].next) { key k,
+ * value k + 1 }. Strict (RFC 8259), with a depth limit (64). */
#ifndef LORD_VAULT_VJSON_H
#define LORD_VAULT_VJSON_H
@@ -13,46 +13,46 @@
enum { VJ_OBJ = 1, VJ_ARR, VJ_STR, VJ_NUM, VJ_TRUE, VJ_FALSE, VJ_NULL };
-typedef struct { uint8_t type; uint32_t start, end; int next; int count; } VjTok; /* start/end: bytes (STR sin comillas) */
+typedef struct { uint8_t type; uint32_t start, end; int next; int count; } VjTok; /* start/end: bytes (STR without quotes) */
typedef struct { const char *s; size_t len; VjTok *t; int n, cap; } Vj;
-int vj_parse(Vj *j, const char *s, size_t len); /* 0 bien; tokens en smem */
+int vj_parse(Vj *j, const char *s, size_t len); /* 0 on success; tokens in smem */
void vj_free(Vj *j);
-int vj_get(const Vj *j, int obj, const char *key); /* token del valor, o -1 */
-int vj_at(const Vj *j, int arr, int i); /* i-ésimo elemento, o -1 */
-int vj_type(const Vj *j, int tok); /* 0 si tok es -1 */
-char *vj_str(const Vj *j, int tok); /* texto sin escapes, en smem (NULL si no es STR) */
-size_t vj_strbuf(const Vj *j, int tok, char *buf, size_t n); /* copia acotada; devuelve el largo */
+int vj_get(const Vj *j, int obj, const char *key); /* value token, or -1 */
+int vj_at(const Vj *j, int arr, int i); /* i-th element, or -1 */
+int vj_type(const Vj *j, int tok); /* 0 if tok is -1 */
+char *vj_str(const Vj *j, int tok); /* text without escapes, in smem (NULL if not STR) */
+size_t vj_strbuf(const Vj *j, int tok, char *buf, size_t n); /* bounded copy; returns the length */
int vj_streq(const Vj *j, int tok, const char *s);
double vj_num(const Vj *j, int tok, double def);
int vj_bool(const Vj *j, int tok, int def);
-/* atajos sobre un objeto */
+/* shortcuts on an object */
char *vj_gets(const Vj *j, int obj, const char *key);
size_t vj_getsbuf(const Vj *j, int obj, const char *key, char *buf, size_t n);
double vj_getn(const Vj *j, int obj, const char *key, double def);
int vj_getb(const Vj *j, int obj, const char *key, int def);
-/* Escritor (en smem). Las comas las pone quien llama, salvo con los vb_k* («"clave":valor» con
- * coma si hace falta: se lleva la cuenta por nivel con vb_open/vb_close). */
+/* Writer (in smem). The caller adds the commas, except with vb_k* ("key":value with a
+ * comma when needed: tracked per level with vb_open/vb_close). */
typedef struct { char *p; size_t n, cap; int oom; uint8_t first[64]; int depth; } VjB;
void vb_init(VjB *b);
-void vb_free(VjB *b); /* borra y libera */
+void vb_free(VjB *b); /* wipes and frees */
void vb_raw(VjB *b, const char *s);
void vb_rawn(VjB *b, const char *s, size_t n);
-void vb_str(VjB *b, const char *s); /* "texto" con escapes; NULL → null */
+void vb_str(VjB *b, const char *s); /* "text" with escapes; NULL → null */
void vb_strn(VjB *b, const char *s, size_t n);
void vb_num(VjB *b, double v);
void vb_int(VjB *b, long long v);
-void vb_open(VjB *b, char c); /* '{' o '[' */
-void vb_close(VjB *b, char c); /* '}' o ']' */
-void vb_sep(VjB *b); /* coma si no es el primero del nivel */
+void vb_open(VjB *b, char c); /* '{' or '[' */
+void vb_close(VjB *b, char c); /* '}' or ']' */
+void vb_sep(VjB *b); /* comma if not the first of the level */
void vb_key(VjB *b, const char *k); /* vb_sep + "k": */
void vb_ks(VjB *b, const char *k, const char *v);
void vb_kn(VjB *b, const char *k, double v);
void vb_ki(VjB *b, const char *k, long long v);
void vb_kb(VjB *b, const char *k, int v);
-/* Base64 (RFC 4648) en smem */
+/* Base64 (RFC 4648) in smem */
char *b64_encode(const uint8_t *in, size_t n);
-uint8_t *b64_decode(const char *in, size_t n, size_t *outlen); /* acepta también base64url */
+uint8_t *b64_decode(const char *in, size_t n, size_t *outlen); /* also accepts base64url */
#endif
diff --git a/server/src/vault/vmodel.h b/server/src/vault/vmodel.h
index 7417ffd..a62f6f2 100644
--- a/server/src/vault/vmodel.h
+++ b/server/src/vault/vmodel.h
@@ -1,15 +1,15 @@
-/* vmodel.h — el contenido de una bóveda abierta, en la arena de secretos: entradas con sus campos,
- * etiquetas, adjuntos e historial, más las categorías, las etiquetas y los ajustes (que la
- * interfaz maneja como JSON y acá se guardan tal cual, validados).
+/* vmodel.h — the contents of an open vault, in the secrets arena: entries with their fields,
+ * tags, attachments and history, plus the categories, tags and settings (which the
+ * UI handles as JSON and which are stored here as-is, validated).
*
- * Contenido (JSON, versión 1):
+ * Contents (JSON, version 1):
* {"v":1,"meta":{…},"cats":[…],"tags":[…],"entries":[{
* "id":"<32 hex>","cat":"internet","title":"…","notes":"…","fav":true,"arch":false,
* "trash":0,"created":…,"modified":…,"pwch":…,"rotate":90,"tags":["…"],
* "f":[{"k":"username","t":"text","l":"…","v":"…"},…],
* "att":[{"id","name","size","mime","nonce","mac"}],
* "hist":[{"t":…,"title":…,"f":[…]}],"x":{…}}]}
- * Tipos de campo: text, hidden, url, date, number, file, totp, email, multiline, pin. */
+ * Field types: text, hidden, url, date, number, file, totp, email, multiline, pin. */
#ifndef LORD_VAULT_VMODEL_H
#define LORD_VAULT_VMODEL_H
@@ -28,45 +28,45 @@ typedef struct {
VAtt *att; int natt;
int fav, arch, rotate;
int64_t trash, created, modified, pwch;
- char *hist; /* JSON (arreglo) tal cual */
- char *x; /* JSON (objeto) extra: datos del llavero, etc. */
- char *fold; /* texto de búsqueda (minúsculas, sin tildes) */
- uint8_t pwhash[16]; /* BLAKE2b de la contraseña (para las repetidas); todo cero si no hay */
+ char *hist; /* JSON (array) as-is */
+ char *x; /* extra JSON (object): keyring data, etc. */
+ char *fold; /* search text (lowercase, no accents) */
+ uint8_t pwhash[16]; /* BLAKE2b of the password (to find duplicates); all zero if none */
} VEntry;
typedef struct {
VEntry **e; int n, cap;
- char *meta, *cats, *tags; /* JSON tal cual */
+ char *meta, *cats, *tags; /* JSON as-is */
int dirty;
} VModel;
-int vm_load(VModel *m, const char *json, size_t len); /* 0 bien */
+int vm_load(VModel *m, const char *json, size_t len); /* 0 on success */
void vm_init(VModel *m);
void vm_free(VModel *m);
-char *vm_dump(const VModel *m, size_t *len); /* contenido JSON en smem */
+char *vm_dump(const VModel *m, size_t *len); /* JSON contents in smem */
VEntry *vm_find(const VModel *m, const char *id);
int vm_index(const VModel *m, const char *id);
-/* Crea o actualiza desde el JSON de la interfaz (objeto en j/tok). Los campos ocultos que llegan
- * con "keep":true conservan el valor de antes. Guarda historial si cambió algo. *out = la entrada. */
+/* Creates or updates from the UI JSON (object in j/tok). Hidden fields that arrive
+ * with "keep":true keep their previous value. Saves history if anything changed. *out = the entry. */
int vm_upsert(VModel *m, const Vj *j, int tok, VEntry **out, char *err, size_t errn);
-int vm_remove(VModel *m, const char *id); /* borrar del todo (vaciar la papelera) */
+int vm_remove(VModel *m, const char *id); /* delete permanently (empty the trash) */
void vm_entry_free(VEntry *e);
-const char *vm_field(const VEntry *e, const char *key); /* valor del primer campo con esa clave */
-const char *vm_field_type(const VEntry *e, const char *type); /* valor del primer campo de ese tipo */
-void vm_refresh(VEntry *e); /* recalcula fold y pwhash */
+const char *vm_field(const VEntry *e, const char *key); /* value of the first field with that key */
+const char *vm_field_type(const VEntry *e, const char *type); /* value of the first field of that type */
+void vm_refresh(VEntry *e); /* recomputes fold and pwhash */
void vm_new_id(char out[33]);
-/* JSON de una entrada (para la interfaz). reveal: 0 = los ocultos sin valor ("has":true),
- * 1 = con valor. Con hist incluye el historial (los valores ocultos del historial solo con reveal). */
+/* JSON of an entry (for the UI). reveal: 0 = hidden fields without value ("has":true),
+ * 1 = with value. With hist it includes the history (hidden history values only with reveal). */
void vm_entry_json(VjB *b, const VEntry *e, int reveal, int hist);
-/* Lista liviana de todas las entradas (sin secretos): id, cat, title, sub, url, fav, arch, trash,
- * modified, tags, totp (si tiene), natt, kind de la contraseña (edad), expira. */
+/* Lightweight list of all entries (no secrets): id, cat, title, sub, url, fav, arch, trash,
+ * modified, tags, totp (if any), natt, password kind (age), expires. */
void vm_list_json(VjB *b, const VModel *m);
-/* Búsqueda: ids que contienen todas las palabras de q (sin tildes ni mayúsculas), en el orden de
- * la lista; scope: "all" (sin papelera), "trash", "archived"… lo filtra la interfaz. */
+/* Search: ids that contain all the words of q (ignoring accents and case), in list
+ * order; scope: "all" (no trash), "trash", "archived"… filtered by the UI. */
void vm_search_json(VjB *b, const VModel *m, const char *q, int max);
-/* Pasa a minúsculas y saca tildes de un texto UTF-8 (en smem). */
+/* Lowercases and strips accents from a UTF-8 text (in smem). */
char *vm_fold(const char *s);
#endif
diff --git a/server/src/vault/vstb.c b/server/src/vault/vstb.c
index 266a572..3034e39 100644
--- a/server/src/vault/vstb.c
+++ b/server/src/vault/vstb.c
@@ -1,4 +1,4 @@
-/* vstb.c — stb_image con la memoria de smem (ver vstb.h). */
+/* vstb.c — stb_image using smem memory (see vstb.h). */
#include "vstb.h"
#include "smem.h"
@@ -42,7 +42,7 @@ uint8_t *vstb_inflate_raw(const uint8_t *in, size_t len, size_t max, size_t *out
}
uint8_t *vstb_gunzip(const uint8_t *in, size_t len, size_t max, size_t *outlen) {
- /* cabecera de 10 bytes (1f 8b 08 flg mtime xfl os) + campos opcionales + deflate + crc32 + isize */
+ /* 10-byte header (1f 8b 08 flg mtime xfl os) + optional fields + deflate + crc32 + isize */
if (len < 18 || in[0] != 0x1f || in[1] != 0x8b || in[2] != 8) return NULL;
uint8_t flg = in[3];
size_t p = 10;
diff --git a/server/src/vault/vstb.h b/server/src/vault/vstb.h
index ed0f969..6138a2f 100644
--- a/server/src/vault/vstb.h
+++ b/server/src/vault/vstb.h
@@ -1,18 +1,18 @@
-/* vstb.h — stb_image (vendorizado) adentro de lord-vault, con la memoria en la arena de secretos
- * (smem.h): un KDBX descomprimido o la foto de un código QR nunca pasan por el montón de la libc.
- * Los símbolos de stb quedan estáticos (no chocan con los de ui/stb.c). */
+/* vstb.h — stb_image (vendored) inside lord-vault, with memory in the secrets arena
+ * (smem.h): a decompressed KDBX or the photo of a QR code never goes through the libc heap.
+ * The stb symbols stay static (they do not clash with those of ui/stb.c). */
#ifndef LORD_VAULT_VSTB_H
#define LORD_VAULT_VSTB_H
#include <stddef.h>
#include <stdint.h>
-/* deflate crudo (sin cabecera zlib) → bytes en smem (liberar con sm_free); NULL si es inválido o
- * pasa de max bytes. */
+/* raw deflate (no zlib header) → bytes in smem (free with sm_free); NULL if invalid or
+ * larger than max bytes. */
uint8_t *vstb_inflate_raw(const uint8_t *in, size_t len, size_t max, size_t *outlen);
-/* gzip (RFC 1952, como el de KDBX) → bytes en smem; NULL si es inválido. */
+/* gzip (RFC 1952, like KDBX's) → bytes in smem; NULL if invalid. */
uint8_t *vstb_gunzip(const uint8_t *in, size_t len, size_t max, size_t *outlen);
-/* PNG o JPEG → píxeles 0xAARRGGBB en smem (w*h); NULL si no se puede (lado máximo 8192). */
+/* PNG or JPEG → 0xAARRGGBB pixels in smem (w*h); NULL on failure (max side 8192). */
uint32_t *vstb_decode_argb(const uint8_t *in, size_t len, int *w, int *h);
#endif
diff --git a/server/src/vault/vwire.c b/server/src/vault/vwire.c
index f8c2142..1a90dff 100644
--- a/server/src/vault/vwire.c
+++ b/server/src/vault/vwire.c
@@ -1,4 +1,4 @@
-/* vwire.c — mensajes del protocolo de lord-vault (ver vwire.h). */
+/* vwire.c — lord-vault protocol messages (see vwire.h). */
#include "vwire.h"
#include <errno.h>
@@ -34,7 +34,7 @@ int vw_send(int sock, uint32_t kind, uint32_t id, const char *json, size_t len,
ssize_t r;
do r = sendmsg(sock, &mh, MSG_NOSIGNAL); while (r < 0 && errno == EINTR);
if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
- /* socket lleno: esperar un poco (el otro lado lee en su hilo o su bucle) */
+ /* socket full: wait a bit (the other side reads in its thread or loop) */
struct timespec ts = { 0, 2000000 };
nanosleep(&ts, NULL);
int tries = 0;
@@ -61,7 +61,7 @@ void vw_rx_free(VwRx *rx, const VwAlloc *a) {
memset(rx, 0, sizeof *rx);
}
-/* Lee un paquete. 1 paquete leído, 0 nada (EAGAIN), -1 cerrado/error */
+/* Reads one packet. 1 packet read, 0 nothing (EAGAIN), -1 closed/error */
static int read_packet(int sock, VwRx *rx, const VwAlloc *a, int flags) {
VHdr h;
char buf[VW_CHUNK];
@@ -81,7 +81,7 @@ static int read_packet(int sock, VwRx *rx, const VwAlloc *a, int flags) {
}
int bad = (size_t)r < sizeof h || h.len != (size_t)r - sizeof h || (mh.msg_flags & (MSG_TRUNC | MSG_CTRUNC));
if (!bad && rx->active && (h.id != rx->cur.id || h.kind != rx->cur.kind)) bad = 1;
- if (!bad && rx->active && nf) bad = 1; /* los fds solo en el primero */
+ if (!bad && rx->active && nf) bad = 1; /* fds only in the first one */
if (!bad && rx->cur.len + h.len > VW_MAX) bad = 1;
if (bad) {
for (int i = 0; i < nf; i++) close(fds[i]);
diff --git a/server/src/vault/vwire.h b/server/src/vault/vwire.h
index 785c748..d882c6d 100644
--- a/server/src/vault/vwire.h
+++ b/server/src/vault/vwire.h
@@ -1,17 +1,17 @@
-/* vwire.h — protocolo entre lord-vault y sus clientes (lord-server y la app Contraseñas).
+/* vwire.h — protocol between lord-vault and its clients (lord-server and the Passwords app).
*
- * Socket SOCK_SEQPACKET. Cada mensaje: VHdr + JSON (UTF-8). Lo que no entra en un paquete
- * (VW_CHUNK) se manda en varios con VWF_MORE, todos con el mismo id; el que recibe los junta. Los
- * fds (SCM_RIGHTS, hasta VW_MAX_FDS) van en el primer paquete. No se usan memfd: así el texto con
- * secretos nunca queda en memoria compartida (que podría ir al swap); del lado de lord-vault se
- * recibe directo en la arena de secretos (smem.h).
+ * SOCK_SEQPACKET socket. Each message: VHdr + JSON (UTF-8). What does not fit in one packet
+ * (VW_CHUNK) is sent in several with VWF_MORE, all with the same id; the receiver joins them. The
+ * fds (SCM_RIGHTS, up to VW_MAX_FDS) go in the first packet. memfd is not used: that way text with
+ * secrets never sits in shared memory (which could be swapped out); on the lord-vault side it is
+ * received directly into the secrets arena (smem.h).
*
- * Tipos (VHdr.kind):
- * VW_REQ cliente → lord-vault: {"op":"…", …} (id lo elige el cliente)
- * VW_REP lord-vault → cliente: {"ok":true,…} | {"error":"código"} (mismo id)
- * VW_EVT lord-vault → cliente: {"ev":"locked"|"changed"|"touch"|"keyring"…} (id 0)
- * VW_CTL lord-server → lord-vault, solo por el canal de control (fd 3): init, attach, lock-all,
- * session-password, fido-device, bus. La app nunca puede mandarlos. */
+ * Types (VHdr.kind):
+ * VW_REQ client → lord-vault: {"op":"…", …} (id chosen by the client)
+ * VW_REP lord-vault → client: {"ok":true,…} | {"error":"code"} (same id)
+ * VW_EVT lord-vault → client: {"ev":"locked"|"changed"|"touch"|"keyring"…} (id 0)
+ * VW_CTL lord-server → lord-vault, only over the control channel (fd 3): init, attach, lock-all,
+ * session-password, fido-device, bus. The app can never send them. */
#ifndef LORD_VAULT_VWIRE_H
#define LORD_VAULT_VWIRE_H
@@ -19,7 +19,7 @@
#include <stdint.h>
#define VW_CHUNK (32 * 1024)
-#define VW_MAX (64u << 20) /* mensaje más grande que se acepta */
+#define VW_MAX (64u << 20) /* largest message accepted */
#define VW_MAX_FDS 4
enum { VW_REQ = 1, VW_REP = 2, VW_EVT = 3, VW_CTL = 4 };
@@ -29,22 +29,22 @@ typedef struct { uint32_t kind, id, len, flags; } VHdr;
typedef struct {
uint32_t kind, id;
- char *json; size_t len; /* terminado en 0 */
+ char *json; size_t len; /* 0-terminated */
int fds[VW_MAX_FDS]; int nfds;
} VMsg;
-/* Asignador para lo recibido: en lord-vault, la arena de secretos; en lord-server, malloc. */
+/* Allocator for received data: in lord-vault, the secrets arena; in lord-server, malloc. */
typedef struct { void *(*alloc)(size_t); void *(*realloc)(void *, size_t); void (*free)(void *); } VwAlloc;
extern const VwAlloc vw_malloc;
int vw_send(int sock, uint32_t kind, uint32_t id, const char *json, size_t len, const int *fds, int nfds);
-/* Recibe un mensaje completo (bloquea hasta tenerlo). 0 bien, 1 fin, -1 error/inválido. */
+/* Receives a complete message (blocks until it has one). 0 ok, 1 end, -1 error/invalid. */
int vw_recv(int sock, VMsg *m, const VwAlloc *a);
-/* Recepción incremental para sockets no bloqueantes (lord-vault atiende varios canales):
- * vw_feed lee lo que haya; devuelve 1 si quedó un mensaje completo en *m, 0 si falta, -1 cerrado. */
+/* Incremental receive for non-blocking sockets (lord-vault serves several channels):
+ * vw_feed reads whatever is available; returns 1 if a complete message is in *m, 0 if incomplete, -1 closed. */
typedef struct { VMsg cur; size_t cap; int active; } VwRx;
int vw_feed(int sock, VwRx *rx, VMsg *m, const VwAlloc *a);
void vw_rx_free(VwRx *rx, const VwAlloc *a);
-void vw_msg_free(VMsg *m, const VwAlloc *a); /* borra el texto (puede tener secretos) y cierra los fds */
+void vw_msg_free(VMsg *m, const VwAlloc *a); /* wipes the text (may hold secrets) and closes the fds */
#endif
diff --git a/server/src/vault/xmlmini.c b/server/src/vault/xmlmini.c
index 203db52..02443bf 100644
--- a/server/src/vault/xmlmini.c
+++ b/server/src/vault/xmlmini.c
@@ -1,4 +1,4 @@
-/* xmlmini.c — lector de XML mínimo (ver xmlmini.h). */
+/* xmlmini.c — minimal XML reader (see xmlmini.h). */
#include "xmlmini.h"
#include "smem.h"
@@ -21,8 +21,8 @@ static size_t put_utf8(char *d, uint32_t cp) {
return 4;
}
-/* Agrega s[a..b) a *buf (con entidades si decode). El resultado nunca es más largo que la
- * entrada (una entidad ocupa al menos tanto como su UTF-8). */
+/* Appends s[a..b) to *buf (decoding entities if decode). The result is never longer than the
+ * input (an entity takes at least as much space as its UTF-8). */
static int append(char **buf, size_t *n, const char *s, size_t a, size_t b, int decode) {
char *d = sm_realloc(*buf, *n + (b - a) + 1);
if (!d) return -1;
@@ -87,7 +87,7 @@ static int skip_to(X *x, const char *w) {
return -1;
}
-/* <nombre atributos> o </nombre>: x->p en '<' */
+/* <name attributes> or </name>: x->p en '<' */
static int parse_tag(X *x, XNode **cur, XNode **root, int *depth) {
const char *s = x->s;
x->p++;
@@ -104,7 +104,7 @@ static int parse_tag(X *x, XNode **cur, XNode **root, int *depth) {
(*depth)--;
return 0;
}
- if (!*cur && *root) return -1; /* un segundo elemento raíz */
+ if (!*cur && *root) return -1; /* a second root element */
size_t a = x->p;
while (x->p < x->len && is_name(s[x->p])) x->p++;
if (x->p == a) return -1;
@@ -120,7 +120,7 @@ static int parse_tag(X *x, XNode **cur, XNode **root, int *depth) {
if (s[x->p] == '/') {
if (x->p + 1 >= x->len || s[x->p + 1] != '>') return -1;
x->p += 2;
- return 0; /* vacío: no se entra */
+ return 0; /* empty: not entered */
}
size_t na = x->p;
while (x->p < x->len && is_name(s[x->p])) x->p++;
@@ -169,10 +169,10 @@ XNode *xml_parse(const char *s, size_t len, const char **err) {
if (append(&cur->text, &cur->tlen, s, a, x.p - 3, 0)) goto bad;
continue;
}
- if (starts(&x, "<!")) { x.err = "doctype"; goto bad; } /* DOCTYPE/ENTITY: nunca */
+ if (starts(&x, "<!")) { x.err = "doctype"; goto bad; } /* DOCTYPE/ENTITY: never */
if (parse_tag(&x, &cur, &root, &depth)) goto bad;
if (root && !cur && depth == 0) {
- /* se cerró la raíz: solo puede seguir espacio, comentarios o PI */
+ /* root closed: only whitespace, comments or PIs may follow */
while (x.p < len) {
if (is_ws(s[x.p])) { x.p++; continue; }
if (starts(&x, "<!--")) { if (skip_to(&x, "-->")) goto bad; continue; }
@@ -200,7 +200,7 @@ bad:
void xml_free(XNode *n) {
if (!n) return;
- /* recursivo: la profundidad ya está acotada (MAX_DEPTH) */
+ /* recursive: depth is already bounded (MAX_DEPTH) */
for (int i = 0; i < n->nkids; i++) xml_free(n->kids[i]);
for (int i = 0; i < n->nattrs; i++) { sm_free(n->attrs[i].name); sm_free(n->attrs[i].value); }
sm_free(n->attrs);
diff --git a/server/src/vault/xmlmini.h b/server/src/vault/xmlmini.h
index 79531c5..e6744d7 100644
--- a/server/src/vault/xmlmini.h
+++ b/server/src/vault/xmlmini.h
@@ -1,8 +1,8 @@
-/* xmlmini.h — lector de XML mínimo, sin validar, para el XML de KeePass (KDBX) y los archivos
- * llave: arma un árbol en la arena de secretos (smem.h). Elementos, atributos, texto con las
- * entidades predefinidas y numéricas (&#N; &#xN;), CDATA, comentarios e instrucciones de
- * procesamiento. Nunca expande entidades declaradas: un <!DOCTYPE es un error (sin «billion
- * laughs» ni entidades externas). Profundidad máxima 256. */
+/* xmlmini.h — minimal non-validating XML reader for the KeePass (KDBX) XML and key
+ * files: builds a tree in the secrets arena (smem.h). Elements, attributes, text with the
+ * predefined and numeric entities (&#N; &#xN;), CDATA, comments and processing
+ * instructions. Never expands declared entities: a <!DOCTYPE is an error (no "billion
+ * laughs" or external entities). Maximum depth 256. */
#ifndef LORD_VAULT_XMLMINI_H
#define LORD_VAULT_XMLMINI_H
@@ -11,19 +11,19 @@
typedef struct { char *name, *value; } XAttr;
typedef struct XNode {
char *name;
- char *text; size_t tlen; /* texto directo (sin el de los hijos), sin entidades */
+ char *text; size_t tlen; /* direct text (without the children's), no entities */
XAttr *attrs; int nattrs;
struct XNode **kids; int nkids, cap;
struct XNode *parent;
} XNode;
-/* Raíz del documento (el elemento de más arriba) o NULL; err (si no es NULL) recibe un código. */
+/* Document root (the topmost element) or NULL; err (if not NULL) receives a code. */
XNode *xml_parse(const char *s, size_t len, const char **err);
void xml_free(XNode *n);
-XNode *xml_child(const XNode *n, const char *name); /* primer hijo con ese nombre */
-const char *xml_attr(const XNode *n, const char *name); /* NULL si no está */
-const char *xml_text(const XNode *n); /* "" si no hay */
-/* Reemplaza el texto (el nuevo queda a cargo del nodo; en smem). */
+XNode *xml_child(const XNode *n, const char *name); /* first child with that name */
+const char *xml_attr(const XNode *n, const char *name); /* NULL if absent */
+const char *xml_text(const XNode *n); /* "" if none */
+/* Replaces the text (the node takes ownership of the new one; in smem). */
void xml_set_text(XNode *n, char *text, size_t len);
#endif
diff --git a/server/src/wl/wl.c b/server/src/wl/wl.c
index 42e3b13..71f399c 100644
--- a/server/src/wl/wl.c
+++ b/server/src/wl/wl.c
@@ -52,6 +52,7 @@
#include <sys/ioctl.h>
#include "../term/term.h"
#include "../ui/ui.h"
+#include "../sec/broker.h"
enum { R_NONE, R_TOPLEVEL, R_POPUP, R_SUB, R_CURSOR };
@@ -2136,16 +2137,7 @@ int wl_send_paste(void) {
return 1;
}
-int wl_key(int code, int value, const KeyInfo *k) {
- if (!dpy) return 0;
- if (k->meta && code == KEY_ESC && fs_surf) { if (value == 1) leave_fullscreen(fs_surf); return 1; } /* ❖Esc exits */
- if (fs_surf && fs_surf->content && key_focus != fs_surf) wl_set_focus(fs_surf->id);
- if (!key_focus) return 0;
- if (k->meta) return 0; /* ❖ + key: LordOS shortcuts */
- /* media keys and Print Screen: always LordOS's (Player, Screenshots) */
- if (code == KEY_PLAYPAUSE || code == KEY_NEXTSONG || code == KEY_PREVIOUSSONG || code == KEY_STOPCD || code == KEY_PLAYCD ||
- code == KEY_PAUSECD || code == KEY_SYSRQ) return 0;
- if (value == 2) return 1; /* apps repeat on their own (repeat_info) */
+static void send_key_to_focus(int code, int value) {
unsigned t = now_ms();
uint32_t d, l, lk, g;
kb_mods(&d, &l, &lk, &g);
@@ -2157,6 +2149,52 @@ int wl_key(int code, int value, const KeyInfo *k) {
wl_keyboard_send_modifiers(kb, wl_display_next_serial(dpy), d, l, lk, g);
}
mods_sent[0] = d; mods_sent[1] = l; mods_sent[2] = lk; mods_sent[3] = g;
+}
+
+/* The client with the keyboard is an isolated LordOS app (`lord-server --app`): its pid is the one
+ * lord-server registered when it spawned it (brokersrv). A Linux app never matches. */
+static int focus_is_lord_app(void) {
+ pid_t pid = 0;
+ uid_t uid;
+ gid_t gid;
+ if (!key_focus || !key_focus->client) return 0;
+ wl_client_get_credentials(key_focus->client, &pid, &uid, &gid);
+ return brokersrv_app_of_pid((int)pid) != NULL;
+}
+
+/* ❖ shortcuts that stay with LordOS even when an isolated app has the keyboard: lock (❖L, ❖⌃Q),
+ * quit (❖Q), search and keyboard layout (❖Space, ❖⌥Space), clipboard history (❖V, ❖⇧V), emoji
+ * (❖.), window switching (❖Tab, ❖`), screenshots (❖⇧3/4/5) and ❖Esc. */
+static int system_meta_key(int code, const KeyInfo *k) {
+ switch (code) {
+ case KEY_L: case KEY_Q: case KEY_SPACE: case KEY_V: case KEY_DOT: case KEY_TAB: case KEY_GRAVE: case KEY_ESC:
+ return 1;
+ case KEY_3: case KEY_4: case KEY_5:
+ return k->shift;
+ default:
+ return code >= KEY_F1 && code <= KEY_F12;
+ }
+}
+
+int wl_key(int code, int value, const KeyInfo *k) {
+ if (!dpy) return 0;
+ if (k->meta && code == KEY_ESC && fs_surf) { if (value == 1) leave_fullscreen(fs_surf); return 1; } /* ❖Esc exits */
+ if (fs_surf && fs_surf->content && key_focus != fs_surf) wl_set_focus(fs_surf->id);
+ if (!key_focus) return 0;
+ int super = code == KEY_LEFTMETA || code == KEY_RIGHTMETA;
+ if (k->meta || super) {
+ /* ❖ + key: LordOS shortcuts. An isolated LordOS app also gets the ones that are not the
+ * system's (❖N, ❖C, ❖A, ❖W…), with the ❖ key itself so it knows the modifier, as an app in
+ * the theme would; the theme still sees them (it tracks ❖ pressed alone). A Linux app only
+ * gets the release of ❖, as before. */
+ if (value != 2 && (focus_is_lord_app() ? super || !system_meta_key(code, k) : super && !value)) send_key_to_focus(code, value);
+ return 0;
+ }
+ /* media keys and Print Screen: always LordOS's (Player, Screenshots) */
+ if (code == KEY_PLAYPAUSE || code == KEY_NEXTSONG || code == KEY_PREVIOUSSONG || code == KEY_STOPCD || code == KEY_PLAYCD ||
+ code == KEY_PAUSECD || code == KEY_SYSRQ) return 0;
+ if (value == 2) return 1; /* apps repeat on their own (repeat_info) */
+ send_key_to_focus(code, value);
return 1;
}
diff --git a/server/tests/brokerkr_e2e.c b/server/tests/brokerkr_e2e.c
new file mode 100644
index 0000000..65635e5
--- /dev/null
+++ b/server/tests/brokerkr_e2e.c
@@ -0,0 +1,205 @@
+/* brokerkr_e2e.c — the keyring op of isolated .lpk apps (src/sec/brokerkr.c, BOP_KEYRING) end to
+ * end with a real lord-vault: the payload an app sends, the owner lord-server sets ("app.<id>"),
+ * isolation between two app ids, the consent prompt (deny and allow), a shell owner that a .lpk
+ * with the same id cannot reach, a missing item, bad requests and a locked keyring.
+ * brokersrv_reply and brokersrv_prompt_event are stand-ins here: replies go to a socketpair (the
+ * "app"), prompts are recorded. Temporary HOME, no D-Bus. Needs build/lord-vault next to it:
+ * `make build/brokerkr-e2e && build/brokerkr-e2e`. */
+#include "sec/broker_int.h"
+#include "vault/vclient.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+
+static int fails, total;
+static void check(int ok, const char *what) { total++; printf("%s: %s\n", ok ? "ok " : "FAIL", what); if (!ok) fails++; }
+static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
+
+/* ---- stand-ins for brokersrv.c ---- */
+static char prompt[256];
+static int nprompts;
+int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd) {
+ (void)passfd;
+ BrokerHdr h = { .reqid = reqid, .op = 0, .status = (uint16_t)status, .len = len };
+ struct iovec iov[2] = { { &h, sizeof h }, { (void *)data, len } };
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = len ? 2 : 1 };
+ return sendmsg(fd, &m, MSG_NOSIGNAL) < 0 ? -1 : 0;
+}
+void brokersrv_prompt_event(const char *json) { snprintf(prompt, sizeof prompt, "%s", json); nprompts++; }
+
+static int app_end, srv_end;
+static uint32_t next_req = 1;
+static char got[1 << 16];
+static int got_status;
+
+/* the app sends op/service/account/label/secret; waits for the reply (or a prompt) */
+static int call(const char *app, const char *op, const char *service, const char *account, const char *label, const char *secret, size_t secret_len) {
+ char p[4096];
+ size_t o = 0;
+ const char *f[4] = { op, service, account, label };
+ for (int i = 0; i < 4; i++) { size_t n = strlen(f[i]); memcpy(p + o, f[i], n); o += n; p[o++] = 0; }
+ memcpy(p + o, secret, secret_len);
+ o += secret_len;
+ p[o] = 0;
+ int before = nprompts;
+ brokerkr_handle(0, srv_end, next_req++, app, p, (uint32_t)o);
+ double t0 = now_ms();
+ while (now_ms() - t0 < 20000) {
+ brokerkr_tick();
+ if (nprompts != before) return 'p';
+ BrokerHdr h;
+ struct iovec iov[2] = { { &h, sizeof h }, { got, sizeof got - 1 } };
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = 2 };
+ ssize_t r = recvmsg(app_end, &m, MSG_DONTWAIT);
+ if (r >= (ssize_t)sizeof h) { got[r - sizeof h] = 0; got_status = h.status; return 'r'; }
+ usleep(2000);
+ }
+ snprintf(got, sizeof got, "timeout");
+ got_status = -1;
+ return 't';
+}
+#define CALL(app, op, svc, acct, sec) call(app, op, svc, acct, "", sec, strlen(sec))
+
+/* after a prompt: the user's answer, then the reply */
+static int answer(int allow) {
+ unsigned id = 0;
+ const char *q = strstr(prompt, "\"reqid\":");
+ if (q) id = (unsigned)strtoul(q + 8, NULL, 10);
+ if (!brokerkr_resolve(id, allow)) return 'x';
+ double t0 = now_ms();
+ while (now_ms() - t0 < 20000) {
+ brokerkr_tick();
+ BrokerHdr h;
+ struct iovec iov[2] = { { &h, sizeof h }, { got, sizeof got - 1 } };
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = 2 };
+ ssize_t r = recvmsg(app_end, &m, MSG_DONTWAIT);
+ if (r >= (ssize_t)sizeof h) { got[r - sizeof h] = 0; got_status = h.status; return 'r'; }
+ usleep(2000);
+ }
+ return 't';
+}
+
+static int is_ok(void) { return got_status == BST_OK && strstr(got, "\"ok\":true"); }
+static int is_err(int st, const char *code) { return got_status == st && !strcmp(got, code); }
+
+/* a request on the system channel (as the desktop's own apps do), waiting for its reply */
+static void sys_req(const char *json) {
+ int id = vc_request(json, strlen(json), NULL, 0);
+ double t0 = now_ms();
+ while (id > 0 && now_ms() - t0 < 20000) {
+ char *s = vc_poll();
+ if (s) { int done = strstr(s, "\"kind\":\"rep\"") != NULL; vc_poll_free(s); if (done) return; }
+ usleep(2000);
+ }
+}
+
+int main(void) {
+ char home[] = "/tmp/brokerkr-e2e-XXXXXX";
+ if (!mkdtemp(home)) return 1;
+ setenv("HOME", home, 1);
+ setenv("XDG_RUNTIME_DIR", "/nonexistent", 1);
+ unsetenv("DBUS_SESSION_BUS_ADDRESS");
+ int sv[2];
+ if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv)) return 1;
+ app_end = sv[0];
+ srv_end = sv[1];
+ check(vc_available(), "lord-vault next to the binary");
+
+ /* no session keyring yet */
+ CALL("alpha", "set", "sync.example.org", "ana", "s");
+ check(is_err(BST_ERROR, "keyring.noKeyring"), "no keyring before the session password → keyring.noKeyring");
+ vc_session_password("session password e2e");
+ usleep(1500000);
+
+ CALL("alpha", "set", "sync.example.org", "ana", "alpha-secret");
+ check(is_ok(), "alpha: set");
+ CALL("alpha", "get", "sync.example.org", "ana", "");
+ check(is_ok() && strstr(got, "alpha-secret") && strstr(got, "\"owner\":\"app.alpha\""), "alpha: get its own item, owner app.alpha");
+ CALL("alpha", "list", "", "", "");
+ check(is_ok() && strstr(got, "sync.example.org") && !strstr(got, "alpha-secret"), "alpha: list has the item, without secrets");
+ CALL("alpha", "get", "missing.example.org", "", "");
+ check(is_err(BST_ERROR, "keyring.notFound"), "alpha: missing item → keyring.notFound");
+
+ /* beta cannot see alpha's item without the user's consent */
+ CALL("beta", "list", "", "", "");
+ check(is_ok() && !strstr(got, "sync.example.org"), "beta: list is empty");
+ CALL("beta", "delete", "sync.example.org", "ana", "");
+ check(is_err(BST_ERROR, "keyring.notFound"), "beta: cannot delete alpha's item (notFound)");
+ CALL("beta", "set", "sync.example.org", "ana", "beta-secret");
+ check(is_ok(), "beta: set with the same service makes beta's own item");
+ CALL("alpha", "get", "sync.example.org", "ana", "");
+ check(is_ok() && strstr(got, "alpha-secret") && !strstr(got, "beta-secret"), "alpha's item unchanged by beta");
+ CALL("beta", "delete", "sync.example.org", "ana", "");
+ check(is_ok(), "beta: delete its own item");
+ int k = CALL("beta", "get", "sync.example.org", "ana", "");
+ check(k == 'p' && strstr(prompt, "\"app\":\"beta\"") && strstr(prompt, "\"perm\":\"keyring\"") && strstr(prompt, "\"owner\":\"alpha\""),
+ "beta: get of alpha's item → system prompt (app beta, owner alpha)");
+ check(answer(0) == 'r' && is_err(BST_DENIED, "keyring.notShared"), "user denies → keyring.notShared");
+ k = CALL("beta", "get", "sync.example.org", "ana", "");
+ check(k == 'r' && is_err(BST_DENIED, "keyring.notShared"), "after a denial, no new prompt this session");
+ k = CALL("delta", "get", "sync.example.org", "ana", "");
+ check(k == 'p' && strstr(prompt, "\"app\":\"delta\""), "another app is still asked");
+ check(answer(1) == 'r' && is_ok() && strstr(got, "alpha-secret"), "user allows → delta reads the shared item");
+ k = CALL("delta", "get", "sync.example.org", "ana", "");
+ check(k == 'r' && is_ok() && strstr(got, "alpha-secret"), "no prompt once shared");
+ CALL("delta", "delete", "sync.example.org", "ana", "");
+ check(is_err(BST_ERROR, "keyring.notFound"), "a shared item can be read, not deleted, by delta");
+ CALL("beta", "list", "", "", "");
+ check(is_ok() && !strstr(got, "sync.example.org"), "beta still sees nothing (shared with delta only)");
+ CALL("gamma", "list", "", "", "");
+ check(is_ok() && !strstr(got, "sync.example.org"), "gamma still sees nothing");
+
+ /* the owner is set by lord-server: a .lpk named "mail" does not reach the desktop's "mail" items */
+ sys_req("{\"op\":\"kr-set\",\"owner\":\"mail\",\"service\":\"imap.example.com\",\"account\":\"ana\",\"secret\":\"desk-secret\"}");
+ k = CALL("mail", "get", "imap.example.com", "ana", "");
+ check(k == 'p' && strstr(prompt, "\"owner\":\"mail\""), ".lpk \"mail\" (owner app.mail) does not own the desktop's \"mail\" item");
+ check(answer(0) == 'r' && is_err(BST_DENIED, "keyring.notShared"), "denied");
+
+ /* bad requests */
+ CALL("alpha", "nope", "x", "", "");
+ check(is_err(BST_ERROR, "keyring.badRequest"), "unknown op → keyring.badRequest");
+ CALL("alpha", "get", "", "", "");
+ check(is_err(BST_ERROR, "keyring.badRequest"), "empty service → keyring.badRequest");
+ call("alpha", "set", "x.example", "", "", "a\0b", 3);
+ check(is_err(BST_ERROR, "keyring.badRequest"), "NUL inside the secret → keyring.badRequest");
+ {
+ static char big[300];
+ memset(big, 'a', sizeof big - 1);
+ CALL("alpha", "get", big, "", "");
+ check(is_err(BST_ERROR, "keyring.badRequest"), "service over 255 bytes → keyring.badRequest");
+ }
+ { const char *sec = "with \"quotes\" and \\ and \n"; call("alpha", "set", "escape.example", "\"quoted\"", "", sec, strlen(sec)); }
+ CALL("alpha", "get", "escape.example", "\"quoted\"", "");
+ check(is_ok() && strstr(got, "with \\\"quotes\\\" and \\\\ and \\n"), "quotes, backslashes and newlines round-trip");
+
+ /* locked keyring (logout locks it) */
+ vc_lock_all("logout");
+ usleep(300000);
+ CALL("alpha", "get", "sync.example.org", "ana", "");
+ check(is_err(BST_ERROR, "keyring.locked"), "locked keyring → keyring.locked");
+
+ /* the app closed while its request was waiting: the late reply is dropped */
+ vc_session_password("session password e2e");
+ usleep(800000);
+ {
+ char p[64];
+ size_t n = (size_t)snprintf(p, sizeof p, "list%c%c%c%c", 0, 0, 0, 0);
+ brokerkr_handle(5, srv_end, 999, "alpha", p, (uint32_t)n);
+ brokerkr_conn_closed(5);
+ double t0 = now_ms();
+ while (vc_private_pending() && now_ms() - t0 < 5000) { brokerkr_tick(); usleep(2000); }
+ char tmp[64];
+ ssize_t r = recv(app_end, tmp, sizeof tmp, MSG_DONTWAIT);
+ check(r < 0 && !vc_private_pending(), "reply for a closed app is drained, not sent");
+ }
+
+ char cmd[128];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", home);
+ if (system(cmd)) { /* best effort */ }
+ printf("brokerkr-e2e: %d/%d ok\n", total - fails, total);
+ return fails ? 1 : 0;
+}
diff --git a/server/tests/secretsvc/run-pw-116.sh b/server/tests/secretsvc/run-pw-116.sh
index 36738de..e9049f3 100644
--- a/server/tests/secretsvc/run-pw-116.sh
+++ b/server/tests/secretsvc/run-pw-116.sh
@@ -53,7 +53,7 @@ stop
grep -q "OpenSession dh-ietf1024-sha256-aes128-cbc-pkcs7" "$LOG" && pass "libsecret negotiated dh-ietf1024-sha256-aes128-cbc-pkcs7" || echo "note: libsecret did not use DH"
grep -q "OpenSession plain" "$LOG" && echo "note: there were plain sessions too"
-grep -q "Unlock → aviso" "$LOG" && pass "Unlock went through a Prompt" || echo "note: there was no Prompt" # matches the "Unlock → aviso" debug line of src/vault/secretsvc.c
+grep -q "Unlock → prompt" "$LOG" && pass "Unlock went through a Prompt" || echo "note: there was no Prompt" # matches the "Unlock → prompt" debug line of src/vault/secretsvc.c
owner && fail "someone still owns the name" || pass "the name is free"
echo "log: $LOG"
rm -f /tmp/ss-search.$$
diff --git a/tools/err-check.mjs b/tools/err-check.mjs
index 6a4400d..ed4bdf2 100644
--- a/tools/err-check.mjs
+++ b/tools/err-check.mjs
@@ -23,7 +23,6 @@ const SRC = path.join(root, 'server/src');
// Out of this pass's scope (engine and app-mode work): warnings until converted.
export const PENDING = [
'ui/paint.c', 'ui/layout.c', 'ui/text.c', 'ui/style.c',
- 'app/', 'sec/brokersrv.c', 'ui/js_broker.c',
];
const CODE = /^[a-z][a-zA-Z0-9]*(?:\.[a-zA-Z0-9]+)+$/;
diff --git a/tools/rpi/build-img.sh b/tools/rpi/build-img.sh
index 5f5695e..c46ac3b 100755
--- a/tools/rpi/build-img.sh
+++ b/tools/rpi/build-img.sh
@@ -25,9 +25,12 @@ VERSION=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' package.json | head -1)
WORK=${1:-/var/tmp/lordos-rpi}
MIRROR=${MIRROR:-http://deb.debian.org/debian}
RPI_MIRROR=${RPI_MIRROR:-http://archive.raspberrypi.com/debian}
-# Raspberry Pi archive key (raspberrypi.gpg.key). Verify it against
-# https://www.raspberrypi.com/documentation/ before the first build (see docs/RASPBERRY.md).
-RPI_KEY_URL=${RPI_KEY_URL:-$RPI_MIRROR/raspberrypi.gpg.key}
+# Raspberry Pi archive key. It is taken from the raspberrypi-archive-keyring package of the archive
+# (found through the Packages index; trust comes only from the fingerprint check below): the loose
+# raspberrypi.gpg.key at the archive root still carries its 2012 SHA-1 binding signatures, which apt's
+# sqv rejects since 2026-02-01 ("SHA1 is not considered secure"), while the package's copy is re-signed
+# with SHA-512. RPI_KEY_URL=<url> (an armored or binary key) skips the package. See docs/RASPBERRY.md.
+RPI_KEY_URL=${RPI_KEY_URL:-}
RPI_KEY_FPR=${RPI_KEY_FPR:-CF8A1AF502A2AA2D763BAE7E82B129927FA3303E}
IMG_EXTRA_MB=${IMG_EXTRA_MB:-512}
SUITE=trixie
@@ -159,17 +162,32 @@ bootstrap "$CH" "$WORK/debootstrap.log"
# Raspberry Pi archive: only kernel, firmware and utilities (preferences.d/raspberrypi)
echo "== Raspberry Pi archive key"
-KEY="$WORK/raspberrypi.asc"
-curl -fsSL "$RPI_KEY_URL" -o "$KEY"
+KEY="$WORK/raspberrypi.pgp"
+rm -f "$KEY"
+if [ -n "$RPI_KEY_URL" ]; then
+ KEY_SRC=$RPI_KEY_URL
+ curl -fsSL "$RPI_KEY_URL" -o "$WORK/raspberrypi.key"
+else
+ KR=$(curl -fsSL "$RPI_MIRROR/dists/$SUITE/main/binary-$ARCH/Packages.gz" | gzip -dc |
+ awk '/^Package: raspberrypi-archive-keyring$/ { f = 1 } f && /^Filename:/ { print $2; exit }')
+ [ -n "$KR" ] || { echo "build-img.sh: raspberrypi-archive-keyring not found in $RPI_MIRROR ($SUITE)" >&2; exit 1; }
+ KEY_SRC="$RPI_MIRROR/$KR"
+ rm -rf "$WORK/rpi-keyring"; mkdir -p "$WORK/rpi-keyring"
+ curl -fsSL "$KEY_SRC" -o "$WORK/rpi-keyring.deb"
+ dpkg-deb -x "$WORK/rpi-keyring.deb" "$WORK/rpi-keyring"
+ cp "$WORK/rpi-keyring/usr/share/keyrings/raspberrypi-archive-keyring.pgp" "$WORK/raspberrypi.key"
+fi
+# always stored binary (dearmored): apt's sqv decides the format by the extension
+gpg --dearmor < "$WORK/raspberrypi.key" > "$KEY" 2>/dev/null && [ -s "$KEY" ] || cp "$WORK/raspberrypi.key" "$KEY"
FPR=$(gpg --show-keys --with-colons "$KEY" 2>/dev/null | awk -F: '$1 == "fpr" { print $10; exit }')
if [ "$FPR" != "$RPI_KEY_FPR" ] && [ "${RPI_KEY_NOCHECK:-0}" != 1 ]; then
- echo "build-img.sh: the key at $RPI_KEY_URL has fingerprint $FPR (expected $RPI_KEY_FPR)" >&2
+ echo "build-img.sh: the key from $KEY_SRC has fingerprint $FPR (expected $RPI_KEY_FPR)" >&2
echo " verify it and pass RPI_KEY_FPR=<fingerprint> (see docs/RASPBERRY.md)" >&2
exit 1
fi
install -d "$CH/etc/apt/keyrings"
-install -m 644 "$KEY" "$CH/etc/apt/keyrings/raspberrypi.asc"
-echo "deb [signed-by=/etc/apt/keyrings/raspberrypi.asc] $RPI_MIRROR $SUITE main" > "$CH/etc/apt/sources.list.d/raspberrypi.list"
+install -m 644 "$KEY" "$CH/etc/apt/keyrings/raspberrypi.pgp"
+echo "deb [signed-by=/etc/apt/keyrings/raspberrypi.pgp] $RPI_MIRROR $SUITE main" > "$CH/etc/apt/sources.list.d/raspberrypi.list"
install -m 644 "$RPI/etc/apt/preferences.d/raspberrypi" "$CH/etc/apt/preferences.d/raspberrypi"
echo lordos-pi > "$CH/etc/hostname"
@@ -202,7 +220,7 @@ en_US.UTF-8 UTF-8
pt_BR.UTF-8 UTF-8
EOF
in_root "$CH" locale-gen > /dev/null
-echo 'LANG=es_ES.UTF-8' > "$CH/etc/default/locale"
+echo 'LANG=en_US.UTF-8' > "$CH/etc/default/locale" # English by default, like the ISO
ln -sf /usr/share/zoneinfo/UTC "$CH/etc/localtime"; echo UTC > "$CH/etc/timezone"
echo 'net.ipv4.ping_group_range = 0 2147483647' > "$CH/etc/sysctl.d/50-lordos-ping.conf"
@@ -294,7 +312,7 @@ PARTUUID=$PARTUUID_BOOT /boot/firmware vfat defaults,umask=0077 0 2
EOF
# lordos.gpu=0 (safe mode, everything on the CPU) and lordos.lang=en|pt can be added here, as on the ISO.
# lsm=: Landlock for app isolation (server/src/sec); those the kernel lacks are ignored.
-printf 'console=serial0,115200 console=tty3 root=PARTUUID=%s rootfstype=ext4 fsck.repair=yes rootwait quiet loglevel=3 cgroup_enable=memory lsm=landlock,lockdown,yama,integrity,apparmor,bpf lordos.lang=es\n' \
+printf 'console=serial0,115200 console=tty3 root=PARTUUID=%s rootfstype=ext4 fsck.repair=yes rootwait quiet loglevel=3 cgroup_enable=memory lsm=landlock,lockdown,yama,integrity,apparmor,bpf lordos.lang=en\n' \
"$PARTUUID_ROOT" > "$WORK/mnt/boot/firmware/cmdline.txt"
sync
umount "$WORK/mnt/boot/firmware"
diff --git a/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example b/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example
index a53a816..7526ae7 100644
--- a/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example
+++ b/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example
@@ -13,7 +13,7 @@ password_hash=$y$j9T$REEMPLAZAR$REEMPLAZAR
#password=
hostname=ana-pi
# es, en or pt
-lang=es
+lang=en
timezone=America/Argentina/Buenos_Aires
keyboard=latam
keyboard_variant=
diff --git a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot
index 4595395..7842802 100755
--- a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot
+++ b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot
@@ -92,8 +92,8 @@ user_dirs() { # user folders by language, like Settings' user-add
if [ -e "$STATE/firstboot-pending" ]; then
F=""
[ -f "$BOOT/lordos-user.txt" ] && F="$BOOT/lordos-user.txt"
- LANG_UI=es
- for a in $(cat /proc/cmdline); do case "$a" in lordos.lang=en) LANG_UI=en ;; lordos.lang=pt) LANG_UI=pt ;; esac; done
+ LANG_UI=en # English by default, like the ISO
+ for a in $(cat /proc/cmdline); do case "$a" in lordos.lang=es) LANG_UI=es ;; lordos.lang=pt) LANG_UI=pt ;; esac; done
U=""; FULL=""; HASH=""; PASS=""; HOST=""; TZ_=""; KB=""; KBV=""
if [ -n "$F" ]; then
U=$(kv user "$F"); FULL=$(kv fullname "$F" | tr -d ':,' | tr -d '\000-\037')
@@ -119,7 +119,7 @@ if [ -e "$STATE/firstboot-pending" ]; then
else printf '%s:%s\n' "$U" "$PASS" | chpasswd; fi # chpasswd: yescrypt, like Debian
: > "/var/lib/systemd/linger/$U"
user_dirs "$U" "$LANG_UI"
- case "$LANG_UI" in en) LOC=en_US.UTF-8 ;; pt) LOC=pt_BR.UTF-8 ;; *) LOC=es_ES.UTF-8 ;; esac
+ case "$LANG_UI" in es) LOC=es_ES.UTF-8 ;; pt) LOC=pt_BR.UTF-8 ;; *) LOC=en_US.UTF-8 ;; esac
printf 'LANG=%s\n' "$LOC" > /etc/default/locale
H=$(getent passwd "$U" | cut -d: -f6)
install -d -o "$U" -g "$U" "$H/.config" "$H/.config/lordos"