瀏覽代碼

Add fprintd shim: GNOME lock screen + Settings fingerprint

GNOME 51 dropped fingerprint login at the greeter (re-authentication only)
and libfprint has no 06cb:0081 support, so GNOME's fingerprint features
need a fprintd-compatible service. work/fprintd-shim/ implements
net.reactivated.Fprint (Manager + Device) backed by the Wine sandbox;
GNOME Shell, pam_fprintd and the fprintd CLI work unchanged.

- verify: runs work/fp-verify.sh as the prefix owner and maps the result
  to verify-match/verify-no-match; claim/release/stop semantics follow
  fprintd's source, including auto-release when a client disconnects on
  PAM success
- enroll: drives enroll.exe and maps the harness output to EnrollStatus
  stages; any existing record is deleted first because a *replacing*
  commit makes the device re-enumerate and the winusb stub dies with
  LIBUSB_ERROR_NO_DEVICE (fresh writes commit reliably)
- delete: real sensor-side delete via delete.exe; the reported state is
  updated optimistically (gnome-control-center abandons the call after
  ~10 s) and restored if the harness fails; in-flight device mutations
  are never aborted by a client release
- state: /var/lib/fprintd-shim/state.json (finger lists per user)
- service installed as /etc/systemd/system/fprintd.service, shadowing the
  packaged unit - its ProtectHome/PrivateTmp sandbox would break the Wine
  prefix; D-Bus activated, no boot enable
- tests: selftest.py (pam_fprintd-like flow), apitest.py (20 API-semantics
  checks), enrolltest.py (CLI enrollment driver)
- work/fp-verify.sh: flock so sudo/polkit/lock screen serialize on the
  USB device
- harness runs log with WINEDEBUG=-all,err+all, surfacing the silent
  winusb exit(0) in /tmp/opencode/harness-*.log
- README: usage, findings and the multi-finger plan (records are keyed by
  identity+subfactor; the harness hardcodes 0xF6)
- evidence: work/debug/fprintd_shim_{lock_screen,phase2}_SUCCESS.txt
Johannes Zellner 1 月之前
父節點
當前提交
d642abb252

+ 98 - 1
README.md

@@ -13,6 +13,10 @@ Quick usage:
 - PAM (active): sudo uses custom `pam_fp.so` — fingerprint OR password,
   whichever comes first (no timeout wait); polkit is finger-first with a
   password fallback. Installer: `sudo work/pam/install.sh`.
+- Lock screen (active, tested 2026-10-15): GNOME re-auth unlocks with the
+  sensor via the fprintd-compatible shim `work/fprintd-shim/` (see the
+  "GNOME lock-screen fingerprint" section).
+  Evidence: `work/debug/fprintd_shim_lock_screen_SUCCESS.txt`.
 
 The native synaTudor route below remains blocked (driver-internal NULL in the
 capture ioctl path); the Wine route is the pragmatic working solution.
@@ -313,6 +317,98 @@ sudo sed -i '1s|.*|auth sufficient /home/nebulon/projects/fingerprint/work/pam/p
 
 Rollback: `sudo cp /etc/pam.d/sudo.bak-fp /etc/pam.d/sudo`
 
