Platform groups with CIDR rules, script editor rework, server MSI with turn-key setup, ARM agents #4

Merged
gsadmin merged 18 commits from dev into main 2026-08-08 16:15:34 +00:00
83 changed files with 8034 additions and 474 deletions
+2 -1
View File
@@ -85,7 +85,7 @@ jobs:
shell: pwsh
run: |
./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} `
-Runtimes win-x64,linux-x64,linux-arm64,osx-x64,osx-arm64
-Runtimes win-x64,win-arm64,linux-x64,linux-arm64,osx-x64,osx-arm64
$stage = 'artifacts/agent-package'
New-Item -ItemType Directory -Force $stage | Out-Null
$msi = "artifacts/Agent-${{ steps.ver.outputs.version }}.msi"
@@ -119,6 +119,7 @@ jobs:
artifacts/Agent-*.msi
artifacts/Agent-*-checksums.txt
artifacts/Server-*.zip
artifacts/Server-*.msi
artifacts/Server-*-checksums.txt
retention-days: 7
+1 -1
View File
@@ -51,7 +51,7 @@ jobs:
shell: pwsh
run: |
./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} `
-Runtimes win-x64,linux-x64,linux-arm64,osx-x64,osx-arm64 -SkipIcon
-Runtimes win-x64,win-arm64,linux-x64,linux-arm64,osx-x64,osx-arm64 -SkipIcon
- name: Package server (win-x64 + linux-x64)
shell: pwsh
+112 -48
View File
@@ -1,21 +1,23 @@
# ExecuteR
Secure Windows endpoint management: a self-contained .NET agent enrolls over
ordinary HTTPS, establishes **scoped NATS messaging over WebSocket** through the
same reverse-proxy edge, publishes live state, accepts durable work, runs
PowerShell in-process, and provides a secured interactive terminal — while the
browser uses a WebSocket-connected NATS client for near-real-time UI updates
with **no SignalR, SSE, or polling**.
Secure cross-platform endpoint management: a self-contained .NET agent enrolls
over ordinary HTTPS, establishes **scoped NATS messaging over WebSocket**
through the same reverse-proxy edge, publishes live state, accepts durable
work, runs PowerShell in-process, and provides a secured interactive terminal —
while the browser uses a WebSocket-connected NATS client for near-real-time UI
updates with **no SignalR, SSE, or polling**.
- **Agent** — single self-contained Windows x64 executable / Windows service
(.NET 10). Deterministic hardware identity, secure one-time bootstrap,
CIM inventory, in-process PowerShell (System.Management.Automation), ConPTY
remote shell, presigned-URL file delivery.
- **Agent** — single self-contained executable for Windows, Linux and macOS
(x64 + arm64, .NET 10), running as a Windows service / systemd unit /
launchd daemon. Deterministic hardware identity, secure one-time bootstrap,
hardware inventory, in-process PowerShell (System.Management.Automation)
plus PowerShell 5 and Bash engines, ConPTY remote shell (Windows),
presigned-URL file delivery.
- **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC
auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live
event relay.
- **WebUI** — SvelteKit dashboard: live device status, Monaco PowerShell editor
with typed parameters and reusable function modules, live job output and
with typed parameters and reusable Functions, live job output and
progress, xterm.js remote shell.
![Dashboard](docs/screenshots/dashboard.png)
@@ -40,7 +42,7 @@ with **no SignalR, SSE, or polling**.
14. [Bootstrap and URL install](#bootstrap-and-url-install)
15. [Local login and OIDC](#local-login-and-oidc)
16. [Custom roles and permissions](#custom-roles-and-permissions)
17. [Typed script parameters and function modules](#typed-script-parameters-and-function-modules)
17. [Typed script parameters and Functions](#typed-script-parameters-and-functions)
18. [Script engines](#script-engines)
19. [Secrets providers and $Secrets](#secrets-providers-and-secrets)
20. [Device groups and script triggers](#device-groups-and-script-triggers)
@@ -322,22 +324,40 @@ docker compose up -d --build
## Standalone server binary
For a quick spin-up without containers, one self-contained binary serves the
WebUI (static SPA), the API, the `/messaging/*` WebSocket relay, and supervises
a bundled `nats-server` sidecar. CI publishes `Server-<version>-win-x64.zip`
and `…-linux-x64.zip` (build locally with `./scripts/Package-Server.ps1`):
For a quick spin-up without containers, one self-contained `ExecuteR-Server`
binary serves the WebUI (static SPA), the API, the `/messaging/*` WebSocket
relay, and supervises a `nats-server` sidecar. CI publishes
`Server-<version>-win-x64.zip`, `…-linux-x64.zip` **and `Server-<version>.msi`**
(build locally with `./scripts/Package-Server.ps1`):
```text
ExecuteRServer setup generate NATS keys, sidecar config, appsettings.json
# edit appsettings.json: set INITIAL_ADMIN_PASSWORD (first start only)
ExecuteRServer run in the foreground on http://0.0.0.0:9080
ExecuteRServer service install Windows service / systemd unit
ExecuteRServer service uninstall
ExecuteR-Server setup
Generates NATS keys, the sidecar config and appsettings.json with the
admin/admin sign-in (override with --admin-user/--admin-password) — and
downloads nats-server for this OS/architecture if it is not bundled.
ExecuteR-Server run in the foreground on http://0.0.0.0:9080
ExecuteR-Server service install Windows service / systemd unit
ExecuteR-Server service uninstall
```
Agents enroll against the same base URL. Put a TLS-terminating reverse proxy
in front for production use; the compose stack remains the recommended
deployment for anything long-lived.
When the password was left at the default, the **first sign-in demands a new
password** before any session is issued — valid credentials return a
must-change signal, and the sign-in page walks straight into a set-new-password
form. Choosing a literal `admin` password (CLI flag or MSI wizard) triggers
the same reset.
![First sign-in password reset](docs/screenshots/login-reset.png)
The **Windows MSI** wraps the same flow: an Administrator account page in the
wizard (defaults admin / admin; `ADMINUSERNAME=… ADMINPASSWORD=…` for silent
installs) then the binary's own `setup` + `service install`. Upgrades never
overwrite existing configuration, and uninstall stops and removes the service.
Bundles ship the **agent installers** (`agent-package/` with `Agent.msi`,
`Agent.zip`, `VERSION`), so the URL install command works immediately — no
seeding, no S3. Agents enroll against the same base URL. Put a TLS-terminating
reverse proxy in front for production use; the compose stack remains the
recommended deployment for anything long-lived.
---
@@ -531,7 +551,7 @@ assigned users cannot be dropped.
---
## Typed script parameters and function modules
## Typed script parameters and Functions
Scripts can declare typed parameters whose editor input changes by type:
string, number, boolean, array (with element type), and hashtable. Hashtable
@@ -551,23 +571,30 @@ and pass the raw text through exactly as typed (regex patterns, literal `$`).
Expansion applies to string scalars, string array elements and hashtable
values — hashtable keys stay literal.
Reusable **function modules** (managed under **Functions**) can be attached to a
Reusable **Functions** can be attached to a
script; the backend prepends them as a prelude executed first in the same
runspace, so individual scripts stay small and duplication is avoided.
Scripts, Functions, schedules, groups (rules and static members included) and
roles all support one-click **Clone** — the copy lands as "Name (copy)" ready
to edit. Role clones copy permissions and device scope but never OIDC claim
values, so identity mappings stay unambiguous; system roles clone into custom
roles, making Admin/Operator/Viewer handy templates.
![Script editor](docs/screenshots/script-editor.png)
---
## Script engines
Each script selects its engine in the editor (Monaco switches syntax
highlighting to match):
Each script picks its **Script Engine** in the editor — the selector shows a
one-line hint describing the selected engine's platform behavior, and Monaco
switches syntax highlighting to match:
- **PowerShell 7 (default)** — the embedded PowerShell SDK in the agent
process on every platform. Full feature set: live progress records, typed
parameters, `$Secrets`, function-module preludes.
- **Windows PowerShell 5.1** — shells out to `powershell.exe` with near
parameters, `$Secrets`, Functions preludes.
- **PowerShell 5** — shells out to `powershell.exe` on Windows with near
parity: a generated wrapper renders parameters as typed PowerShell literals
(hashtables and arrays included), defines the case-insensitive secrets
dictionary, dot-sources the prelude and splats the payload. Stdout/stderr
@@ -576,8 +603,18 @@ highlighting to match):
and secrets arrive as environment variables; complex values are JSON
strings (`jq` friendly). The prelude is concatenated ahead of the script.
An engine unavailable on a device (5.1 on Linux, bash without Git Bash on
Windows) fails the job immediately with a clear message instead of running.
An engine unavailable on a device (PowerShell 5 on Linux, bash without Git
Bash on Windows) fails the job immediately with a clear message instead of
running.
The editor itself pops out to fill the window (Esc restores) and offers
optional **IntelliSense** — a curated offline provider with common cmdlets,
keywords, snippets, plus the script's own parameters, `$Secrets` bindings and
`$Files` entries (typed as FileInfo or DirectoryInfo); no language server
involved. Execution flows vertically beneath the editor: target and
**Execution values**, Schedules, Triggers, then full-width output.
![Script execution flow](docs/screenshots/script-execution.png)
The packaged agent bundles **PSResourceGet**, **Archive** and **ThreadJob**
next to the binary and prepends that directory to `PSModulePath` — so
@@ -636,7 +673,10 @@ and both conditions and groups have an independent **NOT**.
Operators: `equals`, `notEquals`, `contains`, `notContains`, `startsWith`,
`endsWith`, `regex`, `in`, `notIn`, `>`, `>=`, `<`, `<=`, `exists`,
`notExists`.
`notExists`, `inCidr`, `notInCidr`. The CIDR operators evaluate IP fields
against comma-separated ranges (`10.20.0.0/16, 192.168.1.0/24`) using the
BCL `System.Net.IPNetwork` — IPv4 and IPv6, bare IPs mean equality, and host
bits in the base address are normalized.
Fields come from hardware inventory, tags, hostname/identity, and live status —
the full catalogue is served by `GET /api/groups/fields`, so the rule builder
@@ -646,9 +686,16 @@ always matches what the server can evaluate:
|----------|----------|
| Identity | `hostname`, `clientId`, `status`, `tags`, `agentVersion`, `domain` |
| Hardware | `manufacturer`, `model`, `serialNumber`, `cpu.cores`, `memory.totalGb` |
| Operating system | `os.caption`, `os.version`, `os.build`, `os.architecture` |
| Operating system | `os.platform` (windows/linux/macos), `os.caption`, `os.version`, `os.build` |
| Storage | `disk.count`, `disk.totalGb`, `volume.freeGb` |
| Network | `network.ipv4`, `network.mac`, `network.dns` |
| Network | `network.ipv4`, `network.mac`, `network.dns`, `network.interface` |
Every deployment starts with six **default platform groups** — Windows
Servers, Windows Workstations, Linux, Linux Servers, Linux Workstations,
macOS — driven by `os.platform` and, for the Linux split, `os.edition`
(the unix agent reports Workstation when the device boots to a graphical
session, Server otherwise). Seeded only while no groups exist, so edits and
deletions stick.
Multi-valued fields (tags, IPs, MACs, DNS) match when **any** value satisfies a
positive operator, and require **all** values for the negative ones. A missing
@@ -659,8 +706,9 @@ matches and never throws.
![Group rule builder](docs/screenshots/groups-rule-builder.png)
**Script triggers** run a script automatically on a device lifecycle event,
targeted at a group (or all devices):
**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:
| Trigger | Fires when |
|---------|-----------|
@@ -668,8 +716,8 @@ targeted at a group (or all devices):
| `onAgentReady` | The agent is connected *and* its durable command consumer is bound — genuinely ready for jobs |
Triggers default to **once per device** (recorded durably), and triggered runs
use the normal job pipeline, so they carry the script's function-module prelude
and typed parameters and appear alongside manual runs.
use the normal job pipeline, so they carry the script's Functions prelude and
typed parameters and appear alongside manual runs.
---
@@ -683,8 +731,10 @@ 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 run values. One "Nightly at 1am" cadence can drive any
number of scripts, and pausing the cadence pauses everything attached to it.
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.
The cadence builder leads with friendly selectors — *every N minutes/hours*,
*daily/weekly/monthly at a time* with weekday chips — and compiles them to
@@ -710,7 +760,7 @@ Semantics worth knowing:
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.
- Run values captured when a schedule is attached are used for every firing;
- Execution values captured when a schedule is attached are used for every firing;
secret bindings resolve fresh server-side at each fire time.
---
@@ -864,6 +914,19 @@ Configure an S3-compatible store (AWS S3, MinIO, Backblaze B2) from
**Device → Actions → Send file**. Credentials stay on the server — the endpoint
only ever sees a short-lived URL.
**Script file bindings** integrate delivery into execution: in the script
editor's define strip, bind S3 objects (or whole prefixes, delivered
recursively) that download to the device **before the script runs**. The
destination path expands on the device (`%TEMP%`, `$env:ProgramData`,
`$(…)`), and each entry reaches the script through a case-insensitive ordered
dictionary — `$Files.Name` is a **FileInfo** for single objects or a
**DirectoryInfo** for prefixes. The server lists and presigns everything at
dispatch, so agents never hold S3 credentials. Per-entry **continue on
failure** logs a warning and still runs the script (`$Files.Name.Exists`
tells you what arrived); otherwise a failed delivery fails the job before
execution. PowerShell 5 receives the same `$Files` dictionary; bash gets one
environment variable per entry holding the delivered path.
**Configured and tested from the UI.** Settings saved in the browser are stored
in the database (the secret key encrypted at rest with Data Protection) and
override the `S3_*` environment variables, which remain the bootstrap defaults.
@@ -970,11 +1033,12 @@ Gitea Actions workflows live in `.gitea/workflows`:
- **Pull request to `main`** — restore, build, unit + integration tests, Svelte
check. No image push, no release.
- **Push to `dev`** — build + test, agent binaries for every platform
(win-x64, linux-x64, linux-arm64, osx-x64, osx-arm64) + MSI, the standalone
server (win-x64, linux-x64), backend/webui images tagged `dev` and
`<version>-dev`. All binaries upload as the `binaries` run artifact.
(win-x64, win-arm64, linux-x64, linux-arm64, osx-x64, osx-arm64) + MSI, the
standalone server (win-x64 + MSI, linux-x64), backend/webui images tagged
`dev` and `<version>-dev`. All binaries upload as the `binaries` run
artifact.
- **Push to `main`** — the same set, images tagged `<version>` and `latest`,
and a Gitea release with every agent ZIP, the MSI, the Server ZIPs and
and a Gitea release with every agent ZIP, both MSIs, the Server ZIPs and
checksums.
Scripts discover context from optional environment variables and fall back
@@ -1042,8 +1106,8 @@ metadata), and the frontend build metadata.
| ![Device detail](docs/screenshots/device-detail.png) **Device overview, tags and groups** | ![Hardware](docs/screenshots/device-hardware.png) **Hardware inventory** |
| ![Network](docs/screenshots/device-network.png) **Network inventory** | ![Actions](docs/screenshots/device-actions.png) **Device actions and file delivery** |
| ![Groups](docs/screenshots/groups.png) **Groups** | ![Static members](docs/screenshots/groups-static-members.png) **Static group membership** |
| ![Script editor](docs/screenshots/script-editor.png) **Monaco PowerShell editor** | ![Parameters](docs/screenshots/script-parameters.png) **Typed parameters** |
| ![Jobs](docs/screenshots/jobs.png) **Jobs and stored output** | ![Functions](docs/screenshots/functions.png) **Function modules** |
| ![Script editor](docs/screenshots/script-editor.png) **Monaco editor with IntelliSense and pop-out** | ![Script Configuration](docs/screenshots/script-parameters.png) **Script Configuration: parameters, secrets, files, Functions** |
| ![Jobs](docs/screenshots/jobs.png) **Jobs and stored output** | ![Functions](docs/screenshots/functions.png) **Functions** |
| ![Access](docs/screenshots/access.png) **Users and custom roles** | ![Role editor](docs/screenshots/access-role-editor.png) **Role permissions and device scope** |
| ![Settings](docs/screenshots/settings-install-command.png) **Bootstrap token and install command** | ![Light theme](docs/screenshots/dashboard-light.png) **Light theme** |
Binary file not shown.

After

Width:  |  Height:  |  Size: 361 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

After

Width:  |  Height:  |  Size: 208 KiB

+53 -8
View File
@@ -17,6 +17,7 @@ param(
[string]$Version,
[string[]]$Runtimes = @('win-x64', 'linux-x64'),
[switch]$SkipNats,
[switch]$SkipMsi,
[switch]$SkipIcon
)
@@ -64,15 +65,30 @@ foreach ($rid in $Runtimes) {
# Single-file apphosts tolerate renames; ship a recognizable binary name.
if ($rid -like 'win-*') {
Rename-Item (Join-Path $publishDir 'Backend.exe') 'ExecuteRServer.exe'
Rename-Item (Join-Path $publishDir 'Backend.exe') 'ExecuteR-Server.exe'
}
else {
Rename-Item (Join-Path $publishDir 'Backend') 'ExecuteRServer'
Rename-Item (Join-Path $publishDir 'Backend') 'ExecuteR-Server'
}
# ── Embed the WebUI ──────────────────────────────────────────────────────
Copy-Item $staticBuild (Join-Path $publishDir 'wwwroot') -Recurse
# ── Bundle the agent installers so URL install works out of the box ─────
$agentStage = Join-Path $publishDir 'agent-package'
New-Item -ItemType Directory -Force $agentStage | Out-Null
$agentMsi = Join-Path $artifacts "Agent-$Version.msi"
$agentZip = Join-Path $artifacts "Agent-$Version-win-x64.zip"
$staged = $false
if (Test-Path $agentMsi) { Copy-Item $agentMsi (Join-Path $agentStage 'Agent.msi'); $staged = $true }
if (Test-Path $agentZip) { Copy-Item $agentZip (Join-Path $agentStage 'Agent.zip'); $staged = $true }
if ($staged) {
$Version | Set-Content (Join-Path $agentStage 'VERSION') -NoNewline
}
else {
Write-Warning "No agent artifacts for $Version found — run Package-Agent first for a complete bundle."
}
# ── Bundle nats-server for the sidecar ───────────────────────────────────
if (-not $SkipNats) {
$natsDir = Join-Path $publishDir 'nats'
@@ -107,21 +123,23 @@ foreach ($rid in $Runtimes) {
}
# ── Quick-start note ─────────────────────────────────────────────────────
$exeName = if ($rid -like 'win-*') { 'ExecuteRServer.exe' } else { './ExecuteRServer' }
$exeName = if ($rid -like 'win-*') { 'ExecuteR-Server.exe' } else { './ExecuteR-Server' }
Set-Content (Join-Path $publishDir 'QUICKSTART.txt') @"
ExecuteR standalone server $Version ($rid)
1. $exeName setup
Generates NATS keys, the sidecar config and appsettings.json.
2. Edit appsettings.json: set INITIAL_ADMIN_PASSWORD (first start only).
3. $exeName
Generates NATS keys, the sidecar config and appsettings.json with
the admin/admin sign-in (override with --admin-user/--admin-password;
change the password after the first sign-in either way).
2. $exeName
Serves the UI + API on http://0.0.0.0:9080 with the NATS sidecar.
...or run in the background:
$exeName service install (Windows service / systemd unit)
$exeName service uninstall
Put a TLS-terminating reverse proxy in front for production use.
Agents enroll against the same base URL (Settings -> bootstrap token).
Agent installers ship in ./agent-package, so the URL install command
works immediately. Put a TLS-terminating reverse proxy in front for
production use; agents enroll against the same base URL.
"@
# ── Zip it ───────────────────────────────────────────────────────────────
@@ -131,6 +149,33 @@ Agents enroll against the same base URL (Settings -> bootstrap token).
Write-Host "Created $zipPath"
}
# ── Server MSI (win-x64): admin-account wizard + service install ────────────
$serverWix = Join-Path $repoRoot 'src/Installer.Server/Server.Installer.wixproj'
$winPublish = Join-Path $artifacts "server/$Version/win-x64"
if (-not $SkipMsi -and (Test-Path $serverWix) -and (Test-Path $winPublish)) {
# Deterministic MSI ProductVersion transform (same as the agent):
# yyyy.MM.dd.HHmm -> (yyyy-2000).(MM).((dd-1)*1440 + HH*60 + mm)
$parts = $Version.Split('.')
$hhmm = [int]$parts[3]
$msiVersion = '{0}.{1}.{2}' -f ([int]$parts[0] - 2000), [int]$parts[1],
((([int]$parts[2] - 1) * 1440) + ([math]::Floor($hhmm / 100) * 60) + ($hhmm % 100))
Write-Host "Server MSI ProductVersion: $msiVersion"
dotnet build $serverWix -c Release --nologo `
"-p:UnifiedVersion=$Version" `
"-p:MsiProductVersion=$msiVersion" `
"-p:ServerPublishDir=$winPublish"
if ($LASTEXITCODE -ne 0) { throw "Server MSI build failed ($LASTEXITCODE)." }
$msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer.Server/bin/Release') -Filter '*.msi' -Recurse |
Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
if ($msi) {
$msiTarget = Join-Path $artifacts "Server-$Version.msi"
Copy-Item $msi.FullName $msiTarget -Force
Write-Host "Created $msiTarget"
}
}
# Checksums for release attachment.
$checksums = Join-Path $artifacts "Server-$Version-checksums.txt"
Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Server-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object {
+4 -3
View File
@@ -8,15 +8,16 @@
<TargetFrameworks>net10.0-windows;net10.0</TargetFrameworks>
<RootNamespace>Agent</RootNamespace>
<AssemblyName>Agent</AssemblyName>
<RuntimeIdentifiers>win-x64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<RuntimeIdentifiers>win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<!-- Required by the LibraryImport interop source generator. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Ship only English resources (drops PowerShell's ~15 localization satellites). -->
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
<!-- The full PowerShell SDK reference-assembly manifest is host-only bloat. -->
<PreserveCompilationContext>false</PreserveCompilationContext>
<!-- Generated by scripts/Generate-Icons.ps1; absent for plain dev builds. -->
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico</ApplicationIcon>
<!-- Committed icon (regenerate with scripts/Generate-Icons.ps1); conditional
so build contexts without the assets directory still build. -->
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net10.0-windows'">
+16 -2
View File
@@ -199,9 +199,22 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) :
private static List<InventoryNetworkAdapter> CollectNetwork()
{
// The friendly interface name ("Ethernet0") lives on Win32_NetworkAdapter,
// joinable to the configuration rows through the shared Index.
var interfaceNames = new Dictionary<uint, string>();
Query(
"SELECT Index, NetConnectionID FROM Win32_NetworkAdapter WHERE NetConnectionID IS NOT NULL",
obj =>
{
if (obj["Index"] is uint index && obj["NetConnectionID"] is string name && name.Length > 0)
{
interfaceNames[index] = name;
}
});
var adapters = new List<InventoryNetworkAdapter>();
Query(
"SELECT Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE",
"SELECT Index, Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE",
obj =>
{
var addresses = obj["IPAddress"] as string[] ?? [];
@@ -211,7 +224,8 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) :
Ipv4Addresses: [.. addresses.Where(a => !a.Contains(':'))],
Ipv6Addresses: [.. addresses.Where(a => a.Contains(':'))],
Gateways: [.. obj["DefaultIPGateway"] as string[] ?? []],
DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []]));
DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []],
InterfaceName: obj["Index"] is uint index ? interfaceNames.GetValueOrDefault(index) : null));
});
return adapters;
}
+41 -3
View File
@@ -36,7 +36,7 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc
Architecture: System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString(),
InstallDateUtc: null,
LastBootUtc: ReadLastBoot(),
Edition: null);
Edition: DetectEdition());
return new InventoryReport(
Identity: identity,
@@ -50,6 +50,43 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc
CollectedUtc: DateTimeOffset.UtcNow);
}
/// <summary>
/// "Workstation" or "Server". macOS is always a workstation; linux is a
/// workstation when it boots to a graphical session (default systemd
/// target, or installed desktop session files as the fallback).
/// </summary>
private static string DetectEdition()
{
if (OperatingSystem.IsMacOS())
{
return "Workstation";
}
var defaultTarget = UnixHardwareIdentitySource.Exec("systemctl", "get-default")?.Trim();
if (!string.IsNullOrEmpty(defaultTarget))
{
return defaultTarget.Contains("graphical", StringComparison.OrdinalIgnoreCase)
? "Workstation"
: "Server";
}
var hasDesktopSessions =
HasEntries("/usr/share/xsessions") || HasEntries("/usr/share/wayland-sessions");
return hasDesktopSessions ? "Workstation" : "Server";
static bool HasEntries(string path)
{
try
{
return Directory.Exists(path) && Directory.EnumerateFiles(path).Any();
}
catch (Exception)
{
return false;
}
}
}
private static (string? Name, string? Version) ReadOsRelease()
{
if (OperatingSystem.IsMacOS())
@@ -237,12 +274,13 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc
var mac = nic.GetPhysicalAddress().GetAddressBytes();
adapters.Add(new InventoryNetworkAdapter(
Description: nic.Name,
Description: string.IsNullOrWhiteSpace(nic.Description) ? nic.Name : nic.Description,
MacAddress: mac.Length > 0 ? string.Join(':', mac.Select(b => b.ToString("X2"))) : null,
Ipv4Addresses: v4,
Ipv6Addresses: v6,
Gateways: props.GatewayAddresses.Select(g => g.Address.ToString()).ToList(),
DnsServers: props.DnsAddresses.Select(d => d.ToString()).ToList()));
DnsServers: props.DnsAddresses.Select(d => d.ToString()).ToList(),
InterfaceName: nic.Name));
}
catch (Exception)
{
+26 -3
View File
@@ -36,7 +36,8 @@ public static class ExternalScriptRunner
IReadOnlyList<ScriptSecret>? secrets,
string secretsVariableName,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
System.Collections.Specialized.OrderedDictionary? files = null)
{
// Child processes inherit PSModulePath, so 5.1 also sees the bundled
// gallery modules (PSResourceGet supports Windows PowerShell 5.1+).
@@ -48,8 +49,8 @@ public static class ExternalScriptRunner
{
return engine == ScriptEngine.WindowsPowerShell
? await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, workDir, onRecord, cancellationToken)
: await RunBashAsync(content, prelude, parameters, secrets, workDir, onRecord, cancellationToken);
content, prelude, parameters, secrets, secretsVariableName, files, workDir, onRecord, cancellationToken)
: await RunBashAsync(content, prelude, parameters, secrets, files, workDir, onRecord, cancellationToken);
}
finally
{
@@ -70,6 +71,7 @@ public static class ExternalScriptRunner
IReadOnlyDictionary<string, object?> parameters,
IReadOnlyList<ScriptSecret>? secrets,
string secretsVariableName,
System.Collections.Specialized.OrderedDictionary? files,
string workDir,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
@@ -95,6 +97,17 @@ public static class ExternalScriptRunner
}
}
if (files is { Count: > 0 })
{
wrapper.AppendLine("$Files = @{}");
foreach (System.Collections.DictionaryEntry entry in files)
{
var type = entry.Value is DirectoryInfo ? "System.IO.DirectoryInfo" : "System.IO.FileInfo";
var path = ((FileSystemInfo)entry.Value!).FullName;
wrapper.AppendLine($"$Files[{PsLiteral(entry.Key)}] = [{type}]{PsLiteral(path)}");
}
}
wrapper.AppendLine("$__splat = @{}");
foreach (var (name, value) in parameters)
{
@@ -120,6 +133,7 @@ public static class ExternalScriptRunner
string? prelude,
IReadOnlyDictionary<string, object?> parameters,
IReadOnlyList<ScriptSecret>? secrets,
System.Collections.Specialized.OrderedDictionary? files,
string workDir,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
@@ -157,6 +171,15 @@ public static class ExternalScriptRunner
environment[secret.Name] = secret.Value;
}
// Delivered file paths arrive as env vars named after the binding.
if (files is not null)
{
foreach (System.Collections.DictionaryEntry entry in files)
{
environment[(string)entry.Key] = ((FileSystemInfo)entry.Value!).FullName;
}
}
return await RunProcessAsync(bash, $"\"{scriptPath}\"", environment, onRecord, cancellationToken);
}
+58 -2
View File
@@ -69,7 +69,40 @@ public sealed class PowerShellJobHandler(
int exitCode;
string? message = null;
if (command.Engine != ScriptEngine.PowerShell)
// S3 file deliveries land before the script starts. Destination
// paths expand on the device (%VAR% natively; $env:/$(…) through a
// short-lived runspace, regardless of engine), and the resolved
// FileInfo/DirectoryInfo dictionary becomes $Files.
System.Collections.Specialized.OrderedDictionary? filesDict = null;
string? deliveryFailure = null;
if (command.Files is { Count: > 0 })
{
using var expansionRunspace = PowerShellRunspaceFactory.Create();
var fetch = await ScriptFileFetcher.FetchAsync(
command.Files,
path => ExpandDeliveryPath(path, expansionRunspace),
record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
timeoutCts.Token);
if (fetch.FailureMessage is not null)
{
deliveryFailure = fetch.FailureMessage;
}
else
{
filesDict = fetch.Files;
sessionVariables ??= [];
sessionVariables["Files"] = filesDict;
}
}
if (deliveryFailure is not null)
{
finalState = JobState.Failed;
exitCode = 1;
message = deliveryFailure;
await Task.WhenAll(pending);
}
else if (command.Engine != ScriptEngine.PowerShell)
{
// Out-of-process engine: Windows PowerShell 5.1 or Bash.
if (!ExternalScriptRunner.IsAvailable(command.Engine))
@@ -89,7 +122,8 @@ public sealed class PowerShellJobHandler(
command.Secrets,
string.IsNullOrWhiteSpace(command.SecretsVariableName) ? "Secrets" : command.SecretsVariableName,
record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
timeoutCts.Token);
timeoutCts.Token,
files: filesDict);
if (external.WasCancelled && cancellationToken.IsCancellationRequested)
{
@@ -168,6 +202,28 @@ public sealed class PowerShellJobHandler(
Interlocked.Decrement(ref activeJobs);
}
// File destination paths get the full expansion treatment: %VAR% via
// the environment, then $env:/$(…) as double-quoted string content in
// a dedicated runspace (available whatever engine runs the script).
static string ExpandDeliveryPath(string path, System.Management.Automation.Runspaces.Runspace runspace)
{
var expanded = Environment.ExpandEnvironmentVariables(path);
if (!expanded.Contains('$') && !expanded.Contains('`'))
{
return expanded;
}
try
{
return runspace.SessionStateProxy.InvokeCommand.ExpandString(expanded);
}
catch (Exception ex) when (
ex is System.Management.Automation.RuntimeException or InvalidOperationException)
{
return expanded;
}
}
// External engines cannot use the in-runspace ExpandString pass;
// %VAR% expansion via the device environment still applies to
// non-literal string values.
+158
View File
@@ -0,0 +1,158 @@
using System.Collections.Specialized;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
namespace Agent.PowerShell;
/// <summary>
/// Downloads a job's file deliveries before the script starts. Destination
/// paths arrive already expanded; every delivery lands in a case-insensitive
/// ordered dictionary as a FileInfo (single object) or DirectoryInfo
/// (recursive prefix) — the script sees it as <c>$Files.Name</c> even when a
/// continue-on-failure delivery did not arrive (check <c>.Exists</c>).
/// </summary>
public static class ScriptFileFetcher
{
public sealed record FetchResult(OrderedDictionary Files, string? FailureMessage);
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(30) };
public static async Task<FetchResult> FetchAsync(
IReadOnlyList<ScriptFileDelivery> deliveries,
Func<string, string> expandPath,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
var files = new OrderedDictionary(StringComparer.OrdinalIgnoreCase);
foreach (var delivery in deliveries)
{
string destination;
try
{
destination = Path.GetFullPath(expandPath(delivery.DestinationPath));
}
catch (Exception ex)
{
var problem = $"File “{delivery.Name}”: destination “{delivery.DestinationPath}” is invalid ({ex.Message}).";
if (!delivery.ContinueOnFailure)
{
return new FetchResult(files, problem);
}
onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, problem));
continue;
}
files[delivery.Name] = delivery.Directory
? new DirectoryInfo(destination)
: new FileInfo(destination);
if (delivery.Error is not null)
{
var problem = $"File “{delivery.Name}” was not delivered: {delivery.Error}";
if (!delivery.ContinueOnFailure)
{
return new FetchResult(files, problem);
}
onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, problem));
continue;
}
try
{
foreach (var item in delivery.Items)
{
var target = item.RelativePath.Length == 0
? destination
: SafeCombine(destination, item.RelativePath);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
var bytes = await DownloadAsync(item.Url, target, cancellationToken);
onRecord(new NormalizedOutputRecord(OutputStreamKind.Output,
$"Delivered {delivery.Name}{(item.RelativePath.Length > 0 ? "/" + item.RelativePath : "")} → {target} ({FormatSize(bytes)})"));
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
var problem = $"File “{delivery.Name}” failed to download: {ex.Message}";
if (!delivery.ContinueOnFailure)
{
return new FetchResult(files, problem);
}
onRecord(new NormalizedOutputRecord(OutputStreamKind.Warning, $"{problem} — continuing."));
}
}
return new FetchResult(files, null);
}
/// <summary>Streams to a temp file, then moves into place (no partial files).</summary>
private static async Task<long> DownloadAsync(string url, string target, CancellationToken cancellationToken)
{
var temp = target + ".executer-download";
try
{
using var response = await Http.GetAsync(
url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
await using (var file = File.Create(temp))
{
await response.Content.CopyToAsync(file, cancellationToken);
}
File.Move(temp, target, overwrite: true);
return new FileInfo(target).Length;
}
finally
{
try
{
if (File.Exists(temp))
{
File.Delete(temp);
}
}
catch (IOException)
{
// Best effort.
}
}
}
/// <summary>
/// Joins a relative S3 key onto the destination directory, refusing rooted
/// paths and traversal that would escape it.
/// </summary>
internal static string SafeCombine(string root, string relativePath)
{
var normalized = relativePath.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
if (Path.IsPathRooted(normalized))
{
throw new InvalidOperationException($"Refusing rooted relative path “{relativePath}”.");
}
var rootFull = Path.GetFullPath(root);
var combined = Path.GetFullPath(Path.Combine(rootFull, normalized));
if (!combined.StartsWith(rootFull.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException($"Refusing path traversal in “{relativePath}”.");
}
return combined;
}
private static string FormatSize(long bytes) => bytes switch
{
>= 1_073_741_824 => $"{bytes / 1_073_741_824d:F1} GB",
>= 1_048_576 => $"{bytes / 1_048_576d:F1} MB",
>= 1024 => $"{bytes / 1024d:F1} KB",
_ => $"{bytes} bytes",
};
}
+64 -5
View File
@@ -2,6 +2,7 @@ using System.Security.Claims;
using Backend.Proxy;
using Backend.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
@@ -15,6 +16,10 @@ public static class AuthEndpoints
.RequireRateLimiting(RateLimitPolicies.Auth)
.AllowAnonymous();
app.MapPost(ApiRoutes.AuthChangePassword, ChangePasswordAsync)
.RequireRateLimiting(RateLimitPolicies.Auth)
.AllowAnonymous();
app.MapPost(ApiRoutes.AuthLogout, (Delegate)LogoutAsync);
app.MapGet(ApiRoutes.AuthSession, GetSessionAsync).AllowAnonymous();
@@ -54,6 +59,63 @@ public static class AuthEndpoints
return Results.Unauthorized();
}
// Valid credentials, but a defaulted password: no session until a real
// one is set (POST /api/auth/change-password completes the sign-in).
if (user.MustChangePassword)
{
await audit.LogAsync(AuditCategories.Auth, "login-password-change-required",
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
return Results.Ok(new SessionResponse(
false, user.Username, user.DisplayName, null, AuthConstants.ProviderLocal,
MustChangePassword: true));
}
var session = await IssueSessionAsync(user, roles, context, cancellationToken);
await audit.LogAsync(AuditCategories.Auth, "login-succeeded",
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
return Results.Ok(session);
}
private static async Task<IResult> ChangePasswordAsync(
ChangePasswordRequest request,
Backend.Data.AppDbContext db,
UserService users,
RoleCache roles,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
var remoteIp = ClientIp.EffectiveText(context);
if (request.NewPassword.Length < 8)
{
return Results.BadRequest(new { error = "The new password must be at least 8 characters." });
}
var user = await users.ValidateCredentialsAsync(
request.Username, request.CurrentPassword, cancellationToken);
if (user is null)
{
await audit.LogAsync(AuditCategories.Auth, "password-change-failed",
actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
return Results.Unauthorized();
}
var tracked = await db.Users.SingleAsync(u => u.Id == user.Id, cancellationToken);
tracked.PasswordHash = users.HashPassword(tracked, request.NewPassword);
tracked.MustChangePassword = false;
await db.SaveChangesAsync(cancellationToken);
var session = await IssueSessionAsync(tracked, roles, context, cancellationToken);
await audit.LogAsync(AuditCategories.Auth, "password-changed",
actor: tracked.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
return Results.Ok(session);
}
/// <summary>Issues the cookie session + CSRF token and builds the response body.</summary>
private static async Task<SessionResponse> IssueSessionAsync(
Backend.Data.UserEntity user, RoleCache roles, HttpContext context, CancellationToken cancellationToken)
{
var role = user.RoleId is { } roleId ? await roles.FindByIdAsync(roleId, cancellationToken) : null;
role ??= await roles.FindByNameAsync(user.Role.ToString(), cancellationToken);
@@ -63,14 +125,11 @@ public static class AuthEndpoints
await context.SignInAsync(AuthConstants.CookieScheme, principal);
CsrfProtection.IssueToken(context);
await audit.LogAsync(AuditCategories.Auth, "login-succeeded",
actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken);
var permissions = role?.Permissions.Order(StringComparer.Ordinal).ToList() ?? [];
return Results.Ok(new SessionResponse(
return new SessionResponse(
true, user.Username, user.DisplayName,
role is null ? user.Role : Permissions.Tier(role.Permissions),
AuthConstants.ProviderLocal, role?.Name, permissions));
AuthConstants.ProviderLocal, role?.Name, permissions);
}
private static async Task<IResult> LogoutAsync(HttpContext context)
+4 -2
View File
@@ -65,8 +65,10 @@ public static class CsrfProtection
return false;
}
// Login establishes the session; protected by rate limiting + credentials.
if (path.StartsWithSegments("/api/auth/login"))
// Login and the pre-session password change establish the session;
// both are protected by rate limiting + credentials.
if (path.StartsWithSegments("/api/auth/login")
|| path.StartsWithSegments("/api/auth/change-password"))
{
return false;
}
+3 -1
View File
@@ -19,7 +19,8 @@ public sealed class UserService(AppDbContext db, ILogger<UserService> logger)
/// Never overwrites an existing admin's password. Runs after system-role
/// seeding so the account lands on the Admin role.
/// </summary>
public async Task EnsureInitialAdminAsync(string? username, string? password, CancellationToken cancellationToken)
public async Task EnsureInitialAdminAsync(
string? username, string? password, bool mustChangePassword, CancellationToken cancellationToken)
{
if (await db.Users.AnyAsync(cancellationToken))
{
@@ -46,6 +47,7 @@ public sealed class UserService(AppDbContext db, ILogger<UserService> logger)
Role = UserRole.Admin,
RoleId = adminRoleId,
AuthProvider = AuthConstants.ProviderLocal,
MustChangePassword = mustChangePassword,
CreatedUtc = DateTimeOffset.UtcNow,
};
admin.PasswordHash = hasher.HashPassword(admin, password);
+3 -1
View File
@@ -5,7 +5,9 @@
<RootNamespace>Backend</RootNamespace>
<UserSecretsId>backend-dev-secrets</UserSecretsId>
<!-- Exe icon for the standalone server binary (Windows publishes). -->
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico</ApplicationIcon>
<!-- Conditional: the docker build context has no assets directory, and
linux images need no exe icon anyway. -->
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
+110
View File
@@ -0,0 +1,110 @@
using Backend.Jobs;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Models;
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.
/// </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)
{
if (await db.DeviceGroups.AnyAsync(cancellationToken))
{
return;
}
var now = DateTimeOffset.UtcNow;
foreach (var (name, description, rules) in PlatformGroups())
{
db.DeviceGroups.Add(new DeviceGroupEntity
{
Id = Guid.NewGuid(),
Name = name,
Description = description,
Kind = GroupKind.Dynamic,
RulesJson = JsonDefaults.Serialize(rules),
CreatedUtc = now,
UpdatedUtc = now,
UpdatedBy = "system",
});
}
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 Servers", "Every Windows Server edition.",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"),
new RuleCondition("os.caption", RuleOperator.Contains, "Server")));
yield return ("Windows Workstations", "Windows clients (10, 11, ...).",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "windows"),
new RuleCondition("os.caption", RuleOperator.NotContains, "Server")));
yield return ("Linux", "All Linux devices.",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux")));
// The unix agent reports os.edition from the boot target / installed
// desktop sessions: graphical => Workstation, headless => Server.
yield return ("Linux Servers", "Headless Linux (no graphical session).",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux"),
new RuleCondition("os.edition", RuleOperator.Equals, "Server")));
yield return ("Linux Workstations", "Linux with a desktop environment.",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "linux"),
new RuleCondition("os.edition", RuleOperator.Equals, "Workstation")));
yield return ("macOS", "All Apple devices.",
Set(new RuleCondition("os.platform", RuleOperator.Equals, "macos")));
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ public static class DevSeeder
new InventoryVolume("D:", "NTFS", 488_000_000_000, 402_100_000_000, DiskIndex: 0),
new InventoryVolume("E:", "NTFS", 4_000_000_000_000, 1_250_000_000_000, DiskIndex: 1),
],
[new InventoryNetworkAdapter("Intel Ethernet I219-LM", "00:1A:2B:3C:4D:0" + i, ips, ["fe80::1"], ["10.20.0.1"], ["10.20.0.10", "10.20.0.11"])],
[new InventoryNetworkAdapter("Intel Ethernet I219-LM", "00:1A:2B:3C:4D:0" + i, ips, ["fe80::1"], ["10.20.0.1"], ["10.20.0.10", "10.20.0.11"], InterfaceName: "Ethernet0")],
now - seenAgo);
db.DeviceInventory.Add(new DeviceInventoryEntity
+4
View File
@@ -12,6 +12,8 @@ public sealed class UserEntity
public UserRole Role { get; set; }
/// <summary>Assigned <see cref="RoleEntity"/>; null falls back to the legacy tier.</summary>
public Guid? RoleId { get; set; }
/// <summary>Sign-in must set a new password first (e.g. the defaulted admin/admin).</summary>
public bool MustChangePassword { get; set; }
/// <summary>"local" or "oidc".</summary>
public required string AuthProvider { get; set; }
/// <summary>OIDC subject claim for external users.</summary>
@@ -160,6 +162,8 @@ public sealed class ScriptEntity
public string? SecretBindingsJson { get; set; }
/// <summary>Session variable the resolved secrets dictionary binds to (default "Secrets").</summary>
public string? SecretsVariableName { get; set; }
/// <summary>JSON array of ScriptFileBinding definitions (S3 objects delivered before execution).</summary>
public string? FileBindingsJson { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? CreatedBy { get; set; }
@@ -0,0 +1,809 @@
// <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("20260808140726_AddMustChangePassword")]
partial class AddMustChangePassword
{
/// <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>("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>("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<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
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,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddMustChangePassword : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "MustChangePassword",
table: "Users",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "MustChangePassword",
table: "Users");
}
}
}
@@ -0,0 +1,812 @@
// <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("20260808150344_AddScriptFileBindings")]
partial class AddScriptFileBindings
{
/// <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>("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<bool>("OncePerDevice")
.HasColumnType("boolean");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
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,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddScriptFileBindings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "FileBindingsJson",
table: "Scripts",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FileBindingsJson",
table: "Scripts");
}
}
}
@@ -515,6 +515,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("FileBindingsJson")
.HasColumnType("text");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("text");
@@ -747,6 +750,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.HasColumnType("boolean");
b.Property<string>("PasswordHash")
.HasColumnType("text");
@@ -0,0 +1,809 @@
// <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("20260808140730_AddMustChangePassword")]
partial class AddMustChangePassword
{
/// <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>("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>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
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,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddMustChangePassword : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "MustChangePassword",
table: "Users",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "MustChangePassword",
table: "Users");
}
}
}
@@ -0,0 +1,812 @@
// <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("20260808150347_AddScriptFileBindings")]
partial class AddScriptFileBindings
{
/// <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>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<bool>("OncePerDevice")
.HasColumnType("bit");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
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,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddScriptFileBindings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "FileBindingsJson",
table: "Scripts",
type: "nvarchar(max)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FileBindingsJson",
table: "Scripts");
}
}
}
@@ -515,6 +515,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("FileBindingsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("nvarchar(max)");
@@ -747,6 +750,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<DateTimeOffset?>("LastLoginUtc")
.HasColumnType("datetimeoffset");
b.Property<bool>("MustChangePassword")
.HasColumnType("bit");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
@@ -0,0 +1,796 @@
// <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("20260808140722_AddMustChangePassword")]
partial class AddMustChangePassword
{
/// <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>("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>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
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,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddMustChangePassword : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "MustChangePassword",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "MustChangePassword",
table: "Users");
}
}
}
@@ -0,0 +1,799 @@
// <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("20260808150341_AddScriptFileBindings")]
partial class AddScriptFileBindings
{
/// <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>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<bool>("OncePerDevice")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
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,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddScriptFileBindings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "FileBindingsJson",
table: "Scripts",
type: "TEXT",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FileBindingsJson",
table: "Scripts");
}
}
}
@@ -504,6 +504,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("FileBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("FunctionModuleIdsJson")
.HasColumnType("TEXT");
@@ -734,6 +737,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<long?>("LastLoginUtc")
.HasColumnType("INTEGER");
b.Property<bool>("MustChangePassword")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
@@ -0,0 +1,9 @@
namespace Backend.Files;
/// <summary>
/// A script's file bindings could not be resolved (S3 unconfigured, listing or
/// presign failure) for an entry that does not continue on failure. Surfaces
/// before any job rows exist, exactly like secret resolution failures.
/// </summary>
public sealed class FileResolutionException(string message, Exception? inner = null)
: Exception(message, inner);
+43
View File
@@ -35,4 +35,47 @@ public sealed class S3PresignService(S3SettingsService settings)
return (url, new DateTimeOffset(expires, TimeSpan.Zero));
}
/// <summary>
/// Every object key under a prefix (recursive), with sizes. Used for
/// directory file bindings; capped to keep a runaway prefix from turning
/// into a giant payload.
/// </summary>
public async Task<IReadOnlyList<(string Key, long SizeBytes)>> ListKeysAsync(
string prefix, CancellationToken cancellationToken, int maxKeys = 2000)
{
var options = await settings.GetEffectiveAsync(cancellationToken);
if (!options.IsUsable)
{
throw new InvalidOperationException("S3 is not configured.");
}
using var client = S3ClientFactory.Create(options);
var results = new List<(string, long)>();
var request = new ListObjectsV2Request { BucketName = options.Bucket, Prefix = prefix };
ListObjectsV2Response response;
do
{
response = await client.ListObjectsV2Async(request, cancellationToken);
foreach (var entry in response.S3Objects ?? [])
{
// Zero-byte "folder marker" objects are not downloadable content.
if (!entry.Key.EndsWith('/'))
{
results.Add((entry.Key, entry.Size ?? 0));
}
if (results.Count >= maxKeys)
{
return results;
}
}
request.ContinuationToken = response.NextContinuationToken;
}
while (response.IsTruncated == true);
return results;
}
}
+85 -40
View File
@@ -11,33 +11,89 @@ namespace Backend.Groups;
/// <summary>
/// Resolves group membership. Static groups use the explicit member table;
/// dynamic groups evaluate their rules against each device's field bag
/// (inventory + tags + status + identity).
/// (inventory + tags + status + identity). Inventory parsing goes through
/// <see cref="InventoryReportCache"/>, so fleet-wide evaluation stays cheap at
/// thousands of devices: snapshots are re-fetched and re-parsed only when
/// their UpdatedUtc moved.
/// </summary>
public sealed class DeviceGroupService(AppDbContext db)
public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inventoryCache)
{
/// <summary>Builds the rule field bag for one device.</summary>
public static DeviceFieldBag BuildFields(DeviceEntity device, string? inventoryJson, DateTimeOffset now)
{
InventoryReport? inventory = null;
if (!string.IsNullOrWhiteSpace(inventoryJson))
{
try
{
inventory = JsonDefaults.Deserialize<InventoryReport>(inventoryJson);
}
catch (Exception)
{
// Corrupt snapshot: evaluate on identity fields only.
}
}
return DeviceFieldBag.Build(
public static DeviceFieldBag BuildFields(DeviceEntity device, InventoryReport? inventory, DateTimeOffset now)
=> DeviceFieldBag.Build(
device.ClientId,
device.Hostname,
ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now),
device.AgentVersion,
ParseTags(device.TagsJson),
inventory);
inventory,
fallbackOsCaption: device.OsCaption,
fallbackOsVersion: device.OsVersion);
/// <summary>
/// Cached inventory for one device: metadata probe first, JSON fetched
/// only when the snapshot changed since it was last parsed.
/// </summary>
private async Task<InventoryReport?> GetInventoryAsync(string clientId, CancellationToken cancellationToken)
{
var meta = await db.DeviceInventory.AsNoTracking()
.Where(i => i.ClientId == clientId)
.Select(i => new { i.UpdatedUtc })
.FirstOrDefaultAsync(cancellationToken);
if (meta is null)
{
return null;
}
if (inventoryCache.TryGet(clientId, meta.UpdatedUtc, out var cached))
{
return cached;
}
var json = await db.DeviceInventory.AsNoTracking()
.Where(i => i.ClientId == clientId)
.Select(i => i.ReportJson)
.FirstOrDefaultAsync(cancellationToken);
return inventoryCache.Store(clientId, meta.UpdatedUtc, json);
}
/// <summary>Cached inventory for every device, fetching only changed snapshots.</summary>
private async Task<Dictionary<string, InventoryReport?>> GetAllInventoryAsync(CancellationToken cancellationToken)
{
var metadata = await db.DeviceInventory.AsNoTracking()
.Select(i => new { i.ClientId, i.UpdatedUtc })
.ToListAsync(cancellationToken);
var result = new Dictionary<string, InventoryReport?>(metadata.Count);
var misses = new List<string>();
foreach (var row in metadata)
{
if (inventoryCache.TryGet(row.ClientId, row.UpdatedUtc, out var cached))
{
result[row.ClientId] = cached;
}
else
{
misses.Add(row.ClientId);
}
}
if (misses.Count > 0)
{
var updatedByClient = metadata.ToDictionary(m => m.ClientId, m => m.UpdatedUtc);
var rows = await db.DeviceInventory.AsNoTracking()
.Where(i => misses.Contains(i.ClientId))
.Select(i => new { i.ClientId, i.ReportJson })
.ToListAsync(cancellationToken);
foreach (var row in rows)
{
result[row.ClientId] = inventoryCache.Store(
row.ClientId, updatedByClient[row.ClientId], row.ReportJson);
}
}
inventoryCache.Prune(metadata.Select(m => m.ClientId).ToHashSet(StringComparer.Ordinal));
return result;
}
public static IReadOnlyList<string> ParseTags(string? tagsJson)
@@ -86,17 +142,13 @@ public sealed class DeviceGroupService(AppDbContext db)
public async Task<IReadOnlyList<string>> EvaluateAsync(GroupRuleSet rules, CancellationToken cancellationToken)
{
var now = DateTimeOffset.UtcNow;
var rows = await db.Devices.AsNoTracking()
.GroupJoin(
db.DeviceInventory.AsNoTracking(),
d => d.ClientId,
i => i.ClientId,
(d, inv) => new { Device = d, Inventory = inv.Select(x => x.ReportJson).FirstOrDefault() })
.ToListAsync(cancellationToken);
var devices = await db.Devices.AsNoTracking().ToListAsync(cancellationToken);
var inventory = await GetAllInventoryAsync(cancellationToken);
return rows
.Where(r => RuleEvaluator.Matches(rules, BuildFields(r.Device, r.Inventory, now)))
.Select(r => r.Device.ClientId)
return devices
.Where(d => RuleEvaluator.Matches(
rules, BuildFields(d, inventory.GetValueOrDefault(d.ClientId), now)))
.Select(d => d.ClientId)
.ToList();
}
@@ -116,17 +168,14 @@ public sealed class DeviceGroupService(AppDbContext db)
return [];
}
var inventoryJson = await db.DeviceInventory.AsNoTracking()
.Where(i => i.ClientId == clientId)
.Select(i => i.ReportJson)
.FirstOrDefaultAsync(cancellationToken);
var inventory = await GetInventoryAsync(clientId, cancellationToken);
var staticGroupIds = await db.DeviceGroupMembers.AsNoTracking()
.Where(m => m.ClientId == clientId)
.Select(m => m.GroupId)
.ToListAsync(cancellationToken);
var fields = BuildFields(device, inventoryJson, DateTimeOffset.UtcNow);
var fields = BuildFields(device, inventory, DateTimeOffset.UtcNow);
var result = new List<DeviceGroupRefDto>();
foreach (var group in groups)
@@ -176,11 +225,7 @@ public sealed class DeviceGroupService(AppDbContext db)
return false;
}
var inventoryJson = await db.DeviceInventory.AsNoTracking()
.Where(i => i.ClientId == clientId)
.Select(i => i.ReportJson)
.FirstOrDefaultAsync(cancellationToken);
return RuleEvaluator.Matches(rules, BuildFields(device, inventoryJson, DateTimeOffset.UtcNow));
var inventory = await GetInventoryAsync(clientId, cancellationToken);
return RuleEvaluator.Matches(rules, BuildFields(device, inventory, DateTimeOffset.UtcNow));
}
}
@@ -0,0 +1,65 @@
using System.Collections.Concurrent;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
namespace Backend.Groups;
/// <summary>
/// Parsed inventory snapshots keyed by device, invalidated by the snapshot's
/// UpdatedUtc. Dynamic-group evaluation runs against every device on every
/// use (member listings, fan-out, schedule fires, trigger scoping), and
/// deserializing thousands of inventory blobs each time is the hot cost —
/// cached, an evaluation only parses snapshots that actually changed and only
/// fetches JSON for those from the database.
/// </summary>
public sealed class InventoryReportCache
{
private sealed record Entry(DateTimeOffset UpdatedUtc, InventoryReport? Report);
private readonly ConcurrentDictionary<string, Entry> entries = new();
/// <summary>The cached report, when the caller's UpdatedUtc still matches.</summary>
public bool TryGet(string clientId, DateTimeOffset updatedUtc, out InventoryReport? report)
{
if (entries.TryGetValue(clientId, out var entry) && entry.UpdatedUtc == updatedUtc)
{
report = entry.Report;
return true;
}
report = null;
return false;
}
/// <summary>Parses and stores a fresh snapshot (corrupt JSON caches as null).</summary>
public InventoryReport? Store(string clientId, DateTimeOffset updatedUtc, string? reportJson)
{
InventoryReport? report = null;
if (!string.IsNullOrWhiteSpace(reportJson))
{
try
{
report = JsonDefaults.Deserialize<InventoryReport>(reportJson);
}
catch (Exception)
{
// Corrupt snapshot: evaluate on identity fields only.
}
}
entries[clientId] = new Entry(updatedUtc, report);
return report;
}
/// <summary>Drops entries for devices that no longer exist.</summary>
public void Prune(IReadOnlySet<string> liveClientIds)
{
foreach (var key in entries.Keys)
{
if (!liveClientIds.Contains(key))
{
entries.TryRemove(key, out _);
}
}
}
}
+5 -3
View File
@@ -97,14 +97,16 @@ public static class JobEndpoints
var actor = context.User.Identity?.Name;
// Secrets and the prelude are prepared once, before any job rows exist:
// a vault failure surfaces immediately instead of minting failed jobs.
// Secrets, file presigns and the prelude are prepared once, before any
// job rows exist: a vault or S3 failure surfaces immediately instead
// of minting failed jobs.
PreparedScript prepared;
try
{
prepared = await runner.PrepareAsync(script, cancellationToken);
}
catch (Backend.Secrets.SecretResolutionException ex)
catch (Exception ex) when (
ex is Backend.Secrets.SecretResolutionException or Backend.Files.FileResolutionException)
{
return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway);
}
+82 -7
View File
@@ -11,14 +11,15 @@ namespace Backend.Jobs;
/// <summary>
/// A script made ready to dispatch: function-module prelude composed, typed
/// parameters deserialized and secret bindings resolved (once — a group
/// fan-out reuses the same values for every member).
/// parameters deserialized, secret bindings resolved and file bindings
/// presigned (once — a group fan-out reuses the same values for every member).
/// </summary>
public sealed record PreparedScript(
ScriptEntity Script,
string? Prelude,
IReadOnlyList<ScriptParameter>? Parameters,
IReadOnlyList<ScriptSecret>? Secrets);
IReadOnlyList<ScriptSecret>? Secrets,
IReadOnlyList<ScriptFileDelivery>? Files = null);
/// <summary>
/// The one path from "run this script on this device" to a dispatched job.
@@ -30,9 +31,14 @@ public sealed class JobRunner(
AppDbContext db,
CommandDispatcher dispatcher,
BrowserEventBroadcaster broadcaster,
SecretsProviderService secretsService)
SecretsProviderService secretsService,
Backend.Files.S3PresignService s3)
{
/// <summary>Composes the prelude and resolves secrets. Throws <see cref="SecretResolutionException"/>.</summary>
/// <summary>
/// Composes the prelude, resolves secrets and presigns file bindings.
/// Throws <see cref="SecretResolutionException"/> /
/// <see cref="Backend.Files.FileResolutionException"/>.
/// </summary>
public async Task<PreparedScript> PrepareAsync(ScriptEntity script, CancellationToken cancellationToken)
{
var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson);
@@ -46,7 +52,75 @@ public sealed class JobRunner(
secrets = await secretsService.ResolveAsync(bindings, cancellationToken);
}
return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets);
var files = await ResolveFilesAsync(
Backend.Scripts.ScriptEndpoints.DeserializeFileBindings(script.FileBindingsJson), cancellationToken);
return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets, files);
}
/// <summary>
/// Presigns every file binding: single objects become one item, directory
/// bindings list the prefix recursively and presign each object. Failures
/// throw unless the binding continues on failure, in which case the entry
/// ships with the error so the agent can log it and still run the script.
/// </summary>
private async Task<IReadOnlyList<ScriptFileDelivery>?> ResolveFilesAsync(
IReadOnlyList<ScriptFileBinding> bindings, CancellationToken cancellationToken)
{
if (bindings.Count == 0)
{
return null;
}
var deliveries = new List<ScriptFileDelivery>(bindings.Count);
foreach (var binding in bindings)
{
try
{
if (binding.Directory)
{
var prefix = binding.ObjectKey.TrimEnd('/') + "/";
var keys = await s3.ListKeysAsync(prefix, cancellationToken);
if (keys.Count == 0)
{
throw new Backend.Files.FileResolutionException(
$"File binding “{binding.Name}”: no objects under “{prefix}”.");
}
var items = new List<ScriptFileItem>(keys.Count);
foreach (var (key, size) in keys)
{
var (url, _) = await s3.PresignGetAsync(key, cancellationToken);
items.Add(new ScriptFileItem(key[prefix.Length..], url, size));
}
deliveries.Add(new ScriptFileDelivery(
binding.Name, binding.DestinationPath, true, binding.ContinueOnFailure, items));
}
else
{
var (url, _) = await s3.PresignGetAsync(binding.ObjectKey, cancellationToken);
deliveries.Add(new ScriptFileDelivery(
binding.Name, binding.DestinationPath, false, binding.ContinueOnFailure,
[new ScriptFileItem(string.Empty, url)]));
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
var message = ex is Backend.Files.FileResolutionException
? ex.Message
: $"File binding “{binding.Name}”: {ex.Message}";
if (!binding.ContinueOnFailure)
{
throw new Backend.Files.FileResolutionException(message, ex);
}
deliveries.Add(new ScriptFileDelivery(
binding.Name, binding.DestinationPath, binding.Directory, true, [], message));
}
}
return deliveries;
}
public async Task<JobEntity> CreateJobAsync(
@@ -86,7 +160,8 @@ public sealed class JobRunner(
Arguments: arguments,
SecretsVariableName: script.SecretsVariableName,
Secrets: prepared.Secrets,
Engine: Backend.Scripts.ScriptEndpoints.ParseEngine(script.Language)),
Engine: Backend.Scripts.ScriptEndpoints.ParseEngine(script.Language),
Files: prepared.Files),
cancellationToken);
if (dispatched)
+2 -1
View File
@@ -143,7 +143,8 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<Sc
preparedScript = await runner.PrepareAsync(script, cancellationToken);
prepared[script.Id] = preparedScript;
}
catch (SecretResolutionException ex)
catch (Exception ex) when (
ex is SecretResolutionException or Backend.Files.FileResolutionException)
{
assignment.LastResult = ex.Message;
logger.LogWarning("Schedule {Name}: {Message}", schedule.Name, ex.Message);
+24 -4
View File
@@ -38,7 +38,7 @@ if (args.Length > 0 && args[0] == "auth-reset")
// CLI mode: standalone single-binary server management.
if (args.Length > 0 && args[0] == "setup")
{
return Backend.Standalone.ServerCli.RunSetup();
return await Backend.Standalone.ServerCli.RunSetupAsync(args[1..]);
}
if (args.Length > 0 && args[0] == "service")
@@ -46,7 +46,15 @@ if (args.Length > 0 && args[0] == "service")
return Backend.Standalone.ServerCli.RunService(args[1..]);
}
var builder = WebApplication.CreateBuilder(args);
// Standalone bundle: when setup generated an appsettings.json next to the
// binary, anchor the content root there so the server behaves identically
// however it is launched (console from any directory, SCM, systemd).
var standaloneSettings = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ContentRootPath = File.Exists(standaloneSettings) ? AppContext.BaseDirectory : null,
});
// Standalone mode: run cleanly as a Windows service or under systemd
// (both are no-ops when launched normally or inside a container).
@@ -83,6 +91,7 @@ builder.Services.AddApplicationDatabase(databaseOptions);
builder.Services.AddScoped<AuditService>();
builder.Services.AddSingleton(DeviceLifecycleOptions.FromConfiguration(builder.Configuration));
builder.Services.AddSingleton<Backend.Groups.InventoryReportCache>();
builder.Services.AddScoped<DeviceGroupService>();
builder.Services.AddScoped<ScriptTriggerService>();
@@ -127,7 +136,12 @@ builder.Services.AddSingleton<Backend.Secrets.ISecretsProviderDriver, Backend.Se
builder.Services.AddScoped<Backend.Secrets.SecretsProviderService>();
builder.Services.AddSingleton<ShellBridge>();
builder.Services.AddHostedService<MessagingWorkers>();
builder.Services.AddHostedService<ScheduleWorker>();
// SCHEDULE_WORKER=0 keeps the background sweep out of test hosts, where it
// races the tests' deterministic manual sweeps.
if (builder.Configuration["SCHEDULE_WORKER"] != "0")
{
builder.Services.AddHostedService<ScheduleWorker>();
}
builder.Services.AddHostedService(sp => sp.GetRequiredService<ShellBridge>());
// ── Rate limiting ────────────────────────────────────────────────────────
@@ -170,10 +184,16 @@ using (var scope = app.Services.CreateScope())
// System roles must exist before any user is created or resolved.
await scope.ServiceProvider.GetRequiredService<RoleService>().EnsureSystemRolesAsync(CancellationToken.None);
// First-boot initial admin from environment secrets (never a default password).
// First-boot defaults: platform dynamic groups + starter schedules.
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
// First-boot initial admin from environment secrets. INITIAL_ADMIN_MUST_CHANGE
// (set by standalone `setup` when the admin/admin default was used) forces a
// password reset on the first sign-in.
await scope.ServiceProvider.GetRequiredService<UserService>().EnsureInitialAdminAsync(
builder.Configuration["INITIAL_ADMIN_USERNAME"],
builder.Configuration["INITIAL_ADMIN_PASSWORD"],
builder.Configuration["INITIAL_ADMIN_MUST_CHANGE"] == "1",
CancellationToken.None);
if (app.Environment.IsDevelopment() && !db.Scripts.Any())
+65 -1
View File
@@ -48,6 +48,11 @@ public static class ScriptEndpoints
return secretsProblem;
}
if (ValidateFiles(request) is { } filesProblem)
{
return filesProblem;
}
var now = DateTimeOffset.UtcNow;
var actor = context.User.Identity?.Name;
var script = new ScriptEntity
@@ -61,6 +66,7 @@ public static class ScriptEndpoints
FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds),
SecretBindingsJson = SerializeSecretBindings(request.SecretBindings),
SecretsVariableName = NormalizeVariableName(request.SecretsVariableName),
FileBindingsJson = SerializeFileBindings(request.FileBindings),
CreatedUtc = now,
UpdatedUtc = now,
CreatedBy = actor,
@@ -92,6 +98,11 @@ public static class ScriptEndpoints
return secretsProblem;
}
if (ValidateFiles(request) is { } filesProblem)
{
return filesProblem;
}
script.Name = request.Name.Trim();
script.Description = request.Description;
script.Language = request.Engine.ToString();
@@ -100,6 +111,7 @@ public static class ScriptEndpoints
script.FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds);
script.SecretBindingsJson = SerializeSecretBindings(request.SecretBindings);
script.SecretsVariableName = NormalizeVariableName(request.SecretsVariableName);
script.FileBindingsJson = SerializeFileBindings(request.FileBindings);
script.UpdatedUtc = DateTimeOffset.UtcNow;
script.UpdatedBy = context.User.Identity?.Name;
await db.SaveChangesAsync(cancellationToken);
@@ -131,7 +143,8 @@ public static class ScriptEndpoints
DeserializeModuleIds(script.FunctionModuleIdsJson),
script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy,
DeserializeSecretBindings(script.SecretBindingsJson),
script.SecretsVariableName);
script.SecretsVariableName,
DeserializeFileBindings(script.FileBindingsJson));
/// <summary>The injected dictionary must bind to a legal PowerShell variable name.</summary>
private static IResult? ValidateSecrets(SaveScriptRequest request)
@@ -185,6 +198,57 @@ public static class ScriptEndpoints
}
}
/// <summary>Dictionary keys must be legal variable-ish names; every entry needs a key and destination.</summary>
private static IResult? ValidateFiles(SaveScriptRequest request)
{
foreach (var binding in request.FileBindings ?? [])
{
if (string.IsNullOrWhiteSpace(binding.Name)
|| !System.Text.RegularExpressions.Regex.IsMatch(binding.Name.Trim(), "^[A-Za-z_][A-Za-z0-9_]*$"))
{
return Results.BadRequest(new
{
error = "Every file binding needs a name usable as $Files.<Name> (letters, digits, underscore).",
});
}
if (string.IsNullOrWhiteSpace(binding.ObjectKey) || string.IsNullOrWhiteSpace(binding.DestinationPath))
{
return Results.BadRequest(new
{
error = $"File binding “{binding.Name}” needs an S3 key and a destination path.",
});
}
// A directory delivery unpacks a tree INTO the destination — a
// leaf file path (extension on the last segment) is a mistake.
if (binding.Directory && LooksLikeFilePath(binding.DestinationPath))
{
return Results.BadRequest(new
{
error = $"File binding “{binding.Name}” is a directory delivery — the destination "
+ "must be a directory, not a file path.",
});
}
}
return null;
}
internal static bool LooksLikeFilePath(string destinationPath)
{
var leaf = Path.GetFileName(destinationPath.TrimEnd('/', '\\'));
return System.Text.RegularExpressions.Regex.IsMatch(leaf, @"\.[A-Za-z][A-Za-z0-9]{0,6}$");
}
internal static string? SerializeFileBindings(IReadOnlyList<ScriptFileBinding>? bindings)
=> bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings);
internal static IReadOnlyList<ScriptFileBinding> DeserializeFileBindings(string? json)
=> string.IsNullOrWhiteSpace(json)
? []
: JsonDefaults.Deserialize<List<ScriptFileBinding>>(json) ?? [];
internal static string? SerializeSecretBindings(IReadOnlyList<SecretBinding>? bindings)
=> bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings);
+149 -12
View File
@@ -1,4 +1,7 @@
using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Runtime.InteropServices;
using Backend.Nats;
namespace Backend.Standalone;
@@ -6,7 +9,9 @@ namespace Backend.Standalone;
/// <summary>
/// Standalone-server commands for the combined single-binary deployment:
///
/// setup — generate NATS keys + sidecar config + appsettings
/// setup [--admin-user U] [--admin-password P]
/// — generate NATS keys + sidecar config + appsettings,
/// downloading nats-server for this platform if absent
/// service install — register as a Windows service / systemd unit
/// service uninstall — stop and remove the service
///
@@ -18,8 +23,32 @@ public static class ServerCli
public const string WindowsServiceName = "ExecuteRServer";
public const string SystemdUnitName = "executer-server";
public static int RunSetup()
private const string NatsVersion = "2.14.4";
public static async Task<int> RunSetupAsync(string[] args)
{
// Bare `setup` fully configures the server: admin/admin unless the
// flags override — and the defaulted password forces a reset prompt
// on the first sign-in.
var adminUser = "admin";
var adminPassword = "admin";
var passwordDefaulted = true;
for (var i = 0; i < args.Length - 1; i++)
{
switch (args[i])
{
case "--admin-user":
adminUser = args[++i];
break;
case "--admin-password":
adminPassword = args[++i];
// The MSI passes the flag even when the wizard default was
// kept: a literal "admin" password always forces the reset.
passwordDefaulted = adminPassword == "admin";
break;
}
}
var baseDir = AppContext.BaseDirectory;
var natsDir = Path.Combine(baseDir, "nats");
var secretsDir = Path.Combine(baseDir, "secrets", "nats");
@@ -27,6 +56,14 @@ public static class ServerCli
Directory.CreateDirectory(natsDir);
Directory.CreateDirectory(dataDir);
// The sidecar binary: packaged bundles ship it; a bare binary (MSI or
// direct download) fetches it here so setup works the same everywhere.
var ensured = await EnsureNatsServerAsync(natsDir);
if (ensured != 0)
{
return ensured;
}
// NATS operator/account keys + resolver preload (idempotent).
if (!File.Exists(Path.Combine(secretsDir, "resolver.conf")))
{
@@ -83,28 +120,125 @@ public static class ServerCli
"DATABASE_PATH": "{{Path.Combine(dataDir, "app.db").Replace('\\', '/')}}",
"DATAPROTECTION_PATH": "{{Path.Combine(dataDir, "keys").Replace('\\', '/')}}",
"LOG_PATH": "{{Path.Combine(dataDir, "logs").Replace('\\', '/')}}",
"AGENT_PACKAGE_PATH": "{{Path.Combine(baseDir, "agent-package").Replace('\\', '/')}}",
"NATS_URL": "nats://127.0.0.1:4222",
"NATS_SIDECAR": "1",
"NATS_WS_PROXY": "ws://127.0.0.1:9222",
"NATS_ACCOUNT_SIGNING_SEED": "{{signingSeed}}",
"NATS_ACCOUNT_PUBLIC_KEY": "{{accountPublic}}",
"INITIAL_ADMIN_USERNAME": "admin",
"INITIAL_ADMIN_PASSWORD": ""
"INITIAL_ADMIN_USERNAME": "{{adminUser}}",
"INITIAL_ADMIN_PASSWORD": "{{adminPassword}}",
"INITIAL_ADMIN_MUST_CHANGE": "{{(passwordDefaulted ? "1" : "0")}}"
}
""");
Console.WriteLine($"Wrote {appsettings}");
Console.WriteLine();
Console.WriteLine("Set INITIAL_ADMIN_PASSWORD in appsettings.json before first start.");
}
Console.WriteLine();
Console.WriteLine("Setup complete. Next:");
Console.WriteLine(" 1. Set INITIAL_ADMIN_PASSWORD in appsettings.json (first start only).");
Console.WriteLine(" 2. Run the binary directly, or `service install` to run in the background.");
Console.WriteLine(" 3. Put a TLS-terminating proxy in front for production use.");
Console.WriteLine("Setup complete.");
Console.WriteLine(passwordDefaulted
? $" - First sign-in: {adminUser} / admin — a new password is required immediately."
: $" - First sign-in: {adminUser} / <your password>.");
Console.WriteLine(" - Run the binary directly, or `service install` to run in the background.");
Console.WriteLine(" - Put a TLS-terminating proxy in front for production use.");
return 0;
}
/// <summary>
/// Downloads and unpacks nats-server for the current OS/architecture when
/// it is not already next to the binary. Idempotent; packaged bundles ship
/// the sidecar so this is normally a no-op.
/// </summary>
private static async Task<int> EnsureNatsServerAsync(string natsDir)
{
var binaryName = OperatingSystem.IsWindows() ? "nats-server.exe" : "nats-server";
var target = Path.Combine(natsDir, binaryName);
if (File.Exists(target))
{
return 0;
}
var os = OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "darwin" : "linux";
var arch = RuntimeInformation.OSArchitecture switch
{
Architecture.Arm64 => "arm64",
Architecture.X64 => "amd64",
var other => other.ToString().ToLowerInvariant(),
};
var extension = OperatingSystem.IsWindows() ? "zip" : "tar.gz";
var archive = $"nats-server-v{NatsVersion}-{os}-{arch}.{extension}";
var url = $"https://github.com/nats-io/nats-server/releases/download/v{NatsVersion}/{archive}";
Console.WriteLine($"Downloading {archive} ...");
var staging = Path.Combine(natsDir, ".download");
try
{
using var http = new HttpClient();
await using var download = await http.GetStreamAsync(url);
if (Directory.Exists(staging))
{
Directory.Delete(staging, recursive: true);
}
Directory.CreateDirectory(staging);
if (extension == "zip")
{
var zipPath = Path.Combine(staging, archive);
await using (var file = File.Create(zipPath))
{
await download.CopyToAsync(file);
}
ZipFile.ExtractToDirectory(zipPath, staging);
}
else
{
await using var gzip = new GZipStream(download, CompressionMode.Decompress);
await TarFile.ExtractToDirectoryAsync(gzip, staging, overwriteFiles: true);
}
var extracted = Directory.EnumerateFiles(staging, binaryName, SearchOption.AllDirectories).FirstOrDefault();
if (extracted is null)
{
Console.Error.WriteLine($"{binaryName} was not found inside {archive}.");
return 1;
}
File.Move(extracted, target, overwrite: true);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(target,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute
| UnixFileMode.GroupRead | UnixFileMode.GroupExecute
| UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
}
Console.WriteLine($"nats-server v{NatsVersion} installed to {target}");
return 0;
}
catch (Exception ex) when (ex is HttpRequestException or IOException or InvalidDataException)
{
Console.Error.WriteLine($"Could not download nats-server: {ex.Message}");
Console.Error.WriteLine($"Place {binaryName} in {natsDir} manually and re-run setup.");
return 1;
}
finally
{
try
{
if (Directory.Exists(staging))
{
Directory.Delete(staging, recursive: true);
}
}
catch (IOException)
{
// Best effort.
}
}
}
public static int RunService(string[] args)
{
if (args.Length == 0)
@@ -126,10 +260,13 @@ public static class ServerCli
private static int InstallWindows(string exe)
{
Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\"");
// Idempotent: create may fail when the service exists (repair or MSI
// upgrade); config then points it at the current binary either way.
Run("sc.exe", $"create {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto DisplayName= \"ExecuteR Server\"", ignoreErrors: true);
Run("sc.exe", $"config {WindowsServiceName} binPath= \"\\\"{exe}\\\"\" start= delayed-auto");
Run("sc.exe", $"description {WindowsServiceName} \"ExecuteR control plane (UI, API, messaging).\"");
Run("sc.exe", $"failure {WindowsServiceName} reset= 86400 actions= restart/30000/restart/30000/restart/30000");
Run("sc.exe", $"start {WindowsServiceName}");
Run("sc.exe", $"start {WindowsServiceName}", ignoreErrors: true);
Console.WriteLine($"Service {WindowsServiceName} installed and started.");
return 0;
}
+159
View File
@@ -0,0 +1,159 @@
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs"
xmlns:util="http://wixtoolset.org/schemas/v4/wxs/util"
xmlns:ui="http://wixtoolset.org/schemas/v4/wxs/ui">
<!--
ExecuteR Server MSI: the standalone combined server (UI + API + messaging
relay + NATS sidecar) as a Windows service.
Public properties (uppercase): ADMINUSERNAME ADMINPASSWORD — the initial
admin created on first start (defaults Admin/Admin; interactive installs
edit them on the account page). After the files land, the installer runs
the binary's own cross-platform init:
ExecuteR-Server.exe setup (with the admin user/password flags)
ExecuteR-Server.exe service install
setup is idempotent (keys/config/appsettings are only generated when
absent), so upgrades never overwrite an existing configuration and the
admin properties only take effect on the very first install.
-->
<Package Name="ExecuteR Server"
Manufacturer="ExecuteR"
Version="$(MsiProductVersion)"
UpgradeCode="b4e6a7c9-52d1-4f3e-8a20-9c15d7b64e88"
Scope="perMachine"
Compressed="yes">
<SummaryInformation Description="ExecuteR Server $(UnifiedVersion)" />
<MajorUpgrade AllowSameVersionUpgrades="yes"
Schedule="afterInstallInitialize"
DowngradeErrorMessage="A newer version of ExecuteR Server is already installed." />
<MediaTemplate EmbedCab="yes" />
<Property Id="UNIFIEDVERSION" Value="$(UnifiedVersion)" />
<Property Id="ARPCOMMENTS" Value="ExecuteR Server $(UnifiedVersion)" />
<Icon Id="AppIcon" SourceFile="$(AppIconPath)" />
<Property Id="ARPPRODUCTICON" Value="AppIcon" />
<Property Id="ADMINUSERNAME" Value="admin" />
<Property Id="ADMINPASSWORD" Value="admin" Hidden="yes" />
<StandardDirectory Id="ProgramFiles64Folder">
<Directory Id="INSTALLFOLDER" Name="ExecuteR Server" />
</StandardDirectory>
<!-- The whole packaged bundle: ExecuteR-Server.exe, wwwroot, the NATS
sidecar and the agent installers for URL install delivery. -->
<ComponentGroup Id="ServerFiles" Directory="INSTALLFOLDER">
<Files Include="$(var.ServerPublishDir)\**" />
</ComponentGroup>
<Feature Id="Main" Title="ExecuteR Server" Level="1">
<ComponentGroupRef Id="ServerFiles" />
</Feature>
<!-- First-boot init through the binary's own cross-platform CLI. -->
<SetProperty Id="RunServerSetup"
Value="&quot;[INSTALLFOLDER]ExecuteR-Server.exe&quot; setup --admin-user &quot;[ADMINUSERNAME]&quot; --admin-password &quot;[ADMINPASSWORD]&quot;"
Sequence="execute"
Before="RunServerSetup" />
<CustomAction Id="RunServerSetup"
BinaryRef="Wix4UtilCA_X64"
DllEntry="WixQuietExec64"
Execute="deferred"
Impersonate="no"
Return="check" />
<SetProperty Id="InstallServerService"
Value="&quot;[INSTALLFOLDER]ExecuteR-Server.exe&quot; service install"
Sequence="execute"
Before="InstallServerService" />
<CustomAction Id="InstallServerService"
BinaryRef="Wix4UtilCA_X64"
DllEntry="WixQuietExec64"
Execute="deferred"
Impersonate="no"
Return="check" />
<SetProperty Id="UninstallServerService"
Value="&quot;[INSTALLFOLDER]ExecuteR-Server.exe&quot; service uninstall"
Sequence="execute"
Before="UninstallServerService" />
<CustomAction Id="UninstallServerService"
BinaryRef="Wix4UtilCA_X64"
DllEntry="WixQuietExec64"
Execute="deferred"
Impersonate="no"
Return="ignore" />
<!--
Interactive UI: Welcome → Administrator account → Verify → Progress.
The account page edits the same ADMINUSERNAME / ADMINPASSWORD public
properties the command line sets; silent installs pass them as
properties and never show UI.
-->
<ui:WixUI Id="WixUI_InstallDir" InstallDirectory="INSTALLFOLDER" />
<UI>
<Dialog Id="ServerConfigDlg" Width="370" Height="270" Title="ExecuteR Server Setup">
<Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44"
TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" />
<Control Id="Title" Type="Text" X="15" Y="6" Width="330" Height="15"
Transparent="yes" NoPrefix="yes"
Text="{\WixUI_Font_Title}Administrator account" />
<Control Id="Description" Type="Text" X="25" Y="23" Width="330" Height="15"
Transparent="yes" NoPrefix="yes"
Text="The initial sign-in created the first time the server starts." />
<Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" />
<Control Id="UserLabel" Type="Text" X="20" Y="60" Width="330" Height="12"
NoPrefix="yes" Text="Administrator &amp;username:" />
<Control Id="UserEdit" Type="Edit" X="20" Y="74" Width="330" Height="17"
Property="ADMINUSERNAME" />
<Control Id="PasswordLabel" Type="Text" X="20" Y="100" Width="330" Height="12"
NoPrefix="yes" Text="Administrator &amp;password:" />
<Control Id="PasswordEdit" Type="Edit" X="20" Y="114" Width="330" Height="17"
Property="ADMINPASSWORD" Password="yes" />
<Control Id="Note" Type="Text" X="20" Y="142" Width="330" Height="48" NoPrefix="yes"
Text="Defaults to admin / admin — change the password after the first sign-in. This account is only created on the very first install; upgrades keep the existing configuration. Silent installs set the same values with ADMINUSERNAME=... ADMINPASSWORD=... properties." />
<Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" />
<Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17"
Text="!(loc.WixUIBack)" />
<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17"
Default="yes" Text="!(loc.WixUINext)" />
<Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17"
Cancel="yes" Text="!(loc.WixUICancel)">
<Publish Event="SpawnDialog" Value="CancelDlg" />
</Control>
</Dialog>
<!-- Splice the page in: overrides outrank the stock set's publishes. -->
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="ServerConfigDlg"
Order="99" Condition="NOT Installed" />
<Publish Dialog="ServerConfigDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" />
<Publish Dialog="ServerConfigDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" />
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="ServerConfigDlg"
Order="99" Condition="NOT Installed" />
</UI>
<InstallExecuteSequence>
<Custom Action="RunServerSetup"
After="InstallFiles"
Condition="NOT (REMOVE=&quot;ALL&quot;)" />
<Custom Action="InstallServerService"
After="RunServerSetup"
Condition="NOT (REMOVE=&quot;ALL&quot;)" />
<Custom Action="UninstallServerService"
After="InstallInitialize"
Condition="REMOVE=&quot;ALL&quot; AND NOT UPGRADINGPRODUCTCODE" />
</InstallExecuteSequence>
</Package>
</Wix>
@@ -0,0 +1,24 @@
<!-- WiX v5 pinned deliberately: v6+ requires Open Source Maintenance Fee
EULA acceptance, which is an organizational licensing decision. -->
<Project Sdk="WixToolset.Sdk/5.0.2">
<PropertyGroup>
<OutputName>Server</OutputName>
<InstallerPlatform>x64</InstallerPlatform>
<!-- ICE61: AllowSameVersionUpgrades="yes". ICE60: the harvested bundle
carries versioned-but-language-less binaries (nats-server is Go). -->
<SuppressIces>ICE61;ICE60</SuppressIces>
<MsiProductVersion Condition="'$(MsiProductVersion)' == ''">0.0.0</MsiProductVersion>
<!-- Directory containing the packaged standalone server (exe + wwwroot +
nats + agent-package), produced by scripts/Package-Server.ps1. -->
<ServerPublishDir Condition="'$(ServerPublishDir)' == ''">$(MSBuildThisFileDirectory)..\..\artifacts\server\current\win-x64</ServerPublishDir>
<AppIconPath Condition="'$(AppIconPath)' == ''">$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico</AppIconPath>
<DefineConstants>$(DefineConstants);UnifiedVersion=$(UnifiedVersion);MsiProductVersion=$(MsiProductVersion);ServerPublishDir=$(ServerPublishDir);AppIconPath=$(AppIconPath)</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="WixToolset.Util.wixext" />
<PackageReference Include="WixToolset.UI.wixext" />
</ItemGroup>
</Project>
+1 -1
View File
@@ -12,7 +12,7 @@
<MsiProductVersion Condition="'$(MsiProductVersion)' == ''">0.0.0</MsiProductVersion>
<!-- Directory containing the published self-contained Agent.exe. -->
<AgentPublishDir Condition="'$(AgentPublishDir)' == ''">$(MSBuildThisFileDirectory)..\Agent\bin\Release\net10.0-windows\win-x64\publish</AgentPublishDir>
<AppIconPath Condition="'$(AppIconPath)' == '' AND Exists('$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico')">$(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico</AppIconPath>
<AppIconPath Condition="'$(AppIconPath)' == ''">$(MSBuildThisFileDirectory)..\..\assets\icons\app.ico</AppIconPath>
<DefineConstants>$(DefineConstants);UnifiedVersion=$(UnifiedVersion);MsiProductVersion=$(MsiProductVersion);AgentPublishDir=$(AgentPublishDir)</DefineConstants>
<DefineConstants Condition="'$(AppIconPath)' != ''">$(DefineConstants);AppIconPath=$(AppIconPath)</DefineConstants>
</PropertyGroup>
+1
View File
@@ -11,6 +11,7 @@ public static class ApiRoutes
public const string Ready = "/api/ready";
public const string AuthLogin = "/api/auth/login";
public const string AuthChangePassword = "/api/auth/change-password";
public const string AuthLogout = "/api/auth/logout";
public const string AuthSession = "/api/auth/session";
public const string AuthConfig = "/api/auth/config";
+10 -1
View File
@@ -5,6 +5,13 @@ namespace Shared.Contracts.Api;
/// <summary>POST /api/auth/login request body.</summary>
public sealed record LoginRequest(string Username, string Password);
/// <summary>
/// POST /api/auth/change-password request body. Pre-session: the current
/// password authenticates the request, so this also completes the forced
/// first-sign-in reset of the defaulted admin account.
/// </summary>
public sealed record ChangePasswordRequest(string Username, string CurrentPassword, string NewPassword);
/// <summary>
/// GET /api/auth/config — anonymous. Tells the sign-in page what to render;
/// contains nothing sensitive.
@@ -52,7 +59,9 @@ public sealed record SessionResponse(
UserRole? Role,
string? AuthProvider,
string? RoleName = null,
IReadOnlyList<string>? Permissions = null);
IReadOnlyList<string>? Permissions = null,
// Credentials were valid but a new password must be set before a session is issued.
bool MustChangePassword = false);
/// <summary>
/// POST /api/messaging/credential request body. Pass the previously issued
+4 -2
View File
@@ -93,7 +93,8 @@ public sealed record ScriptDto(
string? CreatedBy,
string? UpdatedBy,
IReadOnlyList<SecretBinding>? SecretBindings = null,
string? SecretsVariableName = null);
string? SecretsVariableName = null,
IReadOnlyList<ScriptFileBinding>? FileBindings = null);
/// <summary>POST/PUT /api/scripts request body.</summary>
public sealed record SaveScriptRequest(
@@ -104,7 +105,8 @@ public sealed record SaveScriptRequest(
IReadOnlyList<Guid>? FunctionModuleIds = null,
IReadOnlyList<SecretBinding>? SecretBindings = null,
string? SecretsVariableName = null,
ScriptEngine Engine = ScriptEngine.PowerShell);
ScriptEngine Engine = ScriptEngine.PowerShell,
IReadOnlyList<ScriptFileBinding>? FileBindings = null);
/// <summary>
/// Configured secrets provider. <c>Config</c> is driver-specific and sanitized:
+24 -1
View File
@@ -40,6 +40,28 @@ public static class AgentEventKinds
/// </summary>
public sealed record ScriptSecret(string Name, string Value);
/// <summary>One downloadable piece of a script file delivery (presigned).</summary>
public sealed record ScriptFileItem(
// Path relative to the delivery's destination; empty for a single file
// (the destination IS the file path).
string RelativePath,
string Url,
long? SizeBytes = null);
/// <summary>
/// One resolved file binding delivered with a job: the agent downloads every
/// item before the script starts, expanding <see cref="DestinationPath"/> on
/// the device. <see cref="Error"/> carries a server-side resolution failure
/// for continue-on-failure entries (the agent logs it and runs the script).
/// </summary>
public sealed record ScriptFileDelivery(
string Name,
string DestinationPath,
bool Directory,
bool ContinueOnFailure,
IReadOnlyList<ScriptFileItem> Items,
string? Error = null);
/// <summary>
/// Durable script execution command on <c>agent.&lt;clientId&gt;.command.script</c>.
/// <see cref="Prelude"/> holds reusable function-module content run first in the
@@ -60,7 +82,8 @@ public sealed record ScriptCommandPayload(
IReadOnlyDictionary<string, System.Text.Json.JsonElement>? Arguments = null,
string? SecretsVariableName = null,
IReadOnlyList<ScriptSecret>? Secrets = null,
Shared.Contracts.Models.ScriptEngine Engine = Shared.Contracts.Models.ScriptEngine.PowerShell);
Shared.Contracts.Models.ScriptEngine Engine = Shared.Contracts.Models.ScriptEngine.PowerShell,
IReadOnlyList<ScriptFileDelivery>? Files = null);
/// <summary>Inventory refresh command on <c>agent.&lt;clientId&gt;.command.inventory</c>.</summary>
public sealed record InventoryCommandPayload(string? Reason);
@@ -32,6 +32,10 @@ public enum RuleOperator
LessOrEqual,
Exists,
NotExists,
/// <summary>Value is an IP address inside any of the listed CIDR ranges (or equals a bare IP).</summary>
InCidr,
NotInCidr,
}
/// <summary>
@@ -93,6 +97,7 @@ public static class GroupFields
new("systemType", "System type", "Hardware"),
new("domain", "Domain / workgroup", "Identity"),
new("partOfDomain", "Domain joined", "Identity"),
new("os.platform", "Platform (windows/linux/macos)", "Operating system"),
new("os.caption", "OS name", "Operating system"),
new("os.version", "OS version", "Operating system"),
new("os.build", "OS build", "Operating system"),
@@ -108,5 +113,6 @@ public static class GroupFields
new("network.ipv4", "IPv4 address", "Network", MultiValue: true),
new("network.mac", "MAC address", "Network", MultiValue: true),
new("network.dns", "DNS server", "Network", MultiValue: true),
new("network.interface", "Interface name", "Network", MultiValue: true),
];
}
@@ -66,4 +66,6 @@ public sealed record InventoryNetworkAdapter(
IReadOnlyList<string> Ipv4Addresses,
IReadOnlyList<string> Ipv6Addresses,
IReadOnlyList<string> Gateways,
IReadOnlyList<string> DnsServers);
IReadOnlyList<string> DnsServers,
// OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix.
string? InterfaceName = null);
@@ -0,0 +1,18 @@
namespace Shared.Contracts.Models;
/// <summary>
/// An S3 object (or prefix) delivered to the device before the script runs.
/// The destination path expands on the device (%VAR%, $env:VAR, $(…)) and the
/// resolved location is handed to the script through a case-insensitive
/// ordered dictionary (<c>$Files.Name</c>) as a FileInfo — or a DirectoryInfo
/// when <see cref="Directory"/> requests a recursive prefix download.
/// </summary>
public sealed record ScriptFileBinding(
string Name,
string ObjectKey,
string DestinationPath,
bool Directory = false,
// A failed delivery logs a warning and lets the script run ($Files.Name
// still points at the intended path; check .Exists). Off = fail the job
// before execution.
bool ContinueOnFailure = false);
@@ -65,7 +65,9 @@ public sealed class DeviceFieldBag
DeviceStatus status,
string? agentVersion,
IEnumerable<string>? tags,
InventoryReport? inventory)
InventoryReport? inventory,
string? fallbackOsCaption = null,
string? fallbackOsVersion = null)
{
var bag = new DeviceFieldBag();
bag.Set("clientId", clientId);
@@ -76,6 +78,12 @@ public sealed class DeviceFieldBag
if (inventory is null)
{
// Enrollment already captured the OS, so platform-based groups
// (and the triggers scoped to them) work before the first
// inventory snapshot lands.
bag.Set("os.platform", DerivePlatform(fallbackOsCaption));
bag.Set("os.caption", fallbackOsCaption);
bag.Set("os.version", fallbackOsVersion);
return bag;
}
@@ -87,6 +95,7 @@ public sealed class DeviceFieldBag
bag.Set("domain", inventory.Identity.DomainOrWorkgroup);
bag.Set("partOfDomain", inventory.Identity.PartOfDomain ? "true" : "false");
bag.Set("os.platform", DerivePlatform(inventory.Os.Caption));
bag.Set("os.caption", inventory.Os.Caption);
bag.Set("os.version", inventory.Os.Version);
bag.Set("os.build", inventory.Os.Build);
@@ -116,7 +125,28 @@ public sealed class DeviceFieldBag
bag.SetMany("network.ipv4", inventory.Network.SelectMany(n => n.Ipv4Addresses));
bag.SetMany("network.mac", inventory.Network.Select(n => n.MacAddress).Where(m => m is not null)!);
bag.SetMany("network.dns", inventory.Network.SelectMany(n => n.DnsServers));
bag.SetMany("network.interface", inventory.Network.Select(n => n.InterfaceName).Where(i => i is not null)!);
return bag;
}
/// <summary>Coarse platform from the OS caption: windows, macos or linux.</summary>
public static string? DerivePlatform(string? osCaption)
{
if (string.IsNullOrWhiteSpace(osCaption))
{
return null;
}
if (osCaption.Contains("windows", StringComparison.OrdinalIgnoreCase))
{
return "windows";
}
return osCaption.Contains("macos", StringComparison.OrdinalIgnoreCase)
|| osCaption.Contains("mac os", StringComparison.OrdinalIgnoreCase)
|| osCaption.Contains("darwin", StringComparison.OrdinalIgnoreCase)
? "macos"
: "linux";
}
}
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net;
using System.Text.RegularExpressions;
using Shared.Contracts.Models;
@@ -15,7 +16,8 @@ public static class RuleEvaluator
/// <summary>Operators that are inherently negative and so must hold for ALL values.</summary>
private static bool IsUniversal(RuleOperator op)
=> op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn or RuleOperator.NotExists;
=> op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn
or RuleOperator.NotExists or RuleOperator.NotInCidr;
public static bool Matches(GroupRuleSet? ruleSet, DeviceFieldBag fields)
{
@@ -129,11 +131,78 @@ public static class RuleEvaluator
case RuleOperator.LessOrEqual:
return CompareNumeric(actual, expected, condition.Operator);
case RuleOperator.InCidr:
return MatchesCidr(actual, expected);
case RuleOperator.NotInCidr:
return !MatchesCidr(actual, expected);
default:
return false;
}
}
/// <summary>
/// True when <paramref name="actual"/> is an IP address inside any of the
/// comma-separated CIDR ranges (bare IPs compare for equality). Uses the
/// BCL <see cref="IPNetwork"/>; IPv4 and IPv6 both work.
/// </summary>
private static bool MatchesCidr(string actual, string expected)
{
if (!IPAddress.TryParse(actual.Trim(), out var address))
{
return false;
}
foreach (var item in SplitList(expected))
{
if (item.Contains('/'))
{
if (TryParseNetwork(item, out var network) && network.Contains(address))
{
return true;
}
}
else if (IPAddress.TryParse(item, out var single) && single.Equals(address))
{
return true;
}
}
return false;
}
/// <summary>
/// Lenient CIDR parse: host bits in the base address are tolerated, so
/// "10.30.9.27/24" means the same network as "10.30.9.0/24" (the strict
/// BCL parser rejects non-zero host bits).
/// </summary>
private static bool TryParseNetwork(string cidr, out IPNetwork network)
{
network = default;
var slash = cidr.IndexOf('/');
if (slash <= 0
|| !IPAddress.TryParse(cidr[..slash].Trim(), out var baseAddress)
|| !int.TryParse(cidr[(slash + 1)..].Trim(), out var prefix))
{
return false;
}
var bytes = baseAddress.GetAddressBytes();
if (prefix < 0 || prefix > bytes.Length * 8)
{
return false;
}
for (var i = 0; i < bytes.Length; i++)
{
var bitsForByte = Math.Clamp(prefix - (i * 8), 0, 8);
bytes[i] &= (byte)(0xFF << (8 - bitsForByte));
}
network = new IPNetwork(new IPAddress(bytes), prefix);
return true;
}
private static bool CompareNumeric(string actual, string expected, RuleOperator op)
{
if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var left)
+7
View File
@@ -30,6 +30,7 @@ import type {
ScriptDto,
ServerInfoDto,
ScriptParameter,
ScriptFileBinding,
ScriptTriggerDto,
ScriptTriggerType,
SecretBinding,
@@ -48,6 +49,7 @@ interface SaveScriptBody {
secretBindings?: SecretBinding[];
secretsVariableName?: string;
engine?: string;
fileBindings?: ScriptFileBinding[];
}
interface SaveSecretsProviderBody {
@@ -134,6 +136,11 @@ export const api = {
method: 'POST',
body: JSON.stringify({ username, password })
}),
changePassword: (username: string, currentPassword: string, newPassword: string) =>
request<SessionResponse>('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ username, currentPassword, newPassword })
}),
logout: () => request<void>('/api/auth/logout', { method: 'POST' }),
// Devices
+22 -1
View File
@@ -58,7 +58,9 @@ export type RuleOperator =
| 'lessThan'
| 'lessOrEqual'
| 'exists'
| 'notExists';
| 'notExists'
| 'inCidr'
| 'notInCidr';
export interface RuleCondition {
field: string;
@@ -246,6 +248,8 @@ export interface InventoryReport {
ipv6Addresses: string[];
gateways: string[];
dnsServers: string[];
/** OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix. */
interfaceName?: string;
}[];
collectedUtc: string;
}
@@ -266,6 +270,20 @@ export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'h
*/
export type ValueExpansion = 'auto' | 'literal';
/**
* An S3 object (or prefix) delivered to the device before the script runs.
* The destination expands on the device (%VAR%, $env:VAR, $(…)) and the
* resolved location reaches the script as $Files.Name — a FileInfo, or a
* DirectoryInfo when directory (recursive) is set.
*/
export interface ScriptFileBinding {
name: string;
objectKey: string;
destinationPath: string;
directory?: boolean;
continueOnFailure?: boolean;
}
export interface ScriptParameter {
name: string;
type: ScriptParameterType;
@@ -377,6 +395,7 @@ export interface ScriptDto {
updatedBy?: string;
secretBindings?: SecretBinding[];
secretsVariableName?: string;
fileBindings?: ScriptFileBinding[];
}
// ── Secrets providers ─────────────────────────────────────────────────
@@ -451,6 +470,8 @@ export interface SessionResponse {
roleName?: string;
/** Effective permission keys; '*' grants everything. */
permissions?: string[];
/** Credentials were valid but a new password must be set before a session is issued. */
mustChangePassword?: boolean;
}
export interface RoleDto {
@@ -0,0 +1,109 @@
<script lang="ts">
import type { ScriptFileBinding } from '$lib/api/types';
let { bindings = $bindable() }: { bindings: ScriptFileBinding[] } = $props();
function add() {
bindings = [
...bindings,
{ name: '', objectKey: '', destinationPath: '', directory: false, continueOnFailure: false }
];
}
function remove(index: number) {
bindings = bindings.filter((_, i) => i !== index);
}
// A directory delivery unpacks a tree INTO the destination — a leaf file
// path (extension on the last segment) is a mistake the server rejects.
const looksLikeFile = (path: string) =>
/\.[A-Za-z][A-Za-z0-9]{0,6}$/.test(path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? '');
</script>
<p class="muted small">
Downloaded to the device before the script runs. Destinations expand on the device
(<code>%TEMP%</code>, <code>$env:ProgramData</code>, <code>$(…)</code>) and each entry reaches
the script as <code>$Files.Name</code> — a FileInfo, or a DirectoryInfo when the S3 key is a
prefix delivered recursively. Requires S3 (Settings → File delivery).
</p>
{#each bindings as binding, i (i)}
<div class="row">
<input class="input name" placeholder="Name" bind:value={binding.name} aria-label="File name" />
<input
class="input key"
placeholder={binding.directory ? 'S3 prefix (e.g. tools/scanner/)' : 'S3 object key'}
bind:value={binding.objectKey}
aria-label="S3 key"
/>
<input
class="input dest"
placeholder={binding.directory ? 'Destination directory' : 'Destination file path'}
bind:value={binding.destinationPath}
aria-label="Destination path"
/>
<label class="check" title="Deliver every object under the prefix, preserving structure">
<input type="checkbox" bind:checked={binding.directory} /> directory
</label>
<label class="check" title="A failed download logs a warning and the script still runs (check $Files.Name.Exists)">
<input type="checkbox" bind:checked={binding.continueOnFailure} /> continue on failure
</label>
<button class="btn danger tiny" onclick={() => remove(i)} aria-label="Remove file binding">✕</button>
</div>
{#if binding.directory && looksLikeFile(binding.destinationPath)}
<p class="warn small">
A directory delivery unpacks into the destination — give a directory, not a file path.
</p>
{/if}
{/each}
<button class="btn small add" onclick={add}>+ Add file</button>
<style>
.small {
font-size: 12px;
}
.row {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
margin-bottom: var(--space-2);
}
.name {
flex: 0 1 140px;
}
.key {
flex: 1 1 220px;
}
.dest {
flex: 1 1 240px;
}
.check {
display: flex;
align-items: center;
gap: 5px;
font-size: 12px;
color: var(--text-muted);
white-space: nowrap;
}
.tiny {
padding: 3px 8px;
font-size: 11px;
}
.add {
margin-top: var(--space-1);
}
.warn {
color: var(--warning);
margin: -4px 0 var(--space-2);
}
</style>
@@ -27,7 +27,9 @@
{ value: 'lessThan', label: '<', needsValue: true },
{ value: 'lessOrEqual', label: '<=', needsValue: true },
{ value: 'exists', label: 'exists', needsValue: false },
{ value: 'notExists', label: 'does not exist', needsValue: false }
{ value: 'notExists', label: 'does not exist', needsValue: false },
{ value: 'inCidr', label: 'in CIDR range', needsValue: true },
{ value: 'notInCidr', label: 'not in CIDR range', needsValue: true }
];
const needsValue = (op: RuleOperator) => operators.find((o) => o.value === op)?.needsValue ?? true;
@@ -0,0 +1,155 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api } from '$lib/api/client';
import type { DeviceGroupDto, ScriptTriggerDto, ScriptTriggerType } from '$lib/api/types';
let {
scriptId,
groups
}: {
scriptId: string;
groups: DeviceGroupDto[];
} = $props();
let triggers = $state<ScriptTriggerDto[]>([]);
let triggerType = $state<ScriptTriggerType>('onAgentReady');
let groupId = $state('');
let oncePerDevice = $state(true);
let errorText = $state('');
const mine = $derived(triggers.filter((t) => t.scriptId === scriptId));
const labels: Record<ScriptTriggerType, string> = {
onRegistration: 'On registration',
onAgentReady: 'On agent ready'
};
async function refresh() {
triggers = await api.triggers().catch(() => []);
}
onMount(() => {
void refresh();
});
async function add() {
errorText = '';
try {
await api.createTrigger({
scriptId,
groupId: groupId || undefined,
triggerType,
oncePerDevice
});
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Could not add the trigger.';
}
}
async function remove(id: string) {
await api.deleteTrigger(id);
await refresh();
}
</script>
<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.
</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>
</div>
{#if errorText}<p class="warn small">{errorText}</p>{/if}
{#if mine.length === 0}
<p class="faint small">No triggers yet.</p>
{:else}
<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>
</li>
{/each}
</ul>
{/if}
</section>
<style>
.section {
padding: var(--space-4);
}
.form {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
margin-top: var(--space-2);
}
.form .select {
flex: 1;
min-width: 140px;
}
.once {
display: flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
white-space: nowrap;
}
.list {
list-style: none;
margin: var(--space-3) 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.list li {
display: flex;
justify-content: space-between;
align-items: center;
gap: var(--space-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 6px 10px;
font-size: 13px;
}
.tiny {
padding: 3px 8px;
font-size: 11px;
}
.small {
font-size: 12px;
}
.warn {
color: var(--warning);
}
</style>
@@ -0,0 +1,274 @@
/**
* Lightweight PowerShell IntelliSense for the Monaco editor: a curated set of
* common cmdlets, language keywords, automatic variables and snippets, plus
* dynamic entries for the script's own parameters and secret bindings. No
* language server involved — fast, offline and optional.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
const CMDLETS = [
'Get-ChildItem',
'Get-Content',
'Set-Content',
'Add-Content',
'Get-Item',
'Get-ItemProperty',
'Set-ItemProperty',
'New-Item',
'New-ItemProperty',
'Remove-Item',
'Copy-Item',
'Move-Item',
'Rename-Item',
'Test-Path',
'Join-Path',
'Split-Path',
'Resolve-Path',
'Get-Location',
'Set-Location',
'Get-Process',
'Stop-Process',
'Start-Process',
'Wait-Process',
'Get-Service',
'Start-Service',
'Stop-Service',
'Restart-Service',
'Set-Service',
'Get-CimInstance',
'Invoke-CimMethod',
'Get-Date',
'Start-Sleep',
'Write-Output',
'Write-Host',
'Write-Error',
'Write-Warning',
'Write-Verbose',
'Write-Debug',
'Write-Progress',
'Read-Host',
'Out-String',
'Out-Null',
'Out-File',
'ForEach-Object',
'Where-Object',
'Select-Object',
'Sort-Object',
'Group-Object',
'Measure-Object',
'Compare-Object',
'Select-String',
'ConvertTo-Json',
'ConvertFrom-Json',
'ConvertTo-Csv',
'ConvertFrom-Csv',
'Export-Csv',
'Import-Csv',
'Invoke-RestMethod',
'Invoke-WebRequest',
'Invoke-Expression',
'Invoke-Command',
'Test-Connection',
'Test-NetConnection',
'Resolve-DnsName',
'Get-NetIPAddress',
'Get-NetAdapter',
'Compress-Archive',
'Expand-Archive',
'Get-FileHash',
'New-Guid',
'Get-Random',
'Get-WinEvent',
'Get-EventLog',
'Get-HotFix',
'Get-ComputerInfo',
'Restart-Computer',
'Stop-Computer',
'Get-LocalUser',
'Get-LocalGroup',
'Add-LocalGroupMember',
'Get-ScheduledTask',
'Register-ScheduledTask',
'Unregister-ScheduledTask',
'Get-Module',
'Import-Module',
'Install-PSResource',
'Find-PSResource',
'Start-ThreadJob',
'Get-Job',
'Receive-Job',
'Wait-Job',
'Remove-Job',
'Get-Variable',
'Set-Variable',
'Get-Command',
'Get-Member',
'Get-Help',
'Get-Error',
'New-Object',
'Add-Type',
'Get-Acl',
'Set-Acl',
'ConvertTo-SecureString',
'ConvertFrom-SecureString'
];
const KEYWORDS = [
'if',
'elseif',
'else',
'switch',
'foreach',
'for',
'while',
'do',
'until',
'break',
'continue',
'return',
'function',
'param',
'begin',
'process',
'end',
'try',
'catch',
'finally',
'throw',
'trap',
'class',
'enum',
'using',
'in',
'exit'
];
const AUTOMATIC_VARIABLES = [
'$_',
'$PSItem',
'$args',
'$error',
'$LASTEXITCODE',
'$PSVersionTable',
'$PSScriptRoot',
'$env:COMPUTERNAME',
'$env:USERNAME',
'$env:TEMP',
'$env:ProgramFiles',
'$true',
'$false',
'$null',
'$ErrorActionPreference',
'$ProgressPreference'
];
const SNIPPETS: { label: string; detail: string; insert: string }[] = [
{
label: 'param block',
detail: 'Script parameter declaration',
insert: 'param(\n [string]$${1:Name}${2:,\n [int]$${3:Count} = ${4:1}}\n)\n'
},
{
label: 'try / catch',
detail: 'Error handling block',
insert: 'try {\n ${1}\n}\ncatch {\n Write-Error "${2:Operation failed}: $_"\n}\n'
},
{
label: 'foreach loop',
detail: 'Iterate a collection',
insert: 'foreach ($${1:item} in $${2:collection}) {\n ${3}\n}\n'
},
{
label: 'progress loop',
detail: 'Loop reporting Write-Progress',
insert:
'1..${1:10} | ForEach-Object {\n Write-Progress -Activity \'${2:Working}\' -Status "Step $_ of ${1:10}" -PercentComplete ($_ * ${3:10})\n ${4}\n}\n'
}
];
export interface CompletionContext {
/** Names of the script's declared parameters. */
parameterNames: () => string[];
/** Names bound in the secrets dictionary. */
secretNames: () => string[];
/** The secrets variable name (default "Secrets"). */
secretsVariable: () => string;
/** Names bound in the $Files dictionary, with directory flags. */
fileBindings?: () => { name: string; directory: boolean }[];
}
/** Registers the provider for the given language; returns its disposable. */
export function registerPowerShellCompletions(
monaco: any,
language: string,
context: CompletionContext
): { dispose(): void } {
return monaco.languages.registerCompletionItemProvider(language, {
triggerCharacters: ['-', '$', '.'],
provideCompletionItems(model: any, position: any) {
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const kinds = monaco.languages.CompletionItemKind;
const suggestions: any[] = [
...CMDLETS.map((c) => ({
label: c,
kind: kinds.Function,
insertText: c,
range
})),
...KEYWORDS.map((k) => ({
label: k,
kind: kinds.Keyword,
insertText: k,
range
})),
...AUTOMATIC_VARIABLES.map((v) => ({
label: v,
kind: kinds.Variable,
insertText: v,
range
})),
...SNIPPETS.map((s) => ({
label: s.label,
kind: kinds.Snippet,
detail: s.detail,
insertText: s.insert,
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
range
})),
...context.parameterNames().map((p) => ({
label: `$${p}`,
kind: kinds.Variable,
detail: 'Script parameter',
insertText: `$${p}`,
range
})),
...context.secretNames().map((s) => ({
label: `$${context.secretsVariable()}.${s}`,
kind: kinds.Variable,
detail: 'Secret binding',
insertText: `$${context.secretsVariable()}.${s}`,
range
})),
...(context.fileBindings?.() ?? []).map((f) => ({
label: `$Files.${f.name}`,
kind: kinds.File,
detail: f.directory
? 'Delivered directory (DirectoryInfo)'
: 'Delivered file (FileInfo)',
insertText: `$Files.${f.name}`,
range
}))
];
return { suggestions };
}
});
}
+28
View File
@@ -126,6 +126,33 @@
}
}
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 permissions and device scope into a new custom role — works on
* system roles too, as a template. OIDC claim values deliberately do NOT
* copy: two roles matching the same claims would be a mapping trap.
*/
async function cloneRole(role: RoleDto) {
errorText = '';
try {
await api.createRole({
name: copyName(role.name, (roles ?? []).map((r) => r.name)),
description: role.description,
permissions: [...role.permissions],
oidcClaimValues: [],
deviceScopeGroupIds: [...role.deviceScopeGroupIds]
});
await refresh();
} catch (e) {
errorText = e instanceof Error ? e.message : 'Clone failed.';
}
}
function openCreateUser() {
creatingUser = true;
editingUser = null;
@@ -436,6 +463,7 @@
</td>
<td class="muted">{role.userCount}</td>
<td class="row-actions">
<button class="btn tiny" onclick={() => cloneRole(role)}>⧉ Clone</button>
{#if !role.isSystem}
<button class="btn tiny" onclick={() => openEditRole(role)}>Edit</button>
<button class="btn danger tiny" onclick={() => removeRole(role)}>✕</button>
@@ -140,7 +140,7 @@
{:else}
<div class="head">
<div>
<div class="crumbs"><a href="/devices">Devices</a> / <span class="mono faint">{clientId.slice(0, 12)}…</span></div>
<div class="crumbs"><a href="/devices">Devices</a> / {device.hostname}</div>
<div class="title-row">
<h1>{device.hostname}</h1>
<StatusBadge status={device.status} />
@@ -148,6 +148,9 @@
<div class="muted subtitle">
{[device.manufacturer, device.model].filter(Boolean).join(' · ')}
</div>
<div class="client-id">
<CopyChip value={clientId} label="Client ID" />
</div>
</div>
<div class="head-actions">
<button class="btn" onclick={refreshInventory} disabled={!online} title={online ? '' : 'Agent is offline'}>
@@ -175,8 +178,6 @@
<section class="card section">
<h3>Identity</h3>
<dl>
<dt>Client ID</dt>
<dd class="mono">{clientId}</dd>
<dt>Hostname</dt>
<dd>{device.hostname}</dd>
<dt>Serial number</dt>
@@ -391,9 +392,14 @@
<div class="sections">
{#each inventory.network as adapter, i (i)}
<section class="card section">
<h3>{adapter.description ?? `Adapter ${i + 1}`}</h3>
<h3>
{adapter.interfaceName ?? adapter.description ?? `Adapter ${i + 1}`}
{#if adapter.interfaceName && adapter.description && adapter.interfaceName !== adapter.description}
<span class="muted adapter-desc">· {adapter.description}</span>
{/if}
</h3>
<div class="net-rows">
{#each [{ label: 'MAC', values: adapter.macAddress ? [adapter.macAddress] : [] }, { label: 'IPv4', values: adapter.ipv4Addresses }, { label: 'IPv6', values: adapter.ipv6Addresses }, { label: 'Gateways', values: adapter.gateways }, { label: 'DNS', values: adapter.dnsServers }] as row (row.label)}
{#each [{ label: 'Interface', values: adapter.interfaceName ? [adapter.interfaceName] : [] }, { label: 'MAC', values: adapter.macAddress ? [adapter.macAddress] : [] }, { label: 'IPv4', values: adapter.ipv4Addresses }, { label: 'IPv6', values: adapter.ipv6Addresses }, { label: 'Gateways', values: adapter.gateways }, { label: 'DNS', values: adapter.dnsServers }] as row (row.label)}
<div class="net-row">
<span class="net-label muted">{row.label}</span>
<div class="net-values">
@@ -520,6 +526,11 @@
font-size: 13px;
}
.client-id {
margin-top: var(--space-2);
max-width: 560px;
}
.head-actions {
display: flex;
gap: var(--space-2);
@@ -648,6 +659,11 @@
margin-top: var(--space-3);
}
.adapter-desc {
font-size: 12.5px;
font-weight: 400;
}
.net-row {
display: grid;
grid-template-columns: 76px 1fr;
+27 -4
View File
@@ -55,18 +55,40 @@
async function remove() {
if (!selected) return;
if (!confirm(`Delete function module “${selected.name}”?`)) return;
if (!confirm(`Delete function “${selected.name}”?`)) return;
await api.deleteFunction(selected.id);
selected = null;
name = '';
content = '';
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;
};
async function clone() {
if (!selected) return;
try {
const created = await api.createFunction({
name: copyName(name, (modules ?? []).map((m) => m.name)),
description,
content
});
await refresh();
edit(created);
statusText = 'Cloned — you are editing the copy.';
} catch (e) {
statusText = e instanceof Error ? e.message : 'Clone failed.';
}
}
</script>
<div class="page-head">
<h1>Function modules</h1>
<button class="btn primary" onclick={newModule}>+ New module</button>
<h1>Functions</h1>
<button class="btn primary" onclick={newModule}>+ New function</button>
</div>
<p class="muted intro">
@@ -81,7 +103,7 @@
{#each Array(3) as _, i (i)}<div class="skeleton row">loading…</div>{/each}
</div>
{:else if modules.length === 0}
<EmptyState title="No function modules" detail="Create one to share code across scripts." />
<EmptyState title="No Functions" detail="Create one to share code across scripts." />
{:else}
<ul>
{#each modules as m (m.id)}
@@ -102,6 +124,7 @@
{#if statusText}<span class="muted status">{statusText}</span>{/if}
<div class="spacer"></div>
{#if selected}<button class="btn danger" onclick={remove}>Delete</button>{/if}
{#if selected}<button class="btn" onclick={clone}>⧉ Clone</button>{/if}
<button class="btn primary" onclick={save}>💾 Save</button>
</div>
<input class="input desc-input" placeholder="Description (optional)" bind:value={description} />
+33 -121
View File
@@ -6,10 +6,7 @@
DeviceGroupDto,
GroupFieldDescriptor,
GroupKind,
GroupRuleSet,
ScriptDto,
ScriptTriggerDto,
ScriptTriggerType
GroupRuleSet
} from '$lib/api/types';
import RuleBuilder from '$lib/components/RuleBuilder.svelte';
import StatusBadge from '$lib/components/StatusBadge.svelte';
@@ -18,8 +15,6 @@
let groups = $state<DeviceGroupDto[] | null>(null);
let fields = $state<GroupFieldDescriptor[]>([]);
let devices = $state<DeviceDto[]>([]);
let scripts = $state<ScriptDto[]>([]);
let triggers = $state<ScriptTriggerDto[]>([]);
let selected = $state<DeviceGroupDto | null>(null);
let name = $state('');
@@ -31,19 +26,8 @@
let statusText = $state('');
let busy = $state(false);
// New trigger form
let triggerScriptId = $state('');
let triggerGroupId = $state('');
let triggerType = $state<ScriptTriggerType>('onRegistration');
let triggerOnce = $state(true);
async function refresh() {
[groups, devices, scripts, triggers] = await Promise.all([
api.groups(),
api.devices(),
api.scripts().catch(() => []),
api.triggers().catch(() => [])
]);
[groups, devices] = await Promise.all([api.groups(), api.devices()]);
}
onMount(async () => {
@@ -100,6 +84,36 @@
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 rules (dynamic) or the member list (static) into a new group. */
async function cloneGroup() {
if (!selected) return;
busy = true;
try {
const created = await api.createGroup({
name: copyName(name, (groups ?? []).map((g) => g.name)),
description,
kind,
rules: kind === 'dynamic' ? rules : undefined
});
if (kind === 'static' && members.length > 0) {
await api.updateGroupMembers(created.id, members.map((m) => m.clientId), []);
}
await refresh();
await edit(created);
statusText = 'Cloned — you are editing the copy.';
} catch (e) {
statusText = e instanceof Error ? e.message : 'Clone failed.';
} finally {
busy = false;
}
}
async function runPreview() {
busy = true;
try {
@@ -119,30 +133,7 @@
await refresh();
}
async function addTrigger() {
if (!triggerScriptId) {
statusText = 'Pick a script for the trigger.';
return;
}
await api.createTrigger({
scriptId: triggerScriptId,
groupId: triggerGroupId || undefined,
triggerType,
oncePerDevice: triggerOnce
});
triggers = await api.triggers();
}
async function removeTrigger(id: string) {
await api.deleteTrigger(id);
triggers = await api.triggers();
}
const memberIds = $derived(new Set(members.map((m) => m.clientId)));
const triggerLabels: Record<ScriptTriggerType, string> = {
onRegistration: 'On registration',
onAgentReady: 'On agent ready'
};
</script>
<div class="page-head">
@@ -186,6 +177,7 @@
<div class="spacer"></div>
{#if statusText}<span class="muted small">{statusText}</span>{/if}
{#if selected}<button class="btn danger" onclick={remove}>Delete</button>{/if}
{#if selected}<button class="btn" onclick={cloneGroup} disabled={busy}>⧉ Clone</button>{/if}
<button class="btn primary" onclick={save} disabled={busy}>💾 Save</button>
</div>
<input class="input" placeholder="Description (optional)" bind:value={description} />
@@ -241,59 +233,6 @@
</section>
{/if}
<section class="card section">
<div class="trigger-head">
<h3>Script triggers</h3>
<button class="btn primary" onclick={addTrigger} disabled={!triggerScriptId}>
+ Add trigger
</button>
</div>
<p class="muted small">
Run a script automatically when a device registers, or when its agent connects and is ready
for jobs.
</p>
<div class="trigger-form">
<select class="select" bind:value={triggerScriptId} aria-label="Script">
<option value="">Select script…</option>
{#each scripts as s (s.id)}
<option value={s.id}>{s.name}</option>
{/each}
</select>
<select class="select" bind:value={triggerType} aria-label="Trigger">
<option value="onRegistration">On registration</option>
<option value="onAgentReady">On agent ready</option>
</select>
<select class="select" bind:value={triggerGroupId} aria-label="Target group">
<option value="">All devices</option>
{#each groups ?? [] as g (g.id)}
<option value={g.id}>{g.name}</option>
{/each}
</select>
<label class="once"><input type="checkbox" bind:checked={triggerOnce} /> once per device</label>
</div>
{#if triggers.length > 0}
<div class="table-wrap">
<table class="data">
<thead>
<tr><th>Script</th><th>When</th><th>Target</th><th>Once</th><th></th></tr>
</thead>
<tbody>
{#each triggers as t (t.id)}
<tr>
<td>{t.scriptName}</td>
<td>{triggerLabels[t.triggerType]}</td>
<td class="muted">{t.groupName}</td>
<td class="muted">{t.oncePerDevice ? 'yes' : 'no'}</td>
<td><button class="btn danger small" onclick={() => removeTrigger(t.id)}>Remove</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</section>
</div>
</div>
@@ -460,33 +399,6 @@
font-size: 13px;
}
.trigger-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}
.trigger-form {
display: flex;
gap: var(--space-2);
flex-wrap: wrap;
align-items: center;
}
.trigger-form .select {
flex: 1;
min-width: 150px;
}
.once {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
color: var(--text-muted);
}
.loading {
padding: var(--space-3);
display: flex;
+74 -3
View File
@@ -12,6 +12,11 @@
let busy = $state(false);
let config = $state<AuthConfigDto | null>(null);
// Forced first-sign-in reset (defaulted admin/admin credentials).
let mustChange = $state(false);
let newPassword = $state('');
let confirmPassword = $state('');
onMount(async () => {
// A failed SSO round-trip comes back as ?error= so the operator sees why
// instead of an identity-provider error page.
@@ -34,7 +39,11 @@
error = '';
busy = true;
try {
await session.login(username, password);
const result = await session.login(username, password);
if (result.mustChangePassword) {
mustChange = true;
return;
}
await goto('/');
} catch (e) {
error =
@@ -48,6 +57,34 @@
}
}
async function submitNewPassword(event: SubmitEvent) {
event.preventDefault();
error = '';
if (newPassword.length < 8) {
error = 'The new password must be at least 8 characters.';
return;
}
if (newPassword !== confirmPassword) {
error = 'The passwords do not match.';
return;
}
busy = true;
try {
await api.changePassword(username, password, newPassword);
await session.initialize();
await goto('/');
} catch (e) {
error =
e instanceof ApiError && e.status === 401
? 'The current password no longer matches — start over.'
: e instanceof ApiError && e.status === 429
? 'Too many attempts — try again in a minute.'
: 'Could not set the new password.';
} finally {
busy = false;
}
}
// ?local=1 always reveals the local form — the way back in when the identity
// provider is unavailable.
const forceLocal = $derived(page.url.searchParams.get('local') === '1');
@@ -65,13 +102,43 @@
<span class="brand-mark">X</span>
<span>ExecuteR</span>
</div>
<h1>Sign in</h1>
<h1>{mustChange ? 'Set a new password' : 'Sign in'}</h1>
{#if error}
<div class="error" role="alert">{error}</div>
{/if}
{#if config?.autoRedirect && !error}
{#if mustChange}
<p class="muted small">
This account still uses the default password. Choose a new one to finish signing in as
<strong>{username}</strong>.
</p>
<form onsubmit={submitNewPassword}>
<label>
<span>New password</span>
<input
class="input"
type="password"
autocomplete="new-password"
bind:value={newPassword}
required
/>
</label>
<label>
<span>Confirm new password</span>
<input
class="input"
type="password"
autocomplete="new-password"
bind:value={confirmPassword}
required
/>
</label>
<button class="btn primary submit" disabled={busy}>
{busy ? 'Saving…' : 'Set password and sign in'}
</button>
</form>
{:else if config?.autoRedirect && !error}
<p class="muted">Redirecting to single sign-on…</p>
{:else}
{#if showLocal}
@@ -235,4 +302,8 @@
text-align: center;
font-size: 12px;
}
.small {
font-size: 12.5px;
}
</style>
@@ -89,6 +89,29 @@
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 (
@@ -230,6 +253,7 @@
</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>
+324 -181
View File
@@ -11,14 +11,18 @@
JobProgressPayload,
JobState,
ScriptParameter,
ScriptFileBinding,
SecretBinding
} from '$lib/api/types';
import { nats, type JobEvent } from '$lib/messaging/nats';
import { registerPowerShellCompletions } from '$lib/editor/powershell-completions';
import JobStateBadge from '$lib/components/JobStateBadge.svelte';
import ParameterSchemaEditor from '$lib/components/ParameterSchemaEditor.svelte';
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!);
const isNew = $derived(scriptId === 'new');
@@ -47,6 +51,12 @@
let showParamEditor = $state(false);
let secretBindings = $state<SecretBinding[]>([]);
let secretsVariableName = $state('Secrets');
let fileBindings = $state<ScriptFileBinding[]>([]);
// Editor chrome
let fullscreen = $state(false);
let intellisense = $state(true);
let completionDisposable: { dispose(): void } | null = null;
// Live run state (single-device run)
let job = $state<JobDto | null>(null);
@@ -65,7 +75,45 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let editor: any = null;
const engineHints: Record<string, string> = {
PowerShell: 'Runs inside the agent — full progress, parameters and secrets on every platform.',
WindowsPowerShell:
'Runs via powershell.exe on Windows devices. Near parity; live progress bars are not captured.',
Bash: 'Runs on Linux/macOS devices (or Windows with Git Bash). Parameters and secrets arrive as environment variables.'
};
function applyIntellisense() {
completionDisposable?.dispose();
completionDisposable = null;
if (intellisense && monacoRef && engine !== 'Bash') {
completionDisposable = registerPowerShellCompletions(monacoRef, 'powershell', {
parameterNames: () => parameters.map((p) => p.name).filter(Boolean),
secretNames: () => secretBindings.map((b) => b.name).filter(Boolean),
secretsVariable: () => secretsVariableName.trim() || 'Secrets',
fileBindings: () =>
fileBindings
.filter((b) => b.name.trim())
.map((b) => ({ name: b.name, directory: b.directory ?? false }))
});
}
}
function toggleIntellisense() {
intellisense = !intellisense;
localStorage.setItem('editor-intellisense', intellisense ? '1' : '0');
applyIntellisense();
}
function onEngineChange() {
if (monacoRef && editor) {
monacoRef.editor.setModelLanguage(editor.getModel(), engine === 'Bash' ? 'shell' : 'powershell');
}
applyIntellisense();
}
onMount(() => {
intellisense = localStorage.getItem('editor-intellisense') !== '0';
void (async () => {
const [monaco, editorWorker] = await Promise.all([
import('monaco-editor'),
@@ -85,6 +133,7 @@
functionModuleIds = script.functionModuleIds ?? [];
secretBindings = script.secretBindings ?? [];
secretsVariableName = script.secretsVariableName ?? 'Secrets';
fileBindings = script.fileBindings ?? [];
if (script.language === 'WindowsPowerShell' || script.language === 'Bash') {
engine = script.language;
}
@@ -109,6 +158,7 @@
renderWhitespace: 'selection'
});
editor.onDidChangeModelContent(() => (content = editor.getValue()));
applyIntellisense();
[devices, allGroups] = await Promise.all([api.devices(), api.groups().catch(() => [])]);
const requested = page.url.searchParams.get('target');
@@ -121,6 +171,7 @@
return () => {
unsubscribeJob?.();
completionDisposable?.dispose();
editor?.dispose();
};
});
@@ -140,7 +191,8 @@
parameters,
functionModuleIds,
secretBindings: secretBindings.filter((b) => b.name.trim() && b.secretName.trim()),
secretsVariableName: secretsVariableName.trim() || undefined
secretsVariableName: secretsVariableName.trim() || undefined,
fileBindings: fileBindings.filter((b) => b.name.trim() && b.objectKey.trim() && b.destinationPath.trim())
};
try {
if (isNew) {
@@ -269,6 +321,33 @@
await goto('/scripts');
}
/** Creates a copy with the current editor state and switches to it. */
async function clone() {
if (isNew) return;
statusText = '';
try {
const created = await api.createScript({
name: `${name} (copy)`,
description,
content,
engine,
parameters,
functionModuleIds,
secretBindings: secretBindings.filter((b) => b.name.trim() && b.secretName.trim()),
secretsVariableName: secretsVariableName.trim() || undefined,
fileBindings: fileBindings.filter(
(b) => b.name.trim() && b.objectKey.trim() && b.destinationPath.trim()
)
});
// The editor state already matches the clone; adopt its identity.
name = created.name;
await goto(`/scripts/${created.id}`);
statusText = 'Cloned — you are editing the copy.';
} catch (e) {
statusText = e instanceof Error ? e.message : 'Clone failed.';
}
}
const terminal = ['succeeded', 'failed', 'cancelled', 'timedOut'];
const groupRunning = $derived(
groupJobs.some((g) => !terminal.includes(jobStates[g.jobId] ?? 'queued'))
@@ -284,6 +363,12 @@
);
</script>
<svelte:window
onkeydown={(e) => {
if (e.key === 'Escape' && fullscreen) fullscreen = false;
}}
/>
<div class="head">
<div class="meta">
<div class="crumbs"><a href="/scripts">Scripts</a> / {isNew ? 'New' : name || '…'}</div>
@@ -294,25 +379,17 @@
bind:value={description}
aria-label="Description"
/>
<label class="engine-row">
<span class="muted small">Engine</span>
<select
class="select engine-select"
bind:value={engine}
onchange={() =>
monacoRef && editor
? monacoRef.editor.setModelLanguage(
editor.getModel(),
engine === 'Bash' ? 'shell' : 'powershell'
)
: undefined}
title="PowerShell runs in-process on every platform. Windows PowerShell 5.1 shells out to powershell.exe (Windows devices). Bash runs on unix devices (or Windows with Git Bash); parameters and secrets arrive as environment variables."
>
<option value="PowerShell">PowerShell 7 (in-process, all platforms)</option>
<option value="WindowsPowerShell">Windows PowerShell 5.1 (Windows)</option>
<option value="Bash">Bash (linux/macOS, env-var params)</option>
</select>
</label>
<div class="engine-row">
<label class="engine-label">
<span class="muted small">Script Engine</span>
<select class="select engine-select" bind:value={engine} onchange={onEngineChange}>
<option value="PowerShell">PowerShell 7</option>
<option value="WindowsPowerShell">PowerShell 5</option>
<option value="Bash">Bash</option>
</select>
</label>
<span class="muted small hint">{engineHints[engine]}</span>
</div>
</div>
<div class="actions">
{#if statusText}
@@ -320,6 +397,7 @@
{/if}
{#if !isNew}
<button class="btn danger" onclick={remove}>Delete</button>
<button class="btn" onclick={clone} disabled={saving}>⧉ Clone</button>
{/if}
<button class="btn" onclick={save} disabled={saving}>💾 Save</button>
<button class="btn primary" onclick={run} disabled={saving || !targetKey || running}>
@@ -331,13 +409,14 @@
<section class="card define-strip" class:open={showParamEditor}>
<div class="define-bar">
<div class="define-summary">
<h3>Parameters, secrets &amp; functions</h3>
<h3>Script Configuration</h3>
<span class="muted small">
{parameters.length === 0
? 'No parameters'
: `${parameters.length} parameter${parameters.length === 1 ? '' : 's'}`}
· {secretBindings.length} secret{secretBindings.length === 1 ? '' : 's'}
· {functionModuleIds.length} function module{functionModuleIds.length === 1 ? '' : 's'}
· {fileBindings.length} file{fileBindings.length === 1 ? '' : 's'}
· {functionModuleIds.length} function{functionModuleIds.length === 1 ? '' : 's'}
</span>
</div>
<button class="btn" onclick={() => (showParamEditor = !showParamEditor)}>
@@ -347,17 +426,25 @@
{#if showParamEditor}
<div class="define-body pulse-in">
<ParameterSchemaEditor bind:parameters />
<div class="params-block">
<h4>Parameters</h4>
<ParameterSchemaEditor bind:parameters />
</div>
<div class="secrets-block">
<h4>Secrets</h4>
<SecretBindingsEditor bind:bindings={secretBindings} bind:variableName={secretsVariableName} />
</div>
<div class="files-block">
<h4>Files (S3)</h4>
<FileBindingsEditor bind:bindings={fileBindings} />
</div>
<div class="modules">
<h4>Function modules</h4>
<h4>Functions</h4>
{#if allFunctions.length === 0}
<p class="muted small">No function modules yet. Create them under Functions.</p>
<p class="muted small">Nothing here yet — create reusable Functions from the sidebar.</p>
{:else}
<div class="module-grid">
{#each allFunctions as fn (fn.id)}
@@ -381,132 +468,148 @@
{/if}
</section>
<div class="workbench">
<div class="editor-pane card">
{#if !loaded}
<div class="skeleton editor-skeleton">loading editor…</div>
{/if}
<div class="editor-host" bind:this={editorHost}></div>
<div class="editor-pane card" class:fullscreen>
<div class="editor-toolbar">
<span class="muted small">{engine === 'Bash' ? 'bash' : 'powershell'}</span>
<div class="toolbar-actions">
<button
class="btn tiny"
class:on={intellisense}
onclick={toggleIntellisense}
disabled={engine === 'Bash'}
title="Curated cmdlet, keyword, parameter and secret completions (no language server)"
>
{intellisense && engine !== 'Bash' ? '✓ ' : ''}IntelliSense
</button>
<button
class="btn tiny"
onclick={() => (fullscreen = !fullscreen)}
title={fullscreen ? 'Return to the page (Esc)' : 'Pop the editor out to fill the window'}
>
{fullscreen ? '🗗 Restore' : '⛶ Pop out'}
</button>
</div>
</div>
{#if !loaded}
<div class="skeleton editor-skeleton">loading editor…</div>
{/if}
<div class="editor-host" bind:this={editorHost}></div>
</div>
<aside class="side">
<section class="card section">
<h3>Target</h3>
<select class="select target" bind:value={targetKey} aria-label="Target device or group">
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId} disabled={device.status !== 'online'}>
{device.hostname}
{device.status !== 'online' ? `(${device.status})` : ''}
</option>
<div class="flow">
<section class="card section">
<h3>Execution</h3>
<select class="select target" bind:value={targetKey} aria-label="Target device or group">
<optgroup label="Devices">
{#each devices as device (device.clientId)}
<option value={'device:' + device.clientId} disabled={device.status !== 'online'}>
{device.hostname}
{device.status !== 'online' ? `(${device.status})` : ''}
</option>
{/each}
</optgroup>
{#if allGroups.length > 0}
<optgroup label="Groups (one job per member)">
{#each allGroups as group (group.id)}
<option value={'group:' + group.id}>{group.name} ({group.kind})</option>
{/each}
</optgroup>
{#if allGroups.length > 0}
<optgroup label="Groups (one job per member)">
{#each allGroups as group (group.id)}
<option value={'group:' + group.id}>{group.name} ({group.kind})</option>
{/each}
</optgroup>
{/if}
</select>
{#if targetKey.startsWith('group:')}
<p class="muted small">
Runs on every non-orphaned member. Offline devices receive the job durably when they
reconnect.
</p>
{/if}
{#if devices.length === 0}
<p class="muted">No devices enrolled yet.</p>
{/if}
</section>
</select>
{#if targetKey.startsWith('group:')}
<p class="muted small">
Runs on every non-orphaned member. Offline devices receive the job durably when they
reconnect.
</p>
{/if}
{#if devices.length === 0}
<p class="muted">No devices enrolled yet.</p>
{/if}
{#if parameters.length > 0}
<section class="card section">
<h3>Run values</h3>
<ParameterInputs bind:this={paramInputs} {parameters} />
</section>
<h4 class="exec-values">Execution values</h4>
<ParameterInputs bind:this={paramInputs} {parameters} />
{/if}
</section>
{#if !isNew && loaded}
<SchedulesCard
{scriptId}
{devices}
groups={allGroups}
defaultTarget={targetKey}
collectArgs={() => paramInputs?.collect() ?? {}}
/>
{/if}
{#if groupJobs.length > 0}
<section class="card section">
<div class="job-head">
<h3>Group run</h3>
<span class="muted small">{groupFinished}/{groupJobs.length} finished</span>
</div>
{#if skippedOrphaned.length > 0}
<p class="warn small">Skipped orphaned: {skippedOrphaned.join(', ')}</p>
{/if}
<ul class="group-jobs">
{#each groupJobs as groupJob (groupJob.jobId)}
<li>
<button
type="button"
class="group-job"
class:active={focusJobId === groupJob.jobId}
onclick={() => void focusJob(groupJob.jobId)}
>
<span class="host">{groupJob.hostname ?? groupJob.clientId}</span>
<JobStateBadge state={jobStates[groupJob.jobId] ?? 'queued'} />
</button>
</li>
{/each}
</ul>
</section>
{/if}
<section class="card section">
<div class="job-head">
<h3>{groupJobs.length > 0 ? `Progress — ${focusHostname ?? '…'}` : 'Job'}</h3>
{#if jobState}
<JobStateBadge state={jobState} />
{/if}
</div>
{#if progress}
<div class="progress-block pulse-in">
<div class="progress-label">
<span>{progress.activity}</span>
<span class="muted">{progress.statusDescription ?? ''}</span>
</div>
<div class="progress-track">
<div class="progress-fill" style="width: {progress.percentComplete ?? 0}%"></div>
</div>
<div class="progress-meta muted">
{progress.percentComplete ?? 0}%
{progress.secondsRemaining != null ? ` · ~${progress.secondsRemaining}s remaining` : ''}
</div>
</div>
{:else if running}
<div class="muted">Waiting for progress…</div>
{:else if !job && groupJobs.length === 0}
<div class="muted">Run the script to see live progress and output.</div>
{/if}
</section>
<section class="card section output-section">
<h3>Output{focusHostname ? ` — ${focusHostname}` : ''}</h3>
<div class="output mono">
{#if outputLines.length === 0}
<span class="faint">—</span>
{:else}
{#each outputLines as line (line.seq)}
<div class="output-line {line.stream}">{line.text}</div>
{/each}
{/if}
</div>
</section>
</aside>
{#if !isNew && loaded}
<SchedulesCard
{scriptId}
{devices}
groups={allGroups}
defaultTarget={targetKey}
collectArgs={() => paramInputs?.collect() ?? {}}
/>
<TriggersCard {scriptId} groups={allGroups} />
{/if}
</div>
{#if groupJobs.length > 0}
<section class="card section run-wide">
<div class="job-head">
<h3>Group run</h3>
<span class="muted small">{groupFinished}/{groupJobs.length} finished</span>
</div>
{#if skippedOrphaned.length > 0}
<p class="warn small">Skipped orphaned: {skippedOrphaned.join(', ')}</p>
{/if}
<ul class="group-jobs">
{#each groupJobs as groupJob (groupJob.jobId)}
<li>
<button
type="button"
class="group-job"
class:active={focusJobId === groupJob.jobId}
onclick={() => void focusJob(groupJob.jobId)}
>
<span class="host">{groupJob.hostname ?? groupJob.clientId}</span>
<JobStateBadge state={jobStates[groupJob.jobId] ?? 'queued'} />
</button>
</li>
{/each}
</ul>
</section>
{/if}
<section class="card section run-wide output-section">
<div class="job-head">
<h3>Output{focusHostname ? ` — ${focusHostname}` : ''}</h3>
{#if jobState}
<JobStateBadge state={jobState} />
{/if}
</div>
{#if progress}
<div class="progress-block pulse-in">
<div class="progress-label">
<span>{progress.activity}</span>
<span class="muted">{progress.statusDescription ?? ''}</span>
</div>
<div class="progress-track">
<div class="progress-fill" style="width: {progress.percentComplete ?? 0}%"></div>
</div>
<div class="progress-meta muted">
{progress.percentComplete ?? 0}%
{progress.secondsRemaining != null ? ` · ~${progress.secondsRemaining}s remaining` : ''}
</div>
</div>
{:else if running}
<div class="muted small waiting">Waiting for progress…</div>
{/if}
<div class="output mono">
{#if outputLines.length === 0}
<span class="faint">
{job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'}
</span>
{:else}
{#each outputLines as line (line.seq)}
<div class="output-line {line.stream}">{line.text}</div>
{/each}
{/if}
</div>
</section>
<style>
.head {
display: flex;
@@ -542,6 +645,13 @@
}
.engine-row {
display: flex;
align-items: center;
gap: var(--space-3);
flex-wrap: wrap;
}
.engine-label {
display: flex;
align-items: center;
gap: var(--space-2);
@@ -549,7 +659,11 @@
}
.engine-select {
max-width: 340px;
max-width: 180px;
}
.hint {
max-width: 520px;
}
.actions {
@@ -593,11 +707,14 @@
}
.modules h4,
.secrets-block h4 {
.secrets-block h4,
.files-block h4,
.params-block h4 {
margin-bottom: var(--space-2);
}
.secrets-block {
.secrets-block,
.files-block {
border-top: 1px solid var(--border);
padding-top: var(--space-3);
}
@@ -629,35 +746,66 @@
background: var(--accent-soft);
}
.workbench {
display: grid;
grid-template-columns: minmax(0, 1fr) 360px;
gap: var(--space-4);
min-height: 540px;
}
.editor-pane {
position: relative;
overflow: hidden;
min-height: 540px;
height: 52vh;
min-height: 380px;
display: flex;
flex-direction: column;
margin-bottom: var(--space-4);
}
.editor-pane.fullscreen {
position: fixed;
inset: 0;
z-index: 100;
height: auto;
min-height: 0;
border-radius: 0;
margin: 0;
}
.editor-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 6px 12px;
border-bottom: 1px solid var(--border);
}
.toolbar-actions {
display: flex;
gap: var(--space-2);
}
.tiny {
padding: 3px 10px;
font-size: 11.5px;
}
.tiny.on {
border-color: var(--accent);
color: var(--accent);
}
.editor-host {
position: absolute;
inset: 0;
flex: 1;
min-height: 0;
}
.editor-skeleton {
position: absolute;
inset: var(--space-3);
inset: 42px var(--space-3) var(--space-3);
z-index: 1;
}
.side {
.flow {
display: flex;
flex-direction: column;
gap: var(--space-4);
min-width: 0;
margin-bottom: var(--space-4);
}
.section {
@@ -669,6 +817,16 @@
margin-top: var(--space-2);
}
.exec-values {
margin: var(--space-3) 0 var(--space-2);
border-top: 1px solid var(--border);
padding-top: var(--space-3);
}
.run-wide {
margin-bottom: var(--space-4);
}
.job-head {
display: flex;
justify-content: space-between;
@@ -679,11 +837,9 @@
list-style: none;
margin: var(--space-2) 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
max-height: 260px;
overflow-y: auto;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 6px;
}
.group-job {
@@ -720,6 +876,10 @@
font-size: 12px;
}
.waiting {
margin-top: var(--space-2);
}
.progress-block {
margin-top: var(--space-3);
}
@@ -751,22 +911,15 @@
margin-top: 4px;
}
.output-section {
flex: 1;
display: flex;
flex-direction: column;
min-height: 200px;
}
.output {
flex: 1;
margin-top: var(--space-2);
margin-top: var(--space-3);
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--space-3);
overflow: auto;
max-height: 320px;
min-height: 200px;
max-height: 46vh;
font-size: 12px;
line-height: 1.6;
}
@@ -792,14 +945,4 @@
.output-line.information {
color: var(--info);
}
@media (max-width: 1100px) {
.workbench {
grid-template-columns: 1fr;
}
.editor-pane {
min-height: 380px;
}
}
</style>
+171
View File
@@ -0,0 +1,171 @@
using System.Net;
using System.Text;
using Agent.PowerShell;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
public class ScriptFileFetcherTests
{
[Theory]
[InlineData("sub/file.txt", true)]
[InlineData("deep/er/tree.bin", true)]
[InlineData("../evil.txt", false)]
[InlineData("a/../../evil.txt", false)]
[InlineData("/rooted.txt", false)]
[InlineData("C:\\rooted.txt", false)]
public void SafeCombineRefusesEscapes(string relative, bool allowed)
{
var root = Path.Combine(Path.GetTempPath(), "fetcher-root");
if (allowed)
{
var combined = ScriptFileFetcher.SafeCombine(root, relative);
Assert.StartsWith(Path.GetFullPath(root), combined);
}
else
{
Assert.Throws<InvalidOperationException>(() => ScriptFileFetcher.SafeCombine(root, relative));
}
}
[Fact]
public async Task DownloadsFilesAndDirectoriesAndHonorsContinueOnFailure()
{
using var server = new StaticServer(new Dictionary<string, string>
{
["/single.txt"] = "single-content",
["/dir/a.txt"] = "alpha",
["/dir/sub/b.txt"] = "beta",
});
var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}");
try
{
var deliveries = new List<ScriptFileDelivery>
{
new("Config", Path.Combine(workDir, "config.txt"), false, false,
[new ScriptFileItem("", server.Url("/single.txt"))]),
new("Tools", Path.Combine(workDir, "tools"), true, false,
[
new ScriptFileItem("a.txt", server.Url("/dir/a.txt")),
new ScriptFileItem("sub/b.txt", server.Url("/dir/sub/b.txt")),
]),
// 404s, but continue-on-failure keeps the job alive.
new("Optional", Path.Combine(workDir, "optional.txt"), false, true,
[new ScriptFileItem("", server.Url("/missing.txt"))]),
};
var records = new List<NormalizedOutputRecord>();
var result = await ScriptFileFetcher.FetchAsync(
deliveries, path => path, records.Add, CancellationToken.None);
Assert.Null(result.FailureMessage);
Assert.Equal("single-content", await File.ReadAllTextAsync(Path.Combine(workDir, "config.txt")));
Assert.Equal("beta", await File.ReadAllTextAsync(Path.Combine(workDir, "tools", "sub", "b.txt")));
// Case-insensitive dictionary of FileInfo / DirectoryInfo.
var config = Assert.IsType<FileInfo>(result.Files["CONFIG"]);
Assert.True(config.Exists);
var tools = Assert.IsType<DirectoryInfo>(result.Files["tools"]);
Assert.True(tools.Exists);
// The failed optional entry still resolves (Exists = false) and warned.
var optional = Assert.IsType<FileInfo>(result.Files["Optional"]);
Assert.False(optional.Exists);
Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning && r.Text.Contains("Optional"));
}
finally
{
if (Directory.Exists(workDir))
{
Directory.Delete(workDir, recursive: true);
}
}
}
[Fact]
public async Task AFailedRequiredDeliveryFailsBeforeTheScriptRuns()
{
using var server = new StaticServer([]);
var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}");
var deliveries = new List<ScriptFileDelivery>
{
new("Required", Path.Combine(workDir, "required.txt"), false, false,
[new ScriptFileItem("", server.Url("/missing.txt"))]),
};
var result = await ScriptFileFetcher.FetchAsync(
deliveries, path => path, _ => { }, CancellationToken.None);
Assert.NotNull(result.FailureMessage);
Assert.Contains("Required", result.FailureMessage);
}
[Fact]
public async Task ServerSideResolutionErrorsRespectContinueOnFailure()
{
var deliveries = new List<ScriptFileDelivery>
{
new("Broken", Path.Combine(Path.GetTempPath(), "x.txt"), false, true, [],
Error: "no objects under prefix"),
};
var records = new List<NormalizedOutputRecord>();
var result = await ScriptFileFetcher.FetchAsync(
deliveries, path => path, records.Add, CancellationToken.None);
Assert.Null(result.FailureMessage);
Assert.IsType<FileInfo>(result.Files["Broken"]);
Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning);
}
/// <summary>Tiny loopback HTTP server for real download round-trips.</summary>
private sealed class StaticServer : IDisposable
{
private readonly HttpListener listener = new();
private readonly string baseUrl;
public StaticServer(Dictionary<string, string> content)
{
var port = Random.Shared.Next(20000, 60000);
baseUrl = $"http://127.0.0.1:{port}";
listener.Prefixes.Add(baseUrl + "/");
listener.Start();
_ = Task.Run(async () =>
{
while (listener.IsListening)
{
HttpListenerContext context;
try
{
context = await listener.GetContextAsync();
}
catch (Exception)
{
return;
}
if (content.TryGetValue(context.Request.Url!.AbsolutePath, out var body))
{
var bytes = Encoding.UTF8.GetBytes(body);
context.Response.StatusCode = 200;
await context.Response.OutputStream.WriteAsync(bytes);
}
else
{
context.Response.StatusCode = 404;
}
context.Response.Close();
}
});
}
public string Url(string path) => baseUrl + path;
public void Dispose() => listener.Stop();
}
}
@@ -24,6 +24,9 @@ public sealed class BackendTestFixture : WebApplicationFactory<Program>
builder.UseSetting("NATS_ACCOUNT_PUBLIC_KEY", AccountKey.GetPublicKey());
builder.UseSetting("NATS_URL", string.Empty);
builder.UseSetting("RATE_LIMIT_PER_MINUTE", "10000");
// Tests drive schedule sweeps manually; the background worker would
// race them (fire-and-advance between seeding steps).
builder.UseSetting("SCHEDULE_WORKER", "0");
builder.UseEnvironment("Development");
}
@@ -0,0 +1,69 @@
using Backend.Groups;
using Xunit;
namespace Backend.Tests;
public class InventoryReportCacheTests
{
private const string MinimalReport = """
{
"identity": { "clientId": "c1", "hostname": "PC-001", "partOfDomain": false },
"os": { "caption": "Windows 11 Pro" },
"cpu": {}, "memory": [], "totalPhysicalMemoryBytes": 0,
"disks": [], "volumes": [], "network": [],
"collectedUtc": "2026-08-08T00:00:00Z"
}
""";
[Fact]
public void HitsOnlyWhileTheSnapshotTimestampMatches()
{
var cache = new InventoryReportCache();
var t1 = DateTimeOffset.UtcNow;
Assert.False(cache.TryGet("c1", t1, out _));
var stored = cache.Store("c1", t1, MinimalReport);
Assert.NotNull(stored);
Assert.True(cache.TryGet("c1", t1, out var hit));
Assert.Equal("Windows 11 Pro", hit!.Os.Caption);
// A newer snapshot timestamp invalidates the entry.
Assert.False(cache.TryGet("c1", t1.AddMinutes(15), out _));
}
[Fact]
public void CorruptJsonCachesAsNullInsteadOfReparsingForever()
{
var cache = new InventoryReportCache();
var t1 = DateTimeOffset.UtcNow;
Assert.Null(cache.Store("c1", t1, "{not json"));
Assert.True(cache.TryGet("c1", t1, out var report));
Assert.Null(report);
}
[Theory]
[InlineData(@"C:\temp\agent.msi", true)]
[InlineData("/opt/tools/archive.tar", true)]
[InlineData(@"%TEMP%\executer", false)]
[InlineData("/opt/tools/", false)]
[InlineData(@"C:\app-1.2", false)] // version-like dots are not extensions
[InlineData(@"C:\payload\v2.hotfix", true)]
public void DirectoryDestinationsRejectLeafFilePaths(string destination, bool looksLikeFile)
=> Assert.Equal(looksLikeFile, Backend.Scripts.ScriptEndpoints.LooksLikeFilePath(destination));
[Fact]
public void PruneDropsDevicesThatNoLongerExist()
{
var cache = new InventoryReportCache();
var t1 = DateTimeOffset.UtcNow;
cache.Store("alive", t1, MinimalReport);
cache.Store("gone", t1, MinimalReport);
cache.Prune(new HashSet<string>(StringComparer.Ordinal) { "alive" });
Assert.True(cache.TryGet("alive", t1, out _));
Assert.False(cache.TryGet("gone", t1, out _));
}
}
+64
View File
@@ -176,6 +176,70 @@ public class AccessControlHttpTests(BackendTestFixture fixture) : IClassFixture<
(await viewerClient.GetAsync("/api/admin/roles")).StatusCode);
}
[Fact]
public async Task DefaultedPasswordForcesAResetBeforeAnySessionExists()
{
var seeded = await SeedLocalUserAsync("reset-admin", "admin-password", "Admin");
await fixture.WithDbAsync(async db =>
{
var user = await db.Users.SingleAsync(u => u.Id == seeded.Id);
user.MustChangePassword = true;
await db.SaveChangesAsync();
});
using var client = fixture.CreateClient();
// Valid credentials produce no session — only the must-change signal.
var login = await client.PostAsJsonAsync(
"/api/auth/login", new { username = "reset-admin", password = "admin-password" });
Assert.Equal(System.Net.HttpStatusCode.OK, login.StatusCode);
using (var body = JsonDocument.Parse(await login.Content.ReadAsStringAsync()))
{
Assert.False(body.RootElement.GetProperty("authenticated").GetBoolean());
Assert.True(body.RootElement.GetProperty("mustChangePassword").GetBoolean());
}
Assert.Equal(System.Net.HttpStatusCode.Unauthorized,
(await client.GetAsync("/api/admin/roles")).StatusCode);
// Wrong current password is refused.
Assert.Equal(System.Net.HttpStatusCode.Unauthorized,
(await client.PostAsJsonAsync("/api/auth/change-password", new
{
username = "reset-admin",
currentPassword = "wrong",
newPassword = "brand-new-password-1",
})).StatusCode);
// The change signs the user in and clears the flag.
var change = await client.PostAsJsonAsync("/api/auth/change-password", new
{
username = "reset-admin",
currentPassword = "admin-password",
newPassword = "brand-new-password-1",
});
Assert.Equal(System.Net.HttpStatusCode.OK, change.StatusCode);
using (var body = JsonDocument.Parse(await change.Content.ReadAsStringAsync()))
{
Assert.True(body.RootElement.GetProperty("authenticated").GetBoolean());
Assert.Equal("Admin", body.RootElement.GetProperty("roleName").GetString());
}
Assert.Equal(System.Net.HttpStatusCode.OK,
(await client.GetAsync("/api/admin/roles")).StatusCode);
// Subsequent sign-ins use the new password with no reset detour.
using var fresh = fixture.CreateClient();
var relogin = await fresh.PostAsJsonAsync(
"/api/auth/login", new { username = "reset-admin", password = "brand-new-password-1" });
Assert.Equal(System.Net.HttpStatusCode.OK, relogin.StatusCode);
using (var body = JsonDocument.Parse(await relogin.Content.ReadAsStringAsync()))
{
Assert.True(body.RootElement.GetProperty("authenticated").GetBoolean());
Assert.False(body.RootElement.GetProperty("mustChangePassword").GetBoolean());
}
}
private async Task<UserEntity> SeedLocalUserAsync(string username, string password, string roleName)
=> await fixture.WithDbAsync(async db =>
{
+60 -1
View File
@@ -20,7 +20,7 @@ public class RuleEvaluatorTests
memoryBytes,
[new InventoryDisk("SSD", "S1", 1_000_000_000_000, "NVMe")],
[new InventoryVolume("C:", "NTFS", 1_000_000_000_000, 500_000_000_000)],
[new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"])],
[new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"], InterfaceName: "eth0")],
DateTimeOffset.UtcNow);
private static DeviceFieldBag Bag(
@@ -188,5 +188,64 @@ public class RuleEvaluatorTests
Assert.True(RuleEvaluator.Matches(new RuleCondition("memory.totalGb", RuleOperator.GreaterOrEqual, "15"), bag));
Assert.True(RuleEvaluator.Matches(new RuleCondition("network.ipv4", RuleOperator.StartsWith, "10.20."), bag));
Assert.True(RuleEvaluator.Matches(new RuleCondition("os.caption", RuleOperator.Contains, "Windows 11"), bag));
Assert.True(RuleEvaluator.Matches(new RuleCondition("network.interface", RuleOperator.Equals, "eth0"), bag));
}
[Theory]
[InlineData("10.20.0.0/16", true)]
[InlineData("10.20.4.0/24", true)]
// Host bits in the base address are tolerated (normalized to the network).
[InlineData("10.20.4.99/24", true)]
[InlineData("10.30.0.0/16", false)]
[InlineData("192.168.1.0/24, 10.20.0.0/16", true)] // any range in the list
[InlineData("10.20.4.14", true)] // bare IP means equality
[InlineData("10.20.4.15", false)]
[InlineData("not-a-cidr", false)] // invalid input never matches
[InlineData("10.20.4.0/33", false)] // invalid prefix never matches
public void InCidrMatchesAddressesAgainstRanges(string cidr, bool expected)
{
var condition = new RuleCondition("network.ipv4", RuleOperator.InCidr, cidr);
Assert.Equal(expected, RuleEvaluator.Matches(condition, Bag()));
}
[Fact]
public void NotInCidrIsUniversalAcrossAllAddresses()
{
var multiHomed = Bag(inventory: Inventory(ips: ["10.20.4.14", "192.168.50.9"]));
// One address inside the range → NotInCidr fails (must hold for ALL).
Assert.False(RuleEvaluator.Matches(
new RuleCondition("network.ipv4", RuleOperator.NotInCidr, "192.168.0.0/16"), multiHomed));
Assert.True(RuleEvaluator.Matches(
new RuleCondition("network.ipv4", RuleOperator.NotInCidr, "172.16.0.0/12"), multiHomed));
// And InCidr matches when ANY address is inside.
Assert.True(RuleEvaluator.Matches(
new RuleCondition("network.ipv4", RuleOperator.InCidr, "192.168.0.0/16"), multiHomed));
}
[Fact]
public void EnrollmentOsFallbackWorksBeforeTheFirstInventoryReport()
{
// No inventory yet — the device row's OS caption keeps platform
// groups (and the triggers scoped to them) working immediately.
var bag = DeviceFieldBag.Build(
"c1", "PC-001", DeviceStatus.Online, "2026.08.08.1319", null, inventory: null,
fallbackOsCaption: "Windows Server 2022 Datacenter", fallbackOsVersion: "10.0.20348");
Assert.True(RuleEvaluator.Matches(new RuleCondition("os.platform", RuleOperator.Equals, "windows"), bag));
Assert.True(RuleEvaluator.Matches(new RuleCondition("os.caption", RuleOperator.Contains, "Server"), bag));
Assert.False(bag.Has("memory.totalGb"));
}
[Theory]
[InlineData("Windows Server 2022 Datacenter", "windows")]
[InlineData("Windows 11 Pro", "windows")]
[InlineData("Ubuntu 24.04.1 LTS", "linux")]
[InlineData("macOS 15.3", "macos")]
[InlineData("Debian GNU/Linux 12 (bookworm)", "linux")]
public void PlatformDerivesFromOsCaption(string caption, string platform)
{
var bag = Bag(inventory: Inventory(os: caption));
Assert.True(RuleEvaluator.Matches(new RuleCondition("os.platform", RuleOperator.Equals, platform), bag));
}
}