diff --git a/.env.example b/.env.example index 267ed66..bed4e7d 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,16 @@ APPLE_API_ISSUER= APPLE_API_KEY= APPLE_API_KEY_PATH= +# --- Mac App Store edition (scripts/release-appstore.sh) ---------------------------------- +# "Apple Distribution: Jane Doe (TEAMID1234)" (signs the app) +APPLE_DISTRIBUTION_IDENTITY= +# "3rd Party Mac Developer Installer: Jane Doe (TEAMID1234)" (signs the .pkg) +APPLE_INSTALLER_IDENTITY= +# "Mac App Store Connect" provisioning profile for com.patchbay.patchprobe (keep it outside the repo) +APPLE_PROVISIONING_PROFILE= +# Optional: CFBundleVersion of the upload (defaults to a yyyymmddHHMM timestamp) +BUILD_NUMBER= + # --- Tauri updater signing (only if the updater plugin is ever enabled) ---------------- # Generated with `npm run tauri signer generate`; never commit the private key. TAURI_SIGNING_PRIVATE_KEY= diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d53ddd2..b252092 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,6 +56,11 @@ Release builds (`npm run tauri build`) need signing credentials only for signed/ packages; see [`.env.example`](.env.example). Never commit certificates, keys or passwords. +For a Developer ID signed and notarized macOS build, fill `.env` and run +`rust/app/scripts/release-macos.sh` from Terminal.app. The Mac App Store edition +(sandboxed: no MAC addresses, traceroute or nmap) is packaged by +`rust/app/scripts/release-appstore.sh`, which produces a signed `.pkg` for Transporter. + ## Conventions - **Layering**: pure logic, parsers and protocols go in `PatchProbe-core` (no UI, no diff --git a/README.md b/README.md index dcbcdad..91d81cb 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Everything runs locally: no account, no cloud, no telemetry. Written in Rust Built with Tauri 2 Runs on macOS, Windows and Linux - Status: pre-release + Status: 1.0