+### GNOME lock-screen fingerprint (fprintd shim) — ACTIVE
+
+GNOME 51 dropped fingerprint login at the GDM login screen (re-authentication
+only, see GDM 51 NEWS) and its lock-screen fingerprint support needs
+*fprintd*, which has no 06cb:0081 support. `work/fprintd-shim/` implements
+the fprintd D-Bus API (`net.reactivated.Fprint` Manager + Device) on top of
+`work/fp-verify.sh`, so GNOME Shell, `pam_fprintd` and the fprintd CLI
+tools see this sensor:
+
+- `fprintd-shim.py` — the service (Python 3 + PyGObject; verification runs
+  as `nebulon` via `setpriv`, same environment as the pam_exec path)
+- `fprintd.service` — installed as `/etc/systemd/system/fprintd.service`
+  (shadows the packaged unit; D-Bus activation, no boot enable)
+- `install.sh` / `uninstall.sh` — (un)install, rollback is instant
+- `selftest.py` — pam_fprintd-like smoke test (system bus or `--session`)
+- `apitest.py` — API-semantics regression test (session bus, no touch needed)
+
+Lock-screen behaviour: touch the sensor to unlock; typing the password
+stays available in parallel. A no-touch attempt ends after the pam_fprintd
+timeout (30 s); failed touches are retried up to 3 times. Sudo/polkit keep
+using `pam_fp.so` — untouched. `work/fp-verify.sh` now takes an `flock` so
+concurrent verifications (sudo + lock screen) serialize on the sensor.
+
+Tested end-to-end 2026-10-15 (session 3, Wayland): lock screen unlocked by
+fingerprint in ~5 s (`work/debug/fprintd_shim_lock_screen_SUCCESS.txt`).
+Note: several failed sudo fingerprint attempts trip `pam_faillock` and block
+the `gdm-fingerprint` PAM stack; reset with
+`sudo faillock --user nebulon --reset`.
+
+```sh
+# install / rollback (root)
+sudo work/fprintd-shim/install.sh
+sudo work/fprintd-shim/uninstall.sh
+
+# smoke tests (user)
+fprintd-list "$USER"
+fprintd-verify -f any "$USER"          # touch the sensor
+python3 work/fprintd-shim/selftest.py
+work/pam/pamtest3 -d work/pam/confdir -s fprintd-test "$USER"   # touch
+dbus-run-session -- bash -c '          # full API test, no root
+    python3 work/fprintd-shim/fprintd-shim.py --session &
+    sleep 1; python3 work/fprintd-shim/apitest.py; kill %1'
+```
+
+Phase 2 (mostly done): enrollment and deletion work through GNOME Settings
+and the fprintd CLI.  `EnrollStart` drives `enroll.exe` (fresh commits work;
+see the commit caveat below) and `DeleteEnrolled*` runs `delete.exe` — a real
+sensor-side delete (ioctl 0x442034).  Reported fingerprints live in
+`/var/lib/fprintd-shim/state.json` (today the sensor holds a single record —
+see the multi-finger plan below; deleting the last reported finger deletes
+the device record, deleting one of several only updates the reported list).
+
+Known caveat — re-enrolling an *existing* record: the commit phase there
+makes the device re-enumerate mid-write; the hacked winusb stub cannot
+detect reconnects and exits with `LIBUSB_ERROR_NO_DEVICE` (visible in
+`/tmp/opencode/harness-*.log`), which used to leave a record that matched
+nothing.  The shim therefore deletes any existing record first (the delete
+ioctl does not reset the device) so every enrollment is a fresh write,
+which has been reliable.
+
+### Multi-finger support — plan for the next session
+
+Today the sensor holds exactly one record because the sandbox harness
+hardcodes it (`hello.cc` `commitEnrollment()` / `deleteRecord()`:
+identity GUID `c5698517-…` **subfactor 0xF6** payload `"Unicorn"`; the
+firmware/driver key records by identity+subfactor, i.e. one slot per
+finger).  Not a hardware limit — Windows enrolls each finger under its own
+subfactor.  Steps:
+
+1. `work/artifacts/make-enroll-delete.sh`: locate the subfactor bytes by
+   signature (the 4 bytes `f6 00 00 00` right after the 16-byte identity
+   GUID; assert uniqueness) and emit per-finger variants, e.g.
+   `enroll-<subfactor>.exe` / `delete-<subfactor>.exe`; or have the shim
+   patch a copy on the fly (1 MiB, deterministic) instead of committing 10
+   binaries.  Keep the `"Unicorn"` payload for all of them.
+2. Shim (`fprintd-shim.py`): map `finger_name -> subfactor` (e.g.
+   `left-thumb=0xF0` … `right-little-finger=0xF9`); run the per-finger
+   binary; `DeleteEnrolledFinger(f)` deletes only f's record,
+   `DeleteEnrolledFingers2` loops over the enrolled set; keep the
+   "pre-delete the target slot" habit so each write stays a fresh commit.
+   Note: *adding* a second finger writes a different (empty) slot, so it
+   should behave like a fresh commit — the re-enumerate failure only hit
+   *replacing* an existing record.
+3. Verify stays as-is: every record carries the `"Unicorn"` payload, so
+   `fp-verify.sh`'s check keeps working ("any finger" semantics, like
+   fprintd).  Optional refinement: parse the returned subfactor to support
+   `VerifyStart(<specific finger>)`.
+4. Test: enroll two/three fingers (~10 touches each), verify each matches,
+   delete one and check the others still match, GNOME Settings lists them
+   all, lock screen still unlocks.  Update this README section and the
+   proof file afterwards.
+
 ## Persistence / restore (2026-10-13)
 
 Tracked here: scripts, patches, docs, small runtime artifacts (trust blobs,
@@ -329,7 +425,8 @@ Restore after a wipe:
 4. Prefix: `WINEPREFIX=$PWD/work/wineprefix-48 work/wine-build/install/bin/wine64 wineboot -u`
 5. udev: `sudo cp work/system/70-fingerprint-06cb-0081.rules /etc/udev/rules.d/ && sudo udevadm control --reload`
 6. PAM: `make -C work/pam && sudo work/pam/install.sh`
-7. Test: `work/fp-verify.sh` (touch the sensor) → `Fingerprint matched.`
+7. GNOME lock screen: `sudo work/fprintd-shim/install.sh`
+8. Test: `work/fp-verify.sh` (touch the sensor) → `Fingerprint matched.`
 
 ## Contributing back
 

+ 81 - 0
work/debug/fprintd_shim_lock_screen_SUCCESS.txt

@@ -0,0 +1,81 @@
+Phase 1 fprintd shim — end-to-end success evidence
+===================================================
+Date: 2026-10-15
+Host: lunar (Arch, GNOME Shell 51 / GDM 51, Wayland, session id 3)
+
+Installed service
+-----------------
+/etc/systemd/system/fprintd.service -> work/fprintd-shim/fprintd.service
+Active: active (running)  — serves net.reactivated.Fprint on the system bus
+(work/fprintd-shim/install.sh, authorized via the fingerprint reader itself)
+
+CLI (/usr/bin/fprintd-list)
+---------------------------
+$ fprintd-list nebulon
+found 1 devices
+Device at /net/reactivated/Fprint/Device/0
+Using device /net/reactivated/Fprint/Device/0
+Fingerprints for user nebulon on Synaptics 06cb:0081 (press):
+ - #0: right-index-finger
+
+Shell reader detection (same calls as libshell-51.so -> fingerprintManager.js)
+------------------------------------------------------------------------------
+GetDefaultDevice -> /net/reactivated/Fprint/Device/0  (service auto-started)
+scan-type -> press  => GNOME reader type PRESS (fingerprint mechanism enabled)
+
+fprintd-verify (CLI match path)
+-------------------------------
+$ timeout 50 fprintd-verify -f any nebulon
+Using device /net/reactivated/Fprint/Device/0
+Listing enrolled fingers: - #0: right-index-finger
+Verify started! / Verifying: right-index-finger
+Verify result: verify-match (done)
+fprintd-verify rc=0
+
+(An earlier run matched but exited 1 because VerifyStop returned
+NoActionInProgress after the terminal result; the shim now keeps fprintd's
+"action in progress" semantics until VerifyStop/Release.)
+
+Rollback test (uninstall -> stock fprintd -> reinstall)
+-------------------------------------------------------
+$ sudo work/fprintd-shim/uninstall.sh; fprintd-list nebulon
+No devices available                      <- stock fprintd took over
+$ sudo work/fprintd-shim/install.sh; fprintd-list nebulon
+Fingerprints for user nebulon on Synaptics 06cb:0081 (press):
+ - #0: right-index-finger
+
+pam_fprintd end-to-end (isolated, pam_start_confdir)
+----------------------------------------------------
+$ /tmp/opencode/pamtest3 -d /tmp/opencode/pam-confdir -s fprintd-test nebulon
+service=fprintd-test user=nebulon confdir=/tmp/opencode/pam-confdir
+(touch the sensor)
+pam_authenticate => 0 (Success)
+
+Real lock screen (loginctl lock-session 3, then touch)
+------------------------------------------------------
+journalctl -u fprintd:
+2026-10-15T11:59:01+02:00 fprintd-shim: INFO: claim by :1.2046 for user nebulon
+2026-10-15T11:59:06+02:00 fprintd-shim: INFO: verify[1]: Fingerprint matched.
+2026-10-15T11:59:06+02:00 fprintd-shim: INFO: claiming client :1.2046 vanished, releasing device
+
+...and the session unlocked (loginctl LockedHint: yes -> no) without a
+password entry: pam_fprintd disconnects on PAM_SUCCESS (the shim releases the
+claim via NameOwnerChanged, exactly like fprintd's client-vanished handling).
+
+API semantics regression (session bus, no touch)
+------------------------------------------------
+work/fprintd-shim/apitest.py -> all checks passed:
+GetDevices, ListEnrolledFingers (enrolled vs other user), Claim twice ->
+AlreadyInUse, VerifyStart unclaimed -> ClaimDevice, VerifyStart/Release from
+non-claimer -> AlreadyInUse, unenrolled finger -> NoEnrolledPrints, claim
+auto-release when the claiming client disconnects.
+
+Operational notes
+-----------------
+- Earlier failed `sudo` attempts (fingerprint auth misses) tripped
+  pam_faillock ("User nebulon is temporarily locked out due to 3 consecutive
+  failed login attempts") which blocked the gdm-fingerprint PAM stack before
+  pam_fprintd ran. Reset with: sudo faillock --user nebulon --reset
+- sudo / polkit are unchanged and still use work/pam/pam_fp.so.
+- work/fp-verify.sh takes an flock so concurrent verifications (sudo +
+  lock screen) serialize on the USB device.

+ 76 - 0
work/debug/fprintd_shim_phase2_SUCCESS.txt

@@ -0,0 +1,76 @@
+Phase 2 fprintd shim — GNOME Settings enrollment + deletion evidence
+=====================================================================
+Date: 2026-10-15  (continues work/debug/fprintd_shim_lock_screen_SUCCESS.txt)
+
+What works
+----------
+* Enrollment from GNOME Settings (Users -> Fingerprint Authentication ->
+  Add Fingerprint): verification of the flow 2026-10-15 13:04, 8 stages
+  then commit; the finger is listed and matches:
+
+    journalctl -u fprintd:
+      13:04:38 enroll start (right-middle-finger) by :1.2110
+      13:04:51..13:05:00 enroll: stages 1..8 passed
+      13:05:04 enroll: committed
+      13:05:04 enroll: user nebulon -> right-middle-finger (harness eof rc=0)
+
+    $ fprintd-list nebulon
+      Fingerprints for user nebulon on Synaptics 06cb:0081 (press):
+       - #0: right-middle-finger
+    $ fprintd-verify -f any nebulon        (touch)
+      Verify result: verify-match (done)   rc=0
+
+* Deletion (executed end-to-end through the shim's DeleteEnrolledFinger):
+    ListEnrolledFingers -> ['right-middle-finger']
+    DeleteEnrolledFinger ok
+    ListEnrolledFingers -> net.reactivated.Fprint.Error.NoEnrolledPrints
+
+  Device-side, `delete.exe` (a.exe with enroll() redirected to the existing
+  deleteRecord()) returns:
+      about to 442034
+      Got back 0x8 bytes: 0100000000000000      <- success
+
+Artifacts
+---------
+* work/artifacts/make-enroll-delete.sh -> enroll.exe / delete.exe
+  (a.exe ignores argv - the nop|identify|enroll dispatch is #if 0 upstream -
+  so the hardcoded default flow is patched instead; no WDK headers needed)
+* state: /var/lib/fprintd-shim/state.json (created by the service;
+  default for nebulon is right-index-finger = the original enrollment)
+
+Findings / caveats (all reproduced, all with log evidence)
+----------------------------------------------------------
+1. winusb stub exit(0): the hacked Wine winusb calls exit(0) on any failed
+   libusb transfer (res_err/winusb.c).  With WINEDEBUG=-all this is silent.
+   Harness runs now use -all,err+all and log to /tmp/opencode/harness-*.log.
+2. Re-enrolling an EXISTING record can die in the commit phase (the stub
+   exits mid-write; both attempts 12:46 and 12:47 ended after the commit
+   request with no response).  A fresh commit (no record / after delete)
+   committed cleanly (12:59 and 13:05).  Recovery for a broken record:
+   delete -> enroll again.
+3. The 12:47 aborted update-commit left a device record that matched
+   nothing (0x8009801F WINBIO_E_NO_MATCH for both fingers).  Cleared with
+   delete.exe; a fresh enroll then matched.
+4. GNOME Settings' delete flow starts with an identify step (VerifyStart,
+   expects a touch) and appears to abandon the delete call after ~10 s; the
+   shim now (a) keeps a running delete.exe alive when the client releases,
+   (b) updates the reported state optimistically at delete start (restored
+   if the harness fails) so the UI immediately reflects the deletion, and
+   (c) updates state after a successful harness run even if the client is
+   gone (previously the release-during-delete left state.json stale).
+   Verified 2026-10-15 13:5x: removal via Settings worked.
+5. Why re-enrollments failed (13:10-13:13): a commit that *replaces* an
+   existing record makes the device re-enumerate mid-write:
+
+     /tmp/opencode/harness-enroll.exe-1792062705.log:
+       0009:err:winusb:WinUsb_WritePipe xfer Failed - LIBUSB_ERROR_NO_DEVICE
+       (last marker: "about to Commit Enrollment", no response, harness rc=0)
+
+   while a fresh commit (no record) completes normally:
+     ... about to Commit Enrollment -> Got back 0x1 bytes: 01
+
+   Fix in the shim: always delete any existing record before enrolling
+   (delete ioctl does not reset the device), so every enrollment is a fresh
+   write; state is cleared accordingly and set again on commit.
+   Result: an enrollment that previously failed on the second attempt now
+   runs delete -> fresh commit on every try.

+ 15 - 0
work/fp-verify.sh

@@ -7,6 +7,21 @@ set -u
 export PATH=/usr/local/bin:/usr/bin:/bin
 ROOT=/home/nebulon/projects/fingerprint
 SANDBOX=$ROOT/work/synaWudfBioUsb-sandbox
+
+mkdir -p /tmp/opencode 2>/dev/null
+
+# Serialize sensor access: sudo/polkit (pam_fp.so), the fprintd shim (GNOME
+# lock screen) and manual runs must not drive the Wine sandbox at the same
+# time - the fake winusb cannot handle two Wine runs on one USB device.
+if [ "${FP_VERIFY_LOCK:-1}" = "1" ]; then
+    LOCK=/tmp/opencode/fp-verify.lock
+    exec 9>"$LOCK" || exit 2
+    if ! flock -w "${FP_VERIFY_LOCK_WAIT:-30}" 9; then
+        echo "Fingerprint: another verification is already in progress."
+        exit 2
+    fi
+fi
+
 export HOME="${HOME:-/home/nebulon}"
 export WINEPREFIX=$ROOT/work/wineprefix-48
 export WINEDEBUG=-all

+ 226 - 0
work/fprintd-shim/apitest.py

@@ -0,0 +1,226 @@
+#!/usr/bin/env python3
+"""API semantics regression test for the fprintd shim (session bus).
+
+Checks the fprintd contract against our shim, no sensor touch required:
+
+  * GetDevices / GetDefaultDevice
+  * ListEnrolledFingers for the enrolled user vs another user
+  * Claim twice                 -> AlreadyInUse
+  * VerifyStart unclaimed       -> ClaimDevice
+  * VerifyStart other client    -> error
+  * Release other client        -> error
+  * VerifyStart unenrolled finger -> NoEnrolledPrints
+  * claim owner disconnect      -> automatic release (no stale claim)
+  * EnrollStart validation      -> InvalidFingername / ClaimDevice
+  * EnrollStop idle             -> NoActionInProgress
+  * DeleteEnrolledFinger of a non-enrolled finger -> NoEnrolledPrints
+  * DeleteEnrolledFingers other user -> PermissionDenied
+  * deleting one of several reported fingers is metadata-only (no sensor
+    access - the sensor holds a single template)
+
+Usage:
+  dbus-run-session -- bash -c '
+      FP_SHIM_STATE_DIR=/tmp/opencode/shim-state-test \
+      python3 work/fprintd-shim/fprintd-shim.py --session &
+      sleep 1
+      python3 work/fprintd-shim/apitest.py'
+
+Note: g_bus_get_sync() returns a per-process singleton connection, so other
+clients are spawned as real subprocesses (--client mode).
+"""
+
+import json
+import os
+import subprocess
+import sys
+import time
+
+import gi
+
+gi.require_version('Gio', '2.0')
+gi.require_version('GLib', '2.0')
+from gi.repository import Gio, GLib  # noqa: E402
+
+BUS_NAME = 'net.reactivated.Fprint'
+MANAGER_PATH = '/net/reactivated/Fprint/Manager'
+IFACE_MANAGER = 'net.reactivated.Fprint.Manager'
+IFACE_DEVICE = 'net.reactivated.Fprint.Device'
+DEVICE_PATH = '/net/reactivated/Fprint/Device/0'
+
+failures = []
+
+
+def check(name, cond, detail=''):
+    print(f'{"ok  " if cond else "FAIL"} {name}' + (f'  [{detail}]' if detail else ''))
+    if not cond:
+        failures.append(name)
+
+
+def call(proxy, method, params=None):
+    try:
+        return True, proxy.call_sync(method, params, Gio.DBusCallFlags.NONE, 5000, None)
+    except GLib.Error as e:
+        return False, e
+
+
+def make_proxies():
+    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+    device = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
+                                    BUS_NAME, DEVICE_PATH, IFACE_DEVICE, None)
+    return device
+
+
+def write_state(users):
+    """Seed the shim's state file (FP_SHIM_STATE_DIR must be set for the test)."""
+    state_dir = os.environ.get('FP_SHIM_STATE_DIR', '/var/lib/fprintd-shim')
+    os.makedirs(state_dir, exist_ok=True)
+    with open(os.path.join(state_dir, 'state.json'), 'w') as f:
+        json.dump({'users': users}, f)
+
+
+def client_main(mode):
+    """One-shot client process: perform `mode`, print result, exit."""
+    device = make_proxies()
+    if mode == 'claim':
+        ok, res = call(device, 'Claim', GLib.Variant('(s)', ('nebulon',)))
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    if mode == 'verify-start':
+        ok, res = call(device, 'VerifyStart', GLib.Variant('(s)', ('any',)))
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    if mode == 'enroll-start-invalid':
+        ok, res = call(device, 'EnrollStart', GLib.Variant('(s)', ('any',)))
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    if mode == 'enroll-stop':
+        ok, res = call(device, 'EnrollStop')
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    if mode == 'release':
+        ok, res = call(device, 'Release')
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    if mode == 'claim-and-exit':
+        ok, res = call(device, 'Claim', GLib.Variant('(s)', ('nebulon',)))
+        print('ok' if ok else f'error {res.message}')
+        return 0
+    print(f'unknown mode {mode}')
+    return 2
+
+
+def spawn_client(mode):
+    proc = subprocess.run([sys.executable, __file__, '--client', mode],
+                          capture_output=True, text=True, timeout=30)
+    return proc.stdout.strip()
+
+
+def main():
+    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+    manager = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
+                                     BUS_NAME, MANAGER_PATH, IFACE_MANAGER, None)
+    ok, devices = call(manager, 'GetDevices')
+    devices = devices.unpack()[0] if ok else []
+    check('GetDevices returns one device', len(devices) == 1, str(list(devices)))
+    if not devices:
+        return 1
+
+    device = make_proxies()
+    ok, res = call(device, 'ListEnrolledFingers', GLib.Variant('(s)', ('nebulon',)))
+    check('ListEnrolledFingers(nebulon) -> right-index-finger',
+          ok and res.unpack()[0] == ['right-index-finger'],
+          str(res.unpack()[0]) if ok else res.message)
+
+    out = spawn_client('verify-start')
+    check('VerifyStart without claim -> ClaimDevice',
+          'error' in out and 'ClaimDevice' in out, out)
+
+    ok, res = call(device, 'ListEnrolledFingers', GLib.Variant('(s)', ('someone-else',)))
+    check('ListEnrolledFingers(other user) -> NoEnrolledPrints',
+          not ok and 'NoEnrolledPrints' in str(res), '')
+
+    ok, res = call(device, 'Claim', GLib.Variant('(s)', ('nebulon',)))
+    check('Claim (client A) ok', ok, '' if ok else res.message)
+
+    out = spawn_client('claim')
+    check('second Claim -> AlreadyInUse', 'AlreadyInUse' in out, out)
+
+    out = spawn_client('verify-start')
+    check('VerifyStart from non-claimer -> error', 'error' in out, out)
+
+    out = spawn_client('release')
+    check('Release from non-claimer -> AlreadyInUse', 'AlreadyInUse' in out, out)
+
+    ok, res = call(device, 'VerifyStart', GLib.Variant('(s)', ('left-thumb',)))
+    check('VerifyStart(unenrolled finger) -> NoEnrolledPrints',
+          not ok and 'NoEnrolledPrints' in str(res), '' if not ok else 'no error')
+
+    call(device, 'Release')
+
+    # Claim owner vanishes -> shim must drop the claim (pam_fprintd relies on
+    # this: on PAM success it just disconnects without calling Release).
+    out = spawn_client('claim-and-exit')
+    check('client B claim ok', out == 'ok', out)
+    time.sleep(0.5)   # let the shim's NameOwnerChanged handler run
+
+    ok, res = call(device, 'Claim', GLib.Variant('(s)', ('nebulon',)))
+    check('claim after claimer disconnect ok (auto-release)', ok,
+          '' if ok else res.message)
+
+    # ---------------------------------------------------- enroll/delete API
+    # (client A holds the claim from the auto-release check above)
+    ok2, res = call(device, 'EnrollStart', GLib.Variant('(s)', ('any',)))
+    check('EnrollStart("any") -> InvalidFingername',
+          not ok2 and 'InvalidFingername' in str(res),
+          '' if not ok2 else 'no error')
+
+    ok2, res = call(device, 'EnrollStop')
+    check('EnrollStop (claimed, idle) -> NoActionInProgress',
+          not ok2 and 'NoActionInProgress' in str(res), '' if not ok2 else 'no error')
+
+    call(device, 'Release')
+    out = spawn_client('enroll-stop')
+    check('EnrollStop (unclaimed) -> ClaimDevice', 'ClaimDevice' in out, out)
+
+    ok2, res = call(device, 'DeleteEnrolledFingers', GLib.Variant('(s)', ('someone-else',)))
+    check('DeleteEnrolledFingers(other user) -> PermissionDenied',
+          not ok2 and 'PermissionDenied' in str(res), '' if not ok2 else 'no error')
+
+    ok2, res = call(device, 'Claim', GLib.Variant('(s)', ('nebulon',)))
+    check('re-claim for delete tests', ok2, '' if ok2 else res.message)
+    if not ok2:
+        print()
+        print(f'{len(failures)} failure(s): {", ".join(failures)}')
+        return 1
+
+    ok2, res = call(device, 'DeleteEnrolledFinger', GLib.Variant('(s)', ('left-thumb',)))
+    check('DeleteEnrolledFinger(unenrolled) -> NoEnrolledPrints',
+          not ok2 and 'NoEnrolledPrints' in str(res), '' if not ok2 else 'no error')
+
+    # Deleting one of several reported fingers must be metadata-only (the
+    # sensor holds a single template; no Wine run).  Seed two fingers.
+    write_state({'nebulon': ['right-index-finger', 'left-thumb']})
+    ok2, res = call(device, 'DeleteEnrolledFinger', GLib.Variant('(s)', ('left-thumb',)))
+    check('DeleteEnrolledFinger(enrolled) ok', ok2, '' if ok2 else res.message)
+    ok2, res = call(device, 'ListEnrolledFingers', GLib.Variant('(s)', ('nebulon',)))
+    check('deleted finger gone, other stays',
+          ok2 and res.unpack()[0] == ['right-index-finger'],
+          str(res.unpack()[0]) if ok2 else res.message)
+    ok2, res = call(device, 'DeleteEnrolledFinger', GLib.Variant('(s)', ('left-thumb',)))
+    check('deleting it again -> NoEnrolledPrints',
+          not ok2 and 'NoEnrolledPrints' in str(res), '' if not ok2 else 'no error')
+
+    call(device, 'Release')
+
+    print()
+    if failures:
+        print(f'{len(failures)} failure(s): {", ".join(failures)}')
+        return 1
+    print('all API checks passed')
+    return 0
+
+
+if __name__ == '__main__':
+    if '--client' in sys.argv:
+        sys.exit(client_main(sys.argv[sys.argv.index('--client') + 1]))
+    sys.exit(main())

+ 92 - 0
work/fprintd-shim/enrolltest.py

@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+"""Enroll-flow client for the fprintd shim (used for dry runs and tests).
+
+Claim -> EnrollStart(finger) -> print EnrollStatus / finger-present /
+finger-needed events until --timeout -> EnrollStop -> Release.
+
+Usage:
+  dbus-run-session -- bash -c '
+      FP_SHIM_STATE_DIR=/tmp/opencode/shim-state-test \
+      python3 work/fprintd-shim/fprintd-shim.py --session 2>shim.log &
+      sleep 1.5
+      python3 work/fprintd-shim/enrolltest.py --timeout 30'
+"""
+
+import argparse
+import time
+
+import gi
+
+gi.require_version('Gio', '2.0')
+gi.require_version('GLib', '2.0')
+from gi.repository import Gio, GLib  # noqa: E402
+
+BUS_NAME = 'net.reactivated.Fprint'
+MANAGER_PATH = '/net/reactivated/Fprint/Manager'
+DEVICE_PATH = '/net/reactivated/Fprint/Device/0'
+IFACE_DEVICE = 'net.reactivated.Fprint.Device'
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--session', action='store_true')
+    parser.add_argument('--user', default='nebulon')
+    parser.add_argument('--finger', default='right-index-finger')
+    parser.add_argument('--timeout', type=float, default=60.0)
+    args = parser.parse_args()
+
+    bus_type = Gio.BusType.SESSION if args.session else Gio.BusType.SYSTEM
+    bus = Gio.bus_get_sync(bus_type, None)
+    device = Gio.DBusProxy.new_sync(
+        bus, Gio.DBusProxyFlags.NONE, None, BUS_NAME, DEVICE_PATH,
+        IFACE_DEVICE, None)
+
+    t0 = time.monotonic()
+    done = {'result': None}
+
+    def stamp():
+        return f'{time.monotonic() - t0:6.1f}s'
+
+    def on_signal(_c, _s, _p, iface, signal, params):
+        if iface == IFACE_DEVICE and signal == 'EnrollStatus':
+            result, is_done = params.unpack()
+            print(f'{stamp()} EnrollStatus        -> {result} (done={is_done})')
+            if is_done:
+                done['result'] = result
+                loop.quit()
+        elif iface == 'org.freedesktop.DBus.Properties':
+            iface_name, changed, _ = params.unpack()
+            if 'finger-present' in changed or 'finger-needed' in changed:
+                present = changed.get('finger-present')
+                needed = changed.get('finger-needed')
+                print(f'{stamp()} properties          -> '
+                      f'finger-present={present} finger-needed={needed}')
+
+    bus.signal_subscribe(BUS_NAME, None, None, DEVICE_PATH, None,
+                         Gio.DBusSignalFlags.NONE, on_signal)
+
+    print(f'{stamp()} Claim({args.user})')
+    device.call_sync('Claim', GLib.Variant('(s)', (args.user,)),
+                     Gio.DBusCallFlags.NONE, 5000, None)
+    print(f'{stamp()} EnrollStart({args.finger}) - touch the sensor ~10 times')
+    device.call_sync('EnrollStart', GLib.Variant('(s)', (args.finger,)),
+                     Gio.DBusCallFlags.NONE, 5000, None)
+
+    loop = GLib.MainLoop()
+    GLib.timeout_add(int(args.timeout * 1000), lambda: (loop.quit(), False)[1])
+    loop.run()
+
+    if done['result'] is None:
+        print(f'{stamp()} timeout, stopping')
+    try:
+        device.call_sync('EnrollStop', None, Gio.DBusCallFlags.NONE, 5000, None)
+        print(f'{stamp()} EnrollStop          -> ok')
+    except GLib.Error as e:
+        print(f'{stamp()} EnrollStop          -> {e.message}')
+    device.call_sync('Release', None, Gio.DBusCallFlags.NONE, 5000, None)
+    print(f'{stamp()} Release             -> ok (result: {done["result"]})')
+    return 0 if done['result'] == 'enroll-completed' else 2
+
+
+if __name__ == '__main__':
+    raise SystemExit(main())

+ 1033 - 0
work/fprintd-shim/fprintd-shim.py

@@ -0,0 +1,1033 @@
+#!/usr/bin/env python3
+"""fprintd-compatible D-Bus service backed by the Wine-sandbox driver.
+
+Drop-in replacement for fprintd's daemon for the Synaptics 06cb:0081 sensor
+that libfprint cannot drive yet.  It serves the `net.reactivated.Fprint` bus
+name with the same Manager/Device API, so GNOME Shell (lock-screen
+re-authentication), gnome-control-center and pam_fprintd work unchanged.
+
+Verification shells out to work/fp-verify.sh (vendor driver under Wine, run
+as the Wine-prefix owner).  Enrollment and deletion drive the harness
+binaries built by work/artifacts/make-enroll-delete.sh:
+  enroll.exe - default flow trimmed to enrollment (touch ~10 times)
+  delete.exe - default flow with enroll() redirected to deleteRecord()
+               (real sensor-side delete, ioctl 0x442034)
+
+The sensor stores a single template (identity c5698517-.../subfactor 0xF6),
+so the per-user finger list in state.json is a mapping onto that one
+template: deleting the last reported finger deletes the sensor record,
+deleting one of several only updates the reported list.
+
+Run with --session for a session-bus smoke test (no root needed, see
+selftest.py / apitest.py).
+"""
+
+import argparse
+import glob
+import json
+import logging
+import os
+import select
+import signal
+import subprocess
+import sys
+import threading
+import time
+
+import gi
+
+gi.require_version('Gio', '2.0')
+gi.require_version('GLib', '2.0')
+from gi.repository import Gio, GLib  # noqa: E402
+
+# ---------------------------------------------------------------- constants
+
+BUS_NAME = 'net.reactivated.Fprint'
+MANAGER_PATH = '/net/reactivated/Fprint/Manager'
+DEVICE_PATH = '/net/reactivated/Fprint/Device/0'
+IFACE_MANAGER = 'net.reactivated.Fprint.Manager'
+IFACE_DEVICE = 'net.reactivated.Fprint.Device'
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+VERIFY_SCRIPT = os.path.join(ROOT, 'work', 'fp-verify.sh')
+SANDBOX = os.path.join(ROOT, 'work', 'synaWudfBioUsb-sandbox')
+WINE64 = os.path.join(ROOT, 'work', 'wine-build', 'install', 'bin', 'wine64')
+ENROLL_EXE = 'enroll.exe'
+DELETE_EXE = 'delete.exe'
+
+# same lock file as work/fp-verify.sh: one sensor access at a time
+VERIFY_LOCK = '/tmp/opencode/fp-verify.lock'
+
+RUN_USER = 'nebulon'
+STATE_DIR = os.environ.get('FP_SHIM_STATE_DIR', '/var/lib/fprintd-shim')
+STATE_FILE = os.path.join(STATE_DIR, 'state.json')
+
+DEVICE_NAME = 'Synaptics 06cb:0081'
+SCAN_TYPE = 'press'
+NUM_ENROLL_STAGES = 10
+
+# pam_fprintd's default per-attempt timeout is 30 s; end our run slightly
+# earlier so a no-touch attempt is a clean pam timeout instead of a bogus
+# "failed to match".
+VERIFY_TIMEOUT = int(os.environ.get('FP_SHIM_VERIFY_TIMEOUT', '26'))
+ENROLL_TIMEOUT = int(os.environ.get('FP_SHIM_ENROLL_TIMEOUT', '900'))
+DELETE_TIMEOUT = int(os.environ.get('FP_SHIM_DELETE_TIMEOUT', '180'))
+
+FINGERS = [
+    'left-thumb', 'left-index-finger', 'left-middle-finger', 'left-ring-finger',
+    'left-little-finger', 'right-thumb', 'right-index-finger',
+    'right-middle-finger', 'right-ring-finger', 'right-little-finger',
+]
+
+# Bus errors
+E_ALREADY_IN_USE = 'net.reactivated.Fprint.Error.AlreadyInUse'
+E_CLAIM_DEVICE = 'net.reactivated.Fprint.Error.ClaimDevice'
+E_INTERNAL = 'net.reactivated.Fprint.Error.Internal'
+E_INVALID_FINGERNAME = 'net.reactivated.Fprint.Error.InvalidFingername'
+E_NO_ACTION = 'net.reactivated.Fprint.Error.NoActionInProgress'
+E_NO_ENROLLED_PRINTS = 'net.reactivated.Fprint.Error.NoEnrolledPrints'
+E_NO_SUCH_DEVICE = 'net.reactivated.Fprint.Error.NoSuchDevice'
+E_PERMISSION_DENIED = 'net.reactivated.Fprint.Error.PermissionDenied'
+E_PRINTS_NOT_DELETED = 'net.reactivated.Fprint.Error.PrintsNotDeleted'
+
+log = logging.getLogger('fprintd-shim')
+
+MANAGER_XML = """
+<node>
+  <interface name="net.reactivated.Fprint.Manager">
+    <method name="GetDevices">
+      <arg type="ao" name="devices" direction="out"/>
+    </method>
+    <method name="GetDefaultDevice">
+      <arg type="o" name="device" direction="out"/>
+    </method>
+  </interface>
+</node>
+"""
+
+DEVICE_XML = """
+<node>
+  <interface name="net.reactivated.Fprint.Device">
+    <method name="ListEnrolledFingers">
+      <arg type="s" name="username" direction="in"/>
+      <arg type="as" name="enrolled_fingers" direction="out"/>
+    </method>
+    <method name="DeleteEnrolledFingers">
+      <arg type="s" name="username" direction="in"/>
+    </method>
+    <method name="DeleteEnrolledFingers2"/>
+    <method name="DeleteEnrolledFinger">
+      <arg type="s" name="finger_name" direction="in"/>
+    </method>
+    <method name="Claim">
+      <arg type="s" name="username" direction="in"/>
+    </method>
+    <method name="Release"/>
+    <method name="VerifyStart">
+      <arg type="s" name="finger_name" direction="in"/>
+    </method>
+    <method name="VerifyStop"/>
+    <method name="EnrollStart">
+      <arg type="s" name="finger_name" direction="in"/>
+    </method>
+    <method name="EnrollStop"/>
+    <signal name="VerifyFingerSelected">
+      <arg type="s" name="finger_name"/>
+    </signal>
+    <signal name="VerifyStatus">
+      <arg type="s" name="result"/>
+      <arg type="b" name="done"/>
+    </signal>
+    <signal name="EnrollStatus">
+      <arg type="s" name="result"/>
+      <arg type="b" name="done"/>
+    </signal>
+    <property name="name" type="s" access="read"/>
+    <property name="num-enroll-stages" type="i" access="read"/>
+    <property name="scan-type" type="s" access="read"/>
+    <property name="finger-present" type="b" access="read"/>
+    <property name="finger-needed" type="b" access="read"/>
+  </interface>
+</node>
+"""
+
+
+def sensor_present():
+    """06cb:0081 attached?  Mirrors fprintd's "no devices" behaviour."""
+    try:
+        for dev in glob.glob('/sys/bus/usb/devices/*'):
+            try:
+                with open(os.path.join(dev, 'idVendor')) as f:
+                    vid = f.read().strip()
+                if vid != '06cb':
+                    continue
+                with open(os.path.join(dev, 'idProduct')) as f:
+                    pid = f.read().strip()
+                if pid == '0081':
+                    return True
+            except OSError:
+                continue
+    except OSError:
+        pass
+    return False
+
+
+def default_fingers(user):
+    """Before any enroll/delete through the shim the sensor already holds the
+    template enrolled with run_aexe.sh; report it for the workstation user."""
+    return ['right-index-finger'] if user == RUN_USER else []
+
+
+def load_state():
+    try:
+        with open(STATE_FILE, encoding='utf-8') as f:
+            state = json.load(f)
+        if isinstance(state, dict) and isinstance(state.get('users'), dict):
+            return state
+        log.warning('%s: unexpected layout, ignoring', STATE_FILE)
+    except FileNotFoundError:
+        pass
+    except (OSError, ValueError) as e:
+        log.warning('cannot read %s: %s', STATE_FILE, e)
+    return {'users': {}}
+
+
+def save_state(state):
+    os.makedirs(STATE_DIR, mode=0o700, exist_ok=True)
+    tmp = f'{STATE_FILE}.tmp'
+    with open(tmp, 'w', encoding='utf-8') as f:
+        json.dump(state, f, indent=2, sort_keys=True)
+        f.write('\n')
+    os.replace(tmp, STATE_FILE)
+
+
+class ShimDevice:
+    def __init__(self):
+        self.conn = None
+        self.claimed_by = None      # unique bus name of the claiming client
+        self.claimed_user = None
+        self.lock = threading.Lock()
+
+        self.verify_proc = None
+        self.verify_thread = None
+        self.verify_cancel = threading.Event()
+        self.verifying = False
+
+        self.enroll_proc = None
+        self.enroll_thread = None
+        self.enroll_cancel = threading.Event()
+        self.enrolling = False
+        self._enroll_commit_started = False
+
+        self.delete_proc = None
+        self.delete_cancel = threading.Event()
+        self.deleting = False
+
+        self.finger_present = False
+        self.finger_needed = False
+
+    # ------------------------------------------------------------ state
+
+    def enrolled_fingers(self, user):
+        if not user:
+            user = RUN_USER
+        users = load_state().get('users', {})
+        if user in users:
+            return list(users[user])
+        return default_fingers(user)
+
+    def _set_enrolled_fingers(self, user, fingers):
+        state = load_state()
+        state.setdefault('users', {})[user] = sorted(set(fingers))
+        save_state(state)
+
+    def _selected_finger(self, finger):
+        """fprintd reports the concrete finger chosen for 'any'."""
+        if finger != 'any':
+            return finger
+        fingers = self.enrolled_fingers(self.claimed_user)
+        return fingers[0] if fingers else 'right-index-finger'
+
+    def _busy(self):
+        return self.verifying or self.enrolling or self.deleting
+
+    # ------------------------------------------------------- emission
+
+    def _emit(self, name, variant):
+        GLib.idle_add(self._emit_now, name, variant)
+
+    def _emit_now(self, name, variant):
+        if self.conn is not None:
+            try:
+                self.conn.emit_signal(None, DEVICE_PATH, IFACE_DEVICE, name,
+                                      variant)
+            except GLib.Error as e:
+                log.warning('cannot emit %s: %s', name, e.message)
+        return GLib.SOURCE_REMOVE
+
+    def _notify_properties(self, changed):
+        if self.conn is None:
+            return
+        try:
+            self.conn.emit_signal(
+                None, DEVICE_PATH, 'org.freedesktop.DBus.Properties',
+                'PropertiesChanged',
+                GLib.Variant('(sa{sv}as)', (IFACE_DEVICE, changed, [])))
+        except GLib.Error as e:
+            log.warning('cannot emit PropertiesChanged: %s', e.message)
+
+    def _set_finger_present(self, value):
+        if self.finger_present == value:
+            return
+        self.finger_present = value
+        self._notify_properties({'finger-present': GLib.Variant('b', value)})
+
+    def _set_finger_needed(self, value):
+        if self.finger_needed == value:
+            return
+        self.finger_needed = value
+        self._notify_properties({'finger-needed': GLib.Variant('b', value)})
+
+    # ------------------------------------------------------- claim ops
+
+    def _release_claim(self, shutdown=False):
+        self._stop_verify(quiet=True)
+        self._stop_enroll(quiet=True)
+        # A running delete is deliberately left to finish: it mutates the
+        # device and aborting it can leave a partially written record (the
+        # client may already be gone; the state is updated when it completes).
+        if shutdown:
+            self._stop_delete(quiet=True)
+        self.claimed_by = None
+        self.claimed_user = None
+        self._notify_properties({'num-enroll-stages': GLib.Variant('i', -1)})
+
+    def _check_claim(self, sender, invocation):
+        """fprintd's _fprint_device_check_claimed for STATE_CLAIMED calls."""
+        if self.claimed_by is None:
+            invocation.return_dbus_error(E_CLAIM_DEVICE,
+                                         'Device was not claimed before use')
+            return False
+        if self.claimed_by != sender:
+            invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                         'Device already in use by another user')
+            return False
+        return True
+
+    # ------------------------------------------------------ process ops
+
+    def _kill_proc(self, proc):
+        if proc is None or proc.poll() is not None:
+            return
+        try:
+            os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
+        except (ProcessLookupError, PermissionError):
+            return
+        try:
+            proc.wait(timeout=5)
+        except subprocess.TimeoutExpired:
+            try:
+                os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
+            except (ProcessLookupError, PermissionError):
+                pass
+
+    def _harness_env(self, binary):
+        env = os.environ.copy()
+        usb_script = f'/tmp/opencode/usb-{binary}-{int(time.time())}.txt'
+        try:
+            os.makedirs('/tmp/opencode', exist_ok=True)
+            # The fake winusb opens USB_SCRIPT for write ("wt") *as the Wine
+            # user* and does not check for failure - a root-owned file makes
+            # the harness hang in init without a single message, so create it
+            # as RUN_USER (verified: winusb.c WinUsb_Initialize).
+            fd = os.open(usb_script, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o666)
+            os.close(fd)
+            if os.geteuid() == 0:
+                import pwd
+                pw = pwd.getpwnam(RUN_USER)
+                os.chown(usb_script, pw.pw_uid, pw.pw_gid)
+        except (OSError, KeyError) as e:
+            log.warning('cannot prepare %s: %s', usb_script, e)
+        env.update({
+            'HOME': os.path.join('/home', RUN_USER),
+            'WINEPREFIX': os.path.join(ROOT, 'work', 'wineprefix-48'),
+            # keep wine quiet, but surface winusb/libfprint errors: a failed
+            # libusb transfer makes the hacked winusb stub exit(0) silently
+            'WINEDEBUG': os.environ.get('FP_SHIM_WINEDEBUG', '-all,err+all'),
+            'USB_PLAYBACK': '',
+            'USB_SCRIPT': usb_script,
+        })
+        return env
+
+    def _harness_cmd(self, binary):
+        cmd = [WINE64, binary]
+        if os.geteuid() == 0:
+            cmd = ['setpriv', f'--reuid={RUN_USER}', f'--regid={RUN_USER}',
+                   '--init-groups'] + cmd
+        # one sensor access at a time (same lock as work/fp-verify.sh)
+        return ['flock', '-w', '60', VERIFY_LOCK] + cmd
+
+    def _run_harness(self, binary, timeout, cancel, on_line, proc_slot=None,
+                     expect_markers=None, first_timeout=120):
+        """Run the Wine harness, feed its stdout lines to on_line().
+
+        Returns (status, returncode) with status in
+        {'eof', 'cancelled', 'timeout', 'stalled'}; the process group is
+        killed on cancel/timeout.  'stalled' means no line of
+        expect_markers was seen within first_timeout (the winusb stub hangs
+        silently when e.g. USB_SCRIPT is not writable by the Wine user).
+        """
+        env = self._harness_env(binary)
+        harness_log = open(
+            f'/tmp/opencode/harness-{binary}-{int(time.time())}.log',
+            'w', encoding='utf-8', errors='replace')
+        log.info('%s: harness log %s', binary, harness_log.name)
+        r, w = os.pipe()
+        proc = subprocess.Popen(self._harness_cmd(binary), cwd=SANDBOX,
+                                env=env, stdin=subprocess.DEVNULL,
+                                stdout=w, stderr=w, start_new_session=True)
+        os.close(w)
+        if proc_slot is not None:
+            proc_slot(proc)
+        started = time.monotonic()
+        deadline = started + timeout
+        status = 'eof'
+        buf = ''
+        saw_first = not expect_markers
+
+        def feed(chunk):
+            nonlocal buf, saw_first
+            buf += chunk
+            while '\n' in buf:
+                line, buf = buf.split('\n', 1)
+                line = line.rstrip('\r')
+                harness_log.write(line + '\n')
+                harness_log.flush()
+                if not saw_first and any(m in line for m in expect_markers):
+                    saw_first = True
+                if on_line is not None:
+                    on_line(line)
+
+        while True:
+            if cancel.is_set():
+                self._kill_proc(proc)
+                status = 'cancelled'
+                break
+            if time.monotonic() > deadline:
+                log.warning('%s: timeout after %ss', binary, timeout)
+                self._kill_proc(proc)
+                status = 'timeout'
+                break
+            if not saw_first and time.monotonic() - started > first_timeout:
+                log.error('%s: no progress in %ss (winusb init hang?) - '
+                          'killing; see %s', binary, first_timeout,
+                          harness_log.name)
+                self._kill_proc(proc)
+                status = 'stalled'
+                break
+            ready, _, _ = select.select([r], [], [], 0.2)
+            if ready:
+                try:
+                    chunk = os.read(r, 65536)
+                except OSError:
+                    chunk = b''
+                if not chunk:
+                    break
+                feed(chunk.decode('utf-8', 'replace'))
+            elif proc.poll() is not None:
+                # child exited: drain whatever is left in the pipe
+                while True:
+                    ready, _, _ = select.select([r], [], [], 0)
+                    if not ready:
+                        break
+                    try:
+                        chunk = os.read(r, 65536)
+                    except OSError:
+                        chunk = b''
+                    if not chunk:
+                        break
+                    feed(chunk.decode('utf-8', 'replace'))
+                break
+
+        code = proc.wait()
+        os.close(r)
+        harness_log.close()
+        if proc_slot is not None:
+            proc_slot(None)
+        return status, code
+
+    # ------------------------------------------------------ verify ops
+
+    def _stop_verify(self, quiet=False):
+        with self.lock:
+            running = self.verifying
+            self.verifying = False
+            self.verify_cancel.set()
+            proc = self.verify_proc
+            self.verify_proc = None
+        self._kill_proc(proc)
+        if running and not quiet:
+            log.info('verify stopped by client')
+        return running
+
+    def _verify_cmd(self):
+        script = ['/bin/bash', VERIFY_SCRIPT]
+        if os.geteuid() == 0:
+            return ['setpriv', f'--reuid={RUN_USER}', f'--regid={RUN_USER}',
+                    '--init-groups'] + script
+        # session-bus smoke test: we are already the prefix owner
+        return script
+
+    def _verify_worker(self, finger):
+        try:
+            self._emit('VerifyFingerSelected', GLib.Variant('(s)', (finger,)))
+
+            env = os.environ.copy()
+            env['FP_VERIFY_TIMEOUT'] = str(VERIFY_TIMEOUT)
+            env['FP_VERIFY_QUIET'] = '1'
+            env['FP_VERIFY_LOCK_WAIT'] = '20'
+
+            for attempt in (1, 2):      # one internal retry for flaky Wine/USB
+                if self.verify_cancel.is_set():
+                    return
+                started = time.monotonic()
+                proc = subprocess.Popen(
+                    self._verify_cmd(), env=env, text=True,
+                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                    start_new_session=True)
+                with self.lock:
+                    self.verify_proc = proc
+                try:
+                    out, _ = proc.communicate(timeout=VERIFY_TIMEOUT + 20)
+                except subprocess.TimeoutExpired:
+                    self._kill_proc(proc)
+                    out, _ = proc.communicate()
+                    rc = 124
+                else:
+                    rc = proc.returncode
+                elapsed = time.monotonic() - started
+                for line in (out or '').splitlines():
+                    log.info('verify[%d]: %s', attempt, line)
+                with self.lock:
+                    self.verify_proc = None
+
+                if self.verify_cancel.is_set():
+                    return
+
+                if rc == 0:
+                    self._emit('VerifyStatus',
+                               GLib.Variant('(sb)', ('verify-match', True)))
+                    return
+                if rc == 1:
+                    self._emit('VerifyStatus',
+                               GLib.Variant('(sb)', ('verify-no-match', True)))
+                    return
+                # rc 2: timeout (no finger) or Wine/USB error.  A quick exit
+                # means the sandbox failed before the touch window; retry once.
+                if attempt == 1 and elapsed < VERIFY_TIMEOUT - 5:
+                    log.warning('verify run failed early (%.1fs, rc=%d), retrying',
+                                elapsed, rc)
+                    continue
+                log.info('no terminal status (rc=%d after %.1fs); '
+                         'pam_fprintd will time out', rc, elapsed)
+                return
+        finally:
+            with self.lock:
+                self.verify_proc = None
+            # NOTE: keep self.verifying set after a terminal status: fprintd's
+            # action stays ACTION_VERIFY until VerifyStop/Release (clients like
+            # fprintd-verify call VerifyStop after the result and expect it to
+            # succeed).
+
+    def _start_verify(self, finger):
+        with self.lock:
+            if self._busy():
+                return False
+            self.verifying = True
+            self.verify_cancel.clear()
+        self.verify_thread = threading.Thread(
+            target=self._verify_worker, args=(finger,), daemon=True)
+        self.verify_thread.start()
+        return True
+
+    # ------------------------------------------------------ enroll ops
+
+    def _stop_enroll(self, quiet=False):
+        with self.lock:
+            running = self.enrolling
+            commit_started = self._enroll_commit_started
+            proc = self.enroll_proc
+        if commit_started and proc is not None and proc.poll() is None:
+            # The template write is in flight: let it finish instead of
+            # risking a partially written record.  The action stays "in
+            # progress" until the worker completes.
+            log.info('enroll: commit in progress, not aborting')
+            return running
+        with self.lock:
+            self.enrolling = False
+            self.enroll_cancel.set()
+            self.enroll_proc = None
+        self._kill_proc(proc)
+        self._set_finger_needed(False)
+        self._set_finger_present(False)
+        if running and not quiet:
+            log.info('enrollment stopped by client')
+        return running
+
+    def _enroll_worker(self, user, finger):
+        """Drive `wine enroll.exe`; map the harness output to EnrollStatus.
+
+        Markers (see hello.cc enroll()/commitEnrollment()):
+          "about to Create Enrollment"
+          "about to IOCTL_BIOMETRIC_CAPTURE_DATA"  <- waiting for a touch
+          "about to Update Enrollment"             <- capture accepted
+          "Got back 0x.. bytes: <hex>"             <- response; hex[1:2] is
+                                                      the stage state (00 = done)
+          "about to Check For Duplicate" / "about to Commit Enrollment"
+        A capture marker that follows another capture marker (without an
+        Update Enrollment in between) is a rejected scan (SensorStatus 2).
+        """
+        st = {'capture_open': False, 'expect': None, 'stages': 0,
+              'complete': False, 'committed': False}
+
+        def on_line(line):
+            if line == 'about to IOCTL_BIOMETRIC_CAPTURE_DATA':
+                if st['capture_open']:
+                    log.info('enroll: scan rejected, retry')
+                    self._emit('EnrollStatus',
+                               GLib.Variant('(sb)', ('enroll-retry-scan', False)))
+                    self._set_finger_present(False)
+                st['capture_open'] = True
+                st['expect'] = None
+                self._set_finger_needed(True)
+            elif line == 'about to Update Enrollment':
+                st['capture_open'] = False
+                st['expect'] = 'update'
+                self._set_finger_needed(False)
+                self._set_finger_present(True)
+            elif line == 'about to Check For Duplicate':
+                st['expect'] = 'duplicate'
+            elif line == 'about to Commit Enrollment':
+                st['expect'] = 'commit'
+                self._enroll_commit_started = True
+            elif line.startswith('Got back 0x') and st['expect']:
+                kind, st['expect'] = st['expect'], None
+                hexpart = line.split(':', 1)[1].strip() if ':' in line else ''
+                first = hexpart[:2].lower()
+                if kind == 'update':
+                    self._set_finger_present(False)
+                    if first == '00':
+                        st['complete'] = True
+                    else:
+                        st['stages'] += 1
+                        log.info('enroll: stage %d passed', st['stages'])
+                        self._emit('EnrollStatus',
+                                   GLib.Variant('(sb)', ('enroll-stage-passed', False)))
+                        self._set_finger_needed(True)
+                elif kind == 'commit':
+                    st['committed'] = True
+                    log.info('enroll: committed')
+                    self._set_finger_present(False)
+                    self._set_finger_needed(False)
+
+        def slot(proc):
+            with self.lock:
+                self.enroll_proc = proc
+
+        try:
+            # A commit that replaces an existing record makes the device
+            # re-enumerate mid-write; the hacked winusb stub cannot detect
+            # reconnects and exits with LIBUSB_ERROR_NO_DEVICE (verified
+            # 2026-10-15 13:11-13:12, harness logs).  The delete ioctl does
+            # not reset the device, and a fresh write commits reliably, so
+            # clear any existing record first.
+            if self.enrolled_fingers(user):
+                log.info('enroll: existing record for %s, deleting it first',
+                         user)
+            dstatus, dcode = self._run_harness(
+                DELETE_EXE, DELETE_TIMEOUT, self.enroll_cancel, None, slot,
+                expect_markers=('about to 442034',))
+            d_ok = (dstatus == 'eof' and dcode == 0)
+            log.info('enroll: pre-delete %s (harness %s rc=%s)',
+                     'ok' if d_ok else 'FAILED', dstatus, dcode)
+            if d_ok:
+                # the device has no record now: report that honestly even if
+                # the enrollment is aborted later on
+                self._set_enrolled_fingers(user, [])
+            if self.enroll_cancel.is_set():
+                log.info('enroll: cancelled before start')
+                return
+
+            status, code = self._run_harness(
+                ENROLL_EXE, ENROLL_TIMEOUT, self.enroll_cancel, on_line, slot,
+                expect_markers=('about to setMode', 'about to Create Enrollment',
+                                'about to IOCTL_BIOMETRIC_CAPTURE_DATA'))
+            # A committed template is on the device even if the client went
+            # away meanwhile: always record it and report completion.
+            if st['committed']:
+                self._set_enrolled_fingers(user, [finger])
+                log.info('enroll: user %s -> %s (harness %s rc=%s)',
+                         user, finger, status, code)
+                self._emit('EnrollStatus',
+                           GLib.Variant('(sb)', ('enroll-completed', True)))
+            elif self.enroll_cancel.is_set():
+                log.info('enroll: cancelled')
+            else:
+                log.warning('enroll: not committed (harness %s rc=%s, '
+                            '%d stages)', status, code, st['stages'])
+                self._emit('EnrollStatus',
+                           GLib.Variant('(sb)', ('enroll-failed', True)))
+        finally:
+            with self.lock:
+                self.enroll_proc = None
+                if self.claimed_by is None or self.enroll_cancel.is_set():
+                    # no client is waiting for a stop reply any more
+                    self.enrolling = False
+            self._set_finger_needed(False)
+            self._set_finger_present(False)
+            # NOTE: like verify, keep self.enrolling set (pending EnrollStop)
+            # when the client is still connected after a terminal status.
+
+    def _start_enroll(self, user, finger):
+        with self.lock:
+            if self._busy():
+                return False
+            self.enrolling = True
+            self._enroll_commit_started = False
+            self.enroll_cancel.clear()
+        self.enroll_thread = threading.Thread(
+            target=self._enroll_worker, args=(user, finger), daemon=True)
+        self.enroll_thread.start()
+        return True
+
+    # ------------------------------------------------------ delete ops
+
+    def _stop_delete(self, quiet=True):
+        with self.lock:
+            running = self.deleting
+            self.deleting = False
+            proc = self.delete_proc
+            self.delete_proc = None
+        self.delete_cancel.set()
+        self._kill_proc(proc)
+        if running and not quiet:
+            log.info('delete cancelled')
+        return running
+
+    def _delete_worker(self, invocation, user, remove):
+        """Remove fingers from the reported list; when the list becomes empty
+        also delete the sensor-side template (delete.exe)."""
+        ok, message = True, None
+        try:
+            fingers = self.enrolled_fingers(user)
+            remaining = [f for f in fingers if f not in remove]
+            if fingers and not remaining:
+                # Optimistic state update: the client (gnome-control-center)
+                # re-reads the list right after the call and gives up after
+                # ~10 s - reflect the deletion immediately, restore below if
+                # the harness fails.
+                self._set_enrolled_fingers(user, remaining)
+
+                def slot(proc):
+                    with self.lock:
+                        self.delete_proc = proc
+                status, code = self._run_harness(
+                    DELETE_EXE, DELETE_TIMEOUT, self.delete_cancel, None, slot,
+                    expect_markers=('about to 442034',))
+                ok = (status == 'eof' and code == 0)
+                log.info('delete: sensor record removal %s (harness %s rc=%s)',
+                         'ok' if ok else 'FAILED', status, code)
+                if not ok:
+                    message = 'Could not delete the print from the device'
+                    self._set_enrolled_fingers(user, fingers)   # restore
+            elif remaining:
+                self._set_enrolled_fingers(user, remaining)
+            # NOTE: the state update happens even if the client released the
+            # claim meanwhile - the device record is gone and must not be
+            # reported as enrolled.
+        except Exception:
+            log.exception('delete failed')
+            ok, message = False, 'Internal error while deleting'
+        finally:
+            with self.lock:
+                self.delete_proc = None
+                self.deleting = False
+        GLib.idle_add(self._finish_delete, invocation, ok, message)
+
+    def _finish_delete(self, invocation, ok, message):
+        try:
+            if ok:
+                invocation.return_value(None)
+            else:
+                invocation.return_dbus_error(
+                    E_PRINTS_NOT_DELETED,
+                    message or 'Fingerprint was not deleted')
+        except GLib.Error as e:
+            # client already gave up / connection closed
+            log.info('delete reply not delivered: %s', e.message)
+        return GLib.SOURCE_REMOVE
+
+    # ------------------------------------------------ D-Bus callbacks
+
+    def on_method_call(self, conn, sender, path, iface, method, params, invocation):
+        try:
+            self._dispatch(sender, path, iface, method, params, invocation)
+        except Exception:  # never kill the service on a bug
+            log.exception('method %s.%s failed', iface, method)
+            invocation.return_dbus_error(E_INTERNAL, 'shim internal error')
+
+    def _dispatch(self, sender, path, iface, method, params, invocation):
+        if iface == IFACE_MANAGER:
+            return self._dispatch_manager(method, invocation)
+        if iface == IFACE_DEVICE:
+            return self._dispatch_device(sender, method, params, invocation)
+        invocation.return_dbus_error(E_INTERNAL, f'unknown interface {iface}')
+
+    def _dispatch_manager(self, method, invocation):
+        if method == 'GetDevices':
+            devices = [DEVICE_PATH] if sensor_present() else []
+            invocation.return_value(GLib.Variant('(ao)', (devices,)))
+        elif method == 'GetDefaultDevice':
+            if not sensor_present():
+                invocation.return_dbus_error(E_NO_SUCH_DEVICE,
+                                             'No fingerprint device present')
+            else:
+                invocation.return_value(GLib.Variant('(o)', (DEVICE_PATH,)))
+        else:
+            invocation.return_dbus_error(E_INTERNAL, f'unknown method {method}')
+
+    def _dispatch_device(self, sender, method, params, invocation):
+        if method == 'ListEnrolledFingers':
+            (user,) = params.unpack()
+            fingers = self.enrolled_fingers(user)
+            if not fingers:
+                invocation.return_dbus_error(
+                    E_NO_ENROLLED_PRINTS, 'No enrolled prints for user')
+            else:
+                invocation.return_value(GLib.Variant('(as)', (fingers,)))
+
+        elif method == 'Claim':
+            (user,) = params.unpack()
+            if self.claimed_by is not None:
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Device already in use')
+                return
+            self.claimed_by = sender
+            self.claimed_user = user or RUN_USER
+            log.info('claim by %s for user %s', sender, self.claimed_user)
+            self._notify_properties(
+                {'num-enroll-stages': GLib.Variant('i', NUM_ENROLL_STAGES)})
+            invocation.return_value(None)
+
+        elif method == 'Release':
+            if not self._check_claim(sender, invocation):
+                return
+            self._release_claim()
+            log.info('release by %s', sender)
+            invocation.return_value(None)
+
+        elif method == 'VerifyStart':
+            (finger,) = params.unpack()
+            if not self._check_claim(sender, invocation):
+                return
+            if finger not in FINGERS and finger != 'any':
+                invocation.return_dbus_error(E_INVALID_FINGERNAME,
+                                             f'Invalid finger name {finger}')
+                return
+            fingers = self.enrolled_fingers(self.claimed_user)
+            if not fingers or (finger != 'any' and finger not in fingers):
+                invocation.return_dbus_error(
+                    E_NO_ENROLLED_PRINTS, 'No enrolled prints for user')
+                return
+            if not self._start_verify(self._selected_finger(finger)):
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            log.info('verify start (%s) by %s', finger, sender)
+            invocation.return_value(None)
+
+        elif method == 'VerifyStop':
+            if not self._check_claim(sender, invocation):
+                return
+            if not self._stop_verify():
+                invocation.return_dbus_error(E_NO_ACTION,
+                                             'No verification in progress')
+                return
+            invocation.return_value(None)
+
+        elif method == 'EnrollStart':
+            (finger,) = params.unpack()
+            if not self._check_claim(sender, invocation):
+                return
+            if finger not in FINGERS:
+                invocation.return_dbus_error(
+                    E_INVALID_FINGERNAME,
+                    f'Invalid finger name {finger} (not "any")')
+                return
+            if not self._start_enroll(self.claimed_user, finger):
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            log.info('enroll start (%s) by %s', finger, sender)
+            invocation.return_value(None)
+
+        elif method == 'EnrollStop':
+            if not self._check_claim(sender, invocation):
+                return
+            if not self._stop_enroll():
+                invocation.return_dbus_error(E_NO_ACTION,
+                                             'No enrollment in progress')
+                return
+            invocation.return_value(None)
+
+        elif method == 'DeleteEnrolledFinger':
+            (finger,) = params.unpack()
+            if not self._check_claim(sender, invocation):
+                return
+            if finger not in FINGERS:
+                invocation.return_dbus_error(E_INVALID_FINGERNAME,
+                                             f'Invalid finger name {finger}')
+                return
+            if self._busy():
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            fingers = self.enrolled_fingers(self.claimed_user)
+            if finger not in fingers:
+                invocation.return_dbus_error(
+                    E_NO_ENROLLED_PRINTS,
+                    f'Finger {finger} is not enrolled for this user')
+                return
+            self._start_delete(invocation, self.claimed_user, [finger])
+
+        elif method == 'DeleteEnrolledFingers2':
+            if not self._check_claim(sender, invocation):
+                return
+            if self._busy():
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            fingers = self.enrolled_fingers(self.claimed_user)
+            if not fingers:
+                invocation.return_dbus_error(
+                    E_NO_ENROLLED_PRINTS, 'No enrolled prints for user')
+                return
+            self._start_delete(invocation, self.claimed_user, fingers)
+
+        elif method == 'DeleteEnrolledFingers':
+            (user,) = params.unpack()
+            user = user or self.claimed_user or RUN_USER
+            if user != RUN_USER:
+                invocation.return_dbus_error(
+                    E_PERMISSION_DENIED,
+                    'Only the local user is supported by the shim')
+                return
+            if self.claimed_by is not None and self.claimed_by != sender:
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Device already in use by another user')
+                return
+            if self._busy():
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            fingers = self.enrolled_fingers(user)
+            if not fingers:
+                invocation.return_dbus_error(
+                    E_NO_ENROLLED_PRINTS, 'No enrolled prints for user')
+                return
+            self._start_delete(invocation, user, fingers)
+
+        else:
+            invocation.return_dbus_error(E_INTERNAL, f'unknown method {method}')
+
+    def _start_delete(self, invocation, user, remove):
+        with self.lock:
+            if self._busy():
+                invocation.return_dbus_error(E_ALREADY_IN_USE,
+                                             'Another operation is in progress')
+                return
+            self.deleting = True
+            self.delete_cancel.clear()
+        log.info('delete start: user=%s fingers=%s', user, ','.join(remove))
+        thread = threading.Thread(target=self._delete_worker,
+                                  args=(invocation, user, remove), daemon=True)
+        thread.start()
+
+    def on_get_property(self, conn, sender, path, iface, prop):
+        if iface != IFACE_DEVICE:
+            return None
+        if prop == 'name':
+            return GLib.Variant('s', DEVICE_NAME)
+        if prop == 'scan-type':
+            return GLib.Variant('s', SCAN_TYPE)
+        if prop == 'num-enroll-stages':
+            stages = NUM_ENROLL_STAGES if self.claimed_by else -1
+            return GLib.Variant('i', stages)
+        if prop == 'finger-present':
+            return GLib.Variant('b', self.finger_present)
+        if prop == 'finger-needed':
+            return GLib.Variant('b', self.finger_needed)
+        return None
+
+    def on_name_owner_changed(self, conn, sender, path, iface, signal_name, params):
+        name, _old, new = params.unpack()
+        if new:
+            return
+        if name == self.claimed_by:
+            log.info('claiming client %s vanished, releasing device', name)
+            self._release_claim()
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('--session', action='store_true',
+                        help='own the name on the session bus (smoke test)')
+    parser.add_argument('--debug', action='store_true')
+    args = parser.parse_args()
+
+    logging.basicConfig(
+        level=logging.DEBUG if args.debug else logging.INFO,
+        format='fprintd-shim: %(levelname)s: %(message)s',
+        stream=sys.stderr)
+
+    bus_type = Gio.BusType.SESSION if args.session else Gio.BusType.SYSTEM
+    device = ShimDevice()
+    loop = GLib.MainLoop()
+
+    manager_info = Gio.DBusNodeInfo.new_for_xml(MANAGER_XML).interfaces[0]
+    device_info = Gio.DBusNodeInfo.new_for_xml(DEVICE_XML).interfaces[0]
+
+    def on_bus_acquired(conn, _name):
+        device.conn = conn
+        conn.register_object(MANAGER_PATH, manager_info,
+                             device.on_method_call, device.on_get_property, None)
+        conn.register_object(DEVICE_PATH, device_info,
+                             device.on_method_call, device.on_get_property, None)
+        conn.signal_subscribe(
+            'org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged',
+            '/org/freedesktop/DBus', None, Gio.DBusSignalFlags.NONE,
+            device.on_name_owner_changed)
+        log.info('serving %s (device %s, state %s, enroll/delete via %s)',
+                 BUS_NAME, DEVICE_PATH, STATE_FILE, SANDBOX)
+
+    def on_name_lost(_conn, _name):
+        log.warning('lost bus name %s', BUS_NAME)
+        device._release_claim()
+        loop.quit()
+
+    def on_term(_signum, _frame):
+        log.info('shutting down')
+        device._release_claim()
+        loop.quit()
+
+    signal.signal(signal.SIGTERM, on_term)
+    signal.signal(signal.SIGINT, on_term)
+
+    Gio.bus_own_name(bus_type, BUS_NAME, Gio.BusNameOwnerFlags.NONE,
+                     on_bus_acquired, None, on_name_lost)
+    loop.run()
+
+
+if __name__ == '__main__':
+    main()

