diff --git a/README.md b/README.md index 4ded054..44b4de9 100644 --- a/README.md +++ b/README.md @@ -871,62 +871,55 @@ matches and never throws. ![Group rule builder](docs/screenshots/groups-rule-builder.png) -**Triggers** belong to scripts (the Triggers card on the script editor): run -the script automatically on a device lifecycle event, scoped to a group or -all devices: +**Triggers** belong to scripts (the Triggers card on the script's page). A +trigger fires the script automatically — on a device lifecycle event, or on a +schedule — and each trigger carries **its own target**: all devices, a group +(members resolved at fire time), or a single device. | Trigger | Fires when | |---------|-----------| | `onRegistration` | A device completes enrollment | | `onAgentReady` | The agent is connected *and* its durable command consumer is bound — genuinely ready for jobs | +| `scheduled` | A cadence comes due — one-shot or recurring | -Triggers default to **once per device** (recorded durably), and triggered runs +Lifecycle triggers fire **once per device** (recorded durably). Triggered runs use the normal job pipeline, so they carry the script's Functions prelude and typed parameters and appear alongside manual runs. --- -## Group runs and schedules +## Group runs and scheduled triggers -The script editor's target selector offers **devices and groups**. A group run +The script's target selector offers **devices and groups**. A group run creates one job per non-orphaned member — offline members receive theirs durably when they reconnect — and the side panel tracks every job live, with click-to-focus output per device. Orphaned members are reported as skipped. -**Schedules are reusable cadence objects** — a schedule defines *when* -(one-shot or recurring), nothing else. Scripts honor a schedule through -**assignments**: script + schedule + target (device or group, members resolved -at fire time) + stored execution values. One "Nightly at 1am" cadence can -drive any number of scripts, and pausing the cadence pauses everything -attached to it. Four starter cadences are seeded on first boot (hourly, daily -1 AM, weekdays 7 AM, weekly Sunday 2 AM — UTC) while the table is empty. +**Scheduled triggers carry their cadence inline.** A `scheduled` trigger stores +*when* (one-shot or recurring), its *target* (a device, a group whose members +resolve at fire time, or all devices), and the execution values to run with — +no separate schedule object to manage. The cadence builder leads with friendly selectors — *every N minutes/hours*, *daily/weekly/monthly at a time* with weekday chips — and compiles them to cron internally; a raw cron field exists only under **Advanced**. Whatever is -chosen is auto-described in plain English and grounded by a server-computed -preview of the next occurrences. +chosen is auto-described in plain English. -![Schedule builder](docs/screenshots/script-schedule.png) - -The **Schedules** nav page manages the cadence objects and shows what uses -each one; the script editor's Schedules panel attaches/detaches them: - -![Schedules overview](docs/screenshots/schedules.png) +![Scheduled trigger builder](docs/screenshots/script-schedule.png) Semantics worth knowing: -- Expressions evaluate in the schedule's **time zone** (default UTC), so +- Expressions evaluate in the trigger's **time zone** (default UTC), so "daily at 01:00" tracks DST; storage and comparison are UTC. -- The worker sweeps every 30 s; recurrence advances from *now* after each +- The worker sweeps regularly; recurrence advances from *now* after each firing, so server downtime causes **at most one late firing**, never a storm. -- One-shot cadences disable themselves after firing every assignment once. -- Each assignment records its own **last result** (jobs queued, or the error — - e.g. a vault failure) without stalling the cadence, and jobs show - `schedule:` as their requester. -- Deleting a script or a schedule removes its assignments with it. -- Execution values captured when a schedule is attached are used for every firing; - secret bindings resolve fresh server-side at each fire time. +- One-shot triggers disable themselves after firing. +- Each trigger records its own **last result** (jobs queued, or the error — + e.g. a vault failure) without stalling, and triggered jobs are attributed to + `trigger:`. +- Deleting a script removes its triggers with it. +- Execution values captured on the trigger are used for every firing; secret + bindings resolve fresh server-side at each fire time. --- diff --git a/docs/screenshots/add-device.png b/docs/screenshots/add-device.png index 6c1e8ca..3199e7d 100644 Binary files a/docs/screenshots/add-device.png and b/docs/screenshots/add-device.png differ diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png index 4ceef89..2fe55c0 100644 Binary files a/docs/screenshots/dashboard-light.png and b/docs/screenshots/dashboard-light.png differ diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png index cde1910..1d1cf97 100644 Binary files a/docs/screenshots/dashboard.png and b/docs/screenshots/dashboard.png differ diff --git a/docs/screenshots/device-detail.png b/docs/screenshots/device-detail.png index f5537a6..c7cf471 100644 Binary files a/docs/screenshots/device-detail.png and b/docs/screenshots/device-detail.png differ diff --git a/docs/screenshots/device-hardware.png b/docs/screenshots/device-hardware.png index 49d1d49..cd6fbcc 100644 Binary files a/docs/screenshots/device-hardware.png and b/docs/screenshots/device-hardware.png differ diff --git a/docs/screenshots/device-public-ip.png b/docs/screenshots/device-public-ip.png index d88918c..bc6ee5d 100644 Binary files a/docs/screenshots/device-public-ip.png and b/docs/screenshots/device-public-ip.png differ diff --git a/docs/screenshots/devices.png b/docs/screenshots/devices.png index e535f0d..8bd69ba 100644 Binary files a/docs/screenshots/devices.png and b/docs/screenshots/devices.png differ diff --git a/docs/screenshots/groups-static-members.png b/docs/screenshots/groups-static-members.png index ea9e674..3847a24 100644 Binary files a/docs/screenshots/groups-static-members.png and b/docs/screenshots/groups-static-members.png differ diff --git a/docs/screenshots/groups.png b/docs/screenshots/groups.png index f0fbf06..6733f74 100644 Binary files a/docs/screenshots/groups.png and b/docs/screenshots/groups.png differ diff --git a/docs/screenshots/schedules.png b/docs/screenshots/schedules.png deleted file mode 100644 index d8ad18c..0000000 Binary files a/docs/screenshots/schedules.png and /dev/null differ diff --git a/docs/screenshots/script-execution.png b/docs/screenshots/script-execution.png index b9f5da6..75fade5 100644 Binary files a/docs/screenshots/script-execution.png and b/docs/screenshots/script-execution.png differ diff --git a/docs/screenshots/script-schedule.png b/docs/screenshots/script-schedule.png index 5058090..5c7c1a3 100644 Binary files a/docs/screenshots/script-schedule.png and b/docs/screenshots/script-schedule.png differ diff --git a/docs/screenshots/script-schedules-card.png b/docs/screenshots/script-schedules-card.png deleted file mode 100644 index 2ce7fc5..0000000 Binary files a/docs/screenshots/script-schedules-card.png and /dev/null differ diff --git a/docs/screenshots/settings-install-command.png b/docs/screenshots/settings-install-command.png index b356dbe..f2ad7ab 100644 Binary files a/docs/screenshots/settings-install-command.png and b/docs/screenshots/settings-install-command.png differ diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs index 8e3e824..c505c3a 100644 --- a/src/Agent/Configuration/AgentConfiguration.cs +++ b/src/Agent/Configuration/AgentConfiguration.cs @@ -46,7 +46,7 @@ public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allow InventoryInterval = ResolveTimeSpan(AgentConfigurationKeys.InventoryInterval, ProtocolDefaults.DefaultInventoryInterval), ReconnectMinDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMinDelay, ProtocolDefaults.ReconnectMinDelay), ReconnectMaxDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMaxDelay, ProtocolDefaults.ReconnectMaxDelay), - AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: false), + AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: true), AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true), TlsSkipVerify = ResolveBool(AgentConfigurationKeys.TlsSkipVerify, defaultValue: false), ProxyUrl = ResolveString(AgentConfigurationKeys.ProxyUrl, AgentConfigurationKeys.EnvironmentNames.ProxyUrl, null), diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs index 819389a..b1822e0 100644 --- a/src/Agent/Configuration/AgentConfigurationKeys.cs +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -9,6 +9,7 @@ public static class AgentConfigurationKeys public const string InventoryInterval = "InventoryInterval"; public const string ReconnectMinDelay = "ReconnectMinDelay"; public const string ReconnectMaxDelay = "ReconnectMaxDelay"; + /// DWORD: remote shell. On by default; set 0 to opt out. public const string AllowRemoteShell = "AllowRemoteShell"; public const string AllowScriptExecution = "AllowScriptExecution"; diff --git a/src/Agent/Inventory/InventoryCollector.cs b/src/Agent/Inventory/InventoryCollector.cs index 6d2ab72..cb7d637 100644 --- a/src/Agent/Inventory/InventoryCollector.cs +++ b/src/Agent/Inventory/InventoryCollector.cs @@ -27,6 +27,17 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : string? biosVersion = null; QueryFirst("SELECT SMBIOSBIOSVersion FROM Win32_BIOS", obj => biosVersion = obj["SMBIOSBIOSVersion"] as string); + string? boardManufacturer = null; + string? boardProduct = null; + QueryFirst("SELECT Manufacturer, Product FROM Win32_BaseBoard", obj => + { + boardManufacturer = obj["Manufacturer"] as string; + boardProduct = obj["Product"] as string; + }); + + string? systemUuid = null; + QueryFirst("SELECT UUID FROM Win32_ComputerSystemProduct", obj => systemUuid = obj["UUID"] as string); + var identity = new InventoryIdentity( ClientId: clientId, Hostname: Environment.MachineName, @@ -37,7 +48,10 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : BaseboardSerial: hardware.BaseboardSerialNumber?.Trim(), DomainOrWorkgroup: domain, PartOfDomain: partOfDomain, - SystemType: systemType); + SystemType: systemType, + SystemUuid: systemUuid?.Trim(), + BaseboardManufacturer: boardManufacturer?.Trim(), + BaseboardProduct: boardProduct?.Trim()); var os = CollectOs(); var cpu = CollectCpu(); @@ -60,28 +74,88 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : private static InventoryOs CollectOs() { - string? caption = null; + string? rawCaption = null; string? version = null; string? build = null; string? architecture = null; DateTimeOffset? installDate = null; DateTimeOffset? lastBoot = null; - string? edition = null; + int? productTypeCode = null; QueryFirst( - "SELECT Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime, OperatingSystemSKU FROM Win32_OperatingSystem", + "SELECT Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime, ProductType FROM Win32_OperatingSystem", obj => { - caption = (obj["Caption"] as string)?.Trim(); + rawCaption = (obj["Caption"] as string)?.Trim(); version = obj["Version"] as string; build = obj["BuildNumber"] as string; architecture = obj["OSArchitecture"] as string; installDate = ConvertCimDate(obj["InstallDate"] as string); lastBoot = ConvertCimDate(obj["LastBootUpTime"] as string); - edition = obj["OperatingSystemSKU"]?.ToString(); + productTypeCode = obj["ProductType"] is { } pt ? Convert.ToInt32(pt) : null; }); - return new InventoryOs(caption, version, build, architecture, installDate, lastBoot, edition); + // Win32_OperatingSystem.Version is major.minor.build (e.g. 10.0.22631); + // the UBR (Update Build Revision) lives in the registry. Append it so + // the version reads like 10.0.22631.4317 — otherwise leave it as-is. + var ubr = ReadCurrentVersionValue("UBR"); + if (!string.IsNullOrWhiteSpace(version) && !string.IsNullOrWhiteSpace(ubr)) + { + version = $"{version}.{ubr}"; + } + + // "Microsoft Windows 11 Pro" -> caption "Windows 11", edition "Pro". + var (caption, edition) = ParseWindowsCaption(rawCaption); + var productType = productTypeCode switch + { + 1 => "Workstation", + 2 => "Domain Controller", + 3 => "Server", + _ => null, + }; + + return new InventoryOs( + caption, version, build, architecture, installDate, lastBoot, edition, + ReleaseVersion: ReadCurrentVersionValue("DisplayVersion"), + ProductType: productType); + } + + /// + /// Splits the Win32 caption into the base OS name and the edition: + /// "Microsoft Windows 11 Pro" → ("Windows 11", "Pro"); + /// "Microsoft Windows Server 2022 Standard" → ("Windows Server 2022", "Standard"). + /// + private static (string? Caption, string? Edition) ParseWindowsCaption(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return (raw, null); + } + + var cleaned = System.Text.RegularExpressions.Regex.Replace(raw, @"^Microsoft\s+", "").Trim(); + var match = System.Text.RegularExpressions.Regex.Match( + cleaned, @"^(Windows(?:\s+Server)?\s+\S+)\s*(.*)$"); + if (!match.Success) + { + return (cleaned, null); + } + + var edition = match.Groups[2].Value.Trim(); + return (match.Groups[1].Value.Trim(), string.IsNullOrEmpty(edition) ? null : edition); + } + + private static string? ReadCurrentVersionValue(string name) + { + try + { + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( + @"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); + return key?.GetValue(name)?.ToString(); + } + catch (Exception) + { + return null; + } } private static InventoryCpu CollectCpu() diff --git a/src/Agent/Inventory/UnixInventoryCollector.cs b/src/Agent/Inventory/UnixInventoryCollector.cs index 64274e1..e233389 100644 --- a/src/Agent/Inventory/UnixInventoryCollector.cs +++ b/src/Agent/Inventory/UnixInventoryCollector.cs @@ -27,8 +27,12 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc BaseboardSerial: hardware.BaseboardSerialNumber?.Trim(), DomainOrWorkgroup: null, PartOfDomain: false, - SystemType: System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString()); + SystemType: System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString(), + SystemUuid: ReadTrimmed("/sys/class/dmi/id/product_uuid"), + BaseboardManufacturer: ReadTrimmed("/sys/class/dmi/id/board_vendor"), + BaseboardProduct: ReadTrimmed("/sys/class/dmi/id/board_name")); + var role = DetectEdition(); // Server / Workstation var os = new InventoryOs( Caption: osName, Version: osVersion, @@ -36,7 +40,8 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc Architecture: System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString(), InstallDateUtc: null, LastBootUtc: ReadLastBoot(), - Edition: DetectEdition()); + Edition: role, + ProductType: role); return new InventoryReport( Identity: identity, diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs index 57751f8..3b3b5e2 100644 --- a/src/Backend/Data/AppDbContext.cs +++ b/src/Backend/Data/AppDbContext.cs @@ -24,8 +24,6 @@ public class AppDbContext(DbContextOptions options) : DbContext(op public DbSet ScriptTriggerRuns => Set(); public DbSet AppSettings => Set(); public DbSet SecretsProviders => Set(); - public DbSet Schedules => Set(); - public DbSet ScriptSchedules => Set(); /// /// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores @@ -159,6 +157,8 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.ToTable("ScriptTriggers"); entity.HasKey(e => e.Id); entity.HasIndex(e => e.TriggerType); + // The schedule sweep queries due scheduled triggers by next-run. + entity.HasIndex(e => e.NextRunUtc); entity.Property(e => e.TriggerType).HasConversion(); }); @@ -182,24 +182,5 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasIndex(e => e.Name).IsUnique(); }); - modelBuilder.Entity(entity => - { - entity.ToTable("Schedules"); - entity.HasKey(e => e.Id); - entity.HasIndex(e => e.Name).IsUnique(); - entity.HasIndex(e => e.NextRunUtc); - }); - - modelBuilder.Entity(entity => - { - entity.ToTable("ScriptSchedules"); - entity.HasKey(e => e.Id); - entity.HasIndex(e => e.ScheduleId); - entity.HasIndex(e => e.ScriptId); - entity.HasOne().WithMany() - .HasForeignKey(e => e.ScheduleId).OnDelete(DeleteBehavior.Cascade); - entity.HasOne().WithMany() - .HasForeignKey(e => e.ScriptId).OnDelete(DeleteBehavior.Cascade); - }); } } diff --git a/src/Backend/Data/DefaultSeeder.cs b/src/Backend/Data/DefaultSeeder.cs index ad09bfc..0d30515 100644 --- a/src/Backend/Data/DefaultSeeder.cs +++ b/src/Backend/Data/DefaultSeeder.cs @@ -1,4 +1,3 @@ -using Backend.Jobs; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Models; using Shared.Contracts.Serialization; @@ -6,16 +5,15 @@ using Shared.Contracts.Serialization; namespace Backend.Data; /// -/// First-boot defaults every deployment gets: platform dynamic groups and a -/// few common schedule cadences. Each family seeds only while its table is -/// empty, so operator edits and deletions are never fought. +/// First-boot defaults every deployment gets: the platform dynamic groups. +/// Seeds only while the table is empty, so operator edits and deletions are +/// never fought. /// public static class DefaultSeeder { public static async Task SeedAsync(AppDbContext db, CancellationToken cancellationToken) { await SeedGroupsAsync(db, cancellationToken); - await SeedSchedulesAsync(db, cancellationToken); } private static async Task SeedGroupsAsync(AppDbContext db, CancellationToken cancellationToken) @@ -44,45 +42,15 @@ public static class DefaultSeeder await db.SaveChangesAsync(cancellationToken); } - private static async Task SeedSchedulesAsync(AppDbContext db, CancellationToken cancellationToken) - { - if (await db.Schedules.AnyAsync(cancellationToken)) - { - return; - } - - var now = DateTimeOffset.UtcNow; - foreach (var (name, cron) in new[] - { - ("Hourly", "0 * * * *"), - ("Daily at 1:00 AM", "0 1 * * *"), - ("Weekdays at 7:00 AM", "0 7 * * MON-FRI"), - ("Weekly · Sunday 2:00 AM", "0 2 * * SUN"), - }) - { - db.Schedules.Add(new ScheduleEntity - { - Id = Guid.NewGuid(), - Name = name, - CronExpression = cron, - TimeZoneId = "UTC", - Enabled = true, - NextRunUtc = ScheduleCron.NextOccurrence(cron, "UTC", now), - CreatedUtc = now, - UpdatedUtc = now, - CreatedBy = "system", - UpdatedBy = "system", - }); - } - - await db.SaveChangesAsync(cancellationToken); - } private static IEnumerable<(string Name, string Description, GroupRuleSet Rules)> PlatformGroups() { static GroupRuleSet Set(params RuleCondition[] conditions) => new(RuleCombine.And, [new RuleGroup(RuleCombine.And, conditions)]); + yield return ("Windows", "All Windows devices.", + Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"))); + yield return ("Windows Servers", "Every Windows Server edition.", Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"), new RuleCondition("os.caption", RuleOperator.Contains, "Server"))); diff --git a/src/Backend/Data/DevSeeder.cs b/src/Backend/Data/DevSeeder.cs index 08b2ffc..60f067c 100644 --- a/src/Backend/Data/DevSeeder.cs +++ b/src/Backend/Data/DevSeeder.cs @@ -19,18 +19,19 @@ public static class DevSeeder var now = DateTimeOffset.UtcNow; - var samples = new[] + var samples = new (string Hostname, string Mfr, string Model, string Os, string? Edition, + string ProductType, string? Release, TimeSpan SeenAgo, string[] Ips, string[] Tags)[] { - ("PC-ENG-014", "Dell Inc.", "OptiPlex 7090", "Windows 11 Pro", TimeSpan.FromSeconds(12), new[] { "10.20.4.14" }, new[] { "engineering", "workstation" }), - ("PC-FIN-003", "LENOVO", "ThinkCentre M90q", "Windows 11 Enterprise", TimeSpan.FromMinutes(3), new[] { "10.20.6.3" }, new[] { "finance", "workstation" }), - ("LAB-VM-27", "Microsoft Corporation", "Virtual Machine", "Windows Server 2022", TimeSpan.FromMinutes(20), new[] { "10.30.9.27" }, new[] { "lab", "server" }), - ("web-prod-01", "QEMU", "Standard PC (Q35)", "Ubuntu 22.04.4 LTS", TimeSpan.FromSeconds(28), new[] { "10.40.1.11" }, new[] { "production", "server" }), - ("build-arm-02", "Raspberry Pi Foundation", "Raspberry Pi 5", "Debian GNU/Linux 12", TimeSpan.FromMinutes(6), new[] { "10.40.2.2" }, new[] { "ci", "server" }), - ("MBP-DESIGN-9", "Apple Inc.", "MacBookPro18,3", "macOS 14.5 Sonoma", TimeSpan.FromMinutes(1), new[] { "10.20.8.9" }, new[] { "design", "workstation" }), + ("PC-ENG-014", "Dell Inc.", "OptiPlex 7090", "Windows 11", "Pro", "Workstation", "23H2", TimeSpan.FromSeconds(12), ["10.20.4.14"], ["engineering", "workstation"]), + ("PC-FIN-003", "LENOVO", "ThinkCentre M90q", "Windows 11", "Enterprise", "Workstation", "23H2", TimeSpan.FromMinutes(3), ["10.20.6.3"], ["finance", "workstation"]), + ("LAB-VM-27", "Microsoft Corporation", "Virtual Machine", "Windows Server 2022", "Standard", "Server", "21H2", TimeSpan.FromMinutes(20), ["10.30.9.27"], ["lab", "server"]), + ("web-prod-01", "QEMU", "Standard PC (Q35)", "Ubuntu 22.04.4 LTS", null, "Server", null, TimeSpan.FromSeconds(28), ["10.40.1.11"], ["production", "server"]), + ("build-arm-02", "Raspberry Pi Foundation", "Raspberry Pi 5", "Debian GNU/Linux 12", null, "Server", null, TimeSpan.FromMinutes(6), ["10.40.2.2"], ["ci", "server"]), + ("MBP-DESIGN-9", "Apple Inc.", "MacBookPro18,3", "macOS 14.5 Sonoma", null, "Workstation", null, TimeSpan.FromMinutes(1), ["10.20.8.9"], ["design", "workstation"]), }; var i = 0; - foreach (var (hostname, mfr, model, os, seenAgo, ips, tags) in samples) + foreach (var (hostname, mfr, model, os, edition, productType, release, seenAgo, ips, tags) in samples) { var clientId = (Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"))[..64]; var device = new DeviceEntity @@ -53,8 +54,10 @@ public static class DevSeeder db.Devices.Add(device); var report = new InventoryReport( - new InventoryIdentity(clientId, hostname, mfr, model, $"SN{1000 + i}", "1.14.3", $"BB{2000 + i}", "GRACE", true, "x64-based PC"), - new InventoryOs(os, "10.0.26100", "26100", "64-bit", now.AddMonths(-6), now - seenAgo - TimeSpan.FromHours(9), "Professional"), + new InventoryIdentity(clientId, hostname, mfr, model, $"SN{1000 + i}", "1.14.3", $"BB{2000 + i}", "GRACE", true, "x64-based PC", + SystemUuid: $"4C4C4544-{i:D4}-0010-8039-B4C04F303{i}33", BaseboardManufacturer: mfr, BaseboardProduct: model), + new InventoryOs(os, "10.0.26100.1742", "26100", "64-bit", now.AddMonths(-6), now - seenAgo - TimeSpan.FromHours(9), edition, + ReleaseVersion: release, ProductType: productType), new InventoryCpu("Intel(R) Core(TM) i7-11700 @ 2.50GHz", 16, 8), [new InventoryMemoryModule("DIMM A", 17_179_869_184, "Samsung", 3200), new InventoryMemoryModule("DIMM B", 17_179_869_184, "Samsung", 3200)], 34_359_738_368, diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs index c1c5594..5b751c7 100644 --- a/src/Backend/Data/Entities.cs +++ b/src/Backend/Data/Entities.cs @@ -120,11 +120,35 @@ public sealed class ScriptTriggerEntity { public Guid Id { get; set; } public Guid ScriptId { get; set; } + + // Target: a single device (ClientId), a group (GroupId), or all devices + // when both are null. Event triggers historically used GroupId; scheduled + // triggers can target either. + public string? ClientId { get; set; } public Guid? GroupId { get; set; } + public ScriptTriggerType TriggerType { get; set; } public bool Enabled { get; set; } = true; - /// Run at most once per device (default) or every time the event fires. + + /// + /// Event triggers (OnRegistration/OnAgentReady) run at most once per device. + /// Not applicable to Scheduled triggers. No longer operator-configurable. + /// public bool OncePerDevice { get; set; } = true; + + // Scheduled-trigger timing (unused for event types). + /// 5-field cron for a recurring schedule; null for one-shot. + public string? CronExpression { get; set; } + /// Fire time for a one-shot schedule; null for recurring. + public DateTimeOffset? RunOnceUtc { get; set; } + public string TimeZoneId { get; set; } = "UTC"; + public DateTimeOffset? NextRunUtc { get; set; } + public DateTimeOffset? LastRunUtc { get; set; } + /// Argument values captured for scheduled runs (JSON). + public string? ArgumentsJson { get; set; } + /// Human-readable outcome of the last scheduled firing. + public string? LastResult { get; set; } + public DateTimeOffset CreatedUtc { get; set; } public string? CreatedBy { get; set; } } @@ -170,52 +194,6 @@ public sealed class ScriptEntity public string? UpdatedBy { get; set; } } -/// -/// A reusable cadence object: one-shot () or recurring -/// (, evaluated in ). -/// Schedules carry no script or target — objects (scripts) honor a schedule -/// through associations. -/// -public sealed class ScheduleEntity -{ - public Guid Id { get; set; } - public required string Name { get; set; } - /// 5-field cron for recurring schedules; null for one-shot. - public string? CronExpression { get; set; } - /// Fire time for one-shot schedules; null for recurring. - public DateTimeOffset? RunOnceUtc { get; set; } - public string TimeZoneId { get; set; } = "UTC"; - public bool Enabled { get; set; } = true; - public DateTimeOffset? NextRunUtc { get; set; } - public DateTimeOffset? LastRunUtc { get; set; } - public DateTimeOffset CreatedUtc { get; set; } - public DateTimeOffset UpdatedUtc { get; set; } - public string? CreatedBy { get; set; } - public string? UpdatedBy { get; set; } -} - -/// -/// A script honoring a schedule: when the schedule fires, this script runs -/// against exactly one of / -/// (group members resolved at fire time) with the stored argument values. -/// -public sealed class ScriptScheduleEntity -{ - public Guid Id { get; set; } - public required Guid ScheduleId { get; set; } - public required Guid ScriptId { get; set; } - public string? ClientId { get; set; } - public Guid? GroupId { get; set; } - /// Argument values captured when the association was saved. - public string? ArgumentsJson { get; set; } - public bool Enabled { get; set; } = true; - public DateTimeOffset? LastRunUtc { get; set; } - /// Human-readable outcome of the last firing (job counts or the error). - public string? LastResult { get; set; } - public DateTimeOffset CreatedUtc { get; set; } - public string? CreatedBy { get; set; } -} - /// /// A configured external secrets store (e.g. Infisical). Connection settings /// are a Data Protection-encrypted JSON blob; only the backend ever decrypts diff --git a/src/Backend/Data/Migrations/Postgres/20260810114752_UnifyTriggers.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260810114752_UnifyTriggers.Designer.cs new file mode 100644 index 0000000..e4da03c --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810114752_UnifyTriggers.Designer.cs @@ -0,0 +1,839 @@ +// +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("20260810114752_UnifyTriggers")] + partial class UnifyTriggers + { + /// + 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("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.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.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + 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("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (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.ScriptScheduleEntity", 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("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduleId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .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/20260810114752_UnifyTriggers.cs b/src/Backend/Data/Migrations/Postgres/20260810114752_UnifyTriggers.cs new file mode 100644 index 0000000..90258f6 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810114752_UnifyTriggers.cs @@ -0,0 +1,109 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class UnifyTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ArgumentsJson", + table: "ScriptTriggers", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "ClientId", + table: "ScriptTriggers", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "CronExpression", + table: "ScriptTriggers", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastResult", + table: "ScriptTriggers", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastRunUtc", + table: "ScriptTriggers", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "NextRunUtc", + table: "ScriptTriggers", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "RunOnceUtc", + table: "ScriptTriggers", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "TimeZoneId", + table: "ScriptTriggers", + type: "text", + nullable: false, + defaultValue: ""); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers", + column: "NextRunUtc"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ArgumentsJson", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ClientId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "CronExpression", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastResult", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "RunOnceUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "TimeZoneId", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260810120704_RemoveSchedules.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260810120704_RemoveSchedules.Designer.cs new file mode 100644 index 0000000..caefd95 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810120704_RemoveSchedules.Designer.cs @@ -0,0 +1,728 @@ +// +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("20260810120704_RemoveSchedules")] + partial class RemoveSchedules + { + /// + 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("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.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/20260810120704_RemoveSchedules.cs b/src/Backend/Data/Migrations/Postgres/20260810120704_RemoveSchedules.cs new file mode 100644 index 0000000..37b70d1 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810120704_RemoveSchedules.cs @@ -0,0 +1,101 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class RemoveSchedules : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CronExpression = table.Column(type: "text", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + Name = table.Column(type: "text", nullable: false), + NextRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + RunOnceUtc = table.Column(type: "timestamp with time zone", nullable: true), + TimeZoneId = table.Column(type: "text", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ArgumentsJson = table.Column(type: "text", nullable: true), + ClientId = table.Column(type: "text", nullable: true), + CreatedBy = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + GroupId = table.Column(type: "uuid", nullable: true), + LastResult = table.Column(type: "text", nullable: true), + LastRunUtc = table.Column(type: "timestamp with time zone", nullable: true), + ScheduleId = table.Column(type: "uuid", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs index a741e51..6ca627d 100644 --- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -445,57 +445,6 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("Roles", (string)null); }); - modelBuilder.Entity("Backend.Data.ScheduleEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - 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("LastRunUtc") - .HasColumnType("timestamp with time zone"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("NextRunUtc") - .HasColumnType("timestamp with time zone"); - - b.Property("RunOnceUtc") - .HasColumnType("timestamp with time zone"); - - b.Property("TimeZoneId") - .IsRequired() - .HasColumnType("text"); - - b.Property("UpdatedBy") - .HasColumnType("text"); - - b.Property("UpdatedUtc") - .HasColumnType("timestamp with time zone"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.HasIndex("NextRunUtc"); - - b.ToTable("Schedules", (string)null); - }); - modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -551,7 +500,7 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("Scripts", (string)null); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() @@ -569,6 +518,9 @@ namespace Backend.Data.Migrations.Postgres b.Property("CreatedUtc") .HasColumnType("timestamp with time zone"); + b.Property("CronExpression") + .HasColumnType("text"); + b.Property("Enabled") .HasColumnType("boolean"); @@ -581,51 +533,30 @@ namespace Backend.Data.Migrations.Postgres b.Property("LastRunUtc") .HasColumnType("timestamp with time zone"); - b.Property("ScheduleId") - .HasColumnType("uuid"); - - b.Property("ScriptId") - .HasColumnType("uuid"); - - b.HasKey("Id"); - - b.HasIndex("ScheduleId"); - - b.HasIndex("ScriptId"); - - b.ToTable("ScriptSchedules", (string)null); - }); - - modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("CreatedBy") - .HasColumnType("text"); - - b.Property("CreatedUtc") + b.Property("NextRunUtc") .HasColumnType("timestamp with time zone"); - b.Property("Enabled") - .HasColumnType("boolean"); - - b.Property("GroupId") - .HasColumnType("uuid"); - 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); @@ -784,21 +715,6 @@ namespace Backend.Data.Migrations.Postgres .IsRequired(); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => - { - b.HasOne("Backend.Data.ScheduleEntity", null) - .WithMany() - .HasForeignKey("ScheduleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Backend.Data.ScriptEntity", null) - .WithMany() - .HasForeignKey("ScriptId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/SqlServer/20260810114757_UnifyTriggers.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260810114757_UnifyTriggers.Designer.cs new file mode 100644 index 0000000..0118452 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810114757_UnifyTriggers.Designer.cs @@ -0,0 +1,839 @@ +// +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("20260810114757_UnifyTriggers")] + partial class UnifyTriggers + { + /// + 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("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.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("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScheduleId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .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") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .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/SqlServer/20260810114757_UnifyTriggers.cs b/src/Backend/Data/Migrations/SqlServer/20260810114757_UnifyTriggers.cs new file mode 100644 index 0000000..5aa0747 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810114757_UnifyTriggers.cs @@ -0,0 +1,109 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class UnifyTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ArgumentsJson", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "ClientId", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "CronExpression", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastResult", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastRunUtc", + table: "ScriptTriggers", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "NextRunUtc", + table: "ScriptTriggers", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "RunOnceUtc", + table: "ScriptTriggers", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "TimeZoneId", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: false, + defaultValue: ""); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers", + column: "NextRunUtc"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ArgumentsJson", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ClientId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "CronExpression", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastResult", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "RunOnceUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "TimeZoneId", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.Designer.cs new file mode 100644 index 0000000..494cd33 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.Designer.cs @@ -0,0 +1,728 @@ +// +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("20260810120710_RemoveSchedules")] + partial class RemoveSchedules + { + /// + 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("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.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("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .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") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("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 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.cs b/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.cs new file mode 100644 index 0000000..7384c02 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810120710_RemoveSchedules.cs @@ -0,0 +1,101 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class RemoveSchedules : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CronExpression = table.Column(type: "nvarchar(max)", nullable: true), + Enabled = table.Column(type: "bit", nullable: false), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + Name = table.Column(type: "nvarchar(450)", nullable: false), + NextRunUtc = table.Column(type: "datetimeoffset", nullable: true), + RunOnceUtc = table.Column(type: "datetimeoffset", nullable: true), + TimeZoneId = table.Column(type: "nvarchar(max)", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ArgumentsJson = table.Column(type: "nvarchar(max)", nullable: true), + ClientId = table.Column(type: "nvarchar(max)", nullable: true), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + GroupId = table.Column(type: "uniqueidentifier", nullable: true), + LastResult = table.Column(type: "nvarchar(max)", nullable: true), + LastRunUtc = table.Column(type: "datetimeoffset", nullable: true), + ScheduleId = table.Column(type: "uniqueidentifier", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs index e37f31b..de0d8a1 100644 --- a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -445,57 +445,6 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("Roles", (string)null); }); - modelBuilder.Entity("Backend.Data.ScheduleEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uniqueidentifier"); - - b.Property("CreatedBy") - .HasColumnType("nvarchar(max)"); - - b.Property("CreatedUtc") - .HasColumnType("datetimeoffset"); - - b.Property("CronExpression") - .HasColumnType("nvarchar(max)"); - - b.Property("Enabled") - .HasColumnType("bit"); - - b.Property("LastRunUtc") - .HasColumnType("datetimeoffset"); - - b.Property("Name") - .IsRequired() - .HasColumnType("nvarchar(450)"); - - b.Property("NextRunUtc") - .HasColumnType("datetimeoffset"); - - b.Property("RunOnceUtc") - .HasColumnType("datetimeoffset"); - - b.Property("TimeZoneId") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("UpdatedBy") - .HasColumnType("nvarchar(max)"); - - b.Property("UpdatedUtc") - .HasColumnType("datetimeoffset"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.HasIndex("NextRunUtc"); - - b.ToTable("Schedules", (string)null); - }); - modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -551,7 +500,7 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("Scripts", (string)null); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() @@ -569,6 +518,9 @@ namespace Backend.Data.Migrations.SqlServer b.Property("CreatedUtc") .HasColumnType("datetimeoffset"); + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + b.Property("Enabled") .HasColumnType("bit"); @@ -581,51 +533,30 @@ namespace Backend.Data.Migrations.SqlServer b.Property("LastRunUtc") .HasColumnType("datetimeoffset"); - b.Property("ScheduleId") - .HasColumnType("uniqueidentifier"); - - b.Property("ScriptId") - .HasColumnType("uniqueidentifier"); - - b.HasKey("Id"); - - b.HasIndex("ScheduleId"); - - b.HasIndex("ScriptId"); - - b.ToTable("ScriptSchedules", (string)null); - }); - - modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uniqueidentifier"); - - b.Property("CreatedBy") - .HasColumnType("nvarchar(max)"); - - b.Property("CreatedUtc") + b.Property("NextRunUtc") .HasColumnType("datetimeoffset"); - b.Property("Enabled") - .HasColumnType("bit"); - - b.Property("GroupId") - .HasColumnType("uniqueidentifier"); - b.Property("OncePerDevice") .HasColumnType("bit"); + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + b.Property("ScriptId") .HasColumnType("uniqueidentifier"); + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + b.Property("TriggerType") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); + b.HasIndex("NextRunUtc"); + b.HasIndex("TriggerType"); b.ToTable("ScriptTriggers", (string)null); @@ -784,21 +715,6 @@ namespace Backend.Data.Migrations.SqlServer .IsRequired(); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => - { - b.HasOne("Backend.Data.ScheduleEntity", null) - .WithMany() - .HasForeignKey("ScheduleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Backend.Data.ScriptEntity", null) - .WithMany() - .HasForeignKey("ScriptId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/Sqlite/20260810114748_UnifyTriggers.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260810114748_UnifyTriggers.Designer.cs new file mode 100644 index 0000000..c6b285b --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810114748_UnifyTriggers.Designer.cs @@ -0,0 +1,826 @@ +// +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("20260810114748_UnifyTriggers")] + partial class UnifyTriggers + { + /// + 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("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + 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("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("NextRunUtc"); + + b.ToTable("Schedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("ScheduleId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId"); + + b.HasIndex("ScriptId"); + + b.ToTable("ScriptSchedules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + 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("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + 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.ScriptScheduleEntity", b => + { + b.HasOne("Backend.Data.ScheduleEntity", null) + .WithMany() + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.ScriptEntity", null) + .WithMany() + .HasForeignKey("ScriptId") + .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/Sqlite/20260810114748_UnifyTriggers.cs b/src/Backend/Data/Migrations/Sqlite/20260810114748_UnifyTriggers.cs new file mode 100644 index 0000000..4722f43 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810114748_UnifyTriggers.cs @@ -0,0 +1,108 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class UnifyTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ArgumentsJson", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "ClientId", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "CronExpression", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastResult", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastRunUtc", + table: "ScriptTriggers", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "NextRunUtc", + table: "ScriptTriggers", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "RunOnceUtc", + table: "ScriptTriggers", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "TimeZoneId", + table: "ScriptTriggers", + type: "TEXT", + nullable: false, + defaultValue: ""); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers", + column: "NextRunUtc"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_ScriptTriggers_NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ArgumentsJson", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ClientId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "CronExpression", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastResult", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "LastRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "NextRunUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "RunOnceUtc", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "TimeZoneId", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260810120658_RemoveSchedules.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260810120658_RemoveSchedules.Designer.cs new file mode 100644 index 0000000..7d2d189 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810120658_RemoveSchedules.Designer.cs @@ -0,0 +1,715 @@ +// +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("20260810120658_RemoveSchedules")] + partial class RemoveSchedules + { + /// + 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("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + 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("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + 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("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + 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("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + 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/Sqlite/20260810120658_RemoveSchedules.cs b/src/Backend/Data/Migrations/Sqlite/20260810120658_RemoveSchedules.cs new file mode 100644 index 0000000..e1b36ab --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810120658_RemoveSchedules.cs @@ -0,0 +1,101 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class RemoveSchedules : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScriptSchedules"); + + migrationBuilder.DropTable( + name: "Schedules"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Schedules", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + CronExpression = table.Column(type: "TEXT", nullable: true), + Enabled = table.Column(type: "INTEGER", nullable: false), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + Name = table.Column(type: "TEXT", nullable: false), + NextRunUtc = table.Column(type: "INTEGER", nullable: true), + RunOnceUtc = table.Column(type: "INTEGER", nullable: true), + TimeZoneId = table.Column(type: "TEXT", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Schedules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptSchedules", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ArgumentsJson = table.Column(type: "TEXT", nullable: true), + ClientId = table.Column(type: "TEXT", nullable: true), + CreatedBy = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + GroupId = table.Column(type: "TEXT", nullable: true), + LastResult = table.Column(type: "TEXT", nullable: true), + LastRunUtc = table.Column(type: "INTEGER", nullable: true), + ScheduleId = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptSchedules", x => x.Id); + table.ForeignKey( + name: "FK_ScriptSchedules_Schedules_ScheduleId", + column: x => x.ScheduleId, + principalTable: "Schedules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ScriptSchedules_Scripts_ScriptId", + column: x => x.ScriptId, + principalTable: "Scripts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_Name", + table: "Schedules", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Schedules_NextRunUtc", + table: "Schedules", + column: "NextRunUtc"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScheduleId", + table: "ScriptSchedules", + column: "ScheduleId"); + + migrationBuilder.CreateIndex( + name: "IX_ScriptSchedules_ScriptId", + table: "ScriptSchedules", + column: "ScriptId"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs index 4b2788d..b3ac62a 100644 --- a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -434,57 +434,6 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("Roles", (string)null); }); - modelBuilder.Entity("Backend.Data.ScheduleEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedBy") - .HasColumnType("TEXT"); - - b.Property("CreatedUtc") - .HasColumnType("INTEGER"); - - b.Property("CronExpression") - .HasColumnType("TEXT"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("LastRunUtc") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("NextRunUtc") - .HasColumnType("INTEGER"); - - b.Property("RunOnceUtc") - .HasColumnType("INTEGER"); - - b.Property("TimeZoneId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("UpdatedBy") - .HasColumnType("TEXT"); - - b.Property("UpdatedUtc") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.HasIndex("NextRunUtc"); - - b.ToTable("Schedules", (string)null); - }); - modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -540,7 +489,7 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("Scripts", (string)null); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() @@ -558,6 +507,9 @@ namespace Backend.Data.Migrations.Sqlite b.Property("CreatedUtc") .HasColumnType("INTEGER"); + b.Property("CronExpression") + .HasColumnType("TEXT"); + b.Property("Enabled") .HasColumnType("INTEGER"); @@ -570,51 +522,30 @@ namespace Backend.Data.Migrations.Sqlite b.Property("LastRunUtc") .HasColumnType("INTEGER"); - b.Property("ScheduleId") - .HasColumnType("TEXT"); - - b.Property("ScriptId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ScheduleId"); - - b.HasIndex("ScriptId"); - - b.ToTable("ScriptSchedules", (string)null); - }); - - modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedBy") - .HasColumnType("TEXT"); - - b.Property("CreatedUtc") + b.Property("NextRunUtc") .HasColumnType("INTEGER"); - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("GroupId") - .HasColumnType("TEXT"); - b.Property("OncePerDevice") .HasColumnType("INTEGER"); + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + b.Property("ScriptId") .HasColumnType("TEXT"); + 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); @@ -771,21 +702,6 @@ namespace Backend.Data.Migrations.Sqlite .IsRequired(); }); - modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b => - { - b.HasOne("Backend.Data.ScheduleEntity", null) - .WithMany() - .HasForeignKey("ScheduleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Backend.Data.ScriptEntity", null) - .WithMany() - .HasForeignKey("ScriptId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs index 006d211..69b494b 100644 --- a/src/Backend/Enrollment/InstallEndpoints.cs +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -115,13 +115,16 @@ public static class InstallEndpoints private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration) => Backend.Proxy.PublicUrl.Resolve(context, configuration); - // Covers both PowerShell generations: 7+ ignores ServicePointManager - // (iwr/irm ride HttpClient and need -SkipCertificateCheck, applied here - // as a wildcard default so the whole script inherits it), while 5.1 - // needs the global callback. - private const string PsSkipVerify = - "if ($PSVersionTable.PSVersion.Major -ge 6) { $PSDefaultParameterValues['*:SkipCertificateCheck'] = $true } " + - "else { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } }"; + // The package download uses System.Net.WebClient — far faster than + // Invoke-WebRequest in Windows PowerShell, and it honors ServicePointManager + // in both 5.1 and 7. Enable TLS 1.2 first: 5.1 (as launched by the Run box, + // -NoProfile) defaults to TLS 1.0/1.1 and fails the handshake against a + // modern edge. For a direct self-signed download, also accept the cert. + private const string PsDownloadTls = + "[System.Net.ServicePointManager]::SecurityProtocol = " + + "[System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12"; + private const string PsAcceptCert = + "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }"; // NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell. // selfSigned: the server serves its managed self-signed chain directly, so @@ -155,12 +158,15 @@ public static class InstallEndpoints $ErrorActionPreference = 'Stop' $install = { Write-Host 'Installing ExecuteR Agent...' - {{(skipDownloadVerify ? PsSkipVerify : "")}} + {{PsDownloadTls}} + {{(skipDownloadVerify ? PsAcceptCert : "")}} $server = '{{baseUrl}}' $token = '{{token}}' $msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi') try { - Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $msi -UseBasicParsing + $wc = New-Object System.Net.WebClient + $wc.DownloadFile('{{packageUrl}}', $msi) + $wc.Dispose() $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") $p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" } @@ -179,7 +185,10 @@ public static class InstallEndpoints /// agent zip, unpacks to /opt/executer/agent, configures enrollment via /// the agent's own CLI and registers the systemd unit / launchd daemon. /// - private static string BuildUnixScript(string baseUrl, string token, string os, bool skipDownloadVerify) => $$""" + // ReplaceLineEndings("\n"): the .cs source is checked out with CRLF on + // Windows, but a bash script with CRLF fails hard when piped to bash + // (`set -euo pipefail\r` -> ": invalid option namepefail"). Force LF. + private static string BuildUnixScript(string baseUrl, string token, string os, bool skipDownloadVerify) => ($$""" #!/usr/bin/env bash set -euo pipefail if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi @@ -206,19 +215,22 @@ public static class InstallEndpoints "$dest/executer-agent" configure --url "$server" --token "$token" "$dest/executer-agent" initialize echo 'ExecuteR Agent installed. It will enroll and start automatically.' - """; + """).ReplaceLineEndings("\n"); private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify) => $$""" $ErrorActionPreference = 'Stop' $install = { Write-Host 'Installing ExecuteR Agent (portable)...' - {{(skipDownloadVerify ? PsSkipVerify : "")}} + {{PsDownloadTls}} + {{(skipDownloadVerify ? PsAcceptCert : "")}} $server = '{{baseUrl}}' $token = '{{token}}' $dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent' $zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip') try { - Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $zip -UseBasicParsing + $wc = New-Object System.Net.WebClient + $wc.DownloadFile('{{packageUrl}}', $zip) + $wc.Dispose() New-Item -ItemType Directory -Force -Path $dest | Out-Null Expand-Archive -Path $zip -DestinationPath $dest -Force $exe = Join-Path $dest 'Agent.exe' diff --git a/src/Backend/Groups/ScriptTriggerService.cs b/src/Backend/Groups/ScriptTriggerService.cs index 5b0d271..dcc445d 100644 --- a/src/Backend/Groups/ScriptTriggerService.cs +++ b/src/Backend/Groups/ScriptTriggerService.cs @@ -41,6 +41,12 @@ public sealed class ScriptTriggerService( { try { + // Single-device target: only fire for that device. + if (trigger.ClientId is { } targetClient && targetClient != clientId) + { + continue; + } + if (trigger.OncePerDevice && await db.ScriptTriggerRuns.AnyAsync( r => r.TriggerId == trigger.Id && r.ClientId == clientId, cancellationToken)) @@ -48,7 +54,9 @@ public sealed class ScriptTriggerService( continue; } - if (!await groups.IsMemberAsync(trigger.GroupId, clientId, cancellationToken)) + // Group target (or all devices when both target fields are null). + if (trigger.ClientId is null + && !await groups.IsMemberAsync(trigger.GroupId, clientId, cancellationToken)) { continue; } diff --git a/src/Backend/Groups/TriggerEndpoints.cs b/src/Backend/Groups/TriggerEndpoints.cs index e282c58..e714f0a 100644 --- a/src/Backend/Groups/TriggerEndpoints.cs +++ b/src/Backend/Groups/TriggerEndpoints.cs @@ -1,7 +1,10 @@ using Backend.Auth; using Backend.Data; +using Backend.Jobs; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; namespace Backend.Groups; @@ -17,16 +20,22 @@ public static class TriggerEndpoints private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) { var triggers = await db.ScriptTriggers.AsNoTracking() - .OrderBy(t => t.TriggerType) + .OrderBy(t => t.ScriptId).ThenBy(t => t.TriggerType) .ToListAsync(cancellationToken); var scriptNames = await db.Scripts.AsNoTracking().ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken); var groupNames = await db.DeviceGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken); + var hostnames = await db.Devices.AsNoTracking().ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); return Results.Ok(triggers.Select(t => new ScriptTriggerDto( t.Id, t.ScriptId, scriptNames.GetValueOrDefault(t.ScriptId, "(deleted script)"), - t.GroupId, t.GroupId is null ? "All devices" : groupNames.GetValueOrDefault(t.GroupId.Value, "(deleted group)"), - t.TriggerType, t.Enabled, t.OncePerDevice, t.CreatedUtc)).ToList()); + t.GroupId, + t.GroupId is null ? null : groupNames.GetValueOrDefault(t.GroupId.Value, "(deleted group)"), + t.ClientId, + t.ClientId is null ? null : hostnames.GetValueOrDefault(t.ClientId, t.ClientId), + t.TriggerType, t.Enabled, + t.CronExpression, t.RunOnceUtc, t.TimeZoneId, t.NextRunUtc, t.LastRunUtc, t.LastResult, + t.CreatedUtc)).ToList()); } private static async Task CreateAsync( @@ -37,24 +46,64 @@ public static class TriggerEndpoints return Results.NotFound(new { error = "Script not found." }); } + if (request.GroupId is not null && request.ClientId is not null) + { + return Results.BadRequest(new { error = "A trigger targets a group OR a device, not both." }); + } + if (request.GroupId is not null && !await db.DeviceGroups.AnyAsync(g => g.Id == request.GroupId, cancellationToken)) { return Results.NotFound(new { error = "Group not found." }); } + if (request.ClientId is not null + && !await db.Devices.AnyAsync(d => d.ClientId == request.ClientId, cancellationToken)) + { + return Results.NotFound(new { error = "Device not found." }); + } + var entity = new ScriptTriggerEntity { Id = Guid.NewGuid(), ScriptId = request.ScriptId, GroupId = request.GroupId, + ClientId = request.ClientId, TriggerType = request.TriggerType, Enabled = request.Enabled, - OncePerDevice = request.OncePerDevice, + TimeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId!, + ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null, CreatedUtc = DateTimeOffset.UtcNow, CreatedBy = context.User.Identity?.Name, }; + if (request.TriggerType == ScriptTriggerType.Scheduled) + { + // Recurring (cron) or one-shot (runOnce); compute the first run. + if (!string.IsNullOrWhiteSpace(request.CronExpression)) + { + try + { + entity.CronExpression = request.CronExpression; + entity.NextRunUtc = ScheduleCron.NextOccurrence( + request.CronExpression!, entity.TimeZoneId, DateTimeOffset.UtcNow); + } + catch (Exception ex) + { + return Results.BadRequest(new { error = $"Invalid cron expression: {ex.Message}" }); + } + } + else if (request.RunOnceUtc is { } runOnce) + { + entity.RunOnceUtc = runOnce; + entity.NextRunUtc = runOnce; + } + else + { + return Results.BadRequest(new { error = "A scheduled trigger needs a cron expression or a one-shot time." }); + } + } + db.ScriptTriggers.Add(entity); await db.SaveChangesAsync(cancellationToken); return Results.Created(ApiRoutes.For.Trigger(entity.Id), new { id = entity.Id }); diff --git a/src/Backend/Jobs/ScheduleEndpoints.cs b/src/Backend/Jobs/ScheduleEndpoints.cs deleted file mode 100644 index 1808827..0000000 --- a/src/Backend/Jobs/ScheduleEndpoints.cs +++ /dev/null @@ -1,400 +0,0 @@ -using Backend.Auth; -using Backend.Data; -using Backend.Security; -using Microsoft.EntityFrameworkCore; -using Shared.Contracts.Api; -using Shared.Contracts.Serialization; - -namespace Backend.Jobs; - -/// -/// Schedules are reusable cadence objects; scripts honor them through -/// assignments (script + target + stored run values). The worker fires every -/// enabled assignment when its schedule comes due. -/// -public static class ScheduleEndpoints -{ - public static void Map(WebApplication app) - { - app.MapGet(ApiRoutes.Schedules, ListAsync).RequirePermission(Permissions.AutomationView); - app.MapPost(ApiRoutes.Schedules, CreateAsync).RequirePermission(Permissions.AutomationManage); - app.MapPut(ApiRoutes.Schedule, UpdateAsync).RequirePermission(Permissions.AutomationManage); - app.MapDelete(ApiRoutes.Schedule, DeleteAsync).RequirePermission(Permissions.AutomationManage); - app.MapPost(ApiRoutes.SchedulePreview, Preview).RequirePermission(Permissions.AutomationManage); - - app.MapGet(ApiRoutes.ScheduleAssignments, ListAssignmentsAsync).RequirePermission(Permissions.AutomationView); - app.MapPost(ApiRoutes.ScheduleAssignments, CreateAssignmentAsync).RequirePermission(Permissions.AutomationManage); - app.MapPut(ApiRoutes.ScheduleAssignment, UpdateAssignmentAsync).RequirePermission(Permissions.AutomationManage); - app.MapDelete(ApiRoutes.ScheduleAssignment, DeleteAssignmentAsync).RequirePermission(Permissions.AutomationManage); - } - - // ── Schedule objects ───────────────────────────────────────────────── - - private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) - { - var schedules = await db.Schedules.AsNoTracking() - .OrderBy(s => s.NextRunUtc == null).ThenBy(s => s.NextRunUtc) - .ToListAsync(cancellationToken); - var assignments = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); - - return Results.Ok(schedules.Select(s => ToDto( - s, assignments.Where(a => a.ScheduleId == s.Id).ToList())).ToList()); - } - - private static async Task CreateAsync( - SaveScheduleRequest request, - AppDbContext db, - AuditService audit, - HttpContext context, - CancellationToken cancellationToken) - { - var (error, next) = Validate(request); - if (error is not null) - { - return Results.BadRequest(new { error }); - } - - if (await db.Schedules.AnyAsync(s => s.Name == request.Name.Trim(), cancellationToken)) - { - return Results.BadRequest(new { error = "A schedule with that name already exists." }); - } - - var actor = context.User.Identity?.Name; - var schedule = new ScheduleEntity - { - Id = Guid.NewGuid(), - Name = request.Name.Trim(), - CreatedUtc = DateTimeOffset.UtcNow, - CreatedBy = actor, - }; - Apply(schedule, request, next, actor); - db.Schedules.Add(schedule); - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Jobs, "schedule-created", actor, - detail: $"schedule={schedule.Name} next={schedule.NextRunUtc:O}", cancellationToken: cancellationToken); - - return Results.Created(ApiRoutes.For.Schedule(schedule.Id), ToDto(schedule, [])); - } - - private static async Task UpdateAsync( - Guid id, - SaveScheduleRequest request, - AppDbContext db, - AuditService audit, - HttpContext context, - CancellationToken cancellationToken) - { - var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); - if (schedule is null) - { - return Results.NotFound(); - } - - var (error, next) = Validate(request); - if (error is not null) - { - return Results.BadRequest(new { error }); - } - - if (await db.Schedules.AnyAsync( - s => s.Id != id && s.Name == request.Name.Trim(), cancellationToken)) - { - return Results.BadRequest(new { error = "A schedule with that name already exists." }); - } - - var actor = context.User.Identity?.Name; - schedule.Name = request.Name.Trim(); - Apply(schedule, request, next, actor); - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Jobs, "schedule-updated", actor, - detail: $"schedule={schedule.Name} enabled={schedule.Enabled}", cancellationToken: cancellationToken); - - var assignments = await LoadAssignmentDtosAsync(db, null, schedule.Id, cancellationToken); - return Results.Ok(ToDto(schedule, assignments)); - } - - private static async Task DeleteAsync( - Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) - { - var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); - if (schedule is null) - { - return Results.NotFound(); - } - - // Assignments cascade with the schedule. - db.Schedules.Remove(schedule); - await db.SaveChangesAsync(cancellationToken); - await audit.LogAsync(AuditCategories.Jobs, "schedule-deleted", context.User.Identity?.Name, - detail: schedule.Name, cancellationToken: cancellationToken); - return Results.NoContent(); - } - - /// Validates a cron and returns its next occurrences — the UI's ground truth. - private static IResult Preview(SchedulePreviewRequest request) - { - var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; - var error = ScheduleCron.Validate(request.CronExpression, timeZoneId); - if (error is not null) - { - return Results.Ok(new SchedulePreviewDto(false, error, [])); - } - - var next = ScheduleCron.NextOccurrences( - request.CronExpression, timeZoneId, DateTimeOffset.UtcNow, count: 5); - return Results.Ok(new SchedulePreviewDto(true, null, next)); - } - - // ── Assignments ────────────────────────────────────────────────────── - - private static async Task ListAssignmentsAsync( - AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken) - => Results.Ok(await LoadAssignmentDtosAsync(db, scriptId, scheduleId, cancellationToken)); - - private static async Task CreateAssignmentAsync( - SaveScheduleAssignmentRequest request, - AppDbContext db, - AuditService audit, - HttpContext context, - CancellationToken cancellationToken) - { - if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error) - { - return Results.BadRequest(new { error }); - } - - var actor = context.User.Identity?.Name; - var assignment = new ScriptScheduleEntity - { - Id = Guid.NewGuid(), - ScheduleId = request.ScheduleId, - ScriptId = request.ScriptId, - ClientId = request.ClientId, - GroupId = request.GroupId, - ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null, - Enabled = request.Enabled, - CreatedUtc = DateTimeOffset.UtcNow, - CreatedBy = actor, - }; - db.ScriptSchedules.Add(assignment); - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Jobs, "schedule-attached", actor, - detail: $"schedule={request.ScheduleId} script={request.ScriptId}", cancellationToken: cancellationToken); - - var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); - return Results.Created( - ApiRoutes.For.ScheduleAssignment(assignment.Id), - dtos.Single(a => a.Id == assignment.Id)); - } - - private static async Task UpdateAssignmentAsync( - Guid id, - SaveScheduleAssignmentRequest request, - AppDbContext db, - AuditService audit, - HttpContext context, - CancellationToken cancellationToken) - { - var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken); - if (assignment is null) - { - return Results.NotFound(); - } - - if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error) - { - return Results.BadRequest(new { error }); - } - - assignment.ScheduleId = request.ScheduleId; - assignment.ScriptId = request.ScriptId; - assignment.ClientId = request.ClientId; - assignment.GroupId = request.GroupId; - assignment.Enabled = request.Enabled; - // Null keeps stored values so enable/disable round-trips. - if (request.Arguments is { Count: > 0 }) - { - assignment.ArgumentsJson = JsonDefaults.Serialize(request.Arguments); - } - - await db.SaveChangesAsync(cancellationToken); - await audit.LogAsync(AuditCategories.Jobs, "schedule-assignment-updated", context.User.Identity?.Name, - detail: $"assignment={id} enabled={assignment.Enabled}", cancellationToken: cancellationToken); - - var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken); - return Results.Ok(dtos.Single(a => a.Id == id)); - } - - private static async Task DeleteAssignmentAsync( - Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) - { - var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken); - if (assignment is null) - { - return Results.NotFound(); - } - - db.ScriptSchedules.Remove(assignment); - await db.SaveChangesAsync(cancellationToken); - await audit.LogAsync(AuditCategories.Jobs, "schedule-detached", context.User.Identity?.Name, - detail: $"assignment={id}", cancellationToken: cancellationToken); - return Results.NoContent(); - } - - // ── Helpers ────────────────────────────────────────────────────────── - - private static (string? Error, DateTimeOffset? NextRunUtc) Validate(SaveScheduleRequest request) - { - if (string.IsNullOrWhiteSpace(request.Name)) - { - return ("Schedule name is required.", null); - } - - var hasCron = !string.IsNullOrWhiteSpace(request.CronExpression); - if (hasCron == (request.RunOnceUtc is not null)) - { - return ("Provide exactly one of cronExpression (recurring) or runOnceUtc (one-shot).", null); - } - - var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; - - if (hasCron) - { - var error = ScheduleCron.Validate(request.CronExpression!, timeZoneId); - if (error is not null) - { - return (error, null); - } - - var next = ScheduleCron.NextOccurrence(request.CronExpression!, timeZoneId, DateTimeOffset.UtcNow); - return next is null ? ("The cron expression never fires.", null) : (null, next); - } - - return request.RunOnceUtc <= DateTimeOffset.UtcNow.AddMinutes(-1) - ? ("The one-shot time is in the past.", null) - : (null, request.RunOnceUtc); - } - - private static void Apply( - ScheduleEntity schedule, SaveScheduleRequest request, DateTimeOffset? next, string? actor) - { - schedule.CronExpression = string.IsNullOrWhiteSpace(request.CronExpression) - ? null - : request.CronExpression.Trim(); - schedule.RunOnceUtc = request.RunOnceUtc; - schedule.TimeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId; - schedule.Enabled = request.Enabled; - schedule.NextRunUtc = request.Enabled ? next : null; - schedule.UpdatedUtc = DateTimeOffset.UtcNow; - schedule.UpdatedBy = actor; - } - - private static async Task ValidateAssignmentAsync( - SaveScheduleAssignmentRequest request, AppDbContext db, CancellationToken cancellationToken) - { - if ((request.ClientId is null) == (request.GroupId is null)) - { - return "Target exactly one of clientId or groupId."; - } - - if (!await db.Schedules.AnyAsync(s => s.Id == request.ScheduleId, cancellationToken)) - { - return "Schedule not found."; - } - - if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken)) - { - return "Script not found."; - } - - if (request.ClientId is { } clientId - && !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken)) - { - return "Device not found."; - } - - if (request.GroupId is { } groupId - && !await db.DeviceGroups.AnyAsync(g => g.Id == groupId, cancellationToken)) - { - return "Group not found."; - } - - return null; - } - - private static async Task> LoadAssignmentDtosAsync( - AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken) - { - var query = db.ScriptSchedules.AsNoTracking().AsQueryable(); - if (scriptId is { } sid) - { - query = query.Where(a => a.ScriptId == sid); - } - - if (scheduleId is { } schedId) - { - query = query.Where(a => a.ScheduleId == schedId); - } - - var assignments = await query.OrderBy(a => a.CreatedUtc).ToListAsync(cancellationToken); - - var scheduleIds = assignments.Select(a => a.ScheduleId).Distinct().ToList(); - var schedules = await db.Schedules.AsNoTracking() - .Where(s => scheduleIds.Contains(s.Id)) - .ToDictionaryAsync(s => s.Id, cancellationToken); - - var scriptIds = assignments.Select(a => a.ScriptId).Distinct().ToList(); - var scriptNames = await db.Scripts.AsNoTracking() - .Where(s => scriptIds.Contains(s.Id)) - .ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken); - - var clientIds = assignments.Where(a => a.ClientId != null).Select(a => a.ClientId!).Distinct().ToList(); - var hostnames = await db.Devices.AsNoTracking() - .Where(d => clientIds.Contains(d.ClientId)) - .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); - - var groupIds = assignments.Where(a => a.GroupId != null).Select(a => a.GroupId!.Value).Distinct().ToList(); - var groupNames = await db.DeviceGroups.AsNoTracking() - .Where(g => groupIds.Contains(g.Id)) - .ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken); - - return assignments.Select(a => - { - var schedule = schedules.GetValueOrDefault(a.ScheduleId); - return new ScheduleAssignmentDto( - a.Id, - a.ScheduleId, - schedule?.Name, - schedule?.CronExpression, - schedule?.RunOnceUtc, - schedule?.TimeZoneId ?? "UTC", - schedule?.Enabled ?? false, - schedule?.NextRunUtc, - a.ScriptId, - scriptNames.GetValueOrDefault(a.ScriptId), - a.ClientId, - a.ClientId is null ? null : hostnames.GetValueOrDefault(a.ClientId), - a.GroupId, - a.GroupId is null ? null : groupNames.GetValueOrDefault(a.GroupId.Value), - a.Enabled, - a.LastRunUtc, - a.LastResult); - }).ToList(); - } - - internal static ScheduleDto ToDto(ScheduleEntity s, IReadOnlyList assignments) => new( - s.Id, - s.Name, - s.CronExpression, - s.RunOnceUtc, - s.TimeZoneId, - s.Enabled, - s.NextRunUtc, - s.LastRunUtc, - s.UpdatedUtc, - s.UpdatedBy, - assignments); -} diff --git a/src/Backend/Jobs/ScheduleWorker.cs b/src/Backend/Jobs/ScheduleWorker.cs index 936bde6..5aace29 100644 --- a/src/Backend/Jobs/ScheduleWorker.cs +++ b/src/Backend/Jobs/ScheduleWorker.cs @@ -3,15 +3,18 @@ using Backend.Data; using Backend.Groups; using Backend.Secrets; using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Models; using Shared.Contracts.Serialization; namespace Backend.Jobs; /// -/// Fires due schedules: every enabled assignment (script + target + stored run -/// values) honoring the schedule runs through the normal job pipeline. -/// Recurrence advances from "now" after each firing, so downtime never causes -/// a storm of catch-up runs — at most one late firing per schedule. +/// Fires due Scheduled triggers: each enabled scheduled trigger (script + +/// target + captured argument values) runs through the normal job pipeline when +/// its cron/one-shot time arrives. Recurrence advances from "now" after each +/// firing, so downtime never causes a storm of catch-up runs — at most one late +/// firing per trigger. Event triggers (registration/agent-ready) are handled by +/// , not here. /// public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger logger) : BackgroundService @@ -24,7 +27,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger(); @@ -54,174 +57,141 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger(); var now = DateTimeOffset.UtcNow; - var due = await db.Schedules - .Where(s => s.Enabled && s.NextRunUtc != null && s.NextRunUtc <= now) + var due = await db.ScriptTriggers + .Where(t => t.TriggerType == ScriptTriggerType.Scheduled + && t.Enabled && t.NextRunUtc != null && t.NextRunUtc <= now) .ToListAsync(cancellationToken); - foreach (var schedule in due) + foreach (var trigger in due) { try { - await FireAsync(schedule, db, runner, groups, cancellationToken); + await FireAsync(trigger, db, runner, groups, cancellationToken); } catch (Exception ex) { - logger.LogError(ex, "Schedule {ScheduleId} ({Name}) failed to fire", schedule.Id, schedule.Name); + trigger.LastResult = ex.Message; + logger.LogError(ex, "Scheduled trigger {TriggerId} failed to fire", trigger.Id); } - Advance(schedule); + Advance(trigger); await db.SaveChangesAsync(cancellationToken); } } private async Task FireAsync( - ScheduleEntity schedule, + ScriptTriggerEntity trigger, AppDbContext db, JobRunner runner, DeviceGroupService groups, CancellationToken cancellationToken) { - var assignments = await db.ScriptSchedules - .Where(a => a.ScheduleId == schedule.Id && a.Enabled) - .ToListAsync(cancellationToken); - if (assignments.Count == 0) - { - return; - } - - // One preparation (prelude + secrets) per script per firing, shared by - // every assignment and target using it. - var prepared = new Dictionary(); - - foreach (var assignment in assignments) - { - try - { - await FireAssignmentAsync(schedule, assignment, prepared, db, runner, groups, cancellationToken); - } - catch (Exception ex) - { - assignment.LastRunUtc = DateTimeOffset.UtcNow; - assignment.LastResult = ex.Message; - logger.LogError(ex, - "Schedule {Name}: assignment {AssignmentId} failed", schedule.Name, assignment.Id); - } - } - } - - private async Task FireAssignmentAsync( - ScheduleEntity schedule, - ScriptScheduleEntity assignment, - Dictionary prepared, - AppDbContext db, - JobRunner runner, - DeviceGroupService groups, - CancellationToken cancellationToken) - { - assignment.LastRunUtc = DateTimeOffset.UtcNow; + trigger.LastRunUtc = DateTimeOffset.UtcNow; var script = await db.Scripts.AsNoTracking() - .SingleOrDefaultAsync(s => s.Id == assignment.ScriptId, cancellationToken); + .SingleOrDefaultAsync(s => s.Id == trigger.ScriptId, cancellationToken); if (script is null) { - assignment.Enabled = false; - assignment.LastResult = "Disabled: the script no longer exists."; + trigger.Enabled = false; + trigger.LastResult = "Disabled: the script no longer exists."; return; } - var devices = await ResolveTargetsAsync(assignment, db, groups, cancellationToken); + var devices = await ResolveTargetsAsync(trigger, db, groups, cancellationToken); if (devices.Count == 0) { - assignment.LastResult = "No eligible devices at fire time."; + trigger.LastResult = "No eligible devices at fire time."; return; } - if (!prepared.TryGetValue(script.Id, out var preparedScript)) + PreparedScript prepared; + try { - try - { - preparedScript = await runner.PrepareAsync(script, cancellationToken); - prepared[script.Id] = preparedScript; - } - catch (Exception ex) when ( - ex is SecretResolutionException or Backend.Files.FileResolutionException) - { - assignment.LastResult = ex.Message; - logger.LogWarning("Schedule {Name}: {Message}", schedule.Name, ex.Message); - return; - } + prepared = await runner.PrepareAsync(script, cancellationToken); + } + catch (Exception ex) when (ex is SecretResolutionException or Backend.Files.FileResolutionException) + { + trigger.LastResult = ex.Message; + logger.LogWarning("Scheduled trigger {TriggerId}: {Message}", trigger.Id, ex.Message); + return; } - var arguments = string.IsNullOrWhiteSpace(assignment.ArgumentsJson) + var arguments = string.IsNullOrWhiteSpace(trigger.ArgumentsJson) ? null - : JsonDefaults.Deserialize>(assignment.ArgumentsJson); + : JsonDefaults.Deserialize>(trigger.ArgumentsJson); var queued = 0; foreach (var device in devices) { - var job = await runner.CreateJobAsync( - script, device.ClientId, $"schedule:{schedule.Name}", cancellationToken); + var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken); await runner.DispatchAsync( - prepared[script.Id], job, arguments, - $"Schedule “{schedule.Name}” queued “{script.Name}” for {device.Hostname}", + prepared, job, arguments, + $"Scheduled trigger queued “{script.Name}” for {device.Hostname}", cancellationToken); queued++; } - assignment.LastResult = $"{queued} job(s) queued"; + trigger.LastResult = $"{queued} job(s) queued"; logger.LogInformation( - "Schedule {Name} queued {Count} job(s) of “{Script}”", schedule.Name, queued, script.Name); + "Scheduled trigger {TriggerId} queued {Count} job(s) of “{Script}”", trigger.Id, queued, script.Name); } private static async Task> ResolveTargetsAsync( - ScriptScheduleEntity assignment, + ScriptTriggerEntity trigger, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) { - if (assignment.ClientId is { } clientId) + if (trigger.ClientId is { } clientId) { var device = await db.Devices.AsNoTracking() .SingleOrDefaultAsync(d => d.ClientId == clientId && !d.IsOrphaned, cancellationToken); return device is null ? [] : [device]; } - var group = await db.DeviceGroups.AsNoTracking() - .SingleOrDefaultAsync(g => g.Id == assignment.GroupId, cancellationToken); - if (group is null) + if (trigger.GroupId is { } groupId) { - return []; + var group = await db.DeviceGroups.AsNoTracking() + .SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); + if (group is null) + { + return []; + } + + var memberIds = await groups.GetMembersAsync(group, cancellationToken); + return await db.Devices.AsNoTracking() + .Where(d => memberIds.Contains(d.ClientId) && !d.IsOrphaned) + .ToListAsync(cancellationToken); } - var memberIds = await groups.GetMembersAsync(group, cancellationToken); + // No target = all devices. return await db.Devices.AsNoTracking() - .Where(d => memberIds.Contains(d.ClientId) && !d.IsOrphaned) + .Where(d => !d.IsOrphaned) .ToListAsync(cancellationToken); } - private static void Advance(ScheduleEntity schedule) + private static void Advance(ScriptTriggerEntity trigger) { - schedule.LastRunUtc = DateTimeOffset.UtcNow; + trigger.LastRunUtc = DateTimeOffset.UtcNow; - if (schedule.CronExpression is { } cron) + if (trigger.CronExpression is { } cron) { try { - schedule.NextRunUtc = ScheduleCron.NextOccurrence( - cron, schedule.TimeZoneId, DateTimeOffset.UtcNow); + trigger.NextRunUtc = ScheduleCron.NextOccurrence(cron, trigger.TimeZoneId, DateTimeOffset.UtcNow); } catch (Exception) { // Stored expression went bad (should be impossible past validation). - schedule.Enabled = false; - schedule.NextRunUtc = null; + trigger.Enabled = false; + trigger.NextRunUtc = null; } } else { // One-shot: done. - schedule.Enabled = false; - schedule.NextRunUtc = null; + trigger.Enabled = false; + trigger.NextRunUtc = null; } } } diff --git a/src/Backend/Program.cs b/src/Backend/Program.cs index 8ce6b2c..3717748 100644 --- a/src/Backend/Program.cs +++ b/src/Backend/Program.cs @@ -395,7 +395,6 @@ ScriptEndpoints.Map(app); FunctionEndpoints.Map(app); JobEndpoints.Map(app); DashboardEndpoints.Map(app); -ScheduleEndpoints.Map(app); BootstrapTokenEndpoints.Map(app); MessagingEndpoints.Map(app); ShellEndpoints.Map(app); diff --git a/src/Backend/Standalone/MessagingWsProxy.cs b/src/Backend/Standalone/MessagingWsProxy.cs index 2ce9f5b..2d93530 100644 --- a/src/Backend/Standalone/MessagingWsProxy.cs +++ b/src/Backend/Standalone/MessagingWsProxy.cs @@ -36,10 +36,21 @@ public static class MessagingWsProxy .GetRequiredService() .CreateLogger("MessagingWsProxy"); + var targetUri = new Uri(target); using var upstream = new ClientWebSocket(); + // When the sidecar's WebSocket runs TLS (exposed bind), the relay dials + // it over wss on loopback. Loopback cannot be intercepted, so accept the + // certificate without distributing the self-signed CA to this process. + if (targetUri.Scheme == Uri.UriSchemeWss + && System.Net.IPAddress.TryParse(targetUri.Host, out var host) + && System.Net.IPAddress.IsLoopback(host)) + { + upstream.Options.RemoteCertificateValidationCallback = (_, _, _, _) => true; + } + try { - await upstream.ConnectAsync(new Uri(target), context.RequestAborted); + await upstream.ConnectAsync(targetUri, context.RequestAborted); } catch (Exception ex) { diff --git a/src/Backend/Standalone/NatsSidecar.cs b/src/Backend/Standalone/NatsSidecar.cs index e645014..83bd39d 100644 --- a/src/Backend/Standalone/NatsSidecar.cs +++ b/src/Backend/Standalone/NatsSidecar.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.IO; namespace Backend.Standalone; @@ -16,6 +17,9 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger configuration["NATS_SIDECAR"] == "1"; @@ -51,11 +55,14 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger SuperviseAsync(binary, config, stopping.Token), CancellationToken.None); + SetUpCertReload(configuration["NATS_TLS_CERT"]); await WaitForReadyAsync(cancellationToken); } public async Task StopAsync(CancellationToken cancellationToken) { + certWatcher?.Dispose(); + reloadDebounce?.Dispose(); stopping.Cancel(); if (supervisor is not null) { @@ -98,12 +105,14 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger stopping.Dispose(); + /// + /// Watches the WebSocket TLS certificate (when the exposed bind runs TLS) + /// and bounces nats-server when it rotates — it reads certs only at start, + /// so the supervisor respawns it with the fresh chain. No-op when no cert + /// is configured (loopback default runs plaintext). + /// + private void SetUpCertReload(string? certPath) + { + if (string.IsNullOrWhiteSpace(certPath)) + { + return; + } + + try + { + var full = Path.GetFullPath(certPath); + var dir = Path.GetDirectoryName(full); + var file = Path.GetFileName(full); + if (string.IsNullOrEmpty(dir) || string.IsNullOrEmpty(file)) + { + return; + } + + certWatcher = new FileSystemWatcher(dir, file) + { + NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size, + EnableRaisingEvents = true, + }; + certWatcher.Changed += (_, _) => DebounceReload(); + certWatcher.Created += (_, _) => DebounceReload(); + certWatcher.Renamed += (_, _) => DebounceReload(); + logger.LogInformation("Watching {Cert} to reload NATS on certificate rotation", full); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Could not watch the NATS TLS certificate for rotation"); + } + } + + /// Coalesces the renewal's cert+key writes, then bounces the process. + private void DebounceReload() + { + reloadDebounce?.Dispose(); + reloadDebounce = new Timer(_ => + { + try + { + var proc = running; + if (proc is { HasExited: false }) + { + logger.LogInformation("NATS TLS certificate changed — restarting the sidecar to load it"); + proc.Kill(entireProcessTree: true); + } + } + catch (Exception) + { + // The supervisor respawns on the next loop regardless. + } + }, null, TimeSpan.FromSeconds(3), Timeout.InfiniteTimeSpan); + } + + public void Dispose() + { + certWatcher?.Dispose(); + reloadDebounce?.Dispose(); + stopping.Dispose(); + } } diff --git a/src/Backend/Standalone/ServerCli.cs b/src/Backend/Standalone/ServerCli.cs index 81c26af..9fabd9b 100644 --- a/src/Backend/Standalone/ServerCli.cs +++ b/src/Backend/Standalone/ServerCli.cs @@ -80,6 +80,7 @@ public static class ServerCli : parsed.ToString(); break; case "--nats-bind": + case "--nb": var natsCandidate = args[++i]; if (!System.Net.IPAddress.TryParse(natsCandidate, out _)) { @@ -126,9 +127,10 @@ public static class ServerCli var baseDir = AppContext.BaseDirectory; var natsDir = Path.Combine(baseDir, "nats"); var dataDir = Path.Combine(baseDir, "data"); - // Everything stateful lives under data/ as siblings: db, keys, - // jetstream, resolver, tls and the NATS auth secrets. - var secretsDir = Path.Combine(dataDir, "secrets", "nats"); + // Stateful data lives under data/: db, keys and tls at the top; every + // NATS-related directory (jetstream, resolver, secrets) is grouped + // under data/nats so the layout reads clearly. + var secretsDir = Path.Combine(dataDir, "nats", "secrets"); Directory.CreateDirectory(natsDir); Directory.CreateDirectory(Path.Combine(dataDir, "db")); @@ -142,10 +144,10 @@ public static class ServerCli // NATS operator/account keys + resolver preload (idempotent). The // resolver dir is relative to the sidecar's working dir (natsDir), so - // it lands in data/resolver rather than the filesystem root. + // it lands in data/nats/resolver rather than the filesystem root. if (!File.Exists(Path.Combine(secretsDir, "resolver.conf"))) { - var result = NatsAuthCli.Run(["init", "--output", secretsDir, "--resolver-dir", "../data/resolver"]); + var result = NatsAuthCli.Run(["init", "--output", secretsDir, "--resolver-dir", "../data/nats/resolver"]); if (result != 0) { return result; @@ -156,8 +158,18 @@ public static class ServerCli Console.WriteLine($"NATS keys already present in {secretsDir}"); } - // Sidecar configuration: local-only listeners; the server proxies the - // WebSocket paths itself, so nothing NATS listens on is ever public. + // The core protocol and monitor listeners are backend-only, so they + // always stay on loopback. Only the WebSocket is proxy-facing; its bind + // opens with --nats-bind for an edge proxy on another host, and when + // that happens over self-signed TLS it reuses the server's own managed + // leaf (data/tls) so nothing extra is generated. The loopback default + // stays plaintext — the backend relays /messaging/* over loopback. + var natsWsExposed = !System.Net.IPAddress.IsLoopback(System.Net.IPAddress.Parse(natsBind)); + var natsWsTls = selfSignedTls && natsWsExposed; + var natsWsSecurity = natsWsTls + ? " tls {\n cert_file: \"../data/tls/server.crt\"\n key_file: \"../data/tls/server.key\"\n }" + : " no_tls: true"; + var natsConf = Path.Combine(natsDir, "nats.conf"); if (!File.Exists(natsConf)) { @@ -167,24 +179,24 @@ public static class ServerCli # Generated by `setup` for the standalone ExecuteR server. server_name: executer-standalone - # Listeners bind to {{natsBind}} (loopback by default; the server - # proxies /messaging/* to the websocket port). Set --nats-bind - # to open them when an edge proxy on another host needs them. - listen: {{natsBind}}:{{natsPort}} - http: {{natsBind}}:{{natsMonitorPort}} + # Core + monitor are backend-only: always loopback. + listen: 127.0.0.1:{{natsPort}} + http: 127.0.0.1:{{natsMonitorPort}} jetstream { # nats-server appends "jetstream" itself: this lands in - # ../data/jetstream. - store_dir: "../data" + # ../data/nats/jetstream. + store_dir: "../data/nats" } + # WebSocket bind ({{natsBind}}); loopback stays plaintext, an + # exposed bind over self-signed TLS reuses the managed leaf. websocket { listen: {{natsBind}}:{{natsWsPort}} - no_tls: true + {{natsWsSecurity}} } - include "../data/secrets/nats/resolver.conf" + include "../data/nats/secrets/resolver.conf" """); Console.WriteLine($"Wrote {natsConf}"); } @@ -201,7 +213,7 @@ public static class ServerCli var accountPublic = File.ReadAllText(Path.Combine(secretsDir, "account.pub")).Trim(); File.WriteAllText(appsettings, $$""" { - "Urls": "http://{{bindAddress}}:{{httpPort}}", + "Urls": "{{(selfSignedTls ? "https" : "http")}}://{{bindAddress}}:{{httpPort}}", "DATA_PATH": "{{dataDir.Replace('\\', '/')}}", "DATABASE_PATH": "{{Path.Combine(dataDir, "db", "app.db").Replace('\\', '/')}}", "DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}", @@ -209,7 +221,8 @@ public static class ServerCli "AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}", "NATS_URL": "nats://127.0.0.1:{{natsPort}}", "NATS_SIDECAR": "1", - "NATS_WS_PROXY": "ws://127.0.0.1:{{natsWsPort}}", + "NATS_WS_PROXY": "{{(natsWsTls ? "wss" : "ws")}}://127.0.0.1:{{natsWsPort}}", + "NATS_TLS_CERT": "{{(natsWsTls ? Path.Combine(dataDir, "tls", "server.crt").Replace('\\', '/') : "")}}", "NATS_MONITOR_URL": "http://127.0.0.1:{{natsMonitorPort}}", "NATS_ACCOUNT_SIGNING_SEED": "{{signingSeed}}", "NATS_ACCOUNT_PUBLIC_KEY": "{{accountPublic}}", diff --git a/src/Infra/nginx/executer-http.conf b/src/Infra/nginx/executer-http.conf index 15b0e1c..db9038f 100644 --- a/src/Infra/nginx/executer-http.conf +++ b/src/Infra/nginx/executer-http.conf @@ -16,8 +16,11 @@ # duplicate here or nginx will refuse to start. #============================================================================= -# "upgrade" for WebSocket requests, "close" otherwise. +# "upgrade" for WebSocket requests, empty otherwise. Empty (not "close") +# keeps upstream keepalive working AND lets the site set Connection once at +# server{} level — so no location needs its own proxy_set_header, which in +# nginx would silently drop every inherited header (Host, X-Forwarded-*). map $http_upgrade $connection_upgrade { default upgrade; - '' close; + '' ''; } diff --git a/src/Infra/nginx/executer.conf b/src/Infra/nginx/executer.conf index b7df832..f3d8698 100644 --- a/src/Infra/nginx/executer.conf +++ b/src/Infra/nginx/executer.conf @@ -88,8 +88,14 @@ server { # Set this if you mount the app under a sub-path instead of the site root. proxy_set_header X-Forwarded-Prefix /; - # --- WebSocket upgrade (safe site-wide; $connection_upgrade is "close" - # for ordinary requests) ----------------------------------------------- + # --- WebSocket upgrade (safe site-wide; $connection_upgrade is empty for + # ordinary requests, which also preserves upstream keepalive) ---------- + # IMPORTANT: every proxy_set_header here is set at server{} level so it is + # inherited by all locations. nginx does NOT merge proxy_set_header across + # levels — if any location adds even one proxy_set_header, it DROPS all of + # these (Host, X-Forwarded-*), and the backend then derives its public URL + # from the upstream name (e.g. https://executer_api/...). So do not add + # proxy_set_header inside a location; the map above removes the need to. proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; @@ -146,8 +152,6 @@ server { location ^~ /api/enrollment/ { limit_req zone=executer_enroll burst=5 nodelay; proxy_pass http://executer_api; - proxy_http_version 1.1; - proxy_set_header Connection ""; # The agent package download can be tens of MB. proxy_read_timeout 300s; @@ -163,8 +167,6 @@ server { location ^~ /api/auth/ { limit_req zone=executer_auth burst=10 nodelay; proxy_pass http://executer_api; - proxy_http_version 1.1; - proxy_set_header Connection ""; } # ── Backend API ─────────────────────────────────────────────────────── @@ -172,15 +174,11 @@ server { # rides the rate-limited /api/auth/ location above — one hit per sign-in). location ^~ /api/ { proxy_pass http://executer_api; - proxy_http_version 1.1; - proxy_set_header Connection ""; proxy_read_timeout 120s; } # ── WebUI (everything else) ─────────────────────────────────────────── location / { proxy_pass http://executer_webui; - proxy_http_version 1.1; - proxy_set_header Connection ""; } } diff --git a/src/Installer.Server/Product.wxs b/src/Installer.Server/Product.wxs index 7df2f66..41e6fe1 100644 --- a/src/Installer.Server/Product.wxs +++ b/src/Installer.Server/Product.wxs @@ -53,6 +53,12 @@ + + @@ -104,7 +110,7 @@ the quotes around ENABLETLS are load-bearing: unchecked formats to an empty quoted argument, which setup reads as off. --> - - - - - - + Text="NATS ports; WS bind opens the WebSocket for a remote edge proxy (core/monitor stay local):" /> + + + + + + + + Public self-signed CA chain (root + intermediate) for agent trust. public const string EnrollmentCaChain = "/api/enrollment/ca"; - public const string Schedules = "/api/schedules"; - public const string Schedule = "/api/schedules/{id}"; - public const string SchedulePreview = "/api/schedules/preview"; - public const string ScheduleAssignments = "/api/schedule-assignments"; - public const string ScheduleAssignment = "/api/schedule-assignments/{id}"; - public const string BrowserNatsCredential = "/api/messaging/credential"; public const string AdminBootstrapTokens = "/api/admin/bootstrap-tokens"; @@ -101,8 +95,6 @@ public static class ApiRoutes public static string SecretsProvider(Guid id) => $"/api/secrets/providers/{id:D}"; 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 Schedule(Guid id) => $"/api/schedules/{id:D}"; - public static string ScheduleAssignment(Guid id) => $"/api/schedule-assignments/{id:D}"; public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output"; public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}"; public static string AdminRole(Guid id) => $"/api/admin/roles/{id:D}"; diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 486657a..8dddbbc 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -49,25 +49,43 @@ public sealed record PreviewGroupRequest(GroupRuleSet Rules); /// PUT /api/devices/{clientId}/tags request body. public sealed record UpdateDeviceTagsRequest(IReadOnlyList Tags); -/// Script trigger resource. +/// +/// Unified script trigger: when (event or schedule) + target (device/group/all) +/// + optional captured arguments. Replaces the separate schedule concept. +/// public sealed record ScriptTriggerDto( Guid Id, Guid ScriptId, string ScriptName, Guid? GroupId, string? GroupName, + string? ClientId, + string? ClientHostname, ScriptTriggerType TriggerType, bool Enabled, - bool OncePerDevice, + string? CronExpression, + DateTimeOffset? RunOnceUtc, + string TimeZoneId, + DateTimeOffset? NextRunUtc, + DateTimeOffset? LastRunUtc, + string? LastResult, DateTimeOffset CreatedUtc); -/// POST /api/triggers request body. +/// +/// POST /api/triggers. Target: exactly one of ClientId / GroupId, or neither +/// for all devices. For TriggerType=Scheduled, supply CronExpression (recurring) +/// or RunOnceUtc (one-shot) plus an optional TimeZoneId and Arguments. +/// public sealed record SaveScriptTriggerRequest( Guid ScriptId, - Guid? GroupId, ScriptTriggerType TriggerType, + string? ClientId = null, + Guid? GroupId = null, bool Enabled = true, - bool OncePerDevice = true); + string? CronExpression = null, + DateTimeOffset? RunOnceUtc = null, + string? TimeZoneId = null, + IReadOnlyDictionary? Arguments = null); /// Device detail for GET /api/devices/{clientId}. public sealed record DeviceDetailDto( @@ -214,78 +232,6 @@ public sealed record DashboardDto( IReadOnlyList Timeline, IReadOnlyList RecentRuns); -/// -/// A reusable cadence object. Scripts honor a schedule through assignments — -/// the schedule itself carries no script or target. -/// -public sealed record ScheduleDto( - Guid Id, - string Name, - string? CronExpression, - DateTimeOffset? RunOnceUtc, - string TimeZoneId, - bool Enabled, - DateTimeOffset? NextRunUtc, - DateTimeOffset? LastRunUtc, - DateTimeOffset UpdatedUtc, - string? UpdatedBy, - IReadOnlyList Assignments); - -/// -/// POST/PUT /api/schedules body. Exactly one of -/// CronExpression/RunOnceUtc. -/// -public sealed record SaveScheduleRequest( - string Name, - string? CronExpression, - DateTimeOffset? RunOnceUtc, - string? TimeZoneId = null, - bool Enabled = true); - -/// -/// One script honoring a schedule against one device or group. Carries the -/// schedule's cadence so consumers can describe it without a second lookup. -/// -public sealed record ScheduleAssignmentDto( - Guid Id, - Guid ScheduleId, - string? ScheduleName, - string? CronExpression, - DateTimeOffset? RunOnceUtc, - string TimeZoneId, - bool ScheduleEnabled, - DateTimeOffset? NextRunUtc, - Guid ScriptId, - string? ScriptName, - string? ClientId, - string? TargetHostname, - Guid? GroupId, - string? GroupName, - bool Enabled, - DateTimeOffset? LastRunUtc, - string? LastResult); - -/// -/// POST/PUT /api/schedule-assignments body. Exactly one of -/// ClientId/GroupId. Null Arguments keeps stored values. -/// -public sealed record SaveScheduleAssignmentRequest( - Guid ScheduleId, - Guid ScriptId, - string? ClientId, - Guid? GroupId, - IReadOnlyDictionary? Arguments = null, - bool Enabled = true); - -/// POST /api/schedules/preview body. -public sealed record SchedulePreviewRequest(string CronExpression, string? TimeZoneId = null); - -/// Validation + the next concrete occurrences, so the UI never guesses. -public sealed record SchedulePreviewDto( - bool Valid, - string? Error, - IReadOnlyList NextRunsUtc); - /// One stored output record for GET /api/jobs/{jobId}/output. public sealed record JobOutputRecordDto( long Sequence, diff --git a/src/Shared.Contracts/Models/Enums.cs b/src/Shared.Contracts/Models/Enums.cs index f590c49..c515bfe 100644 --- a/src/Shared.Contracts/Models/Enums.cs +++ b/src/Shared.Contracts/Models/Enums.cs @@ -48,6 +48,13 @@ public enum ScriptTriggerType /// Fires when the agent is connected and consuming job commands. OnAgentReady, + + /// + /// Fires on a time cadence — a cron expression (recurring) or a one-shot + /// time. This unifies the former "schedule" concept into triggers: a + /// trigger carries its own timing AND its own target. + /// + Scheduled, } /// Remote shell session lifecycle states. diff --git a/src/Shared.Contracts/Models/InventoryReport.cs b/src/Shared.Contracts/Models/InventoryReport.cs index 714b95f..b553503 100644 --- a/src/Shared.Contracts/Models/InventoryReport.cs +++ b/src/Shared.Contracts/Models/InventoryReport.cs @@ -22,7 +22,11 @@ public sealed record InventoryIdentity( string? BaseboardSerial, string? DomainOrWorkgroup, bool PartOfDomain, - string? SystemType); + string? SystemType, + // System firmware UUID (SMBIOS) and motherboard make/product. + string? SystemUuid = null, + string? BaseboardManufacturer = null, + string? BaseboardProduct = null); public sealed record InventoryOs( string? Caption, @@ -31,7 +35,11 @@ public sealed record InventoryOs( string? Architecture, DateTimeOffset? InstallDateUtc, DateTimeOffset? LastBootUtc, - string? Edition); + string? Edition, + // Windows feature-update release (e.g. "23H2"); null off Windows. + string? ReleaseVersion = null, + // Workstation / Server / Domain Controller. + string? ProductType = null); public sealed record InventoryCpu( string? Name, diff --git a/src/Shared.Infrastructure/Versioning/BuildVersion.cs b/src/Shared.Infrastructure/Versioning/BuildVersion.cs index 32f5dc6..abbe6c5 100644 --- a/src/Shared.Infrastructure/Versioning/BuildVersion.cs +++ b/src/Shared.Infrastructure/Versioning/BuildVersion.cs @@ -23,9 +23,24 @@ public static class BuildVersion return "0.0.0.0"; } - // Strip any source-revision suffix MSBuild may append (+sha). - var plus = informational.IndexOf('+'); - return plus >= 0 ? informational[..plus] : informational; + // The binary keeps its full informational version (date-hash) for + // support; the REPORTED version (enrollment, presence, /health, CLI) + // is the clean unified yyyy.MM.dd.HHmm. Strip build metadata (+sha) + // and the short-commit suffix (-sha) — the date part has no '-'. + var trimmed = informational; + var plus = trimmed.IndexOf('+'); + if (plus >= 0) + { + trimmed = trimmed[..plus]; + } + + var dash = trimmed.IndexOf('-'); + if (dash >= 0) + { + trimmed = trimmed[..dash]; + } + + return trimmed; } /// diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index df73d8d..2504930 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -23,11 +23,6 @@ import type { UserAccountDto, S3SettingsDto, S3TestResultDto, - SaveScheduleAssignmentBody, - SaveScheduleBody, - ScheduleAssignmentDto, - ScheduleDto, - SchedulePreviewDto, ScriptDto, ServerInfoDto, ScriptParameter, @@ -211,37 +206,6 @@ export const api = { body: JSON.stringify({ groupId, scriptId, arguments: args }) }), - // Schedules (cadence objects) + assignments (script honors schedule) - schedules: () => request('/api/schedules'), - createSchedule: (body: SaveScheduleBody) => - request('/api/schedules', { method: 'POST', body: JSON.stringify(body) }), - updateSchedule: (id: string, body: SaveScheduleBody) => - request(`/api/schedules/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteSchedule: (id: string) => request(`/api/schedules/${id}`, { method: 'DELETE' }), - previewSchedule: (cronExpression: string, timeZoneId?: string) => - request('/api/schedules/preview', { - method: 'POST', - body: JSON.stringify({ cronExpression, timeZoneId }) - }), - scheduleAssignments: (scriptId?: string, scheduleId?: string) => { - const params = new URLSearchParams(); - if (scriptId) params.set('scriptId', scriptId); - if (scheduleId) params.set('scheduleId', scheduleId); - const qs = params.size > 0 ? `?${params}` : ''; - return request(`/api/schedule-assignments${qs}`); - }, - createScheduleAssignment: (body: SaveScheduleAssignmentBody) => - request('/api/schedule-assignments', { - method: 'POST', - body: JSON.stringify(body) - }), - updateScheduleAssignment: (id: string, body: SaveScheduleAssignmentBody) => - request(`/api/schedule-assignments/${id}`, { - method: 'PUT', - body: JSON.stringify(body) - }), - deleteScheduleAssignment: (id: string) => - request(`/api/schedule-assignments/${id}`, { method: 'DELETE' }), // Groups groups: () => request('/api/groups'), @@ -273,10 +237,14 @@ export const api = { triggers: () => request('/api/triggers'), createTrigger: (body: { scriptId: string; - groupId?: string; triggerType: ScriptTriggerType; + clientId?: string; + groupId?: string; enabled?: boolean; - oncePerDevice?: boolean; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId?: string; + arguments?: Record; }) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }), deleteTrigger: (id: string) => request(`/api/triggers/${id}`, { method: 'DELETE' }), diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts index 414050a..ab34607 100644 --- a/src/WebUI/src/lib/api/types.ts +++ b/src/WebUI/src/lib/api/types.ts @@ -183,7 +183,7 @@ export interface AgentPackageStatusDto { offloadUploaded: boolean; } -export type ScriptTriggerType = 'onRegistration' | 'onAgentReady'; +export type ScriptTriggerType = 'onRegistration' | 'onAgentReady' | 'scheduled'; export interface ScriptTriggerDto { id: string; @@ -191,9 +191,16 @@ export interface ScriptTriggerDto { scriptName: string; groupId?: string; groupName?: string; + clientId?: string; + clientHostname?: string; triggerType: ScriptTriggerType; enabled: boolean; - oncePerDevice: boolean; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId: string; + nextRunUtc?: string; + lastRunUtc?: string; + lastResult?: string; createdUtc: string; } @@ -209,6 +216,9 @@ export interface InventoryReport { domainOrWorkgroup?: string; partOfDomain: boolean; systemType?: string; + systemUuid?: string; + baseboardManufacturer?: string; + baseboardProduct?: string; }; os: { caption?: string; @@ -218,6 +228,8 @@ export interface InventoryReport { installDateUtc?: string; lastBootUtc?: string; edition?: string; + releaseVersion?: string; + productType?: string; }; cpu: { name?: string; logicalProcessors: number; cores: number }; memory: { @@ -300,65 +312,6 @@ export interface GroupRunDto { skippedOrphaned: string[]; } -/** A reusable cadence object; scripts honor it through assignments. */ -export interface ScheduleDto { - id: string; - name: string; - cronExpression?: string; - runOnceUtc?: string; - timeZoneId: string; - enabled: boolean; - nextRunUtc?: string; - lastRunUtc?: string; - updatedUtc: string; - updatedBy?: string; - assignments: ScheduleAssignmentDto[]; -} - -export interface SaveScheduleBody { - name: string; - cronExpression?: string; - runOnceUtc?: string; - timeZoneId?: string; - enabled: boolean; -} - -/** One script honoring a schedule against one device or group. */ -export interface ScheduleAssignmentDto { - id: string; - scheduleId: string; - scheduleName?: string; - cronExpression?: string; - runOnceUtc?: string; - timeZoneId: string; - scheduleEnabled: boolean; - nextRunUtc?: string; - scriptId: string; - scriptName?: string; - clientId?: string; - targetHostname?: string; - groupId?: string; - groupName?: string; - enabled: boolean; - lastRunUtc?: string; - lastResult?: string; -} - -export interface SaveScheduleAssignmentBody { - scheduleId: string; - scriptId: string; - clientId?: string; - groupId?: string; - arguments?: Record; - enabled: boolean; -} - -export interface SchedulePreviewDto { - valid: boolean; - error?: string; - nextRunsUtc: string[]; -} - export interface CountPoint { label: string; count: number; diff --git a/src/WebUI/src/lib/components/AddDeviceModal.svelte b/src/WebUI/src/lib/components/AddDeviceModal.svelte index 7016322..f55a3c9 100644 --- a/src/WebUI/src/lib/components/AddDeviceModal.svelte +++ b/src/WebUI/src/lib/components/AddDeviceModal.svelte @@ -16,6 +16,10 @@ let token = $state(''); let tokenId = $state(''); let baseUrl = $state(''); + // Server-informed (no operator toggle): true when this origin is the + // self-signed listener reached directly, so the target's own fetch must + // skip verification. False behind a real-cert proxy. + let selfSignedDirect = $state(false); let errorText = $state(''); let busy = $state(false); let regenTimer: ReturnType | undefined; @@ -31,6 +35,7 @@ .serverInfo() .then((info) => { baseUrl = info.baseUrl ?? location.origin; + selfSignedDirect = info.selfSignedDirect ?? false; }) .catch(() => (baseUrl = location.origin)); @@ -92,20 +97,27 @@ const command = $derived.by(() => { if (!token || !baseUrl) return ''; - // The served script decides trust itself: when the server runs - // self-signed TLS it makes the agent fetch and trust the CA, and if this - // origin is the self-signed listener directly it also skips verification - // for its own download. Nothing here to toggle. + // The served script decides trust for the agent itself. This outer fetch + // only needs: TLS 1.2 on Windows PowerShell (the Run box launches 5.1 + // -NoProfile, which otherwise defaults to TLS 1.0 and fails the + // handshake), and — when this origin is the self-signed listener reached + // directly — accepting that certificate. const install = `${baseUrl}/api/enrollment/install?token=${token}`; + // Short prefix so the whole command still fits the Win+R box. + const tls = "[Net.ServicePointManager]::SecurityProtocol='Tls12'; "; + const accept = selfSignedDirect + ? '[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}; ' + : ''; + const k = selfSignedDirect ? 'k' : ''; switch (platform) { case 'windows': // Wrapped as a single powershell.exe -Command so it pastes into // a Run box (Win+R) or an elevated prompt, not just a PS host. - return `powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "iwr '${install}' -UseBasicParsing | iex"`; + return `powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "${tls}${accept}iwr '${install}' -UseBasicParsing | iex"`; case 'linux': - return `bash -c "curl -fsSL '${install}&type=linux' | sudo bash"`; + return `bash -c "curl -fsSL${k} '${install}&type=linux' | sudo bash"`; case 'macos': - return `bash -c "curl -fsSL '${install}&type=osx' | sudo bash"`; + return `bash -c "curl -fsSL${k} '${install}&type=osx' | sudo bash"`; } }); diff --git a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte index 71d798a..4571261 100644 --- a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte +++ b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte @@ -9,8 +9,6 @@ @@ -206,18 +186,6 @@
{description} - {#if preview && freq !== 'once'} - {#if preview.valid} - - Next: {preview.nextRunsUtc - .slice(0, 3) - .map((t) => new Date(t).toLocaleString()) - .join(' · ')} - - {:else} - {preview.error} - {/if} - {/if}
@@ -285,7 +253,4 @@ font-size: 12px; } - .warn { - color: var(--warning); - } diff --git a/src/WebUI/src/lib/components/SchedulesCard.svelte b/src/WebUI/src/lib/components/SchedulesCard.svelte deleted file mode 100644 index 1c41a53..0000000 --- a/src/WebUI/src/lib/components/SchedulesCard.svelte +++ /dev/null @@ -1,277 +0,0 @@ - - -
-
-

Schedules

- {#if !adding} - - {/if} -
- - {#if assignments.length === 0 && !adding} -

- No schedules attached. Attach a cadence from Schedules to run this - script automatically. -

- {/if} - - {#each assignments as assignment (assignment.id)} -
-
- {assignment.scheduleName ?? '?'} - {scheduleCadence(assignment)} · {targetLabel(assignment)} - - {#if !assignment.scheduleEnabled} - Schedule paused - {:else if assignment.enabled && assignment.nextRunUtc} - Next: {new Date(assignment.nextRunUtc).toLocaleString()} - {:else if !assignment.enabled} - Disabled here - {/if} - {#if assignment.lastResult} - · Last: {assignment.lastResult} - {/if} - -
-
- - -
-
- {/each} - - {#if adding} -
- {#if allSchedules.length === 0} -

- No schedules defined yet — create one on the - Schedules page first. -

- {:else} - - - - -

Current run values are stored and used for every firing.

- -
- - -
- {/if} - {#if errorText}

{errorText}

{/if} -
- {/if} -
- - diff --git a/src/WebUI/src/lib/components/TriggersCard.svelte b/src/WebUI/src/lib/components/TriggersCard.svelte index 374ec21..21cc1d2 100644 --- a/src/WebUI/src/lib/components/TriggersCard.svelte +++ b/src/WebUI/src/lib/components/TriggersCard.svelte @@ -1,28 +1,56 @@ - -
-
-

Schedules

-

- Reusable cadences. Attach one to a script (with a device or group target) from the script's - Schedules panel — every assignment fires when the schedule comes due. -

-
- {#if !formOpen} - - {/if} -
- -{#if errorText}

{errorText}

{/if} - -{#if formOpen} -
-

{editing ? `Edit “${editing.name}”` : 'New schedule'}

-
- - {#key editing?.id ?? 'new'} - - {/key} -
-
- - -
-
-{/if} - -
- {#if schedules === null} -
- {#each Array(3) as _, i (i)} -
loading…
- {/each} -
- {:else if schedules.length === 0} - - {:else} - - - - - - - - - - - - - - {#each schedules as schedule (schedule.id)} - {@const s = status(schedule)} - - - - - - - - - - {/each} - -
StatusNameCadenceNext runLast firedUsed by
{s.label}{schedule.name}{scheduleCadence(schedule)} - {schedule.enabled && schedule.nextRunUtc - ? new Date(schedule.nextRunUtc).toLocaleString() - : '—'} - - {#if schedule.lastRunUtc} - - {:else} - — - {/if} - - {#if schedule.assignments.length === 0} - nothing yet - {:else} - - {/if} - - {#if !(schedule.runOnceUtc && schedule.lastRunUtc)} - - {/if} - - - -
- {/if} -
- - diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte index 9430411..eb96643 100644 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -21,7 +21,6 @@ import ParameterInputs from '$lib/components/ParameterInputs.svelte'; import SecretBindingsEditor from '$lib/components/SecretBindingsEditor.svelte'; import FileBindingsEditor from '$lib/components/FileBindingsEditor.svelte'; - import SchedulesCard from '$lib/components/SchedulesCard.svelte'; import TriggersCard from '$lib/components/TriggersCard.svelte'; const scriptId = $derived(page.params.id!); @@ -86,6 +85,18 @@ let job = $state(null); let jobState = $state(null); let outputLines = $state<{ seq: number; stream: string; text: string }[]>([]); + let outputSearch = $state(''); + let copiedOutput = $state(false); + const filteredOutput = $derived( + outputSearch.trim() + ? outputLines.filter((l) => l.text.toLowerCase().includes(outputSearch.trim().toLowerCase())) + : outputLines + ); + async function copyOutput() { + await navigator.clipboard.writeText(outputLines.map((l) => l.text).join('\n')); + copiedOutput = true; + setTimeout(() => (copiedOutput = false), 1400); + } let progress = $state(null); let unsubscribeJob: (() => void) | null = null; @@ -524,7 +535,7 @@
-

Execution

+

Targets

+ + {/if} +
{#if progress} @@ -645,8 +661,10 @@ {job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'} + {:else if filteredOutput.length === 0} + No lines match “{outputSearch}”. {:else} - {#each outputLines as line (line.seq)} + {#each filteredOutput as line (line.seq)}
{line.text}
{/each} {/if} @@ -945,6 +963,21 @@ display: flex; justify-content: space-between; align-items: center; + gap: var(--space-2); + } + + .output-tools { + display: flex; + align-items: center; + gap: var(--space-2); + margin-left: auto; + } + + .output-search { + width: 200px; + max-width: 40vw; + padding: 4px 8px; + font-size: 12px; } .group-jobs { diff --git a/src/WebUI/src/routes/settings/+page.svelte b/src/WebUI/src/routes/settings/+page.svelte index aaaa0f5..80cf1c0 100644 --- a/src/WebUI/src/routes/settings/+page.svelte +++ b/src/WebUI/src/routes/settings/+page.svelte @@ -20,13 +20,19 @@ // PUBLIC_SERVER_URL (or trusted forwarded headers) beats the browser's own // origin, so the command works even when the admin browses via an internal - // hostname the target devices cannot reach. The served script decides trust - // itself from the server's self-signed state — no operator toggle. - const installCommand = $derived( - newToken?.token - ? `iwr ${serverInfo?.baseUrl ?? location.origin}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex` - : '' - ); + // hostname the target devices cannot reach. The served script decides the + // agent's trust; this outer fetch just forces TLS 1.2 (Windows PowerShell + // 5.1 defaults lower) and accepts the cert when the server is self-signed + // and reached directly. + const installCommand = $derived.by(() => { + if (!newToken?.token) return ''; + const base = serverInfo?.baseUrl ?? location.origin; + const tls = "[Net.ServicePointManager]::SecurityProtocol='Tls12'; "; + const accept = serverInfo?.selfSignedDirect + ? '[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}; ' + : ''; + return `${tls}${accept}iwr ${base}/api/enrollment/install?token=${newToken.token} -UseBasicParsing | iex`; + }); async function refresh() { tokens = await api.bootstrapTokens().catch(() => []); diff --git a/tests/Agent.Tests/AgentConfigurationTests.cs b/tests/Agent.Tests/AgentConfigurationTests.cs index 73dabc2..ef14d05 100644 --- a/tests/Agent.Tests/AgentConfigurationTests.cs +++ b/tests/Agent.Tests/AgentConfigurationTests.cs @@ -79,7 +79,7 @@ public class AgentConfigurationTests Assert.Equal(ProtocolDefaults.DefaultInventoryInterval, config.InventoryInterval.Value); Assert.Equal(ProtocolDefaults.ReconnectMinDelay, config.ReconnectMinDelay.Value); Assert.Equal(ProtocolDefaults.ReconnectMaxDelay, config.ReconnectMaxDelay.Value); - Assert.False(config.AllowRemoteShell.Value); + Assert.True(config.AllowRemoteShell.Value); // on by default (opt-out) Assert.True(config.AllowScriptExecution.Value); Assert.False(config.TlsSkipVerify.Value); Assert.Null(config.ProxyUrl.Value); diff --git a/tests/Backend.Tests/InstallScriptTests.cs b/tests/Backend.Tests/InstallScriptTests.cs index 13b5cdf..9b843e7 100644 --- a/tests/Backend.Tests/InstallScriptTests.cs +++ b/tests/Backend.Tests/InstallScriptTests.cs @@ -143,6 +143,12 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture NullLogger.Instance); [Fact] - public async Task DeletingAScriptCascadesItsAssignmentsAndTheScheduleSurvives() + public async Task DeletingAScriptDisablesItsScheduledTriggerAndOthersStillFire() { - var scheduleId = await SeedScheduleAsync("cascade-cadence", cron: "*/5 * * * *", due: true); var survivorScriptId = await SeedScriptAsync("survivor"); var doomedScriptId = await SeedScriptAsync("doomed"); var clientId = await SeedDeviceAsync("SCHED-HOST-0"); - var doomedAssignment = await SeedAssignmentAsync(scheduleId, doomedScriptId, clientId); - var survivorAssignment = await SeedAssignmentAsync(scheduleId, survivorScriptId, clientId); + var doomedTrigger = await SeedScheduledTriggerAsync(doomedScriptId, clientId, cron: "*/5 * * * *", due: true); + var survivorTrigger = await SeedScheduledTriggerAsync(survivorScriptId, clientId, cron: "*/5 * * * *", due: true); await fixture.WithDbAsync(async db => { @@ -82,102 +82,82 @@ public class ScheduleWorkerTests : IClassFixture await db.SaveChangesAsync(); }); - await Worker().FireDueSchedulesAsync(CancellationToken.None); + await Worker().FireDueTriggersAsync(CancellationToken.None); - var (doomedGone, survivor, schedule) = await fixture.WithDbAsync(async db => await Task.FromResult(( - !db.ScriptSchedules.Any(a => a.Id == doomedAssignment), - db.ScriptSchedules.Single(a => a.Id == survivorAssignment), - db.Schedules.Single(s => s.Id == scheduleId)))); + var (doomed, survivor) = await fixture.WithDbAsync(async db => await Task.FromResult(( + db.ScriptTriggers.Single(t => t.Id == doomedTrigger), + db.ScriptTriggers.Single(t => t.Id == survivorTrigger)))); - Assert.True(doomedGone); // FK cascade removed the orphaned assignment + Assert.False(doomed.Enabled); // script gone -> disabled + Assert.Contains("no longer exists", doomed.LastResult); Assert.Contains("1 job(s) queued", survivor.LastResult); - Assert.True(schedule.Enabled); // recurring cadence survives - Assert.True(schedule.NextRunUtc > DateTimeOffset.UtcNow); + Assert.True(survivor.Enabled); // recurring survives + Assert.True(survivor.NextRunUtc > DateTimeOffset.UtcNow); } [Fact] - public async Task OneShotFiresEveryAssignmentOnceThenDisablesTheSchedule() + public async Task OneShotScheduledTriggerFiresOnceThenDisables() { - var scheduleId = await SeedScheduleAsync("once-cadence", runOnce: DateTimeOffset.UtcNow.AddMinutes(-1)); var scriptId = await SeedScriptAsync("one-shot-script"); - var clientA = await SeedDeviceAsync("SCHED-HOST-1"); - var clientB = await SeedDeviceAsync("SCHED-HOST-2"); - await SeedAssignmentAsync(scheduleId, scriptId, clientA); - await SeedAssignmentAsync(scheduleId, scriptId, clientB); + var clientId = await SeedDeviceAsync("SCHED-HOST-1"); + var triggerId = await SeedScheduledTriggerAsync( + scriptId, clientId, runOnce: DateTimeOffset.UtcNow.AddMinutes(-1)); - await Worker().FireDueSchedulesAsync(CancellationToken.None); + await Worker().FireDueTriggersAsync(CancellationToken.None); - var (schedule, jobCount) = await fixture.WithDbAsync(async db => await Task.FromResult(( - db.Schedules.Single(s => s.Id == scheduleId), - db.Jobs.Count(j => j.RequestedBy == "schedule:once-cadence")))); + var (trigger, jobCount) = await fixture.WithDbAsync(async db => await Task.FromResult(( + db.ScriptTriggers.Single(t => t.Id == triggerId), + db.Jobs.Count(j => j.ClientId == clientId && j.RequestedBy == "schedule")))); - Assert.False(schedule.Enabled); - Assert.Null(schedule.NextRunUtc); - Assert.Equal(2, jobCount); // one per assignment + Assert.False(trigger.Enabled); + Assert.Null(trigger.NextRunUtc); + Assert.Equal(1, jobCount); // A second sweep must not fire again. - await Worker().FireDueSchedulesAsync(CancellationToken.None); + await Worker().FireDueTriggersAsync(CancellationToken.None); var after = await fixture.WithDbAsync(async db => await Task.FromResult( - db.Jobs.Count(j => j.RequestedBy == "schedule:once-cadence"))); - Assert.Equal(2, after); + db.Jobs.Count(j => j.ClientId == clientId && j.RequestedBy == "schedule"))); + Assert.Equal(1, after); } [Fact] - public async Task RecurringScheduleAdvancesAndRecordsAssignmentResults() + public async Task RecurringScheduledTriggerAdvancesAndRecordsResult() { - var scheduleId = await SeedScheduleAsync("hourly-cadence", cron: "0 * * * *", due: true); var scriptId = await SeedScriptAsync("recurring-script"); var clientId = await SeedDeviceAsync("SCHED-HOST-3"); - var assignmentId = await SeedAssignmentAsync(scheduleId, scriptId, clientId); + var triggerId = await SeedScheduledTriggerAsync(scriptId, clientId, cron: "0 * * * *", due: true); - await Worker().FireDueSchedulesAsync(CancellationToken.None); + await Worker().FireDueTriggersAsync(CancellationToken.None); - var (schedule, assignment) = await fixture.WithDbAsync(async db => await Task.FromResult(( - db.Schedules.Single(s => s.Id == scheduleId), - db.ScriptSchedules.Single(a => a.Id == assignmentId)))); + var trigger = await fixture.WithDbAsync(async db => await Task.FromResult( + db.ScriptTriggers.Single(t => t.Id == triggerId))); - Assert.True(schedule.Enabled); - Assert.NotNull(schedule.LastRunUtc); - Assert.True(schedule.NextRunUtc > DateTimeOffset.UtcNow); - Assert.Contains("1 job(s) queued", assignment.LastResult); - Assert.NotNull(assignment.LastRunUtc); + Assert.True(trigger.Enabled); + Assert.NotNull(trigger.LastRunUtc); + Assert.True(trigger.NextRunUtc > DateTimeOffset.UtcNow); + Assert.Contains("1 job(s) queued", trigger.LastResult); } - private async Task SeedScheduleAsync( - string name, string? cron = null, DateTimeOffset? runOnce = null, bool due = false) + private async Task SeedScheduledTriggerAsync( + Guid scriptId, string clientId, string? cron = null, DateTimeOffset? runOnce = null, bool due = false) => await fixture.WithDbAsync(async db => { - var schedule = new ScheduleEntity + var trigger = new ScriptTriggerEntity { Id = Guid.NewGuid(), - Name = name, + ScriptId = scriptId, + ClientId = clientId, + TriggerType = ScriptTriggerType.Scheduled, CronExpression = cron, RunOnceUtc = runOnce, NextRunUtc = due || runOnce is not null ? DateTimeOffset.UtcNow.AddMinutes(-1) : DateTimeOffset.UtcNow.AddHours(1), CreatedUtc = DateTimeOffset.UtcNow, - UpdatedUtc = DateTimeOffset.UtcNow, }; - db.Schedules.Add(schedule); + db.ScriptTriggers.Add(trigger); await db.SaveChangesAsync(); - return schedule.Id; - }); - - private async Task SeedAssignmentAsync(Guid scheduleId, Guid scriptId, string clientId) - => await fixture.WithDbAsync(async db => - { - var assignment = new ScriptScheduleEntity - { - Id = Guid.NewGuid(), - ScheduleId = scheduleId, - ScriptId = scriptId, - ClientId = clientId, - CreatedUtc = DateTimeOffset.UtcNow, - }; - db.ScriptSchedules.Add(assignment); - await db.SaveChangesAsync(); - return assignment.Id; + return trigger.Id; }); private async Task SeedScriptAsync(string name)