Merge remote-tracking branch 'origin/main' into fix-camera-access-nullable-select

This commit is contained in:
arnaud.dartois committed 2026-11-08 20:14:28 +01:00
commit 81b794daf7
53 files changed
+997 -117

No files matched your search

@@ -902,10 +902,17 @@ else
_ = LoadUpdateInfoAsync();
}
}
catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex))
{
// Le filtre d'accès renvoie 403 pour masquer un agent absent ou non accessible.
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _loading = false; }
}
private static bool IsMissingOrHiddenResource(HttpRequestException exception) =>
exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden;
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
private async Task LoadMetricHistoryAsync(string range)
@@ -372,14 +372,24 @@ else
_eventRecordingEnabled = _camera.EventRecordingEnabled;
}
}
catch (HttpRequestException ex) when (IsMissingOrHiddenResource(ex))
{
// Le filtre d'accès renvoie 403 pour masquer une caméra absente ou non accessible.
}
catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); }
finally { _loading = false; }
await LoadEventsAsync();
await LoadRecordingsAsync();
await LoadLatestSnapshotAsync();
if (_camera is not null)
{
await LoadEventsAsync();
await LoadRecordingsAsync();
await LoadLatestSnapshotAsync();
}
}
private static bool IsMissingOrHiddenResource(HttpRequestException exception) =>
exception.StatusCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden;
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
// L'auto-refresh démarre après le premier rendu : une boucle infinie
@@ -389,7 +399,7 @@ else
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender && !_autoRefreshStarted)
if (firstRender && !_autoRefreshStarted && _camera is not null)
{
_autoRefreshStarted = true;
await StartAutoRefresh();
@@ -282,6 +282,8 @@
// infinie awaitée dans OnInitializedAsync bloque le rendu initial
// (SSR/prerender attend la fin du cycle de vie) → page lente.
private CancellationTokenSource? _refreshCts;
private Task? _refreshTask;
private readonly object _refreshLock = new();
private bool _disposed;
private bool _autoRefreshStarted;
@@ -290,18 +292,24 @@
if (firstRender && !_autoRefreshStarted)
{
_autoRefreshStarted = true;
await StartAutoRefresh();
lock (_refreshLock)
{
if (!_disposed)
{
_refreshCts = new CancellationTokenSource();
_refreshTask = RunAutoRefreshAsync(_refreshCts.Token);
}
}
}
}
private async Task StartAutoRefresh()
private async Task RunAutoRefreshAsync(CancellationToken cancellationToken)
{
_refreshCts = new CancellationTokenSource();
try
{
while (!_refreshCts.Token.IsCancellationRequested)
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(15), _refreshCts.Token);
await Task.Delay(TimeSpan.FromSeconds(15), cancellationToken);
if (_disposed) return;
// Rafraîchit uniquement la section agents (léger) : les stats
// globales restent au refresh manuel pour éviter le flash.
@@ -311,6 +319,10 @@
var agentsPage = await Api.GetAllAgentsAsync(1, 5);
_agents = agentsPage?.Items?.ToList();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch { /* keep last state */ }
finally
{
@@ -320,6 +332,7 @@
}
}
catch (OperationCanceledException) { /* arrêt volontaire */ }
catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested) { /* arrêt concurrent */ }
}
private async Task LoadData()
@@ -401,9 +414,29 @@
public void Dispose()
{
_disposed = true;
CancellationTokenSource? refreshCts;
lock (_refreshLock)
{
_disposed = true;
refreshCts = _refreshCts;
_refreshCts = null;
}
Language.LanguageChanged -= OnLanguageChanged;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
if (refreshCts is not null)
{
try { refreshCts.Cancel(); }
catch (ObjectDisposedException) { /* shutdown already completed */ }
_ = DisposeRefreshAsync(refreshCts, _refreshTask);
}
}
private static async Task DisposeRefreshAsync(CancellationTokenSource refreshCts, Task? refreshTask)
{
try
{
if (refreshTask is not null) await refreshTask;
}
catch (OperationCanceledException) { }
finally { refreshCts.Dispose(); }
}
}
+16 -15
View File
@@ -131,19 +131,19 @@
{
_loading = true;
_errorMessage = "";
Logger.LogInformation("Login attempt for email: {Email}", _email);
Logger.LogInformation("Login attempt");
try
{
var result = await Api.LoginAsync(_email, _password);
if (result is null)
{
Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email);
Logger.LogWarning("Login failed: invalid credentials");
_errorMessage = Text["LoginPage_InvalidCredentials"];
return;
}
Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa);
Logger.LogInformation("Login succeeded. Requires 2FA: {Requires2fa}", result.Requires2fa);
// Check if 2FA is required
if (result.Requires2fa)
@@ -152,7 +152,7 @@
_password = "";
_requires2fa = true;
_loading = false;
Logger.LogInformation("2FA required for {Email}", _email);
Logger.LogInformation("2FA required");
return;
}
@@ -160,7 +160,7 @@
}
catch (Exception ex)
{
Logger.LogError(ex, "Login error for {Email}", _email);
Logger.LogError("Login flow failed (error type {ErrorType})", ex.GetType().Name);
_errorMessage = UiErrors.OperationFailed();
}
finally { _loading = false; }
@@ -170,31 +170,31 @@
{
if (string.IsNullOrWhiteSpace(_twoFactorCode))
{
Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email);
Logger.LogWarning("2FA verification attempted with an empty code");
_errorMessage = Text["LoginPage_TwoFactorCodeRequired"];
return;
}
_loading = true;
_errorMessage = "";
Logger.LogInformation("2FA verification attempt for {Email}", _email);
Logger.LogInformation("2FA verification attempt");
try
{
var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim());
if (result is null)
{
Logger.LogWarning("2FA verification failed for {Email}", _email);
Logger.LogWarning("2FA verification failed");
_errorMessage = Text["LoginPage_InvalidTwoFactorCode"];
return;
}
Logger.LogInformation("2FA verification successful for {Email}", _email);
Logger.LogInformation("2FA verification succeeded");
await CompleteAuthAsync(result);
}
catch (Exception ex)
{
Logger.LogError(ex, "2FA verification error for {Email}", _email);
Logger.LogError("2FA verification flow failed (error type {ErrorType})", ex.GetType().Name);
_errorMessage = UiErrors.OperationFailed();
}
finally { _loading = false; }
@@ -202,7 +202,7 @@
private async Task CompleteAuthAsync(AuthResponse result)
{
Logger.LogInformation("Completing authentication for {Email}", _email);
Logger.LogInformation("Completing authentication");
// Update Blazor-level auth state
await AuthStateProvider.NotifyLoginAsync(result);
@@ -211,23 +211,24 @@
var cookieOk = true;
if (!string.IsNullOrEmpty(result.AccessToken))
{
Logger.LogDebug("Creating auth cookie for {Email}", _email);
Logger.LogDebug("Creating auth cookie");
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
Logger,
AuthHelper.CreateSignInPayload(result.AccessToken));
}
else
{
Logger.LogWarning("No access token in auth response for {Email}", _email);
Logger.LogWarning("No access token in auth response");
}
if (!cookieOk)
{
Logger.LogError("Failed to create auth cookie for {Email}", _email);
Logger.LogError("Failed to create auth cookie");
_errorMessage = Text["LoginPage_AuthSessionFailed"];
return;
}
Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl);
Logger.LogInformation("Authentication completed successfully, redirecting to {ReturnUrl}", _returnUrl);
Snackbar.Add(Text["LoginPage_SignInSucceeded"], Severity.Success);
Navigation.NavigateTo(_returnUrl);
}
@@ -0,0 +1,88 @@
@page "/notifications"
@using Heimdall.Application.DTOs
@attribute [Authorize]
@layout MainLayout
@inject HeimdallApiClient Api
@inject NotificationsHubClient Hub
@inject UiText Text
@inject ISnackbar Snackbar
<MudText Typo="Typo.h1" Class="mb-4">@Text["NotificationsPage_Title"]</MudText>
@if (_loading)
{
<MudProgressLinear Indeterminate="true" />
}
else if (_failed)
{
<MudAlert Severity="Severity.Error">@Text["NotificationsPage_Failed"]</MudAlert>
}
else if (_items.Count == 0)
{
<MudAlert Severity="Severity.Info">@Text["NotificationsPage_Empty"]</MudAlert>
}
else
{
<div class="d-flex justify-end mb-3">
<MudButton Variant="Variant.Outlined" Disabled="@(!_items.Any(x => !x.IsRead))" OnClick="MarkAllReadAsync">
@Text["NotificationsPage_MarkAllRead"]
</MudButton>
</div>
@foreach (var item in _items)
{
<MudPaper Class="pa-4 mb-2" Elevation="1">
<div class="d-flex justify-space-between align-start">
<div>
<MudText Typo="Typo.h6">@item.Title</MudText>
<MudText>@item.Message</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">@item.CreatedAt.ToLocalTime().ToString("g")</MudText>
</div>
@if (!item.IsRead)
{
<MudButton Variant="Variant.Text" OnClick="@(() => MarkReadAsync(item.Id))">@Text["NotificationsPage_MarkRead"]</MudButton>
}
</div>
</MudPaper>
}
}
@code {
private List<NotificationDto> _items = [];
private bool _loading = true;
private bool _failed;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
_loading = true;
_failed = false;
try
{
var result = await Api.GetNotificationsAsync();
_items = result?.Items.ToList() ?? [];
_failed = result is null;
}
catch (HttpRequestException) { _failed = true; }
finally { _loading = false; }
}
private async Task MarkReadAsync(Guid id)
{
if (await Api.MarkNotificationAsReadAsync(id))
{
await LoadAsync();
await Hub.RefreshUnreadCountAsync();
}
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
}
private async Task MarkAllReadAsync()
{
if (await Api.MarkAllNotificationsAsReadAsync())
{
await LoadAsync();
await Hub.RefreshUnreadCountAsync();
}
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
}
}
@@ -309,12 +309,19 @@ else
{
_person = await Api.GetPersonAsync(Id);
}
catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// La vue dédiée affiche l'état introuvable sans lancer les lectures associées.
}
catch { Snackbar.Add(Text["PersonDetailPage_OperationFailed"], Severity.Error); }
finally { _loading = false; }
await LoadFaces();
await LoadVehicles();
await LoadEvents();
if (_person is not null)
{
await LoadFaces();
await LoadVehicles();
await LoadEvents();
}
}
private async Task LoadFaces()
@@ -11,6 +11,7 @@
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthProvider
@inject IJSRuntime JS
@inject Microsoft.Extensions.Logging.ILogger<Profile> Logger
<MudText Typo="Typo.h1" Class="mb-6">
<i class="fas fa-user-circle mr-2"></i>
@@ -470,7 +471,7 @@ else if (_profile is not null)
return;
}
await AuthProvider.NotifyLoginAsync(renewedSession);
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
if (!await AuthHelper.SignInAsync(JS, Logger, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
{
_2faError = Text["OperationFailed"];
_show2faDialog = true;
@@ -5,6 +5,7 @@
@inject HeimdallAuthStateProvider AuthStateProvider
@inject NavigationManager Navigation
@inject IJSRuntime JsRuntime
@inject Microsoft.Extensions.Logging.ILogger<Setup> Logger
<div class="auth-page">
<div class="auth-card">
@@ -96,7 +97,7 @@
}
await AuthStateProvider.NotifyLoginAsync(result);
var cookieOk = !string.IsNullOrEmpty(result.AccessToken) && await AuthHelper.SignInAsync(
JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken));
JsRuntime, Logger, AuthHelper.CreateSignInPayload(result.AccessToken));
if (!cookieOk)
{
_error = Text["SetupAdmin_AutoLoginFailed"];
@@ -253,7 +253,6 @@ else
private bool _generating;
private string? _generatedToken;
private DateTime _tokenExpiresAt;
private string _dockerComposeSnippet = "";
// ── Identifiants caméras ──────────────────────────────────────
private List<SiteCredentialItem> _credentials = [];
@@ -385,15 +384,12 @@ else
}
_generatedToken = result.Token;
_tokenExpiresAt = result.ExpiresAt;
_dockerComposeSnippet = GenerateDockerComposeSnippet(_generatedToken);
Snackbar.Add(Text["SiteDetail_TokenGenerated"], Severity.Warning);
}
catch { Snackbar.Add(Text["SiteDetail_OperationFailed"], Severity.Error); }
finally { _generating = false; }
}
private string GenerateDockerComposeSnippet(string token) => "";
/// <summary>Origin exposed by the browser that operators use to reach Central.</summary>
private string CentralUrl => Nav.BaseUri.TrimEnd('/');
}
@@ -10,7 +10,7 @@
Visible="@(Hub.UnreadCount > 0)">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
aria-label="@Text["SharedNotificationBadge_Title"]"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
OnClick="@(() => Navigation.NavigateTo("/notifications"))" />
</MudBadge>
</MudTooltip>
@@ -64,18 +64,29 @@ else if (_method == "docker-compose" && !CanGenerateDocker)
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
@foreach (var command in Commands)
else if (_method == "docker-run" && CanGenerateDocker)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
}
else if (_method == "docker-run")
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
@if (_method != "docker-run" || CanGenerateDocker)
{
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
}
}
@if (_method == "windows-run")
@@ -165,7 +176,10 @@ else if (_method == "windows-service")
[
("SiteInstallPanel_Install", DockerRunInstallCommand),
("SiteInstallPanel_Run", DockerRunCommand),
("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}")
("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}"),
("SiteInstallPanel_InstallPowerShell", DockerRunPowerShellInstallCommand),
("SiteInstallPanel_RunPowerShell", DockerRunPowerShellCommand),
("SiteInstallPanel_CheckPowerShell", DockerRunPowerShellCheckCommand)
];
return [];
}
@@ -208,6 +222,8 @@ else if (_method == "windows-service")
container_name: heimdall-agent-{{safeName}}
restart: unless-stopped
user: "1654:1654"
group_add:
- "${DOCKER_GID:-0}"
network_mode: host
environment:
Agent__CentralUrl: {{YamlScalar(CentralUrl)}}
@@ -219,6 +235,7 @@ else if (_method == "windows-service")
Agent__UpdatePublicKeyPem: "{{pem}}"
volumes:
- agent_state_{{safeName}}:/var/lib/heimdall
- /var/run/docker.sock:/var/run/docker.sock
depends_on:
agent-state-init:
condition: service_completed_successfully
@@ -249,8 +266,9 @@ else if (_method == "windows-service")
get
{
var volume = "heimdall-agent-state-" + Slugify(SiteName);
return $"docker pull {_agentImageReference} && docker volume create {volume} && " +
$"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {_agentImageReference} -R 1654:1654 /state";
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
return $"docker pull {image} && docker volume create {volume} && " +
$"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {image} -R 1654:1654 /state";
}
}
@@ -263,6 +281,8 @@ else if (_method == "windows-service")
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
(_useGpuImage ? "--gpus all " : "") +
"--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " +
"-v /var/run/docker.sock:/var/run/docker.sock " +
$"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " +
$"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " +
$"-e Agent__InferenceExecutionProvider={(_useGpuImage ? "CUDA" : "CPU")} " +
@@ -271,6 +291,55 @@ else if (_method == "windows-service")
}
}
private string DockerRunPowerShellInstallCommand
{
get
{
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
return "$ErrorActionPreference = 'Stop'; " +
"docker pull " + PowerShellQuote(image ?? "") + "; if ($LASTEXITCODE -ne 0) { throw 'docker pull failed' }; " +
"docker volume create " + PowerShellQuote(volume) + "; if ($LASTEXITCODE -ne 0) { throw 'docker volume create failed' }; " +
"docker run --rm --user 0:0 --entrypoint chown -v " + PowerShellQuote(volume + ":/state") + " " +
PowerShellQuote(image ?? "") + " -R 1654:1654 /state; if ($LASTEXITCODE -ne 0) { throw 'state volume initialization failed' }";
}
}
private string DockerRunPowerShellCommand
{
get
{
var name = "heimdall-agent-" + Slugify(SiteName);
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
var args = new List<string> { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
if (_useGpuImage) args.AddRange(["--gpus", "all"]);
args.AddRange([
"-e", "Agent__CentralUrl=" + CentralUrl,
"-e", "Agent__SiteToken=" + SiteToken,
"-e", "Agent__AgentName=" + SiteName,
"-e", "Agent__StateDirectory=/var/lib/heimdall",
"-e", "ASPNETCORE_URLS=http://+:8080",
"-e", "Agent__InferenceExecutionProvider=" + (_useGpuImage ? "CUDA" : "CPU"),
"-e", "Agent__UpdatePublicKeyPem=" + (_updatePublicKeyPem ?? ""),
"-v", volume + ":/var/lib/heimdall",
image ?? ""
]);
return "$dockerArgs = @(" + string.Join(",", args.Select(PowerShellQuote)) + "); & docker @dockerArgs; if ($LASTEXITCODE -ne 0) { throw 'docker run failed' }";
}
}
private string DockerRunPowerShellCheckCommand
{
get
{
var name = "heimdall-agent-" + Slugify(SiteName);
return "$status = docker inspect --format '{{.State.Status}}' " + PowerShellQuote(name) + "; " +
"if ($LASTEXITCODE -ne 0) { throw 'container inspect failed' }; $status; " +
"docker logs --tail 50 " + PowerShellQuote(name) + "; if ($LASTEXITCODE -ne 0) { throw 'container logs failed' }";
}
}
private string LinuxInstallCommand(bool service)
{
var baseUrl = CentralUrl.TrimEnd('/');
+1
View File
@@ -12,6 +12,7 @@
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.Api.Tests" />
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
<InternalsVisibleTo Include="Heimdall.Web.Tests" />
</ItemGroup>
<ItemGroup>
@@ -4072,7 +4072,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Install (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Run (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Check (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
@@ -4072,7 +4072,7 @@
<value>Vérifier</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé.</value>
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Installer (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Démarrer (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Vérifier (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Utiliser l’inférence GPU NVIDIA</value>
</data>
@@ -4124,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Impossible de charger les notifications. Réessayez.</value></data>
<data name="NotificationsPage_Empty"><value>Vous n’avez aucune notification.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Tout marquer comme lu</value></data>
<data name="NotificationsPage_MarkRead"><value>Marquer comme lu</value></data>
<data name="NotificationsPage_UpdateFailed"><value>Impossible de mettre à jour la notification.</value></data>
</root>
@@ -4072,7 +4072,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
@@ -4083,6 +4083,15 @@
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
<value>Docker Run</value>
</data>
<data name="SiteInstallPanel_InstallPowerShell" xml:space="preserve">
<value>Install (PowerShell)</value>
</data>
<data name="SiteInstallPanel_RunPowerShell" xml:space="preserve">
<value>Run (PowerShell)</value>
</data>
<data name="SiteInstallPanel_CheckPowerShell" xml:space="preserve">
<value>Check (PowerShell)</value>
</data>
<data name="SiteInstallPanel_NvidiaInference" xml:space="preserve">
<value>Use NVIDIA GPU inference</value>
</data>
@@ -4124,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Notifications could not be loaded. Try again.</value></data>
<data name="NotificationsPage_Empty"><value>You have no notifications.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Mark all as read</value></data>
<data name="NotificationsPage_MarkRead"><value>Mark as read</value></data>
<data name="NotificationsPage_UpdateFailed"><value>The notification could not be updated.</value></data>
</root>
+70 -1
View File
@@ -850,6 +850,55 @@ public partial class Program
localizationOptions.RequestCultureProviders.Insert(1, new CookieRequestCultureProvider());
app.UseRequestLocalization(localizationOptions);
// Unknown browser routes have no endpoint and cannot start the interactive
// Blazor circuit. Render the same localized NotFound content as a static
// 404 document; preserve native API, hub, health, Hangfire, and asset errors.
app.UseStatusCodePages(async statusCodeContext =>
{
var context = statusCodeContext.HttpContext;
var path = context.Request.Path;
var isNonUiResponse = path.StartsWithSegments("/api")
|| path.StartsWithSegments("/hubs")
|| path.StartsWithSegments("/healthz")
|| path.StartsWithSegments("/hangfire")
|| Path.HasExtension(path.Value)
|| !context.Request.Headers.Accept.Any(value =>
value?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true);
if (context.Response.StatusCode != StatusCodes.Status404NotFound || isNonUiResponse) return;
var text = context.RequestServices.GetRequiredService<UiText>();
var encoder = System.Text.Encodings.Web.HtmlEncoder.Default;
var title = encoder.Encode(text["NotFoundPage_Title"]);
var message = encoder.Encode(text["NotFoundPage_Body"]);
var back = encoder.Encode(text["NotFoundPage_Back"]);
context.Response.ContentType = "text/html; charset=utf-8";
var document = $$"""
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{title}}</title>
<style>
body { margin: 0; background: #101828; color: #f9fafb; font: 16px Inter, system-ui, sans-serif; }
main { box-sizing: border-box; max-width: 48rem; margin: 12vh auto; padding: 2rem; }
h1 { color: #60a5fa; font-size: 2.5rem; }
p { color: #cbd5e1; line-height: 1.6; }
a { display: inline-block; margin-top: 1rem; padding: .75rem 1rem; border-radius: .5rem; background: #2563eb; color: white; text-decoration: none; }
</style>
</head>
<body>
<main>
<h1>{{title}}</h1>
<p>{{message}}</p>
<a href="/dashboard">{{back}}</a>
</main>
</body>
</html>
""";
await context.Response.WriteAsync(document);
});
// Hangfire dashboard — Admin uniquement (policy AdminJobs).
// MapHangfireDashboard est utilisé car UseHangfireDashboard avec
// DashboardOptions.Authorization n'existe pas pour les policies ASP.NET.
@@ -925,11 +974,13 @@ public partial class Program
{
if (string.IsNullOrEmpty(request.AccessToken))
return Results.BadRequest(new { error = "AccessToken is required" });
var failureStage = "token validation";
try
{
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(request.AccessToken,
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _);
failureStage = "account session validation";
if (!await ValidateAccountSessionAsync(principal, httpContext))
return Results.Unauthorized();
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
@@ -954,6 +1005,7 @@ public partial class Program
claims.Add(new Claim("permission", permission.Value));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
failureStage = "cookie issuance";
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity),
new AuthenticationProperties
{
@@ -964,7 +1016,24 @@ public partial class Program
return Results.Ok();
}
catch (SecurityTokenExpiredException) { return Results.Unauthorized(); }
catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); }
catch (SecurityTokenException ex)
{
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
return Results.Unauthorized();
}
catch (ArgumentException ex) when (failureStage == "token validation")
{
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
return Results.Unauthorized();
}
catch (Exception ex)
{
logger.LogError("Cookie sign-in failed during {FailureStage} (error type {ErrorType})",
failureStage, ex.GetType().Name);
return Results.Problem(
statusCode: StatusCodes.Status500InternalServerError,
title: "Authentication session could not be created");
}
});
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
+19 -6
View File
@@ -1,4 +1,5 @@
using Microsoft.JSInterop;
using Microsoft.Extensions.Logging;
namespace Heimdall.Web.Services;
@@ -7,18 +8,30 @@ internal static class AuthHelper
{
/// <summary>Creates the middleware-level auth cookie via JS interop.</summary>
/// <returns>True if the sign-in HTTP call succeeded (2xx).</returns>
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, object user)
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, ILogger logger, object user)
{
try
{
var ok = await jsRuntime.InvokeAsync<bool>("heimdallAuth.signIn", user);
if (!ok)
Console.Error.WriteLine("[AuthHelper] SignInAsync: /_auth/signin returned non-2xx status");
return ok;
var statusCode = await jsRuntime.InvokeAsync<int>("heimdallAuth.signIn", user);
if (statusCode is >= 200 and < 300)
return true;
logger.LogWarning("Cookie sign-in endpoint returned HTTP status {StatusCode}", statusCode);
return false;
}
catch (JSDisconnectedException)
{
logger.LogInformation("Cookie sign-in was interrupted because the browser circuit disconnected");
return false;
}
catch (JSException ex)
{
logger.LogWarning("Cookie sign-in JavaScript interop failed (error type {ErrorType})", ex.GetType().Name);
return false;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[AuthHelper] SignInAsync JS interop failed: {ex.Message}");
logger.LogWarning("Cookie sign-in bridge failed (error type {ErrorType})", ex.GetType().Name);
return false;
}
}
@@ -1037,6 +1037,25 @@ public class HeimdallApiClient : IDisposable
// ─── Notification Config ─────────────────────────────────────────
public async Task<PagedResult<NotificationDto>?> GetNotificationsAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedResult<NotificationDto>>(
$"api/notifications?page={page}&pageSize={pageSize}", Json);
}
public async Task<bool> MarkNotificationAsReadAsync(Guid id)
{
using var response = await CreateClient().PostAsync($"api/notifications/{id}/read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<bool> MarkAllNotificationsAsReadAsync()
{
using var response = await CreateClient().PostAsync("api/notifications/mark-all-read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<NotificationConfigItem?> GetNotificationConfigAsync()
{
var client = CreateClient();
+2 -2
View File
@@ -11,9 +11,9 @@ window.heimdallAuth = {
body: JSON.stringify(data),
credentials: 'include'
});
return response.ok;
return response.status;
} catch {
return false;
return 0;
}
},