Compare commits

..
Author SHA1 Message Date
ietm64 8c6b642975 Accès tablette : vérification du réseau et autorisation pare-feu en un clic
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 42s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 51s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m33s
Build & Push Images / build (brain) (push) Successful in 1m39s
Build & Push Images / build (web) (push) Successful in 2m3s
Build & Push Images / build-switcher (push) Successful in 25s
Build & Push Images / build (core) (push) Successful in 4m13s
Constat terrain : le téléphone chargeait sans fin — le pare-feu Windows
n'avait aucune règle pour DM Loremind (la fenêtre d'autorisation n'apparaît
pas toujours) et le Wi-Fi était classé « Public » par défaut.

- Bloc « Vérification du réseau » dans Paramètres > Accès depuis une
  tablette : lit le type des réseaux connectés et les règles entrantes du
  pare-feu visant l'appli (PowerShell, lecture seule, sans droits admin).
- Bouton « Autoriser dans le pare-feu » : confirmation administrateur
  Windows (UAC), règle limitée aux réseaux privés, blocages éventuels de
  l'appli retirés ; résultat affiché (appliqué / annulé / échec).
- Réseau classé « Public » : explication + bouton « Ouvrir les réglages
  réseau » (le profil réseau reste un choix de l'utilisateur).
- Textes et doc corrigés (fin de la consigne trompeuse « réseaux privés
  uniquement ») ; section « La tablette charge sans fin » avec la commande
  manuelle de secours.

Vérifié : core clean verify (1219 tests, dont une vraie lecture du système
sur Windows), web build + 337 vitest, lint sans erreur, bloc vérifié en mode
bureau isolé.
À redéployer : core + web (mode bureau ; aucune migration).
2026-10-17 14:41:54 +02:00
15 changed files with 782 additions and 7 deletions
@@ -0,0 +1,67 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
* le système. Logique pure (testable sans Windows).
*
* @param supported vérification possible (Windows)
* @param ready rien ne bloque côté PC
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
* @param program exécutable concerné
*/
public record NetworkReadiness(
boolean supported,
boolean ready,
List<String> publicNetworks,
boolean firewallAllowed,
boolean firewallBlocked,
String program
) {
static final String PUBLIC = "Public";
static final String PRIVATE = "Private";
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
if (snapshot == null || !snapshot.supported()) {
return new NetworkReadiness(false, false, List.of(), false, false, null);
}
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
.stream()
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
.toList();
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, snapshot.program());
}
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
return rules.stream()
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
}
private static List<String> profiles(String raw) {
if (raw == null) return List.of();
return Arrays.stream(raw.split(","))
.map(s -> s.trim().toLowerCase(Locale.ROOT))
.filter(s -> !s.isEmpty())
.toList();
}
}
@@ -0,0 +1,30 @@
package com.loremind.domain.remoteaccess;
import java.util.List;
/**
* Faits bruts sur la machine hôte, lus par le système (pas d'interprétation ici) :
* réseaux connectés avec leur catégorie Windows, et règles ENTRANTES du pare-feu qui
* visent l'exécutable de l'application.
*
* @param supported vérification possible sur ce système (Windows uniquement)
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
* @param networks réseaux connectés
* @param rules règles entrantes du pare-feu pour ce programme
*/
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules) {
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
public record Network(String name, String alias, String category) {}
/**
* @param action {@code Allow} ou {@code Block}
* @param profile profils couverts : {@code Any}, ou liste comme {@code Private, Public}
* @param enabled {@code True} / {@code False}
*/
public record FirewallRule(String action, String profile, String enabled) {}
public static NetworkSnapshot unsupported() {
return new NetworkSnapshot(false, null, List.of(), List.of());
}
}
@@ -0,0 +1,26 @@
package com.loremind.domain.remoteaccess.ports;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
/**
* Port vers le système hôte pour que l'accès distant fonctionne vraiment : sans règle
* de pare-feu, ou sur un réseau classé « Public », Windows jette en silence les requêtes
* de la tablette (elle charge sans fin).
*/
public interface HostNetworkAccess {
/** Résultat de la demande d'autorisation dans le pare-feu. */
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
/** Lecture seule, sans droits administrateur. */
NetworkSnapshot inspect();
/**
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
* administrateur du système (UAC) : bloque jusqu'à la réponse de l'utilisateur.
*/
FirewallFixOutcome allowThroughFirewall();
/** Ouvre la page des réglages réseau du système (pour passer un Wi-Fi en « Privé »). */
void openNetworkSettings();
}
@@ -0,0 +1,208 @@
package com.loremind.infrastructure.desktop;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* Accès au réseau et au pare-feu de Windows pour l'accès distant (mode bureau).
* <p>
* Lecture via PowerShell, sans droits administrateur. L'autorisation dans le pare-feu
* passe par {@code Start-Process -Verb RunAs} : Windows affiche sa confirmation
* administrateur (UAC) et l'utilisateur garde la main. La règle créée n'ouvre DM Loremind
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
* (réglage système, jamais modifié par l'application).
* <p>
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
*/
@Component
@Profile("local")
public class WindowsHostNetworkAccess implements HostNetworkAccess {
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
static final String RULE_NAME = "DM Loremind (accès tablette)";
private static final long INSPECT_TIMEOUT_S = 20;
/** Le temps pour l'utilisateur de lire et de répondre à la fenêtre UAC. */
private static final long ELEVATION_TIMEOUT_S = 180;
/** Code Windows ERROR_CANCELLED : l'utilisateur a refusé la confirmation administrateur. */
private static final int EXIT_CANCELLED = 1223;
private final ObjectMapper objectMapper;
public WindowsHostNetworkAccess(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public NetworkSnapshot inspect() {
String program = currentProgram();
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
try {
String json = runPowerShell(inspectScript(program), INSPECT_TIMEOUT_S).output();
return parseSnapshot(objectMapper, program, json);
} catch (IOException | RuntimeException e) {
log.warn("Accès distant : lecture du réseau / pare-feu impossible : {}", e.getMessage());
return NetworkSnapshot.unsupported();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return NetworkSnapshot.unsupported();
}
}
@Override
public FirewallFixOutcome allowThroughFirewall() {
String program = currentProgram();
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
String outer = "try {\n"
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
+ encode(allowScript(program)) + "')\n"
+ " exit $p.ExitCode\n"
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
try {
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
log.info("Accès distant : autorisation pare-feu → {}", outcome);
return outcome;
} catch (IOException | RuntimeException e) {
log.warn("Accès distant : autorisation pare-feu impossible : {}", e.getMessage());
return FirewallFixOutcome.FAILED;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return FirewallFixOutcome.FAILED;
}
}
@Override
public void openNetworkSettings() {
if (!isWindows()) return;
try {
// « État du réseau » : le réseau connecté et son bouton « Propriétés » (type de profil).
new ProcessBuilder("cmd", "/c", "start", "", "ms-settings:network-status").start();
} catch (IOException e) {
log.warn("Ouverture des réglages réseau impossible : {}", e.getMessage());
}
}
// --- Scripts --------------------------------------------------------------------------
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
static String inspectScript(String program) {
return "$ErrorActionPreference = 'SilentlyContinue'\n"
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
+ "$p = '" + psQuote(program) + "'\n"
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
+ "[pscustomobject]@{ networks = $nets; rules = $rules } | ConvertTo-Json -Depth 4 -Compress\n";
}
/**
* Exécuté ÉLEVÉ : retire les blocages entrants visant CE programme (créés par un « Annuler »
* dans la fenêtre du pare-feu, ils l'emporteraient sur toute autorisation), remplace notre
* propre règle si elle existe, puis autorise sur les réseaux privés uniquement.
*/
static String allowScript(String program) {
String name = psQuote(RULE_NAME);
return "try {\n"
+ " $p = '" + psQuote(program) + "'\n"
+ " Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' -and $_.Action.ToString() -eq 'Block' } | "
+ "Remove-NetFirewallRule\n"
+ " Get-NetFirewallRule -DisplayName '" + name + "' -ErrorAction SilentlyContinue | Remove-NetFirewallRule\n"
+ " New-NetFirewallRule -DisplayName '" + name + "' -Direction Inbound -Program $p -Action Allow "
+ "-Profile Private -ErrorAction Stop | Out-Null\n"
+ " exit 0\n"
+ "} catch { exit 2 }\n";
}
static NetworkSnapshot parseSnapshot(ObjectMapper mapper, String program, String json) throws IOException {
JsonNode root = mapper.readTree(json == null || json.isBlank() ? "{}" : json.trim());
List<NetworkSnapshot.Network> networks = new ArrayList<>();
for (JsonNode n : array(root.path("networks"))) {
networks.add(new NetworkSnapshot.Network(text(n, "name"), text(n, "alias"), text(n, "category")));
}
List<NetworkSnapshot.FirewallRule> rules = new ArrayList<>();
for (JsonNode r : array(root.path("rules"))) {
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
}
return new NetworkSnapshot(true, program, networks, rules);
}
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
private static Iterable<JsonNode> array(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) return List.of();
return node.isArray() ? node : List.of(node);
}
private static String text(JsonNode node, String field) {
JsonNode v = node.get(field);
return v == null || v.isNull() ? null : v.asText();
}
static String psQuote(String value) {
return value.replace("'", "''");
}
static String encode(String script) {
return Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
}
// --- Exécution ------------------------------------------------------------------------
private record Result(int exitCode, String output) {}
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start();
process.getOutputStream().close();
// Lecture en parallèle : un tampon de sortie plein bloquerait le processus avant sa fin.
CompletableFuture<String> output = CompletableFuture.supplyAsync(() -> {
try (InputStream out = process.getInputStream()) {
return new String(out.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
return "";
}
});
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
process.destroyForcibly();
throw new IOException("PowerShell n'a pas répondu en " + timeoutSeconds + " s");
}
return new Result(process.exitValue(), output.join());
}
private static boolean isWindows() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
}
/** Exécutable du processus courant : DM Loremind.exe en bureau (java.exe en développement). */
private static String currentProgram() {
return ProcessHandle.current().info().command().orElse(null);
}
}
@@ -1,8 +1,10 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.remoteaccess.NetworkReadiness;
import com.loremind.application.remoteaccess.PairingCode;
import com.loremind.application.remoteaccess.RemoteAccessService;
import com.loremind.application.remoteaccess.RemoteAccessStatus;
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -29,13 +31,18 @@ import java.util.Map;
public class RemoteAccessAdminController {
private final RemoteAccessService remoteAccessService;
private final HostNetworkAccess hostNetworkAccess;
public RemoteAccessAdminController(RemoteAccessService remoteAccessService) {
public RemoteAccessAdminController(RemoteAccessService remoteAccessService, HostNetworkAccess hostNetworkAccess) {
this.remoteAccessService = remoteAccessService;
this.hostNetworkAccess = hostNetworkAccess;
}
public record ConfigureRequest(boolean enabled, int port) {}
/** Réponse du bouton « Autoriser dans le pare-feu » : ce qui s'est passé + le nouvel état. */
public record FirewallFixResponse(HostNetworkAccess.FirewallFixOutcome outcome, NetworkReadiness readiness) {}
@GetMapping
public RemoteAccessStatus status() {
return remoteAccessService.status();
@@ -51,6 +58,26 @@ public class RemoteAccessAdminController {
return remoteAccessService.newPairingCode();
}
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
@GetMapping("/network-check")
public NetworkReadiness networkCheck() {
return NetworkReadiness.evaluate(hostNetworkAccess.inspect());
}
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
@PostMapping("/firewall-rule")
public FirewallFixResponse allowThroughFirewall() {
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect()));
}
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
@PostMapping("/open-network-settings")
public ResponseEntity<Void> openNetworkSettings() {
hostNetworkAccess.openNetworkSettings();
return ResponseEntity.noContent().build();
}
@DeleteMapping("/devices/{id}")
public ResponseEntity<Void> revoke(@PathVariable String id) {
return remoteAccessService.revoke(id) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
@@ -0,0 +1,79 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import com.loremind.domain.remoteaccess.NetworkSnapshot.FirewallRule;
import com.loremind.domain.remoteaccess.NetworkSnapshot.Network;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** Test du verdict « une tablette peut-elle joindre ce PC ? » à partir des faits lus sur Windows. */
class NetworkReadinessTest {
private static final Network HOME_PRIVATE = new Network("Bbox-Maison", "Wi-Fi", "Private");
private static final Network HOME_PUBLIC = new Network("Bbox-Maison", "Wi-Fi", "Public");
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules));
}
@Test
void unsupported_whenNotWindows() {
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.unsupported());
assertFalse(r.supported());
assertFalse(r.ready());
}
@Test
void ready_onPrivateNetwork_withAllowRule() {
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE));
assertTrue(r.ready());
assertTrue(r.firewallAllowed());
assertTrue(r.publicNetworks().isEmpty());
}
@Test
void notReady_withoutAnyRule_evenOnPrivateNetwork() {
// Cas réel du 2026-10-17 : Wi-Fi passé en privé, mais aucune règle → la tablette charge sans fin.
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of());
assertFalse(r.ready());
assertFalse(r.firewallAllowed());
}
@Test
void notReady_onPublicNetwork_evenWithPrivateRule() {
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(ALLOW_PRIVATE));
assertFalse(r.ready());
assertEquals(List.of("Bbox-Maison"), r.publicNetworks());
}
@Test
void publicNetwork_isNotAnObstacle_whenPublicExplicitlyAllowed() {
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(new FirewallRule("Allow", "Private, Public", "True")));
assertTrue(r.ready());
assertTrue(r.publicNetworks().isEmpty());
}
@Test
void blockRule_winsOverAllow() {
NetworkReadiness r = eval(List.of(HOME_PRIVATE),
List.of(ALLOW_PRIVATE, new FirewallRule("Block", "Any", "True")));
assertFalse(r.ready());
assertTrue(r.firewallBlocked());
}
@Test
void disabledRules_areIgnored_andAnyCoversPrivate() {
assertFalse(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Private", "False"))).ready());
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
}
@Test
void publicNetwork_withoutName_usesInterfaceAlias() {
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
}
}
@@ -0,0 +1,73 @@
package com.loremind.infrastructure.desktop;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test de {@link WindowsHostNetworkAccess} : lecture du JSON de PowerShell (objet seul ou
* tableau), contenu des scripts, et — sur Windows seulement — un vrai appel en lecture seule.
*/
class WindowsHostNetworkAccessTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void parse_handlesSingleObjectsAndArrays() throws Exception {
// ConvertTo-Json écrit un objet (pas un tableau) quand il n'y a qu'un élément.
String json = "{\"networks\":{\"name\":\"Bbox\",\"alias\":\"Wi-Fi\",\"category\":\"Private\"},"
+ "\"rules\":[{\"action\":\"Allow\",\"profile\":\"Private\",\"enabled\":\"True\"},"
+ "{\"action\":\"Block\",\"profile\":\"Public\",\"enabled\":\"True\"}]}";
NetworkSnapshot s = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", json);
assertTrue(s.supported());
assertEquals(1, s.networks().size());
assertEquals("Private", s.networks().get(0).category());
assertEquals(2, s.rules().size());
assertEquals("Block", s.rules().get(1).action());
}
@Test
void parse_handlesEmptyLists_andEmptyOutput() throws Exception {
NetworkSnapshot empty = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", "{\"networks\":[],\"rules\":[]}");
assertTrue(empty.networks().isEmpty());
assertTrue(empty.rules().isEmpty());
NetworkSnapshot blank = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", " ");
assertTrue(blank.networks().isEmpty());
}
@Test
void scripts_quoteThePath_andOnlyOpenPrivateNetworks() {
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
String allow = WindowsHostNetworkAccess.allowScript(path);
assertTrue(allow.contains("'C:\\Users\\l''MJ\\DM Loremind.exe'"), "apostrophe doublée dans la chaîne PowerShell");
assertTrue(allow.contains("-Profile Private"));
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
}
@Test
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
String encoded = WindowsHostNetworkAccess.encode("é");
assertEquals("é", new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
}
@Test
@EnabledOnOs(OS.WINDOWS)
void inspect_readsTheRealSystem_onWindows() {
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect();
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
assertNotNull(s.program());
}
}
@@ -30,6 +30,24 @@ export interface PairingCode {
expiresAt: string;
}
/** Une tablette peut-elle joindre ce PC ? (Windows : type de réseau + pare-feu) */
export interface NetworkReadiness {
supported: boolean;
ready: boolean;
/** Réseaux connectés classés « Public » que le pare-feu ne laisse pas passer. */
publicNetworks: string[];
firewallAllowed: boolean;
firewallBlocked: boolean;
program?: string | null;
}
export type FirewallFixOutcome = 'APPLIED' | 'CANCELLED' | 'FAILED' | 'UNSUPPORTED';
export interface FirewallFixResponse {
outcome: FirewallFixOutcome;
readiness: NetworkReadiness;
}
export interface RemoteSession {
/** Requête arrivée par le réseau local (tablette) plutôt que depuis le PC. */
remote: boolean;
@@ -65,6 +83,19 @@ export class RemoteAccessService {
return this.http.delete<void>(`${this.adminUrl}/devices/${deviceId}`);
}
networkCheck(): Observable<NetworkReadiness> {
return this.http.get<NetworkReadiness>(`${this.adminUrl}/network-check`);
}
/** Attend la réponse de l'utilisateur à la confirmation administrateur de Windows. */
allowThroughFirewall(): Observable<FirewallFixResponse> {
return this.http.post<FirewallFixResponse>(`${this.adminUrl}/firewall-rule`, {});
}
openNetworkSettings(): Observable<void> {
return this.http.post<void>(`${this.adminUrl}/open-network-settings`, {});
}
pair(code: string, deviceName: string): Observable<PairedDevice> {
return this.http.post<PairedDevice>('/api/remote-access/pair', { code, deviceName });
}
@@ -36,6 +36,48 @@
}
</div>
@if (network?.supported) {
<div class="remote-block network-check" [class.ok]="network!.ready">
<h3>{{ 'remoteAccess.network.title' | translate }}</h3>
@if (network!.ready) {
<p class="check-ok">
<lucide-icon [img]="CheckCircle2" [size]="16"></lucide-icon>
{{ 'remoteAccess.network.ready' | translate }}
</p>
} @else {
@if (network!.publicNetworks.length > 0) {
<div class="check-item">
<p class="check-problem">{{ 'remoteAccess.network.publicProblem' | translate: { names: network!.publicNetworks.join(', ') } }}</p>
<p class="note">{{ 'remoteAccess.network.publicHowTo' | translate }}</p>
<button type="button" class="btn-secondary" (click)="openNetworkSettings()">
<lucide-icon [img]="Settings2" [size]="15"></lucide-icon>
{{ 'remoteAccess.network.openSettings' | translate }}
</button>
</div>
}
@if (firewallNeedsFix) {
<div class="check-item">
<p class="check-problem">
{{ (network!.firewallBlocked ? 'remoteAccess.network.firewallBlocked' : 'remoteAccess.network.firewallMissing') | translate }}
</p>
<button type="button" class="btn-primary" (click)="allowFirewall()" [disabled]="fixing">
<lucide-icon [img]="ShieldCheck" [size]="16"></lucide-icon>
{{ (fixing ? 'remoteAccess.network.fixing' : 'remoteAccess.network.allowFirewall') | translate }}
</button>
<p class="note">{{ 'remoteAccess.network.uacNote' | translate }}</p>
</div>
}
}
@if (fixMessage) {
<p class="fix-message" role="status">{{ fixMessage }}</p>
}
<button type="button" class="btn-link" (click)="checkNetwork()" [disabled]="checking">
<lucide-icon [img]="RefreshCw" [size]="14"></lucide-icon>
{{ (checking ? 'remoteAccess.network.checking' : 'remoteAccess.network.recheck') | translate }}
</button>
</div>
}
<div class="remote-block">
<h3>{{ 'remoteAccess.settings.pairTitle' | translate }}</h3>
@if (pairing) {
@@ -171,3 +171,63 @@
color: white;
}
}
// --- Vérification du réseau (pare-feu / réseau public) ---------------------------------
.network-check {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
padding: 0.9rem 1rem;
border-radius: 8px;
border: 1px solid rgba(245, 158, 11, 0.35);
background: rgba(245, 158, 11, 0.06);
&.ok {
border-color: rgba(34, 197, 94, 0.35);
background: rgba(34, 197, 94, 0.06);
}
}
.check-ok {
display: flex;
align-items: center;
gap: 0.45rem;
margin: 0;
color: #86efac;
font-size: 0.9rem;
}
.check-item {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
}
.check-problem {
margin: 0;
color: #fde68a;
font-size: 0.9rem;
line-height: 1.5;
}
.fix-message {
margin: 0;
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.75);
}
.btn-link {
padding: 0;
border: none;
background: none;
color: #a5b4fc;
font-size: 0.85rem;
cursor: pointer;
min-height: 32px !important;
&:hover:not(:disabled) { text-decoration: underline; }
&:disabled { opacity: 0.6; cursor: wait; }
&:focus-visible { outline: 2px solid #6c63ff; border-radius: 4px; }
}
@@ -3,11 +3,11 @@ import { FormsModule } from '@angular/forms';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { LucideAngularModule, Tablet, Trash2, RefreshCw, AlertCircle, ShieldCheck } from 'lucide-angular';
import { LucideAngularModule, Tablet, Trash2, RefreshCw, AlertCircle, ShieldCheck, CheckCircle2, Settings2 } from 'lucide-angular';
import QRCode from 'qrcode';
import {
PairedDevice, PairingCode, RemoteAccessService, RemoteAccessStatus
NetworkReadiness, PairedDevice, PairingCode, RemoteAccessService, RemoteAccessStatus
} from '../../services/remote-access.service';
import { ConfirmDialogService } from '../../shared/confirm-dialog/confirm-dialog.service';
@@ -28,6 +28,8 @@ export class RemoteAccessSectionComponent implements OnInit, OnDestroy {
readonly RefreshCw = RefreshCw;
readonly AlertCircle = AlertCircle;
readonly ShieldCheck = ShieldCheck;
readonly CheckCircle2 = CheckCircle2;
readonly Settings2 = Settings2;
private readonly remoteAccess = inject(RemoteAccessService);
private readonly translate = inject(TranslateService);
@@ -41,6 +43,12 @@ export class RemoteAccessSectionComponent implements OnInit, OnDestroy {
busy = false;
error: string | null = null;
/** Pare-feu et type de réseau (Windows) : null tant que non vérifié ou accès fermé. */
network: NetworkReadiness | null = null;
checking = false;
fixing = false;
fixMessage: string | null = null;
pairing: PairingCode | null = null;
qrDataUrl: string | null = null;
secondsLeft = 0;
@@ -138,6 +146,50 @@ export class RemoteAccessSectionComponent implements OnInit, OnDestroy {
private apply(status: RemoteAccessStatus): void {
this.status = status;
this.port = status.port;
if (status.running) {
this.checkNetwork();
} else {
this.network = null;
this.fixMessage = null;
}
}
// --- Vérification du réseau (Windows) ----------------------------------------------
/** Sans règle de pare-feu, ou sur un réseau « Public », la tablette charge sans fin : on le dit. */
checkNetwork(): void {
if (this.checking) return;
this.checking = true;
this.remoteAccess.networkCheck().subscribe({
next: r => { this.checking = false; this.network = r; },
error: () => { this.checking = false; this.network = null; }
});
}
/** Windows affiche sa confirmation administrateur : la requête attend la réponse. */
allowFirewall(): void {
if (this.fixing) return;
this.fixing = true;
this.fixMessage = null;
this.remoteAccess.allowThroughFirewall().subscribe({
next: res => {
this.fixing = false;
this.network = res.readiness;
this.fixMessage = this.translate.instant(`remoteAccess.network.fix.${res.outcome}`);
},
error: () => {
this.fixing = false;
this.fixMessage = this.translate.instant('remoteAccess.network.fix.FAILED');
}
});
}
openNetworkSettings(): void {
this.remoteAccess.openNetworkSettings().subscribe({ error: () => undefined });
}
get firewallNeedsFix(): boolean {
return !!this.network && (!this.network.firewallAllowed || this.network.firewallBlocked);
}
/** Le QR code ouvre directement l'écran d'appairage avec le code pré-rempli. */
+21 -1
View File
@@ -2393,7 +2393,7 @@
"title": "Access from a tablet",
"hint": "Browse and edit your campaigns from a tablet or phone on the same Wi-Fi as this PC. Each device must be authorized once, with a code shown here.",
"enable": "Allow access from the local network",
"firewallNote": "When you turn this on, Windows may ask to allow DM Loremind through the firewall: choose \"Private networks\" only. Only enable it on a trusted network (your home router), never on public Wi-Fi.",
"firewallNote": "Once access is on, DM Loremind checks that the Windows firewall and your network type let the tablet through, and helps you fix it if needed. Only turn it on at home, never on public Wi-Fi.",
"addressTitle": "Address to open on the tablet",
"noAddress": "No local network address found: check that this PC is connected to your Wi-Fi or home router.",
"pairTitle": "Connect a device",
@@ -2434,6 +2434,26 @@
"onHostTitle": "You're on the PC",
"onHostText": "This page is for connecting a tablet. On this PC, access is managed from Settings.",
"onHostLink": "Open access settings"
},
"network": {
"title": "Network check",
"ready": "The firewall and the network let the tablet through.",
"publicProblem": "Windows considers your network \"{{names}}\" public: it blocks other devices, even with the firewall permission.",
"publicHowTo": "If it's your home network, switch it to \"Private\": Windows network settings > your Wi-Fi > Properties > Network profile type: Private. Then check again.",
"openSettings": "Open network settings",
"firewallMissing": "The Windows firewall doesn't let DM Loremind through yet: the tablet would load forever.",
"firewallBlocked": "The Windows firewall blocks DM Loremind (a permission was probably declined).",
"allowFirewall": "Allow through the firewall",
"fixing": "Confirm in the Windows prompt…",
"uacNote": "Windows will ask for administrator confirmation. DM Loremind will be allowed on private networks only.",
"recheck": "Check again",
"checking": "Checking…",
"fix": {
"APPLIED": "Done: DM Loremind is allowed through the firewall.",
"CANCELLED": "Confirmation cancelled: nothing was changed.",
"FAILED": "The permission failed. You can try again, or add it manually (see the documentation).",
"UNSUPPORTED": "This check is only available on Windows."
}
}
},
"mobileShell": {
+21 -1
View File
@@ -2393,7 +2393,7 @@
"title": "Accès depuis une tablette",
"hint": "Consulte et modifie tes campagnes depuis une tablette ou un téléphone connecté au même Wi-Fi que ce PC. Chaque appareil doit être autorisé une fois, avec un code affiché ici.",
"enable": "Autoriser l'accès depuis le réseau local",
"firewallNote": "À l'activation, Windows peut demander d'autoriser DM Loremind dans le pare-feu : choisis « Réseaux privés » uniquement. À n'activer que sur un réseau de confiance (ta box), jamais sur un Wi-Fi public.",
"firewallNote": "Une fois l'accès activé, DM Loremind vérifie que le pare-feu Windows et le type de ton réseau laissent passer la tablette, et t'aide à corriger si besoin. À n'activer que sur ton réseau de maison, jamais sur un Wi-Fi public.",
"addressTitle": "Adresse à ouvrir sur la tablette",
"noAddress": "Aucune adresse réseau locale détectée : vérifie que ce PC est bien connecté au Wi-Fi ou au réseau de ta box.",
"pairTitle": "Connecter un appareil",
@@ -2434,6 +2434,26 @@
"onHostTitle": "Tu es sur le PC",
"onHostText": "Cette page sert à connecter une tablette. Sur ce PC, l'accès se règle depuis les Paramètres.",
"onHostLink": "Ouvrir les réglages d'accès"
},
"network": {
"title": "Vérification du réseau",
"ready": "Le pare-feu et le réseau laissent passer la tablette.",
"publicProblem": "Windows considère ton réseau « {{names}} » comme un réseau public : il bloque les autres appareils, même avec l'autorisation du pare-feu.",
"publicHowTo": "S'il s'agit de ton réseau de maison, passe-le en « Privé » : réglages réseau de Windows > ton Wi-Fi > Propriétés > Type de profil réseau : Privé. Puis vérifie à nouveau.",
"openSettings": "Ouvrir les réglages réseau",
"firewallMissing": "Le pare-feu Windows ne laisse pas encore passer DM Loremind : la tablette chargerait sans fin.",
"firewallBlocked": "Le pare-feu Windows bloque DM Loremind (une autorisation a sans doute été refusée).",
"allowFirewall": "Autoriser dans le pare-feu",
"fixing": "Confirme dans la fenêtre de Windows…",
"uacNote": "Windows te demandera une confirmation administrateur. DM Loremind sera autorisé sur les réseaux privés uniquement.",
"recheck": "Vérifier à nouveau",
"checking": "Vérification…",
"fix": {
"APPLIED": "C'est fait : DM Loremind est autorisé dans le pare-feu.",
"CANCELLED": "Confirmation annulée : rien n'a été modifié.",
"FAILED": "L'autorisation a échoué. Tu peux réessayer, ou l'ajouter à la main (voir la documentation).",
"UNSUPPORTED": "Cette vérification n'est disponible que sur Windows."
}
}
},
"mobileShell": {
@@ -4,7 +4,7 @@
"title": "Access from a tablet",
"hint": "Browse and edit your campaigns from a tablet or phone on the same Wi-Fi as this PC. Each device must be authorized once, with a code shown here.",
"enable": "Allow access from the local network",
"firewallNote": "When you turn this on, Windows may ask to allow DM Loremind through the firewall: choose \"Private networks\" only. Only enable it on a trusted network (your home router), never on public Wi-Fi.",
"firewallNote": "Once access is on, DM Loremind checks that the Windows firewall and your network type let the tablet through, and helps you fix it if needed. Only turn it on at home, never on public Wi-Fi.",
"addressTitle": "Address to open on the tablet",
"noAddress": "No local network address found: check that this PC is connected to your Wi-Fi or home router.",
"pairTitle": "Connect a device",
@@ -45,6 +45,26 @@
"onHostTitle": "You're on the PC",
"onHostText": "This page is for connecting a tablet. On this PC, access is managed from Settings.",
"onHostLink": "Open access settings"
},
"network": {
"title": "Network check",
"ready": "The firewall and the network let the tablet through.",
"publicProblem": "Windows considers your network \"{{names}}\" public: it blocks other devices, even with the firewall permission.",
"publicHowTo": "If it's your home network, switch it to \"Private\": Windows network settings > your Wi-Fi > Properties > Network profile type: Private. Then check again.",
"openSettings": "Open network settings",
"firewallMissing": "The Windows firewall doesn't let DM Loremind through yet: the tablet would load forever.",
"firewallBlocked": "The Windows firewall blocks DM Loremind (a permission was probably declined).",
"allowFirewall": "Allow through the firewall",
"fixing": "Confirm in the Windows prompt…",
"uacNote": "Windows will ask for administrator confirmation. DM Loremind will be allowed on private networks only.",
"recheck": "Check again",
"checking": "Checking…",
"fix": {
"APPLIED": "Done: DM Loremind is allowed through the firewall.",
"CANCELLED": "Confirmation cancelled: nothing was changed.",
"FAILED": "The permission failed. You can try again, or add it manually (see the documentation).",
"UNSUPPORTED": "This check is only available on Windows."
}
}
}
}
@@ -4,7 +4,7 @@
"title": "Accès depuis une tablette",
"hint": "Consulte et modifie tes campagnes depuis une tablette ou un téléphone connecté au même Wi-Fi que ce PC. Chaque appareil doit être autorisé une fois, avec un code affiché ici.",
"enable": "Autoriser l'accès depuis le réseau local",
"firewallNote": "À l'activation, Windows peut demander d'autoriser DM Loremind dans le pare-feu : choisis « Réseaux privés » uniquement. À n'activer que sur un réseau de confiance (ta box), jamais sur un Wi-Fi public.",
"firewallNote": "Une fois l'accès activé, DM Loremind vérifie que le pare-feu Windows et le type de ton réseau laissent passer la tablette, et t'aide à corriger si besoin. À n'activer que sur ton réseau de maison, jamais sur un Wi-Fi public.",
"addressTitle": "Adresse à ouvrir sur la tablette",
"noAddress": "Aucune adresse réseau locale détectée : vérifie que ce PC est bien connecté au Wi-Fi ou au réseau de ta box.",
"pairTitle": "Connecter un appareil",
@@ -45,6 +45,26 @@
"onHostTitle": "Tu es sur le PC",
"onHostText": "Cette page sert à connecter une tablette. Sur ce PC, l'accès se règle depuis les Paramètres.",
"onHostLink": "Ouvrir les réglages d'accès"
},
"network": {
"title": "Vérification du réseau",
"ready": "Le pare-feu et le réseau laissent passer la tablette.",
"publicProblem": "Windows considère ton réseau « {{names}} » comme un réseau public : il bloque les autres appareils, même avec l'autorisation du pare-feu.",
"publicHowTo": "S'il s'agit de ton réseau de maison, passe-le en « Privé » : réglages réseau de Windows > ton Wi-Fi > Propriétés > Type de profil réseau : Privé. Puis vérifie à nouveau.",
"openSettings": "Ouvrir les réglages réseau",
"firewallMissing": "Le pare-feu Windows ne laisse pas encore passer DM Loremind : la tablette chargerait sans fin.",
"firewallBlocked": "Le pare-feu Windows bloque DM Loremind (une autorisation a sans doute été refusée).",
"allowFirewall": "Autoriser dans le pare-feu",
"fixing": "Confirme dans la fenêtre de Windows…",
"uacNote": "Windows te demandera une confirmation administrateur. DM Loremind sera autorisé sur les réseaux privés uniquement.",
"recheck": "Vérifier à nouveau",
"checking": "Vérification…",
"fix": {
"APPLIED": "C'est fait : DM Loremind est autorisé dans le pare-feu.",
"CANCELLED": "Confirmation annulée : rien n'a été modifié.",
"FAILED": "L'autorisation a échoué. Tu peux réessayer, ou l'ajouter à la main (voir la documentation).",
"UNSUPPORTED": "Cette vérification n'est disponible que sur Windows."
}
}
}
}