@@ -88,6 +88,8 @@ Everything runs locally: no account, no cloud, no telemetry. - Every technique returns a typed result (*found*, *no name* with the reason, *timeout*, *error*, *skipped*). The **name diagnostic** panel shows the full trace for a host and can re-run every technique on demand. +- **Default name source** setting: the HTML title of web services is shown first by default + (best for self-hosted services); pick any other technique, or the automatic order, in Settings. - A per-IP cache keeps found names for 7 days; failures are only remembered for 5 minutes. - All protocol decoders are hand-written, bounds-checked and tested against truncated and corrupted packets. @@ -101,6 +103,9 @@ Everything runs locally: no account, no cloud, no telemetry. - Vendor lookup in the **embedded IEEE OUI registry** (about 39,000 entries), offline. - **Manual vendor correction per MAC address**, to relabel a device or fix a randomized MAC. - **Wake-on-LAN** magic packet from the host details. +- On **macOS 27**, the system only shows the neighbor table to notarized apps: use the signed + release (or a Developer ID build). The Mac App Store edition is sandboxed and shows no MAC + addresses or vendors. ## Port scanning @@ -155,37 +160,26 @@ Everything runs locally: no account, no cloud, no telemetry. ## Downloads -> **Pre-release v0.1.0.** The first build is available for **Apple silicon only** and is -> **unsigned** (no Apple Developer ID yet). Intel, Windows and Linux packages are coming soon; -> until then, [build from source](#build-from-source). +> **Version 1.0.0.** The macOS build is for **Apple silicon**, signed with an Apple Developer ID +> and notarized. Intel, Windows and Linux packages are coming soon; until then, +> [build from source](#build-from-source). ### macOS | Build | File | Notes | |---|---|---| -| App, Apple silicon (arm64) | [`PatchProbe_0.1.0_aarch64.dmg`](https://github.com/Patchbay-s/PatchProbe/releases/download/v0.1.0/PatchProbe_0.1.0_aarch64.dmg) | **Unsigned** — see the Gatekeeper note below | -| App, universal (Apple silicon + Intel) | `patchprobe--macos-universal.dmg` | Coming soon (signed and notarized) | +| App, Apple silicon (arm64) | [`PatchProbe_1.0.0_aarch64.dmg`](https://github.com/Patchbay-s/PatchProbe/releases/download/v1.0.0/PatchProbe_1.0.0_aarch64.dmg) | Signed and notarized, all features | +| Mac App Store | Coming soon | Sandboxed edition: no MAC addresses, vendors, traceroute or nmap | +| App, universal (Apple silicon + Intel) | `PatchProbe__universal.dmg` | Coming soon | #### Install with Homebrew -The Homebrew cask installs the same unsigned Apple silicon build: - ```bash brew tap Patchbay-s/patchprobe brew install --cask patchprobe ``` -On first launch, macOS may block the unsigned app. In Finder, Control-click -`PatchProbe.app`, choose **Open**, then confirm. Intel support and signed builds are coming soon. - -Because this build is not signed or notarized, macOS will refuse to open it on first launch. -After downloading, either right-click the app and choose **Open**, or clear the quarantine flag: - -```bash -xattr -dr com.apple.quarantine /Applications/PatchProbe.app -``` - -Verify the download against [`SHA256SUMS.txt`](https://github.com/Patchbay-s/PatchProbe/releases/download/v0.1.0/SHA256SUMS.txt). +Verify the download against [`SHA256SUMS.txt`](https://github.com/Patchbay-s/PatchProbe/releases/download/v1.0.0/SHA256SUMS.txt). ### Windows @@ -221,7 +215,7 @@ git clone https://github.com/Patchbay-s/PatchProbe.git cd PatchProbe/rust/app npm ci npm run tauri dev # run in development mode -npm run tauri build # build an app bundle/installer for your OS (unsigned) +npm run tauri build # build an app bundle/installer for your OS (not notarized) ``` Run the checks: @@ -251,10 +245,9 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for per-OS details and the permissions a ## Status -PatchProbe is **pre-release**. What works today: - -Current version: **0.1.0**, published as a [pre-release](https://github.com/Patchbay-s/PatchProbe/releases/tag/v0.1.0) -(Apple silicon, unsigned). Follow the [releases page](https://github.com/Patchbay-s/PatchProbe/releases) for updates. +Current version: **1.0.0**, [released](https://github.com/Patchbay-s/PatchProbe/releases/tag/v1.0.0) for +Apple silicon (signed and notarized). Follow the +[releases page](https://github.com/Patchbay-s/PatchProbe/releases) for updates. What works today: - Everything described above is implemented in the Rust/Tauri app and covered by about 200 automated tests (parsers and protocol decoders fed with fixtures from all three OS, network @@ -263,8 +256,7 @@ Current version: **0.1.0**, published as a [pre-release](https://github.com/Patc What is missing or known to be rough: -- **No signed or notarized packages yet**, and no auto-update: the v0.1.0 pre-release is an - unsigned Apple silicon build only. +- **Apple silicon only** for now, and no auto-update. - The app has **not yet been field-tested by users on many real networks**; please report what you see, the name diagnostic panel output is especially useful. - Features of the legacy Swift app **not ported yet**: reading and changing the IP configuration diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cddd01b..5220907 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -2283,7 +2283,7 @@ dependencies = [ [[package]] name = "patchprobe-app" -version = "0.1.0" +version = "1.0.0" dependencies = [ "chrono", "patchprobe-core", @@ -2300,7 +2300,7 @@ dependencies = [ [[package]] name = "patchprobe-core" -version = "0.1.0" +version = "1.0.0" dependencies = [ "async-trait", "chrono", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "patchprobe-platform" -version = "0.1.0" +version = "1.0.0" dependencies = [ "async-trait", "directories", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index cdf95ba..f158df6 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -7,7 +7,7 @@ members = [ ] [workspace.package] -version = "0.1.0" +version = "1.0.0" edition = "2021" license = "GPL-3.0-only" publish = false diff --git a/rust/app/app-icon.png b/rust/app/app-icon.png index 73d1ab9..c7ef5e1 100644 Binary files a/rust/app/app-icon.png and b/rust/app/app-icon.png differ diff --git a/rust/app/package-lock.json b/rust/app/package-lock.json index 57cefbb..a571d4e 100644 --- a/rust/app/package-lock.json +++ b/rust/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "patchprobe-app", - "version": "0.1.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "patchprobe-app", - "version": "0.1.0", + "version": "1.0.0", "license": "GPL-3.0-only", "dependencies": { "@tauri-apps/api": "^2.12.3", diff --git a/rust/app/package.json b/rust/app/package.json index d35f950..f89b4be 100644 --- a/rust/app/package.json +++ b/rust/app/package.json @@ -1,7 +1,7 @@ { "name": "patchprobe-app", "private": true, - "version": "0.1.0", + "version": "1.0.0", "license": "GPL-3.0-only", "type": "module", "scripts": { diff --git a/rust/app/scripts/release-appstore.sh b/rust/app/scripts/release-appstore.sh new file mode 100755 index 0000000..0d083a1 --- /dev/null +++ b/rust/app/scripts/release-appstore.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# Paquet Mac App Store de PatchProbe (.pkg signé, prêt pour Transporter). +# +# Usage : scripts/release-appstore.sh [--upload] +# --upload envoie le .pkg à App Store Connect avec la clé API (APPLE_API_KEY…). +# +# Identifiants lus dans l'environnement ou dans `.env` à la racine du dépôt (git-ignoré, voir +# `.env.example`). L'édition App Store tourne dans le bac à sable d'Apple : pas de MAC, de +# traceroute ni de nmap (l'interface le signale). À lancer depuis Terminal.app. +set -euo pipefail + +app_dir="$(cd "$(dirname "$0")/.." && pwd)" +repo_root="$(cd "$app_dir/../.." && pwd)" +target_root="$(cd "$app_dir/.." && pwd)/target" +out_dir="$target_root/appstore" +bundle_id="com.patchbay.patchprobe" + +upload=false +[[ "${1:-}" == "--upload" ]] && upload=true + +if [[ -f "$repo_root/.env" ]]; then + set -a + # shellcheck disable=SC1091 + source "$repo_root/.env" + set +a +fi + +fail() { echo "erreur : $*" >&2; exit 1; } +has_identity() { security find-identity -v | grep -qF "\"$1\""; } + +[[ "${APPLE_DISTRIBUTION_IDENTITY:-}" == "Apple Distribution:"* || + "${APPLE_DISTRIBUTION_IDENTITY:-}" == "3rd Party Mac Developer Application:"* ]] || + fail "APPLE_DISTRIBUTION_IDENTITY doit être un certificat « Apple Distribution: … »." +[[ "${APPLE_INSTALLER_IDENTITY:-}" == "3rd Party Mac Developer Installer:"* || + "${APPLE_INSTALLER_IDENTITY:-}" == "Mac Installer Distribution:"* ]] || + fail "APPLE_INSTALLER_IDENTITY doit être un certificat « 3rd Party Mac Developer Installer: … »." +has_identity "$APPLE_DISTRIBUTION_IDENTITY" || fail "certificat introuvable : $APPLE_DISTRIBUTION_IDENTITY" +has_identity "$APPLE_INSTALLER_IDENTITY" || fail "certificat introuvable : $APPLE_INSTALLER_IDENTITY" +[[ -n "${APPLE_TEAM_ID:-}" ]] || fail "APPLE_TEAM_ID manquant." +[[ -f "${APPLE_PROVISIONING_PROFILE:-}" ]] || + fail "APPLE_PROVISIONING_PROFILE doit pointer vers le profil « Mac App Store Connect » (.provisionprofile)." + +version="$(node -p 'require(process.argv[1]).version' "$app_dir/src-tauri/tauri.conf.json")" +# CFBundleVersion doit croître à chaque envoi pour une même version. +build_number="${BUILD_NUMBER:-$(date +%Y%m%d%H%M)}" + +# Binaire universel si la cible Intel est installée, sinon Apple silicon seulement : l'App Store +# n'accepte alors le paquet qu'avec macOS 12.0 minimum (erreur 90869). +if [[ -d "$(rustc --print target-libdir --target x86_64-apple-darwin 2>/dev/null)" ]]; then + target="universal-apple-darwin" + minimum_macos="11.0" +else + target="aarch64-apple-darwin" + minimum_macos="12.0" + echo "note : cible x86_64-apple-darwin absente, paquet Apple silicon uniquement (macOS 12.0+)." +fi + +mkdir -p "$out_dir" +sed -e "s/__TEAM_ID__/$APPLE_TEAM_ID/g" -e "s/__BUNDLE_ID__/$bundle_id/g" \ + "$app_dir/src-tauri/appstore/Entitlements.plist.in" > "$out_dir/Entitlements.plist" +node -e ' + const [entitlements, profile, build, minimumSystemVersion, file] = process.argv.slice(1); + const config = { bundle: { macOS: { + entitlements, bundleVersion: build, minimumSystemVersion, + files: { "embedded.provisionprofile": profile }, + } } }; + require("fs").writeFileSync(file, JSON.stringify(config, null, 2)); +' "$out_dir/Entitlements.plist" "$APPLE_PROVISIONING_PROFILE" "$build_number" "$minimum_macos" \ + "$out_dir/tauri.appstore.json" + +cd "$app_dir" +npm ci +# Variables de notarisation retirées : un paquet App Store n'est pas notarisé. +env -u APPLE_ID -u APPLE_PASSWORD -u APPLE_API_ISSUER -u APPLE_API_KEY -u APPLE_API_KEY_PATH \ + APPLE_SIGNING_IDENTITY="$APPLE_DISTRIBUTION_IDENTITY" \ + npm run tauri build -- --bundles app --target "$target" --config "$out_dir/tauri.appstore.json" + +app="$target_root/$target/release/bundle/macos/PatchProbe.app" +pkg="$out_dir/PatchProbe-$version-$build_number.pkg" + +echo "--- vérifications" +codesign --verify --strict --deep "$app" +codesign -d --entitlements - --xml "$app" 2>/dev/null | grep -q "com.apple.security.app-sandbox" || + fail "le bac à sable n'est pas activé dans la signature." +[[ -f "$app/Contents/embedded.provisionprofile" ]] || fail "profil de provisionnement absent du .app." +[[ "$(plutil -extract LSMinimumSystemVersion raw "$app/Contents/Info.plist")" == "$minimum_macos" ]] || + fail "LSMinimumSystemVersion différent de $minimum_macos." + +productbuild --component "$app" /Applications --sign "$APPLE_INSTALLER_IDENTITY" "$pkg" +pkgutil --check-signature "$pkg" | head -n 3 +echo "OK : $pkg (version $version, build $build_number)" + +if $upload; then + [[ -n "${APPLE_API_KEY:-}" && -n "${APPLE_API_ISSUER:-}" && -f "${APPLE_API_KEY_PATH:-}" ]] || + fail "--upload demande APPLE_API_KEY, APPLE_API_ISSUER et APPLE_API_KEY_PATH." + API_PRIVATE_KEYS_DIR="$(dirname "$APPLE_API_KEY_PATH")" \ + xcrun altool --upload-app -f "$pkg" -t macos --apiKey "$APPLE_API_KEY" --apiIssuer "$APPLE_API_ISSUER" +else + echo "Envoi : glisser le .pkg dans l'app Transporter, ou relancer avec --upload." +fi diff --git a/rust/app/scripts/release-macos.sh b/rust/app/scripts/release-macos.sh new file mode 100755 index 0000000..086b8ea --- /dev/null +++ b/rust/app/scripts/release-macos.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Build signé Developer ID + notarisé de PatchProbe pour macOS (.app et .dmg). +# +# Identifiants lus dans l'environnement ou dans `.env` à la racine du dépôt (git-ignoré, voir +# `.env.example`). Rien n'est écrit sur disque en dehors de `rust/target/`. +# +# À lancer depuis Terminal.app : la notarisation a besoin d'une session utilisateur normale. +set -euo pipefail + +app_dir="$(cd "$(dirname "$0")/.." && pwd)" +repo_root="$(cd "$app_dir/../.." && pwd)" +bundle_dir="$app_dir/../target/release/bundle" + +if [[ -f "$repo_root/.env" ]]; then + set -a + # shellcheck disable=SC1091 + source "$repo_root/.env" + set +a +fi + +fail() { echo "erreur : $*" >&2; exit 1; } + +[[ "${APPLE_SIGNING_IDENTITY:-}" == "Developer ID Application:"* ]] || + fail "APPLE_SIGNING_IDENTITY doit être un certificat « Developer ID Application: … »." +security find-identity -v -p codesigning | grep -qF "\"$APPLE_SIGNING_IDENTITY\"" || + fail "certificat introuvable dans le trousseau : $APPLE_SIGNING_IDENTITY" + +if [[ -n "${APPLE_API_ISSUER:-}" || -n "${APPLE_API_KEY:-}" ]]; then + [[ -n "${APPLE_API_ISSUER:-}" && -n "${APPLE_API_KEY:-}" && -f "${APPLE_API_KEY_PATH:-}" ]] || + fail "clé App Store Connect incomplète : APPLE_API_ISSUER, APPLE_API_KEY et APPLE_API_KEY_PATH (.p8)." +elif [[ -z "${APPLE_ID:-}" || -z "${APPLE_PASSWORD:-}" || -z "${APPLE_TEAM_ID:-}" ]]; then + fail "identifiants de notarisation manquants (clé API App Store Connect, ou APPLE_ID/APPLE_PASSWORD/APPLE_TEAM_ID)." +fi + +# Volumes laissés par un bundle_dmg.sh interrompu : ils font échouer l'éjection suivante. +for volume in /Volumes/dmg.*; do + [[ -d "$volume" ]] && hdiutil detach "$volume" -force >/dev/null 2>&1 || true +done + +cd "$app_dir" +npm ci +npm run tauri build -- --bundles app,dmg + +app="$bundle_dir/macos/PatchProbe.app" +dmg="$(ls -t "$bundle_dir"/dmg/PatchProbe_*.dmg | head -n 1)" + +echo "--- vérifications" +codesign --verify --strict --deep "$app" +spctl --assess --type execute -vv "$app" +xcrun stapler validate "$app" +echo "OK : $dmg" diff --git a/rust/app/src-tauri/Info.plist b/rust/app/src-tauri/Info.plist index 0edf370..ad00c89 100644 --- a/rust/app/src-tauri/Info.plist +++ b/rust/app/src-tauri/Info.plist @@ -6,6 +6,9 @@ les sondes échouent et le scan ne trouve aucun hôte. --> NSLocalNetworkUsageDescription PatchProbe a besoin d'accéder au réseau local pour détecter les appareils connectés, leurs ports ouverts et leurs noms. + + ITSAppUsesNonExemptEncryption + NSBonjourServices diff --git a/rust/app/src-tauri/appstore/Entitlements.plist.in b/rust/app/src-tauri/appstore/Entitlements.plist.in new file mode 100644 index 0000000..1768ae2 --- /dev/null +++ b/rust/app/src-tauri/appstore/Entitlements.plist.in @@ -0,0 +1,23 @@ + + + + + + com.apple.security.app-sandbox + + + com.apple.security.network.client + + + com.apple.security.network.server + + + com.apple.security.files.user-selected.read-write + + com.apple.application-identifier + __TEAM_ID__.__BUNDLE_ID__ + com.apple.developer.team-identifier + __TEAM_ID__ + + diff --git a/rust/app/src-tauri/icons/128x128.png b/rust/app/src-tauri/icons/128x128.png index 2caa19c..1655ca5 100644 Binary files a/rust/app/src-tauri/icons/128x128.png and b/rust/app/src-tauri/icons/128x128.png differ diff --git a/rust/app/src-tauri/icons/128x128@2x.png b/rust/app/src-tauri/icons/128x128@2x.png index 17c6ec7..6136b64 100644 Binary files a/rust/app/src-tauri/icons/128x128@2x.png and b/rust/app/src-tauri/icons/128x128@2x.png differ diff --git a/rust/app/src-tauri/icons/32x32.png b/rust/app/src-tauri/icons/32x32.png index 1a4d811..01d022a 100644 Binary files a/rust/app/src-tauri/icons/32x32.png and b/rust/app/src-tauri/icons/32x32.png differ diff --git a/rust/app/src-tauri/icons/64x64.png b/rust/app/src-tauri/icons/64x64.png index 5ae0ae6..0c8a6fa 100644 Binary files a/rust/app/src-tauri/icons/64x64.png and b/rust/app/src-tauri/icons/64x64.png differ diff --git a/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-dark.png b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-dark.png new file mode 100644 index 0000000..00757fb Binary files /dev/null and b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-dark.png differ diff --git a/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-light.png b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-light.png new file mode 100644 index 0000000..b2036be Binary files /dev/null and b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-light.png differ diff --git a/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-tinted.png b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-tinted.png new file mode 100644 index 0000000..d9b89c2 Binary files /dev/null and b/rust/app/src-tauri/icons/PatchProbe.icon/Assets/mark-tinted.png differ diff --git a/rust/app/src-tauri/icons/PatchProbe.icon/icon.json b/rust/app/src-tauri/icons/PatchProbe.icon/icon.json new file mode 100644 index 0000000..04af2fb --- /dev/null +++ b/rust/app/src-tauri/icons/PatchProbe.icon/icon.json @@ -0,0 +1,57 @@ +{ + "fill-specializations" : [ + { + "value" : { + "linear-gradient" : [ + "extended-srgb:1.00000,1.00000,1.00000,1.00000", + "extended-srgb:0.91765,0.94510,0.95686,1.00000" + ] + } + }, + { + "appearance" : "dark", + "value" : { + "linear-gradient" : [ + "extended-srgb:0.09020,0.16471,0.22353,1.00000", + "extended-srgb:0.04314,0.08627,0.12549,1.00000" + ] + } + } + ], + "groups" : [ + { + "layers" : [ + { + "glass" : false, + "image-name-specializations" : [ + { + "value" : "mark-light.png" + }, + { + "appearance" : "dark", + "value" : "mark-dark.png" + }, + { + "appearance" : "tinted", + "value" : "mark-tinted.png" + } + ], + "name" : "mark" + } + ], + "shadow" : { + "kind" : "neutral", + "opacity" : 0.4 + }, + "translucency" : { + "enabled" : false, + "value" : 0.5 + } + } + ], + "supported-platforms" : { + "squares" : [ + "macOS" + ] + } +} diff --git a/rust/app/src-tauri/icons/icon.icns b/rust/app/src-tauri/icons/icon.icns index 6654924..9beeb0d 100644 Binary files a/rust/app/src-tauri/icons/icon.icns and b/rust/app/src-tauri/icons/icon.icns differ diff --git a/rust/app/src-tauri/icons/icon.ico b/rust/app/src-tauri/icons/icon.ico index d5eda4b..7c33c9b 100644 Binary files a/rust/app/src-tauri/icons/icon.ico and b/rust/app/src-tauri/icons/icon.ico differ diff --git a/rust/app/src-tauri/icons/icon.png b/rust/app/src-tauri/icons/icon.png index 899188a..d58fb20 100644 Binary files a/rust/app/src-tauri/icons/icon.png and b/rust/app/src-tauri/icons/icon.png differ diff --git a/rust/app/src-tauri/src/commands.rs b/rust/app/src-tauri/src/commands.rs index 7e2ff24..09c97fc 100644 --- a/rust/app/src-tauri/src/commands.rs +++ b/rust/app/src-tauri/src/commands.rs @@ -53,6 +53,9 @@ pub struct Bootstrap { udp_ports: Vec, nmap_available: bool, nmap_hint: &'static str, + traceroute_available: bool, + /// Édition App Store (bac à sable) : pas de MAC ni de fabricant. + sandboxed: bool, annotations: Annotations, data_dir: String, range_input: String, @@ -79,6 +82,8 @@ pub async fn bootstrap(state: State<'_, AppState>) -> CmdResult { udp_ports: DEFAULT_UDP_PORTS.to_vec(), nmap_available: tools::find_nmap().is_some(), nmap_hint: tools::nmap_install_hint(), + traceroute_available: tools::traceroute_available(), + sandboxed: patchprobe_platform::is_sandboxed(), annotations: state.annotations.get(), data_dir: state.paths.base().display().to_string(), range_input, @@ -435,10 +440,12 @@ pub async fn export_scan( } }; let target = std::path::PathBuf::from(&path); - tauri::async_runtime::spawn_blocking(move || patchprobe_core::store::write_atomic(&target, content.as_bytes())) + // Écriture directe, pas `write_atomic` : dans le bac à sable de l'App Store, seul le fichier + // choisi dans le panneau d'enregistrement est accessible, pas un fichier temporaire voisin. + tauri::async_runtime::spawn_blocking(move || std::fs::write(&target, content.as_bytes())) .await .map_err(|e| e.to_string())? - .map_err(|e| e.to_string())?; + .map_err(|e| format!("Impossible d'écrire {path} : {e}"))?; Ok(path) } diff --git a/rust/app/src-tauri/tauri.conf.json b/rust/app/src-tauri/tauri.conf.json index 2677754..3c48a2e 100644 --- a/rust/app/src-tauri/tauri.conf.json +++ b/rust/app/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PatchProbe", - "version": "0.1.0", + "version": "1.0.0", "identifier": "com.patchbay.patchprobe", "build": { "beforeDevCommand": "npm run dev", @@ -35,8 +35,10 @@ ], "macOS": { "infoPlist": "Info.plist", - "minimumSystemVersion": "11.0" + "minimumSystemVersion": "11.0", + "signingIdentity": "-" }, + "category": "Utility", "license": "GPL-3.0-only", "licenseFile": "../../../LICENSE", "copyright": "Copyright © 2026 PatchProbe contributors. Licensed under GPL-3.0." diff --git a/rust/app/src/App.tsx b/rust/app/src/App.tsx index e02e50b..3c77d0d 100644 --- a/rust/app/src/App.tsx +++ b/rust/app/src/App.tsx @@ -287,6 +287,7 @@ export default function App() { onSelect={setSelectedIp} onPing={(ip) => api.pingHost(ip).then((h) => mergeHosts([h])).catch((e) => notify("error", errorMessage(e)))} onOpen={(ip) => api.openHost(ip).catch((e) => notify("error", errorMessage(e)))} + showMac={!(boot?.sandboxed ?? false)} emptyText={ hosts.size === 0 ? progress.running @@ -304,6 +305,8 @@ export default function App() { annotation={annotations[selectedHost.ip] ?? null} nmapAvailable={boot.nmapAvailable} nmapHint={boot.nmapHint} + tracerouteAvailable={boot.tracerouteAvailable} + sandboxed={boot.sandboxed} udpPorts={boot.udpPorts} onClose={() => setSelectedIp(null)} onAnnotations={setAnnotations} diff --git a/rust/app/src/components/HostDetail.tsx b/rust/app/src/components/HostDetail.tsx index 3268fb1..7cb8070 100644 --- a/rust/app/src/components/HostDetail.tsx +++ b/rust/app/src/components/HostDetail.tsx @@ -18,6 +18,8 @@ interface Props { annotation: IpAnnotation | null; nmapAvailable: boolean; nmapHint: string; + tracerouteAvailable: boolean; + sandboxed: boolean; udpPorts: number[]; onClose: () => void; onAnnotations: (a: Annotations) => void; @@ -128,7 +130,7 @@ function RunButtons({ task, label }: { task: ReturnType>; l ); } -export function HostDetail({ host, annotation, nmapAvailable, nmapHint, udpPorts, onClose, onAnnotations, onHostsUpdated, notify }: Props) { +export function HostDetail({ host, annotation, nmapAvailable, nmapHint, tracerouteAvailable, sandboxed, udpPorts, onClose, onAnnotations, onHostsUpdated, notify }: Props) { const ip = host.ip; const [note, setNote] = useState(annotation?.note ?? ""); const [vendorInput, setVendorInput] = useState(host.vendorOverridden ? host.vendor ?? "" : ""); @@ -211,7 +213,12 @@ export function HostDetail({ host, annotation, nmapAvailable, nmapHint, udpPorts {host.ttl !== null && (TTL {host.ttl})}
MAC
-
{host.mac ?? (host.isLikelyRouted ? "Non disponible — hôte routé (pas un voisin Ethernet direct)" : "—")}
+
{host.mac ?? + (host.isLikelyRouted + ? "Non disponible — hôte routé (pas un voisin Ethernet direct)" + : sandboxed + ? "Non disponible dans la version App Store" + : "—")}
Fabricant
{host.vendor ?? "—"} {host.vendorOverridden && modifié} @@ -292,8 +299,10 @@ export function HostDetail({ host, annotation, nmapAvailable, nmapHint, udpPorts )} -
}> - {trace.state.status === "done" ? ( +
: undefined}> + {!tracerouteAvailable ? ( +

Traceroute n'est pas disponible dans la version App Store.

+ ) : trace.state.status === "done" ? ( ) : trace.state.status === "error" ? (

{trace.state.message}

diff --git a/rust/app/src/components/ResultsTable.tsx b/rust/app/src/components/ResultsTable.tsx index 8d36c90..e7fd7a3 100644 --- a/rust/app/src/components/ResultsTable.tsx +++ b/rust/app/src/components/ResultsTable.tsx @@ -13,6 +13,8 @@ interface Props { onPing: (ip: string) => void; onOpen: (ip: string) => void; emptyText: string; + /** Faux dans l'édition App Store : la table ARP y est inaccessible, MAC et fabricant restent vides. */ + showMac: boolean; } type Row = { kind: "group"; key: string; count: number } | { kind: "host"; host: Host }; @@ -62,15 +64,17 @@ export function ResultsTable(props: Props) { const last = Math.min(rows.length, Math.ceil((scrollTop + viewport) / ROW_HEIGHT) + OVERSCAN); const visible = rows.slice(first, last); + const columns = props.showMac ? COLUMNS : COLUMNS.filter((c) => c.key !== "mac" && c.key !== "vendor"); + const headerClick = (key: SortKey | null) => { if (!key) return; props.onSort(props.sort.key === key ? { key, ascending: !props.sort.ascending } : { key, ascending: true }); }; return ( -
+
- {COLUMNS.map((column, index) => ( + {columns.map((column, index) => (
{formatLatency(host.latencyMs)}
{host.probableOs ?? —}
-
- {host.mac ?? {host.isLikelyRouted ? "routé" : "—"}} -
-
- {host.vendor ?? —} - {host.vendorOverridden ? modifié : null} -
+ {props.showMac && ( + <> +
+ {host.mac ?? {host.isLikelyRouted ? "routé" : "—"}} +
+
+ {host.vendor ?? —} + {host.vendorOverridden ? modifié : null} +
+ + )}
{host.openPorts.length ? host.openPorts.join(", ") : —}
diff --git a/rust/app/src/components/SettingsPanel.tsx b/rust/app/src/components/SettingsPanel.tsx index 4feaec8..14cc8dd 100644 --- a/rust/app/src/components/SettingsPanel.tsx +++ b/rust/app/src/components/SettingsPanel.tsx @@ -1,5 +1,6 @@ import { useState } from "react"; -import type { AppSettings, PortPresetInfo, PortPresetKind, ScanSettings, TimingPreset } from "../types"; +import type { AppSettings, PortPresetInfo, PortPresetKind, ScanSettings, TechniqueId, TimingPreset } from "../types"; +import { TECHNIQUE_LABEL } from "../util"; import { Modal } from "./Modal"; interface Props { @@ -13,6 +14,9 @@ interface Props { onClose: () => void; } +/** Sources proposées comme nom par défaut (miroir de `TechniqueId::PREFERABLE`). */ +const NAME_SOURCES: TechniqueId[] = ["webTitle", "gatewayDns", "ptr", "mdns", "nbns", "smb", "llmnr", "snmp"]; + type NumericKey = { [K in keyof ScanSettings]: ScanSettings[K] extends number ? K : never; }[keyof ScanSettings]; @@ -88,6 +92,32 @@ export function SettingsPanel({ settings, portPresets, dataDir, onSave, onTiming
+
+

Nom des appareils

+
+ +
+

+ Nom affiché quand cette source en trouve un ; sinon l'ordre automatique s'applique. Pris en compte au prochain scan. +

+ +
+

Ports par type d'appareil

    diff --git a/rust/app/src/styles.css b/rust/app/src/styles.css index aabff93..9de90ad 100644 --- a/rust/app/src/styles.css +++ b/rust/app/src/styles.css @@ -137,6 +137,7 @@ textarea { width: 100%; resize: vertical; } grid-template-columns: 34px 130px 110px minmax(140px, 1.4fr) 76px 110px 140px minmax(120px, 1fr) minmax(110px, 1fr) 100px; align-items: center; } +.table.no-mac .table-row { grid-template-columns: 34px 130px 110px minmax(140px, 1.4fr) 76px 110px minmax(110px, 1fr) 100px; } .table-header { font-weight: 600; background: var(--bg-alt); border-bottom: 1px solid var(--border); height: 30px; } .table-header .sortable { cursor: pointer; user-select: none; } .table-body { flex: 1; overflow: auto; position: relative; } @@ -224,5 +225,6 @@ pre.raw { max-height: 240px; overflow: auto; background: var(--bg-alt); padding: .settings-section h3 { margin: 0; font-size: 13px; } .settings-grid { display: grid; gap: 6px; } .settings-grid label { display: grid; grid-template-columns: 1fr 110px 30px; align-items: center; gap: 8px; } +.settings-grid label.wide { grid-template-columns: 1fr 260px; } .preset-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; } .preset-list li { display: flex; gap: 10px; align-items: center; } diff --git a/rust/app/src/types.ts b/rust/app/src/types.ts index 45c149e..c1121fc 100644 --- a/rust/app/src/types.ts +++ b/rust/app/src/types.ts @@ -40,6 +40,8 @@ export interface ScanSettings { maxTcpConnections: number; maxParallelHosts: number; maxParallelNameResolutions: number; + /** Source du nom affiché quand elle en trouve un ; `null` = ordre automatique. */ + preferredNameSource: TechniqueId | null; } export type PortPresetKind = "cameraIP" | "generic" | "webServer" | "printer" | "nas"; @@ -88,6 +90,9 @@ export interface Bootstrap { udpPorts: number[]; nmapAvailable: boolean; nmapHint: string; + tracerouteAvailable: boolean; + /** Édition App Store (bac à sable) : pas de MAC ni de fabricant. */ + sandboxed: boolean; annotations: Annotations; dataDir: string; rangeInput: string; diff --git a/rust/crates/patchprobe-core/src/engine/tests.rs b/rust/crates/patchprobe-core/src/engine/tests.rs index df364ee..8fc36c2 100644 --- a/rust/crates/patchprobe-core/src/engine/tests.rs +++ b/rust/crates/patchprobe-core/src/engine/tests.rs @@ -254,7 +254,7 @@ impl NameResolution for InstantNames { Outcome::Found(format!("host-{}", ip.octets()[3])), Duration::ZERO, )); - trace.choose(); + trace.choose(None); trace } diff --git a/rust/crates/patchprobe-core/src/resolve/mod.rs b/rust/crates/patchprobe-core/src/resolve/mod.rs index 25261af..3742dd4 100644 --- a/rust/crates/patchprobe-core/src/resolve/mod.rs +++ b/rust/crates/patchprobe-core/src/resolve/mod.rs @@ -53,6 +53,8 @@ pub struct ResolverConfig { pub gateway: Option, pub snmp_community: String, pub ports: TechniquePorts, + /// Source de nom retenue en priorité quand elle trouve un nom (`None` : ordre par défaut). + pub preferred_name: Option, } impl Default for ResolverConfig { @@ -64,6 +66,7 @@ impl Default for ResolverConfig { gateway: None, snmp_community: "public".into(), ports: TechniquePorts::default(), + preferred_name: None, } } } @@ -74,6 +77,7 @@ impl ResolverConfig { name_timeout: Duration::from_millis(settings.name_timeout_ms), web_title_timeout: Duration::from_millis(settings.web_title_timeout_ms), gateway, + preferred_name: settings.preferred_name_source, ..Self::default() } } @@ -136,26 +140,37 @@ impl Resolver { CacheLookup::RecentFailure => Some("échec récent mémorisé (moins de 5 min)".to_owned()), CacheLookup::Miss => None, }; - let skip = skip_reason.as_deref(); + // La source préférée n'est jamais sautée : un nom en cache venant d'une autre + // technique ne doit pas l'empêcher de reprendre la main. + let skip_unless_preferred = + |technique: TechniqueId| skip_reason.as_deref().filter(|_| cfg.preferred_name != Some(technique)); let at = |port: u16| SocketAddrV4::new(ip, port); let (ptr, gateway, mdns, nbns, smb, llmnr, snmp) = tokio::join!( timed(TechniqueId::Ptr, techniques::system_ptr(ip, timeout)), timed(TechniqueId::GatewayDns, techniques::gateway_dns(ip, cfg.gateway, cfg.ports.dns, timeout)), unless_skipped( TechniqueId::Mdns, - skip, + skip_unless_preferred(TechniqueId::Mdns), techniques::dns_ptr(at(cfg.ports.mdns), ip, timeout, false, "mDNS") ), - unless_skipped(TechniqueId::Nbns, skip, techniques::nbns_query(at(cfg.ports.nbns), timeout)), - unless_skipped(TechniqueId::Smb, skip, techniques::smb_name(at(cfg.ports.smb), timeout)), + unless_skipped( + TechniqueId::Nbns, + skip_unless_preferred(TechniqueId::Nbns), + techniques::nbns_query(at(cfg.ports.nbns), timeout) + ), + unless_skipped( + TechniqueId::Smb, + skip_unless_preferred(TechniqueId::Smb), + techniques::smb_name(at(cfg.ports.smb), timeout) + ), unless_skipped( TechniqueId::Llmnr, - skip, + skip_unless_preferred(TechniqueId::Llmnr), techniques::dns_ptr(at(cfg.ports.llmnr), ip, timeout, false, "LLMNR") ), unless_skipped( TechniqueId::Snmp, - skip, + skip_unless_preferred(TechniqueId::Snmp), techniques::snmp_sys_name(at(cfg.ports.snmp), &cfg.snmp_community, timeout) ), ); @@ -165,9 +180,10 @@ impl Resolver { } let has_name = trace.results.iter().any(|r| r.outcome.found().is_some()); - let web = if let (ResolveMode::Scan, Some(reason)) = (mode, skip_reason.as_deref()) { + let web_preferred = cfg.preferred_name == Some(TechniqueId::WebTitle); + let web = if let (ResolveMode::Scan, Some(reason)) = (mode, skip_unless_preferred(TechniqueId::WebTitle)) { skipped(TechniqueId::WebTitle, reason) - } else if mode == ResolveMode::Scan && has_name { + } else if mode == ResolveMode::Scan && has_name && !web_preferred { skipped(TechniqueId::WebTitle, "un nom a déjà été trouvé") } else { timed( @@ -181,7 +197,7 @@ impl Resolver { if let CacheLookup::Hit { name, .. } = &cached { trace.push(TechniqueResult::new(TechniqueId::Cache, Outcome::Found(name.clone()), Duration::ZERO)); } - trace.choose(); + trace.choose(cfg.preferred_name); self.remember(&trace, mode); trace } diff --git a/rust/crates/patchprobe-core/src/resolve/tests.rs b/rust/crates/patchprobe-core/src/resolve/tests.rs index 4182b4e..4ea0a51 100644 --- a/rust/crates/patchprobe-core/src/resolve/tests.rs +++ b/rust/crates/patchprobe-core/src/resolve/tests.rs @@ -33,6 +33,28 @@ async fn fake_nbns() -> u16 { port } +/// Faux service web sur loopback : renvoie une page dont le titre est « Test Panel ». +async fn fake_http() -> u16 { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + tokio::spawn(async move { + let mut buf = [0u8; 1024]; + let _ = stream.read(&mut buf).await; + let body = "Test Panel"; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()).await; + }); + } + }); + port +} + fn config(nbns: u16) -> ResolverConfig { ResolverConfig { name_timeout: Duration::from_millis(400), @@ -40,6 +62,7 @@ fn config(nbns: u16) -> ResolverConfig { discovery_budget: Duration::from_millis(100), gateway: None, snmp_community: "public".into(), + preferred_name: None, ports: TechniquePorts { dns: closed_udp_port(), mdns: closed_udp_port(), @@ -129,3 +152,42 @@ async fn discovery_fills_cache() { ); let _ = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0); } + +#[tokio::test] +async fn preferred_web_title_wins_over_other_names() { + let cache: SharedCache = Arc::new(Mutex::new(ResolutionCache::default())); + let config = ResolverConfig { preferred_name: Some(TechniqueId::WebTitle), ..config(fake_nbns().await) }; + let resolver = Resolver::new(config, cache).with_clock(fixed_clock); + let ports = [fake_http().await]; + + let trace = resolver.resolve(Ipv4Addr::LOCALHOST, &ports, ResolveMode::Scan).await; + assert_eq!(outcome(&trace, TechniqueId::Nbns), Outcome::Found("MEDIA-PC".into())); + assert_eq!(trace.chosen, Some(ChosenName { name: "Test Panel".into(), technique: TechniqueId::WebTitle })); + + // Rescan : le nom est en cache, mais la source préférée est quand même rejouée. + let again = resolver.resolve(Ipv4Addr::LOCALHOST, &ports, ResolveMode::Scan).await; + assert_eq!(again.chosen.map(|c| c.technique), Some(TechniqueId::WebTitle)); +} + +#[tokio::test] +async fn preferred_source_is_not_skipped_by_cache() { + let cache: SharedCache = Arc::new(Mutex::new(ResolutionCache::default())); + let config = ResolverConfig { preferred_name: Some(TechniqueId::Nbns), ..config(fake_nbns().await) }; + let resolver = Resolver::new(config, cache).with_clock(fixed_clock); + let first = resolver.resolve(Ipv4Addr::LOCALHOST, &[], ResolveMode::Scan).await; + assert_eq!(first.chosen.map(|c| c.technique), Some(TechniqueId::Nbns)); + let again = resolver.resolve(Ipv4Addr::LOCALHOST, &[], ResolveMode::Scan).await; + assert_eq!(outcome(&again, TechniqueId::Nbns), Outcome::Found("MEDIA-PC".into())); + assert!(matches!(outcome(&again, TechniqueId::Mdns), Outcome::Skipped(ref why) if why.contains("cache"))); + assert_eq!(again.chosen.map(|c| c.technique), Some(TechniqueId::Nbns)); +} + +#[tokio::test] +async fn preferred_source_without_name_falls_back_to_priority() { + let cache: SharedCache = Arc::new(Mutex::new(ResolutionCache::default())); + let config = ResolverConfig { preferred_name: Some(TechniqueId::WebTitle), ..config(fake_nbns().await) }; + let resolver = Resolver::new(config, cache).with_clock(fixed_clock); + // Aucun port web : le titre web n'a rien, un autre nom est retenu. + let trace = resolver.resolve(Ipv4Addr::LOCALHOST, &[], ResolveMode::Scan).await; + assert!(trace.chosen.is_some_and(|c| c.technique != TechniqueId::WebTitle)); +} diff --git a/rust/crates/patchprobe-core/src/resolve/types.rs b/rust/crates/patchprobe-core/src/resolve/types.rs index 9a5eae9..55c0b50 100644 --- a/rust/crates/patchprobe-core/src/resolve/types.rs +++ b/rust/crates/patchprobe-core/src/resolve/types.rs @@ -50,6 +50,10 @@ impl TechniqueId { Self::Cache, ]; + /// Techniques proposées comme source de nom préférée (directes, rejouées à chaque scan). + pub const PREFERABLE: [TechniqueId; 8] = + [Self::GatewayDns, Self::Ptr, Self::Mdns, Self::Nbns, Self::Smb, Self::Llmnr, Self::Snmp, Self::WebTitle]; + pub fn label(self) -> &'static str { match self { Self::Cache => "Cache", @@ -158,9 +162,10 @@ impl NameTrace { self.results.iter().rev().find(|r| r.technique == technique) } - /// Choisit le nom selon [`TechniqueId::PRIORITY`] parmi les résultats `Found`. - pub fn choose(&mut self) { - self.chosen = TechniqueId::PRIORITY.into_iter().find_map(|technique| { + /// Choisit le nom parmi les résultats `Found` : la technique préférée d'abord si elle a + /// trouvé un nom, sinon selon [`TechniqueId::PRIORITY`]. + pub fn choose(&mut self, preferred: Option) { + self.chosen = preferred.into_iter().chain(TechniqueId::PRIORITY).find_map(|technique| { self.result(technique) .and_then(|r| r.outcome.found()) .map(|name| ChosenName { name: name.to_owned(), technique }) @@ -222,12 +227,27 @@ mod tests { Outcome::Found("pc.example.invalid".into()), Duration::ZERO, )); - trace.choose(); + trace.choose(None); let chosen = trace.chosen.unwrap(); assert_eq!(chosen.name, "pc.example.invalid"); assert_eq!(chosen.technique, TechniqueId::GatewayDns); } + #[test] + fn preferred_technique_wins_then_priority_applies() { + let found = + |technique, name: &str| TechniqueResult::new(technique, Outcome::Found(name.into()), Duration::ZERO); + let mut trace = NameTrace::new(Ipv4Addr::LOCALHOST); + trace.push(found(TechniqueId::GatewayDns, "pc.example.invalid")); + trace.push(found(TechniqueId::WebTitle, "Panel")); + trace.choose(Some(TechniqueId::WebTitle)); + assert_eq!(trace.chosen.as_ref().map(|c| c.technique), Some(TechniqueId::WebTitle)); + trace.choose(Some(TechniqueId::Snmp)); + assert_eq!(trace.chosen.as_ref().map(|c| c.technique), Some(TechniqueId::GatewayDns)); + trace.choose(None); + assert_eq!(trace.chosen.as_ref().map(|c| c.technique), Some(TechniqueId::GatewayDns)); + } + #[test] fn outcome_serialization_is_tagged() { let json = serde_json::to_value(Outcome::Found("x".into())).unwrap(); diff --git a/rust/crates/patchprobe-core/src/settings.rs b/rust/crates/patchprobe-core/src/settings.rs index ff1a2e1..91c5d67 100644 --- a/rust/crates/patchprobe-core/src/settings.rs +++ b/rust/crates/patchprobe-core/src/settings.rs @@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize}; +use crate::resolve::TechniqueId; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum TimingPreset { @@ -38,6 +40,9 @@ pub struct ScanSettings { pub max_parallel_hosts: usize, /// Budget séparé de résolutions de nom simultanées (jamais affamé par le scan de ports). pub max_parallel_name_resolutions: usize, + /// Source du nom affiché quand elle en trouve un (`None` : ordre automatique). Le titre web + /// par défaut : c'est le nom le plus parlant pour les services auto-hébergés. + pub preferred_name_source: Option, } impl ScanSettings { @@ -64,6 +69,7 @@ impl ScanSettings { max_tcp_connections: 256, max_parallel_hosts: 64, max_parallel_name_resolutions: 32, + preferred_name_source: Some(TechniqueId::WebTitle), } } @@ -108,6 +114,7 @@ impl ScanSettings { self.max_tcp_connections = self.max_tcp_connections.clamp(1, 4096); self.max_parallel_hosts = self.max_parallel_hosts.clamp(1, 1024); self.max_parallel_name_resolutions = self.max_parallel_name_resolutions.clamp(1, 512); + self.preferred_name_source = self.preferred_name_source.filter(|t| TechniqueId::PREFERABLE.contains(t)); self } } @@ -171,4 +178,15 @@ mod tests { assert_eq!(s.max_tcp_connections, 1); assert_eq!(s.max_parallel_hosts, 1024); } + + #[test] + fn preferred_name_source_defaults_to_web_title() { + assert_eq!(ScanSettings::default().preferred_name_source, Some(TechniqueId::WebTitle)); + let parsed: ScanSettings = serde_json::from_str(r#"{"preferredNameSource":null}"#).unwrap(); + assert_eq!(parsed.preferred_name_source, None); + let parsed: ScanSettings = serde_json::from_str(r#"{"preferredNameSource":"nbns"}"#).unwrap(); + assert_eq!(parsed.preferred_name_source, Some(TechniqueId::Nbns)); + let cached = ScanSettings { preferred_name_source: Some(TechniqueId::Cache), ..Default::default() }; + assert_eq!(cached.sanitized().preferred_name_source, None); + } } diff --git a/rust/crates/patchprobe-platform/src/lib.rs b/rust/crates/patchprobe-platform/src/lib.rs index ec751e9..0c43c19 100644 --- a/rust/crates/patchprobe-platform/src/lib.rs +++ b/rust/crates/patchprobe-platform/src/lib.rs @@ -8,4 +8,10 @@ pub mod system; pub mod tools; pub use patchprobe_core as core; + +/// Vrai dans le bac à sable d'Apple (édition Mac App Store) : la table ARP y est vide et +/// traceroute ou nmap ne peuvent pas être lancés. +pub fn is_sandboxed() -> bool { + cfg!(target_os = "macos") && std::env::var_os("APP_SANDBOX_CONTAINER_ID").is_some() +} pub use system::{validate_url, Ipv4Config, NetworkProfile, Platform, PlatformError, SystemPlatform}; diff --git a/rust/crates/patchprobe-platform/src/system.rs b/rust/crates/patchprobe-platform/src/system.rs index 10a1f17..4daa7a3 100644 --- a/rust/crates/patchprobe-platform/src/system.rs +++ b/rust/crates/patchprobe-platform/src/system.rs @@ -113,7 +113,9 @@ const SBIN_DIRS: &[&str] = &["/sbin", "/usr/sbin", "/bin", "/usr/bin", "C:\\Wind impl SystemPlatform { pub fn new() -> Self { - Self { ping_path: find_executable("ping", SBIN_DIRS), arp_path: find_executable("arp", SBIN_DIRS) } + // Bac à sable : la table ARP est toujours vide, inutile de lancer `arp` pour chaque hôte. + let arp_path = if crate::is_sandboxed() { None } else { find_executable("arp", SBIN_DIRS) }; + Self { ping_path: find_executable("ping", SBIN_DIRS), arp_path } } /// Arguments d'un ping unique sans privilèges, selon l'OS. diff --git a/rust/crates/patchprobe-platform/src/tools.rs b/rust/crates/patchprobe-platform/src/tools.rs index e55a015..d54c86b 100644 --- a/rust/crates/patchprobe-platform/src/tools.rs +++ b/rust/crates/patchprobe-platform/src/tools.rs @@ -24,7 +24,9 @@ const NMAP_DIRS: &[&str] = &["/usr/bin", "/usr/local/bin", "/snap/bin"]; /// Indication d'installation propre à l'OS. pub fn nmap_install_hint() -> &'static str { - if cfg!(target_os = "macos") { + if crate::is_sandboxed() { + "nmap n'est pas disponible dans la version App Store : utilisez la version téléchargeable." + } else if cfg!(target_os = "macos") { "nmap introuvable — installez-le avec « brew install nmap »." } else if cfg!(target_os = "windows") { "nmap introuvable — installez-le depuis https://nmap.org/download.html (installateur Windows)." @@ -34,9 +36,17 @@ pub fn nmap_install_hint() -> &'static str { } pub fn find_nmap() -> Option { + if crate::is_sandboxed() { + return None; + } find_executable("nmap", NMAP_DIRS) } +/// Traceroute utilisable (le bac à sable de l'App Store interdit de lancer `traceroute`). +pub fn traceroute_available() -> bool { + !crate::is_sandboxed() +} + #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum ToolError { #[error("{0}")] @@ -96,6 +106,9 @@ pub fn traceroute_command(ip: Ipv4Addr) -> Option<(PathBuf, Vec, Duratio } pub async fn run_traceroute(ip: Ipv4Addr, cancel: &CancellationToken) -> Result, ToolError> { + if !traceroute_available() { + return Err(ToolError::NotInstalled("traceroute n'est pas disponible dans la version App Store.".into())); + } let (path, args, timeout) = traceroute_command(ip).ok_or_else(|| { ToolError::NotInstalled( "traceroute introuvable sur ce système (ni traceroute, ni tracepath, ni tracert).".into(),