+ 23 - 0
work/fprintd-shim/fprintd.service

@@ -0,0 +1,23 @@
+# Shadow file for the packaged fprintd unit; installed to
+# /etc/systemd/system/fprintd.service by install.sh.  It serves the same
+# bus name (net.reactivated.Fprint) with the Wine-sandbox-backed shim for
+# the Synaptics 06cb:0081 sensor.
+#
+# NOTE: the packaged unit's sandbox (ProtectHome=true, PrivateTmp=true,
+# StateDirectory=... etc.) must not be inherited here: the Wine prefix and
+# the verify logs live under /home/nebulon and /tmp.
+[Unit]
+Description=Fingerprint Authentication Daemon (Wine sandbox shim, 06cb:0081)
+Documentation=man:fprintd(1) file:///home/nebulon/projects/fingerprint/README.md
+After=dbus.service
+
+[Service]
+Type=dbus
+BusName=net.reactivated.Fprint
+ExecStart=/home/nebulon/projects/fingerprint/work/fprintd-shim/run.sh
+# enroll/delete state (finger lists per user) lives here
+StateDirectory=fprintd-shim
+StateDirectoryMode=0700
+KillMode=mixed
+TimeoutStopSec=15
+Restart=no

+ 37 - 0
work/fprintd-shim/install.sh

