Standalone NATS + install fixes, unified triggers, richer inventory & docs #11

Merged
gsadmin merged 13 commits from dev into main 2026-08-10 12:53:28 +00:00
73 changed files with 6283 additions and 2039 deletions
+23 -30
View File
@@ -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:<name>` 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:<type>`.
- 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.
---
Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 KiB

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 207 KiB

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 209 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

After

Width:  |  Height:  |  Size: 237 KiB

@@ -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),
@@ -9,6 +9,7 @@ public static class AgentConfigurationKeys
public const string InventoryInterval = "InventoryInterval";
public const string ReconnectMinDelay = "ReconnectMinDelay";
public const string ReconnectMaxDelay = "ReconnectMaxDelay";
/// <summary>DWORD: remote shell. On by default; set 0 to opt out.</summary>
public const string AllowRemoteShell = "AllowRemoteShell";
public const string AllowScriptExecution = "AllowScriptExecution";
+81 -7
View File
@@ -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);
}
/// <summary>
/// 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").
/// </summary>
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()
@@ -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,
+2 -21
View File
@@ -24,8 +24,6 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
public DbSet<ScriptTriggerRunEntity> ScriptTriggerRuns => Set<ScriptTriggerRunEntity>();
public DbSet<AppSettingEntity> AppSettings => Set<AppSettingEntity>();
public DbSet<SecretsProviderEntity> SecretsProviders => Set<SecretsProviderEntity>();
public DbSet<ScheduleEntity> Schedules => Set<ScheduleEntity>();
public DbSet<ScriptScheduleEntity> ScriptSchedules => Set<ScriptScheduleEntity>();
/// <summary>
/// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores
@@ -159,6 +157,8 @@ public class AppDbContext(DbContextOptions<AppDbContext> 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<string>();
});
@@ -182,24 +182,5 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
entity.HasIndex(e => e.Name).IsUnique();
});
modelBuilder.Entity<ScheduleEntity>(entity =>
{
entity.ToTable("Schedules");
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.Name).IsUnique();
entity.HasIndex(e => e.NextRunUtc);
});
modelBuilder.Entity<ScriptScheduleEntity>(entity =>
{
entity.ToTable("ScriptSchedules");
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.ScheduleId);
entity.HasIndex(e => e.ScriptId);
entity.HasOne<ScheduleEntity>().WithMany()
.HasForeignKey(e => e.ScheduleId).OnDelete(DeleteBehavior.Cascade);
entity.HasOne<ScriptEntity>().WithMany()
.HasForeignKey(e => e.ScriptId).OnDelete(DeleteBehavior.Cascade);
});
}
}
+6 -38
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
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")));
+13 -10
View File
@@ -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,
+25 -47
View File
@@ -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;
/// <summary>Run at most once per device (default) or every time the event fires.</summary>
/// <summary>
/// Event triggers (OnRegistration/OnAgentReady) run at most once per device.
/// Not applicable to Scheduled triggers. No longer operator-configurable.
/// </summary>
public bool OncePerDevice { get; set; } = true;
// Scheduled-trigger timing (unused for event types).
/// <summary>5-field cron for a recurring schedule; null for one-shot.</summary>
public string? CronExpression { get; set; }
/// <summary>Fire time for a one-shot schedule; null for recurring.</summary>
public DateTimeOffset? RunOnceUtc { get; set; }
public string TimeZoneId { get; set; } = "UTC";
public DateTimeOffset? NextRunUtc { get; set; }
public DateTimeOffset? LastRunUtc { get; set; }
/// <summary>Argument values captured for scheduled runs (JSON).</summary>
public string? ArgumentsJson { get; set; }
/// <summary>Human-readable outcome of the last scheduled firing.</summary>
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; }
}
/// <summary>
/// A reusable cadence object: one-shot (<see cref="RunOnceUtc"/>) or recurring
/// (<see cref="CronExpression"/>, evaluated in <see cref="TimeZoneId"/>).
/// Schedules carry no script or target — objects (scripts) honor a schedule
/// through <see cref="ScriptScheduleEntity"/> associations.
/// </summary>
public sealed class ScheduleEntity
{
public Guid Id { get; set; }
public required string Name { get; set; }
/// <summary>5-field cron for recurring schedules; null for one-shot.</summary>
public string? CronExpression { get; set; }
/// <summary>Fire time for one-shot schedules; null for recurring.</summary>
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; }
}
/// <summary>
/// A script honoring a schedule: when the schedule fires, this script runs
/// against exactly one of <see cref="ClientId"/> / <see cref="GroupId"/>
/// (group members resolved at fire time) with the stored argument values.
/// </summary>
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; }
/// <summary>Argument values captured when the association was saved.</summary>
public string? ArgumentsJson { get; set; }
public bool Enabled { get; set; } = true;
public DateTimeOffset? LastRunUtc { get; set; }
/// <summary>Human-readable outcome of the last firing (job counts or the error).</summary>
public string? LastResult { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public string? CreatedBy { get; set; }
}
/// <summary>
/// A configured external secrets store (e.g. Infisical). Connection settings
/// are a Data Protection-encrypted JSON blob; only the backend ever decrypts
@@ -0,0 +1,839 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
[DbContext(typeof(PostgresAppDbContext))]
[Migration("20260810114752_UnifyTriggers")]
partial class UnifyTriggers
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("text");
b.Property<bool>("IsSecret")
.HasColumnType("boolean");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Actor")
.HasColumnType("text");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("Detail")
.HasColumnType("text");
b.Property<string>("RemoteIp")
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("timestamp with time zone");
b.Property<int>("MaxUses")
.HasColumnType("integer");
b.Property<string>("Note")
.HasColumnType("text");
b.Property<bool>("Revoked")
.HasColumnType("boolean");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Uses")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("AgentVersion")
.HasColumnType("text");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uuid");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddressesJson")
.HasColumnType("text");
b.Property<bool>("IsOrphaned")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Manufacturer")
.HasColumnType("text");
b.Property<string>("Model")
.HasColumnType("text");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("OsCaption")
.HasColumnType("text");
b.Property<string>("OsVersion")
.HasColumnType("text");
b.Property<string>("PublicIp")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("TagsJson")
.HasColumnType("text");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RulesJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ExitCode")
.HasColumnType("integer");
b.Property<string>("OutputSummary")
.HasColumnType("text");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("text");
b.Property<bool>("IsSystem")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("text");
b.Property<string>("PermissionsJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.HasIndex("NextRunUtc");
b.ToTable("Schedules", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("FileBindingsJson")
.HasColumnType("text");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("text");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ParametersJson")
.HasColumnType("text");
b.Property<string>("SecretBindingsJson")
.HasColumnType("text");
b.Property<string>("SecretsVariableName")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ArgumentsJson")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("LastResult")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScheduleId")
.HasColumnType("uuid");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ArgumentsJson")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("LastResult")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<Guid>("TriggerId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseReason")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasColumnType("text");
b.Property<string>("ExternalId")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.HasColumnType("boolean");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("RoleId")
.HasColumnType("uuid");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.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
}
}
}
@@ -0,0 +1,109 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class UnifyTriggers : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ArgumentsJson",
table: "ScriptTriggers",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ClientId",
table: "ScriptTriggers",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CronExpression",
table: "ScriptTriggers",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastResult",
table: "ScriptTriggers",
type: "text",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "LastRunUtc",
table: "ScriptTriggers",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "NextRunUtc",
table: "ScriptTriggers",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "RunOnceUtc",
table: "ScriptTriggers",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "TimeZoneId",
table: "ScriptTriggers",
type: "text",
nullable: false,
defaultValue: "");
migrationBuilder.CreateIndex(
name: "IX_ScriptTriggers_NextRunUtc",
table: "ScriptTriggers",
column: "NextRunUtc");
}
/// <inheritdoc />
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");
}
}
}
@@ -0,0 +1,728 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
[DbContext(typeof(PostgresAppDbContext))]
[Migration("20260810120704_RemoveSchedules")]
partial class RemoveSchedules
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("text");
b.Property<bool>("IsSecret")
.HasColumnType("boolean");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Actor")
.HasColumnType("text");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("Detail")
.HasColumnType("text");
b.Property<string>("RemoteIp")
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("timestamp with time zone");
b.Property<int>("MaxUses")
.HasColumnType("integer");
b.Property<string>("Note")
.HasColumnType("text");
b.Property<bool>("Revoked")
.HasColumnType("boolean");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Uses")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("AgentVersion")
.HasColumnType("text");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uuid");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("text");
b.Property<string>("IpAddressesJson")
.HasColumnType("text");
b.Property<bool>("IsOrphaned")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Manufacturer")
.HasColumnType("text");
b.Property<string>("Model")
.HasColumnType("text");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("OsCaption")
.HasColumnType("text");
b.Property<string>("OsVersion")
.HasColumnType("text");
b.Property<string>("PublicIp")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("TagsJson")
.HasColumnType("text");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("RulesJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ExitCode")
.HasColumnType("integer");
b.Property<string>("OutputSummary")
.HasColumnType("text");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("text");
b.Property<bool>("IsSystem")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("text");
b.Property<string>("PermissionsJson")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("FileBindingsJson")
.HasColumnType("text");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("text");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ParametersJson")
.HasColumnType("text");
b.Property<string>("SecretBindingsJson")
.HasColumnType("text");
b.Property<string>("SecretsVariableName")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ArgumentsJson")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("LastResult")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("JobId")
.HasColumnType("uuid");
b.Property<Guid>("TriggerId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CloseReason")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("RequestedBy")
.HasColumnType("text");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasColumnType("text");
b.Property<string>("ExternalId")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.HasColumnType("boolean");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("RoleId")
.HasColumnType("uuid");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,101 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class RemoveSchedules : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
CreatedBy = table.Column<string>(type: "text", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CronExpression = table.Column<string>(type: "text", nullable: true),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
Name = table.Column<string>(type: "text", nullable: false),
NextRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
TimeZoneId = table.Column<string>(type: "text", nullable: false),
UpdatedBy = table.Column<string>(type: "text", nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(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<Guid>(type: "uuid", nullable: false),
ArgumentsJson = table.Column<string>(type: "text", nullable: true),
ClientId = table.Column<string>(type: "text", nullable: true),
CreatedBy = table.Column<string>(type: "text", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
GroupId = table.Column<Guid>(type: "uuid", nullable: true),
LastResult = table.Column<string>(type: "text", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
ScheduleId = table.Column<Guid>(type: "uuid", nullable: false),
ScriptId = table.Column<Guid>(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");
}
}
}
@@ -445,57 +445,6 @@ namespace Backend.Data.Migrations.Postgres
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.HasIndex("NextRunUtc");
b.ToTable("Schedules", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -569,6 +518,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
@@ -581,51 +533,30 @@ namespace Backend.Data.Migrations.Postgres
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScheduleId")
.HasColumnType("uuid");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
@@ -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");
@@ -0,0 +1,839 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
[DbContext(typeof(SqlServerAppDbContext))]
[Migration("20260810114757_UnifyTriggers")]
partial class UnifyTriggers
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsSecret")
.HasColumnType("bit");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Actor")
.HasColumnType("nvarchar(max)");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("Detail")
.HasColumnType("nvarchar(max)");
b.Property<string>("RemoteIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("datetimeoffset");
b.Property<int>("MaxUses")
.HasColumnType("int");
b.Property<string>("Note")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Revoked")
.HasColumnType("bit");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Uses")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("AgentVersion")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("IpAddressesJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsOrphaned")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Manufacturer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Model")
.HasColumnType("nvarchar(max)");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("OsCaption")
.HasColumnType("nvarchar(max)");
b.Property<string>("OsVersion")
.HasColumnType("nvarchar(max)");
b.Property<string>("PublicIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("TagsJson")
.HasColumnType("nvarchar(max)");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("RulesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<Guid>("GroupId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<int?>("ExitCode")
.HasColumnType("int");
b.Property<string>("OutputSummary")
.HasColumnType("nvarchar(max)");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsSystem")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("PermissionsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("FileBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("ParametersJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretsVariableName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ArgumentsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LastResult")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScheduleId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ArgumentsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LastResult")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("TriggerId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("CloseReason")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("ExternalId")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("MustChangePassword")
.HasColumnType("bit");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.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
}
}
}
@@ -0,0 +1,109 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class UnifyTriggers : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ArgumentsJson",
table: "ScriptTriggers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ClientId",
table: "ScriptTriggers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CronExpression",
table: "ScriptTriggers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastResult",
table: "ScriptTriggers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "LastRunUtc",
table: "ScriptTriggers",
type: "datetimeoffset",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "NextRunUtc",
table: "ScriptTriggers",
type: "datetimeoffset",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "RunOnceUtc",
table: "ScriptTriggers",
type: "datetimeoffset",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "TimeZoneId",
table: "ScriptTriggers",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
migrationBuilder.CreateIndex(
name: "IX_ScriptTriggers_NextRunUtc",
table: "ScriptTriggers",
column: "NextRunUtc");
}
/// <inheritdoc />
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");
}
}
}
@@ -0,0 +1,728 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
[DbContext(typeof(SqlServerAppDbContext))]
[Migration("20260810120710_RemoveSchedules")]
partial class RemoveSchedules
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsSecret")
.HasColumnType("bit");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("Action")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Actor")
.HasColumnType("nvarchar(max)");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("Detail")
.HasColumnType("nvarchar(max)");
b.Property<string>("RemoteIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("ExpiresUtc")
.HasColumnType("datetimeoffset");
b.Property<int>("MaxUses")
.HasColumnType("int");
b.Property<string>("Note")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Revoked")
.HasColumnType("bit");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("Uses")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("AgentVersion")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("EnrolledUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("EnrollmentId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("IpAddressesJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsOrphaned")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LastSeenUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Manufacturer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Model")
.HasColumnType("nvarchar(max)");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("OrphanedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("OsCaption")
.HasColumnType("nvarchar(max)");
b.Property<string>("OsVersion")
.HasColumnType("nvarchar(max)");
b.Property<string>("PublicIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("TagsJson")
.HasColumnType("nvarchar(max)");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("RulesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AddedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<Guid>("GroupId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset?>("CompletedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<int?>("ExitCode")
.HasColumnType("int");
b.Property<string>("OutputSummary")
.HasColumnType("nvarchar(max)");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("StartedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<long>("Sequence")
.HasColumnType("bigint");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("TimestampUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsSystem")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("PermissionsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("FileBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("ParametersJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecretsVariableName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ArgumentsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LastResult")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset>("FiredUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("JobId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("TriggerId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("CloseReason")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ClosedUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("RequestedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("ExternalId")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("MustChangePassword")
.HasColumnType("bit");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<Guid?>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,101 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class RemoveSchedules : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CronExpression = table.Column<string>(type: "nvarchar(max)", nullable: true),
Enabled = table.Column<bool>(type: "bit", nullable: false),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
NextRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
TimeZoneId = table.Column<string>(type: "nvarchar(max)", nullable: false),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Schedules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScriptSchedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ArgumentsJson = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClientId = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
GroupId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
LastResult = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
ScheduleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ScriptId = table.Column<Guid>(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");
}
}
}
@@ -445,57 +445,6 @@ namespace Backend.Data.Migrations.SqlServer
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("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<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -569,6 +518,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
@@ -581,51 +533,30 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScheduleId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
@@ -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");
@@ -0,0 +1,826 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
[DbContext(typeof(SqliteAppDbContext))]
[Migration("20260810114748_UnifyTriggers")]
partial class UnifyTriggers
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.10");
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Action")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Actor")
.HasColumnType("TEXT");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("Detail")
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresUtc")
.HasColumnType("INTEGER");
b.Property<int>("MaxUses")
.HasColumnType("INTEGER");
b.Property<string>("Note")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Uses")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("AgentVersion")
.HasColumnType("TEXT");
b.Property<long>("EnrolledUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("EnrollmentId")
.HasColumnType("TEXT");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("IpAddressesJson")
.HasColumnType("TEXT");
b.Property<bool>("IsOrphaned")
.HasColumnType("INTEGER");
b.Property<long?>("LastSeenUtc")
.HasColumnType("INTEGER");
b.Property<string>("Manufacturer")
.HasColumnType("TEXT");
b.Property<string>("Model")
.HasColumnType("TEXT");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("OrphanedUtc")
.HasColumnType("INTEGER");
b.Property<string>("OsCaption")
.HasColumnType("TEXT");
b.Property<string>("OsVersion")
.HasColumnType("TEXT");
b.Property<string>("PublicIp")
.HasColumnType("TEXT");
b.Property<long?>("ReadyUtc")
.HasColumnType("INTEGER");
b.Property<string>("TagsJson")
.HasColumnType("TEXT");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RulesJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AddedUtc")
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("CompletedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<int?>("ExitCode")
.HasColumnType("INTEGER");
b.Property<string>("OutputSummary")
.HasColumnType("TEXT");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("StartedUtc")
.HasColumnType("INTEGER");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<long>("Sequence")
.HasColumnType("INTEGER");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("TEXT");
b.Property<bool>("IsSystem")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("TEXT");
b.Property<string>("PermissionsJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("FileBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("TEXT");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ParametersJson")
.HasColumnType("TEXT");
b.Property<string>("SecretBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("SecretsVariableName")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ArgumentsJson")
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<string>("LastResult")
.HasColumnType("TEXT");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScheduleId")
.HasColumnType("TEXT");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ArgumentsJson")
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<string>("LastResult")
.HasColumnType("TEXT");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("FiredUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<Guid>("TriggerId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CloseReason")
.HasColumnType("TEXT");
b.Property<long?>("ClosedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasColumnType("TEXT");
b.Property<long?>("LastLoginUtc")
.HasColumnType("INTEGER");
b.Property<bool>("MustChangePassword")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid?>("RoleId")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.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
}
}
}
@@ -0,0 +1,108 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class UnifyTriggers : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ArgumentsJson",
table: "ScriptTriggers",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ClientId",
table: "ScriptTriggers",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CronExpression",
table: "ScriptTriggers",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastResult",
table: "ScriptTriggers",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "LastRunUtc",
table: "ScriptTriggers",
type: "INTEGER",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "NextRunUtc",
table: "ScriptTriggers",
type: "INTEGER",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "RunOnceUtc",
table: "ScriptTriggers",
type: "INTEGER",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "TimeZoneId",
table: "ScriptTriggers",
type: "TEXT",
nullable: false,
defaultValue: "");
migrationBuilder.CreateIndex(
name: "IX_ScriptTriggers_NextRunUtc",
table: "ScriptTriggers",
column: "NextRunUtc");
}
/// <inheritdoc />
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");
}
}
}
@@ -0,0 +1,715 @@
// <auto-generated />
using System;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
[DbContext(typeof(SqliteAppDbContext))]
[Migration("20260810120658_RemoveSchedules")]
partial class RemoveSchedules
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.10");
modelBuilder.Entity("Backend.Data.AppSettingEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<bool>("IsSecret")
.HasColumnType("INTEGER");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("AppSettings", (string)null);
});
modelBuilder.Entity("Backend.Data.AuditEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Action")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Actor")
.HasColumnType("TEXT");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("Detail")
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TimestampUtc");
b.ToTable("AuditEvents", (string)null);
});
modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresUtc")
.HasColumnType("INTEGER");
b.Property<int>("MaxUses")
.HasColumnType("INTEGER");
b.Property<string>("Note")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Uses")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("BootstrapTokens", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("AgentVersion")
.HasColumnType("TEXT");
b.Property<long>("EnrolledUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("EnrollmentId")
.HasColumnType("TEXT");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("IpAddressesJson")
.HasColumnType("TEXT");
b.Property<bool>("IsOrphaned")
.HasColumnType("INTEGER");
b.Property<long?>("LastSeenUtc")
.HasColumnType("INTEGER");
b.Property<string>("Manufacturer")
.HasColumnType("TEXT");
b.Property<string>("Model")
.HasColumnType("TEXT");
b.Property<string>("NkeyPublic")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("OrphanedUtc")
.HasColumnType("INTEGER");
b.Property<string>("OsCaption")
.HasColumnType("TEXT");
b.Property<string>("OsVersion")
.HasColumnType("TEXT");
b.Property<string>("PublicIp")
.HasColumnType("TEXT");
b.Property<long?>("ReadyUtc")
.HasColumnType("INTEGER");
b.Property<string>("TagsJson")
.HasColumnType("TEXT");
b.HasKey("ClientId");
b.HasIndex("Hostname");
b.ToTable("Devices", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RulesJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("DeviceGroups", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AddedUtc")
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("GroupId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("GroupId", "ClientId")
.IsUnique();
b.ToTable("DeviceGroupMembers", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("ReportJson")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("ClientId");
b.ToTable("DeviceInventory", (string)null);
});
modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("FunctionModules", (string)null);
});
modelBuilder.Entity("Backend.Data.JobEntity", b =>
{
b.Property<Guid>("JobId")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("CompletedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<int?>("ExitCode")
.HasColumnType("INTEGER");
b.Property<string>("OutputSummary")
.HasColumnType("TEXT");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("ScriptName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("StartedUtc")
.HasColumnType("INTEGER");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("JobId");
b.HasIndex("ClientId");
b.HasIndex("CreatedUtc");
b.ToTable("Jobs", (string)null);
});
modelBuilder.Entity("Backend.Data.JobOutputEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<long>("Sequence")
.HasColumnType("INTEGER");
b.Property<string>("Stream")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TimestampUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("JobId", "Sequence")
.IsUnique();
b.ToTable("JobOutput", (string)null);
});
modelBuilder.Entity("Backend.Data.OidcProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Authority")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("OidcProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.RoleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceScopeGroupIdsJson")
.HasColumnType("TEXT");
b.Property<bool>("IsSystem")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("OidcClaimValuesJson")
.HasColumnType("TEXT");
b.Property<string>("PermissionsJson")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("FileBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("TEXT");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ParametersJson")
.HasColumnType("TEXT");
b.Property<string>("SecretBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("SecretsVariableName")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ArgumentsJson")
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<string>("LastResult")
.HasColumnType("TEXT");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("FiredUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("JobId")
.HasColumnType("TEXT");
b.Property<Guid>("TriggerId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TriggerId", "ClientId")
.IsUnique();
b.ToTable("ScriptTriggerRuns", (string)null);
});
modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ConfigProtected")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("SecretsProviders", (string)null);
});
modelBuilder.Entity("Backend.Data.ShellSessionEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CloseReason")
.HasColumnType("TEXT");
b.Property<long?>("ClosedUtc")
.HasColumnType("INTEGER");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("RequestedBy")
.HasColumnType("TEXT");
b.Property<string>("State")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("ShellSessions", (string)null);
});
modelBuilder.Entity("Backend.Data.UserEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("AuthProvider")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("ExternalId")
.HasColumnType("TEXT");
b.Property<long?>("LastLoginUtc")
.HasColumnType("INTEGER");
b.Property<bool>("MustChangePassword")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid?>("RoleId")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,101 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class RemoveSchedules : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CronExpression = table.Column<string>(type: "TEXT", nullable: true),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
Name = table.Column<string>(type: "TEXT", nullable: false),
NextRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
RunOnceUtc = table.Column<long>(type: "INTEGER", nullable: true),
TimeZoneId = table.Column<string>(type: "TEXT", nullable: false),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Schedules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScriptSchedules",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ArgumentsJson = table.Column<string>(type: "TEXT", nullable: true),
ClientId = table.Column<string>(type: "TEXT", nullable: true),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
GroupId = table.Column<Guid>(type: "TEXT", nullable: true),
LastResult = table.Column<string>(type: "TEXT", nullable: true),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
ScheduleId = table.Column<Guid>(type: "TEXT", nullable: false),
ScriptId = table.Column<Guid>(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");
}
}
}
@@ -434,57 +434,6 @@ namespace Backend.Data.Migrations.Sqlite
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Backend.Data.ScheduleEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("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<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -558,6 +507,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
@@ -570,51 +522,30 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScheduleId")
.HasColumnType("TEXT");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("TriggerType");
b.ToTable("ScriptTriggers", (string)null);
@@ -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");
+25 -13
View File
@@ -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.
/// </summary>
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'
+9 -1
View File
@@ -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;
}
+53 -4
View File
@@ -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<IResult> 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<IResult> 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 });
-400
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<IResult> 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<IResult> 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<IResult> 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<IResult> 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();
}
/// <summary>Validates a cron and returns its next occurrences — the UI's ground truth.</summary>
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<IResult> ListAssignmentsAsync(
AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken)
=> Results.Ok(await LoadAssignmentDtosAsync(db, scriptId, scheduleId, cancellationToken));
private static async Task<IResult> 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<IResult> 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<IResult> 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<string?> 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<List<ScheduleAssignmentDto>> 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<ScheduleAssignmentDto> assignments) => new(
s.Id,
s.Name,
s.CronExpression,
s.RunOnceUtc,
s.TimeZoneId,
s.Enabled,
s.NextRunUtc,
s.LastRunUtc,
s.UpdatedUtc,
s.UpdatedBy,
assignments);
}
+65 -95
View File
@@ -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;
/// <summary>
/// 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
/// <see cref="Backend.Groups.ScriptTriggerService"/>, not here.
/// </summary>
public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<ScheduleWorker> logger)
: BackgroundService
@@ -24,7 +27,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
{
try
{
await FireDueSchedulesAsync(stoppingToken);
await FireDueTriggersAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
@@ -32,7 +35,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
}
catch (Exception ex)
{
logger.LogError(ex, "Schedule sweep failed");
logger.LogError(ex, "Scheduled-trigger sweep failed");
}
try
@@ -46,7 +49,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
}
}
internal async Task FireDueSchedulesAsync(CancellationToken cancellationToken)
internal async Task FireDueTriggersAsync(CancellationToken cancellationToken)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
@@ -54,174 +57,141 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
var groups = scope.ServiceProvider.GetRequiredService<DeviceGroupService>();
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<Guid, PreparedScript>();
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<Guid, PreparedScript> 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<Dictionary<string, JsonElement>>(assignment.ArgumentsJson);
: JsonDefaults.Deserialize<Dictionary<string, JsonElement>>(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<List<DeviceEntity>> 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;
}
}
}
-1
View File
@@ -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);
+12 -1
View File
@@ -36,10 +36,21 @@ public static class MessagingWsProxy
.GetRequiredService<ILoggerFactory>()
.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)
{
+76 -1
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.IO;
namespace Backend.Standalone;
@@ -16,6 +17,9 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger<NatsSideca
{
private readonly CancellationTokenSource stopping = new();
private Task? supervisor;
private volatile Process? running;
private FileSystemWatcher? certWatcher;
private Timer? reloadDebounce;
public static bool IsEnabled(IConfiguration configuration)
=> configuration["NATS_SIDECAR"] == "1";
@@ -51,11 +55,14 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger<NatsSideca
}
supervisor = Task.Run(() => 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<NatsSideca
try
{
process.Start();
running = process;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
logger.LogInformation("NATS sidecar started (pid {Pid})", process.Id);
delay = TimeSpan.FromSeconds(1);
await process.WaitForExitAsync(stoppingToken);
running = null;
logger.LogWarning("NATS sidecar exited with {Code}", process.ExitCode);
}
catch (OperationCanceledException)
@@ -171,5 +180,71 @@ public sealed class NatsSidecar(IConfiguration configuration, ILogger<NatsSideca
logger.LogWarning("NATS sidecar did not report healthy in time; continuing anyway");
}
public void Dispose() => stopping.Dispose();
/// <summary>
/// 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).
/// </summary>
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");
}
}
/// <summary>Coalesces the renewal's cert+key writes, then bounces the process.</summary>
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();
}
}
+31 -18
View File
@@ -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}}",
+5 -2
View File
@@ -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;
'' '';
}
+8 -10
View File
@@ -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 "";
}
}
+16 -8
View File
@@ -53,6 +53,12 @@
<Property Id="NATSPORT" Value="4222" />
<Property Id="NATSWSPORT" Value="9222" />
<Property Id="NATSMONITORPORT" Value="8222" />
<!-- The NATS WebSocket listener binds here (core + monitor always stay on
loopback). Loopback by default — the server relays /messaging/* over
loopback. Set to 0.0.0.0 only when an edge proxy on another host must
reach the WebSocket directly; over self-signed TLS it reuses the
managed leaf certificate. -->
<Property Id="NATSBIND" Value="127.0.0.1" />
<!-- Self-Signed TLS is on by default; unchecking the Network page
checkbox (or ENABLETLS="" on the command line) opts out. -->
@@ -104,7 +110,7 @@
the quotes around ENABLETLS are load-bearing: unchecked formats to
an empty quoted argument, which setup reads as off. -->
<SetProperty Id="RunServerSetup"
Value="&quot;[INSTALLFOLDER]ExecuteR-Server.exe&quot; setup --admin-user &quot;[ADMINUSERNAME]&quot; --admin-password &quot;[ADMINPASSWORD]&quot; --bind &quot;[BINDADDRESS]&quot; --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --tls &quot;[ENABLETLS]&quot;"
Value="&quot;[INSTALLFOLDER]ExecuteR-Server.exe&quot; setup --admin-user &quot;[ADMINUSERNAME]&quot; --admin-password &quot;[ADMINPASSWORD]&quot; --bind &quot;[BINDADDRESS]&quot; --http [HTTPPORT] --nats [NATSPORT] --ws [NATSWSPORT] --monitor [NATSMONITORPORT] --nb &quot;[NATSBIND]&quot; --tls &quot;[ENABLETLS]&quot;"
Sequence="execute"
Before="RunServerSetup" />
<CustomAction Id="RunServerSetup"
@@ -225,13 +231,15 @@
Property="HTTPPORT" />
<Control Id="NatsLabel" Type="Text" X="20" Y="128" Width="330" Height="12" NoPrefix="yes"
Text="Internal NATS ports (loopback-only; change only on a conflict):" />
<Control Id="NatsCoreLabel" Type="Text" X="20" Y="143" Width="70" Height="10" NoPrefix="yes" Text="Core" />
<Control Id="NatsCoreEdit" Type="Edit" X="20" Y="154" Width="70" Height="16" Property="NATSPORT" />
<Control Id="NatsWsLabel" Type="Text" X="110" Y="143" Width="70" Height="10" NoPrefix="yes" Text="WebSocket" />
<Control Id="NatsWsEdit" Type="Edit" X="110" Y="154" Width="70" Height="16" Property="NATSWSPORT" />
<Control Id="NatsMonLabel" Type="Text" X="200" Y="143" Width="70" Height="10" NoPrefix="yes" Text="Monitor" />
<Control Id="NatsMonEdit" Type="Edit" X="200" Y="154" Width="70" Height="16" Property="NATSMONITORPORT" />
Text="NATS ports; WS bind opens the WebSocket for a remote edge proxy (core/monitor stay local):" />
<Control Id="NatsBindLabel" Type="Text" X="20" Y="143" Width="85" Height="10" NoPrefix="yes" Text="WS bind" />
<Control Id="NatsBindEdit" Type="Edit" X="20" Y="154" Width="85" Height="16" Property="NATSBIND" />
<Control Id="NatsCoreLabel" Type="Text" X="115" Y="143" Width="55" Height="10" NoPrefix="yes" Text="Core" />
<Control Id="NatsCoreEdit" Type="Edit" X="115" Y="154" Width="55" Height="16" Property="NATSPORT" />
<Control Id="NatsWsLabel" Type="Text" X="180" Y="143" Width="55" Height="10" NoPrefix="yes" Text="WebSocket" />
<Control Id="NatsWsEdit" Type="Edit" X="180" Y="154" Width="55" Height="16" Property="NATSWSPORT" />
<Control Id="NatsMonLabel" Type="Text" X="245" Y="143" Width="55" Height="10" NoPrefix="yes" Text="Monitor" />
<Control Id="NatsMonEdit" Type="Edit" X="245" Y="154" Width="55" Height="16" Property="NATSMONITORPORT" />
<Control Id="TlsCheck" Type="CheckBox" X="20" Y="176" Width="330" Height="12"
Property="ENABLETLS" CheckBoxValue="1"
-8
View File
@@ -68,12 +68,6 @@ public static class ApiRoutes
/// <summary>Public self-signed CA chain (root + intermediate) for agent trust.</summary>
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}";
+23 -77
View File
@@ -49,25 +49,43 @@ public sealed record PreviewGroupRequest(GroupRuleSet Rules);
/// <summary>PUT /api/devices/{clientId}/tags request body.</summary>
public sealed record UpdateDeviceTagsRequest(IReadOnlyList<string> Tags);
/// <summary>Script trigger resource.</summary>
/// <summary>
/// Unified script trigger: when (event or schedule) + target (device/group/all)
/// + optional captured arguments. Replaces the separate schedule concept.
/// </summary>
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);
/// <summary>POST /api/triggers request body.</summary>
/// <summary>
/// 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.
/// </summary>
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<string, System.Text.Json.JsonElement>? Arguments = null);
/// <summary>Device detail for GET /api/devices/{clientId}.</summary>
public sealed record DeviceDetailDto(
@@ -214,78 +232,6 @@ public sealed record DashboardDto(
IReadOnlyList<DayPoint> Timeline,
IReadOnlyList<JobDto> RecentRuns);
/// <summary>
/// A reusable cadence object. Scripts honor a schedule through assignments —
/// the schedule itself carries no script or target.
/// </summary>
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<ScheduleAssignmentDto> Assignments);
/// <summary>
/// POST/PUT /api/schedules body. Exactly one of
/// <c>CronExpression</c>/<c>RunOnceUtc</c>.
/// </summary>
public sealed record SaveScheduleRequest(
string Name,
string? CronExpression,
DateTimeOffset? RunOnceUtc,
string? TimeZoneId = null,
bool Enabled = true);
/// <summary>
/// One script honoring a schedule against one device or group. Carries the
/// schedule's cadence so consumers can describe it without a second lookup.
/// </summary>
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);
/// <summary>
/// POST/PUT /api/schedule-assignments body. Exactly one of
/// <c>ClientId</c>/<c>GroupId</c>. Null <c>Arguments</c> keeps stored values.
/// </summary>
public sealed record SaveScheduleAssignmentRequest(
Guid ScheduleId,
Guid ScriptId,
string? ClientId,
Guid? GroupId,
IReadOnlyDictionary<string, System.Text.Json.JsonElement>? Arguments = null,
bool Enabled = true);
/// <summary>POST /api/schedules/preview body.</summary>
public sealed record SchedulePreviewRequest(string CronExpression, string? TimeZoneId = null);
/// <summary>Validation + the next concrete occurrences, so the UI never guesses.</summary>
public sealed record SchedulePreviewDto(
bool Valid,
string? Error,
IReadOnlyList<DateTimeOffset> NextRunsUtc);
/// <summary>One stored output record for GET /api/jobs/{jobId}/output.</summary>
public sealed record JobOutputRecordDto(
long Sequence,
+7
View File
@@ -48,6 +48,13 @@ public enum ScriptTriggerType
/// <summary>Fires when the agent is connected and consuming job commands.</summary>
OnAgentReady,
/// <summary>
/// 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.
/// </summary>
Scheduled,
}
/// <summary>Remote shell session lifecycle states.</summary>
+10 -2
View File
@@ -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,
@@ -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;
}
/// <summary>
+6 -38
View File
@@ -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<ScheduleDto[]>('/api/schedules'),
createSchedule: (body: SaveScheduleBody) =>
request<ScheduleDto>('/api/schedules', { method: 'POST', body: JSON.stringify(body) }),
updateSchedule: (id: string, body: SaveScheduleBody) =>
request<ScheduleDto>(`/api/schedules/${id}`, { method: 'PUT', body: JSON.stringify(body) }),
deleteSchedule: (id: string) => request<void>(`/api/schedules/${id}`, { method: 'DELETE' }),
previewSchedule: (cronExpression: string, timeZoneId?: string) =>
request<SchedulePreviewDto>('/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<ScheduleAssignmentDto[]>(`/api/schedule-assignments${qs}`);
},
createScheduleAssignment: (body: SaveScheduleAssignmentBody) =>
request<ScheduleAssignmentDto>('/api/schedule-assignments', {
method: 'POST',
body: JSON.stringify(body)
}),
updateScheduleAssignment: (id: string, body: SaveScheduleAssignmentBody) =>
request<ScheduleAssignmentDto>(`/api/schedule-assignments/${id}`, {
method: 'PUT',
body: JSON.stringify(body)
}),
deleteScheduleAssignment: (id: string) =>
request<void>(`/api/schedule-assignments/${id}`, { method: 'DELETE' }),
// Groups
groups: () => request<DeviceGroupDto[]>('/api/groups'),
@@ -273,10 +237,14 @@ export const api = {
triggers: () => request<ScriptTriggerDto[]>('/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<string, unknown>;
}) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }),
deleteTrigger: (id: string) => request<void>(`/api/triggers/${id}`, { method: 'DELETE' }),
+14 -61
View File
@@ -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<string, unknown>;
enabled: boolean;
}
export interface SchedulePreviewDto {
valid: boolean;
error?: string;
nextRunsUtc: string[];
}
export interface CountPoint {
label: string;
count: number;
@@ -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<typeof setTimeout> | 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"`;
}
});
@@ -9,8 +9,6 @@
</script>
<script lang="ts">
import { api } from '$lib/api/client';
import type { SchedulePreviewDto } from '$lib/api/types';
import { describeCron } from '$lib/schedule/cron-describe';
let {
@@ -32,7 +30,6 @@
let onceLocal = $state('');
let cron = $state('0 1 * * *');
let timeZone = $state('UTC');
let preview = $state<SchedulePreviewDto | null>(null);
// Editing an existing schedule: seed the form once from its stored cadence.
// Parents key this component by the schedule being edited, so switching
@@ -101,32 +98,15 @@
: ''
);
// The server is the ground truth for what a cron actually does.
let previewTimer: ReturnType<typeof setTimeout> | undefined;
$effect(() => {
const expression = builtCron;
const tz = timeZone;
if (!expression) {
preview = null;
return;
}
clearTimeout(previewTimer);
previewTimer = setTimeout(() => {
api
.previewSchedule(expression, tz)
.then((p) => (preview = p))
.catch(() => (preview = null));
}, 350);
return () => clearTimeout(previewTimer);
});
// Publish the built cadence to the caller.
// Publish the built cadence to the caller. The backend validates the cron
// on save; client-side we only require a non-empty expression / a picked
// time, and describeCron gives the human summary below.
$effect(() => {
value = {
cronExpression: freq === 'once' ? undefined : (builtCron ?? undefined),
runOnceUtc: freq === 'once' && onceLocal ? new Date(onceLocal).toISOString() : undefined,
timeZoneId: timeZone.trim() || 'UTC',
valid: freq === 'once' ? Boolean(onceLocal) : preview?.valid !== false
valid: freq === 'once' ? Boolean(onceLocal) : Boolean(builtCron && builtCron.trim())
};
});
</script>
@@ -206,18 +186,6 @@
<div class="describe">
<strong>{description}</strong>
{#if preview && freq !== 'once'}
{#if preview.valid}
<span class="faint small">
Next: {preview.nextRunsUtc
.slice(0, 3)
.map((t) => new Date(t).toLocaleString())
.join(' · ')}
</span>
{:else}
<span class="warn small">{preview.error}</span>
{/if}
{/if}
</div>
</div>
@@ -285,7 +253,4 @@
font-size: 12px;
}
.warn {
color: var(--warning);
}
</style>
@@ -1,277 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api } from '$lib/api/client';
import type { DeviceDto, DeviceGroupDto, ScheduleAssignmentDto, ScheduleDto } from '$lib/api/types';
import { scheduleCadence } from '$lib/schedule/cron-describe';
let {
scriptId,
devices,
groups,
defaultTarget,
collectArgs
}: {
scriptId: string;
devices: DeviceDto[];
groups: DeviceGroupDto[];
defaultTarget: string;
collectArgs: () => Record<string, unknown>;
} = $props();
let assignments = $state<ScheduleAssignmentDto[]>([]);
let allSchedules = $state<ScheduleDto[]>([]);
let adding = $state(false);
let busy = $state(false);
let errorText = $state('');
let scheduleId = $state('');
let target = $state('');
async function refresh() {
[assignments, allSchedules] = await Promise.all([
api.scheduleAssignments(scriptId).catch(() => []),
api.schedules().catch(() => [])
]);
}
onMount(refresh);
function openForm() {
adding = true;
errorText = '';
target = defaultTarget;
scheduleId = allSchedules[0]?.id ?? '';
}
// The page's device list can arrive after the form opens; keep an untouched
// target following the page selection instead of staying blank.
$effect(() => {
if (adding && !target) {
target = defaultTarget || (devices[0] ? 'device:' + devices[0].clientId : '');
}
});
async function attach() {
busy = true;
errorText = '';
const isGroup = target.startsWith('group:');
const targetId = target.slice(target.indexOf(':') + 1);
try {
await api.createScheduleAssignment({
scheduleId,
scriptId,
clientId: isGroup ? undefined : targetId,
groupId: isGroup ? targetId : undefined,
arguments: collectArgs(),
enabled: true
});
adding = false;
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Could not attach the schedule.';
} finally {
busy = false;
}
}
async function toggle(assignment: ScheduleAssignmentDto) {
errorText = '';
try {
await api.updateScheduleAssignment(assignment.id, {
scheduleId: assignment.scheduleId,
scriptId: assignment.scriptId,
clientId: assignment.clientId,
groupId: assignment.groupId,
enabled: !assignment.enabled
});
} catch (e) {
errorText = e instanceof Error ? e.message : 'Could not update the assignment.';
}
await refresh();
}
async function detach(assignment: ScheduleAssignmentDto) {
if (!confirm(`Detach schedule “${assignment.scheduleName}” from this script?`)) return;
await api.deleteScheduleAssignment(assignment.id);
await refresh();
}
function targetLabel(assignment: ScheduleAssignmentDto): string {
return assignment.groupId
? `group ${assignment.groupName ?? '?'}`
: (assignment.targetHostname ?? assignment.clientId ?? '?');
}
</script>
<section class="card section">
<div class="head">
<h3>Schedules</h3>
{#if !adding}
<button class="btn primary tiny" onclick={openForm}>+ Attach</button>
{/if}
</div>
{#if assignments.length === 0 && !adding}
<p class="muted small">
No schedules attached. Attach a cadence from <a href="/schedules">Schedules</a> to run this
script automatically.
</p>
{/if}
{#each assignments as assignment (assignment.id)}
<div class="row" class:off={!assignment.enabled || !assignment.scheduleEnabled}>
<div class="row-main">
<span class="row-name">{assignment.scheduleName ?? '?'}</span>
<span class="muted small">{scheduleCadence(assignment)} · {targetLabel(assignment)}</span>
<span class="faint small">
{#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}
</span>
</div>
<div class="row-actions">
<button class="btn tiny" onclick={() => toggle(assignment)}>
{assignment.enabled ? 'Pause' : 'Enable'}
</button>
<button class="btn danger tiny" onclick={() => detach(assignment)}>✕</button>
</div>
</div>
{/each}
{#if adding}
<div class="form pulse-in">
{#if allSchedules.length === 0}
<p class="muted small">
No schedules defined yet — create one on the
<a href="/schedules">Schedules</a> page first.
</p>
{:else}
<label>
<span class="muted">Schedule</span>
<select class="select" bind:value={scheduleId}>
{#each allSchedules as schedule (schedule.id)}
<option value={schedule.id}>
{schedule.name} — {scheduleCadence(schedule)}
</option>
{/each}
</select>
</label>
<label>
<span class="muted">Target</span>
<select class="select" bind:value={target}>
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId}>{device.hostname}</option>
{/each}
</optgroup>
{#if groups.length > 0}
<optgroup label="Groups (members resolved at fire time)">
{#each groups as group (group.id)}
<option value={'group:' + group.id}>{group.name} ({group.kind})</option>
{/each}
</optgroup>
{/if}
</select>
</label>
<p class="faint small">Current run values are stored and used for every firing.</p>
<div class="actions">
<button class="btn primary" onclick={attach} disabled={busy || !scheduleId || !target}>
{busy ? 'Attaching…' : 'Attach schedule'}
</button>
<button class="btn" onclick={() => (adding = false)}>Cancel</button>
</div>
{/if}
{#if errorText}<p class="warn small">{errorText}</p>{/if}
</div>
{/if}
</section>
<style>
.section {
padding: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.head {
display: flex;
align-items: center;
justify-content: space-between;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 6px 10px;
}
.row.off {
opacity: 0.6;
}
.row-main {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.row-name {
font-size: 13px;
font-weight: 600;
}
.row-actions {
display: flex;
gap: 4px;
flex-shrink: 0;
}
.form {
display: flex;
flex-direction: column;
gap: var(--space-2);
border-top: 1px solid var(--border);
padding-top: var(--space-3);
}
label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
}
.actions {
display: flex;
gap: var(--space-2);
}
.tiny {
padding: 3px 8px;
font-size: 11px;
}
.small {
font-size: 12px;
}
.warn {
color: var(--warning);
}
</style>
+125 -39
View File
@@ -1,28 +1,56 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api } from '$lib/api/client';
import type { DeviceGroupDto, ScriptTriggerDto, ScriptTriggerType } from '$lib/api/types';
import ScheduleCadenceEditor, {
type CadenceValue
} from '$lib/components/ScheduleCadenceEditor.svelte';
import type {
DeviceGroupDto,
DeviceDto,
ScriptTriggerDto,
ScriptTriggerType
} from '$lib/api/types';
let {
scriptId,
groups
groups,
devices = []
}: {
scriptId: string;
groups: DeviceGroupDto[];
devices?: DeviceDto[];
} = $props();
let triggers = $state<ScriptTriggerDto[]>([]);
let triggerType = $state<ScriptTriggerType>('onAgentReady');
let groupId = $state('');
let oncePerDevice = $state(true);
let when = $state<ScriptTriggerType>('onAgentReady');
// Target: 'all', 'group:<id>', or 'device:<clientId>'.
let target = $state('all');
// Schedule cadence (when === 'scheduled'), built by the friendly editor.
let cadence = $state<CadenceValue>({ cronExpression: '0 * * * *', timeZoneId: 'UTC', valid: true });
let errorText = $state('');
let busy = $state(false);
const mine = $derived(triggers.filter((t) => t.scriptId === scriptId));
const labels: Record<ScriptTriggerType, string> = {
const whenLabels: Record<ScriptTriggerType, string> = {
onRegistration: 'On registration',
onAgentReady: 'On agent ready'
onAgentReady: 'On agent ready',
scheduled: 'Scheduled'
};
function targetLabel(t: ScriptTriggerDto): string {
if (t.clientId) return t.clientHostname ?? t.clientId;
if (t.groupId) return t.groupName ?? 'group';
return 'All devices';
}
function whenLabel(t: ScriptTriggerDto): string {
if (t.triggerType !== 'scheduled') return whenLabels[t.triggerType];
if (t.cronExpression) return `Every: ${t.cronExpression}`;
if (t.runOnceUtc) return `Once: ${new Date(t.runOnceUtc).toLocaleString()}`;
return 'Scheduled';
}
async function refresh() {
triggers = await api.triggers().catch(() => []);
}
@@ -33,16 +61,28 @@
async function add() {
errorText = '';
if (when === 'scheduled' && !cadence.valid) {
errorText = 'Choose a valid schedule.';
return;
}
busy = true;
try {
const clientId = target.startsWith('device:') ? target.slice(7) : undefined;
const groupId = target.startsWith('group:') ? target.slice(6) : undefined;
await api.createTrigger({
scriptId,
groupId: groupId || undefined,
triggerType,
oncePerDevice
triggerType: when,
clientId,
groupId,
cronExpression: when === 'scheduled' ? cadence.cronExpression : undefined,
runOnceUtc: when === 'scheduled' ? cadence.runOnceUtc : undefined,
timeZoneId: when === 'scheduled' ? cadence.timeZoneId : undefined
});
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Could not add the trigger.';
} finally {
busy = false;
}
}
@@ -55,23 +95,46 @@
<section class="card section">
<h3>Triggers</h3>
<p class="muted small">
Run this script automatically when a device registers, or when its agent connects and is ready
for jobs.
Run this script automatically — on registration, when the agent becomes ready, or on a schedule
— against a chosen target. Add as many as you like: the same script can run at different times on
different targets.
</p>
<div class="form">
<select class="select" bind:value={triggerType} aria-label="Trigger event">
<option value="onAgentReady">On agent ready</option>
<option value="onRegistration">On registration</option>
</select>
<select class="select" bind:value={groupId} aria-label="Trigger scope">
<option value="">All devices</option>
{#each groups as group (group.id)}
<option value={group.id}>{group.name}</option>
{/each}
</select>
<label class="once"><input type="checkbox" bind:checked={oncePerDevice} /> once per device</label>
<button class="btn primary" onclick={add}>+ Add</button>
<label class="field">
<span class="lbl">When</span>
<select class="select" bind:value={when} aria-label="Trigger when">
<option value="onAgentReady">On agent ready</option>
<option value="onRegistration">On registration</option>
<option value="scheduled">Scheduled (cron)</option>
</select>
</label>
{#if when === 'scheduled'}
<div class="field cadence-field">
<span class="lbl">Schedule</span>
<ScheduleCadenceEditor bind:value={cadence} />
</div>
{/if}
<label class="field">
<span class="lbl">Targets</span>
<select class="select" bind:value={target} aria-label="Trigger target">
<option value="all">All devices</option>
<optgroup label="Groups">
{#each groups as group (group.id)}
<option value={'group:' + group.id}>{group.name}</option>
{/each}
</optgroup>
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId}>{device.hostname}</option>
{/each}
</optgroup>
</select>
</label>
<button class="btn primary add" onclick={add} disabled={busy}>+ Add trigger</button>
</div>
{#if errorText}<p class="warn small">{errorText}</p>{/if}
@@ -82,12 +145,15 @@
<ul class="list">
{#each mine as trigger (trigger.id)}
<li>
<span>
{labels[trigger.triggerType]}
<span class="muted">· {trigger.groupName ?? 'All devices'}</span>
{#if trigger.oncePerDevice}<span class="faint">· once per device</span>{/if}
</span>
<button class="btn danger tiny" onclick={() => remove(trigger.id)}>✕</button>
<div class="tinfo">
<span class="twhen">{whenLabel(trigger)}</span>
<span class="muted">→ {targetLabel(trigger)}</span>
{#if trigger.triggerType === 'scheduled' && trigger.nextRunUtc}
<span class="faint">· next {new Date(trigger.nextRunUtc).toLocaleString()}</span>
{/if}
{#if trigger.lastResult}<span class="faint">· {trigger.lastResult}</span>{/if}
</div>
<button class="btn danger tiny" onclick={() => remove(trigger.id)} aria-label="Remove trigger">✕</button>
</li>
{/each}
</ul>
@@ -103,21 +169,30 @@
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
align-items: flex-end;
margin-top: var(--space-2);
}
.form .select {
.field {
display: flex;
flex-direction: column;
gap: 3px;
flex: 1;
min-width: 140px;
min-width: 160px;
}
.once {
display: flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
white-space: nowrap;
/* The cadence editor takes its own full-width row. */
.cadence-field {
flex-basis: 100%;
}
.lbl {
font-size: 11px;
color: var(--text-muted);
}
.add {
flex-shrink: 0;
}
.list {
@@ -140,6 +215,17 @@
font-size: 13px;
}
.tinfo {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
}
.twhen {
font-weight: 500;
}
.tiny {
padding: 3px 8px;
font-size: 11px;
-1
View File
@@ -19,7 +19,6 @@
{ href: '/scripts', label: 'Scripts', icon: '⌘', permission: 'scripts.view' },
{ href: '/functions', label: 'Functions', icon: 'ƒ', permission: 'functions.view' },
{ href: '/jobs', label: 'Jobs', icon: '≡', permission: 'jobs.view' },
{ href: '/schedules', label: 'Schedules', icon: '◷', permission: 'automation.view' },
{ href: '/access', label: 'Access', icon: '⚿', permission: 'access.manage' },
{ href: '/settings', label: 'Settings', icon: '⚙', permission: 'settings.manage' }
];
+45 -7
View File
@@ -2,7 +2,7 @@
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { api } from '$lib/api/client';
import type { DashboardDto } from '$lib/api/types';
import type { DashboardDto, ActivityEventPayload } from '$lib/api/types';
import { nats, type JobEvent } from '$lib/messaging/nats';
import EmptyState from '$lib/components/EmptyState.svelte';
import JobStateBadge from '$lib/components/JobStateBadge.svelte';
@@ -12,6 +12,8 @@
import TimelineChart from '$lib/components/charts/TimelineChart.svelte';
let data = $state<DashboardDto | null>(null);
// Live activity feed (newest first, capped) fed by NATS activity events.
let activity = $state<ActivityEventPayload[]>([]);
// Live deployment tracker: NATS job.state events roll up into a running
// count so a group run of N endpoints shows progress as it lands.
@@ -62,6 +64,7 @@
const poll = setInterval(() => void refresh(), 15000);
const offActivity = nats.onActivity((event) => {
activity = [event, ...activity].slice(0, 20);
if (event.kind !== 'device-presence') {
void refresh();
}
@@ -119,21 +122,21 @@
<span class="ok">{data.devicesOnline} online</span> · {data.devicesOffline} offline
</div>
</button>
<div class="tile card">
<button class="tile card" onclick={() => goto('/jobs')}>
<div class="value">{data.jobsTotal}</div>
<div class="label">Jobs · 30 days</div>
<div class="sub">{data.jobsInProgress} in progress</div>
</div>
<div class="tile card">
</button>
<button class="tile card" onclick={() => goto('/jobs')}>
<div class="value ok">{data.successRate}%</div>
<div class="label">Success rate</div>
<div class="sub">{data.jobsSucceeded} ok · {data.jobsFailed} failed</div>
</div>
<div class="tile card">
</button>
<button class="tile card" onclick={() => goto('/jobs?state=failed')}>
<div class="value {data.jobsFailed > 0 ? 'bad' : ''}">{data.jobsFailed}</div>
<div class="label">Failed · 30 days</div>
<div class="sub">TimedOut counted</div>
</div>
</button>
</section>
<div class="grid">
@@ -228,6 +231,33 @@
</ul>
{/if}
</section>
<section class="card panel recent">
<h2>Activity</h2>
{#if activity.length === 0}
<EmptyState title="Live activity" detail="Enrollments, runs and presence changes appear here as they happen." />
{:else}
<ul class="runs">
{#each activity as a, i (a.timestampUtc + '-' + i)}
<li>
<button
class="run"
onclick={() =>
a.jobId
? goto(`/jobs?job=${a.jobId}`)
: a.clientId
? goto(`/devices/${a.clientId}`)
: undefined}
>
<span class="act-kind faint">{a.kind}</span>
<span class="run-script">{a.text}</span>
<span class="run-time faint">{new Date(a.timestampUtc).toLocaleTimeString()}</span>
</button>
</li>
{/each}
</ul>
{/if}
</section>
</div>
{/if}
@@ -419,6 +449,14 @@
white-space: nowrap;
}
.act-kind {
font-size: 10.5px;
text-transform: uppercase;
letter-spacing: 0.04em;
flex-shrink: 0;
min-width: 84px;
}
.live {
padding: var(--space-3) var(--space-4);
margin-bottom: var(--space-4);
@@ -25,6 +25,13 @@
// The public IP is operationally sensitive-ish; keep it masked until asked.
let showPublicIp = $state(false);
const inventory = $derived(detail?.inventory);
// Ordered by physical disk number (falling back to report order), so Disk 0
// comes before Disk 1, etc. Keeps each disk's resolved index for volume mapping.
const sortedDisks = $derived(
(inventory?.disks ?? [])
.map((disk, i) => ({ disk, diskIndex: disk.index ?? i }))
.sort((a, b) => a.diskIndex - b.diskIndex)
);
// Volumes the partition-association walk could not tie to a disk.
const unmappedVolumes = $derived(
inventory
@@ -151,6 +158,7 @@
{[device.manufacturer, device.model].filter(Boolean).join(' · ')}
</div>
<div class="client-id">
<span class="client-id-label muted">Client ID:</span>
<CopyChip value={clientId} label="Client ID" />
</div>
</div>
@@ -182,8 +190,16 @@
<dl>
<dt>Hostname</dt>
<dd>{device.hostname}</dd>
<dt>Make / model</dt>
<dd>
{[inventory?.identity.manufacturer, inventory?.identity.model]
.filter(Boolean)
.join(' · ') || '—'}
</dd>
<dt>Serial number</dt>
<dd>{inventory?.identity.serialNumber ?? '—'}</dd>
<dd class="mono">{inventory?.identity.serialNumber ?? '—'}</dd>
<dt>System UUID</dt>
<dd class="mono">{inventory?.identity.systemUuid ?? '—'}</dd>
<dt>Domain / workgroup</dt>
<dd>{inventory?.identity.domainOrWorkgroup ?? '—'}</dd>
<dt>System type</dt>
@@ -195,8 +211,14 @@
<dl>
<dt>OS</dt>
<dd>{inventory?.os.caption ?? device.osCaption ?? '—'}</dd>
<dt>Version / build</dt>
<dd>{inventory?.os.version ?? '—'} (build {inventory?.os.build ?? '—'})</dd>
<dt>Edition</dt>
<dd>{inventory?.os.edition ?? '—'}</dd>
<dt>Product type</dt>
<dd>{inventory?.os.productType ?? '—'}</dd>
<dt>Release</dt>
<dd>{inventory?.os.releaseVersion ?? '—'}</dd>
<dt>Version</dt>
<dd class="mono">{inventory?.os.version ?? '—'}</dd>
<dt>Architecture</dt>
<dd>{inventory?.os.architecture ?? '—'}</dd>
<dt>Installed</dt>
@@ -215,7 +237,7 @@
</dl>
</section>
<section class="card section">
<h3>Tags &amp; groups</h3>
<h3>Tags</h3>
<div class="tag-row">
{#each device.tags ?? [] as tag (tag)}
<span class="tag">
@@ -236,6 +258,10 @@
/>
<button class="btn" onclick={addTag}>Add</button>
</div>
</section>
<section class="card section">
<h3>Groups</h3>
<div class="tag-row groups">
{#each detail?.groups ?? [] as g (g.id)}
<a class="tag group-tag" href="/groups">{g.name}<span class="faint"> · {g.kind}</span></a>
@@ -309,18 +335,23 @@
{/each}
</section>
<section class="card section">
<h3>Firmware</h3>
<h3>Firmware &amp; board</h3>
<dl>
<dt>BIOS version</dt>
<dd>{inventory.identity.biosVersion ?? '—'}</dd>
<dd class="mono">{inventory.identity.biosVersion ?? '—'}</dd>
<dt>Motherboard</dt>
<dd>
{[inventory.identity.baseboardManufacturer, inventory.identity.baseboardProduct]
.filter(Boolean)
.join(' · ') || '—'}
</dd>
<dt>Baseboard serial</dt>
<dd>{inventory.identity.baseboardSerial ?? '—'}</dd>
<dd class="mono">{inventory.identity.baseboardSerial ?? '—'}</dd>
</dl>
</section>
<section class="card section wide">
<h3>Storage</h3>
{#each inventory.disks as disk, i (i)}
{@const diskIndex = disk.index ?? i}
{#each sortedDisks as { disk, diskIndex } (diskIndex)}
{@const diskVolumes = inventory.volumes.filter((v) => v.diskIndex === diskIndex)}
<div class="disk">
<div class="disk-head">
@@ -536,7 +567,15 @@
.client-id {
margin-top: var(--space-2);
max-width: 560px;
max-width: 620px;
display: flex;
align-items: center;
gap: var(--space-2);
}
.client-id-label {
font-size: 12.5px;
flex-shrink: 0;
}
.head-actions {
@@ -581,7 +620,7 @@
.sections {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
gap: var(--space-4);
}
@@ -589,6 +628,14 @@
display: inline-flex;
align-items: center;
gap: var(--space-2);
flex-wrap: nowrap;
}
/* Keep the Reveal/Hide button on one line — it was collapsing to a
vertical strip when the revealed chip crowded the cell. */
.public-ip .btn {
flex-shrink: 0;
white-space: nowrap;
}
.tiny {
@@ -100,6 +100,18 @@
statusText = 'Opening shell…';
// Never hang forever: if the agent hasn't opened the shell shortly,
// it's offline or remote shell was opted out (AllowRemoteShell is on
// by default). Tell the operator instead of spinning.
setTimeout(() => {
if (disposed || connected || closed) return;
statusText = 'No response from the agent';
term.write(
'\r\n\x1b[33m— No response from the agent. It may be offline, or remote shell was ' +
'disabled on it (AllowRemoteShell=0 via policy/registry). —\x1b[0m\r\n'
);
}, 15000);
return () => window.removeEventListener('resize', resize);
})();
+16 -1
View File
@@ -191,9 +191,24 @@
</div>
<RuleBuilder bind:rules {fields} />
{#if selected}
<div class="preview">
<h3>Members — {members.length} device(s)</h3>
{#if members.length > 0}
<ul class="chips">
{#each members as d (d.clientId)}
<li class="chip"><StatusBadge status={d.status} /> {d.hostname}</li>
{/each}
</ul>
{:else}
<p class="muted small">No devices currently match. Adjust the rules and Save.</p>
{/if}
</div>
{/if}
{#if preview !== null}
<div class="preview">
<h3>Preview — {preview.length} device(s)</h3>
<h3>Preview (unsaved rules) — {preview.length} device(s)</h3>
{#if preview.length > 0}
<ul class="chips">
{#each preview as d (d.clientId)}
+14 -1
View File
@@ -12,6 +12,14 @@
let selected = $state<JobDto | null>(null);
let output = $state<JobOutputRecordDto[]>([]);
// Optional ?state= filter (e.g. the dashboard's Failed tile links here).
const stateFilter = $derived(page.url.searchParams.get('state'));
const visibleJobs = $derived(
(jobs ?? []).filter(
(j) => !stateFilter || j.state.toLowerCase() === stateFilter.toLowerCase()
)
);
async function refresh() {
jobs = await api.jobs(undefined, 100);
const requested = page.url.searchParams.get('job');
@@ -57,6 +65,9 @@
<div class="page-head">
<h1>Jobs</h1>
{#if stateFilter}
<a class="btn small" href="/jobs">Filtered: {stateFilter} ✕</a>
{/if}
</div>
<div class="split">
@@ -69,6 +80,8 @@
</div>
{:else if jobs.length === 0}
<EmptyState title="No jobs yet" detail="Run a script on a device to create a job." />
{:else if visibleJobs.length === 0}
<EmptyState title="No matching jobs" detail={`No jobs in state "${stateFilter}".`} />
{:else}
<table class="data">
<thead>
@@ -81,7 +94,7 @@
</tr>
</thead>
<tbody>
{#each jobs as job (job.jobId)}
{#each visibleJobs as job (job.jobId)}
<tr
class="clickable"
class:selected={selected?.jobId === job.jobId}
-381
View File
@@ -1,381 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api } from '$lib/api/client';
import type { ScheduleDto } from '$lib/api/types';
import { scheduleCadence } from '$lib/schedule/cron-describe';
import ScheduleCadenceEditor, {
type CadenceValue
} from '$lib/components/ScheduleCadenceEditor.svelte';
import RelativeTime from '$lib/components/RelativeTime.svelte';
import EmptyState from '$lib/components/EmptyState.svelte';
let schedules = $state<ScheduleDto[] | null>(null);
let errorText = $state('');
let busy = $state(false);
// Create/edit form
let editing = $state<ScheduleDto | null>(null);
let creating = $state(false);
let name = $state('');
let cadence = $state<CadenceValue>({ timeZoneId: 'UTC', valid: false });
const formOpen = $derived(creating || editing !== null);
async function refresh() {
schedules = await api.schedules();
}
onMount(() => {
void refresh().catch(() => (schedules = []));
});
function openCreate() {
creating = true;
editing = null;
name = '';
errorText = '';
}
function openEdit(schedule: ScheduleDto) {
editing = schedule;
creating = false;
name = schedule.name;
errorText = '';
}
function close() {
creating = false;
editing = null;
errorText = '';
}
async function save() {
busy = true;
errorText = '';
try {
const body = {
name,
cronExpression: cadence.cronExpression,
runOnceUtc: cadence.runOnceUtc,
timeZoneId: cadence.timeZoneId,
enabled: editing?.enabled ?? true
};
if (editing) {
await api.updateSchedule(editing.id, body);
} else {
await api.createSchedule(body);
}
close();
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Save failed.';
} finally {
busy = false;
}
}
async function toggle(schedule: ScheduleDto) {
errorText = '';
try {
await api.updateSchedule(schedule.id, {
name: schedule.name,
cronExpression: schedule.cronExpression,
runOnceUtc: schedule.runOnceUtc,
timeZoneId: schedule.timeZoneId,
enabled: !schedule.enabled
});
} catch (e) {
errorText = e instanceof Error ? e.message : 'Could not update the schedule.';
}
await refresh();
}
const copyName = (base: string, existing: string[]) => {
let candidate = `${base} (copy)`;
for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (copy ${i})`;
return candidate;
};
/** Copies the cadence only — assignments stay with the original. */
async function clone(schedule: ScheduleDto) {
errorText = '';
try {
await api.createSchedule({
name: copyName(schedule.name, (schedules ?? []).map((s) => s.name)),
cronExpression: schedule.cronExpression,
runOnceUtc: schedule.runOnceUtc,
timeZoneId: schedule.timeZoneId,
enabled: schedule.enabled
});
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Clone failed.';
}
}
async function remove(schedule: ScheduleDto) {
const uses = schedule.assignments.length;
if (
!confirm(
`Delete schedule “${schedule.name}”?` +
(uses > 0 ? ` ${uses} script assignment(s) will be removed with it.` : '')
)
)
return;
await api.deleteSchedule(schedule.id);
await refresh();
}
function status(schedule: ScheduleDto): { label: string; kind: string } {
if (schedule.enabled && schedule.nextRunUtc) return { label: 'Active', kind: 'ok' };
if (!schedule.enabled && schedule.runOnceUtc && schedule.lastRunUtc)
return { label: 'Done', kind: 'muted' };
return { label: 'Paused', kind: 'muted' };
}
</script>
<div class="page-head">
<div>
<h1>Schedules</h1>
<p class="muted small">
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.
</p>
</div>
{#if !formOpen}
<button class="btn primary" onclick={openCreate}>+ New schedule</button>
{/if}
</div>
{#if errorText}<p class="warn small">{errorText}</p>{/if}
{#if formOpen}
<div class="card form-card pulse-in">
<h3>{editing ? `Edit “${editing.name}”` : 'New schedule'}</h3>
<div class="form-grid">
<label>
<span class="muted">Name</span>
<input class="input" placeholder="e.g. Nightly at 1am" bind:value={name} />
</label>
{#key editing?.id ?? 'new'}
<ScheduleCadenceEditor
bind:value={cadence}
initial={editing
? {
cronExpression: editing.cronExpression,
runOnceUtc: editing.runOnceUtc,
timeZoneId: editing.timeZoneId
}
: undefined}
/>
{/key}
</div>
<div class="actions">
<button
class="btn primary"
onclick={save}
disabled={busy || !name.trim() || !cadence.valid}
>
{busy ? 'Saving…' : '💾 Save schedule'}
</button>
<button class="btn" onclick={close}>Cancel</button>
</div>
</div>
{/if}
<div class="card table-wrap">
{#if schedules === null}
<div class="loading">
{#each Array(3) as _, i (i)}
<div class="skeleton row-skeleton">loading…</div>
{/each}
</div>
{:else if schedules.length === 0}
<EmptyState title="No schedules" detail="Create a cadence, then attach scripts to it." />
{:else}
<table class="data">
<thead>
<tr>
<th>Status</th>
<th>Name</th>
<th>Cadence</th>
<th>Next run</th>
<th>Last fired</th>
<th>Used by</th>
<th></th>
</tr>
</thead>
<tbody>
{#each schedules as schedule (schedule.id)}
{@const s = status(schedule)}
<tr class:dim={!schedule.enabled}>
<td><span class="chip {s.kind}">{s.label}</span></td>
<td>{schedule.name}</td>
<td class="muted">{scheduleCadence(schedule)}</td>
<td class="muted">
{schedule.enabled && schedule.nextRunUtc
? new Date(schedule.nextRunUtc).toLocaleString()
: '—'}
</td>
<td class="muted">
{#if schedule.lastRunUtc}
<RelativeTime value={schedule.lastRunUtc} />
{:else}
—
{/if}
</td>
<td>
{#if schedule.assignments.length === 0}
<span class="faint">nothing yet</span>
{:else}
<div class="uses">
{#each schedule.assignments as assignment (assignment.id)}
<a
class="use-chip"
class:off={!assignment.enabled}
href="/scripts/{assignment.scriptId}"
title={assignment.lastResult ?? ''}
>
{assignment.scriptName ?? '?'}
<span class="faint">
→ {assignment.groupId
? (assignment.groupName ?? 'group')
: (assignment.targetHostname ?? assignment.clientId)}
</span>
</a>
{/each}
</div>
{/if}
</td>
<td class="row-actions">
{#if !(schedule.runOnceUtc && schedule.lastRunUtc)}
<button class="btn tiny" onclick={() => toggle(schedule)}>
{schedule.enabled ? 'Pause' : 'Enable'}
</button>
{/if}
<button class="btn tiny" onclick={() => openEdit(schedule)}>Edit</button>
<button class="btn tiny" onclick={() => clone(schedule)}>⧉ Clone</button>
<button class="btn danger tiny" onclick={() => remove(schedule)}>✕</button>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
</div>
<style>
.page-head {
margin-bottom: var(--space-4);
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-4);
}
.form-card {
padding: var(--space-4);
margin-bottom: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.form-grid {
display: grid;
grid-template-columns: minmax(220px, 320px) minmax(280px, 1fr);
gap: var(--space-4);
align-items: start;
}
.form-grid label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
}
.actions {
display: flex;
gap: var(--space-2);
}
tr.dim td {
opacity: 0.65;
}
.chip {
display: inline-block;
border-radius: 999px;
padding: 2px 10px;
font-size: 11.5px;
font-weight: 600;
border: 1px solid var(--border);
}
.chip.ok {
color: var(--success);
border-color: var(--success);
}
.chip.muted {
color: var(--text-muted);
}
.uses {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.use-chip {
display: inline-flex;
gap: 4px;
align-items: baseline;
border: 1px solid var(--border);
border-radius: 999px;
padding: 2px 10px;
font-size: 12px;
text-decoration: none;
color: var(--text);
}
.use-chip.off {
opacity: 0.55;
}
.row-actions {
display: flex;
gap: 4px;
justify-content: flex-end;
}
.tiny {
padding: 3px 8px;
font-size: 11px;
}
.small {
font-size: 12px;
}
.warn {
color: var(--warning);
}
.loading {
padding: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.row-skeleton {
height: 36px;
}
@media (max-width: 900px) {
.form-grid {
grid-template-columns: 1fr;
}
}
</style>
+44 -11
View File
@@ -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<JobDto | null>(null);
let jobState = $state<JobState | null>(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<JobProgressPayload | null>(null);
let unsubscribeJob: (() => void) | null = null;
@@ -524,7 +535,7 @@
<div class="flow">
<section class="card section">
<h3>Execution</h3>
<h3>Targets</h3>
<div class="target-row">
<select class="select target" bind:value={targetKey} aria-label="Add a target device or group">
<optgroup label="Devices">
@@ -576,14 +587,7 @@
</section>
{#if !isNew && loaded}
<SchedulesCard
{scriptId}
{devices}
groups={allGroups}
defaultTarget={targetKey}
collectArgs={() => paramInputs?.collect() ?? {}}
/>
<TriggersCard {scriptId} groups={allGroups} />
<TriggersCard {scriptId} groups={allGroups} {devices} />
{/if}
</div>
@@ -620,6 +624,18 @@
{#if jobState}
<JobStateBadge state={jobState} />
{/if}
<div class="output-tools">
{#if outputLines.length > 0}
<input
class="input output-search"
type="search"
placeholder="Search output…"
bind:value={outputSearch}
aria-label="Search output"
/>
<button class="btn small" onclick={copyOutput}>{copiedOutput ? '✔ Copied' : '⧉ Copy'}</button>
{/if}
</div>
</div>
{#if progress}
@@ -645,8 +661,10 @@
<span class="faint">
{job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'}
</span>
{:else if filteredOutput.length === 0}
<span class="faint">No lines match “{outputSearch}”.</span>
{:else}
{#each outputLines as line (line.seq)}
{#each filteredOutput as line (line.seq)}
<div class="output-line {line.stream}">{line.text}</div>
{/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 {
+13 -7
View File
@@ -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(() => []);
+1 -1
View File
@@ -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);
@@ -143,6 +143,12 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<Back
Assert.Contains("$install.ToString()", script);
Assert.DoesNotContain("-EncodedCommand", script);
Assert.DoesNotContain("#Requires -RunAsAdministrator", script);
// The package download uses WebClient (fast) over TLS 1.2, never the
// slow Invoke-WebRequest.
Assert.Contains("System.Net.WebClient", script);
Assert.Contains("Tls12", script);
Assert.DoesNotContain("Invoke-WebRequest", script);
}
[Theory]
+43 -63
View File
@@ -2,6 +2,7 @@ using Backend.Data;
using Backend.Jobs;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Models;
using Xunit;
namespace Backend.Tests;
@@ -66,15 +67,14 @@ public class ScheduleWorkerTests : IClassFixture<BackendTestFixture>
NullLogger<ScheduleWorker>.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<BackendTestFixture>
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<Guid> SeedScheduleAsync(
string name, string? cron = null, DateTimeOffset? runOnce = null, bool due = false)
private async Task<Guid> 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<Guid> 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<Guid> SeedScriptAsync(string name)