Executions/script-page rework + self-signed TLS fingerprint pin & graceful root renewal #14

Merged
gsadmin merged 6 commits from dev into main 2026-08-11 09:47:17 +00:00
32 changed files with 3364 additions and 502 deletions
@@ -26,6 +26,28 @@ public sealed class AgentConfiguration
Shared.Infrastructure.Routing.ServerUrl.TryParse(ServerUrlText.Value, out var parsed, out _) ? parsed : null;
public bool HasBootstrapToken => !string.IsNullOrWhiteSpace(BootstrapToken.Value);
/// <summary>
/// The server CA fingerprint (SHA-256, lowercase hex) the operator baked into
/// the bootstrap token as a "secret.fp" suffix, or null. The agent pins the CA
/// it fetches on first contact to this, so an on-path attacker cannot swap it.
/// The full token (with the suffix) is still what gets sent for validation.
/// </summary>
public string? ServerCaFingerprint
{
get
{
var token = BootstrapToken.Value;
var dot = token?.LastIndexOf('.') ?? -1;
if (token is null || dot < 0)
{
return null;
}
var fp = token[(dot + 1)..];
return fp.Length == 64 && fp.All(Uri.IsHexDigit) ? fp.ToLowerInvariant() : null;
}
}
}
/// <summary>Loads effective configuration using deterministic precedence.</summary>
+99 -23
View File
@@ -1,4 +1,6 @@
using System.Net.Http.Json;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Agent.Configuration;
using Agent.Identity;
using Agent.Storage;
@@ -80,35 +82,71 @@ public sealed class EnrollmentService(
AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly),
Device: ReadDeviceInfo());
// Always probe for a self-signed CA first (the probe accepts any
// certificate — it only asks whether the server is self-signed and
// fetches public CA certs). A self-signed server's chain lands in the
// OS trust store so ordinary system validation succeeds below; a real
// certificate returns 404 and this is a no-op. Not pinned — a proxy
// with a real certificate added later still validates.
await ServerTrust.FetchAndInstallCaAsync(serverUrl, HttpClient.DefaultProxy, logger, cancellationToken);
// TlsSkipVerify is the accept-any escape hatch; otherwise validate
// against the OS trust store (which now contains the CA above).
using var handler = new HttpClientHandler();
if (configuration.TlsSkipVerify.Value)
{
handler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
}
using var http = new HttpClient(handler);
var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap);
logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint);
using var response = await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
// Connection-first trust: attempt a normally-validated connection. Only if
// the server certificate does not validate — a self-signed server on first
// contact — do we anchor trust by fetching its CA and pinning it to the
// fingerprint baked into the bootstrap token. A real/edge certificate, or a
// CA installed on a previous run, just validates and installs nothing.
HttpResponseMessage response;
if (configuration.TlsSkipVerify.Value)
{
logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode);
return null;
// Manual accept-any escape hatch (CLI/GPO) — no anchoring.
using var skipHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
};
response = await PostBootstrapAsync(skipHandler, endpoint, request, cancellationToken);
}
else
{
try
{
using var validating = new HttpClientHandler();
response = await PostBootstrapAsync(validating, endpoint, request, cancellationToken);
}
catch (HttpRequestException ex) when (ex.HttpRequestError == HttpRequestError.SecureConnectionError)
{
var expectedFingerprint = configuration.ServerCaFingerprint;
if (expectedFingerprint is null)
{
logger.LogError(
"Server certificate is not trusted and the bootstrap token carries no CA fingerprint; refusing to enroll");
return null;
}
var (status, pinnedChain) = await ServerTrust.FetchAndInstallCaAsync(
serverUrl, HttpClient.DefaultProxy, logger, expectedFingerprint, cancellationToken);
if (status != ServerCaStatus.Installed)
{
logger.LogError("Could not anchor server trust ({Status}); refusing to enroll", status);
return null;
}
// Retry, validating the leaf against the CA we just verified so it
// succeeds in-process regardless of OS trust-store timing.
using var pinnedHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = TrustPinnedChain(pinnedChain),
};
response = await PostBootstrapAsync(pinnedHandler, endpoint, request, cancellationToken);
}
}
BootstrapResponse? result;
using (response)
{
if (!response.IsSuccessStatusCode)
{
logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode);
return null;
}
result = await response.Content.ReadFromJsonAsync<BootstrapResponse>(JsonDefaults.Options, cancellationToken);
}
var result = await response.Content.ReadFromJsonAsync<BootstrapResponse>(JsonDefaults.Options, cancellationToken);
if (result is null || string.IsNullOrWhiteSpace(result.UserJwt))
{
logger.LogError("Bootstrap response was empty or invalid");
@@ -134,6 +172,44 @@ public sealed class EnrollmentService(
return credentials;
}
private static async Task<HttpResponseMessage> PostBootstrapAsync(
HttpMessageHandler handler, Uri endpoint, BootstrapRequest request, CancellationToken cancellationToken)
{
using var http = new HttpClient(handler, disposeHandler: false);
return await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken);
}
/// <summary>
/// Validates the server leaf against a specific fetched-and-pinned CA chain
/// (custom root trust). Accepts only an untrusted-chain error — a name
/// mismatch or a missing certificate is still rejected.
/// </summary>
private static Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> TrustPinnedChain(
X509Certificate2Collection pinned)
=> (_, cert, _, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
if ((errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0 || cert is null)
{
return false;
}
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
foreach (X509Certificate2 ca in pinned)
{
chain.ChainPolicy.CustomTrustStore.Add(ca);
chain.ChainPolicy.ExtraStore.Add(ca);
}
return chain.Build(cert);
};
/// <summary>
/// Computes the deterministic client id, verifies it against the cached
/// runtime value and refreshes the cache.
+102 -9
View File
@@ -1,6 +1,8 @@
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging;
using Shared.Contracts.Api;
@@ -8,6 +10,22 @@ using Shared.Infrastructure.Routing;
namespace Agent.Enrollment;
/// <summary>Outcome of probing and (maybe) installing the server's self-signed CA.</summary>
public enum ServerCaStatus
{
/// <summary>404 — the server is not self-signed (a real certificate is in front).</summary>
NotSelfSigned,
/// <summary>The fetched CA matched the pinned fingerprint and was installed.</summary>
Installed,
/// <summary>A chain was fetched but it did not match the pinned fingerprint — not installed.</summary>
FingerprintMismatch,
/// <summary>The CA could not be fetched or parsed.</summary>
FetchFailed,
}
/// <summary>
/// Makes the server's managed self-signed CA available to the OS trust store
/// so ordinary system validation succeeds when the agent connects to the
@@ -20,14 +38,16 @@ namespace Agent.Enrollment;
public static class ServerTrust
{
/// <summary>
/// Fetches the server's CA chain and installs it into the OS trust store
/// (idempotent, best-effort). The fetch accepts any certificate — it is
/// retrieving public CA certs to establish trust — then verifies the
/// payload is real PEM certificates before installing. Returns true when
/// a chain was fetched.
/// Fetches the server's CA chain over an accept-any connection, verifies it
/// against <paramref name="expectedFingerprint"/> (the pin the operator baked
/// into the bootstrap token), and — only on a match — installs it into the OS
/// trust store. The transport is untrusted by design; the fingerprint, not the
/// connection, is what authenticates the anchor. Returns the outcome and, when
/// installed, the verified chain (so the caller can validate the retry against
/// it directly, independent of OS trust-store timing).
/// </summary>
public static async Task<bool> FetchAndInstallCaAsync(
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken)
public static async Task<(ServerCaStatus Status, X509Certificate2Collection Chain)> FetchAndInstallCaAsync(
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, string expectedFingerprint, CancellationToken cancellationToken)
{
using var handler = new HttpClientHandler
{
@@ -48,7 +68,7 @@ public static class ServerTrust
using var response = await http.GetAsync(endpoint, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return false; // Server is not self-signed — nothing to install.
return (ServerCaStatus.NotSelfSigned, []);
}
response.EnsureSuccessStatusCode();
@@ -57,12 +77,85 @@ public static class ServerTrust
if (chain.Count == 0)
{
logger.LogWarning("Server CA response contained no certificates");
return false;
return (ServerCaStatus.FetchFailed, []);
}
}
catch (Exception ex)
{
logger.LogWarning(ex, "Could not fetch the server CA from {Endpoint}", endpoint);
return (ServerCaStatus.FetchFailed, []);
}
var expected = expectedFingerprint.Trim().ToLowerInvariant();
var matched = chain.Cast<X509Certificate2>()
.Any(c => Convert.ToHexStringLower(SHA256.HashData(c.RawData)) == expected);
if (!matched)
{
logger.LogError(
"Fetched server CA does not match the fingerprint pinned in the bootstrap token; refusing to trust (possible MITM)");
return (ServerCaStatus.FingerprintMismatch, []);
}
if (OperatingSystem.IsWindows())
{
InstallWindows(chain, logger);
}
else if (OperatingSystem.IsMacOS())
{
InstallMac(pem, logger);
}
else
{
InstallLinux(pem, logger);
}
return (ServerCaStatus.Installed, chain);
}
/// <summary>
/// Post-enrollment CA refresh over a NORMALLY-VALIDATED connection. The agent
/// already trusts the current CA, so an updated chain served over that trusted
/// connection — a root renewed in place (same key, longer validity) or a new
/// intermediate — is authentic and installed. No pin here: the validated
/// transport, not a fingerprint, authenticates it (first contact was pinned at
/// enrollment). A 404 (real certificate) or a validation failure is a harmless
/// no-op. Returns true when a chain was installed.
/// </summary>
public static async Task<bool> RefreshCaAsync(
ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken)
{
using var handler = new HttpClientHandler();
if (proxy is not null)
{
handler.Proxy = proxy;
handler.UseProxy = true;
}
using var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
var endpoint = serverUrl.ApiEndpoint(ApiRoutes.EnrollmentCaChain);
string pem;
X509Certificate2Collection chain = [];
try
{
using var response = await http.GetAsync(endpoint, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
response.EnsureSuccessStatusCode();
pem = await response.Content.ReadAsStringAsync(cancellationToken);
chain.ImportFromPem(pem);
if (chain.Count == 0)
{
return false;
}
}
catch (Exception ex)
{
// Untrusted (root may have rotated its key — needs re-enrollment),
// unchanged, or unreachable: nothing to do this cycle.
logger.LogDebug(ex, "CA refresh skipped");
return false;
}
+10 -9
View File
@@ -6,14 +6,15 @@ using Microsoft.Extensions.Logging;
namespace Agent.Service;
/// <summary>
/// Keeps the server's self-signed CA present in the OS trust store: probes
/// GET /api/enrollment/ca on start and every few hours, installing the chain
/// when the server is self-signed so a server-side rotation stays trusted
/// without operator action. The probe accepts any certificate (it is only
/// asking whether the server is self-signed and fetching public CA certs); a
/// 404 means the server is not self-signed, so it is a harmless no-op. It never
/// forces validation against the CA — a proxy with a real certificate is
/// unaffected.
/// Keeps the server's CA current in the OS trust store after enrollment. Every
/// few hours it re-fetches GET /api/enrollment/ca over a NORMALLY-VALIDATED
/// connection and installs the chain, so a root renewed in place (same key,
/// extended validity) or a new intermediate is picked up before the old cert
/// expires — no operator action, no re-enrollment. The validated transport
/// authenticates the update, so no pin is needed here (first-contact trust was
/// pinned to the token at enrollment). A real/edge certificate returns 404 — a
/// no-op — and a full root *key* rotation cannot validate and is left for a
/// fresh bootstrap token.
/// </summary>
public sealed class CaRefreshService(
AgentConfigurationLoader loader, ILogger<CaRefreshService> logger) : BackgroundService
@@ -27,7 +28,7 @@ public sealed class CaRefreshService(
{
if (loader.Load().ServerUrl is { } serverUrl)
{
await ServerTrust.FetchAndInstallCaAsync(
await ServerTrust.RefreshCaAsync(
serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, stoppingToken);
}
}
+64 -23
View File
@@ -1,7 +1,6 @@
#if !WINDOWS_AGENT
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Agent.Shell;
@@ -12,12 +11,17 @@ namespace Agent.Shell;
/// detection all work). Terminal output is delivered via
/// <see cref="OutputReceived"/>; input is written with
/// <see cref="WriteAsync"/>.
///
/// I/O goes straight through read(2)/write(2) on the master fd rather than a
/// FileStream: a FileStream serializes its async read and write behind one
/// semaphore, so the always-pending output read would block every input write
/// (the shell opens but you cannot type). The raw syscalls are independent.
/// </summary>
internal sealed class UnixPtySession : IPtySession
{
private int masterFd = -1;
private int childPid = -1;
private FileStream? io;
private readonly Lock writeLock = new();
private readonly CancellationTokenSource lifetime = new();
private bool disposed;
@@ -67,9 +71,10 @@ internal sealed class UnixPtySession : IPtySession
childPid = pid;
masterFd = Marshal.ReadInt32(masterPtr);
io = new FileStream(new SafeFileHandle((IntPtr)masterFd, ownsHandle: true), FileAccess.ReadWrite);
_ = Task.Run(PumpOutputAsync);
// Dedicated thread for the blocking read loop; a threadpool thread
// would be parked indefinitely waiting for terminal output.
new Thread(ReadLoop) { IsBackground = true, Name = "pty-read" }.Start();
_ = Task.Run(WatchProcessAsync);
}
finally
@@ -82,15 +87,39 @@ internal sealed class UnixPtySession : IPtySession
}
}
public async Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
public Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
if (io is null)
WriteAll(data.Span);
return Task.CompletedTask;
}
// write(2) is independent of the read loop, so input is delivered even while
// a read is pending. The lock keeps concurrent writes in order and handles
// partial writes.
private unsafe void WriteAll(ReadOnlySpan<byte> data)
{
if (masterFd < 0)
{
return;
}
await io.WriteAsync(data, cancellationToken);
await io.FlushAsync(cancellationToken);
lock (writeLock)
{
fixed (byte* p = data)
{
var total = 0;
while (total < data.Length)
{
var written = Native.write(masterFd, p + total, (nuint)(data.Length - total));
if (written <= 0)
{
break; // fd closed on teardown, or EIO once the child exited
}
total += (int)written;
}
}
}
}
public void Resize(int cols, int rows)
@@ -108,26 +137,32 @@ internal sealed class UnixPtySession : IPtySession
_ = Native.ioctl(masterFd, Native.TIOCSWINSZ, ref win);
}
private async Task PumpOutputAsync()
private unsafe void ReadLoop()
{
var buffer = new byte[4096];
try
{
while (!lifetime.IsCancellationRequested)
{
var read = await io!.ReadAsync(buffer, lifetime.Token);
if (read == 0)
nint read;
fixed (byte* p = buffer)
{
break;
read = Native.read(masterFd, p, (nuint)buffer.Length);
}
OutputReceived?.Invoke(buffer.AsMemory(0, read).ToArray());
if (read <= 0)
{
break; // 0 = EOF; -1 = EIO on the master when the slave closes / fd closed
}
var chunk = new byte[read];
Buffer.BlockCopy(buffer, 0, chunk, 0, (int)read);
OutputReceived?.Invoke(chunk);
}
}
catch (Exception)
{
// EIO on the master when the slave closes (child exited), or the
// stream was disposed on shutdown.
// fd closed underneath the read on shutdown.
}
}
@@ -163,20 +198,17 @@ internal sealed class UnixPtySession : IPtySession
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.
// Closing the master hangs up the slave (SIGHUP → the shell exits) and
// unblocks the read loop; SIGTERM covers a shell that ignores the hangup.
if (childPid > 0)
{
_ = Native.kill(childPid, Native.SIGTERM);
}
try
if (masterFd >= 0)
{
io?.Dispose();
}
catch (IOException)
{
// Master already closed.
_ = Native.close(masterFd);
masterFd = -1;
}
if (childPid > 0)
@@ -324,6 +356,15 @@ internal sealed class UnixPtySession : IPtySession
[DllImport("libc", SetLastError = true)]
public static extern int kill(int pid, int sig);
[DllImport("libc", SetLastError = true)]
public static extern unsafe nint read(int fd, byte* buf, nuint count);
[DllImport("libc", SetLastError = true)]
public static extern unsafe nint write(int fd, byte* buf, nuint count);
[DllImport("libc", SetLastError = true)]
public static extern int close(int fd);
}
}
#endif
@@ -1,6 +1,7 @@
using Backend.Auth;
using Backend.Data;
using Backend.Security;
using Backend.Tls;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Infrastructure.Constants;
@@ -47,7 +48,18 @@ public static class BootstrapTokenEndpoints
var maxUses = request?.MaxUses ?? ProtocolDefaults.BootstrapTokenDefaultMaxUses;
// Plaintext exists exactly once: in this response. Only the hash is stored.
// When the server runs the managed self-signed chain, append its CA
// fingerprint (token = "secret.fp"): the agent pins the CA it fetches on
// first contact to this value, so an on-path attacker cannot substitute a
// CA. The fp travels wherever the token does — no extra plumbing — and the
// hash covers the whole string, so enrollment validation is unchanged.
var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes);
var caFingerprint = context.RequestServices.GetService<SelfSignedTlsManager>()?.CaFingerprint();
if (caFingerprint is not null)
{
token += "." + caFingerprint;
}
var actor = context.User.Identity?.Name;
var entity = new BootstrapTokenEntity
+1
View File
@@ -104,6 +104,7 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
entity.HasKey(e => e.JobId);
entity.HasIndex(e => e.ClientId);
entity.HasIndex(e => e.CreatedUtc);
entity.HasIndex(e => new { e.ScriptId, e.RunId });
entity.Property(e => e.State).HasConversion<string>();
});
+8
View File
@@ -241,6 +241,14 @@ public sealed class FunctionModuleEntity
public sealed class JobEntity
{
public Guid JobId { get; set; }
/// <summary>
/// Groups every per-device job created by one run (ad-hoc, group, or a
/// trigger firing) so executions can be listed and drilled into. Null on
/// legacy jobs, which are treated as single-target executions.
/// </summary>
public Guid? RunId { get; set; }
public required string ClientId { get; set; }
public Guid ScriptId { get; set; }
public required string ScriptName { get; set; }
@@ -0,0 +1,733 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
[DbContext(typeof(PostgresAppDbContext))]
[Migration("20260810205443_AddJobRunId")]
partial class AddJobRunId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("text");
b.Property<bool>("IsSecret")
.HasColumnType("boolean");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Actor")
.HasColumnType("text");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("Detail")
.HasColumnType("text");
b.Property<string>("RemoteIp")
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("timestamp with time zone");
b.Property<int>("MaxUses")
.HasColumnType("integer");
b.Property<string>("Note")
.HasColumnType("text");
b.Property<bool>("Revoked")
.HasColumnType("boolean");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Uses")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("AgentVersion")
.HasColumnType("text");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uuid");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddressesJson")
.HasColumnType("text");
b.Property<bool>("IsOrphaned")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Manufacturer")
.HasColumnType("text");
b.Property<string>("Model")
.HasColumnType("text");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("OsCaption")
.HasColumnType("text");
b.Property<string>("OsVersion")
.HasColumnType("text");
b.Property<string>("PublicIp")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("TagsJson")
.HasColumnType("text");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RulesJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ExitCode")
.HasColumnType("integer");
b.Property<string>("OutputSummary")
.HasColumnType("text");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<Guid?>("RunId")
.HasColumnType("uuid");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("text");
b.Property<bool>("IsSystem")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("text");
b.Property<string>("PermissionsJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("FileBindingsJson")
.HasColumnType("text");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("text");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ParametersJson")
.HasColumnType("text");
b.Property<string>("SecretBindingsJson")
.HasColumnType("text");
b.Property<string>("SecretsVariableName")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ArgumentsJson")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("LastResult")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<Guid>("TriggerId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseReason")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasColumnType("text");
b.Property<string>("ExternalId")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.HasColumnType("boolean");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("RoleId")
.HasColumnType("uuid");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddJobRunId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "RunId",
table: "Jobs",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs",
columns: new[] { "ScriptId", "RunId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs");
migrationBuilder.DropColumn(
name: "RunId",
table: "Jobs");
}
}
}
@@ -321,6 +321,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<Guid?>("RunId")
.HasColumnType("uuid");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
@@ -341,6 +344,8 @@ namespace Backend.Data.Migrations.Postgres
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
@@ -0,0 +1,733 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
[DbContext(typeof(SqlServerAppDbContext))]
[Migration("20260810205500_AddJobRunId")]
partial class AddJobRunId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsSecret")
.HasColumnType("bit");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Actor")
.HasColumnType("nvarchar(max)");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("Detail")
.HasColumnType("nvarchar(max)");
b.Property<string>("RemoteIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("datetimeoffset");
b.Property<int>("MaxUses")
.HasColumnType("int");
b.Property<string>("Note")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Revoked")
.HasColumnType("bit");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Uses")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("AgentVersion")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("IpAddressesJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsOrphaned")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Manufacturer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Model")
.HasColumnType("nvarchar(max)");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("OsCaption")
.HasColumnType("nvarchar(max)");
b.Property<string>("OsVersion")
.HasColumnType("nvarchar(max)");
b.Property<string>("PublicIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("TagsJson")
.HasColumnType("nvarchar(max)");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("RulesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<Guid>("GroupId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<int?>("ExitCode")
.HasColumnType("int");
b.Property<string>("OutputSummary")
.HasColumnType("nvarchar(max)");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("RunId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsSystem")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("PermissionsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("FileBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("ParametersJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretsVariableName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ArgumentsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LastResult")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("TriggerId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("CloseReason")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("ExternalId")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("MustChangePassword")
.HasColumnType("bit");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddJobRunId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "RunId",
table: "Jobs",
type: "uniqueidentifier",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs",
columns: new[] { "ScriptId", "RunId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs");
migrationBuilder.DropColumn(
name: "RunId",
table: "Jobs");
}
}
}
@@ -321,6 +321,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("RunId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
@@ -341,6 +344,8 @@ namespace Backend.Data.Migrations.SqlServer
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
@@ -0,0 +1,720 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
[DbContext(typeof(SqliteAppDbContext))]
[Migration("20260810205428_AddJobRunId")]
partial class AddJobRunId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.10");
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Action")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Actor")
.HasColumnType("TEXT");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("Detail")
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresUtc")
.HasColumnType("INTEGER");
b.Property<int>("MaxUses")
.HasColumnType("INTEGER");
b.Property<string>("Note")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Uses")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("AgentVersion")
.HasColumnType("TEXT");
b.Property<long>("EnrolledUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("EnrollmentId")
.HasColumnType("TEXT");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("IpAddressesJson")
.HasColumnType("TEXT");
b.Property<bool>("IsOrphaned")
.HasColumnType("INTEGER");
b.Property<long?>("LastSeenUtc")
.HasColumnType("INTEGER");
b.Property<string>("Manufacturer")
.HasColumnType("TEXT");
b.Property<string>("Model")
.HasColumnType("TEXT");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("OrphanedUtc")
.HasColumnType("INTEGER");
b.Property<string>("OsCaption")
.HasColumnType("TEXT");
b.Property<string>("OsVersion")
.HasColumnType("TEXT");
b.Property<string>("PublicIp")
.HasColumnType("TEXT");
b.Property<long?>("ReadyUtc")
.HasColumnType("INTEGER");
b.Property<string>("TagsJson")
.HasColumnType("TEXT");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RulesJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AddedUtc")
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("CompletedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<int?>("ExitCode")
.HasColumnType("INTEGER");
b.Property<string>("OutputSummary")
.HasColumnType("TEXT");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<Guid?>("RunId")
.HasColumnType("TEXT");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("StartedUtc")
.HasColumnType("INTEGER");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<long>("Sequence")
.HasColumnType("INTEGER");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("TEXT");
b.Property<bool>("IsSystem")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("TEXT");
b.Property<string>("PermissionsJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("FileBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("TEXT");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ParametersJson")
.HasColumnType("TEXT");
b.Property<string>("SecretBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("SecretsVariableName")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ArgumentsJson")
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<string>("LastResult")
.HasColumnType("TEXT");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("FiredUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<Guid>("TriggerId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CloseReason")
.HasColumnType("TEXT");
b.Property<long?>("ClosedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasColumnType("TEXT");
b.Property<long?>("LastLoginUtc")
.HasColumnType("INTEGER");
b.Property<bool>("MustChangePassword")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid?>("RoleId")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddJobRunId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "RunId",
table: "Jobs",
type: "TEXT",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs",
columns: new[] { "ScriptId", "RunId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Jobs_ScriptId_RunId",
table: "Jobs");
migrationBuilder.DropColumn(
name: "RunId",
table: "Jobs");
}
}
}
@@ -312,6 +312,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<Guid?>("RunId")
.HasColumnType("TEXT");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
@@ -332,6 +335,8 @@ namespace Backend.Data.Migrations.Sqlite
b.HasIndex("CreatedUtc");
b.HasIndex("ScriptId", "RunId");
b.ToTable("Jobs", (string)null);
});
+1 -1
View File
@@ -69,7 +69,7 @@ public sealed class ScriptTriggerService(
}
var job = await runner.CreateJobAsync(
script, clientId, $"trigger:{triggerType}", cancellationToken);
script, clientId, $"trigger:{triggerType}", cancellationToken, Guid.NewGuid());
if (trigger.OncePerDevice)
{
+34
View File
@@ -14,6 +14,7 @@ public static class TriggerEndpoints
{
app.MapGet(ApiRoutes.Triggers, ListAsync).RequirePermission(Permissions.AutomationView);
app.MapPost(ApiRoutes.Triggers, CreateAsync).RequirePermission(Permissions.AutomationManage);
app.MapPatch(ApiRoutes.Trigger, SetEnabledAsync).RequirePermission(Permissions.AutomationManage);
app.MapDelete(ApiRoutes.Trigger, DeleteAsync).RequirePermission(Permissions.AutomationManage);
}
@@ -109,6 +110,39 @@ public static class TriggerEndpoints
return Results.Created(ApiRoutes.For.Trigger(entity.Id), new { id = entity.Id });
}
private static async Task<IResult> SetEnabledAsync(
Guid id, SetTriggerEnabledRequest request, AppDbContext db, CancellationToken cancellationToken)
{
var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken);
if (entity is null)
{
return Results.NotFound();
}
entity.Enabled = request.Enabled;
// Re-enabling a recurring schedule whose next run already passed would
// fire a backlog on the next sweep; advance it to the next future run.
if (request.Enabled
&& entity.TriggerType == ScriptTriggerType.Scheduled
&& !string.IsNullOrWhiteSpace(entity.CronExpression)
&& (entity.NextRunUtc is null || entity.NextRunUtc <= DateTimeOffset.UtcNow))
{
try
{
entity.NextRunUtc = ScheduleCron.NextOccurrence(
entity.CronExpression!, entity.TimeZoneId, DateTimeOffset.UtcNow);
}
catch (Exception)
{
// An unparseable cron simply won't fire; leave NextRunUtc as-is.
}
}
await db.SaveChangesAsync(cancellationToken);
return Results.NoContent();
}
private static async Task<IResult> DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken)
{
var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken);
+136 -2
View File
@@ -19,6 +19,66 @@ public static class JobEndpoints
app.MapPost(ApiRoutes.Jobs, CreateAsync).RequirePermission(Permissions.JobsRun);
app.MapGet(ApiRoutes.Job, GetAsync).RequirePermission(Permissions.JobsView);
app.MapGet(ApiRoutes.JobOutput, GetOutputAsync).RequirePermission(Permissions.JobsView);
app.MapGet(ApiRoutes.ScriptExecutions, ListExecutionsAsync).RequirePermission(Permissions.JobsView);
app.MapGet(ApiRoutes.Execution, GetExecutionAsync).RequirePermission(Permissions.JobsView);
}
/// <summary>Executions of a script: its per-device jobs grouped by run (newest first).</summary>
private static async Task<IResult> ListExecutionsAsync(
Guid scriptId, AppDbContext db, CancellationToken cancellationToken)
{
var jobs = await db.Jobs.AsNoTracking()
.Where(j => j.ScriptId == scriptId)
.OrderByDescending(j => j.CreatedUtc)
.Take(2000)
.Select(j => new { j.JobId, j.RunId, j.State, j.CreatedUtc, j.RequestedBy })
.ToListAsync(cancellationToken);
// Null RunId (legacy jobs) is treated as a single-target run keyed by its
// own JobId. Grouping is in-memory to keep the coalesce provider-agnostic.
var executions = jobs
.GroupBy(j => j.RunId ?? j.JobId)
.Select(g => new ExecutionSummaryDto(
g.Key,
scriptId,
g.Min(j => j.CreatedUtc),
g.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null),
g.Count(),
g.Count(j => j.State == JobState.Succeeded),
g.Count(j => j.State is JobState.Failed or JobState.TimedOut),
g.Count(j => j.State is JobState.Queued or JobState.Running)))
.OrderByDescending(e => e.StartedUtc)
.Take(50)
.ToList();
return Results.Ok(executions);
}
/// <summary>A single execution and the targets (devices) it ran on.</summary>
private static async Task<IResult> GetExecutionAsync(
Guid runId, AppDbContext db, CancellationToken cancellationToken)
{
var jobs = await db.Jobs.AsNoTracking()
.Where(j => j.RunId == runId || j.JobId == runId)
.OrderBy(j => j.CreatedUtc)
.ToListAsync(cancellationToken);
if (jobs.Count == 0)
{
return Results.NotFound();
}
var hostnames = await db.Devices.AsNoTracking()
.Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId))
.ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken);
var targets = jobs.Select(j => new ExecutionTargetDto(
j.JobId, j.ClientId, hostnames.GetValueOrDefault(j.ClientId), j.State, j.ExitCode,
j.CreatedUtc, j.StartedUtc, j.CompletedUtc)).ToList();
var first = jobs[0];
return Results.Ok(new ExecutionDetailDto(
runId, first.ScriptId, first.ScriptName, jobs.Min(j => j.CreatedUtc),
jobs.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), targets));
}
private static async Task<IResult> ListAsync(
@@ -116,6 +176,12 @@ public static class JobEndpoints
return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway);
}
if (request.GroupIds is { Count: > 0 } groupIds)
{
return await RunOnGroupsAsync(
groupIds, prepared, request, db, runner, groups, scope, audit, actor, context, cancellationToken);
}
if (request.GroupId is { } groupId)
{
return await RunOnGroupAsync(
@@ -147,7 +213,7 @@ public static class JobEndpoints
});
}
var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken);
var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken, Guid.NewGuid());
await runner.DispatchAsync(
prepared, job, request.Arguments,
$"Job “{script.Name}” queued for {device.Hostname}", cancellationToken);
@@ -196,6 +262,7 @@ public static class JobEndpoints
var jobs = new List<JobDto>();
var skipped = new List<string>();
var runId = Guid.NewGuid();
foreach (var device in devices)
{
@@ -205,7 +272,7 @@ public static class JobEndpoints
continue;
}
var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken);
var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId);
await runner.DispatchAsync(
prepared, job, request.Arguments,
$"Job “{prepared.Script.Name}” queued for {device.Hostname} (group “{group.Name}”)",
@@ -220,6 +287,73 @@ public static class JobEndpoints
return Results.Ok(new GroupRunDto(jobs, skipped));
}
/// <summary>Run across the deduped union of several groups' members, as one execution.</summary>
private static async Task<IResult> RunOnGroupsAsync(
IReadOnlyList<Guid> groupIds,
PreparedScript prepared,
CreateJobRequest request,
AppDbContext db,
JobRunner runner,
Backend.Groups.DeviceGroupService groups,
DeviceScopeService scope,
AuditService audit,
string? actor,
HttpContext context,
CancellationToken cancellationToken)
{
var selected = await db.DeviceGroups.AsNoTracking()
.Where(g => groupIds.Contains(g.Id))
.ToListAsync(cancellationToken);
if (selected.Count == 0)
{
return Results.NotFound(new { error = "No matching groups." });
}
var memberIds = new HashSet<string>();
foreach (var group in selected)
{
foreach (var member in await groups.GetMembersAsync(group, cancellationToken))
{
memberIds.Add(member);
}
}
var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken);
if (allowed is not null)
{
memberIds.IntersectWith(allowed);
}
var devices = await db.Devices.AsNoTracking()
.Where(d => memberIds.Contains(d.ClientId))
.ToListAsync(cancellationToken);
var jobs = new List<JobDto>();
var skipped = new List<string>();
var runId = Guid.NewGuid();
foreach (var device in devices)
{
if (device.IsOrphaned)
{
skipped.Add(device.Hostname);
continue;
}
var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId);
await runner.DispatchAsync(
prepared, job, request.Arguments,
$"Job “{prepared.Script.Name}” queued for {device.Hostname}", cancellationToken);
jobs.Add(ToDto(job, device.Hostname));
}
await audit.LogAsync(AuditCategories.Jobs, "group-run", actor,
detail: $"script={prepared.Script.Name} groups={selected.Count} jobs={jobs.Count} skipped={skipped.Count}",
cancellationToken: cancellationToken);
return Results.Ok(new GroupRunDto(jobs, skipped));
}
private static JobDto ToDto(JobEntity job, string? hostname) => new(
job.JobId, job.ClientId, hostname, job.ScriptId, job.ScriptName, job.State,
job.CreatedUtc, job.StartedUtc, job.CompletedUtc, job.ExitCode, job.RequestedBy, job.OutputSummary);
+3 -1
View File
@@ -125,11 +125,13 @@ public sealed class JobRunner(
}
public async Task<JobEntity> CreateJobAsync(
ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken)
ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken,
Guid? runId = null)
{
var job = new JobEntity
{
JobId = Guid.NewGuid(),
RunId = runId,
ClientId = clientId,
ScriptId = script.Id,
ScriptName = script.Name,
+2 -1
View File
@@ -121,9 +121,10 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
: JsonDefaults.Deserialize<Dictionary<string, JsonElement>>(trigger.ArgumentsJson);
var queued = 0;
var runId = Guid.NewGuid();
foreach (var device in devices)
{
var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken);
var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken, runId);
await runner.DispatchAsync(
prepared, job, arguments,
$"Scheduled trigger queued “{script.Name}” for {device.Hostname}",
+67 -6
View File
@@ -81,19 +81,40 @@ public sealed class SelfSignedTlsManager
}
/// <summary>
/// Creates or re-issues whatever links are missing, expiring, or no
/// longer signed by the current parent (a rotated root cascades down).
/// Idempotent; returns true when anything was issued.
/// SHA-256 (lowercase hex) of the root CA certificate. Baked into bootstrap
/// tokens so an enrolling agent can pin the CA it fetches over the untrusted
/// first-contact channel to the one this server actually publishes. Null
/// before the chain exists.
/// </summary>
public bool EnsureChain(ILogger logger)
public string? CaFingerprint()
{
lock (gate)
{
var root = persistence.Load(TlsRole.Root);
return root is null
? null
: Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(root.RawData));
}
}
/// <summary>
/// Creates or re-issues whatever links are missing, expiring, or no longer
/// signed by the current parent. The root is renewed <em>in place with the
/// same key</em> so the trust anchor stays continuous — already-enrolled
/// agents keep validating; only the certificate's validity is extended.
/// Idempotent; returns true when anything was issued.
/// </summary>
public bool EnsureChain(ILogger logger) => EnsureChain(logger, DateTimeOffset.UtcNow);
/// <summary>Testable overload — the clock is injected so renewal can be exercised.</summary>
internal bool EnsureChain(ILogger logger, DateTimeOffset now)
{
lock (gate)
{
var now = DateTimeOffset.UtcNow;
var changed = false;
var root = persistence.Load(TlsRole.Root);
if (!IsUsable(root, now, lifetimes.RootRenewalMargin))
if (root is null)
{
root = persistence.Save(TlsRole.Root, CreateRoot(now));
logger.LogInformation(
@@ -101,6 +122,17 @@ public sealed class SelfSignedTlsManager
root.NotAfter.ToUniversalTime());
changed = true;
}
else if (!IsUsable(root, now, lifetimes.RootRenewalMargin))
{
// Renew with the SAME key: the intermediate/leaf still chain to it,
// and agents that already trust this root keep validating across the
// handoff. A true key rotation is a deliberate re-enrollment event.
root = persistence.Save(TlsRole.Root, RenewRoot(root, now));
logger.LogInformation(
"Self-signed TLS: renewed the root CA in place (valid to {NotAfter:u})",
root.NotAfter.ToUniversalTime());
changed = true;
}
var intermediate = persistence.Load(TlsRole.Intermediate);
if (!IsUsable(intermediate, now, lifetimes.IntermediateRenewalMargin)
@@ -168,6 +200,35 @@ public sealed class SelfSignedTlsManager
return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root);
}
/// <summary>
/// Re-issues the root certificate with the <em>same key</em> and an extended
/// validity. Same subject + key means the same Subject Key Identifier, so the
/// existing intermediate (and everything under it) keeps chaining to it — the
/// only change agents see is a longer-lived root cert, picked up on refresh.
/// </summary>
private X509Certificate2 RenewRoot(X509Certificate2 existing, DateTimeOffset now)
{
// Rebuild a fresh ECDsa from the same key material (like CreateRoot's fresh
// key), so the renewed certificate owns a durable, exportable private key.
ECParameters parameters;
using (var existingKey = existing.GetECDsaPrivateKey()
?? throw new InvalidOperationException("Root certificate has no ECDSA private key to renew from."))
{
parameters = existingKey.ExportParameters(includePrivateParameters: true);
}
using var key = ECDsa.Create(parameters);
var request = new CertificateRequest(TlsSubjects.Root, key, HashAlgorithmName.SHA384);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(
certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 1, critical: true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(
X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
[new Oid("1.3.6.1.5.5.7.3.1")], critical: false));
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false));
return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root);
}
private X509Certificate2 CreateIntermediate(X509Certificate2 root, DateTimeOffset now)
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384);
+7 -2
View File
@@ -104,10 +104,15 @@ internal sealed class FileTlsPersistence(string directory) : ITlsPersistence
+ root.ExportCertificatePem() + '\n');
}
/// <summary>SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows.</summary>
/// <summary>
/// SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows.
/// Exportable mirrors the Windows-store backend and lets an in-place root
/// renewal re-use the key (it is already an exportable PEM on disk here).
/// </summary>
private static X509Certificate2 WithUsableKey(X509Certificate2 certificate)
=> OperatingSystem.IsWindows()
? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null)
? X509CertificateLoader.LoadPkcs12(
certificate.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable)
: certificate;
private static void WriteSecret(string path, string content)
+6
View File
@@ -63,6 +63,10 @@ public static class ApiRoutes
public const string Job = "/api/jobs/{jobId}";
public const string JobOutput = "/api/jobs/{jobId}/output";
/// <summary>Executions of a script (per-device jobs grouped by run).</summary>
public const string ScriptExecutions = "/api/scripts/{scriptId}/executions";
public const string Execution = "/api/executions/{runId}";
public const string Dashboard = "/api/dashboard";
/// <summary>Public self-signed CA chain (root + intermediate) for agent trust.</summary>
@@ -96,6 +100,8 @@ public static class ApiRoutes
public static string SecretsProviderNames(Guid id) => $"/api/secrets/providers/{id:D}/secret-names";
public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}";
public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output";
public static string ScriptExecutions(Guid scriptId) => $"/api/scripts/{scriptId:D}/executions";
public static string Execution(Guid runId) => $"/api/executions/{runId:D}";
public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}";
public static string AdminRole(Guid id) => $"/api/admin/roles/{id:D}";
public static string AdminUser(Guid id) => $"/api/admin/users/{id:D}";
+36 -1
View File
@@ -87,6 +87,40 @@ public sealed record SaveScriptTriggerRequest(
string? TimeZoneId = null,
IReadOnlyDictionary<string, System.Text.Json.JsonElement>? Arguments = null);
/// <summary>PATCH /api/triggers/{id} — enable or disable a trigger without deleting it.</summary>
public sealed record SetTriggerEnabledRequest(bool Enabled);
/// <summary>One execution (run) of a script — the per-device jobs it created, summarized.</summary>
public sealed record ExecutionSummaryDto(
Guid RunId,
Guid ScriptId,
DateTimeOffset StartedUtc,
string? RequestedBy,
int Total,
int Succeeded,
int Failed,
int Pending);
/// <summary>One device within an execution.</summary>
public sealed record ExecutionTargetDto(
Guid JobId,
string ClientId,
string? Hostname,
JobState State,
int? ExitCode,
DateTimeOffset CreatedUtc,
DateTimeOffset? StartedUtc,
DateTimeOffset? CompletedUtc);
/// <summary>GET /api/executions/{runId} — a run and the targets it ran on.</summary>
public sealed record ExecutionDetailDto(
Guid RunId,
Guid ScriptId,
string ScriptName,
DateTimeOffset StartedUtc,
string? RequestedBy,
IReadOnlyList<ExecutionTargetDto> Targets);
/// <summary>Device detail for GET /api/devices/{clientId}.</summary>
public sealed record DeviceDetailDto(
DeviceDto Device,
@@ -196,7 +230,8 @@ public sealed record CreateJobRequest(
string? ClientId,
Guid ScriptId,
IReadOnlyDictionary<string, System.Text.Json.JsonElement>? Arguments = null,
Guid? GroupId = null);
Guid? GroupId = null,
IReadOnlyList<Guid>? GroupIds = null);
/// <summary>Result of a group fan-out run: one job per eligible member.</summary>
public sealed record GroupRunDto(
+12
View File
@@ -13,6 +13,8 @@ import type {
JobDto,
DashboardDto,
JobOutputRecordDto,
ExecutionSummaryDto,
ExecutionDetailDto,
AgentPackageStatusDto,
AuthConfigDto,
AuthSettingsDto,
@@ -195,6 +197,9 @@ export const api = {
request<JobOutputRecordDto[]>(
`/api/jobs/${jobId}/output${afterSequence ? `?afterSequence=${afterSequence}` : ''}`
),
scriptExecutions: (scriptId: string) =>
request<ExecutionSummaryDto[]>(`/api/scripts/${scriptId}/executions`),
execution: (runId: string) => request<ExecutionDetailDto>(`/api/executions/${runId}`),
createJob: (clientId: string, scriptId: string, args?: Record<string, unknown>) =>
request<JobDto>('/api/jobs', {
method: 'POST',
@@ -205,6 +210,11 @@ export const api = {
method: 'POST',
body: JSON.stringify({ groupId, scriptId, arguments: args })
}),
createGroupsJob: (groupIds: string[], scriptId: string, args?: Record<string, unknown>) =>
request<GroupRunDto>('/api/jobs', {
method: 'POST',
body: JSON.stringify({ groupIds, scriptId, arguments: args })
}),
// Groups
@@ -246,6 +256,8 @@ export const api = {
timeZoneId?: string;
arguments?: Record<string, unknown>;
}) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }),
setTriggerEnabled: (id: string, enabled: boolean) =>
request<void>(`/api/triggers/${id}`, { method: 'PATCH', body: JSON.stringify({ enabled }) }),
deleteTrigger: (id: string) => request<void>(`/api/triggers/${id}`, { method: 'DELETE' }),
// Messaging
+31
View File
@@ -451,6 +451,37 @@ export interface JobOutputRecordDto {
text: string;
}
export interface ExecutionSummaryDto {
runId: string;
scriptId: string;
startedUtc: string;
requestedBy?: string;
total: number;
succeeded: number;
failed: number;
pending: number;
}
export interface ExecutionTargetDto {
jobId: string;
clientId: string;
hostname?: string;
state: JobState;
exitCode?: number;
createdUtc: string;
startedUtc?: string;
completedUtc?: string;
}
export interface ExecutionDetailDto {
runId: string;
scriptId: string;
scriptName: string;
startedUtc: string;
requestedBy?: string;
targets: ExecutionTargetDto[];
}
export interface SessionResponse {
authenticated: boolean;
username?: string;
@@ -54,6 +54,33 @@
const allDays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
// Full IANA list where the browser exposes it (all modern engines do),
// falling back to a common shortlist. UTC is always first/selectable.
const timeZones: string[] = (() => {
try {
const all = (Intl as unknown as { supportedValuesOf?: (k: string) => string[] })
.supportedValuesOf?.('timeZone');
if (all && all.length > 0) {
return ['UTC', ...all.filter((z) => z !== 'UTC')];
}
} catch {
// Older engine — fall through to the shortlist.
}
return [
'UTC',
'America/New_York',
'America/Chicago',
'America/Denver',
'America/Los_Angeles',
'Europe/London',
'Europe/Paris',
'Europe/Berlin',
'Asia/Tokyo',
'Asia/Singapore',
'Australia/Sydney'
];
})();
const frequencies: { value: Freq; label: string }[] = [
{ value: 'minutes', label: 'Every N minutes' },
{ value: 'hours', label: 'Every N hours' },
@@ -180,7 +207,11 @@
{#if freq !== 'once'}
<label>
<span class="muted">Time zone</span>
<input class="input" placeholder="UTC" bind:value={timeZone} />
<select class="select" bind:value={timeZone}>
{#each timeZones as tz (tz)}
<option value={tz}>{tz}</option>
{/each}
</select>
</label>
{/if}
@@ -4,21 +4,14 @@
import ScheduleCadenceEditor, {
type CadenceValue
} from '$lib/components/ScheduleCadenceEditor.svelte';
import type {
DeviceGroupDto,
DeviceDto,
ScriptTriggerDto,
ScriptTriggerType
} from '$lib/api/types';
import type { DeviceGroupDto, ScriptTriggerDto, ScriptTriggerType } from '$lib/api/types';
let {
scriptId,
groups,
devices = []
groups
}: {
scriptId: string;
groups: DeviceGroupDto[];
devices?: DeviceDto[];
} = $props();
let triggers = $state<ScriptTriggerDto[]>([]);
@@ -86,6 +79,11 @@
}
}
async function toggle(trigger: ScriptTriggerDto) {
await api.setTriggerEnabled(trigger.id, !trigger.enabled).catch(() => {});
await refresh();
}
async function remove(id: string) {
await api.deleteTrigger(id);
await refresh();
@@ -126,11 +124,6 @@
<option value={'group:' + group.id}>{group.name}</option>
{/each}
</optgroup>
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId}>{device.hostname}</option>
{/each}
</optgroup>
</select>
</label>
@@ -144,16 +137,23 @@
{:else}
<ul class="list">
{#each mine as trigger (trigger.id)}
<li>
<li class:off={!trigger.enabled}>
<div class="tinfo">
<span class="twhen">{whenLabel(trigger)}</span>
<span class="muted">→ {targetLabel(trigger)}</span>
{#if trigger.triggerType === 'scheduled' && trigger.nextRunUtc}
{#if !trigger.enabled}
<span class="pill">Disabled</span>
{:else if trigger.triggerType === 'scheduled' && trigger.nextRunUtc}
<span class="faint">· next {new Date(trigger.nextRunUtc).toLocaleString()}</span>
{/if}
{#if trigger.lastResult}<span class="faint">· {trigger.lastResult}</span>{/if}
</div>
<button class="btn danger tiny" onclick={() => remove(trigger.id)} aria-label="Remove trigger">✕</button>
<div class="tactions">
<button class="btn tiny" onclick={() => toggle(trigger)}>
{trigger.enabled ? 'Disable' : 'Enable'}
</button>
<button class="btn danger tiny" onclick={() => remove(trigger.id)} aria-label="Remove trigger">✕</button>
</div>
</li>
{/each}
</ul>
@@ -222,10 +222,30 @@
gap: 6px;
}
.tactions {
display: flex;
gap: 6px;
flex-shrink: 0;
}
.twhen {
font-weight: 500;
}
.list li.off {
opacity: 0.55;
}
.pill {
font-size: 10.5px;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 1px 7px;
border-radius: 999px;
border: 1px solid var(--border);
color: var(--text-muted);
}
.tiny {
padding: 3px 8px;
font-size: 11px;
+284 -406
View File
@@ -4,17 +4,15 @@
import { goto } from '$app/navigation';
import { api } from '$lib/api/client';
import type {
DeviceDto,
DeviceGroupDto,
FunctionModuleDto,
JobDto,
JobProgressPayload,
JobState,
ScriptParameter,
ScriptFileBinding,
SecretBinding
SecretBinding,
ExecutionSummaryDto,
ExecutionDetailDto,
ExecutionTargetDto
} from '$lib/api/types';
import { nats, type JobEvent } from '$lib/messaging/nats';
import { registerPowerShellCompletions } from '$lib/editor/powershell-completions';
import JobStateBadge from '$lib/components/JobStateBadge.svelte';
import ParameterSchemaEditor from '$lib/components/ParameterSchemaEditor.svelte';
@@ -38,33 +36,29 @@
let saving = $state(false);
let statusText = $state('');
let devices = $state<DeviceDto[]>([]);
let allGroups = $state<DeviceGroupDto[]>([]);
// Picker value ('device:<clientId>' or 'group:<groupId>') and the added set.
let targetKey = $state('');
let targets = $state<string[]>([]);
let history = $state<JobDto[]>([]);
// Run targets are groups only (multi-select); a fleet's device list is too
// long to pick from here — single-device runs live on the device page.
let selectedGroups = $state<string[]>([]);
let running = $state(false);
function addTarget() {
if (targetKey && !targets.includes(targetKey)) targets = [...targets, targetKey];
// Executions drill-in: list → a run's targets → one target's output.
let executions = $state<ExecutionSummaryDto[]>([]);
let currentRun = $state<ExecutionDetailDto | null>(null);
let currentTarget = $state<ExecutionTargetDto | null>(null);
let pollTimer: ReturnType<typeof setInterval> | null = null;
const terminalStates = ['succeeded', 'failed', 'cancelled', 'timedOut'];
function toggleGroup(id: string) {
selectedGroups = selectedGroups.includes(id)
? selectedGroups.filter((g) => g !== id)
: [...selectedGroups, id];
}
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() {
async function loadExecutions() {
if (isNew) return;
history = await api.jobs(undefined, 50, scriptId).catch(() => []);
executions = await api.scriptExecutions(scriptId).catch(() => []);
}
let parameters = $state<ScriptParameter[]>([]);
@@ -81,9 +75,7 @@
let intellisense = $state(true);
let completionDisposable: { dispose(): void } | null = null;
// Live run state (single-device run)
let job = $state<JobDto | null>(null);
let jobState = $state<JobState | null>(null);
// Output of the drilled-in target, fetched from stored job output.
let outputLines = $state<{ seq: number; stream: string; text: string }[]>([]);
let outputSearch = $state('');
let copiedOutput = $state(false);
@@ -97,14 +89,6 @@
copiedOutput = true;
setTimeout(() => (copiedOutput = false), 1400);
}
let progress = $state<JobProgressPayload | null>(null);
let unsubscribeJob: (() => void) | null = null;
// Live run state (group fan-out)
let groupJobs = $state<JobDto[]>([]);
let jobStates = $state<Record<string, JobState>>({});
let skippedOrphaned = $state<string[]>([]);
let focusJobId = $state<string | null>(null);
let editorHost: HTMLDivElement;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -195,19 +179,12 @@
editor.onDidChangeModelContent(() => (content = editor.getValue()));
applyIntellisense();
[devices, allGroups] = await Promise.all([api.devices(), api.groups().catch(() => [])]);
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();
allGroups = await api.groups().catch(() => []);
void loadExecutions();
})();
return () => {
unsubscribeJob?.();
stopPoll();
completionDisposable?.dispose();
editor?.dispose();
};
@@ -249,106 +226,96 @@
}
}
function appendOutput(payload: { sequence: number; stream: string; text: string }) {
outputLines = [
...outputLines,
{ seq: payload.sequence, stream: payload.stream, text: payload.text }
].slice(-2000);
}
/** Switches the output panel to one job of a group run. */
async function focusJob(jobId: string) {
focusJobId = jobId;
outputLines = [];
progress = null;
const stored = await api.jobOutput(jobId).catch(() => []);
if (focusJobId === jobId && outputLines.length === 0) {
outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text }));
}
}
async function run() {
async function runNow() {
const id = await save();
if (!id || targets.length === 0) return;
outputLines = [];
progress = null;
jobState = null;
job = null;
groupJobs = [];
jobStates = {};
skippedOrphaned = [];
focusJobId = null;
if (!id || selectedGroups.length === 0) return;
running = true;
statusText = '';
const args = paramInputs?.collect() ?? {};
// One or more targets: devices dispatch one job each, groups fan out
// per member. Everything lands in one per-device list below.
try {
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));
}
const result = await api.createGroupsJob(selectedGroups, id, args);
await loadExecutions();
if (result.skippedOrphaned.length > 0) {
statusText = `Skipped orphaned: ${result.skippedOrphaned.join(', ')}`;
}
groupJobs = runJobs;
skippedOrphaned = skipped;
for (const started of runJobs) {
jobStates[started.jobId] = started.state;
// Drill straight into the run we just started.
if (executions.length > 0) {
await openExecution(executions[0].runId);
}
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;
statusText = e instanceof Error ? e.message : 'Failed to start run.';
} finally {
running = false;
}
}
unsubscribeJob?.();
unsubscribeJob = nats.onJobEvent((jobId: string, event: JobEvent) => {
if (job && jobId === job.jobId) {
if (event.type === 'job.output') {
appendOutput(event.payload);
} else if (event.type === 'job.progress') {
progress = event.payload;
} else if (event.type === 'job.state') {
jobState = event.payload.state;
if (['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state)) {
progress = null;
}
}
return;
}
async function openExecution(runId: string) {
currentTarget = null;
outputLines = [];
currentRun = await api.execution(runId).catch(() => null);
schedulePoll();
}
if (jobId in jobStates) {
if (event.type === 'job.state') {
jobStates[jobId] = event.payload.state;
}
if (jobId === focusJobId) {
if (event.type === 'job.output') {
appendOutput(event.payload);
} else if (event.type === 'job.progress') {
progress = event.payload;
} else if (
event.type === 'job.state' &&
['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state)
) {
progress = null;
async function openTarget(target: ExecutionTargetDto) {
currentTarget = target;
outputSearch = '';
outputLines = [];
await loadOutput();
schedulePoll();
}
async function loadOutput() {
if (!currentTarget) return;
const records = await api.jobOutput(currentTarget.jobId).catch(() => []);
outputLines = records.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text }));
}
function backToExecutions() {
currentRun = null;
currentTarget = null;
stopPoll();
void loadExecutions();
}
function backToTargets() {
currentTarget = null;
outputLines = [];
if (currentRun) void openExecution(currentRun.runId);
}
function runActive(): boolean {
return currentRun?.targets.some((t) => !terminalStates.includes(t.state)) ?? false;
}
// Output is persisted, so the drill-in polls it (and the targets' states)
// while anything is still running, then stops.
function schedulePoll() {
stopPoll();
pollTimer = setInterval(async () => {
if (currentRun) {
const fresh = await api.execution(currentRun.runId).catch(() => null);
if (fresh) {
currentRun = fresh;
if (currentTarget) {
currentTarget =
fresh.targets.find((t) => t.jobId === currentTarget!.jobId) ?? currentTarget;
}
}
}
});
if (currentTarget) {
await loadOutput();
}
if (!runActive()) {
stopPoll();
}
}, 1600);
}
void refreshHistory();
function stopPoll() {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
}
async function remove() {
@@ -385,19 +352,6 @@
}
}
const terminal = ['succeeded', 'failed', 'cancelled', 'timedOut'];
const groupRunning = $derived(
groupJobs.some((g) => !terminal.includes(jobStates[g.jobId] ?? 'queued'))
);
const groupFinished = $derived(
groupJobs.filter((g) => terminal.includes(jobStates[g.jobId] ?? 'queued')).length
);
const running = $derived(
(jobState !== null && !terminal.includes(jobState)) || (groupJobs.length > 0 && groupRunning)
);
const focusHostname = $derived(
groupJobs.find((g) => g.jobId === focusJobId)?.hostname ?? null
);
</script>
<svelte:window
@@ -437,7 +391,11 @@
<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 || targets.length === 0 || running}>
<button
class="btn primary"
onclick={runNow}
disabled={saving || selectedGroups.length === 0 || running}
>
▶ Run
</button>
</div>
@@ -535,49 +493,28 @@
<div class="flow">
<section class="card section">
<h3>Targets</h3>
<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 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:'))}
<h3>Run</h3>
{#if allGroups.length === 0}
<p class="muted small">
Groups run on every non-orphaned member. Offline devices receive the job durably when
they reconnect.
No groups yet — create one under Groups, then run this script against it.
</p>
{/if}
{#if devices.length === 0}
<p class="muted">No devices enrolled yet.</p>
{:else}
<p class="muted small">
Select one or more groups. Each runs on every non-orphaned member; offline devices
receive the job when they reconnect.
</p>
<div class="grouppick">
{#each allGroups as group (group.id)}
<label class="grp" class:on={selectedGroups.includes(group.id)}>
<input
type="checkbox"
checked={selectedGroups.includes(group.id)}
onchange={() => toggleGroup(group.id)}
/>
{group.name} <span class="faint">({group.kind})</span>
</label>
{/each}
</div>
{/if}
{#if parameters.length > 0}
@@ -587,114 +524,98 @@
</section>
{#if !isNew && loaded}
<TriggersCard {scriptId} groups={allGroups} {devices} />
<TriggersCard {scriptId} groups={allGroups} />
{/if}
</div>
{#if groupJobs.length > 0}
<section class="card section run-wide">
<div class="job-head">
<h3>Run</h3>
<span class="muted small">{groupFinished}/{groupJobs.length} finished</span>
</div>
{#if skippedOrphaned.length > 0}
<p class="warn small">Skipped orphaned: {skippedOrphaned.join(', ')}</p>
{/if}
<ul class="group-jobs">
{#each groupJobs as groupJob (groupJob.jobId)}
<li>
<button
type="button"
class="group-job"
class:active={focusJobId === groupJob.jobId}
onclick={() => void focusJob(groupJob.jobId)}
>
<span class="host">{groupJob.hostname ?? groupJob.clientId}</span>
<JobStateBadge state={jobStates[groupJob.jobId] ?? 'queued'} />
</button>
</li>
{/each}
</ul>
</section>
{/if}
<section class="card section run-wide output-section">
<div class="job-head">
<h3>Output{focusHostname ? ` — ${focusHostname}` : ''}</h3>
{#if jobState}
<JobStateBadge state={jobState} />
{/if}
<div class="output-tools">
{#if outputLines.length > 0}
<input
class="input output-search"
type="search"
placeholder="Search output…"
bind:value={outputSearch}
aria-label="Search output"
/>
<button class="btn small" onclick={copyOutput}>{copiedOutput ? '✔ Copied' : '⧉ Copy'}</button>
{/if}
</div>
</div>
{#if progress}
<div class="progress-block pulse-in">
<div class="progress-label">
<span>{progress.activity}</span>
<span class="muted">{progress.statusDescription ?? ''}</span>
</div>
<div class="progress-track">
<div class="progress-fill" style="width: {progress.percentComplete ?? 0}%"></div>
</div>
<div class="progress-meta muted">
{progress.percentComplete ?? 0}%
{progress.secondsRemaining != null ? ` · ~${progress.secondsRemaining}s remaining` : ''}
</div>
</div>
{:else if running}
<div class="muted small waiting">Waiting for progress…</div>
{/if}
<div class="output mono">
{#if outputLines.length === 0}
<span class="faint">
{job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'}
</span>
{:else if filteredOutput.length === 0}
<span class="faint">No lines match “{outputSearch}”.</span>
{:else}
{#each filteredOutput as line (line.seq)}
<div class="output-line {line.stream}">{line.text}</div>
{/each}
{/if}
</div>
</section>
{#if !isNew}
<section class="card section run-wide">
<div class="job-head">
<h3>History</h3>
<button class="btn" onclick={refreshHistory}>↻ Refresh</button>
<h3 class="crumbs-h">
<button class="crumb" onclick={backToExecutions} disabled={!currentRun}>Executions</button>
{#if currentRun}
<span class="sep">›</span>
<button class="crumb" onclick={backToTargets} disabled={!currentTarget}>
{new Date(currentRun.startedUtc).toLocaleString()} ·
{currentRun.targets.length} target{currentRun.targets.length === 1 ? '' : 's'}
</button>
{/if}
{#if currentTarget}
<span class="sep">›</span>
<span class="crumb current">{currentTarget.hostname ?? currentTarget.clientId}</span>
{/if}
</h3>
{#if !currentRun}
<button class="btn" onclick={loadExecutions}>↻ Refresh</button>
{/if}
</div>
{#if history.length === 0}
<p class="muted small">No executions of this script yet.</p>
{:else}
{#if !currentRun}
<!-- Level 1: executions of this script -->
{#if executions.length === 0}
<p class="muted small">No executions yet. Select a group above and Run.</p>
{:else}
<table class="data">
<thead><tr><th>Started</th><th>By</th><th>Targets</th><th>Result</th></tr></thead>
<tbody>
{#each executions as ex (ex.runId)}
<tr class="clickable" onclick={() => openExecution(ex.runId)}>
<td class="muted">{new Date(ex.startedUtc).toLocaleString()}</td>
<td class="muted">{ex.requestedBy ?? '—'}</td>
<td>{ex.total}</td>
<td>
<span class="tally ok">{ex.succeeded}✓</span>
{#if ex.failed > 0}<span class="tally bad">{ex.failed}✗</span>{/if}
{#if ex.pending > 0}<span class="tally run">{ex.pending}…</span>{/if}
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
{:else if !currentTarget}
<!-- Level 2: the run's target devices -->
<table class="data">
<thead>
<tr><th>Started</th><th>Device</th><th>State</th><th>Exit</th></tr>
</thead>
<thead><tr><th>Device</th><th>State</th><th>Exit</th><th>Finished</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>
{#each currentRun.targets as t (t.jobId)}
<tr class="clickable" onclick={() => openTarget(t)}>
<td>{t.hostname ?? t.clientId}</td>
<td><JobStateBadge state={t.state} /></td>
<td class="muted">{t.exitCode ?? '—'}</td>
<td class="muted">{t.completedUtc ? new Date(t.completedUtc).toLocaleString() : '—'}</td>
</tr>
{/each}
</tbody>
</table>
{:else}
<!-- Level 3: one target's output — full width, searchable, line by line -->
<div class="output-tools">
<JobStateBadge state={currentTarget.state} />
{#if outputLines.length > 0}
<input
class="input output-search"
type="search"
placeholder="Search output…"
bind:value={outputSearch}
aria-label="Search output"
/>
<button class="btn small" onclick={copyOutput}>{copiedOutput ? '✔ Copied' : '⧉ Copy'}</button>
{/if}
</div>
<div class="output mono">
{#if outputLines.length === 0}
<span class="faint">
{terminalStates.includes(currentTarget.state) ? 'No output.' : 'Waiting for output…'}
</span>
{:else if filteredOutput.length === 0}
<span class="faint">No lines match “{outputSearch}”.</span>
{:else}
{#each filteredOutput as line (line.seq)}
<div class="output-line {line.stream}">{line.text}</div>
{/each}
{/if}
</div>
{/if}
</section>
{/if}
@@ -709,49 +630,84 @@
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;
}
.grouppick {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: var(--space-2);
}
.grp {
display: flex;
align-items: center;
gap: 6px;
border: 1px solid var(--border);
border-radius: 999px;
padding: 3px 12px;
font-size: 13px;
cursor: pointer;
}
.grp.on {
border-color: var(--accent);
background: var(--accent-soft);
}
.grp input {
accent-color: var(--accent);
}
.crumbs-h {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 2px;
}
.crumb {
background: none;
border: none;
padding: 0;
font: inherit;
color: var(--accent);
cursor: pointer;
}
.crumb:disabled {
color: var(--text);
cursor: default;
}
.crumb.current {
color: var(--text);
}
.sep {
color: var(--text-muted);
margin: 0 6px;
}
.tally {
font-size: 12px;
margin-right: 8px;
}
.tally.ok {
color: var(--success);
}
.tally.bad {
color: var(--danger);
}
.tally.run {
color: var(--text-muted);
}
.crumbs {
font-size: 12px;
color: var(--text-muted);
@@ -944,11 +900,6 @@
padding: var(--space-4);
}
.target {
width: 100%;
margin-top: var(--space-2);
}
.exec-values {
margin: var(--space-3) 0 var(--space-2);
border-top: 1px solid var(--border);
@@ -980,84 +931,10 @@
font-size: 12px;
}
.group-jobs {
list-style: none;
margin: var(--space-2) 0 0;
padding: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 6px;
}
.group-job {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
background: none;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 6px 10px;
font-size: 13px;
color: var(--text);
cursor: pointer;
}
.group-job.active {
border-color: var(--accent);
background: var(--accent-soft);
}
.group-job .host {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.warn {
color: var(--warning);
}
.small {
font-size: 12px;
}
.waiting {
margin-top: var(--space-2);
}
.progress-block {
margin-top: var(--space-3);
}
.progress-label {
display: flex;
justify-content: space-between;
font-size: 12.5px;
margin-bottom: 6px;
gap: var(--space-2);
}
.progress-track {
height: 8px;
border-radius: 999px;
background: var(--surface-muted);
overflow: hidden;
}
.progress-fill {
height: 100%;
border-radius: 999px;
background: var(--accent);
transition: width 0.4s ease;
}
.progress-meta {
font-size: 11.5px;
margin-top: 4px;
}
.output {
margin-top: var(--space-3);
background: var(--bg);
@@ -1071,9 +948,10 @@
line-height: 1.6;
}
/* Terminal-style: keep each line intact and scroll wide output horizontally
(e.g. ifconfig) rather than wrapping it into a block. */
.output-line {
white-space: pre-wrap;
overflow-wrap: anywhere;
white-space: pre;
}
.output-line.error {
+43
View File
@@ -111,6 +111,49 @@ public sealed class SelfSignedTlsTests : IDisposable
Assert.Equal(oldRoot, File.ReadAllText(Path.Combine(directory, "root.crt")));
}
[Fact]
public void EnsureChain_RenewsRootInPlaceWithSameKey_SoEnrolledAgentsKeepValidating()
{
// Root life above the intermediate's renewal margin (so only the root is
// due to renew), but below its own renewal margin (so it renews now).
var lifetimes = TlsLifetimes.Default with
{
Root = TimeSpan.FromDays(300),
RootRenewalMargin = TimeSpan.FromDays(400),
};
var manager = new SelfSignedTlsManager(Settings, lifetimes);
manager.EnsureChain(NullLogger.Instance);
using var originalRoot = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "root.crt"));
var originalRootThumbprint = originalRoot.Thumbprint;
var originalRootKey = originalRoot.GetECDsaPublicKey()!.ExportSubjectPublicKeyInfo();
var originalIntermediate = File.ReadAllText(Path.Combine(directory, "intermediate.crt"));
var originalLeaf = manager.ServerCertificate!.Thumbprint;
var changed = manager.EnsureChain(NullLogger.Instance);
Assert.True(changed);
using var renewedRoot = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "root.crt"));
// The root certificate is a new one (extended validity) ...
Assert.NotEqual(originalRootThumbprint, renewedRoot.Thumbprint);
// ... but the same key, and the intermediate + leaf are untouched.
Assert.Equal(originalRootKey, renewedRoot.GetECDsaPublicKey()!.ExportSubjectPublicKeyInfo());
Assert.Equal(originalIntermediate, File.ReadAllText(Path.Combine(directory, "intermediate.crt")));
Assert.Equal(originalLeaf, manager.ServerCertificate!.Thumbprint);
// The crux: an agent that still trusts only the ORIGINAL root validates the
// current leaf, because the chain signs to the same key — no break, no
// re-enrollment when the root renews.
using var intermediate = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "intermediate.crt"));
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.CustomTrustStore.Add(originalRoot);
chain.ChainPolicy.ExtraStore.Add(intermediate);
Assert.True(chain.Build(manager.ServerCertificate!), "leaf must still validate against the original root");
}
[Fact]
public void EnsureChain_RotatedRootCascadesToTheWholeChain()
{