@@ -0,0 +1,37 @@
+#!/bin/bash
+# Install the phase-1 fprintd shim: serve net.reactivated.Fprint from
+# work/fprintd-shim instead of the packaged fprintd daemon, so GNOME Shell
+# (lock screen), pam_fprintd and fprintd-* tools see the 06cb:0081 sensor.
+#
+# Rollback: work/fprintd-shim/uninstall.sh
+set -euo pipefail
+
+SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+UNIT=/etc/systemd/system/fprintd.service
+
+if [ "$(id -u)" != "0" ]; then
+    echo "install.sh: run as root (sudo $0)" >&2
+    exit 1
+fi
+
+command -v python3 >/dev/null || { echo "install.sh: python3 missing" >&2; exit 1; }
+python3 -c 'import gi; gi.require_version("Gio", "2.0"); from gi.repository import Gio' \
+    || { echo "install.sh: python-gobject (gi) is required" >&2; exit 1; }
+[ -e /usr/lib/security/pam_fprintd.so ] \
+    || echo "install.sh: warning: pam_fprintd.so not found (install the fprintd package)"
+
+chmod +x "$SELF_DIR/fprintd-shim.py" "$SELF_DIR/run.sh" "$SELF_DIR/selftest.py"
+python3 -B -m py_compile "$SELF_DIR/fprintd-shim.py"
+rm -rf "$SELF_DIR/__pycache__"   # py_compile as root must not leave root-owned files
+
+echo "installing $UNIT (shadows the packaged fprintd.service)"
+install -m 0644 "$SELF_DIR/fprintd.service" "$UNIT"
+systemctl daemon-reload
+systemctl stop fprintd 2>/dev/null || true
+systemctl start fprintd
+sleep 0.3
+systemctl --no-pager --full status fprintd | head -n 12 || true
+
+echo
+echo "Installed.  Smoke test (as your user):  fprintd-list \$USER"
+echo "Rollback:                               sudo $SELF_DIR/uninstall.sh"

