diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs
index c505c3a..81ea0ee 100644
--- a/src/Agent/Configuration/AgentConfiguration.cs
+++ b/src/Agent/Configuration/AgentConfiguration.cs
@@ -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);
+
+ ///
+ /// 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.
+ ///
+ 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;
+ }
+ }
}
/// Loads effective configuration using deterministic precedence.
diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs
index 79ea6e7..56377c6 100644
--- a/src/Agent/Enrollment/EnrollmentService.cs
+++ b/src/Agent/Enrollment/EnrollmentService.cs
@@ -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(JsonDefaults.Options, cancellationToken);
}
- var result = await response.Content.ReadFromJsonAsync(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 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ private static Func 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);
+ };
+
///
/// Computes the deterministic client id, verifies it against the cached
/// runtime value and refreshes the cache.
diff --git a/src/Agent/Enrollment/ServerTrust.cs b/src/Agent/Enrollment/ServerTrust.cs
index a8f32d8..e18ad3e 100644
--- a/src/Agent/Enrollment/ServerTrust.cs
+++ b/src/Agent/Enrollment/ServerTrust.cs
@@ -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;
+/// Outcome of probing and (maybe) installing the server's self-signed CA.
+public enum ServerCaStatus
+{
+ /// 404 — the server is not self-signed (a real certificate is in front).
+ NotSelfSigned,
+
+ /// The fetched CA matched the pinned fingerprint and was installed.
+ Installed,
+
+ /// A chain was fetched but it did not match the pinned fingerprint — not installed.
+ FingerprintMismatch,
+
+ /// The CA could not be fetched or parsed.
+ FetchFailed,
+}
+
///
/// 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
{
///
- /// 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 (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).
///
- public static async Task 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()
+ .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);
+ }
+
+ ///
+ /// 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.
+ ///
+ public static async Task 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;
}
diff --git a/src/Agent/Service/CaRefreshService.cs b/src/Agent/Service/CaRefreshService.cs
index 412fd4b..d22f637 100644
--- a/src/Agent/Service/CaRefreshService.cs
+++ b/src/Agent/Service/CaRefreshService.cs
@@ -6,14 +6,15 @@ using Microsoft.Extensions.Logging;
namespace Agent.Service;
///
-/// 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.
///
public sealed class CaRefreshService(
AgentConfigurationLoader loader, ILogger 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);
}
}
diff --git a/src/Agent/Shell/UnixPtySession.cs b/src/Agent/Shell/UnixPtySession.cs
index e544d59..7129966 100644
--- a/src/Agent/Shell/UnixPtySession.cs
+++ b/src/Agent/Shell/UnixPtySession.cs
@@ -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
/// ; input is written with
/// .
+///
+/// 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.
///
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 data, CancellationToken cancellationToken)
+ public Task WriteAsync(ReadOnlyMemory 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 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
diff --git a/src/Backend/Api/BootstrapTokenEndpoints.cs b/src/Backend/Api/BootstrapTokenEndpoints.cs
index f1b0a46..d08b879 100644
--- a/src/Backend/Api/BootstrapTokenEndpoints.cs
+++ b/src/Backend/Api/BootstrapTokenEndpoints.cs
@@ -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()?.CaFingerprint();
+ if (caFingerprint is not null)
+ {
+ token += "." + caFingerprint;
+ }
+
var actor = context.User.Identity?.Name;
var entity = new BootstrapTokenEntity
diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs
index 3b3b5e2..0241bc0 100644
--- a/src/Backend/Data/AppDbContext.cs
+++ b/src/Backend/Data/AppDbContext.cs
@@ -104,6 +104,7 @@ public class AppDbContext(DbContextOptions 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();
});
diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs
index 5b751c7..c10889d 100644
--- a/src/Backend/Data/Entities.cs
+++ b/src/Backend/Data/Entities.cs
@@ -241,6 +241,14 @@ public sealed class FunctionModuleEntity
public sealed class JobEntity
{
public Guid JobId { get; set; }
+
+ ///
+ /// 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.
+ ///
+ public Guid? RunId { get; set; }
+
public required string ClientId { get; set; }
public Guid ScriptId { get; set; }
public required string ScriptName { get; set; }
diff --git a/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs
new file mode 100644
index 0000000..0265ff6
--- /dev/null
+++ b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs
@@ -0,0 +1,733 @@
+//
+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
+ {
+ ///
+ 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("Key")
+ .HasColumnType("text");
+
+ b.Property("IsSecret")
+ .HasColumnType("boolean");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Value")
+ .HasColumnType("text");
+
+ b.HasKey("Key");
+
+ b.ToTable("AppSettings", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("Action")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Actor")
+ .HasColumnType("text");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("ClientId")
+ .HasColumnType("text");
+
+ b.Property("Detail")
+ .HasColumnType("text");
+
+ b.Property("RemoteIp")
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedBy")
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ExpiresUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("MaxUses")
+ .HasColumnType("integer");
+
+ b.Property("Note")
+ .HasColumnType("text");
+
+ b.Property("Revoked")
+ .HasColumnType("boolean");
+
+ b.Property("TokenHash")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Uses")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TokenHash")
+ .IsUnique();
+
+ b.ToTable("BootstrapTokens", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
+ {
+ b.Property("ClientId")
+ .HasColumnType("text");
+
+ b.Property("AgentVersion")
+ .HasColumnType("text");
+
+ b.Property("EnrolledUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("EnrollmentId")
+ .HasColumnType("uuid");
+
+ b.Property("Hostname")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("IpAddressesJson")
+ .HasColumnType("text");
+
+ b.Property("IsOrphaned")
+ .HasColumnType("boolean");
+
+ b.Property("LastSeenUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Manufacturer")
+ .HasColumnType("text");
+
+ b.Property("Model")
+ .HasColumnType("text");
+
+ b.Property("NkeyPublic")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OrphanedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("OsCaption")
+ .HasColumnType("text");
+
+ b.Property("OsVersion")
+ .HasColumnType("text");
+
+ b.Property("PublicIp")
+ .HasColumnType("text");
+
+ b.Property("ReadyUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("TagsJson")
+ .HasColumnType("text");
+
+ b.HasKey("ClientId");
+
+ b.HasIndex("Hostname");
+
+ b.ToTable("Devices", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Description")
+ .HasColumnType("text");
+
+ b.Property("Kind")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("RulesJson")
+ .HasColumnType("text");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("AddedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("GroupId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("GroupId", "ClientId")
+ .IsUnique();
+
+ b.ToTable("DeviceGroupMembers", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
+ {
+ b.Property("ClientId")
+ .HasColumnType("text");
+
+ b.Property("ReportJson")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("ClientId");
+
+ b.ToTable("DeviceInventory", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Content")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Description")
+ .HasColumnType("text");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("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("JobId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CompletedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ExitCode")
+ .HasColumnType("integer");
+
+ b.Property("OutputSummary")
+ .HasColumnType("text");
+
+ b.Property("RequestedBy")
+ .HasColumnType("text");
+
+ b.Property("RunId")
+ .HasColumnType("uuid");
+
+ b.Property("ScriptId")
+ .HasColumnType("uuid");
+
+ b.Property("ScriptName")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("StartedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("JobId")
+ .HasColumnType("uuid");
+
+ b.Property("Sequence")
+ .HasColumnType("bigint");
+
+ b.Property("Stream")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Text")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Authority")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("OidcProviders", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.RoleEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Description")
+ .HasColumnType("text");
+
+ b.Property("DeviceScopeGroupIdsJson")
+ .HasColumnType("text");
+
+ b.Property("IsSystem")
+ .HasColumnType("boolean");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OidcClaimValuesJson")
+ .HasColumnType("text");
+
+ b.Property("PermissionsJson")
+ .HasColumnType("text");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Content")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CreatedBy")
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Description")
+ .HasColumnType("text");
+
+ b.Property("FileBindingsJson")
+ .HasColumnType("text");
+
+ b.Property("FunctionModuleIdsJson")
+ .HasColumnType("text");
+
+ b.Property("Language")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("ParametersJson")
+ .HasColumnType("text");
+
+ b.Property("SecretBindingsJson")
+ .HasColumnType("text");
+
+ b.Property("SecretsVariableName")
+ .HasColumnType("text");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ArgumentsJson")
+ .HasColumnType("text");
+
+ b.Property("ClientId")
+ .HasColumnType("text");
+
+ b.Property("CreatedBy")
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CronExpression")
+ .HasColumnType("text");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("GroupId")
+ .HasColumnType("uuid");
+
+ b.Property("LastResult")
+ .HasColumnType("text");
+
+ b.Property("LastRunUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("NextRunUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("OncePerDevice")
+ .HasColumnType("boolean");
+
+ b.Property("RunOnceUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ScriptId")
+ .HasColumnType("uuid");
+
+ b.Property("TimeZoneId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("FiredUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("JobId")
+ .HasColumnType("uuid");
+
+ b.Property("TriggerId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TriggerId", "ClientId")
+ .IsUnique();
+
+ b.ToTable("ScriptTriggerRuns", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ConfigProtected")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Kind")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("text");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CloseReason")
+ .HasColumnType("text");
+
+ b.Property("ClosedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("RequestedBy")
+ .HasColumnType("text");
+
+ b.Property("State")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ClientId");
+
+ b.ToTable("ShellSessions", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.UserEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AuthProvider")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DisplayName")
+ .HasColumnType("text");
+
+ b.Property("ExternalId")
+ .HasColumnType("text");
+
+ b.Property("LastLoginUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("MustChangePassword")
+ .HasColumnType("boolean");
+
+ b.Property("PasswordHash")
+ .HasColumnType("text");
+
+ b.Property("Role")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("RoleId")
+ .HasColumnType("uuid");
+
+ b.Property("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
+ }
+ }
+}
diff --git a/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs
new file mode 100644
index 0000000..14e7d70
--- /dev/null
+++ b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs
@@ -0,0 +1,38 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Backend.Data.Migrations.Postgres
+{
+ ///
+ public partial class AddJobRunId : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "RunId",
+ table: "Jobs",
+ type: "uuid",
+ nullable: true);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Jobs_ScriptId_RunId",
+ table: "Jobs",
+ columns: new[] { "ScriptId", "RunId" });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_Jobs_ScriptId_RunId",
+ table: "Jobs");
+
+ migrationBuilder.DropColumn(
+ name: "RunId",
+ table: "Jobs");
+ }
+ }
+}
diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs
index 6ca627d..624cffa 100644
--- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs
+++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs
@@ -321,6 +321,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property("RequestedBy")
.HasColumnType("text");
+ b.Property("RunId")
+ .HasColumnType("uuid");
+
b.Property("ScriptId")
.HasColumnType("uuid");
@@ -341,6 +344,8 @@ namespace Backend.Data.Migrations.Postgres
b.HasIndex("CreatedUtc");
+ b.HasIndex("ScriptId", "RunId");
+
b.ToTable("Jobs", (string)null);
});
diff --git a/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs
new file mode 100644
index 0000000..db3e231
--- /dev/null
+++ b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs
@@ -0,0 +1,733 @@
+//
+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
+ {
+ ///
+ 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("Key")
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("IsSecret")
+ .HasColumnType("bit");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("Value")
+ .HasColumnType("nvarchar(max)");
+
+ b.HasKey("Key");
+
+ b.ToTable("AppSettings", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"));
+
+ b.Property("Action")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Actor")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ClientId")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Detail")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("RemoteIp")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("TimestampUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TimestampUtc");
+
+ b.ToTable("AuditEvents", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("CreatedBy")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("ExpiresUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("MaxUses")
+ .HasColumnType("int");
+
+ b.Property("Note")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Revoked")
+ .HasColumnType("bit");
+
+ b.Property("TokenHash")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("Uses")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TokenHash")
+ .IsUnique();
+
+ b.ToTable("BootstrapTokens", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
+ {
+ b.Property("ClientId")
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("AgentVersion")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("EnrolledUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("EnrollmentId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("Hostname")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("IpAddressesJson")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("IsOrphaned")
+ .HasColumnType("bit");
+
+ b.Property("LastSeenUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("Manufacturer")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Model")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("NkeyPublic")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("OrphanedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("OsCaption")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("OsVersion")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("PublicIp")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ReadyUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("TagsJson")
+ .HasColumnType("nvarchar(max)");
+
+ b.HasKey("ClientId");
+
+ b.HasIndex("Hostname");
+
+ b.ToTable("Devices", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("Description")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Kind")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("RulesJson")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name")
+ .IsUnique();
+
+ b.ToTable("DeviceGroups", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"));
+
+ b.Property("AddedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("GroupId")
+ .HasColumnType("uniqueidentifier");
+
+ b.HasKey("Id");
+
+ b.HasIndex("GroupId", "ClientId")
+ .IsUnique();
+
+ b.ToTable("DeviceGroupMembers", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
+ {
+ b.Property("ClientId")
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("ReportJson")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.HasKey("ClientId");
+
+ b.ToTable("DeviceInventory", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("Content")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("Description")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UpdatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name");
+
+ b.ToTable("FunctionModules", (string)null);
+ });
+
+ modelBuilder.Entity("Backend.Data.JobEntity", b =>
+ {
+ b.Property("JobId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("ClientId")
+ .IsRequired()
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("CompletedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("CreatedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("ExitCode")
+ .HasColumnType("int");
+
+ b.Property("OutputSummary")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("RequestedBy")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("RunId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("ScriptId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("ScriptName")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("StartedUtc")
+ .HasColumnType("datetimeoffset");
+
+ b.Property("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("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"));
+
+ b.Property("JobId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("Sequence")
+ .HasColumnType("bigint");
+
+ b.Property("Stream")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Text")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property