Cross-platform shell, informative dashboard, OS icons, deployment fixes #8

Merged
gsadmin merged 7 commits from dev into main 2026-08-09 14:35:39 +00:00
53 changed files with 1980 additions and 441 deletions
+5
View File
@@ -92,6 +92,11 @@ FORWARD_LIMIT=1
TLS_SELF_SIGNED=0
TLS_CERT_DIR=
# ── Execution history ──────────────────────────────────────────────────────
# Newest jobs kept per device (older jobs and their stored output are
# pruned). 0 disables pruning.
JOB_HISTORY_LIMIT=200
# ── Initial local admin (first startup only) ───────────────────────────────
INITIAL_ADMIN_USERNAME=admin
# Generate: openssl rand -base64 24
+9 -9
View File
@@ -112,12 +112,12 @@ jobs:
-Runtimes win-x64,win-arm64,linux-x64,linux-arm64,osx-x64,osx-arm64
$stage = 'artifacts/agent-package'
New-Item -ItemType Directory -Force $stage | Out-Null
$msi = "artifacts/Agent-${{ steps.ver.outputs.version }}.msi"
$zip = "artifacts/Agent-${{ steps.ver.outputs.version }}-win-x64.zip"
$msi = "artifacts/ExecuteR-Agent-${{ steps.ver.outputs.version }}.msi"
$zip = "artifacts/ExecuteR-Agent-${{ steps.ver.outputs.version }}-win-x64.zip"
if (Test-Path $msi) { Copy-Item $msi "$stage/Agent.msi" }
if (Test-Path $zip) { Copy-Item $zip "$stage/Agent.zip" }
foreach ($rid in 'linux-x64','linux-arm64','osx-x64','osx-arm64') {
$unix = "artifacts/Agent-${{ steps.ver.outputs.version }}-$rid.zip"
$unix = "artifacts/ExecuteR-Agent-${{ steps.ver.outputs.version }}-$rid.zip"
if (Test-Path $unix) { Copy-Item $unix "$stage/Agent-$rid.zip" }
}
'${{ steps.ver.outputs.version }}' | Set-Content "$stage/VERSION" -NoNewline
@@ -143,12 +143,12 @@ jobs:
with:
name: binaries
path: |
artifacts/Agent-*.zip
artifacts/Agent-*.msi
artifacts/Agent-*-checksums.txt
artifacts/Server-*.zip
artifacts/Server-*.msi
artifacts/Server-*-checksums.txt
artifacts/ExecuteR-Agent-*.zip
artifacts/ExecuteR-Agent-*.msi
artifacts/ExecuteR-Agent-*-checksums.txt
artifacts/ExecuteR-Server-*.zip
artifacts/ExecuteR-Server-*.msi
artifacts/ExecuteR-Server-*-checksums.txt
retention-days: 7
images:
+6 -1
View File
@@ -11,7 +11,12 @@
<Version>$(UnifiedVersion)</Version>
<AssemblyVersion>$(UnifiedVersion)</AssemblyVersion>
<FileVersion>$(UnifiedVersion)</FileVersion>
<InformationalVersion>$(UnifiedVersion)</InformationalVersion>
<!-- ProductVersion shown in file properties: date version-shortcommit.
Packaging passes -p:GitCommitShort; plain local builds omit it. -->
<InformationalVersion Condition="'$(GitCommitShort)' != ''">$(UnifiedVersion)-$(GitCommitShort)</InformationalVersion>
<InformationalVersion Condition="'$(GitCommitShort)' == ''">$(UnifiedVersion)</InformationalVersion>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Company>ExecuteR</Company>
</PropertyGroup>
<PropertyGroup>
+21 -23
View File
@@ -11,8 +11,8 @@ updates with **no SignalR, SSE, or polling**.
(x64 + arm64, .NET 10), running as a Windows service / systemd unit /
launchd daemon. Deterministic hardware identity, secure one-time bootstrap,
hardware inventory, in-process PowerShell (System.Management.Automation)
plus PowerShell 5 and Bash engines, ConPTY remote shell (Windows),
presigned-URL file delivery.
plus PowerShell 5 and Bash engines, interactive remote shell (ConPTY on
Windows, forkpty on Linux/macOS), presigned-URL file delivery.
- **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC
auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live
event relay.
@@ -327,7 +327,8 @@ docker compose up -d --build
For a quick spin-up without containers, one self-contained `ExecuteR-Server`
binary serves the WebUI (static SPA), the API, the `/messaging/*` WebSocket
relay, and supervises a `nats-server` sidecar. CI publishes
`Server-<version>-win-x64.zip`, `…-linux-x64.zip` **and `Server-<version>.msi`**
`ExecuteR-Server-<version>-win-x64.zip`, `…-linux-x64.zip` **and
`ExecuteR-Server-<version>.msi`**
(build locally with `./scripts/Package-Server.ps1`):
```text
@@ -399,26 +400,21 @@ packages — lives inside its own directory, so instances never share state.
## Networking and TLS
ExecuteR serves **plain HTTP only — SSL/TLS termination is not supported in
the service itself and will not be added**. Terminating TLS inside every
application is yesterday's pattern; the state of the art is a dedicated edge
appliance or service that terminates TLS once, renews certificates
automatically (ACME/Let's Encrypt) and gives you layer-7 visibility — access
logs, request metrics, rate limiting, WAF hooks — for everything behind it:
ExecuteR encrypts its own listener **by default** with a self-managed
certificate chain — see [Self-Signed TLS](#self-signed-tls-on-by-default)
below. Public TLS termination still belongs at a dedicated edge: it
terminates TLS once with real certificates, renews them automatically via
ACME, and gives you layer-7 visibility — access logs, request metrics, rate
limiting, WAF hooks — for everything behind it.
| Edge | Notes |
|------|-------|
| [Caddy](https://caddyserver.com) | Automatic HTTPS out of the box; single binary, runs fine on **Windows** or Linux |
| [nginx](https://nginx.org) + [Nginx UI](https://nginxui.com) | The classic; Nginx UI adds a web console with ACME renewal and also installs on **Windows** |
| [HAProxy](https://www.haproxy.org) | High-throughput L4/L7 balancing and fine-grained traffic policy |
| [Zoraxy](https://zoraxy.aroz.org) | All-in-one reverse proxy with a friendly UI |
The recommended edge is **[Nginx UI](https://nginxui.com)** — a web console
for nginx with ACME renewal built in, and it installs on **Windows** too.
Put any of these in front on `:443` and forward to ExecuteR over HTTP.
Because forwarded headers are trusted from private address space by default
(next section), this works with zero ExecuteR-side configuration — the edge
handles certificates and encryption, ExecuteR handles the rest. For the
standalone Windows server the shortest path is installing Caddy (or Nginx UI
if you want a console) on the same host and proxying `localhost:9080`.
Put it in front on `:443` and forward the routes below. Because forwarded
headers are trusted from private address space by default (next section),
this works with zero ExecuteR-side configuration. For the standalone
Windows server the shortest path is installing Nginx UI on the same host
and proxying `localhost:9080`.
### Self-Signed TLS (on by default)
@@ -535,7 +531,9 @@ instead of the registry, credentials under `/var/lib/executer` (mode 600).
On startup the agent idempotently installs PowerShell 7 when missing (Homebrew
on macOS, the official install script on Linux) — scripts run via the embedded
PowerShell SDK either way, so this only matters for operator convenience.
Remote shell is Windows-only for now.
Remote shell works on every platform — ConPTY on Windows, a forkpty-backed
PTY (with a real controlling terminal, so job control and Ctrl-C behave) on
Linux and macOS.
---
@@ -1050,7 +1048,7 @@ unchanged build is skipped (the object key is content-addressed by hash).
For a local build without CI:
```powershell
./scripts/Package-Agent.ps1 # writes artifacts/Agent-<version>.msi
./scripts/Package-Agent.ps1 # writes artifacts/ExecuteR-Agent-<version>.msi
# then mount that directory at /data/agent, or set AGENT_PACKAGE_PATH
```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 195 KiB

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 KiB

After

Width:  |  Height:  |  Size: 206 KiB

+9 -4
View File
@@ -47,10 +47,15 @@ foreach ($rid in $Runtimes) {
-p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true `
-p:EnableCompressionInSingleFile=true `
-p:DebugType=None `
"-p:UnifiedVersion=$Version" `
"-p:GitCommitShort=$(git -C $repoRoot rev-parse --short HEAD 2>$null)" `
-o $ridPublishDir
if ($LASTEXITCODE -ne 0) { throw "Agent publish for $rid failed ($LASTEXITCODE)." }
# Shipping bundles carry no debug symbols.
Get-ChildItem $ridPublishDir -Filter '*.pdb' -Recurse | Remove-Item -Force
# A recognizable binary name on unix; the MSI harvest expects Agent.exe.
if ($rid -notlike 'win-*') {
Rename-Item (Join-Path $ridPublishDir 'Agent') 'executer-agent'
@@ -58,7 +63,7 @@ foreach ($rid in $Runtimes) {
Copy-Item $modulesStage (Join-Path $ridPublishDir 'Modules') -Recurse
$zipPath = Join-Path $artifacts "Agent-$Version-$rid.zip"
$zipPath = Join-Path $artifacts "ExecuteR-Agent-$Version-$rid.zip"
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Compress-Archive -Path (Join-Path $ridPublishDir '*') -DestinationPath $zipPath
Write-Host "Created $zipPath"
@@ -85,15 +90,15 @@ if (-not $SkipMsi -and (Test-Path $wixProject) -and (Test-Path $publishDir)) {
$msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer/bin/Release') -Filter '*.msi' -Recurse |
Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
if ($msi) {
$msiTarget = Join-Path $artifacts "Agent-$Version.msi"
$msiTarget = Join-Path $artifacts "ExecuteR-Agent-$Version.msi"
Copy-Item $msi.FullName $msiTarget -Force
Write-Host "Created $msiTarget"
}
}
# Checksums for release attachment.
$checksums = Join-Path $artifacts "Agent-$Version-checksums.txt"
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Agent-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
$checksums = Join-Path $artifacts "ExecuteR-Agent-$Version-checksums.txt"
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "ExecuteR-Agent-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
"{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name
} | Set-Content $checksums -Encoding utf8NoBOM
Write-Host "Created $checksums"
+14 -8
View File
@@ -59,10 +59,16 @@ foreach ($rid in $Runtimes) {
dotnet publish (Join-Path $repoRoot 'src/Backend/Backend.csproj') `
-c Release -r $rid --self-contained `
-p:PublishSingleFile=true `
-p:DebugType=None `
-p:UnifiedVersion=$Version `
"-p:GitCommitShort=$(git -C $repoRoot rev-parse --short HEAD 2>$null)" `
-o $publishDir
if ($LASTEXITCODE -ne 0) { throw "dotnet publish for $rid failed ($LASTEXITCODE)." }
# Shipping bundles carry no debug symbols or build-time asset manifests.
Get-ChildItem $publishDir -Filter '*.pdb' -Recurse | Remove-Item -Force
Remove-Item (Join-Path $publishDir 'Backend.staticwebassets.endpoints.json') -ErrorAction SilentlyContinue
# Single-file apphosts tolerate renames; ship a recognizable binary name.
if ($rid -like 'win-*') {
Rename-Item (Join-Path $publishDir 'Backend.exe') 'ExecuteR-Server.exe'
@@ -77,13 +83,13 @@ foreach ($rid in $Runtimes) {
# ── Bundle the agent installers so URL install works out of the box ─────
$agentStage = Join-Path $publishDir 'agent-package'
New-Item -ItemType Directory -Force $agentStage | Out-Null
$agentMsi = Join-Path $artifacts "Agent-$Version.msi"
$agentZip = Join-Path $artifacts "Agent-$Version-win-x64.zip"
$agentMsi = Join-Path $artifacts "ExecuteR-Agent-$Version.msi"
$agentZip = Join-Path $artifacts "ExecuteR-Agent-$Version-win-x64.zip"
$staged = $false
if (Test-Path $agentMsi) { Copy-Item $agentMsi (Join-Path $agentStage 'Agent.msi'); $staged = $true }
if (Test-Path $agentZip) { Copy-Item $agentZip (Join-Path $agentStage 'Agent.zip'); $staged = $true }
foreach ($unixRid in 'linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64') {
$unixZip = Join-Path $artifacts "Agent-$Version-$unixRid.zip"
$unixZip = Join-Path $artifacts "ExecuteR-Agent-$Version-$unixRid.zip"
if (Test-Path $unixZip) { Copy-Item $unixZip (Join-Path $agentStage "Agent-$unixRid.zip"); $staged = $true }
}
if ($staged) {
@@ -167,7 +173,7 @@ TRUSTED_HOSTS, TRUST_PROXY=0 to disable.
"@
# ── Zip it ───────────────────────────────────────────────────────────────
$zipPath = Join-Path $artifacts "Server-$Version-$rid.zip"
$zipPath = Join-Path $artifacts "ExecuteR-Server-$Version-$rid.zip"
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Compress-Archive -Path (Join-Path $publishDir '*') -DestinationPath $zipPath
Write-Host "Created $zipPath"
@@ -194,17 +200,17 @@ if (-not $SkipMsi -and (Test-Path $serverWix) -and (Test-Path $winPublish)) {
$msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer.Server/bin/Release') -Filter '*.msi' -Recurse |
Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
if ($msi) {
$msiTarget = Join-Path $artifacts "Server-$Version.msi"
$msiTarget = Join-Path $artifacts "ExecuteR-Server-$Version.msi"
Copy-Item $msi.FullName $msiTarget -Force
Write-Host "Created $msiTarget"
}
}
# Checksums for release attachment.
$checksums = Join-Path $artifacts "Server-$Version-checksums.txt"
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Server-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
$checksums = Join-Path $artifacts "ExecuteR-Server-$Version-checksums.txt"
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "ExecuteR-Server-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
"{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name
} | Set-Content $checksums -Encoding utf8NoBOM
Write-Host "Created $checksums"
Get-ChildItem $artifacts -Filter "Server-$Version-*.zip" | Select-Object Name, Length
Get-ChildItem $artifacts -Filter "ExecuteR-Server-$Version-*.zip" | Select-Object Name, Length
+2 -2
View File
@@ -53,9 +53,9 @@ catch {
$artifacts = Join-Path $repoRoot 'artifacts'
$assets = Get-ChildItem $artifacts -File |
Where-Object { $_.Name -like "Agent-$Version*" -or $_.Name -like "Server-$Version*" }
Where-Object { $_.Name -like "ExecuteR-Agent-$Version*" -or $_.Name -like "ExecuteR-Server-$Version*" }
if (-not $assets) {
throw "No artifacts matching Agent-$Version* or Server-$Version* under $artifacts."
throw "No artifacts matching ExecuteR-Agent-$Version* or ExecuteR-Server-$Version* under $artifacts."
}
foreach ($asset in $assets) {
+3 -1
View File
@@ -4,10 +4,12 @@
<OutputType>Exe</OutputType>
<!-- net10.0-windows: full agent (WMI inventory, ConPTY shell, DPAPI,
Windows service). net10.0: linux/macOS agent (file config, portable
inventory, systemd/launchd; remote shell unsupported). -->
inventory, systemd/launchd, forkpty remote shell). -->
<TargetFrameworks>net10.0-windows;net10.0</TargetFrameworks>
<RootNamespace>Agent</RootNamespace>
<AssemblyName>Agent</AssemblyName>
<Product>ExecuteR Agent</Product>
<AssemblyTitle>ExecuteR Agent</AssemblyTitle>
<RuntimeIdentifiers>win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<!-- Required by the LibraryImport interop source generator. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+1 -1
View File
@@ -37,7 +37,7 @@ public static class AgentHost
var logSettings = LogSettings.FromConfiguration(
builder.Configuration,
LogDefaults.Agent,
defaultDirectory: Path.Combine(Branding.AgentProgramDataDirectory, "logs")) with
defaultDirectory: Path.Combine(AppContext.BaseDirectory, "Logs")) with
{
// The agent's level comes from its own precedence chain
// (GPO > registry > default), not from the environment.
+9 -3
View File
@@ -7,9 +7,9 @@ namespace Agent.Shell;
/// <summary>
/// A live ConPTY-backed shell process. Terminal output is delivered via
/// <see cref="OutputReceived"/>; input is written with <see cref="Write"/>.
/// <see cref="OutputReceived"/>; input is written with <see cref="WriteAsync"/>.
/// </summary>
public sealed class ConPtySession : IDisposable
public sealed class ConPtySession : IPtySession
{
private IntPtr pseudoConsole = IntPtr.Zero;
private IntPtr attributeList = IntPtr.Zero;
@@ -28,8 +28,14 @@ public sealed class ConPtySession : IDisposable
/// <summary>Raised when the shell process exits.</summary>
public event Action? Exited;
public void Start(string commandLine, int cols, int rows)
public void Start(string fileName, string[] args, int cols, int rows)
{
// CreateProcessW takes a single command line: quote the executable and
// append the arguments verbatim (our args carry no embedded spaces).
var commandLine = args.Length == 0
? $"\"{fileName}\""
: $"\"{fileName}\" {string.Join(' ', args)}";
// Two pipes: one the PTY reads input from, one it writes output to.
if (!CreatePipe(out var inputRead, out var inputWrite, IntPtr.Zero, 0))
{
+22
View File
@@ -0,0 +1,22 @@
namespace Agent.Shell;
/// <summary>
/// A live pseudo-terminal-backed shell process. Windows uses ConPTY
/// (<see cref="ConPtySession"/>); Linux/macOS use forkpty
/// (<c>UnixPtySession</c>). Output arrives via <see cref="OutputReceived"/>;
/// input is written with <see cref="WriteAsync"/>.
/// </summary>
internal interface IPtySession : IDisposable
{
/// <summary>Raised with raw terminal output bytes as they arrive.</summary>
event Action<ReadOnlyMemory<byte>>? OutputReceived;
/// <summary>Raised when the shell process exits.</summary>
event Action? Exited;
void Start(string fileName, string[] args, int cols, int rows);
Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken);
void Resize(int cols, int rows);
}
+3 -22
View File
@@ -10,7 +10,8 @@ namespace Agent.Shell;
/// <summary>
/// Subscribes to Core NATS shell commands (open/input/resize/close) and drives
/// the <see cref="ShellManager"/>. Shell traffic stays on Core NATS — never
/// JetStream. Honors the AllowRemoteShell policy.
/// JetStream. Honors the AllowRemoteShell policy. The PTY backend is
/// ConPTY on Windows and forkpty on Linux/macOS.
/// </summary>
public sealed class ShellCommandListener(
NatsConnection connection,
@@ -18,21 +19,10 @@ public sealed class ShellCommandListener(
AgentConfiguration configuration,
ILogger logger) : IDisposable
{
#if WINDOWS_AGENT
private readonly ShellManager manager = new(publisher, logger);
#endif
public async Task RunAsync(CancellationToken cancellationToken)
{
#if !WINDOWS_AGENT
// The interactive shell is ConPTY-based; unsupported off Windows.
logger.LogInformation("Remote shell is not supported on this platform; not listening for shell commands");
_ = connection;
_ = publisher;
_ = configuration;
await Task.CompletedTask;
return;
#else
if (!configuration.AllowRemoteShell.Value)
{
logger.LogInformation("Remote shell disabled by policy; not listening for shell commands");
@@ -58,10 +48,8 @@ public sealed class ShellCommandListener(
logger.LogWarning(ex, "Failed to handle shell command on {Subject}", msg.Subject);
}
}
#endif
}
#if WINDOWS_AGENT
private async Task HandleAsync(MessageEnvelope? envelope, CancellationToken cancellationToken)
{
if (envelope is null)
@@ -109,12 +97,5 @@ public sealed class ShellCommandListener(
}
}
#endif
public void Dispose()
{
#if WINDOWS_AGENT
manager.Dispose();
#endif
}
public void Dispose() => manager.Dispose();
}
+40 -13
View File
@@ -1,4 +1,3 @@
#if WINDOWS_AGENT
using Agent.Messaging;
using Microsoft.Extensions.Logging;
using Shared.Contracts.Messages;
@@ -9,9 +8,10 @@ using Shared.Infrastructure.Nats;
namespace Agent.Shell;
/// <summary>
/// Manages interactive ConPTY shell sessions for one agent. MVP allows a
/// single active session per device; opening a new one closes the previous.
/// Output is published as base64 over Core NATS with a monotonic sequence.
/// Manages interactive PTY shell sessions for one agent — ConPTY on Windows,
/// forkpty on Linux/macOS. A single active session per device; opening a new
/// one closes the previous. Output is published as base64 over Core NATS with
/// a monotonic sequence.
/// </summary>
public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDisposable
{
@@ -21,7 +21,7 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
private sealed class ActiveShell
{
public required Guid SessionId { get; init; }
public required ConPtySession Pty { get; init; }
public required IPtySession Pty { get; init; }
public required Timer IdleTimer { get; init; }
public required Timer MaxLifetimeTimer { get; init; }
public long Sequence;
@@ -32,8 +32,8 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
{
CloseCurrent("superseded by new session");
var shell = ResolveShellCommand();
var pty = new ConPtySession();
var (fileName, args) = ResolveShellCommand();
var pty = CreatePty();
Guid sessionId = command.SessionId;
var active = new ActiveShell
@@ -54,9 +54,9 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
try
{
pty.Start(shell, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
pty.Start(fileName, args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
PublishState(sessionId, ShellSessionState.Open, null);
logger.LogInformation("Shell session {SessionId} opened ({Shell})", sessionId, shell);
logger.LogInformation("Shell session {SessionId} opened ({Shell})", sessionId, fileName);
}
catch (Exception ex)
{
@@ -173,22 +173,49 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
_ = reason;
}
private static IPtySession CreatePty() =>
#if WINDOWS_AGENT
new ConPtySession();
#else
new UnixPtySession();
#endif
#if WINDOWS_AGENT
/// <summary>Prefers PowerShell 7 (pwsh) when present, else Windows PowerShell.</summary>
private static string ResolveShellCommand()
private static (string FileName, string[] Args) ResolveShellCommand()
{
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var pwsh = Path.Combine(programFiles, "PowerShell", "7", "pwsh.exe");
if (File.Exists(pwsh))
{
return $"\"{pwsh}\" -NoLogo";
return (pwsh, ["-NoLogo"]);
}
var windowsPowerShell = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
"WindowsPowerShell", "v1.0", "powershell.exe");
return $"\"{windowsPowerShell}\" -NoLogo";
return (windowsPowerShell, ["-NoLogo"]);
}
#else
/// <summary>Honors $SHELL, then falls back to bash/zsh/sh.</summary>
private static (string FileName, string[] Args) ResolveShellCommand()
{
var candidates = new[]
{
Environment.GetEnvironmentVariable("SHELL"),
"/bin/bash", "/bin/zsh", "/bin/sh",
};
foreach (var candidate in candidates)
{
if (!string.IsNullOrEmpty(candidate) && File.Exists(candidate))
{
return (candidate, []);
}
}
return ("/bin/sh", []);
}
#endif
public void Dispose() => CloseCurrent("agent shutting down");
}
#endif
+329
View File
@@ -0,0 +1,329 @@
#if !WINDOWS_AGENT
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Agent.Shell;
/// <summary>
/// A live forkpty-backed shell on Linux/macOS. forkpty performs
/// openpty + fork + setsid + TIOCSCTTY + dup2 in one native call, so the
/// child gets a proper controlling terminal (job control, Ctrl-C, and TTY
/// detection all work). Terminal output is delivered via
/// <see cref="OutputReceived"/>; input is written with
/// <see cref="WriteAsync"/>.
/// </summary>
internal sealed class UnixPtySession : IPtySession
{
private int masterFd = -1;
private int childPid = -1;
private FileStream? io;
private readonly CancellationTokenSource lifetime = new();
private bool disposed;
public event Action<ReadOnlyMemory<byte>>? OutputReceived;
public event Action? Exited;
public void Start(string fileName, string[] args, int cols, int rows)
{
// Everything the forked child touches must be prepared HERE: after
// fork the child has a single thread and any managed allocation,
// JIT or lock acquisition can deadlock. The child therefore only
// calls execve/_exit, both passed pre-marshaled pointers.
var argv = BuildStringArray(fileName, args);
var envp = BuildEnvironment();
var pathPtr = Marshal.StringToHGlobalAnsi(fileName);
var winPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WinSize>());
Marshal.StructureToPtr(
new WinSize
{
ws_row = (ushort)Math.Clamp(rows, 1, ushort.MaxValue),
ws_col = (ushort)Math.Clamp(cols, 1, ushort.MaxValue),
},
winPtr, false);
var masterPtr = Marshal.AllocHGlobal(sizeof(int));
// Pre-JIT the child's only calls so no compilation happens post-fork.
TryPrepare(nameof(Native.execve));
TryPrepare(nameof(Native._exit));
var pid = Native.forkpty(masterPtr, IntPtr.Zero, IntPtr.Zero, winPtr);
if (pid == 0)
{
// CHILD — exec only, no managed work.
Native.execve(pathPtr, argv, envp);
Native._exit(127);
return;
}
try
{
if (pid < 0)
{
throw new InvalidOperationException(
$"forkpty failed (errno {Marshal.GetLastPInvokeError()}).");
}
childPid = pid;
masterFd = Marshal.ReadInt32(masterPtr);
io = new FileStream(new SafeFileHandle((IntPtr)masterFd, ownsHandle: true), FileAccess.ReadWrite);
_ = Task.Run(PumpOutputAsync);
_ = Task.Run(WatchProcessAsync);
}
finally
{
FreeStringArray(argv);
FreeStringArray(envp);
Marshal.FreeHGlobal(pathPtr);
Marshal.FreeHGlobal(winPtr);
Marshal.FreeHGlobal(masterPtr);
}
}
public async Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
if (io is null)
{
return;
}
await io.WriteAsync(data, cancellationToken);
await io.FlushAsync(cancellationToken);
}
public void Resize(int cols, int rows)
{
if (masterFd < 0)
{
return;
}
var win = new WinSize
{
ws_row = (ushort)Math.Clamp(rows, 1, ushort.MaxValue),
ws_col = (ushort)Math.Clamp(cols, 1, ushort.MaxValue),
};
_ = Native.ioctl(masterFd, Native.TIOCSWINSZ, ref win);
}
private async Task PumpOutputAsync()
{
var buffer = new byte[4096];
try
{
while (!lifetime.IsCancellationRequested)
{
var read = await io!.ReadAsync(buffer, lifetime.Token);
if (read == 0)
{
break;
}
OutputReceived?.Invoke(buffer.AsMemory(0, read).ToArray());
}
}
catch (Exception)
{
// EIO on the master when the slave closes (child exited), or the
// stream was disposed on shutdown.
}
}
private async Task WatchProcessAsync()
{
try
{
while (!lifetime.IsCancellationRequested)
{
if (Native.waitpid(childPid, out _, Native.WNOHANG) == childPid)
{
break;
}
await Task.Delay(250, lifetime.Token);
}
}
catch (OperationCanceledException)
{
return;
}
Exited?.Invoke();
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
lifetime.Cancel();
// Closing the master hangs up the slave (SIGHUP → the shell exits);
// send SIGTERM as well in case it ignores the hangup, then reap.
if (childPid > 0)
{
_ = Native.kill(childPid, Native.SIGTERM);
}
try
{
io?.Dispose();
}
catch (IOException)
{
// Master already closed.
}
if (childPid > 0)
{
_ = Native.waitpid(childPid, out _, 0);
}
lifetime.Dispose();
}
private static void TryPrepare(string method)
{
try
{
RuntimeHelpers.PrepareMethod(typeof(Native).GetMethod(method)!.MethodHandle);
}
catch (Exception)
{
// Best effort; the signatures are fully blittable so the stubs
// are trivial even if preparation is skipped.
}
}
/// <summary>Null-terminated array of ANSI char* : { argv0, args..., NULL }.</summary>
private static IntPtr BuildStringArray(string first, string[] rest)
{
var items = new List<string> { first };
items.AddRange(rest);
return Allocate(items);
}
private static IntPtr BuildEnvironment()
{
var items = new List<string>();
var hasTerm = false;
foreach (System.Collections.DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
var key = (string)entry.Key;
items.Add($"{key}={entry.Value}");
if (string.Equals(key, "TERM", StringComparison.Ordinal))
{
hasTerm = true;
}
}
if (!hasTerm)
{
items.Add("TERM=xterm-256color");
}
return Allocate(items);
}
private static IntPtr Allocate(List<string> items)
{
var array = Marshal.AllocHGlobal(IntPtr.Size * (items.Count + 1));
for (var i = 0; i < items.Count; i++)
{
Marshal.WriteIntPtr(array, i * IntPtr.Size, Marshal.StringToHGlobalAnsi(items[i]));
}
Marshal.WriteIntPtr(array, items.Count * IntPtr.Size, IntPtr.Zero);
return array;
}
private static void FreeStringArray(IntPtr array)
{
if (array == IntPtr.Zero)
{
return;
}
for (var i = 0; ; i++)
{
var ptr = Marshal.ReadIntPtr(array, i * IntPtr.Size);
if (ptr == IntPtr.Zero)
{
break;
}
Marshal.FreeHGlobal(ptr);
}
Marshal.FreeHGlobal(array);
}
[StructLayout(LayoutKind.Sequential)]
private struct WinSize
{
public ushort ws_row;
public ushort ws_col;
public ushort ws_xpixel;
public ushort ws_ypixel;
}
private static class Native
{
// forkpty lives in libutil on Linux and libSystem (libc) on macOS.
private const string PtyLib = "executer-pty";
public const int WNOHANG = 1;
public const int SIGTERM = 15;
// TIOCSWINSZ differs per platform (_IOW('t', 103, struct winsize)).
public static readonly nuint TIOCSWINSZ =
OperatingSystem.IsMacOS() ? 0x80087467u : 0x5414u;
static Native()
{
NativeLibrary.SetDllImportResolver(typeof(Native).Assembly, (name, _, _) =>
{
if (name != PtyLib)
{
return IntPtr.Zero;
}
foreach (var candidate in OperatingSystem.IsMacOS()
? ["libSystem.dylib", "libc"]
: new[] { "libutil.so.1", "libutil.so", "libc" })
{
if (NativeLibrary.TryLoad(candidate, out var handle))
{
return handle;
}
}
return IntPtr.Zero;
});
}
[DllImport(PtyLib, SetLastError = true)]
public static extern int forkpty(IntPtr amaster, IntPtr name, IntPtr termp, IntPtr winp);
[DllImport("libc", SetLastError = true)]
public static extern int execve(IntPtr path, IntPtr argv, IntPtr envp);
[DllImport("libc", EntryPoint = "_exit")]
public static extern void _exit(int status);
[DllImport("libc", SetLastError = true)]
public static extern int ioctl(int fd, nuint request, ref WinSize winsize);
[DllImport("libc", SetLastError = true)]
public static extern int waitpid(int pid, out int status, int options);
[DllImport("libc", SetLastError = true)]
public static extern int kill(int pid, int sig);
}
}
#endif
+14 -4
View File
@@ -24,9 +24,19 @@ public static class BootstrapTokenEndpoints
HttpContext context,
CancellationToken cancellationToken)
{
var lifetime = request?.ValidMinutes is > 0
? TimeSpan.FromMinutes(request.ValidMinutes.Value)
: ProtocolDefaults.BootstrapTokenDefaultLifetime;
// 0 disables expiry entirely (pipelines and pre-staged installers);
// absent keeps the 24-hour default. Revocation always applies.
if (request?.ValidMinutes is < 0)
{
return Results.BadRequest(new { error = "validMinutes must be 0 (no expiry) or positive." });
}
var expiresUtc = request?.ValidMinutes switch
{
0 => DateTimeOffset.MaxValue,
> 0 => DateTimeOffset.UtcNow + TimeSpan.FromMinutes(request.ValidMinutes.Value),
_ => DateTimeOffset.UtcNow + ProtocolDefaults.BootstrapTokenDefaultLifetime,
};
// 0 means unlimited uses (expiry and revocation still apply).
if (request?.MaxUses is < 0 or > 9999)
@@ -45,7 +55,7 @@ public static class BootstrapTokenEndpoints
Id = Guid.NewGuid(),
TokenHash = TokenHashing.Sha256Hex(token),
CreatedUtc = DateTimeOffset.UtcNow,
ExpiresUtc = DateTimeOffset.UtcNow + lifetime,
ExpiresUtc = expiresUtc,
MaxUses = maxUses,
Note = request?.Note,
CreatedBy = actor,
+17 -3
View File
@@ -41,11 +41,15 @@ public static class AuthEndpoints
app.MapGet(ApiRoutes.AuthOidcCallback, () => Results.Redirect("/")).AllowAnonymous();
}
/// <summary>The built-in default; signing in with it forces a reset.</summary>
private const string DefaultAdminPassword = "admin";
private static async Task<IResult> LoginAsync(
LoginRequest request,
UserService users,
RoleCache roles,
AuditService audit,
Backend.Data.AppDbContext db,
HttpContext context,
CancellationToken cancellationToken)
{
@@ -59,9 +63,11 @@ public static class AuthEndpoints
return Results.Unauthorized();
}
// Valid credentials, but a defaulted password: no session until a real
// one is set (POST /api/auth/change-password completes the sign-in).
if (user.MustChangePassword)
// The reset presents only while the password is still the built-in
// default — a custom password chosen at install signs straight in,
// whatever the flag says (POST /api/auth/change-password completes
// the sign-in when the reset does apply).
if (user.MustChangePassword && request.Password == DefaultAdminPassword)
{
await audit.LogAsync(AuditCategories.Auth, "login-password-change-required",
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
@@ -70,6 +76,14 @@ public static class AuthEndpoints
MustChangePassword: true));
}
if (user.MustChangePassword)
{
// Stale flag with a non-default password: clear it.
var tracked = await db.Users.SingleAsync(u => u.Id == user.Id, cancellationToken);
tracked.MustChangePassword = false;
await db.SaveChangesAsync(cancellationToken);
}
var session = await IssueSessionAsync(user, roles, context, cancellationToken);
await audit.LogAsync(AuditCategories.Auth, "login-succeeded",
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
+2
View File
@@ -4,6 +4,8 @@
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Backend</RootNamespace>
<UserSecretsId>backend-dev-secrets</UserSecretsId>
<Product>ExecuteR Server</Product>
<AssemblyTitle>ExecuteR Server</AssemblyTitle>
<!-- Exe icon for the standalone server binary (Windows publishes). -->
<!-- Conditional: the docker build context has no assets directory, and
linux images need no exe icon anyway. -->
+84 -26
View File
@@ -24,6 +24,9 @@ public static class DevSeeder
("PC-ENG-014", "Dell Inc.", "OptiPlex 7090", "Windows 11 Pro", TimeSpan.FromSeconds(12), new[] { "10.20.4.14" }, new[] { "engineering", "workstation" }),
("PC-FIN-003", "LENOVO", "ThinkCentre M90q", "Windows 11 Enterprise", TimeSpan.FromMinutes(3), new[] { "10.20.6.3" }, new[] { "finance", "workstation" }),
("LAB-VM-27", "Microsoft Corporation", "Virtual Machine", "Windows Server 2022", TimeSpan.FromMinutes(20), new[] { "10.30.9.27" }, new[] { "lab", "server" }),
("web-prod-01", "QEMU", "Standard PC (Q35)", "Ubuntu 22.04.4 LTS", TimeSpan.FromSeconds(28), new[] { "10.40.1.11" }, new[] { "production", "server" }),
("build-arm-02", "Raspberry Pi Foundation", "Raspberry Pi 5", "Debian GNU/Linux 12", TimeSpan.FromMinutes(6), new[] { "10.40.2.2" }, new[] { "ci", "server" }),
("MBP-DESIGN-9", "Apple Inc.", "MacBookPro18,3", "macOS 14.5 Sonoma", TimeSpan.FromMinutes(1), new[] { "10.20.8.9" }, new[] { "design", "workstation" }),
};
var i = 0;
@@ -127,46 +130,101 @@ public static class DevSeeder
await db.SaveChangesAsync(cancellationToken);
}
var firstDevice = db.Devices.First();
var script = db.Scripts.FirstOrDefault();
if (script is not null)
// A few scripts across engines so the dashboard's engine mix, top
// scripts and drill-ins have something to show.
var scripts = new List<ScriptEntity>();
var scriptSeeds = new[]
{
var jobs = new[]
("Collect event logs", "PowerShell"),
("Patch & reboot", "PowerShell"),
("Rotate log files", "Bash"),
("Inventory installed apps", "WindowsPowerShell"),
("Restart web service", "Bash"),
};
foreach (var (name, language) in scriptSeeds)
{
if (db.Scripts.Any(s => s.Name == name))
{
(JobState.Succeeded, now.AddMinutes(-8), now.AddMinutes(-7), 0),
(JobState.Running, now.AddMinutes(-1), (DateTimeOffset?)null, (int?)null),
(JobState.Failed, now.AddHours(-2), now.AddHours(-2).AddSeconds(4), 1),
};
continue;
}
foreach (var (state, started, completed, exit) in jobs)
var script = new ScriptEntity
{
var job = new JobEntity
Id = Guid.NewGuid(),
Name = name,
Description = "Seeded sample script.",
Language = language,
Content = language == "Bash" ? "#!/usr/bin/env bash\necho ok\n" : "Write-Output 'ok'\n",
CreatedUtc = now.AddDays(-20),
UpdatedUtc = now.AddDays(-20),
CreatedBy = "seed",
UpdatedBy = "seed",
};
db.Scripts.Add(script);
scripts.Add(script);
}
await db.SaveChangesAsync(cancellationToken);
scripts = db.Scripts.ToList();
var allDevices = db.Devices.ToList();
if (scripts.Count > 0 && allDevices.Count > 0)
{
// Deterministic spread over the last 14 days: mostly successes,
// a realistic minority of failures and a couple in flight.
var rng = new Random(1742);
var exitPool = new[] { 0, 0, 0, 0, 0, 1, 2, 3, 1 };
for (var n = 0; n < 90; n++)
{
var device = allDevices[rng.Next(allDevices.Count)];
var script = scripts[rng.Next(scripts.Count)];
var created = now.AddDays(-rng.Next(0, 14))
.AddHours(-rng.Next(0, 24))
.AddMinutes(-rng.Next(0, 60));
var roll = rng.NextDouble();
JobState state;
int? exit;
if (roll < 0.72)
{
state = JobState.Succeeded;
exit = 0;
}
else if (roll < 0.9)
{
state = JobState.Failed;
exit = exitPool[rng.Next(exitPool.Length)] is var e && e == 0 ? 1 : e;
}
else if (roll < 0.96)
{
state = JobState.Running;
exit = null;
}
else
{
state = JobState.TimedOut;
exit = null;
}
DateTimeOffset? started = state == JobState.Queued ? null : created.AddSeconds(1);
DateTimeOffset? completed = state is JobState.Succeeded or JobState.Failed or JobState.TimedOut
? created.AddSeconds(rng.Next(2, 40))
: null;
db.Jobs.Add(new JobEntity
{
JobId = Guid.NewGuid(),
ClientId = firstDevice.ClientId,
ClientId = device.ClientId,
ScriptId = script.Id,
ScriptName = script.Name,
State = state,
CreatedUtc = started.AddSeconds(-1),
CreatedUtc = created,
StartedUtc = started,
CompletedUtc = completed,
ExitCode = exit,
RequestedBy = "admin",
OutputSummary = state == JobState.Failed ? "Access to the path is denied." : null,
};
db.Jobs.Add(job);
for (var s = 1; s <= 5; s++)
{
db.JobOutput.Add(new JobOutputEntity
{
JobId = job.JobId,
Sequence = s,
Stream = OutputStreamKind.Output,
TimestampUtc = started.AddSeconds(s),
Text = $"Completed step {s}",
});
}
});
}
await db.SaveChangesAsync(cancellationToken);
+1 -1
View File
@@ -160,7 +160,7 @@ public static class InstallEndpoints
{{(skipVerify ? PsSkipVerify : "")}}
$server = '{{baseUrl}}'
$token = '{{token}}'
$dest = Join-Path $env:ProgramFiles 'ExecuteR Agent'
$dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent'
$zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip')
try {
Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $zip -UseBasicParsing
+142
View File
@@ -0,0 +1,142 @@
using Backend.Auth;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Infrastructure.Constants;
using Shared.Infrastructure.Grouping;
namespace Backend.Jobs;
/// <summary>
/// The dashboard overview: one aggregate read across devices, jobs and
/// scripts. Everything is computed from stored rows — no new bookkeeping.
/// </summary>
public static class DashboardEndpoints
{
public static void Map(WebApplication app)
{
app.MapGet(ApiRoutes.Dashboard, GetAsync).RequirePermission(Permissions.DevicesView);
}
private static async Task<IResult> GetAsync(AppDbContext db, CancellationToken cancellationToken)
{
var now = DateTimeOffset.UtcNow;
var devices = await db.Devices.AsNoTracking()
.Select(d => new { d.LastSeenUtc, d.OsCaption })
.ToListAsync(cancellationToken);
var statuses = devices
.Select(d => ProtocolDefaults.CalculateStatus(d.LastSeenUtc, now))
.ToList();
var byPlatform = devices
.GroupBy(d => DeviceFieldBag.DerivePlatform(d.OsCaption) ?? "unknown")
.Select(g => new CountPoint(g.Key, g.Count()))
.OrderByDescending(p => p.Count)
.ToList();
// Bound the window so the dashboard stays quick on busy fleets.
var since = now.AddDays(-30);
var jobs = await db.Jobs.AsNoTracking()
.Where(j => j.CreatedUtc >= since)
.Select(j => new
{
j.JobId, j.ScriptId, j.ScriptName, j.ClientId, j.State,
j.ExitCode, j.CreatedUtc,
})
.ToListAsync(cancellationToken);
var succeeded = jobs.Count(j => j.State == JobState.Succeeded);
var failed = jobs.Count(j => j.State is JobState.Failed or JobState.TimedOut);
var inProgress = jobs.Count(j => j.State is JobState.Queued or JobState.Dispatched or JobState.Running);
var finished = succeeded + failed;
var byState = jobs
.GroupBy(j => j.State)
.Select(g => new CountPoint(g.Key.ToString(), g.Count()))
.OrderByDescending(p => p.Count)
.ToList();
var byExitCode = jobs
.Where(j => j.ExitCode is not null)
.GroupBy(j => j.ExitCode!.Value)
.Select(g => new CountPoint(g.Key == 0 ? "0 (ok)" : g.Key.ToString(), g.Count()))
.OrderByDescending(p => p.Count)
.Take(6)
.ToList();
// Engine mix: join each job's script to its language (deleted scripts
// fall into "Unknown").
var languages = await db.Scripts.AsNoTracking()
.Select(s => new { s.Id, s.Language })
.ToDictionaryAsync(s => s.Id, s => s.Language, cancellationToken);
var byEngine = jobs
.GroupBy(j => languages.GetValueOrDefault(j.ScriptId) is { Length: > 0 } lang ? lang : "Unknown")
.Select(g => new CountPoint(g.Key, g.Count()))
.OrderByDescending(p => p.Count)
.ToList();
var hostnames = await db.Devices.AsNoTracking()
.ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken);
var topTargets = jobs
.GroupBy(j => hostnames.GetValueOrDefault(j.ClientId, j.ClientId))
.Select(g => new CountPoint(g.Key, g.Count()))
.OrderByDescending(p => p.Count)
.Take(6)
.ToList();
var topScripts = jobs
.GroupBy(j => j.ScriptName)
.Select(g => new CountPoint(g.Key, g.Count()))
.OrderByDescending(p => p.Count)
.Take(6)
.ToList();
// 14-day timeline (oldest → newest) of succeeded / failed / other.
var timeline = new List<DayPoint>();
for (var day = 13; day >= 0; day--)
{
var date = now.AddDays(-day).Date;
var dayJobs = jobs.Where(j => j.CreatedUtc.UtcDateTime.Date == date).ToList();
timeline.Add(new DayPoint(
date.ToString("MMM d"),
dayJobs.Count(j => j.State == JobState.Succeeded),
dayJobs.Count(j => j.State is JobState.Failed or JobState.TimedOut),
dayJobs.Count(j => j.State is not (JobState.Succeeded or JobState.Failed or JobState.TimedOut))));
}
var recentIds = jobs
.OrderByDescending(j => j.CreatedUtc)
.Take(8)
.Select(j => j.JobId)
.ToList();
var recentRuns = await db.Jobs.AsNoTracking()
.Where(j => recentIds.Contains(j.JobId))
.OrderByDescending(j => j.CreatedUtc)
.Select(j => new JobDto(
j.JobId, j.ClientId, hostnames.GetValueOrDefault(j.ClientId), j.ScriptId, j.ScriptName,
j.State, j.CreatedUtc, j.StartedUtc, j.CompletedUtc, j.ExitCode, j.RequestedBy, j.OutputSummary))
.ToListAsync(cancellationToken);
return Results.Ok(new DashboardDto(
DevicesTotal: devices.Count,
DevicesOnline: statuses.Count(s => s == DeviceStatus.Online),
DevicesStale: statuses.Count(s => s == DeviceStatus.Stale),
DevicesOffline: statuses.Count(s => s == DeviceStatus.Offline),
DevicesByPlatform: byPlatform,
JobsTotal: jobs.Count,
JobsSucceeded: succeeded,
JobsFailed: failed,
JobsInProgress: inProgress,
SuccessRate: finished == 0 ? 0 : Math.Round(100.0 * succeeded / finished, 1),
JobsByState: byState,
JobsByExitCode: byExitCode,
JobsByEngine: byEngine,
TopTargets: topTargets,
TopScripts: topScripts,
Timeline: timeline,
RecentRuns: recentRuns));
}
}
+6 -1
View File
@@ -22,7 +22,7 @@ public static class JobEndpoints
}
private static async Task<IResult> ListAsync(
AppDbContext db, string? clientId, int? limit, CancellationToken cancellationToken)
AppDbContext db, string? clientId, Guid? scriptId, int? limit, CancellationToken cancellationToken)
{
var query = db.Jobs.AsNoTracking().OrderByDescending(j => j.CreatedUtc).AsQueryable();
if (!string.IsNullOrEmpty(clientId))
@@ -30,6 +30,11 @@ public static class JobEndpoints
query = query.Where(j => j.ClientId == clientId);
}
if (scriptId is { } sid)
{
query = query.Where(j => j.ScriptId == sid);
}
var jobs = await query.Take(Math.Clamp(limit ?? 100, 1, 500)).ToListAsync(cancellationToken);
var hostnames = await db.Devices.AsNoTracking()
.Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId))
+33 -1
View File
@@ -32,7 +32,8 @@ public sealed class JobRunner(
CommandDispatcher dispatcher,
BrowserEventBroadcaster broadcaster,
SecretsProviderService secretsService,
Backend.Files.S3PresignService s3)
Backend.Files.S3PresignService s3,
IConfiguration configuration)
{
/// <summary>
/// Composes the prelude, resolves secrets and presigns file bindings.
@@ -138,9 +139,40 @@ public sealed class JobRunner(
};
db.Jobs.Add(job);
await db.SaveChangesAsync(cancellationToken);
await PruneHistoryAsync(clientId, cancellationToken);
return job;
}
/// <summary>
/// Execution history retention: keeps the newest JOB_HISTORY_LIMIT jobs
/// per device (default 200, 0 disables pruning) and drops the stored
/// output of anything older.
/// </summary>
private async Task PruneHistoryAsync(string clientId, CancellationToken cancellationToken)
{
var limit = int.TryParse(configuration["JOB_HISTORY_LIMIT"], out var configured) && configured >= 0
? configured
: 200;
if (limit == 0)
{
return;
}
var doomed = await db.Jobs.AsNoTracking()
.Where(j => j.ClientId == clientId)
.OrderByDescending(j => j.CreatedUtc)
.Skip(limit)
.Select(j => j.JobId)
.ToListAsync(cancellationToken);
if (doomed.Count == 0)
{
return;
}
await db.JobOutput.Where(o => doomed.Contains(o.JobId)).ExecuteDeleteAsync(cancellationToken);
await db.Jobs.Where(j => doomed.Contains(j.JobId)).ExecuteDeleteAsync(cancellationToken);
}
/// <summary>Publishes the durable command and broadcasts the activity item.</summary>
public async Task<bool> DispatchAsync(
PreparedScript prepared,
+1
View File
@@ -387,6 +387,7 @@ DeviceEndpoints.Map(app);
ScriptEndpoints.Map(app);
FunctionEndpoints.Map(app);
JobEndpoints.Map(app);
DashboardEndpoints.Map(app);
ScheduleEndpoints.Map(app);
BootstrapTokenEndpoints.Map(app);
MessagingEndpoints.Map(app);
+6 -4
View File
@@ -113,7 +113,7 @@ public static class ServerCli
var secretsDir = Path.Combine(baseDir, "secrets", "nats");
var dataDir = Path.Combine(baseDir, "data");
Directory.CreateDirectory(natsDir);
Directory.CreateDirectory(dataDir);
Directory.CreateDirectory(Path.Combine(dataDir, "db"));
// The sidecar binary: packaged bundles ship it; a bare binary (MSI or
// direct download) fetches it here so setup works the same everywhere.
@@ -154,7 +154,9 @@ public static class ServerCli
http: 127.0.0.1:{{natsMonitorPort}}
jetstream {
store_dir: "../data/jetstream"
# nats-server appends "jetstream" itself: this lands in
# ../data/jetstream.
store_dir: "../data"
}
websocket {
@@ -180,9 +182,9 @@ public static class ServerCli
File.WriteAllText(appsettings, $$"""
{
"Urls": "http://{{bindAddress}}:{{httpPort}}",
"DATABASE_PATH": "{{Path.Combine(dataDir, "app.db").Replace('\\', '/')}}",
"DATABASE_PATH": "{{Path.Combine(dataDir, "db", "app.db").Replace('\\', '/')}}",
"DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}",
"LOG_PATH": "{{Path.Combine(dataDir, "logs").Replace('\\', '/')}}",
"LOG_PATH": "{{Path.Combine(baseDir, "logs").Replace('\\', '/')}}",
"AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}",
"NATS_URL": "nats://127.0.0.1:{{natsPort}}",
"NATS_SIDECAR": "1",
+23 -21
View File
@@ -73,7 +73,9 @@
Return="ignore" />
<StandardDirectory Id="ProgramFiles64Folder">
<Directory Id="INSTALLFOLDER" Name="ExecuteR Server" />
<Directory Id="ExecuteRFolder" Name="ExecuteR">
<Directory Id="INSTALLFOLDER" Name="Server" />
</Directory>
</StandardDirectory>
<!-- The whole packaged bundle: ExecuteR-Server.exe, wwwroot, the NATS
@@ -143,17 +145,17 @@
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
<Control Id="UserLabel" Type="Text" X="20" Y="60" Width="330" Height="12"
NoPrefix="yes" Text="Administrator &amp;username:" />
NoPrefix="yes" Text="Administrator username:" />
<Control Id="UserEdit" Type="Edit" X="20" Y="74" Width="330" Height="17"
Property="ADMINUSERNAME" />
<Control Id="PasswordLabel" Type="Text" X="20" Y="100" Width="330" Height="12"
NoPrefix="yes" Text="Administrator &amp;password:" />
NoPrefix="yes" Text="Administrator password:" />
<Control Id="PasswordEdit" Type="Edit" X="20" Y="114" Width="330" Height="17"
Property="ADMINPASSWORD" Password="yes" />
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="48" NoPrefix="yes"
Text="Defaults to admin / admin — change the password after the first sign-in. This account is only created on the very first install; upgrades keep the existing configuration. Silent installs set the same values with ADMINUSERNAME=... ADMINPASSWORD=... properties." />
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="60" NoPrefix="yes"
Text="Keeping the default (admin / admin) forces a password reset at first sign-in.&#13;&#10;&#13;&#10;Created on first install only; upgrades keep existing configuration.&#13;&#10;&#13;&#10;Silent: ADMINUSERNAME=... ADMINPASSWORD=..." />
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
@@ -178,32 +180,32 @@
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
<Control Id="BindLabel" Type="Text" X="20" Y="54" Width="330" Height="12" NoPrefix="yes"
Text="&amp;Bind address — 0.0.0.0 listens on every interface; 127.0.0.1 serves only a local reverse proxy:" />
Text="Bind address (0.0.0.0 = every interface; 127.0.0.1 = local proxy only):" />
<Control Id="BindEdit" Type="Edit" X="20" Y="67" Width="140" Height="16"
Property="BINDADDRESS" />
<Control Id="HttpLabel" Type="Text" X="20" Y="91" Width="330" Height="12" NoPrefix="yes"
Text="&amp;HTTP port — serves the UI, the API and enrolling agents:" />
Text="HTTP port (UI, API, agent enrollment):" />
<Control Id="HttpEdit" Type="Edit" X="20" Y="104" Width="70" Height="16"
Property="HTTPPORT" />
<Control Id="NatsLabel" Type="Text" X="20" Y="126" Width="330" Height="20" NoPrefix="yes"
Text="Internal messaging (NATS) ports — always bound to 127.0.0.1 and never exposed. Change them only if another application already uses one:" />
<Control Id="NatsCoreLabel" Type="Text" X="20" Y="147" Width="70" Height="10" NoPrefix="yes" Text="Core" />
<Control Id="NatsCoreEdit" Type="Edit" X="20" Y="158" Width="70" Height="16" Property="NATSPORT" />
<Control Id="NatsWsLabel" Type="Text" X="110" Y="147" Width="70" Height="10" NoPrefix="yes" Text="WebSocket" />
<Control Id="NatsWsEdit" Type="Edit" X="110" Y="158" Width="70" Height="16" Property="NATSWSPORT" />
<Control Id="NatsMonLabel" Type="Text" X="200" Y="147" Width="70" Height="10" NoPrefix="yes" Text="Monitor" />
<Control Id="NatsMonEdit" Type="Edit" X="200" Y="158" Width="70" Height="16" Property="NATSMONITORPORT" />
<Control Id="NatsLabel" Type="Text" X="20" Y="128" Width="330" Height="12" NoPrefix="yes"
Text="Internal NATS ports (loopback-only; change only on a conflict):" />
<Control Id="NatsCoreLabel" Type="Text" X="20" Y="143" Width="70" Height="10" NoPrefix="yes" Text="Core" />
<Control Id="NatsCoreEdit" Type="Edit" X="20" Y="154" Width="70" Height="16" Property="NATSPORT" />
<Control Id="NatsWsLabel" Type="Text" X="110" Y="143" Width="70" Height="10" NoPrefix="yes" Text="WebSocket" />
<Control Id="NatsWsEdit" Type="Edit" X="110" Y="154" Width="70" Height="16" Property="NATSWSPORT" />
<Control Id="NatsMonLabel" Type="Text" X="200" Y="143" Width="70" Height="10" NoPrefix="yes" Text="Monitor" />
<Control Id="NatsMonEdit" Type="Edit" X="200" Y="154" Width="70" Height="16" Property="NATSMONITORPORT" />
<Control Id="TlsCheck" Type="CheckBox" X="20" Y="178" Width="330" Height="12"
<Control Id="TlsCheck" Type="CheckBox" X="20" Y="176" Width="330" Height="12"
Property="ENABLETLS" CheckBoxValue="1"
Text="Enable Self-Signed TLS (encrypts this server's traffic; auto-renewed)" />
<Control Id="TlsNote" Type="Text" X="32" Y="191" Width="318" Height="24" NoPrefix="yes"
Text="Reverse proxies: skip TLS verification (still encrypted — the roots simply are not distributed), or import the root and intermediate to establish trust and re-import when they rotate at expiry. Follow your organization's security standards." />
Text="Enable Self-Signed TLS (auto-renewed)" />
<Control Id="TlsNote" Type="Text" X="32" Y="190" Width="318" Height="20" NoPrefix="yes"
Text="Reverse proxies: skip TLS verification (traffic stays encrypted), or import the root + intermediate and re-import when they rotate." />
<Control Id="Note" Type="Text" X="20" Y="217" Width="330" Height="16" NoPrefix="yes"
Text="Everything lands in appsettings.json next to the binary (restart the service to apply). Several instances on one machine: use the ZIP bundle instead." />
<Control Id="Note" Type="Text" X="20" Y="214" Width="330" Height="18" NoPrefix="yes"
Text="Settings persist in appsettings.json next to the binary.&#13;&#10;Multiple instances on one machine: use the ZIP bundle." />
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
+10 -8
View File
@@ -78,8 +78,10 @@
</Property>
<StandardDirectory Id="ProgramFiles64Folder">
<Directory Id="INSTALLFOLDER" Name="ExecuteR Agent">
<Directory Id="ModulesFolder" Name="Modules" />
<Directory Id="ExecuteRFolder" Name="ExecuteR">
<Directory Id="INSTALLFOLDER" Name="Agent">
<Directory Id="ModulesFolder" Name="Modules" />
</Directory>
</Directory>
</StandardDirectory>
@@ -207,22 +209,22 @@
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
<Control Id="ServerUrlLabel" Type="Text" X="20" Y="60" Width="330" Height="12"
NoPrefix="yes" Text="&amp;Server URL (for example https://control.example.com):" />
NoPrefix="yes" Text="Server URL (https://control.example.com):" />
<Control Id="ServerUrlEdit" Type="Edit" X="20" Y="74" Width="330" Height="17"
Property="SERVERURL" />
<Control Id="TokenLabel" Type="Text" X="20" Y="100" Width="330" Height="12"
NoPrefix="yes" Text="&amp;Bootstrap token (one-time enrollment secret):" />
NoPrefix="yes" Text="Bootstrap token (one-time enrollment secret):" />
<Control Id="TokenEdit" Type="Edit" X="20" Y="114" Width="330" Height="17"
Property="BOOTSTRAPTOKEN" Password="yes" />
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="48" NoPrefix="yes"
Text="Leave blank to keep values already configured on this machine (upgrades), or to configure later via registry or Group Policy. The service enrolls automatically at start once both values are present. Command-line properties (SERVERURL=… BOOTSTRAPTOKEN=…) set the same fields and are the way to install silently." />
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="44" NoPrefix="yes"
Text="Blank keeps values already configured (upgrades), or set later via registry / Group Policy. The service enrolls once both values are present.&#13;&#10;&#13;&#10;Silent: SERVERURL=... BOOTSTRAPTOKEN=..." />
<!-- Unchecked by default; prefilled from the registry on upgrades. -->
<Control Id="SkipTlsCheck" Type="CheckBox" X="20" Y="194" Width="330" Height="14"
<Control Id="SkipTlsCheck" Type="CheckBox" X="20" Y="192" Width="330" Height="14"
Property="SKIPTLSVERIFY" CheckBoxValue="1"
Text="Skip TLS certificate verification (self-signed server — traffic stays encrypted)" />
Text="Skip TLS verification (self-signed server; traffic stays encrypted)" />
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
+2
View File
@@ -63,6 +63,8 @@ public static class ApiRoutes
public const string Job = "/api/jobs/{jobId}";
public const string JobOutput = "/api/jobs/{jobId}/output";
public const string Dashboard = "/api/dashboard";
public const string Schedules = "/api/schedules";
public const string Schedule = "/api/schedules/{id}";
public const string SchedulePreview = "/api/schedules/preview";
+29
View File
@@ -185,6 +185,35 @@ public sealed record GroupRunDto(
IReadOnlyList<JobDto> Jobs,
IReadOnlyList<string> SkippedOrphaned);
/// <summary>A labeled count used by the dashboard charts.</summary>
public sealed record CountPoint(string Label, int Count);
/// <summary>One day of the execution timeline.</summary>
public sealed record DayPoint(string Date, int Succeeded, int Failed, int Other);
/// <summary>
/// Aggregated control-plane overview for the dashboard. Everything is derived
/// from the jobs, devices and scripts already stored — one read per load.
/// </summary>
public sealed record DashboardDto(
int DevicesTotal,
int DevicesOnline,
int DevicesStale,
int DevicesOffline,
IReadOnlyList<CountPoint> DevicesByPlatform,
int JobsTotal,
int JobsSucceeded,
int JobsFailed,
int JobsInProgress,
double SuccessRate,
IReadOnlyList<CountPoint> JobsByState,
IReadOnlyList<CountPoint> JobsByExitCode,
IReadOnlyList<CountPoint> JobsByEngine,
IReadOnlyList<CountPoint> TopTargets,
IReadOnlyList<CountPoint> TopScripts,
IReadOnlyList<DayPoint> Timeline,
IReadOnlyList<JobDto> RecentRuns);
/// <summary>
/// A reusable cadence object. Scripts honor a schedule through assignments —
/// the schedule itself carries no script or target.
+5 -1
View File
@@ -11,6 +11,7 @@ import type {
GroupRuleSet,
GroupRunDto,
JobDto,
DashboardDto,
JobOutputRecordDto,
AgentPackageStatusDto,
AuthConfigDto,
@@ -184,10 +185,13 @@ export const api = {
deleteFunction: (id: string) => request<void>(`/api/functions/${id}`, { method: 'DELETE' }),
// Jobs
jobs: (clientId?: string, limit?: number) => {
dashboard: () => request<DashboardDto>('/api/dashboard'),
jobs: (clientId?: string, limit?: number, scriptId?: string) => {
const params = new URLSearchParams();
if (clientId) params.set('clientId', clientId);
if (limit) params.set('limit', String(limit));
if (scriptId) params.set('scriptId', scriptId);
const qs = params.size > 0 ? `?${params}` : '';
return request<JobDto[]>(`/api/jobs${qs}`);
},
+32
View File
@@ -359,6 +359,38 @@ export interface SchedulePreviewDto {
nextRunsUtc: string[];
}
export interface CountPoint {
label: string;
count: number;
}
export interface DayPoint {
date: string;
succeeded: number;
failed: number;
other: number;
}
export interface DashboardDto {
devicesTotal: number;
devicesOnline: number;
devicesStale: number;
devicesOffline: number;
devicesByPlatform: CountPoint[];
jobsTotal: number;
jobsSucceeded: number;
jobsFailed: number;
jobsInProgress: number;
successRate: number;
jobsByState: CountPoint[];
jobsByExitCode: CountPoint[];
jobsByEngine: CountPoint[];
topTargets: CountPoint[];
topScripts: CountPoint[];
timeline: DayPoint[];
recentRuns: JobDto[];
}
export interface ServerInfoDto {
baseUrl: string;
fromEnvironment: boolean;
@@ -12,6 +12,7 @@
let scope = $state<Scope>('single');
let multiUses = $state(1);
let unlimited = $state(false);
let noExpiry = $state(false);
let token = $state('');
let tokenId = $state('');
let baseUrl = $state('');
@@ -58,7 +59,7 @@
}
const created = await api.createBootstrapToken({
validMinutes: 24 * 60,
validMinutes: scope === 'multi' && noExpiry ? 0 : 24 * 60,
maxUses: effectiveUses,
note:
scope === 'single'
@@ -88,6 +89,9 @@
function setScope(next: Scope) {
if (scope === next) return;
scope = next;
// A single device is a one-time enrollment — no-expiry is a
// multi-device convenience only.
if (scope === 'single') noExpiry = false;
limitsChanged();
}
@@ -181,6 +185,13 @@
</label>
</div>
{/if}
{#if scope === 'multi'}
<label class="radio">
<input type="checkbox" bind:checked={noExpiry} onchange={limitsChanged} />
No expiry
<span class="faint">(pipelines and pre-staged installers; revoke when done)</span>
</label>
{/if}
<label class="radio">
<input type="checkbox" bind:checked={skipTlsVerify} />
Skip TLS verification
@@ -198,8 +209,9 @@
</div>
<p class="muted small">
{#if busy}Updating the token…{:else}
{shellHint} The token expires in 24 hours; the agent downloads from this server,
installs as a {platform === 'windows' ? 'Windows service' : platform === 'linux' ? 'systemd unit' : 'launchd daemon'}
{shellHint} The token {noExpiry ? 'never expires' : 'expires in 24 hours'}; the agent
downloads from this server, installs as a
{platform === 'windows' ? 'Windows service' : platform === 'linux' ? 'systemd unit' : 'launchd daemon'}
and enrolls automatically.
{/if}
</p>
@@ -209,8 +221,9 @@
? 'one use'
: unlimited
? 'unlimited uses'
: `up to ${effectiveUses} use${effectiveUses === 1 ? '' : 's'}`}, 24-hour expiry)
and builds the paste-ready install command for the selected platform.
: `up to ${effectiveUses} use${effectiveUses === 1 ? '' : 's'}`},
{noExpiry ? 'no expiry' : '24-hour expiry'}) and builds the paste-ready install command
for the selected platform.
</p>
{/if}
+100
View File
@@ -0,0 +1,100 @@
<script lang="ts" module>
export type OsPlatform = 'windows' | 'macos' | 'linux' | 'unknown';
/** Mirrors the backend DeviceFieldBag.DerivePlatform normalization. */
export function osPlatform(caption?: string | null): OsPlatform {
if (!caption) return 'unknown';
const c = caption.toLowerCase();
if (c.includes('windows')) return 'windows';
if (c.includes('macos') || c.includes('mac os') || c.includes('darwin')) return 'macos';
return 'linux';
}
</script>
<script lang="ts">
let { caption = undefined, size = 16 }: { caption?: string | null; size?: number } = $props();
const platform = $derived(osPlatform(caption));
const label = $derived(
platform === 'windows'
? 'Windows'
: platform === 'macos'
? 'macOS'
: platform === 'linux'
? 'Linux'
: 'Unknown OS'
);
</script>
<span
class="os-icon {platform}"
title={caption ?? label}
role="img"
aria-label={label}
style="--os-size: {size}px"
>
{#if platform === 'windows'}
<svg viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">
<path
d="M3 4.6 10.6 3.5V11.2H3V4.6Zm8.5-1.2L21 2v9.2h-9.5V3.4ZM3 12.8h7.6v7.7L3 19.4V12.8Zm8.5 0H21V22l-9.5-1.3V12.8Z"
/>
</svg>
{:else if platform === 'macos'}
<svg viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">
<path
d="M18.7 12.9c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.9-1.4-.1-2.8.9-3.5.9s-1.8-.8-3-.8c-1.6 0-3 .9-3.8 2.3-1.6 2.8-.4 7 1.2 9.3.8 1.1 1.7 2.3 2.9 2.3 1.2 0 1.6-.7 3-.7s1.8.7 3 .7 2-1.1 2.8-2.2c.9-1.3 1.2-2.5 1.3-2.6-.1 0-2.5-1-2.5-3.8Zm-2.4-6.9c.6-.8 1.1-1.9 1-3-1 0-2.1.6-2.8 1.4-.6.7-1.1 1.8-1 2.9 1 .1 2.1-.5 2.8-1.3Z"
/>
</svg>
{:else if platform === 'linux'}
<!-- Stylized Tux: amber body (currentColor), theme-aware belly + eyes,
orange beak and feet. -->
<svg viewBox="0 0 24 24" aria-hidden="true">
<ellipse cx="9.4" cy="21" rx="2" ry="1.1" fill="#e6802a" />
<ellipse cx="14.6" cy="21" rx="2" ry="1.1" fill="#e6802a" />
<path
d="M12 2.5c-3 0-5 2.4-5 5.6 0 1.3.2 2 .2 3.1 0 3-1 4.4-1 7.2 0 2.6 2.6 4 5.8 4s5.8-1.4 5.8-4c0-2.8-1-4.2-1-7.2 0-1.1.2-1.8.2-3.1 0-3.2-2-5.6-5-5.6Z"
fill="currentColor"
/>
<ellipse cx="12" cy="14.8" rx="3.1" ry="4.6" fill="var(--surface)" />
<circle cx="10.5" cy="7.6" r="1.1" fill="var(--surface)" />
<circle cx="13.5" cy="7.6" r="1.1" fill="var(--surface)" />
<circle cx="10.7" cy="7.8" r="0.5" fill="#1a1a1a" />
<circle cx="13.3" cy="7.8" r="0.5" fill="#1a1a1a" />
<path d="M11 9.1h2l-1 1.5Z" fill="#e6802a" />
</svg>
{:else}
<svg viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">
<path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 15a1.2 1.2 0 1 1 0-2.4A1.2 1.2 0 0 1 12 17Zm1.2-4.3c0 .6-.5.8-.5 1.1h-1.4c0-.9.4-1.4 1-1.8.5-.4.7-.6.7-1.1 0-.6-.5-1-1.1-1s-1.1.4-1.1 1.2H9.4c0-1.5 1.1-2.5 2.7-2.5 1.5 0 2.6.9 2.6 2.2 0 1.1-.7 1.6-1.5 1.9Z" />
</svg>
{/if}
</span>
<style>
.os-icon {
display: inline-flex;
width: var(--os-size);
height: var(--os-size);
flex: none;
vertical-align: -2px;
}
.os-icon svg {
width: 100%;
height: 100%;
}
.windows {
color: #2f8fed;
}
.macos {
color: var(--text-muted, #888);
}
.linux {
color: #e0902f;
}
.unknown {
color: var(--text-muted, #888);
}
</style>
@@ -0,0 +1,82 @@
<script lang="ts">
// Horizontal bars for ranked counts — label, proportional bar, value.
let {
items,
color = 'var(--accent)',
emptyText = 'No data yet'
}: {
items: { label: string; count: number }[];
color?: string;
emptyText?: string;
} = $props();
const max = $derived(Math.max(1, ...items.map((i) => i.count)));
</script>
{#if items.length === 0}
<p class="empty">{emptyText}</p>
{:else}
<ul class="bars">
{#each items as item (item.label)}
<li>
<span class="label" title={item.label}>{item.label}</span>
<span class="track">
<span class="fill" style="width: {(item.count / max) * 100}%; background: {color}"></span>
</span>
<span class="count">{item.count}</span>
</li>
{/each}
</ul>
{/if}
<style>
.bars {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.bars li {
display: grid;
grid-template-columns: minmax(0, 8rem) 1fr auto;
align-items: center;
gap: var(--space-3);
font-size: 12px;
}
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-muted);
}
.track {
height: 8px;
border-radius: 999px;
background: var(--border);
overflow: hidden;
}
.fill {
display: block;
height: 100%;
border-radius: 999px;
min-width: 2px;
}
.count {
font-variant-numeric: tabular-nums;
font-weight: 600;
color: var(--text);
}
.empty {
color: var(--text-muted);
font-size: 13px;
margin: 0;
}
</style>
@@ -0,0 +1,101 @@
<script lang="ts">
// A quiet donut: segments proportional to value, with a centered total.
let {
segments,
size = 132,
thickness = 16,
centerLabel = '',
centerValue = ''
}: {
segments: { label: string; value: number; color: string }[];
size?: number;
thickness?: number;
centerLabel?: string;
centerValue?: string;
} = $props();
const radius = $derived((size - thickness) / 2);
const circumference = $derived(2 * Math.PI * radius);
const total = $derived(segments.reduce((sum, s) => sum + s.value, 0));
const arcs = $derived.by(() => {
let offset = 0;
return segments
.filter((s) => s.value > 0)
.map((s) => {
const fraction = total > 0 ? s.value / total : 0;
const arc = { ...s, dash: fraction * circumference, offset };
offset += fraction * circumference;
return arc;
});
});
</script>
<div class="donut" style="--size: {size}px">
<svg viewBox="0 0 {size} {size}" role="img" aria-label={centerLabel}>
<g transform="rotate(-90 {size / 2} {size / 2})">
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke="var(--border)"
stroke-width={thickness}
/>
{#each arcs as arc (arc.label)}
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke={arc.color}
stroke-width={thickness}
stroke-dasharray="{arc.dash} {circumference - arc.dash}"
stroke-dashoffset={-arc.offset}
stroke-linecap="butt"
/>
{/each}
</g>
</svg>
<div class="center">
<div class="value">{centerValue}</div>
<div class="label">{centerLabel}</div>
</div>
</div>
<style>
.donut {
position: relative;
width: var(--size);
height: var(--size);
flex: none;
}
.donut svg {
width: 100%;
height: 100%;
}
.center {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
.value {
font-size: 22px;
font-weight: 700;
line-height: 1.1;
}
.label {
font-size: 10px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.06em;
}
</style>
@@ -0,0 +1,93 @@
<script lang="ts">
import type { DayPoint } from '$lib/api/types';
// A calm stacked column chart of executions per day (succeeded / failed /
// other), sized to its container with a thin baseline.
let { days }: { days: DayPoint[] } = $props();
const max = $derived(Math.max(1, ...days.map((d) => d.succeeded + d.failed + d.other)));
const total = $derived(days.reduce((sum, d) => sum + d.succeeded + d.failed + d.other, 0));
</script>
{#if total === 0}
<p class="empty">No executions in the last 14 days.</p>
{:else}
<div class="chart" role="img" aria-label="Executions over the last 14 days">
{#each days as day (day.date)}
{@const sum = day.succeeded + day.failed + day.other}
<div class="col" title="{day.date}: {day.succeeded} ok, {day.failed} failed, {day.other} other">
<div class="stack" style="height: {(sum / max) * 100}%">
{#if day.other > 0}
<div class="seg other" style="flex: {day.other}"></div>
{/if}
{#if day.failed > 0}
<div class="seg failed" style="flex: {day.failed}"></div>
{/if}
{#if day.succeeded > 0}
<div class="seg ok" style="flex: {day.succeeded}"></div>
{/if}
</div>
</div>
{/each}
</div>
<div class="axis">
<span>{days[0]?.date}</span>
<span>{days[days.length - 1]?.date}</span>
</div>
{/if}
<style>
.chart {
display: flex;
align-items: flex-end;
gap: 4px;
height: 120px;
padding-top: var(--space-2);
}
.col {
flex: 1;
height: 100%;
display: flex;
align-items: flex-end;
}
.stack {
width: 100%;
min-height: 2px;
display: flex;
flex-direction: column;
border-radius: 3px 3px 0 0;
overflow: hidden;
}
.seg {
width: 100%;
}
.seg.ok {
background: var(--success);
}
.seg.failed {
background: var(--danger);
}
.seg.other {
background: var(--text-faint);
}
.axis {
display: flex;
justify-content: space-between;
font-size: 11px;
color: var(--text-muted);
margin-top: 6px;
}
.empty {
color: var(--text-muted);
font-size: 13px;
margin: 0;
}
</style>
+409 -192
View File
@@ -1,265 +1,482 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { api } from '$lib/api/client';
import type { ActivityEventPayload, DeviceDto, JobDto } from '$lib/api/types';
import { nats } from '$lib/messaging/nats';
import type { DashboardDto } from '$lib/api/types';
import { nats, type JobEvent } from '$lib/messaging/nats';
import EmptyState from '$lib/components/EmptyState.svelte';
import JobStateBadge from '$lib/components/JobStateBadge.svelte';
import OsIcon from '$lib/components/OsIcon.svelte';
import Donut from '$lib/components/charts/Donut.svelte';
import BarList from '$lib/components/charts/BarList.svelte';
import TimelineChart from '$lib/components/charts/TimelineChart.svelte';
let devices = $state<DeviceDto[] | null>(null);
let jobs = $state<JobDto[] | null>(null);
let activity = $state<ActivityEventPayload[]>([]);
let data = $state<DashboardDto | null>(null);
const counts = $derived.by(() => {
const list = devices ?? [];
return {
total: list.length,
online: list.filter((d) => d.status === 'online').length,
stale: list.filter((d) => d.status === 'stale').length,
offline: list.filter((d) => d.status === 'offline').length
};
});
// Live deployment tracker: NATS job.state events roll up into a running
// count so a group run of N endpoints shows progress as it lands.
let liveTotal = $state(0);
let liveFinished = $state(0);
const liveActive = $derived(liveTotal > 0 && liveFinished < liveTotal);
const jobCounts = $derived.by(() => {
const list = jobs ?? [];
return {
running: list.filter((j) => j.state === 'running' || j.state === 'dispatched').length,
failed: list.filter((j) => j.state === 'failed' || j.state === 'timedOut').length
};
});
const stateColors: Record<string, string> = {
Succeeded: 'var(--success)',
Failed: 'var(--danger)',
TimedOut: '#c2410c',
Running: 'var(--info)',
Dispatched: 'var(--info)',
Queued: 'var(--text-faint)',
Cancelled: 'var(--text-faint)'
};
const platformColors: Record<string, string> = {
windows: '#2f8fed',
linux: '#e0902f',
macos: 'var(--text-muted)',
unknown: 'var(--text-faint)'
};
const latestEnrollments = $derived(
[...(devices ?? [])].sort((a, b) => b.enrolledUtc.localeCompare(a.enrolledUtc)).slice(0, 5)
const stateSegments = $derived(
(data?.jobsByState ?? []).map((s) => ({
label: s.label,
value: s.count,
color: stateColors[s.label] ?? 'var(--accent)'
}))
);
const platformSegments = $derived(
(data?.devicesByPlatform ?? []).map((p) => ({
label: p.label,
value: p.count,
color: platformColors[p.label] ?? 'var(--accent)'
}))
);
async function refresh() {
[devices, jobs] = await Promise.all([api.devices(), api.jobs(undefined, 100)]);
data = await api.dashboard().catch(() => data);
}
onMount(() => {
void refresh().catch(() => undefined);
void refresh();
const unsubscribe = nats.onActivity((event) => {
// Near-real-time: NATS events refresh immediately; a slow poll keeps
// the aggregates current even without a browser messaging session.
const poll = setInterval(() => void refresh(), 15000);
const offActivity = nats.onActivity((event) => {
if (event.kind !== 'device-presence') {
activity = [event, ...activity].slice(0, 40);
void refresh().catch(() => undefined);
void refresh();
}
});
return unsubscribe;
const offJob = nats.onJobEvent((_jobId: string, event: JobEvent) => {
if (event.type === 'job.state') {
const state = event.payload.state;
if (['queued', 'dispatched'].includes(state)) {
liveTotal += 1;
} else if (['succeeded', 'failed', 'cancelled', 'timedOut'].includes(state)) {
liveFinished += 1;
void refresh();
}
}
});
return () => {
clearInterval(poll);
offActivity();
offJob();
};
});
const activityIcon = (kind: string) =>
({
'device-online': '●',
'device-offline': '○',
'device-enrolled': '✚',
'inventory-updated': '⟳',
'job-created': '▶',
'job-started': '▶',
'job-completed': '✔'
})[kind] ?? '·';
function resetLive() {
liveTotal = 0;
liveFinished = 0;
}
</script>
<div class="grid">
{#if data === null}
<div class="tiles">
{#each Array(4) as _, i (i)}<div class="tile card"><span class="skeleton">loading…</span></div>{/each}
</div>
{:else}
{#if liveActive}
<section class="card live pulse-in">
<div class="live-head">
<span class="live-dot" aria-hidden="true"></span>
<strong>Deploying</strong>
<span class="muted">{liveFinished} of {liveTotal} endpoints finished</span>
<button class="btn ghost small" onclick={resetLive}>Dismiss</button>
</div>
<div class="live-track">
<div class="live-fill" style="width: {(liveFinished / liveTotal) * 100}%"></div>
</div>
</section>
{/if}
<section class="tiles">
{#if devices === null}
{#each Array(6) as _, i (i)}
<div class="tile card"><span class="skeleton">loading…</span></div>
{/each}
{:else}
<div class="tile card">
<div class="value">{counts.total}</div>
<div class="label">Devices</div>
<button class="tile card" onclick={() => goto('/devices')}>
<div class="value">{data.devicesTotal}</div>
<div class="label">Devices</div>
<div class="sub">
<span class="ok">{data.devicesOnline} online</span> · {data.devicesOffline} offline
</div>
<div class="tile card accent-success">
<div class="value">{counts.online}</div>
<div class="label">Online</div>
</div>
<div class="tile card accent-warning">
<div class="value">{counts.stale}</div>
<div class="label">Stale</div>
</div>
<div class="tile card accent-muted">
<div class="value">{counts.offline}</div>
<div class="label">Offline</div>
</div>
<div class="tile card accent-info">
<div class="value">{jobCounts.running}</div>
<div class="label">Running jobs</div>
</div>
<div class="tile card accent-danger">
<div class="value">{jobCounts.failed}</div>
<div class="label">Failed jobs</div>
</div>
{/if}
</button>
<div class="tile card">
<div class="value">{data.jobsTotal}</div>
<div class="label">Jobs · 30 days</div>
<div class="sub">{data.jobsInProgress} in progress</div>
</div>
<div class="tile card">
<div class="value ok">{data.successRate}%</div>
<div class="label">Success rate</div>
<div class="sub">{data.jobsSucceeded} ok · {data.jobsFailed} failed</div>
</div>
<div class="tile card">
<div class="value {data.jobsFailed > 0 ? 'bad' : ''}">{data.jobsFailed}</div>
<div class="label">Failed · 30 days</div>
<div class="sub">TimedOut counted</div>
</div>
</section>
<section class="card panel activity-panel">
<div class="panel-head">
<h2>Live activity</h2>
</div>
{#if activity.length === 0}
<EmptyState
title="Waiting for activity"
detail="Device connections, inventory updates and job events appear here in real time."
/>
{:else}
<ul class="feed">
{#each activity as event, i (event.timestampUtc + event.text + i)}
<li class="pulse-in kind-{event.kind}">
<span class="glyph" aria-hidden="true">{activityIcon(event.kind)}</span>
<span class="text">{event.text}</span>
<span class="time faint">{new Date(event.timestampUtc).toLocaleTimeString()}</span>
</li>
{/each}
</ul>
{/if}
</section>
<div class="grid">
<section class="card panel">
<h2>Job outcomes</h2>
<div class="donut-row">
<Donut
segments={stateSegments}
centerValue={String(data.jobsTotal)}
centerLabel="jobs"
/>
<ul class="legend">
{#each data.jobsByState as s (s.label)}
<li>
<span class="swatch" style="background: {stateColors[s.label] ?? 'var(--accent)'}"></span>
<span class="lg-label">{s.label}</span>
<span class="lg-count">{s.count}</span>
</li>
{/each}
</ul>
</div>
</section>
<section class="card panel">
<div class="panel-head">
<h2>Latest enrollments</h2>
</div>
{#if latestEnrollments.length === 0}
<EmptyState
title="No devices yet"
detail="Generate a bootstrap token in Settings and install the agent to enroll your first device."
/>
{:else}
<ul class="enrollments">
{#each latestEnrollments as device (device.clientId)}
<li>
<a href="/devices/{device.clientId}">{device.hostname}</a>
<span class="faint">{new Date(device.enrolledUtc).toLocaleString()}</span>
</li>
{/each}
</ul>
{/if}
</section>
</div>
<section class="card panel">
<h2>Executions · 14 days</h2>
<TimelineChart days={data.timeline} />
<div class="legend-inline">
<span><span class="swatch" style="background: var(--success)"></span>Succeeded</span>
<span><span class="swatch" style="background: var(--danger)"></span>Failed</span>
<span><span class="swatch" style="background: var(--text-faint)"></span>Other</span>
</div>
</section>
<section class="card panel">
<h2>Script engine</h2>
<BarList items={data.jobsByEngine} color="#7c6cf0" emptyText="No jobs yet." />
</section>
<section class="card panel">
<h2>Exit codes</h2>
<BarList items={data.jobsByExitCode} color="var(--info)" emptyText="No completed jobs yet." />
</section>
<section class="card panel">
<h2>Top targets</h2>
<BarList items={data.topTargets} color="#2f8fed" emptyText="No jobs yet." />
</section>
<section class="card panel">
<h2>Most-run scripts</h2>
<BarList items={data.topScripts} color="#22a06b" emptyText="No jobs yet." />
</section>
<section class="card panel">
<h2>Fleet platforms</h2>
<div class="donut-row">
<Donut
segments={platformSegments}
centerValue={String(data.devicesTotal)}
centerLabel="devices"
/>
<ul class="legend">
{#each data.devicesByPlatform as p (p.label)}
<li>
<span class="swatch" style="background: {platformColors[p.label] ?? 'var(--accent)'}"></span>
<span class="lg-label">{p.label}</span>
<span class="lg-count">{p.count}</span>
</li>
{/each}
</ul>
</div>
</section>
<section class="card panel recent">
<h2>Latest executions</h2>
{#if data.recentRuns.length === 0}
<EmptyState title="No runs yet" detail="Run a script to see executions here." />
{:else}
<ul class="runs">
{#each data.recentRuns as run (run.jobId)}
<li>
<button class="run" onclick={() => goto(`/jobs?job=${run.jobId}`)}>
<JobStateBadge state={run.state} />
<span class="run-script">{run.scriptName}</span>
<span class="run-host">
<OsIcon caption={undefined} size={13} />{run.hostname ?? run.clientId}
</span>
<span class="run-time faint">{new Date(run.createdUtc).toLocaleTimeString()}</span>
</button>
</li>
{/each}
</ul>
{/if}
</section>
</div>
{/if}
<style>
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-4);
}
.tiles {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: var(--space-3);
margin-bottom: var(--space-4);
}
.tile {
padding: var(--space-4);
text-align: left;
border: 1px solid var(--border);
}
button.tile {
cursor: pointer;
font: inherit;
color: inherit;
}
button.tile:hover {
border-color: var(--accent);
}
.value {
font-size: 26px;
font-size: 28px;
font-weight: 700;
line-height: 1.2;
line-height: 1.1;
}
.label {
font-size: 12px;
color: var(--text-muted);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.accent-success .value {
.value.ok {
color: var(--success);
}
.accent-warning .value {
color: var(--warning);
}
.accent-danger .value {
.value.bad {
color: var(--danger);
}
.accent-info .value {
color: var(--info);
.label {
font-size: 11px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.06em;
font-weight: 600;
margin-top: 2px;
}
.accent-muted .value {
color: var(--text-faint);
.sub {
font-size: 12px;
color: var(--text-muted);
margin-top: var(--space-2);
}
.panel {
overflow: hidden;
}
.panel-head {
padding: var(--space-3) var(--space-4);
border-bottom: 1px solid var(--border);
}
.activity-panel {
min-height: 320px;
}
.feed {
list-style: none;
margin: 0;
padding: var(--space-2) 0;
max-height: 420px;
overflow-y: auto;
}
.feed li {
display: flex;
align-items: baseline;
gap: var(--space-3);
padding: 6px var(--space-4);
font-size: 13px;
}
.glyph {
width: 16px;
text-align: center;
color: var(--text-faint);
}
.kind-device-online .glyph,
.kind-job-completed .glyph {
.sub .ok {
color: var(--success);
}
.kind-device-enrolled .glyph,
.kind-job-created .glyph,
.kind-job-started .glyph {
color: var(--accent);
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-4);
}
.kind-inventory-updated .glyph {
color: var(--info);
.panel {
padding: var(--space-4);
}
.text {
.panel h2 {
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted);
margin: 0 0 var(--space-3);
}
.recent {
grid-column: 1 / -1;
}
.donut-row {
display: flex;
align-items: center;
gap: var(--space-4);
}
.legend {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
flex: 1;
}
.time {
.legend li {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: var(--space-2);
font-size: 12px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
display: inline-block;
}
.lg-label {
color: var(--text-muted);
}
.lg-count {
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.legend-inline {
display: flex;
gap: var(--space-4);
font-size: 11px;
color: var(--text-muted);
margin-top: var(--space-2);
}
.legend-inline span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.runs {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.run {
width: 100%;
display: grid;
grid-template-columns: 90px minmax(0, 1fr) minmax(0, 1fr) auto;
align-items: center;
gap: var(--space-3);
padding: 8px 4px;
background: none;
border: none;
border-top: 1px solid var(--border);
cursor: pointer;
font: inherit;
color: inherit;
text-align: left;
}
.runs li:first-child .run {
border-top: none;
}
.run:hover {
background: var(--bg-subtle, rgba(127, 127, 127, 0.06));
}
.run-script {
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.run-host {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--text-muted);
font-size: 13px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.run-time {
font-size: 11px;
white-space: nowrap;
}
.enrollments {
list-style: none;
margin: 0;
padding: var(--space-2) 0;
.live {
padding: var(--space-3) var(--space-4);
margin-bottom: var(--space-4);
border: 1px solid var(--info);
}
.enrollments li {
.live-head {
display: flex;
justify-content: space-between;
padding: 8px var(--space-4);
font-size: 13px;
align-items: center;
gap: var(--space-2);
margin-bottom: var(--space-2);
}
.live-head .muted {
flex: 1;
}
.live-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--info);
animation: pulse 1.2s ease-in-out infinite;
}
.live-track {
height: 8px;
border-radius: 999px;
background: var(--border);
overflow: hidden;
}
.live-fill {
height: 100%;
background: var(--info);
border-radius: 999px;
transition: width 0.3s ease;
}
.btn.ghost {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
}
.small {
font-size: 12px;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
@media (max-width: 1100px) {
+13 -1
View File
@@ -9,6 +9,7 @@
import RelativeTime from '$lib/components/RelativeTime.svelte';
import EmptyState from '$lib/components/EmptyState.svelte';
import AddDeviceModal from '$lib/components/AddDeviceModal.svelte';
import OsIcon from '$lib/components/OsIcon.svelte';
let devices = $state<DeviceDto[] | null>(null);
let showAddDevice = $state(false);
@@ -126,7 +127,12 @@
tabindex="0"
>
<td><StatusBadge status={device.status} /></td>
<td class="hostname">{device.hostname}</td>
<td class="hostname">
<span class="host-cell">
<OsIcon caption={device.osCaption} />
{device.hostname}
</span>
</td>
<td class="muted">
{[device.manufacturer, device.model].filter(Boolean).join(' · ') || '—'}
</td>
@@ -164,6 +170,12 @@
font-weight: 600;
}
.host-cell {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.sort {
background: none;
border: none;
@@ -10,6 +10,7 @@
import RelativeTime from '$lib/components/RelativeTime.svelte';
import EmptyState from '$lib/components/EmptyState.svelte';
import CopyChip from '$lib/components/CopyChip.svelte';
import OsIcon from '$lib/components/OsIcon.svelte';
const clientId = $derived(page.params.clientId!);
@@ -39,7 +40,7 @@
async function refresh() {
try {
detail = await api.device(clientId);
jobs = await api.jobs(clientId, 25);
jobs = await api.jobs(clientId, 100);
} catch (e) {
error = e instanceof ApiError && e.status === 404 ? 'Device not found.' : 'Failed to load device.';
}
@@ -126,7 +127,7 @@
{ id: 'overview', label: 'Overview' },
{ id: 'hardware', label: 'Hardware' },
{ id: 'network', label: 'Network' },
{ id: 'jobs', label: 'Jobs' },
{ id: 'jobs', label: 'Execution History' },
{ id: 'actions', label: 'Actions' }
];
</script>
@@ -142,6 +143,7 @@
<div>
<div class="crumbs"><a href="/devices">Devices</a> / {device.hostname}</div>
<div class="title-row">
<OsIcon caption={device.osCaption} size={22} />
<h1>{device.hostname}</h1>
<StatusBadge status={device.status} />
</div>
@@ -421,28 +423,34 @@
{:else if tab === 'jobs'}
<div class="card table-wrap">
{#if jobs.length === 0}
<EmptyState title="No jobs for this device" />
<EmptyState title="No executions on this device yet" />
{:else}
<table class="data">
<thead>
<tr><th>State</th><th>Script</th><th>Created</th><th>Duration</th><th>Exit</th></tr>
</thead>
<tbody>
{#each jobs as job (job.jobId)}
<tr class="clickable" onclick={() => goto(`/jobs?job=${job.jobId}`)}>
<td><JobStateBadge state={job.state} /></td>
<td>{job.scriptName}</td>
<td class="muted"><RelativeTime value={job.createdUtc} /></td>
<td class="muted">
{job.startedUtc && job.completedUtc
? `${Math.round((new Date(job.completedUtc).getTime() - new Date(job.startedUtc).getTime()) / 1000)}s`
: '—'}
</td>
<td class="mono muted">{job.exitCode ?? '—'}</td>
</tr>
{/each}
</tbody>
</table>
{#each [...new Set(jobs.map((j) => j.scriptName))] as scriptName (scriptName)}
<h4 class="history-script">{scriptName}</h4>
<table class="data">
<thead>
<tr><th>State</th><th>Started</th><th>Duration</th><th>Exit</th></tr>
</thead>
<tbody>
{#each jobs.filter((j) => j.scriptName === scriptName) as job (job.jobId)}
<tr class="clickable" onclick={() => goto(`/jobs?job=${job.jobId}`)}>
<td><JobStateBadge state={job.state} /></td>
<td class="muted"><RelativeTime value={job.createdUtc} /></td>
<td class="muted">
{job.startedUtc && job.completedUtc
? `${Math.round((new Date(job.completedUtc).getTime() - new Date(job.startedUtc).getTime()) / 1000)}s`
: '—'}
</td>
<td class="mono muted">{job.exitCode ?? '—'}</td>
</tr>
{/each}
</tbody>
</table>
{/each}
<p class="muted small history-note">
Click an execution to open its output. Retention keeps the newest runs per device
(JOB_HISTORY_LIMIT, default 200).
</p>
{/if}
</div>
{:else if tab === 'actions'}
@@ -536,6 +544,14 @@
gap: var(--space-2);
}
.history-script {
margin: var(--space-3) var(--space-3) var(--space-1);
}
.history-note {
margin: var(--space-2) var(--space-3) var(--space-3);
}
.tabs {
display: flex;
gap: var(--space-1);
+21 -11
View File
@@ -7,6 +7,7 @@
let modules = $state<FunctionModuleDto[] | null>(null);
let selected = $state<FunctionModuleDto | null>(null);
let creating = $state(false);
let name = $state('');
let description = $state('');
let content = $state('');
@@ -20,6 +21,7 @@
function edit(m: FunctionModuleDto) {
selected = m;
creating = false;
name = m.name;
description = m.description ?? '';
content = m.content;
@@ -28,6 +30,7 @@
function newModule() {
selected = null;
creating = true;
name = '';
description = '';
content = 'function Write-ExecuteRLog {\n param([string]$Message)\n Write-Output "[ExecuteR] $Message"\n}\n';
@@ -58,6 +61,7 @@
if (!confirm(`Delete function “${selected.name}”?`)) return;
await api.deleteFunction(selected.id);
selected = null;
creating = false;
name = '';
content = '';
await refresh();
@@ -118,18 +122,24 @@
{/if}
</div>
<div class="card editor">
<div class="editor-head">
<input class="input name-input" placeholder="Module name" bind:value={name} />
{#if statusText}<span class="muted status">{statusText}</span>{/if}
<div class="spacer"></div>
{#if selected}<button class="btn danger" onclick={remove}>Delete</button>{/if}
{#if selected}<button class="btn" onclick={clone}>⧉ Clone</button>{/if}
<button class="btn primary" onclick={save}>💾 Save</button>
{#if selected || creating}
<div class="card editor">
<div class="editor-head">
<input class="input name-input" placeholder="Function name" bind:value={name} />
{#if statusText}<span class="muted status">{statusText}</span>{/if}
<div class="spacer"></div>
{#if selected}<button class="btn danger" onclick={remove}>Delete</button>{/if}
{#if selected}<button class="btn" onclick={clone}>⧉ Clone</button>{/if}
<button class="btn primary" onclick={save}>💾 Save</button>
</div>
<input class="input desc-input" placeholder="Description (optional)" bind:value={description} />
<textarea class="input code" spellcheck="false" bind:value={content} placeholder={'function Verb-Noun { ... }'}></textarea>
</div>
<input class="input desc-input" placeholder="Description (optional)" bind:value={description} />
<textarea class="input code" spellcheck="false" bind:value={content} placeholder={'function Verb-Noun { ... }'}></textarea>
</div>
{:else}
<div class="card editor">
<EmptyState title="No Function selected" detail="Pick one from the list, or click + New function." />
</div>
{/if}
</div>
<style>
+160 -46
View File
@@ -41,8 +41,32 @@
let devices = $state<DeviceDto[]>([]);
let allGroups = $state<DeviceGroupDto[]>([]);
// 'device:<clientId>' or 'group:<groupId>'
// Picker value ('device:<clientId>' or 'group:<groupId>') and the added set.
let targetKey = $state('');
let targets = $state<string[]>([]);
let history = $state<JobDto[]>([]);
function addTarget() {
if (targetKey && !targets.includes(targetKey)) targets = [...targets, targetKey];
}
function removeTarget(key: string) {
targets = targets.filter((t) => t !== key);
}
function targetLabel(key: string) {
const id = key.slice(key.indexOf(':') + 1);
if (key.startsWith('group:')) {
const group = allGroups.find((g) => g.id === id);
return group ? `${group.name} (group)` : id;
}
return devices.find((d) => d.clientId === id)?.hostname ?? id;
}
async function refreshHistory() {
if (isNew) return;
history = await api.jobs(undefined, 50, scriptId).catch(() => []);
}
let parameters = $state<ScriptParameter[]>([]);
let functionModuleIds = $state<string[]>([]);
@@ -164,9 +188,11 @@
const requested = page.url.searchParams.get('target');
if (requested && devices.some((d) => d.clientId === requested)) {
targetKey = `device:${requested}`;
targets = [targetKey];
} else if (devices.length > 0) {
targetKey = `device:${devices[0].clientId}`;
}
void refreshHistory();
})();
return () => {
@@ -232,7 +258,7 @@
async function run() {
const id = await save();
if (!id || !targetKey) return;
if (!id || targets.length === 0) return;
outputLines = [];
progress = null;
@@ -244,26 +270,33 @@
focusJobId = null;
const args = paramInputs?.collect() ?? {};
const isGroup = targetKey.startsWith('group:');
const targetId = targetKey.slice(targetKey.indexOf(':') + 1);
// One or more targets: devices dispatch one job each, groups fan out
// per member. Everything lands in one per-device list below.
try {
if (isGroup) {
const result = await api.createGroupJob(targetId, id, args);
groupJobs = result.jobs;
skippedOrphaned = result.skippedOrphaned;
for (const groupJob of result.jobs) {
jobStates[groupJob.jobId] = groupJob.state;
const runJobs: JobDto[] = [];
const skipped: string[] = [];
for (const key of targets) {
const targetId = key.slice(key.indexOf(':') + 1);
if (key.startsWith('group:')) {
const result = await api.createGroupJob(targetId, id, args);
runJobs.push(...result.jobs);
skipped.push(...result.skippedOrphaned);
} else {
runJobs.push(await api.createJob(targetId, id, args));
}
if (result.jobs.length === 0) {
statusText = 'The group has no devices able to run jobs.';
return;
}
void focusJob(result.jobs[0].jobId);
} else {
job = await api.createJob(targetId, id, args);
jobState = job.state;
}
groupJobs = runJobs;
skippedOrphaned = skipped;
for (const started of runJobs) {
jobStates[started.jobId] = started.state;
}
if (runJobs.length === 0) {
statusText = 'No devices were able to run this job.';
return;
}
void focusJob(runJobs[0].jobId);
} catch (e) {
statusText = e instanceof Error ? e.message : 'Failed to start job.';
return;
@@ -304,14 +337,7 @@
}
});
if (job) {
// Recovery model: fetch any output persisted before our subscription.
const singleJobId = job.jobId;
const stored = await api.jobOutput(singleJobId).catch(() => []);
if (stored.length > 0 && outputLines.length === 0) {
outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text }));
}
}
void refreshHistory();
}
async function remove() {
@@ -400,7 +426,7 @@
<button class="btn" onclick={clone} disabled={saving}>⧉ Clone</button>
{/if}
<button class="btn" onclick={save} disabled={saving}>💾 Save</button>
<button class="btn primary" onclick={run} disabled={saving || !targetKey || running}>
<button class="btn primary" onclick={run} disabled={saving || targets.length === 0 || running}>
▶ Run
</button>
</div>
@@ -499,27 +525,44 @@
<div class="flow">
<section class="card section">
<h3>Execution</h3>
<select class="select target" bind:value={targetKey} aria-label="Target device or group">
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId} disabled={device.status !== 'online'}>
{device.hostname}
{device.status !== 'online' ? `(${device.status})` : ''}
</option>
{/each}
</optgroup>
{#if allGroups.length > 0}
<optgroup label="Groups (one job per member)">
{#each allGroups as group (group.id)}
<option value={'group:' + group.id}>{group.name} ({group.kind})</option>
<div class="target-row">
<select class="select target" bind:value={targetKey} aria-label="Add a target device or group">
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId} disabled={device.status !== 'online'}>
{device.hostname}
{device.status !== 'online' ? `(${device.status})` : ''}
</option>
{/each}
</optgroup>
{/if}
</select>
{#if targetKey.startsWith('group:')}
{#if allGroups.length > 0}
<optgroup label="Groups (one job per member)">
{#each allGroups as group (group.id)}
<option value={'group:' + group.id}>{group.name} ({group.kind})</option>
{/each}
</optgroup>
{/if}
</select>
<button class="btn" onclick={addTarget} disabled={!targetKey}>+ Add target</button>
</div>
{#if targets.length > 0}
<ul class="chips">
{#each targets as key (key)}
<li class="chip">
{targetLabel(key)}
<button class="chip-x" aria-label="Remove target" onclick={() => removeTarget(key)}
>✕</button
>
</li>
{/each}
</ul>
{:else}
<p class="muted small">Add one or more devices or groups, then Run.</p>
{/if}
{#if targets.some((t) => t.startsWith('group:'))}
<p class="muted small">
Runs on every non-orphaned member. Offline devices receive the job durably when they
reconnect.
Groups run on every non-orphaned member. Offline devices receive the job durably when
they reconnect.
</p>
{/if}
{#if devices.length === 0}
@@ -547,7 +590,7 @@
{#if groupJobs.length > 0}
<section class="card section run-wide">
<div class="job-head">
<h3>Group run</h3>
<h3>Run</h3>
<span class="muted small">{groupFinished}/{groupJobs.length} finished</span>
</div>
{#if skippedOrphaned.length > 0}
@@ -610,6 +653,34 @@
</div>
</section>
{#if !isNew}
<section class="card section run-wide">
<div class="job-head">
<h3>History</h3>
<button class="btn" onclick={refreshHistory}>↻ Refresh</button>
</div>
{#if history.length === 0}
<p class="muted small">No executions of this script yet.</p>
{:else}
<table class="data">
<thead>
<tr><th>Started</th><th>Device</th><th>State</th><th>Exit</th></tr>
</thead>
<tbody>
{#each history as h (h.jobId)}
<tr class="clickable" onclick={() => goto(`/jobs?job=${h.jobId}`)}>
<td class="muted">{new Date(h.createdUtc).toLocaleString()}</td>
<td>{h.hostname ?? h.clientId}</td>
<td><JobStateBadge state={h.state} /></td>
<td class="muted">{h.exitCode ?? '—'}</td>
</tr>
{/each}
</tbody>
</table>
{/if}
</section>
{/if}
<style>
.head {
display: flex;
@@ -620,6 +691,49 @@
flex-wrap: wrap;
}
.target-row {
display: flex;
gap: var(--space-2);
align-items: center;
}
.chips {
list-style: none;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: var(--space-2) 0 0;
padding: 0;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 8px;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 12px;
background: var(--bg-subtle, transparent);
}
.chip-x {
border: none;
background: none;
cursor: pointer;
color: var(--text-muted);
font-size: 11px;
padding: 0;
}
.chip-x:hover {
color: var(--danger, #d33);
}
.clickable {
cursor: pointer;
}
.crumbs {
font-size: 12px;
color: var(--text-muted);
+7 -3
View File
@@ -111,8 +111,8 @@
<div class="token-form">
<label>
<span class="muted">Valid (minutes)</span>
<input class="input" type="number" min="5" bind:value={validMinutes} />
<span class="muted">Valid (minutes, 0 = never expires)</span>
<input class="input" type="number" min="0" bind:value={validMinutes} />
</label>
<label>
<span class="muted">Max uses (0 = unlimited)</span>
@@ -165,7 +165,11 @@
{#each tokens as token (token.id)}
<tr>
<td class="muted">{new Date(token.createdUtc).toLocaleString()}</td>
<td class="muted">{new Date(token.expiresUtc).toLocaleString()}</td>
<td class="muted"
>{new Date(token.expiresUtc).getFullYear() > 9000
? 'Never'
: new Date(token.expiresUtc).toLocaleString()}</td
>
<td>{token.uses} / {token.maxUses === 0 ? '∞' : token.maxUses}</td>
<td class="muted">{token.note ?? '—'}</td>
<td>
+23
View File
@@ -38,6 +38,29 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<Back
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task ValidMinutesZeroMeansNoExpiry()
{
using var client = await AdminClientAsync();
var response = await client.PostAsJsonAsync(
"/api/admin/bootstrap-tokens", new { maxUses = 1, validMinutes = 0 });
response.EnsureSuccessStatusCode();
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var expires = body.RootElement.GetProperty("expiresUtc").GetDateTimeOffset();
Assert.True(expires.Year > 9000, $"expected a never-expires sentinel, got {expires:u}");
}
[Fact]
public async Task NegativeValidMinutesIsRejected()
{
using var client = await AdminClientAsync();
var response = await client.PostAsJsonAsync(
"/api/admin/bootstrap-tokens", new { maxUses = 1, validMinutes = -5 });
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
}
private async Task<HttpClient> AdminClientAsync()
{
await fixture.WithDbAsync(async db =>
+34 -3
View File
@@ -179,7 +179,8 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture<
[Fact]
public async Task DefaultedPasswordForcesAResetBeforeAnySessionExists()
{
var seeded = await SeedLocalUserAsync("reset-admin", "admin-password", "Admin");
// The reset only applies while the password IS the built-in default.
var seeded = await SeedLocalUserAsync("reset-admin", "admin", "Admin");
await fixture.WithDbAsync(async db =>
{
var user = await db.Users.SingleAsync(u => u.Id == seeded.Id);
@@ -191,7 +192,7 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture<
// Valid credentials produce no session — only the must-change signal.
var login = await client.PostAsJsonAsync(
"/api/auth/login", new { username = "reset-admin", password = "admin-password" });
"/api/auth/login", new { username = "reset-admin", password = "admin" });
Assert.Equal(System.Net.HttpStatusCode.OK, login.StatusCode);
using (var body = JsonDocument.Parse(await login.Content.ReadAsStringAsync()))
{
@@ -215,7 +216,7 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture<
var change = await client.PostAsJsonAsync("/api/auth/change-password", new
{
username = "reset-admin",
currentPassword = "admin-password",
currentPassword = "admin",
newPassword = "brand-new-password-1",
});
Assert.Equal(System.Net.HttpStatusCode.OK, change.StatusCode);
@@ -240,6 +241,36 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture<
}
}
[Fact]
public async Task CustomPasswordSignsInDespiteAStaleMustChangeFlag()
{
// A custom install-time password must never be forced to reset,
// whatever the flag says — and the stale flag is cleared.
var seeded = await SeedLocalUserAsync("custom-admin", "chosen-at-install-1", "Admin");
await fixture.WithDbAsync(async db =>
{
var user = await db.Users.SingleAsync(u => u.Id == seeded.Id);
user.MustChangePassword = true;
await db.SaveChangesAsync();
});
using var client = fixture.CreateClient();
var login = await client.PostAsJsonAsync(
"/api/auth/login", new { username = "custom-admin", password = "chosen-at-install-1" });
Assert.Equal(System.Net.HttpStatusCode.OK, login.StatusCode);
using (var body = JsonDocument.Parse(await login.Content.ReadAsStringAsync()))
{
Assert.True(body.RootElement.GetProperty("authenticated").GetBoolean());
Assert.False(body.RootElement.GetProperty("mustChangePassword").GetBoolean());
}
await fixture.WithDbAsync(async db =>
{
var user = await db.Users.SingleAsync(u => u.Id == seeded.Id);
Assert.False(user.MustChangePassword);
});
}
private async Task<UserEntity> SeedLocalUserAsync(string username, string password, string roleName)
=> await fixture.WithDbAsync(async db =>
{