+ 3 - 0
work/fprintd-shim/run.sh

@@ -0,0 +1,3 @@
+#!/bin/bash
+# Entry point for the fprintd shim systemd unit.
+exec /usr/bin/python3 -u /home/nebulon/projects/fingerprint/work/fprintd-shim/fprintd-shim.py "$@"

+ 131 - 0
work/fprintd-shim/selftest.py

@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Smoke-test client for the fprintd shim; mimics pam_fprintd's call flow.
+
+GetDevices -> ListEnrolledFingers -> Claim -> VerifyStart('any')
+   waits for VerifyStatus (touch the sensor) until --timeout
+   -> VerifyStop -> Release
+
+Exits 0 when a verify outcome (match/no-match) or a clean timeout was seen.
+
+Usage:
+  # on the system bus (installed service):
+  work/fprintd-shim/selftest.py [--user nebulon] [--timeout 12]
+
+  # on a private session bus (no root needed):
+  dbus-run-session -- bash -c '
+      python3 work/fprintd-shim/fprintd-shim.py --session &
+      sleep 1
+      python3 work/fprintd-shim/selftest.py --session --user nebulon --timeout 12
+      kill %1'
+"""
+
+import argparse
+import sys
+
+import gi
+
+gi.require_version('Gio', '2.0')
+gi.require_version('GLib', '2.0')
+from gi.repository import Gio, GLib  # noqa: E402
+
+BUS_NAME = 'net.reactivated.Fprint'
+MANAGER_PATH = '/net/reactivated/Fprint/Manager'
+IFACE_MANAGER = 'net.reactivated.Fprint.Manager'
+IFACE_DEVICE = 'net.reactivated.Fprint.Device'
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--session', action='store_true')
+    parser.add_argument('--user', default='nebulon')
+    parser.add_argument('--timeout', type=float, default=12.0,
+                        help='seconds to wait for a verify result')
+    args = parser.parse_args()
+
+    bus_type = Gio.BusType.SESSION if args.session else Gio.BusType.SYSTEM
+    bus = Gio.bus_get_sync(bus_type, None)
+
+    manager = Gio.DBusProxy.new_sync(
+        bus, Gio.DBusProxyFlags.NONE, None, BUS_NAME, MANAGER_PATH,
+        IFACE_MANAGER, None)
+
+    devices = manager.call_sync('GetDevices', None,
+                                Gio.DBusCallFlags.NONE, 5000, None).unpack()[0]
+    print(f'GetDevices            -> {list(devices)}')
+    if not devices:
+        print('FAIL: no devices')
+        return 1
+
+    default = manager.call_sync('GetDefaultDevice', None,
+                                Gio.DBusCallFlags.NONE, 5000, None).unpack()[0]
+    print(f'GetDefaultDevice      -> {default}')
+
+    device = Gio.DBusProxy.new_sync(
+        bus, Gio.DBusProxyFlags.NONE, None, BUS_NAME, default,
+        IFACE_DEVICE, None)
+    print(f'properties            -> name={device.get_cached_property("name")!r} '
+          f'scan-type={device.get_cached_property("scan-type")!r} '
+          f'num-enroll-stages={device.get_cached_property("num-enroll-stages")!r}')
+
+    result = {'status': None, 'reason': 'timeout before any verify result'}
+    loop = GLib.MainLoop()
+
+    def on_signal(_conn, _sender, _path, iface, signal, params):
+        if iface != IFACE_DEVICE:
+            return
+        if signal == 'VerifyFingerSelected':
+            print(f'VerifyFingerSelected  -> {params.unpack()[0]}')
+        elif signal == 'VerifyStatus':
+            status, done = params.unpack()
+            print(f'VerifyStatus          -> {status} (done={done})')
+            result['status'] = status
+            result['reason'] = 'terminal verify status'
+            if done:
+                loop.quit()
+    bus.signal_subscribe(BUS_NAME, IFACE_DEVICE, None, default, None,
+                         Gio.DBusSignalFlags.NONE, on_signal)
+
+    try:
+        fingers = device.call_sync('ListEnrolledFingers', GLib.Variant('(s)', (args.user,)),
+                                   Gio.DBusCallFlags.NONE, 5000, None).unpack()[0]
+        print(f'ListEnrolledFingers   -> {list(fingers)}')
+    except GLib.Error as e:
+        print(f'ListEnrolledFingers   -> error {e.message}')
+        fingers = []
+    if not fingers:
+        print('FAIL: no enrolled fingers reported')
+        return 1
+
+    device.call_sync('Claim', GLib.Variant('(s)', (args.user,)),
+                     Gio.DBusCallFlags.NONE, 5000, None)
+    print('Claim                 -> ok')
+    print(f'                      (touch the sensor, waiting {args.timeout:.0f}s)')
+    device.call_sync('VerifyStart', GLib.Variant('(s)', ('any',)),
+                     Gio.DBusCallFlags.NONE, 5000, None)
+
+    def give_up():
+        result['reason'] = 'timeout waiting for a verify result'
+        loop.quit()
+        return GLib.SOURCE_REMOVE
+    GLib.timeout_add(int(args.timeout * 1000), give_up)
+    loop.run()
+
+    try:
+        device.call_sync('VerifyStop', None, Gio.DBusCallFlags.NONE, 5000, None)
+        print('VerifyStop            -> ok')
+    except GLib.Error as e:
+        print(f'VerifyStop            -> {e.message}')
+    device.call_sync('Release', None, Gio.DBusCallFlags.NONE, 5000, None)
+    print('Release               -> ok')
+
+    print(f'result: {result["reason"]}'
+          + (f' ({result["status"]})' if result['status'] else ''))
+    if result['status'] == 'verify-match':
+        return 0
+    if result['status'] == 'verify-no-match':
+        return 1
+    return 2
+
+
+if __name__ == '__main__':
+    sys.exit(main())

+ 23 - 0
work/fprintd-shim/uninstall.sh

@@ -0,0 +1,23 @@
+#!/bin/bash
+# Remove the phase-1 fprintd shim unit; the packaged fprintd daemon is
+# D-Bus activated again on demand.
+set -euo pipefail
+
+SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+UNIT=/etc/systemd/system/fprintd.service
+
+if [ "$(id -u)" != "0" ]; then
+    echo "uninstall.sh: run as root (sudo $0)" >&2
+    exit 1
+fi
+
+systemctl stop fprintd 2>/dev/null || true
+if [ -f "$UNIT" ]; then
+    rm -f "$UNIT"
+    echo "removed $UNIT"
+else
+    echo "no local unit at $UNIT (nothing to do)"
+fi
+systemctl daemon-reload
+systemctl reset-failed fprintd 2>/dev/null || true
+echo "Done.  fprintd-list will show 'No devices available' again until reinstalled."