Secrets, schedules-as-objects, group runs, OIDC UX, installer dialog and GPO polish #2

Merged
gsadmin merged 30 commits from dev into main 2026-08-07 22:45:39 +00:00
147 changed files with 20713 additions and 689 deletions
+13 -2
View File
@@ -75,16 +75,27 @@ INITIAL_ADMIN_USERNAME=admin
# Generate: openssl rand -base64 24
INITIAL_ADMIN_PASSWORD=
# ── OIDC (optional) ────────────────────────────────────────────────────────
# ── OIDC (optional; also configurable from Settings → Authentication) ──────
# Register the redirect URI <public-url>/api/auth/oidc/callback at your provider.
# The path is fixed by design — the Settings page shows the exact value.
OIDC_ENABLED=0
OIDC_AUTHORITY=
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
OIDC_CALLBACK_PATH=/signin-oidc
# Friendly name shown on the sign-in button (Authentik, Entra ID, Keycloak…)
OIDC_PROVIDER_NAME=
OIDC_SCOPES=openid profile email
OIDC_NAME_CLAIM=
OIDC_ROLE_CLAIM=
OIDC_ADMIN_ROLE=
OIDC_OPERATOR_ROLE=
OIDC_VIEWER_ROLE=
OIDC_DEFAULT_ROLE=Operator
OIDC_REQUIRE_MAPPED_ROLE=0
# LocalOnly | Both | OidcOnly | OidcAutoRedirect
AUTH_LOGIN_MODE=Both
# Break-glass: 1 bypasses OIDC entirely regardless of saved settings.
AUTH_FORCE_LOCAL=0
# ── NATS decentralized auth (generated — do NOT hand-edit) ─────────────────
# These MUST be real Ed25519 NKeys from scripts/New-LocalSecrets.ps1
+75 -5
View File
@@ -9,10 +9,25 @@ on:
jobs:
build-test:
# Windows is required to build/test the agent (CIM, ConPTY, DPAPI, service).
runs-on: windows
# Label must match a registered runner: windows-host.
runs-on: windows-host
steps:
# This repository uses the SHA-256 object format. actions/checkout
# cannot clone it (it inits a SHA-1 repo then fetches: "mismatched
# algorithms"), so check out with plain git clone, which negotiates
# the object format correctly.
- name: Checkout
uses: actions/checkout@v4
shell: pwsh
env:
CHECKOUT_TOKEN: ${{ github.token }}
run: |
$ErrorActionPreference = 'Stop'
Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
$ref = '${{ github.head_ref }}'
if (-not $ref) { $ref = '${{ github.ref_name }}' }
$url = '${{ github.server_url }}/${{ github.repository }}.git' -replace '^https://', "https://x-access-token:$env:CHECKOUT_TOKEN@"
git clone --depth 1 --branch $ref $url .
git log -1 --format='%H %s'
- name: Setup .NET 10
uses: actions/setup-dotnet@v4
@@ -22,7 +37,8 @@ jobs:
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
# @nats-io/* packages require Node >= 22.
node-version: '22'
- name: Compute unified version
id: ver
@@ -61,6 +77,30 @@ jobs:
run: npm run build
working-directory: src/WebUI
# Package the agent here (only Windows can build it) so the Linux image
# job can bake it into the backend image — no manual seeding at deploy.
- name: Package agent
if: ${{ github.event_name == 'push' }}
shell: pwsh
run: |
./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }}
$stage = 'artifacts/agent-package'
New-Item -ItemType Directory -Force $stage | Out-Null
$msi = "artifacts/Agent-${{ steps.ver.outputs.version }}.msi"
$zip = "artifacts/Agent-${{ steps.ver.outputs.version }}-win-x64.zip"
if (Test-Path $msi) { Copy-Item $msi "$stage/Agent.msi" }
if (Test-Path $zip) { Copy-Item $zip "$stage/Agent.zip" }
'${{ steps.ver.outputs.version }}' | Set-Content "$stage/VERSION" -NoNewline
Get-ChildItem $stage | Select-Object Name, Length
- name: Upload agent package
if: ${{ github.event_name == 'push' }}
uses: actions/upload-artifact@v3
with:
name: agent-package
path: artifacts/agent-package/
retention-days: 7
images:
# Build the backend + webui images and publish them to the Gitea container
# registry. Image names match what docker-compose.yml pulls:
@@ -68,7 +108,8 @@ jobs:
# <gitea-host>/<owner>/executer-webui:<tag>
needs: build-test
if: ${{ github.event_name == 'push' }}
runs-on: ubuntu-latest
# Needs Docker; label must match a registered Linux runner.
runs-on: ubuntu-host
env:
# Gitea's built-in container registry lives on the Gitea host itself and
# needs no configuration: Actions injects GITEA_TOKEN per run and it is
@@ -82,8 +123,19 @@ jobs:
BUILTIN_TOKEN: ${{ secrets.GITEA_TOKEN }}
OWNER: ${{ github.repository_owner }}
steps:
# SHA-256 repo: plain git clone (see build-test).
- name: Checkout
uses: actions/checkout@v4
shell: bash
env:
CHECKOUT_TOKEN: ${{ github.token }}
run: |
set -e
find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true
REF='${{ github.head_ref }}'
[ -z "$REF" ] && REF='${{ github.ref_name }}'
URL="$(echo '${{ github.server_url }}/${{ github.repository }}.git' | sed "s#^https://#https://x-access-token:${CHECKOUT_TOKEN}@#")"
git clone --depth 1 --branch "$REF" "$URL" .
git log -1 --format='%H %s'
- name: Resolve version and registry target
id: ver
@@ -117,6 +169,24 @@ jobs:
- name: Registry login
run: echo "$REGISTRY_LOGIN_PASSWORD" | docker login "${{ steps.ver.outputs.host }}" -u "${{ steps.ver.outputs.user }}" --password-stdin
# Bake the Windows-built agent into the backend image so the URL install
# flow serves it with no manual seeding.
- name: Download agent package
uses: actions/download-artifact@v3
continue-on-error: true
with:
name: agent-package
path: src/Infra/backend/agent-package
- name: Confirm agent package staged
run: |
if ls src/Infra/backend/agent-package/Agent.* >/dev/null 2>&1; then
echo "Agent package will be baked into the backend image:"
ls -la src/Infra/backend/agent-package/
else
echo "::warning::No agent package staged - the backend image will ship without an installer and /api/enrollment/agent-package will 404 until one is mounted or offloaded to S3."
fi
- name: Build images
env:
VERSION: ${{ steps.ver.outputs.version }}
+14 -3
View File
@@ -7,11 +7,22 @@ on:
jobs:
agent-artifacts:
# Publishes the self-contained agent, MSI and checksums, then attaches them
# to a Gitea release for the unified version (when GITEA_TOKEN is available).
runs-on: windows
# to a Gitea release for the unified version.
# Label must match a registered runner: windows-host.
runs-on: windows-host
steps:
# SHA-256 repo: plain git clone (actions/checkout inits SHA-1 and
# cannot fetch from a SHA-256 server).
- name: Checkout
uses: actions/checkout@v4
shell: pwsh
env:
CHECKOUT_TOKEN: ${{ github.token }}
run: |
$ErrorActionPreference = 'Stop'
Get-ChildItem -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
$url = '${{ github.server_url }}/${{ github.repository }}.git' -replace '^https://', "https://x-access-token:$env:CHECKOUT_TOKEN@"
git clone --depth 1 --branch '${{ github.ref_name }}' $url .
git log -1 --format='%H %s'
- name: Setup .NET 10
uses: actions/setup-dotnet@v4
+4
View File
@@ -38,3 +38,7 @@ assets/*.ico
# OS noise
Thumbs.db
.DS_Store
# CI stages the built agent installer here before the backend image build
src/Infra/backend/agent-package/*
!src/Infra/backend/agent-package/.gitkeep
+2
View File
@@ -32,6 +32,7 @@
<!-- Backend -->
<PackageVersion Include="AWSSDK.S3" Version="4.0.102" />
<PackageVersion Include="Cronos" Version="0.11.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.10" />
@@ -47,6 +48,7 @@
<!-- Installer -->
<PackageVersion Include="WixToolset.Util.wixext" Version="5.0.2" />
<PackageVersion Include="WixToolset.UI.wixext" Version="5.0.2" />
<!-- Tests -->
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
+185 -22
View File
@@ -39,15 +39,17 @@ with **no SignalR, SSE, or polling**.
13. [Bootstrap and URL install](#bootstrap-and-url-install)
14. [Local login and OIDC](#local-login-and-oidc)
15. [Typed script parameters and function modules](#typed-script-parameters-and-function-modules)
16. [Device groups and script triggers](#device-groups-and-script-triggers)
17. [Database providers](#database-providers)
18. [Logging](#logging)
19. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan)
20. [S3 file delivery](#s3-file-delivery)
21. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables)
22. [Versioning](#versioning)
23. [MVP demo sequence](#mvp-demo-sequence)
24. [Troubleshooting](#troubleshooting)
16. [Secrets providers and $Secrets](#secrets-providers-and-secrets)
17. [Device groups and script triggers](#device-groups-and-script-triggers)
18. [Group runs and schedules](#group-runs-and-schedules)
19. [Database providers](#database-providers)
20. [Logging](#logging)
21. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan)
22. [S3 file delivery](#s3-file-delivery)
23. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables)
24. [Versioning](#versioning)
25. [MVP demo sequence](#mvp-demo-sequence)
26. [Troubleshooting](#troubleshooting)
---
@@ -333,9 +335,10 @@ processes forwarded headers before auth and trusts them only from configured
`TRUSTED_PROXIES` / `TRUSTED_NETWORKS`. If path-based proxying conflicts with
your NATS WebSocket config, use dedicated hostnames behind the same `:443` edge.
A ready-to-adapt nginx site (nginx-ui style, with shared snippets, edge rate
limiting, long-lived WebSocket timeouts and commented IP allow-lists) is in
[src/Infra/nginx](src/Infra/nginx).
A ready-to-adapt single-file nginx site (nginx-ui style, edge rate limiting,
long-lived WebSocket timeouts and commented IP allow-lists) is in
[src/Infra/nginx](src/Infra/nginx). The OIDC callback (`/api/auth/oidc/callback`)
rides the `/api/*` location — no extra route is needed.
---
@@ -427,7 +430,9 @@ The initial admin is created on first boot from `INITIAL_ADMIN_USERNAME` /
`INITIAL_ADMIN_PASSWORD`. Sessions are HTTP-only cookies with double-submit CSRF
protection on state-changing calls; login is rate limited.
Generic OIDC (any compliant provider — Authentik, Keycloak, Entra ID, Okta):
Generic OIDC (any compliant provider — Authentik, Keycloak, Entra ID, Okta) is
configurable from **Settings → Authentication** (saved values override the
environment and apply without a restart) or bootstrapped via environment:
```text
OIDC_ENABLED=1
@@ -437,11 +442,28 @@ OIDC_CLIENT_SECRET=<secret>
OIDC_SCOPES=openid profile email
OIDC_ROLE_CLAIM=groups
OIDC_ADMIN_ROLE=executer-admins
OIDC_OPERATOR_ROLE=executer-operators
OIDC_VIEWER_ROLE=executer-viewers
AUTH_LOGIN_MODE=Both # LocalOnly | Both | OidcOnly | OidcAutoRedirect
```
Register the redirect URI `<public-url>/api/auth/oidc/callback` at the
provider — the path is fixed by design and shown (copyable) in the Settings UI.
Displayed URLs and generated install commands use `PUBLIC_SERVER_URL` when
set; otherwise they derive from **trusted forwarded headers**, so they are
correct behind the reverse proxy without any configuration.
Roles: **Admin** (everything), **Operator** (view, scripts, run, remote shell,
file delivery), **Viewer** (read-only). A matching `OIDC_ADMIN_ROLE` claim
grants Admin; otherwise OIDC users are Operators.
file delivery), **Viewer** (read-only). Group→role mapping checks Admin →
Operator → Viewer (most privileged wins); unmatched users get the configured
default role, or are refused when *Require mapped role* is on.
**Lockout recovery** (an IdP outage is never terminal):
- `/login?local=1` always reveals the local sign-in form, even in SSO-only modes.
- `docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password '<new>'`
disables OIDC in the database and restores/creates a local admin.
- `AUTH_FORCE_LOCAL=1` (environment only) bypasses stored OIDC settings at startup.
![Login](docs/screenshots/login.png)
@@ -450,10 +472,22 @@ grants Admin; otherwise OIDC users are Operators.
## Typed script parameters and function modules
Scripts can declare typed parameters whose editor input changes by type:
string, number, boolean, array (with element type), and hashtable (with
**per-key and per-value primitive types**). Values are bound to the script with
`AddParameter`, so PowerShell receives real `[int]`, `[bool]`, `[string[]]`, and
`[hashtable]` values.
string, number, boolean, array (with element type), and hashtable. Hashtable
entries are **typed per entry** — every key and value picks its own primitive
(string/number/boolean) as you add it, carried as native JSON and rebuilt by
the agent, so `@{ Name = 'x'; 42 = $true; Retries = 3 }` arrives exactly
typed. Values bind with `AddParameter`, so PowerShell receives real `[int]`,
`[bool]`, `[string[]]`, and `[hashtable]` values. The builder sits in a
full-width strip above the editor (toggle **Define**); run-time values stay in
the side panel next to the target.
String values **expand on the target device automatically** — `%TEMP%`,
`$env:COMPUTERNAME` and `$(…)` resolve with the *device's* environment
(`ExpandEnvironmentVariables`, then `ExpandString` in the job's runspace)
before the script runs. Mark a parameter **Literal** in the builder to opt out
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
script; the backend prepends them as a prelude executed first in the same
@@ -463,6 +497,42 @@ runspace, so individual scripts stay small and duplication is avoided.
---
## Secrets providers and $Secrets
Configure external vaults under **Settings → Secrets providers** (Infisical
first; the driver interface is pluggable). Connection details are stored as a
**Data Protection-encrypted blob**, secret config fields never return to the
browser, and a **Test connection** validates authentication and listing before
you rely on it.
In the script editor's define strip, bind entries of a secrets dictionary to
provider secrets. At dispatch time the **server** resolves every binding and
sends only the values with the job — **devices and browsers never contact the
vault and never hold vault credentials**. The agent injects them as a
**case-insensitive ordered dictionary** session variable (name configurable per
script, default `Secrets`):
```powershell
# Bindings: ApiKey ← Infisical API_KEY, DbPassword ← Infisical DB_PASSWORD
Invoke-RestMethod -Uri $Url -Headers @{ Authorization = "Bearer $($Secrets.ApiKey)" }
$cred = ConvertTo-SecureString $Secrets.dbpassword -AsPlainText -Force # case-insensitive
```
The secret picker **browses the vault**: folders starting from the provider's
default path, then a dropdown of secret names at the chosen path (names only —
values never reach the browser), with manual entry as the fallback when the
vault is unreachable. Saved providers have a per-row **⚡ Test** that validates
the stored credentials without re-entering them. A failed fetch at dispatch
(vault down, secret missing) fails the job with a value-free error naming the
binding and provider. Triggered and scheduled runs resolve secrets the same
way as manual runs.
![Secrets providers](docs/screenshots/settings-secrets.png)
![Script parameters and secrets](docs/screenshots/script-parameters.png)
---
## Device groups and script triggers
Groups are either **static** (an explicit member list) or **dynamic** (rules
@@ -511,6 +581,48 @@ and typed parameters and appear alongside manual runs.
---
## Group runs and schedules
The script editor's target selector offers **devices and groups**. A group run
creates one job per non-orphaned member — offline members receive theirs
durably when they reconnect — and the side panel tracks every job live, with
click-to-focus output per device. Orphaned members are reported as skipped.
**Schedules are reusable cadence objects** — a schedule defines *when*
(one-shot or recurring), nothing else. Scripts honor a schedule through
**assignments**: script + schedule + target (device or group, members resolved
at fire time) + stored run values. One "Nightly at 1am" cadence can drive any
number of scripts, and pausing the cadence pauses everything attached to it.
The cadence builder leads with friendly selectors — *every N minutes/hours*,
*daily/weekly/monthly at a time* with weekday chips — and compiles them to
cron internally; a raw cron field exists only under **Advanced**. Whatever is
chosen is auto-described in plain English and grounded by a server-computed
preview of the next occurrences.
![Schedule builder](docs/screenshots/script-schedule.png)
The **Schedules** nav page manages the cadence objects and shows what uses
each one; the script editor's Schedules panel attaches/detaches them:
![Schedules overview](docs/screenshots/schedules.png)
Semantics worth knowing:
- Expressions evaluate in the schedule's **time zone** (default UTC), so
"daily at 01:00" tracks DST; storage and comparison are UTC.
- The worker sweeps every 30 s; recurrence advances from *now* after each
firing, so server downtime causes **at most one late firing**, never a storm.
- One-shot cadences disable themselves after firing every assignment once.
- Each assignment records its own **last result** (jobs queued, or the error —
e.g. a vault failure) without stalling the cadence, and jobs show
`schedule:<name>` as their requester.
- Deleting a script or a schedule removes its assignments with it.
- Run values captured when a schedule is attached are used for every firing;
secret bindings resolve fresh server-side at each fire time.
---
## Database providers
SQLite is the default and needs no configuration. Postgres and SQL Server are
@@ -617,11 +729,62 @@ the device keeps its history, groups and tags.
---
## Agent installer delivery
**The installer ships inside the backend image — no manual seeding.** The CI
Windows job runs `Package-Agent.ps1`, uploads the result as an artifact, and
the Linux image job stages it into the backend image at `/opt/executer/agent`
before `docker build`. A stock deployment can therefore serve
`/api/enrollment/install` immediately.
The backend resolves the package in this order:
1. `AGENT_PACKAGE_PATH`, when explicitly set
2. `/opt/executer/agent` — baked in by CI
3. `/data/agent` — a manually mounted volume (local builds, air-gapped)
If S3 offload is enabled, `/api/enrollment/agent-package` returns a **302 to a
presigned URL** instead of streaming the file, keeping multi-megabyte
downloads off the control plane. If presigning fails for any reason it falls
back to local delivery rather than breaking installs.
Settings → **Agent installer delivery** shows which source is live, the file
size, version and SHA-256, and offers a one-click upload to S3. Re-uploading an
unchanged build is skipped (the object key is content-addressed by hash).
For a local build without CI:
```powershell
./scripts/Package-Agent.ps1 # writes artifacts/Agent-<version>.msi
# then mount that directory at /data/agent, or set AGENT_PACKAGE_PATH
```
---
## S3 file delivery
Enable an S3-compatible store (`S3_ENABLED=1`; AWS S3, MinIO, Backblaze B2) and
push files from **Device → Actions → Send file**. Credentials stay on the
server — the endpoint only ever sees a short-lived URL.
Configure an S3-compatible store (AWS S3, MinIO, Backblaze B2) from
**Settings → Object storage**, then push files from
**Device → Actions → Send file**. Credentials stay on the server — the endpoint
only ever sees a short-lived URL.
**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.
The **Test connection** button runs a real round-trip and reports each step
separately, so a partial failure is obvious:
| Step | What it proves |
|------|----------------|
| bucket | Credentials valid and the bucket reachable |
| write | The key has `PutObject` |
| read | Content round-trips intact |
| presigned download | The signed URL is fetchable — this is the mechanism agents use, and the step that catches an endpoint reachable from the backend but not from devices |
| delete | The key can clean up after itself |
A probe object is written under `executer-connectivity-check/` and deleted
again. Only a fully passing test records `lastTestUtc`, and agent offload
cannot be enabled until one has passed.
```mermaid
sequenceDiagram
+8 -1
View File
@@ -115,15 +115,22 @@ services:
PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}'
INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}'
INITIAL_ADMIN_PASSWORD: '${INITIAL_ADMIN_PASSWORD:-}'
# The OIDC callback path is fixed at /api/auth/oidc/callback (shown in the UI).
OIDC_ENABLED: '${OIDC_ENABLED:-0}'
OIDC_AUTHORITY: '${OIDC_AUTHORITY:-}'
OIDC_CLIENT_ID: '${OIDC_CLIENT_ID:-}'
OIDC_CLIENT_SECRET: '${OIDC_CLIENT_SECRET:-}'
OIDC_CALLBACK_PATH: '${OIDC_CALLBACK_PATH:-/signin-oidc}'
OIDC_PROVIDER_NAME: '${OIDC_PROVIDER_NAME:-}'
OIDC_SCOPES: '${OIDC_SCOPES:-openid profile email}'
OIDC_NAME_CLAIM: '${OIDC_NAME_CLAIM:-}'
OIDC_ROLE_CLAIM: '${OIDC_ROLE_CLAIM:-}'
OIDC_ADMIN_ROLE: '${OIDC_ADMIN_ROLE:-}'
OIDC_OPERATOR_ROLE: '${OIDC_OPERATOR_ROLE:-}'
OIDC_VIEWER_ROLE: '${OIDC_VIEWER_ROLE:-}'
OIDC_DEFAULT_ROLE: '${OIDC_DEFAULT_ROLE:-Operator}'
OIDC_REQUIRE_MAPPED_ROLE: '${OIDC_REQUIRE_MAPPED_ROLE:-0}'
AUTH_LOGIN_MODE: '${AUTH_LOGIN_MODE:-Both}'
AUTH_FORCE_LOCAL: '${AUTH_FORCE_LOCAL:-0}'
NATS_ACCOUNT_SIGNING_SEED: '${NATS_ACCOUNT_SIGNING_SEED:-}'
NATS_ACCOUNT_PUBLIC_KEY: '${NATS_ACCOUNT_PUBLIC_KEY:-}'
AGENT_PACKAGE_PATH: '${AGENT_PACKAGE_PATH:-/data/agent}'
Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 175 KiB

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 191 KiB

+9
View File
@@ -27,6 +27,15 @@ if (-not $Force -and (Test-Path $output) -and
$magick = Get-Command magick -ErrorAction SilentlyContinue
if (-not $magick) {
# winget only exists in interactive user contexts — CI service accounts
# (LocalSystem) do not have it. The icon is cosmetic (the MSI compiles
# without it via ?ifdef AppIconPath), so degrade to a warning.
$winget = Get-Command winget -ErrorAction SilentlyContinue
if (-not $winget) {
Write-Warning 'ImageMagick and winget are both unavailable — skipping icon generation (MSI builds without an icon).'
return
}
Write-Host 'ImageMagick not found — installing via winget...'
winget install ImageMagick.ImageMagick --silent --accept-package-agreements --accept-source-agreements --disable-interactivity
if ($LASTEXITCODE -ne 0) { throw "winget install of ImageMagick failed ($LASTEXITCODE)." }
+1 -1
View File
@@ -21,7 +21,7 @@ public sealed record AgentCredentials(
/// <summary>
/// DPAPI(LocalMachine)-protected credential persistence in
/// %ProgramData%\&lt;Company&gt;\&lt;Product&gt;\credentials.dat. The file and its
/// %ProgramData%\ExecuteR\credentials.dat. The file and its
/// directory are ACL'd to SYSTEM + Administrators only. Content is a
/// versioned encrypted JSON blob — never a plaintext .creds file.
/// </summary>
+60 -4
View File
@@ -115,31 +115,87 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource)
private static List<InventoryDisk> CollectDisks()
{
var disks = new List<InventoryDisk>();
Query("SELECT Model, SerialNumber, Size, InterfaceType FROM Win32_DiskDrive", obj =>
Query("SELECT Index, Model, SerialNumber, Size, InterfaceType FROM Win32_DiskDrive", obj =>
{
disks.Add(new InventoryDisk(
Model: (obj["Model"] as string)?.Trim(),
SerialNumber: (obj["SerialNumber"] as string)?.Trim(),
SizeBytes: (long?)(obj["Size"] as ulong?) ?? 0,
BusType: obj["InterfaceType"] as string));
BusType: obj["InterfaceType"] as string,
Index: (int?)(obj["Index"] as uint?)));
});
return disks;
}
private static List<InventoryVolume> CollectVolumes()
{
var letterToDisk = MapDriveLettersToDisks();
var volumes = new List<InventoryVolume>();
Query("SELECT DeviceID, FileSystem, Size, FreeSpace FROM Win32_LogicalDisk WHERE DriveType = 3", obj =>
{
var letter = obj["DeviceID"] as string ?? string.Empty;
volumes.Add(new InventoryVolume(
DriveLetter: obj["DeviceID"] as string ?? string.Empty,
DriveLetter: letter,
FileSystem: obj["FileSystem"] as string,
TotalSizeBytes: (long?)(obj["Size"] as ulong?) ?? 0,
FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0));
FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0,
DiskIndex: letterToDisk.TryGetValue(letter, out var index) ? index : null));
});
return volumes;
}
/// <summary>
/// Walks Win32_DiskDriveToDiskPartition and Win32_LogicalDiskToPartition
/// so each drive letter maps back to its physical disk index. The
/// association rows expose object-reference strings; the identifiers are
/// parsed out of them.
/// </summary>
private static Dictionary<string, int> MapDriveLettersToDisks()
{
// Win32_DiskPartition.DeviceID ("Disk #0, Partition #1") → disk index.
var partitionToDisk = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
Query("SELECT Antecedent, Dependent FROM Win32_DiskDriveToDiskPartition", obj =>
{
var driveRef = obj["Antecedent"] as string; // …PHYSICALDRIVE0"
var partitionRef = obj["Dependent"] as string; // …DeviceID="Disk #0, Partition #1"
var indexMatch = System.Text.RegularExpressions.Regex.Match(
driveRef ?? string.Empty, @"PHYSICALDRIVE(\d+)");
var partition = ExtractDeviceId(partitionRef);
if (indexMatch.Success && partition is not null)
{
partitionToDisk[partition] = int.Parse(indexMatch.Groups[1].Value);
}
});
var letterToDisk = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
Query("SELECT Antecedent, Dependent FROM Win32_LogicalDiskToPartition", obj =>
{
var partition = ExtractDeviceId(obj["Antecedent"] as string);
var letter = ExtractDeviceId(obj["Dependent"] as string);
if (partition is not null && letter is not null
&& partitionToDisk.TryGetValue(partition, out var index))
{
letterToDisk[letter] = index;
}
});
return letterToDisk;
}
/// <summary>Pulls the DeviceID value out of a WMI object-reference string.</summary>
private static string? ExtractDeviceId(string? objectReference)
{
if (objectReference is null)
{
return null;
}
var match = System.Text.RegularExpressions.Regex.Match(
objectReference, "DeviceID=\"([^\"]+)\"");
return match.Success ? match.Groups[1].Value.Replace("\\\\", "\\") : null;
}
private static List<InventoryNetworkAdapter> CollectNetwork()
{
var adapters = new List<InventoryNetworkAdapter>();
@@ -25,7 +25,10 @@ public sealed class PowerShellExecutionService
/// Runs <paramref name="prelude"/> (reusable function definitions), if any,
/// then the main <paramref name="scriptContent"/> in the same runspace, so
/// the main script keeps its <c>param()</c> block first while still calling
/// shared functions.
/// shared functions. <paramref name="expansions"/> rewrites string argument
/// values with the device's environment before binding, and
/// <paramref name="sessionVariables"/> are set on the runspace before
/// anything runs (used for the injected secrets dictionary).
/// </summary>
public async Task<PowerShellExecutionResult> ExecuteAsync(
string scriptContent,
@@ -33,12 +36,27 @@ public sealed class PowerShellExecutionService
string? prelude,
Action<NormalizedOutputRecord> onRecord,
Action<NormalizedProgressRecord> onProgress,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
IReadOnlyDictionary<string, Shared.Contracts.Models.ValueExpansion>? expansions = null,
IReadOnlyDictionary<string, object?>? sessionVariables = null)
{
using var runspace = PowerShellRunspaceFactory.Create();
using var powerShell = System.Management.Automation.PowerShell.Create();
powerShell.Runspace = runspace;
if (sessionVariables is not null)
{
foreach (var (name, value) in sessionVariables)
{
runspace.SessionStateProxy.SetVariable(name, value);
}
}
if (parameters is not null && expansions is { Count: > 0 })
{
parameters = ValueExpander.Expand(parameters, expansions, runspace);
}
if (!string.IsNullOrWhiteSpace(prelude))
{
powerShell.AddScript(prelude);
+25 -1
View File
@@ -42,6 +42,28 @@ public sealed class PowerShellJobHandler(
var pending = new List<Task>();
var boundParameters = ScriptArgumentBinder.Bind(command.Parameters, command.Arguments);
// Expansion is the background default; only Literal opts out.
var expansions = command.Parameters?
.Where(p => p.Expansion != ValueExpansion.Literal)
.ToDictionary(p => p.Name, p => p.Expansion, StringComparer.OrdinalIgnoreCase);
// Server-resolved secrets become a case-insensitive ordered
// dictionary session variable ($Secrets.Name by default). Values
// are never logged or published by the agent.
Dictionary<string, object?>? sessionVariables = null;
if (command.Secrets is { Count: > 0 })
{
var secrets = new System.Collections.Specialized.OrderedDictionary(StringComparer.OrdinalIgnoreCase);
foreach (var secret in command.Secrets)
{
secrets[secret.Name] = secret.Value;
}
var variableName = string.IsNullOrWhiteSpace(command.SecretsVariableName)
? "Secrets"
: command.SecretsVariableName;
sessionVariables = new Dictionary<string, object?> { [variableName] = secrets };
}
var result = await executionService.ExecuteAsync(
command.Content,
@@ -49,7 +71,9 @@ public sealed class PowerShellJobHandler(
command.Prelude,
onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
onProgress: progress => pending.Add(PublishProgressAsync(progress)),
cancellationToken: timeoutCts.Token);
cancellationToken: timeoutCts.Token,
expansions: expansions,
sessionVariables: sessionVariables);
await Task.WhenAll(pending);
+26 -20
View File
@@ -54,8 +54,7 @@ public static class ScriptArgumentBinder
ScriptParameterType.Number => ConvertNumber(value),
ScriptParameterType.Boolean => ConvertBoolean(value),
ScriptParameterType.Array => ConvertArray(parameter.ElementType ?? PrimitiveType.String, value),
ScriptParameterType.Hashtable => ConvertHashtable(
parameter.KeyType ?? PrimitiveType.String, parameter.ValueType ?? PrimitiveType.String, value),
ScriptParameterType.Hashtable => ConvertHashtable(value),
_ => value.ToString(),
};
@@ -72,7 +71,15 @@ public static class ScriptArgumentBinder
{
if (value.TryGetInt64(out var l))
{
return l is >= int.MinValue and <= int.MaxValue ? (int)l : l;
// Explicit branches: a conditional expression would widen the
// int back to long before boxing, breaking hashtable key
// equality (boxed long 42 never equals a literal int 42).
if (l is >= int.MinValue and <= int.MaxValue)
{
return (int)l;
}
return l;
}
return value.GetDouble();
@@ -113,10 +120,11 @@ public static class ScriptArgumentBinder
/// <summary>
/// Accepts either a JSON object (string keys) or an array of
/// <c>{ "key": ..., "value": ... }</c> pairs (typed keys) and returns a
/// PowerShell <see cref="Hashtable"/> with coerced keys and values.
/// <c>{ "key": ..., "value": ... }</c> pairs and returns a PowerShell
/// <see cref="Hashtable"/>. Entries are typed per entry: the native JSON
/// kind of each key and value (string/number/boolean) is preserved.
/// </summary>
private static Hashtable ConvertHashtable(PrimitiveType keyType, PrimitiveType valueType, JsonElement value)
private static Hashtable ConvertHashtable(JsonElement value)
{
var table = new Hashtable();
@@ -124,11 +132,7 @@ public static class ScriptArgumentBinder
{
foreach (var property in value.EnumerateObject())
{
var key = ConvertPrimitiveKey(keyType, property.Name);
if (key is not null)
{
table[key] = ConvertPrimitive(valueType, property.Value);
}
table[property.Name] = FromJson(property.Value);
}
}
else if (value.ValueKind == JsonValueKind.Array)
@@ -142,10 +146,10 @@ public static class ScriptArgumentBinder
continue;
}
var key = ConvertPrimitive(keyType, keyElement);
var key = FromJson(keyElement);
if (key is not null)
{
table[key] = ConvertPrimitive(valueType, valueElement);
table[key] = FromJson(valueElement);
}
}
}
@@ -153,11 +157,13 @@ public static class ScriptArgumentBinder
return table;
}
private static object? ConvertPrimitiveKey(PrimitiveType keyType, string rawKey)
=> keyType switch
{
PrimitiveType.Number => long.TryParse(rawKey, out var l) ? l : rawKey,
PrimitiveType.Boolean => bool.TryParse(rawKey, out var b) && b,
_ => rawKey,
};
/// <summary>CLR value matching a JSON element's own kind.</summary>
private static object? FromJson(JsonElement element) => element.ValueKind switch
{
JsonValueKind.Number => ConvertNumber(element),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null or JsonValueKind.Undefined => null,
_ => element.ToString(),
};
}
+78
View File
@@ -0,0 +1,78 @@
using System.Collections;
using System.Management.Automation.Runspaces;
using Shared.Contracts.Models;
namespace Agent.PowerShell;
/// <summary>
/// Expands string argument values on the target device in the background:
/// %VAR% via ExpandEnvironmentVariables, then $env:VAR and $(…) via
/// ExpandString in the job's runspace. Parameters marked
/// <see cref="ValueExpansion.Literal"/> pass through untouched.
/// </summary>
public static class ValueExpander
{
public static IReadOnlyDictionary<string, object?> Expand(
IReadOnlyDictionary<string, object?> values,
IReadOnlyDictionary<string, ValueExpansion> expansions,
Runspace runspace)
{
var result = new Dictionary<string, object?>(values, StringComparer.OrdinalIgnoreCase);
foreach (var (name, mode) in expansions)
{
if (mode == ValueExpansion.Literal || !result.TryGetValue(name, out var value))
{
continue;
}
result[name] = ExpandValue(value, runspace);
}
return result;
}
private static object? ExpandValue(object? value, Runspace runspace) => value switch
{
string s => ExpandString(s, runspace),
object?[] array => array.Select(item => ExpandValue(item, runspace)).ToArray(),
Hashtable table => ExpandHashtableValues(table, runspace),
_ => value,
};
private static Hashtable ExpandHashtableValues(Hashtable table, Runspace runspace)
{
// Keys stay literal — only values are subject to expansion.
var expanded = new Hashtable();
foreach (DictionaryEntry entry in table)
{
expanded[entry.Key] = entry.Value is string s ? ExpandString(s, runspace) : entry.Value;
}
return expanded;
}
private static string ExpandString(string value, Runspace runspace)
{
// %VAR% first (pure .NET), then PowerShell string interpolation.
var expanded = System.Environment.ExpandEnvironmentVariables(value);
// Nothing PowerShell would touch — skip the pipeline round-trip.
if (!expanded.Contains('$') && !expanded.Contains('`'))
{
return expanded;
}
// ExpandString treats the input as double-quoted string content, so
// $env:VAR, $(…) and backtick escapes resolve; passing the raw value
// as an argument keeps embedded quotes from being re-parsed.
using var powerShell = System.Management.Automation.PowerShell.Create();
powerShell.Runspace = runspace;
powerShell
.AddScript("param($s) $ExecutionContext.InvokeCommand.ExpandString($s)")
.AddArgument(expanded);
var results = powerShell.Invoke();
return results.Count > 0 && results[0] is not null ? results[0].ToString() : expanded;
}
}
+2 -1
View File
@@ -103,6 +103,7 @@ public static class DeviceEndpoints
LastSeenUtc: device.LastSeenUtc,
EnrolledUtc: device.EnrolledUtc,
Tags: Groups.DeviceGroupService.ParseTags(device.TagsJson),
IsOrphaned: device.IsOrphaned);
IsOrphaned: device.IsOrphaned,
PublicIp: device.PublicIp);
}
}
+40
View File
@@ -0,0 +1,40 @@
using Shared.Contracts.Models;
namespace Backend.Auth;
/// <summary>
/// Reads the environment bootstrap defaults for authentication. Anything saved
/// from the Settings UI layers on top of these.
/// </summary>
public static class AuthBootstrap
{
public static AuthSettings FromConfiguration(IConfiguration configuration)
{
var mode = configuration["AUTH_LOGIN_MODE"];
return new AuthSettings
{
OidcEnabled = configuration["OIDC_ENABLED"] == "1",
Authority = configuration["OIDC_AUTHORITY"],
ClientId = configuration["OIDC_CLIENT_ID"],
ClientSecret = configuration["OIDC_CLIENT_SECRET"],
ProviderName = configuration["OIDC_PROVIDER_NAME"],
Scopes = string.IsNullOrWhiteSpace(configuration["OIDC_SCOPES"])
? "openid profile email"
: configuration["OIDC_SCOPES"]!,
NameClaim = configuration["OIDC_NAME_CLAIM"],
RoleClaim = configuration["OIDC_ROLE_CLAIM"],
AdminRole = configuration["OIDC_ADMIN_ROLE"],
OperatorRole = configuration["OIDC_OPERATOR_ROLE"],
ViewerRole = configuration["OIDC_VIEWER_ROLE"],
DefaultRole = Enum.TryParse<UserRole>(configuration["OIDC_DEFAULT_ROLE"], true, out var role)
? role
: UserRole.Operator,
RequireMappedRole = configuration["OIDC_REQUIRE_MAPPED_ROLE"] == "1",
LoginMode = Enum.TryParse<LoginMode>(mode, true, out var parsed) ? parsed : LoginMode.Both,
// Break-glass: ignores stored OIDC settings entirely.
ForceLocal = configuration["AUTH_FORCE_LOCAL"] == "1",
};
}
}
+11 -5
View File
@@ -9,7 +9,7 @@ namespace Backend.Auth;
public static class AuthEndpoints
{
public static void Map(WebApplication app, OidcOptions oidc)
public static void Map(WebApplication app)
{
app.MapPost(ApiRoutes.AuthLogin, LoginAsync)
.RequireRateLimiting(RateLimitPolicies.Auth)
@@ -19,10 +19,16 @@ public static class AuthEndpoints
app.MapGet(ApiRoutes.AuthSession, GetSession).AllowAnonymous();
app.MapGet(ApiRoutes.AuthOidcLogin, (HttpContext context) =>
oidc.IsUsable
? Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }, [AuthConstants.OidcScheme])
: Results.NotFound(new { error = "OIDC is not configured." }))
// Challenge only when OIDC is actually usable, so a half-configured or
// disabled provider returns a clear error instead of a broken redirect.
app.MapGet(ApiRoutes.AuthOidcLogin, async (
HttpContext context, AuthSettingsService settings, CancellationToken cancellationToken) =>
{
var effective = await settings.GetEffectiveAsync(cancellationToken);
return effective.IsOidcUsable
? Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }, [AuthConstants.OidcScheme])
: Results.NotFound(new { error = "Single sign-on is not configured." });
})
.AllowAnonymous();
// OIDC completes at CallbackPath (handler-owned); this route lets the
+149 -89
View File
@@ -1,32 +1,44 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Shared.Contracts.Models;
namespace Backend.Auth;
/// <summary>Wires cookie + optional OIDC authentication and role-based authorization.</summary>
/// <summary>Wires cookie + OIDC authentication and role-based authorization.</summary>
public static class AuthExtensions
{
public static void AddControlPlaneAuth(this WebApplicationBuilder builder, OidcOptions oidc)
public static void AddControlPlaneAuth(this WebApplicationBuilder builder, AuthSettings bootstrap)
{
var authBuilder = builder.Services
builder.Services.AddSingleton(bootstrap);
builder.Services.AddSingleton(new AuthSettingsCache(bootstrap));
builder.Services.AddScoped<AuthSettingsService>();
// OpenIdConnectOptions are rebuilt from the settings cache whenever the
// UI saves, so enabling or repointing OIDC needs no restart.
builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureOidc>();
builder.Services.AddSingleton<IOptionsChangeTokenSource<OpenIdConnectOptions>, OidcChangeTokenSource>();
builder.Services
.AddAuthentication(options =>
{
options.DefaultScheme = AuthConstants.CookieScheme;
options.DefaultChallengeScheme = oidc.IsUsable ? AuthConstants.OidcScheme : AuthConstants.CookieScheme;
// Challenges are issued explicitly by the login endpoints, so the
// default stays local; that keeps API 401s from bouncing to an IdP.
options.DefaultChallengeScheme = AuthConstants.CookieScheme;
})
.AddCookie(AuthConstants.CookieScheme, options =>
{
options.Cookie.Name = "executer_session";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
// Lax so the OIDC redirect back to the app carries the cookie.
options.Cookie.SameSite = SameSiteMode.Lax;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromHours(12);
// APIs must return 401/403, never redirect to a login page.
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
@@ -37,88 +49,10 @@ public static class AuthExtensions
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
};
});
if (oidc.IsUsable)
{
authBuilder.AddOpenIdConnect(AuthConstants.OidcScheme, options =>
{
options.Authority = oidc.Authority;
options.ClientId = oidc.ClientId;
options.ClientSecret = oidc.ClientSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.CallbackPath = oidc.CallbackPath;
options.SaveTokens = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.SignInScheme = AuthConstants.CookieScheme;
options.UsePkce = true;
options.Scope.Clear();
foreach (var scope in oidc.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
options.Scope.Add(scope);
}
if (!string.IsNullOrWhiteSpace(oidc.NameClaim))
{
options.TokenValidationParameters.NameClaimType = oidc.NameClaim;
}
if (!string.IsNullOrWhiteSpace(oidc.RoleClaim))
{
options.TokenValidationParameters.RoleClaimType = oidc.RoleClaim;
}
// Upsert the user and stamp the app role claim onto the cookie identity.
options.Events.OnTokenValidated = async context =>
{
var principal = context.Principal;
if (principal?.Identity is not ClaimsIdentity identity)
{
return;
}
var subject = principal.FindFirstValue(ClaimTypes.NameIdentifier)
?? principal.FindFirstValue("sub");
if (string.IsNullOrEmpty(subject))
{
context.Fail("OIDC token has no subject claim.");
return;
}
var username = (oidc.NameClaim is not null ? principal.FindFirstValue(oidc.NameClaim) : null)
?? principal.FindFirstValue(ClaimTypes.Name)
?? principal.FindFirstValue("preferred_username")
?? principal.FindFirstValue(ClaimTypes.Email)
?? subject;
var displayName = principal.FindFirstValue("name") ?? username;
// MVP role mapping: matching admin role claim → Admin, else Operator.
var role = UserRole.Operator;
if (!string.IsNullOrWhiteSpace(oidc.AdminRole) && !string.IsNullOrWhiteSpace(oidc.RoleClaim))
{
var hasAdminRole = principal.FindAll(oidc.RoleClaim)
.Any(c => string.Equals(c.Value, oidc.AdminRole, StringComparison.OrdinalIgnoreCase));
if (hasAdminRole)
{
role = UserRole.Admin;
}
}
var users = context.HttpContext.RequestServices.GetRequiredService<UserService>();
await users.UpsertOidcUserAsync(subject, username, displayName, role, context.HttpContext.RequestAborted);
// Normalize the identity so cookie claims match local users.
identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
identity.AddClaim(new Claim(AuthConstants.ProviderClaim, AuthConstants.ProviderOidc));
identity.AddClaim(new Claim("display_name", displayName));
if (identity.FindFirst(ClaimTypes.Name) is null)
{
identity.AddClaim(new Claim(ClaimTypes.Name, username));
}
};
});
}
})
// Registered unconditionally; ConfigureOidc fills it from current
// settings and the login endpoint refuses to challenge when unusable.
.AddOpenIdConnect(AuthConstants.OidcScheme, _ => { });
builder.Services.AddAuthorization(options =>
{
@@ -131,7 +65,6 @@ public static class AuthExtensions
});
}
/// <summary>Builds the cookie principal for an authenticated user.</summary>
public static ClaimsPrincipal BuildPrincipal(string username, string? displayName, UserRole role, string provider)
{
var identity = new ClaimsIdentity(AuthConstants.CookieScheme, ClaimTypes.Name, ClaimTypes.Role);
@@ -146,3 +79,130 @@ public static class AuthExtensions
return new ClaimsPrincipal(identity);
}
}
/// <summary>Builds OpenIdConnectOptions from the live settings cache.</summary>
internal sealed class ConfigureOidc(AuthSettingsCache cache, IServiceScopeFactory scopeFactory)
: IConfigureNamedOptions<OpenIdConnectOptions>
{
public void Configure(OpenIdConnectOptions options) => Configure(Options.DefaultName, options);
public void Configure(string? name, OpenIdConnectOptions options)
{
if (name != AuthConstants.OidcScheme)
{
return;
}
var settings = cache.Current;
// The OIDC handler is an IAuthenticationRequestHandler, so the
// authentication middleware initializes it on every request — and
// RemoteAuthenticationOptions.Validate() throws on a null Authority or
// ClientId. Placeholders keep validation happy while OIDC is off; the
// login endpoint refuses to challenge unless the real settings are
// usable, so these are never contacted.
options.Authority = string.IsNullOrWhiteSpace(settings.Authority)
? "https://oidc.invalid/not-configured"
: settings.Authority;
options.ClientId = string.IsNullOrWhiteSpace(settings.ClientId)
? "oidc-not-configured"
: settings.ClientId;
options.ClientSecret = settings.ClientSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
// Fixed by design — must match the IdP registration exactly.
options.CallbackPath = AuthSettingsService.CallbackPath;
options.SaveTokens = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.SignInScheme = AuthConstants.CookieScheme;
options.UsePkce = true;
options.Scope.Clear();
foreach (var scope in settings.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
options.Scope.Add(scope);
}
if (!string.IsNullOrWhiteSpace(settings.NameClaim))
{
options.TokenValidationParameters.NameClaimType = settings.NameClaim;
}
if (!string.IsNullOrWhiteSpace(settings.RoleClaim))
{
options.TokenValidationParameters.RoleClaimType = settings.RoleClaim;
}
options.Events.OnTokenValidated = async context =>
{
var current = cache.Current;
if (context.Principal?.Identity is not ClaimsIdentity identity)
{
return;
}
var principal = context.Principal;
var subject = principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? principal.FindFirstValue("sub");
if (string.IsNullOrEmpty(subject))
{
context.Fail("OIDC token has no subject claim.");
return;
}
var username = (current.NameClaim is not null ? principal.FindFirstValue(current.NameClaim) : null)
?? principal.FindFirstValue(ClaimTypes.Name)
?? principal.FindFirstValue("preferred_username")
?? principal.FindFirstValue(ClaimTypes.Email)
?? subject;
var displayName = principal.FindFirstValue("name") ?? username;
// Map identity-provider groups/roles onto an application role.
var claimValues = string.IsNullOrWhiteSpace(current.RoleClaim)
? []
: principal.FindAll(current.RoleClaim).Select(c => c.Value).ToList();
var role = current.MapRole(claimValues);
if (role is null)
{
context.Fail(
"Your account is not a member of any group mapped to an ExecuteR role.");
return;
}
using var scope = scopeFactory.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserService>();
await users.UpsertOidcUserAsync(
subject, username, displayName, role.Value, context.HttpContext.RequestAborted);
identity.AddClaim(new Claim(ClaimTypes.Role, role.Value.ToString()));
identity.AddClaim(new Claim(AuthConstants.ProviderClaim, AuthConstants.ProviderOidc));
identity.AddClaim(new Claim("display_name", displayName));
if (identity.FindFirst(ClaimTypes.Name) is null)
{
identity.AddClaim(new Claim(ClaimTypes.Name, username));
}
};
// Never strand the operator on an IdP error page.
options.Events.OnRemoteFailure = context =>
{
context.Response.Redirect(
"/login?error=" + Uri.EscapeDataString(context.Failure?.Message ?? "Single sign-on failed."));
context.HandleResponse();
return Task.CompletedTask;
};
options.Events.OnAccessDenied = context =>
{
context.Response.Redirect("/login?error=" + Uri.EscapeDataString("Access denied by the identity provider."));
context.HandleResponse();
return Task.CompletedTask;
};
}
}
internal sealed class OidcChangeTokenSource(AuthSettingsCache cache) : IOptionsChangeTokenSource<OpenIdConnectOptions>
{
public string Name => AuthConstants.OidcScheme;
public IChangeToken GetChangeToken() => cache.GetChangeToken();
}
+128
View File
@@ -0,0 +1,128 @@
using Backend.Data;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Models;
namespace Backend.Auth;
/// <summary>
/// Lockout recovery, runnable inside the container:
///
/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset
/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password '&lt;new&gt;'
///
/// Disables OIDC and restores local sign-in, so an identity provider that is
/// down, misconfigured or has revoked the client can never permanently lock an
/// operator out. Optionally resets (or creates) a local admin.
///
/// Setting AUTH_FORCE_LOCAL=1 achieves the same at startup without a database
/// write, which is the faster option if the container will not stay up.
/// </summary>
public static class AuthResetCli
{
public static async Task<int> RunAsync(string[] args, IConfiguration configuration)
{
var username = ArgValue(args, "--admin");
var password = ArgValue(args, "--password");
var databaseOptions = DatabaseOptions.FromConfiguration(configuration);
var services = new ServiceCollection();
services.AddLogging(b => b.AddSimpleConsole());
services.AddDataProtection().PersistKeysToFileSystem(
new DirectoryInfo(DataProtectionPath(configuration)));
services.AddApplicationDatabase(databaseOptions);
services.AddScoped<Settings.SettingsStore>();
await using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// Clear the OIDC flags directly: this must work even when the rest of
// the application cannot start.
foreach (var (key, value) in new[]
{
(AuthSettingsService.Keys.OidcEnabled, "0"),
(AuthSettingsService.Keys.LoginMode, nameof(LoginMode.LocalOnly)),
})
{
var row = await db.AppSettings.SingleOrDefaultAsync(s => s.Key == key);
if (row is null)
{
db.AppSettings.Add(new AppSettingEntity
{
Key = key,
Value = value,
IsSecret = false,
UpdatedUtc = DateTimeOffset.UtcNow,
UpdatedBy = "auth-reset",
});
}
else
{
row.Value = value;
row.UpdatedUtc = DateTimeOffset.UtcNow;
row.UpdatedBy = "auth-reset";
}
}
await db.SaveChangesAsync();
Console.WriteLine("OIDC disabled; local sign-in restored.");
if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
{
var hasher = new PasswordHasher<UserEntity>();
var user = await db.Users.SingleOrDefaultAsync(
u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal);
if (user is null)
{
user = new UserEntity
{
Id = Guid.NewGuid(),
Username = username!,
DisplayName = username,
Role = UserRole.Admin,
AuthProvider = AuthConstants.ProviderLocal,
CreatedUtc = DateTimeOffset.UtcNow,
};
db.Users.Add(user);
Console.WriteLine($"Local admin '{username}' created.");
}
else
{
user.Role = UserRole.Admin;
Console.WriteLine($"Local admin '{username}' password reset and role set to Admin.");
}
user.PasswordHash = hasher.HashPassword(user, password!);
await db.SaveChangesAsync();
}
else
{
Console.WriteLine("Tip: pass --admin <user> --password <pass> to also reset a local admin.");
}
Console.WriteLine("Restart is not required; sign in at /login.");
return 0;
}
private static string DataProtectionPath(IConfiguration configuration)
{
var configured = configuration["DATAPROTECTION_PATH"];
if (!string.IsNullOrWhiteSpace(configured))
{
return configured;
}
var databasePath = configuration["DATABASE_PATH"] ?? "data/app.db";
return Path.Combine(Path.GetDirectoryName(Path.GetFullPath(databasePath)) ?? "data", "keys");
}
private static string? ArgValue(string[] args, string name)
{
var index = Array.IndexOf(args, name);
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
}
}
+95
View File
@@ -0,0 +1,95 @@
using Shared.Contracts.Models;
namespace Backend.Auth;
/// <summary>How the sign-in page behaves.</summary>
public enum LoginMode
{
/// <summary>Local username/password only.</summary>
LocalOnly,
/// <summary>Both local fields and an SSO button.</summary>
Both,
/// <summary>SSO button only — local fields hidden (still reachable, see below).</summary>
OidcOnly,
/// <summary>Redirect straight to the identity provider, no sign-in page.</summary>
OidcAutoRedirect,
}
/// <summary>
/// Effective authentication configuration: values saved from the UI layered
/// over the environment bootstrap defaults.
///
/// The OIDC redirect path is deliberately NOT operator-tunable at runtime — see
/// <see cref="AuthSettingsService.CallbackPath"/>.
/// </summary>
public sealed record AuthSettings
{
public bool OidcEnabled { get; init; }
public string? Authority { get; init; }
public string? ClientId { get; init; }
public string? ClientSecret { get; init; }
/// <summary>Friendly IdP name shown on the sign-in button (e.g. "Authentik", "Entra ID").</summary>
public string? ProviderName { get; init; }
public string Scopes { get; init; } = "openid profile email";
public string? NameClaim { get; init; }
public string? RoleClaim { get; init; }
/// <summary>Claim values mapped to each application role.</summary>
public string? AdminRole { get; init; }
public string? OperatorRole { get; init; }
public string? ViewerRole { get; init; }
/// <summary>Role granted to an authenticated user matching no mapping.</summary>
public UserRole DefaultRole { get; init; } = UserRole.Operator;
/// <summary>Refuse sign-in entirely when no mapping matches.</summary>
public bool RequireMappedRole { get; init; }
public LoginMode LoginMode { get; init; } = LoginMode.LocalOnly;
/// <summary>
/// Emergency switch (env only, never settable from the UI): forces local
/// sign-in regardless of what is stored. See the auth-reset CLI.
/// </summary>
public bool ForceLocal { get; init; }
public bool IsOidcUsable => OidcEnabled
&& !ForceLocal
&& !string.IsNullOrWhiteSpace(Authority)
&& !string.IsNullOrWhiteSpace(ClientId);
/// <summary>Local sign-in is never truly switched off — see the lockout note.</summary>
public bool ShowLocalFields => !IsOidcUsable || LoginMode is LoginMode.LocalOnly or LoginMode.Both;
public bool AutoRedirect => IsOidcUsable && LoginMode == LoginMode.OidcAutoRedirect;
/// <summary>Maps identity-provider claim values to an application role.</summary>
public UserRole? MapRole(IEnumerable<string> claimValues)
{
var values = claimValues.ToList();
bool Matches(string? configured) =>
!string.IsNullOrWhiteSpace(configured)
&& values.Any(v => string.Equals(v, configured, StringComparison.OrdinalIgnoreCase));
if (Matches(AdminRole))
{
return UserRole.Admin;
}
if (Matches(OperatorRole))
{
return UserRole.Operator;
}
if (Matches(ViewerRole))
{
return UserRole.Viewer;
}
return RequireMappedRole ? null : DefaultRole;
}
}
+186
View File
@@ -0,0 +1,186 @@
using Backend.Security;
using Shared.Contracts.Api;
namespace Backend.Auth;
/// <summary>
/// Identity-provider configuration from the UI, plus the anonymous config the
/// sign-in page needs to decide what to render.
/// </summary>
public static class AuthSettingsEndpoints
{
public static void Map(WebApplication app)
{
app.MapGet(ApiRoutes.AuthConfig, GetPublicConfigAsync).AllowAnonymous();
app.MapGet(ApiRoutes.AuthSettings, GetAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
app.MapPut(ApiRoutes.AuthSettings, SaveAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
app.MapPost(ApiRoutes.AuthSettingsTest, TestAsync).RequireAuthorization(AuthConstants.PolicyAdmin);
}
/// <summary>Anonymous: only what the sign-in page needs to render itself.</summary>
private static async Task<IResult> GetPublicConfigAsync(
AuthSettingsService settings, CancellationToken cancellationToken)
{
var effective = await settings.GetEffectiveAsync(cancellationToken);
return Results.Ok(new AuthConfigDto(
OidcAvailable: effective.IsOidcUsable,
ShowLocalFields: effective.ShowLocalFields,
AutoRedirect: effective.AutoRedirect,
// Friendly name (Authentik, Entra ID, …) when set; authority host
// is only the fallback.
ProviderName: effective.IsOidcUsable
? (string.IsNullOrWhiteSpace(effective.ProviderName)
? DescribeAuthority(effective.Authority)
: effective.ProviderName)
: null));
}
private static string? DescribeAuthority(string? authority)
=> Uri.TryCreate(authority, UriKind.Absolute, out var uri) ? uri.Host : authority;
private static async Task<IResult> GetAsync(
AuthSettingsService settings,
HttpContext context,
IConfiguration configuration,
CancellationToken cancellationToken)
{
var effective = await settings.GetEffectiveAsync(cancellationToken);
return Results.Ok(ToDto(effective, context, configuration));
}
private static async Task<IResult> SaveAsync(
AuthSettingsDto request,
AuthSettingsService settings,
AuditService audit,
HttpContext context,
IConfiguration configuration,
CancellationToken cancellationToken)
{
var current = await settings.GetEffectiveAsync(cancellationToken);
if (!Enum.TryParse<LoginMode>(request.LoginMode, true, out var mode))
{
mode = LoginMode.LocalOnly;
}
// Refuse to hide local sign-in behind an IdP that is not usable —
// that is exactly how an instance locks itself out.
var wouldBeUsable = request.OidcEnabled
&& !string.IsNullOrWhiteSpace(request.Authority)
&& !string.IsNullOrWhiteSpace(request.ClientId);
if (!wouldBeUsable && mode is LoginMode.OidcOnly or LoginMode.OidcAutoRedirect)
{
return Results.BadRequest(new
{
error = "Configure and enable OIDC before choosing an SSO-only sign-in mode.",
});
}
var updated = current with
{
OidcEnabled = request.OidcEnabled,
Authority = request.Authority,
ClientId = request.ClientId,
ClientSecret = request.ClientSecret,
ProviderName = request.ProviderName,
Scopes = string.IsNullOrWhiteSpace(request.Scopes) ? "openid profile email" : request.Scopes,
NameClaim = request.NameClaim,
RoleClaim = request.RoleClaim,
AdminRole = request.AdminRole,
OperatorRole = request.OperatorRole,
ViewerRole = request.ViewerRole,
DefaultRole = request.DefaultRole,
RequireMappedRole = request.RequireMappedRole,
LoginMode = mode,
};
await settings.SaveAsync(updated, context.User.Identity?.Name, cancellationToken);
await audit.LogAsync(AuditCategories.Auth, "oidc-settings-updated", context.User.Identity?.Name,
detail: $"enabled={request.OidcEnabled} mode={mode} authority={request.Authority}",
cancellationToken: cancellationToken);
return Results.Ok(ToDto(await settings.GetEffectiveAsync(cancellationToken), context, configuration));
}
/// <summary>Fetches the discovery document so a bad authority is caught before saving.</summary>
private static async Task<IResult> TestAsync(
AuthSettingsDto request, AuthSettingsService settings, CancellationToken cancellationToken)
{
var steps = new List<S3TestStepDto>();
var authority = string.IsNullOrWhiteSpace(request.Authority)
? (await settings.GetEffectiveAsync(cancellationToken)).Authority
: request.Authority;
if (string.IsNullOrWhiteSpace(authority))
{
steps.Add(new S3TestStepDto("authority", false, "Authority is required."));
return Results.Ok(new AuthTestResultDto(false, steps));
}
var discovery = $"{authority.TrimEnd('/')}/.well-known/openid-configuration";
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
using var response = await http.GetAsync(discovery, cancellationToken);
if (!response.IsSuccessStatusCode)
{
steps.Add(new S3TestStepDto("discovery", false,
$"HTTP {(int)response.StatusCode} from {discovery}"));
return Results.Ok(new AuthTestResultDto(false, steps));
}
steps.Add(new S3TestStepDto("discovery", true, $"{discovery} reachable"));
using var document = System.Text.Json.JsonDocument.Parse(
await response.Content.ReadAsStringAsync(cancellationToken));
var root = document.RootElement;
foreach (var required in new[] { "authorization_endpoint", "token_endpoint", "jwks_uri" })
{
var present = root.TryGetProperty(required, out _);
steps.Add(new S3TestStepDto(required, present, present ? "present" : "missing from discovery"));
}
var pkce = root.TryGetProperty("code_challenge_methods_supported", out var methods)
&& methods.EnumerateArray().Any(m => m.GetString() == "S256");
steps.Add(new S3TestStepDto("PKCE (S256)", pkce,
pkce ? "supported" : "not advertised — sign-in may fail"));
}
catch (Exception ex)
{
steps.Add(new S3TestStepDto("discovery", false, ex.Message));
}
return Results.Ok(new AuthTestResultDto(steps.All(s => s.Ok), steps));
}
private static AuthSettingsDto ToDto(AuthSettings s, HttpContext context, IConfiguration configuration)
{
// PUBLIC_SERVER_URL wins so the IdP registration matches what agents
// and browsers actually use, even when an admin browses via an
// internal hostname; trusted forwarded headers are the fallback.
var origin = Backend.Proxy.PublicUrl.Resolve(context, configuration);
return new AuthSettingsDto(
OidcEnabled: s.OidcEnabled,
Authority: s.Authority,
ClientId: s.ClientId,
ClientSecret: null,
ProviderName: s.ProviderName,
Scopes: s.Scopes,
NameClaim: s.NameClaim,
RoleClaim: s.RoleClaim,
AdminRole: s.AdminRole,
OperatorRole: s.OperatorRole,
ViewerRole: s.ViewerRole,
DefaultRole: s.DefaultRole,
RequireMappedRole: s.RequireMappedRole,
LoginMode: s.LoginMode.ToString(),
ClientSecretIsSet: !string.IsNullOrWhiteSpace(s.ClientSecret),
ForcedLocalByEnvironment: s.ForceLocal,
CallbackPath: AuthSettingsService.CallbackPath,
RedirectUri: origin + AuthSettingsService.CallbackPath);
}
}
+144
View File
@@ -0,0 +1,144 @@
using Backend.Settings;
using Microsoft.Extensions.Primitives;
using Shared.Contracts.Models;
namespace Backend.Auth;
/// <summary>
/// Resolves effective auth settings (database over environment) and caches
/// them for the OIDC handler, which cannot take a scoped dependency.
///
/// Saving triggers a change token so the handler is rebuilt without a restart.
/// </summary>
public sealed class AuthSettingsService(SettingsStore store, AuthSettings environmentDefaults, AuthSettingsCache cache)
{
public const string Prefix = "auth.";
/// <summary>
/// The OIDC redirect path is fixed. It must match what is registered at the
/// identity provider exactly, and letting it drift at runtime is a reliable
/// way to break sign-in with no obvious cause. It lives under /api/ so the
/// reverse proxy's existing API location covers it, and it is shown in the
/// UI so it can be copied into the IdP verbatim.
/// </summary>
public const string CallbackPath = Shared.Contracts.Api.ApiRoutes.AuthOidcCallback;
public static class Keys
{
public const string OidcEnabled = Prefix + "oidcEnabled";
public const string Authority = Prefix + "authority";
public const string ClientId = Prefix + "clientId";
public const string ClientSecret = Prefix + "clientSecret";
public const string ProviderName = Prefix + "providerName";
public const string Scopes = Prefix + "scopes";
public const string NameClaim = Prefix + "nameClaim";
public const string RoleClaim = Prefix + "roleClaim";
public const string AdminRole = Prefix + "adminRole";
public const string OperatorRole = Prefix + "operatorRole";
public const string ViewerRole = Prefix + "viewerRole";
public const string DefaultRole = Prefix + "defaultRole";
public const string RequireMappedRole = Prefix + "requireMappedRole";
public const string LoginMode = Prefix + "loginMode";
}
public async Task<AuthSettings> GetEffectiveAsync(CancellationToken cancellationToken)
{
var saved = await store.GetAllAsync(Prefix, cancellationToken);
var effective = Merge(saved, environmentDefaults);
cache.Set(effective);
return effective;
}
internal static AuthSettings Merge(IReadOnlyDictionary<string, string> saved, AuthSettings defaults) => new()
{
OidcEnabled = Bool(saved, Keys.OidcEnabled, defaults.OidcEnabled),
Authority = Str(saved, Keys.Authority, defaults.Authority),
ClientId = Str(saved, Keys.ClientId, defaults.ClientId),
ClientSecret = Str(saved, Keys.ClientSecret, defaults.ClientSecret),
ProviderName = Str(saved, Keys.ProviderName, defaults.ProviderName),
Scopes = Str(saved, Keys.Scopes, defaults.Scopes) ?? "openid profile email",
NameClaim = Str(saved, Keys.NameClaim, defaults.NameClaim),
RoleClaim = Str(saved, Keys.RoleClaim, defaults.RoleClaim),
AdminRole = Str(saved, Keys.AdminRole, defaults.AdminRole),
OperatorRole = Str(saved, Keys.OperatorRole, defaults.OperatorRole),
ViewerRole = Str(saved, Keys.ViewerRole, defaults.ViewerRole),
DefaultRole = Enum.TryParse<UserRole>(Str(saved, Keys.DefaultRole, null), true, out var role)
? role
: defaults.DefaultRole,
RequireMappedRole = Bool(saved, Keys.RequireMappedRole, defaults.RequireMappedRole),
LoginMode = Enum.TryParse<LoginMode>(Str(saved, Keys.LoginMode, null), true, out var mode)
? mode
: defaults.LoginMode,
// Never persisted: environment-only escape hatch.
ForceLocal = defaults.ForceLocal,
};
public async Task SaveAsync(AuthSettings settings, string? actor, CancellationToken cancellationToken)
{
await store.SetAsync(Keys.OidcEnabled, settings.OidcEnabled ? "1" : "0", false, actor, cancellationToken);
await store.SetAsync(Keys.Authority, settings.Authority, false, actor, cancellationToken);
await store.SetAsync(Keys.ClientId, settings.ClientId, false, actor, cancellationToken);
await store.SetAsync(Keys.ProviderName, settings.ProviderName, false, actor, cancellationToken);
await store.SetAsync(Keys.Scopes, settings.Scopes, false, actor, cancellationToken);
await store.SetAsync(Keys.NameClaim, settings.NameClaim, false, actor, cancellationToken);
await store.SetAsync(Keys.RoleClaim, settings.RoleClaim, false, actor, cancellationToken);
await store.SetAsync(Keys.AdminRole, settings.AdminRole, false, actor, cancellationToken);
await store.SetAsync(Keys.OperatorRole, settings.OperatorRole, false, actor, cancellationToken);
await store.SetAsync(Keys.ViewerRole, settings.ViewerRole, false, actor, cancellationToken);
await store.SetAsync(Keys.DefaultRole, settings.DefaultRole.ToString(), false, actor, cancellationToken);
await store.SetAsync(
Keys.RequireMappedRole, settings.RequireMappedRole ? "1" : "0", false, actor, cancellationToken);
await store.SetAsync(Keys.LoginMode, settings.LoginMode.ToString(), false, actor, cancellationToken);
// Null secret means "keep the stored one".
if (!string.IsNullOrWhiteSpace(settings.ClientSecret))
{
await store.SetAsync(Keys.ClientSecret, settings.ClientSecret, true, actor, cancellationToken);
}
// Rebuild the OIDC handler with the new values.
cache.Set(await GetEffectiveAsync(cancellationToken));
cache.Reload();
}
/// <summary>Disables OIDC and restores local sign-in. Used by the auth-reset CLI.</summary>
public async Task ResetToLocalAsync(string? actor, CancellationToken cancellationToken)
{
await store.SetAsync(Keys.OidcEnabled, "0", false, actor, cancellationToken);
await store.SetAsync(Keys.LoginMode, nameof(LoginMode.LocalOnly), false, actor, cancellationToken);
cache.Set(await GetEffectiveAsync(cancellationToken));
cache.Reload();
}
public AuthSettings EnvironmentDefaults => environmentDefaults;
private static string? Str(IReadOnlyDictionary<string, string> saved, string key, string? fallback)
=> saved.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback;
private static bool Bool(IReadOnlyDictionary<string, string> saved, string key, bool fallback)
=> saved.TryGetValue(key, out var value) ? value is "1" or "true" or "True" : fallback;
}
/// <summary>
/// Holds the current effective auth settings for the OIDC handler (a singleton
/// that cannot resolve scoped services), and signals options reload on change.
/// </summary>
public sealed class AuthSettingsCache(AuthSettings initial)
{
private AuthSettings current = initial;
private CancellationTokenSource changeSource = new();
public AuthSettings Current => Volatile.Read(ref current);
public void Set(AuthSettings settings) => Volatile.Write(ref current, settings);
public IChangeToken GetChangeToken() => new CancellationChangeToken(changeSource.Token);
/// <summary>Invalidates cached OpenIdConnectOptions so they are rebuilt.</summary>
public void Reload()
{
var previous = Interlocked.Exchange(ref changeSource, new CancellationTokenSource());
previous.Cancel();
previous.Dispose();
}
}
-36
View File
@@ -1,36 +0,0 @@
namespace Backend.Auth;
/// <summary>Generic OIDC configuration (works with any compliant provider).</summary>
public sealed class OidcOptions
{
public bool Enabled { get; init; }
public string? Authority { get; init; }
public string? ClientId { get; init; }
public string? ClientSecret { get; init; }
public string CallbackPath { get; init; } = "/signin-oidc";
public string Scopes { get; init; } = "openid profile email";
public string? NameClaim { get; init; }
public string? RoleClaim { get; init; }
public string? AdminRole { get; init; }
public bool IsUsable => Enabled
&& !string.IsNullOrWhiteSpace(Authority)
&& !string.IsNullOrWhiteSpace(ClientId);
public static OidcOptions FromConfiguration(IConfiguration configuration) => new()
{
Enabled = configuration["OIDC_ENABLED"] == "1",
Authority = configuration["OIDC_AUTHORITY"],
ClientId = configuration["OIDC_CLIENT_ID"],
ClientSecret = configuration["OIDC_CLIENT_SECRET"],
CallbackPath = string.IsNullOrWhiteSpace(configuration["OIDC_CALLBACK_PATH"])
? "/signin-oidc"
: configuration["OIDC_CALLBACK_PATH"]!,
Scopes = string.IsNullOrWhiteSpace(configuration["OIDC_SCOPES"])
? "openid profile email"
: configuration["OIDC_SCOPES"]!,
NameClaim = configuration["OIDC_NAME_CLAIM"],
RoleClaim = configuration["OIDC_ROLE_CLAIM"],
AdminRole = configuration["OIDC_ADMIN_ROLE"],
};
}
+5
View File
@@ -6,8 +6,13 @@
<UserSecretsId>backend-dev-secrets</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Backend.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" />
<PackageReference Include="Cronos" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
+37
View File
@@ -21,6 +21,10 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
public DbSet<DeviceGroupMemberEntity> DeviceGroupMembers => Set<DeviceGroupMemberEntity>();
public DbSet<ScriptTriggerEntity> ScriptTriggers => Set<ScriptTriggerEntity>();
public DbSet<ScriptTriggerRunEntity> ScriptTriggerRuns => Set<ScriptTriggerRunEntity>();
public DbSet<AppSettingEntity> AppSettings => Set<AppSettingEntity>();
public DbSet<SecretsProviderEntity> SecretsProviders => Set<SecretsProviderEntity>();
public DbSet<ScheduleEntity> Schedules => Set<ScheduleEntity>();
public DbSet<ScriptScheduleEntity> ScriptSchedules => Set<ScriptScheduleEntity>();
/// <summary>
/// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores
@@ -156,5 +160,38 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
entity.HasKey(e => e.Id);
entity.HasIndex(e => new { e.TriggerId, e.ClientId }).IsUnique();
});
modelBuilder.Entity<AppSettingEntity>(entity =>
{
entity.ToTable("AppSettings");
entity.HasKey(e => e.Key);
});
modelBuilder.Entity<SecretsProviderEntity>(entity =>
{
entity.ToTable("SecretsProviders");
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.Name).IsUnique();
});
modelBuilder.Entity<ScheduleEntity>(entity =>
{
entity.ToTable("Schedules");
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.Name).IsUnique();
entity.HasIndex(e => e.NextRunUtc);
});
modelBuilder.Entity<ScriptScheduleEntity>(entity =>
{
entity.ToTable("ScriptSchedules");
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.ScheduleId);
entity.HasIndex(e => e.ScriptId);
entity.HasOne<ScheduleEntity>().WithMany()
.HasForeignKey(e => e.ScheduleId).OnDelete(DeleteBehavior.Cascade);
entity.HasOne<ScriptEntity>().WithMany()
.HasForeignKey(e => e.ScriptId).OnDelete(DeleteBehavior.Cascade);
});
}
}
+10 -2
View File
@@ -43,6 +43,7 @@ public static class DevSeeder
EnrollmentId = Guid.NewGuid(),
EnrolledUtc = now.AddDays(-i - 1),
LastSeenUtc = now - seenAgo,
PublicIp = $"203.0.113.{40 + i}",
IpAddressesJson = JsonSerializer.Serialize(ips, JsonDefaults.Options),
TagsJson = JsonSerializer.Serialize(tags, JsonDefaults.Options),
};
@@ -54,8 +55,15 @@ public static class DevSeeder
new InventoryCpu("Intel(R) Core(TM) i7-11700 @ 2.50GHz", 16, 8),
[new InventoryMemoryModule("DIMM A", 17_179_869_184, "Samsung", 3200), new InventoryMemoryModule("DIMM B", 17_179_869_184, "Samsung", 3200)],
34_359_738_368,
[new InventoryDisk("Samsung SSD 980 1TB", $"S{i}XYZ", 1_000_204_886_016, "NVMe")],
[new InventoryVolume("C:", "NTFS", 1_000_204_886_016, 512_204_886_016)],
[
new InventoryDisk("Samsung SSD 980 1TB", $"S{i}XYZ", 1_000_204_886_016, "NVMe", Index: 0),
new InventoryDisk("WDC WD40EZRZ 4TB", $"WD{i}ABC", 4_000_787_030_016, "SATA", Index: 1),
],
[
new InventoryVolume("C:", "NTFS", 511_000_000_000, 198_500_000_000, DiskIndex: 0),
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"])],
now - seenAgo);
+88
View File
@@ -53,6 +53,12 @@ public sealed class DeviceEntity
public bool IsOrphaned { get; set; }
public DateTimeOffset? OrphanedUtc { get; set; }
/// <summary>
/// Public IP the agent was last seen from, resolved through trusted
/// forwarded headers at enrollment and credential refresh.
/// </summary>
public string? PublicIp { get; set; }
public DeviceInventoryEntity? Inventory { get; set; }
}
@@ -125,12 +131,94 @@ public sealed class ScriptEntity
public string? ParametersJson { get; set; }
/// <summary>JSON array of attached FunctionModule ids (prepended at run time).</summary>
public string? FunctionModuleIdsJson { get; set; }
/// <summary>JSON array of SecretBinding definitions (resolved server-side at dispatch).</summary>
public string? SecretBindingsJson { get; set; }
/// <summary>Session variable the resolved secrets dictionary binds to (default "Secrets").</summary>
public string? SecretsVariableName { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? CreatedBy { get; set; }
public string? UpdatedBy { get; set; }
}
/// <summary>
/// A reusable cadence object: one-shot (<see cref="RunOnceUtc"/>) or recurring
/// (<see cref="CronExpression"/>, evaluated in <see cref="TimeZoneId"/>).
/// Schedules carry no script or target — objects (scripts) honor a schedule
/// through <see cref="ScriptScheduleEntity"/> associations.
/// </summary>
public sealed class ScheduleEntity
{
public Guid Id { get; set; }
public required string Name { get; set; }
/// <summary>5-field cron for recurring schedules; null for one-shot.</summary>
public string? CronExpression { get; set; }
/// <summary>Fire time for one-shot schedules; null for recurring.</summary>
public DateTimeOffset? RunOnceUtc { get; set; }
public string TimeZoneId { get; set; } = "UTC";
public bool Enabled { get; set; } = true;
public DateTimeOffset? NextRunUtc { get; set; }
public DateTimeOffset? LastRunUtc { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? CreatedBy { get; set; }
public string? UpdatedBy { get; set; }
}
/// <summary>
/// A script honoring a schedule: when the schedule fires, this script runs
/// against exactly one of <see cref="ClientId"/> / <see cref="GroupId"/>
/// (group members resolved at fire time) with the stored argument values.
/// </summary>
public sealed class ScriptScheduleEntity
{
public Guid Id { get; set; }
public required Guid ScheduleId { get; set; }
public required Guid ScriptId { get; set; }
public string? ClientId { get; set; }
public Guid? GroupId { get; set; }
/// <summary>Argument values captured when the association was saved.</summary>
public string? ArgumentsJson { get; set; }
public bool Enabled { get; set; } = true;
public DateTimeOffset? LastRunUtc { get; set; }
/// <summary>Human-readable outcome of the last firing (job counts or the error).</summary>
public string? LastResult { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public string? CreatedBy { get; set; }
}
/// <summary>
/// A configured external secrets store (e.g. Infisical). Connection settings
/// are a Data Protection-encrypted JSON blob; only the backend ever decrypts
/// them, and secret values are fetched server-side at job dispatch.
/// </summary>
public sealed class SecretsProviderEntity
{
public Guid Id { get; set; }
public required string Name { get; set; }
/// <summary>Driver kind, e.g. "infisical".</summary>
public required string Kind { get; set; }
/// <summary>Encrypted driver-specific config JSON.</summary>
public required string ConfigProtected { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? UpdatedBy { get; set; }
}
/// <summary>
/// Operator-editable application settings that override environment defaults.
/// Values marked secret are encrypted at rest with ASP.NET Data Protection and
/// are never returned to the browser.
/// </summary>
public sealed class AppSettingEntity
{
public required string Key { get; set; }
public string? Value { get; set; }
public bool IsSecret { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? UpdatedBy { get; set; }
}
/// <summary>Reusable PowerShell function library prepended to referencing scripts.</summary>
public sealed class FunctionModuleEntity
{
@@ -0,0 +1,606 @@
// <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("20260807135644_AddAppSettings")]
partial class AddAppSettings
{
/// <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<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.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>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("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.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<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,37 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddAppSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AppSettings",
columns: table => new
{
Key = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true),
IsSecret = table.Column<bool>(type: "boolean", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedBy = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AppSettings", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AppSettings");
}
}
}
@@ -0,0 +1,647 @@
// <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("20260807150650_AddSecretsProviders")]
partial class AddSecretsProviders
{
/// <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<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.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.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<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,65 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddSecretsProviders : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "SecretBindingsJson",
table: "Scripts",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SecretsVariableName",
table: "Scripts",
type: "text",
nullable: true);
migrationBuilder.CreateTable(
name: "SecretsProviders",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Kind = table.Column<string>(type: "text", nullable: false),
ConfigProtected = table.Column<string>(type: "text", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedBy = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SecretsProviders", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_SecretsProviders_Name",
table: "SecretsProviders",
column: "Name",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SecretsProviders");
migrationBuilder.DropColumn(
name: "SecretBindingsJson",
table: "Scripts");
migrationBuilder.DropColumn(
name: "SecretsVariableName",
table: "Scripts");
}
}
}
@@ -0,0 +1,711 @@
// <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("20260807153218_AddScheduledRuns")]
partial class AddScheduledRuns
{
/// <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<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.ScheduledRunEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ArgumentsJson")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("CronExpression")
.HasColumnType("text");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<Guid?>("GroupId")
.HasColumnType("uuid");
b.Property<string>("LastResult")
.HasColumnType("text");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("ScriptId")
.HasColumnType("uuid");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("ScriptId");
b.ToTable("ScheduledRuns", (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.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<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class AddScheduledRuns : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ScriptId = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: true),
ClientId = table.Column<string>(type: "text", nullable: true),
GroupId = table.Column<Guid>(type: "uuid", nullable: true),
CronExpression = table.Column<string>(type: "text", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
TimeZoneId = table.Column<string>(type: "text", nullable: false),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
ArgumentsJson = table.Column<string>(type: "text", nullable: true),
NextRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LastResult = table.Column<string>(type: "text", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CreatedBy = table.Column<string>(type: "text", nullable: true),
UpdatedBy = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
}
}
}
@@ -0,0 +1,758 @@
// <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("20260807165542_ScheduleObjects")]
partial class ScheduleObjects
{
/// <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<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.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<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.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,141 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class ScheduleObjects : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
CronExpression = table.Column<string>(type: "text", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
TimeZoneId = table.Column<string>(type: "text", nullable: false),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
NextRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CreatedBy = table.Column<string>(type: "text", nullable: true),
UpdatedBy = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Schedules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScriptSchedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ScheduleId = table.Column<Guid>(type: "uuid", nullable: false),
ScriptId = table.Column<Guid>(type: "uuid", nullable: false),
ClientId = table.Column<string>(type: "text", nullable: true),
GroupId = table.Column<Guid>(type: "uuid", nullable: true),
ArgumentsJson = table.Column<string>(type: "text", nullable: true),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LastResult = table.Column<string>(type: "text", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CreatedBy = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScriptSchedules", x => x.Id);
table.ForeignKey(
name: "FK_ScriptSchedules_Schedules_ScheduleId",
column: x => x.ScheduleId,
principalTable: "Schedules",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ScriptSchedules_Scripts_ScriptId",
column: x => x.ScriptId,
principalTable: "Scripts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Schedules_Name",
table: "Schedules",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Schedules_NextRunUtc",
table: "Schedules",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScheduleId",
table: "ScriptSchedules",
column: "ScheduleId");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScriptId",
table: "ScriptSchedules",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ArgumentsJson = table.Column<string>(type: "text", nullable: true),
ClientId = table.Column<string>(type: "text", nullable: true),
CreatedBy = table.Column<string>(type: "text", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CronExpression = table.Column<string>(type: "text", nullable: true),
Enabled = table.Column<bool>(type: "boolean", nullable: false),
GroupId = table.Column<Guid>(type: "uuid", nullable: true),
LastResult = table.Column<string>(type: "text", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
Name = table.Column<string>(type: "text", nullable: true),
NextRunUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
ScriptId = table.Column<Guid>(type: "uuid", nullable: false),
TimeZoneId = table.Column<string>(type: "text", nullable: false),
UpdatedBy = table.Column<string>(type: "text", nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
}
}
@@ -0,0 +1,761 @@
// <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("20260807185828_AddDevicePublicIp")]
partial class AddDevicePublicIp
{
/// <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.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<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.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.Postgres
{
/// <inheritdoc />
public partial class AddDevicePublicIp : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "PublicIp",
table: "Devices",
type: "text",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PublicIp",
table: "Devices");
}
}
}
@@ -22,6 +22,28 @@ namespace Backend.Data.Migrations.Postgres
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")
@@ -145,6 +167,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<string>("OsVersion")
.HasColumnType("text");
b.Property<string>("PublicIp")
.HasColumnType("text");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("timestamp with time zone");
@@ -378,6 +403,57 @@ namespace Backend.Data.Migrations.Postgres
b.ToTable("OidcProviders", (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")
@@ -411,6 +487,12 @@ namespace Backend.Data.Migrations.Postgres
b.Property<string>("ParametersJson")
.HasColumnType("text");
b.Property<string>("SecretBindingsJson")
.HasColumnType("text");
b.Property<string>("SecretsVariableName")
.HasColumnType("text");
b.Property<string>("UpdatedBy")
.HasColumnType("text");
@@ -424,6 +506,51 @@ namespace Backend.Data.Migrations.Postgres
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")
@@ -488,6 +615,41 @@ namespace Backend.Data.Migrations.Postgres
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")
@@ -571,6 +733,21 @@ namespace Backend.Data.Migrations.Postgres
.IsRequired();
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.HasOne("Backend.Data.ScheduleEntity", null)
.WithMany()
.HasForeignKey("ScheduleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Backend.Data.ScriptEntity", null)
.WithMany()
.HasForeignKey("ScriptId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
@@ -0,0 +1,606 @@
// <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("20260807135650_AddAppSettings")]
partial class AddAppSettings
{
/// <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<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.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>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("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.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<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,37 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddAppSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AppSettings",
columns: table => new
{
Key = table.Column<string>(type: "nvarchar(450)", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsSecret = table.Column<bool>(type: "bit", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AppSettings", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AppSettings");
}
}
}
@@ -0,0 +1,647 @@
// <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("20260807150654_AddSecretsProviders")]
partial class AddSecretsProviders
{
/// <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<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.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.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<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,65 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddSecretsProviders : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "SecretBindingsJson",
table: "Scripts",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SecretsVariableName",
table: "Scripts",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.CreateTable(
name: "SecretsProviders",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
Kind = table.Column<string>(type: "nvarchar(max)", nullable: false),
ConfigProtected = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SecretsProviders", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_SecretsProviders_Name",
table: "SecretsProviders",
column: "Name",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SecretsProviders");
migrationBuilder.DropColumn(
name: "SecretBindingsJson",
table: "Scripts");
migrationBuilder.DropColumn(
name: "SecretsVariableName",
table: "Scripts");
}
}
}
@@ -0,0 +1,711 @@
// <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("20260807153221_AddScheduledRuns")]
partial class AddScheduledRuns
{
/// <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<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.ScheduledRunEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ArgumentsJson")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("CronExpression")
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<Guid?>("GroupId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LastResult")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("LastRunUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("NextRunUtc")
.HasColumnType("datetimeoffset");
b.Property<DateTimeOffset?>("RunOnceUtc")
.HasColumnType("datetimeoffset");
b.Property<Guid>("ScriptId")
.HasColumnType("uniqueidentifier");
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("NextRunUtc");
b.HasIndex("ScriptId");
b.ToTable("ScheduledRuns", (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.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<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class AddScheduledRuns : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ScriptId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClientId = table.Column<string>(type: "nvarchar(max)", nullable: true),
GroupId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
CronExpression = table.Column<string>(type: "nvarchar(max)", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
TimeZoneId = table.Column<string>(type: "nvarchar(max)", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
ArgumentsJson = table.Column<string>(type: "nvarchar(max)", nullable: true),
NextRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LastResult = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
}
}
}
@@ -0,0 +1,758 @@
// <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("20260807165546_ScheduleObjects")]
partial class ScheduleObjects
{
/// <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<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.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<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
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,141 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class ScheduleObjects : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(450)", nullable: false),
CronExpression = table.Column<string>(type: "nvarchar(max)", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
TimeZoneId = table.Column<string>(type: "nvarchar(max)", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
NextRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Schedules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScriptSchedules",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ScheduleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ScriptId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ClientId = table.Column<string>(type: "nvarchar(max)", nullable: true),
GroupId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
ArgumentsJson = table.Column<string>(type: "nvarchar(max)", nullable: true),
Enabled = table.Column<bool>(type: "bit", nullable: false),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
LastResult = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScriptSchedules", x => x.Id);
table.ForeignKey(
name: "FK_ScriptSchedules_Schedules_ScheduleId",
column: x => x.ScheduleId,
principalTable: "Schedules",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ScriptSchedules_Scripts_ScriptId",
column: x => x.ScriptId,
principalTable: "Scripts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Schedules_Name",
table: "Schedules",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Schedules_NextRunUtc",
table: "Schedules",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScheduleId",
table: "ScriptSchedules",
column: "ScheduleId");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScriptId",
table: "ScriptSchedules",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ArgumentsJson = table.Column<string>(type: "nvarchar(max)", nullable: true),
ClientId = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CronExpression = table.Column<string>(type: "nvarchar(max)", nullable: true),
Enabled = table.Column<bool>(type: "bit", nullable: false),
GroupId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
LastResult = table.Column<string>(type: "nvarchar(max)", nullable: true),
LastRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
NextRunUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
RunOnceUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
ScriptId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
TimeZoneId = table.Column<string>(type: "nvarchar(max)", nullable: false),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
}
}
@@ -0,0 +1,761 @@
// <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("20260807185831_AddDevicePublicIp")]
partial class AddDevicePublicIp
{
/// <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.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<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
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 AddDevicePublicIp : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "PublicIp",
table: "Devices",
type: "nvarchar(max)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PublicIp",
table: "Devices");
}
}
}
@@ -22,6 +22,28 @@ namespace Backend.Data.Migrations.SqlServer
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")
@@ -145,6 +167,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<string>("OsVersion")
.HasColumnType("nvarchar(max)");
b.Property<string>("PublicIp")
.HasColumnType("nvarchar(max)");
b.Property<DateTimeOffset?>("ReadyUtc")
.HasColumnType("datetimeoffset");
@@ -378,6 +403,57 @@ namespace Backend.Data.Migrations.SqlServer
b.ToTable("OidcProviders", (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")
@@ -411,6 +487,12 @@ namespace Backend.Data.Migrations.SqlServer
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)");
@@ -424,6 +506,51 @@ namespace Backend.Data.Migrations.SqlServer
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")
@@ -488,6 +615,41 @@ namespace Backend.Data.Migrations.SqlServer
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")
@@ -571,6 +733,21 @@ namespace Backend.Data.Migrations.SqlServer
.IsRequired();
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.HasOne("Backend.Data.ScheduleEntity", null)
.WithMany()
.HasForeignKey("ScheduleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Backend.Data.ScriptEntity", null)
.WithMany()
.HasForeignKey("ScriptId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
@@ -0,0 +1,593 @@
// <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("20260807135638_AddAppSettings")]
partial class AddAppSettings
{
/// <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<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.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>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Scripts", (string)null);
});
modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("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.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<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddAppSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AppSettings",
columns: table => new
{
Key = table.Column<string>(type: "TEXT", nullable: false),
Value = table.Column<string>(type: "TEXT", nullable: true),
IsSecret = table.Column<bool>(type: "INTEGER", nullable: false),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AppSettings", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AppSettings");
}
}
}
@@ -0,0 +1,634 @@
// <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("20260807150646_AddSecretsProviders")]
partial class AddSecretsProviders
{
/// <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<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.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.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<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,65 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddSecretsProviders : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "SecretBindingsJson",
table: "Scripts",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SecretsVariableName",
table: "Scripts",
type: "TEXT",
nullable: true);
migrationBuilder.CreateTable(
name: "SecretsProviders",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
Kind = table.Column<string>(type: "TEXT", nullable: false),
ConfigProtected = table.Column<string>(type: "TEXT", nullable: false),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SecretsProviders", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_SecretsProviders_Name",
table: "SecretsProviders",
column: "Name",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SecretsProviders");
migrationBuilder.DropColumn(
name: "SecretBindingsJson",
table: "Scripts");
migrationBuilder.DropColumn(
name: "SecretsVariableName",
table: "Scripts");
}
}
}
@@ -0,0 +1,698 @@
// <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("20260807153214_AddScheduledRuns")]
partial class AddScheduledRuns
{
/// <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<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.ScheduledRunEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ArgumentsJson")
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("CronExpression")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<Guid?>("GroupId")
.HasColumnType("TEXT");
b.Property<string>("LastResult")
.HasColumnType("TEXT");
b.Property<long?>("LastRunUtc")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<long?>("NextRunUtc")
.HasColumnType("INTEGER");
b.Property<long?>("RunOnceUtc")
.HasColumnType("INTEGER");
b.Property<Guid>("ScriptId")
.HasColumnType("TEXT");
b.Property<string>("TimeZoneId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("NextRunUtc");
b.HasIndex("ScriptId");
b.ToTable("ScheduledRuns", (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.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<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b =>
{
b.HasOne("Backend.Data.DeviceEntity", null)
.WithOne("Inventory")
.HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class AddScheduledRuns : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ScriptId = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: true),
ClientId = table.Column<string>(type: "TEXT", nullable: true),
GroupId = table.Column<Guid>(type: "TEXT", nullable: true),
CronExpression = table.Column<string>(type: "TEXT", nullable: true),
RunOnceUtc = table.Column<long>(type: "INTEGER", nullable: true),
TimeZoneId = table.Column<string>(type: "TEXT", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
ArgumentsJson = table.Column<string>(type: "TEXT", nullable: true),
NextRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
LastResult = table.Column<string>(type: "TEXT", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
}
}
}
@@ -0,0 +1,745 @@
// <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("20260807165537_ScheduleObjects")]
partial class ScheduleObjects
{
/// <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<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.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<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.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,141 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class ScheduleObjects : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledRuns");
migrationBuilder.CreateTable(
name: "Schedules",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
CronExpression = table.Column<string>(type: "TEXT", nullable: true),
RunOnceUtc = table.Column<long>(type: "INTEGER", nullable: true),
TimeZoneId = table.Column<string>(type: "TEXT", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
NextRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Schedules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScriptSchedules",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ScheduleId = table.Column<Guid>(type: "TEXT", nullable: false),
ScriptId = table.Column<Guid>(type: "TEXT", nullable: false),
ClientId = table.Column<string>(type: "TEXT", nullable: true),
GroupId = table.Column<Guid>(type: "TEXT", nullable: true),
ArgumentsJson = table.Column<string>(type: "TEXT", nullable: true),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
LastResult = table.Column<string>(type: "TEXT", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScriptSchedules", x => x.Id);
table.ForeignKey(
name: "FK_ScriptSchedules_Schedules_ScheduleId",
column: x => x.ScheduleId,
principalTable: "Schedules",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ScriptSchedules_Scripts_ScriptId",
column: x => x.ScriptId,
principalTable: "Scripts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Schedules_Name",
table: "Schedules",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Schedules_NextRunUtc",
table: "Schedules",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScheduleId",
table: "ScriptSchedules",
column: "ScheduleId");
migrationBuilder.CreateIndex(
name: "IX_ScriptSchedules_ScriptId",
table: "ScriptSchedules",
column: "ScriptId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScriptSchedules");
migrationBuilder.DropTable(
name: "Schedules");
migrationBuilder.CreateTable(
name: "ScheduledRuns",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ArgumentsJson = table.Column<string>(type: "TEXT", nullable: true),
ClientId = table.Column<string>(type: "TEXT", nullable: true),
CreatedBy = table.Column<string>(type: "TEXT", nullable: true),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CronExpression = table.Column<string>(type: "TEXT", nullable: true),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
GroupId = table.Column<Guid>(type: "TEXT", nullable: true),
LastResult = table.Column<string>(type: "TEXT", nullable: true),
LastRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
Name = table.Column<string>(type: "TEXT", nullable: true),
NextRunUtc = table.Column<long>(type: "INTEGER", nullable: true),
RunOnceUtc = table.Column<long>(type: "INTEGER", nullable: true),
ScriptId = table.Column<Guid>(type: "TEXT", nullable: false),
TimeZoneId = table.Column<string>(type: "TEXT", nullable: false),
UpdatedBy = table.Column<string>(type: "TEXT", nullable: true),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledRuns", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_NextRunUtc",
table: "ScheduledRuns",
column: "NextRunUtc");
migrationBuilder.CreateIndex(
name: "IX_ScheduledRuns_ScriptId",
table: "ScheduledRuns",
column: "ScriptId");
}
}
}
@@ -0,0 +1,748 @@
// <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("20260807185825_AddDevicePublicIp")]
partial class AddDevicePublicIp
{
/// <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.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<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.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 AddDevicePublicIp : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "PublicIp",
table: "Devices",
type: "TEXT",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PublicIp",
table: "Devices");
}
}
}
@@ -17,6 +17,28 @@ namespace Backend.Data.Migrations.Sqlite
#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")
@@ -138,6 +160,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<string>("OsVersion")
.HasColumnType("TEXT");
b.Property<string>("PublicIp")
.HasColumnType("TEXT");
b.Property<long?>("ReadyUtc")
.HasColumnType("INTEGER");
@@ -367,6 +392,57 @@ namespace Backend.Data.Migrations.Sqlite
b.ToTable("OidcProviders", (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")
@@ -400,6 +476,12 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<string>("ParametersJson")
.HasColumnType("TEXT");
b.Property<string>("SecretBindingsJson")
.HasColumnType("TEXT");
b.Property<string>("SecretsVariableName")
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasColumnType("TEXT");
@@ -413,6 +495,51 @@ namespace Backend.Data.Migrations.Sqlite
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")
@@ -475,6 +602,41 @@ namespace Backend.Data.Migrations.Sqlite
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")
@@ -558,6 +720,21 @@ namespace Backend.Data.Migrations.Sqlite
.IsRequired();
});
modelBuilder.Entity("Backend.Data.ScriptScheduleEntity", b =>
{
b.HasOne("Backend.Data.ScheduleEntity", null)
.WithMany()
.HasForeignKey("ScheduleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Backend.Data.ScriptEntity", null)
.WithMany()
.HasForeignKey("ScriptId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Backend.Data.DeviceEntity", b =>
{
b.Navigation("Inventory");
@@ -116,6 +116,7 @@ public static class EnrollmentEndpoints
device.OsCaption = request.Device.OsCaption;
device.OsVersion = request.Device.OsVersion;
device.AgentVersion = request.AgentVersion;
device.PublicIp = remoteIp;
token.Uses++;
@@ -225,6 +226,14 @@ public static class EnrollmentEndpoints
return Results.Unauthorized();
}
// A verified refresh is the freshest sighting of the agent's public IP.
var publicIp = ClientIp.EffectiveText(context);
if (!string.Equals(device.PublicIp, publicIp, StringComparison.Ordinal))
{
device.PublicIp = publicIp;
await db.SaveChangesAsync(cancellationToken);
}
var userJwt = issuer.IssueAgentCredential(request.ClientId, request.NkeyPublic);
return Results.Ok(new CredentialRefreshResponse(userJwt, CredentialExpiresUtc: null));
}
+18 -22
View File
@@ -46,24 +46,29 @@ public static class InstallEndpoints
return Results.Text(script, "text/plain; charset=utf-8");
}
private static async Task<IResult> GetAgentPackage(HttpContext context, IConfiguration configuration, string? type)
private static async Task<IResult> GetAgentPackage(
Files.AgentPackageService packages, string? type, CancellationToken cancellationToken)
{
var directory = configuration["AGENT_PACKAGE_PATH"];
if (string.IsNullOrWhiteSpace(directory))
var packageType = Files.AgentPackageService.NormalizeType(type);
var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi";
// When S3 offload is on, hand the endpoint a presigned URL so the
// transfer never touches the control plane. Falls through to local
// delivery if presigning fails for any reason.
var offloadUrl = await packages.TryGetOffloadUrlAsync(packageType, cancellationToken);
if (offloadUrl is not null)
{
directory = "/data/agent";
return Results.Redirect(offloadUrl, permanent: false);
}
var packageType = type?.ToLowerInvariant() == "zip" ? "zip" : "msi";
var fileName = packageType == "zip" ? "Agent.zip" : "Agent.msi";
var path = Path.Combine(directory, fileName);
if (!File.Exists(path))
var path = packages.ResolveLocalPath(packageType);
if (path is null)
{
return Results.NotFound(new
{
error = $"Agent package '{fileName}' is not available. " +
"Place the built package in AGENT_PACKAGE_PATH (default /data/agent).",
error = $"Agent package '{fileName}' is not available. CI bakes it into the backend " +
"image; for a local build run scripts/Package-Agent.ps1 and mount the output " +
"at AGENT_PACKAGE_PATH (or /data/agent).",
});
}
@@ -73,16 +78,7 @@ public static class InstallEndpoints
}
private static string ResolveBaseUrl(HttpContext context, IConfiguration configuration)
{
var configured = configuration["PUBLIC_SERVER_URL"];
if (!string.IsNullOrWhiteSpace(configured))
{
return configured.TrimEnd('/');
}
// Derived from forwarded headers (proxy-aware) after ForwardedHeaders ran.
return $"{context.Request.Scheme}://{context.Request.Host}";
}
=> Backend.Proxy.PublicUrl.Resolve(context, configuration);
// NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell.
private static string BuildMsiScript(string baseUrl, string token, string packageUrl) => $$"""
@@ -110,7 +106,7 @@ public static class InstallEndpoints
Write-Host 'Installing ExecuteR Agent (portable)...'
$server = '{{baseUrl}}'
$token = '{{token}}'
$dest = Join-Path $env:ProgramFiles 'Grace Solution\ExecuteR Agent'
$dest = Join-Path $env:ProgramFiles 'ExecuteR Agent'
$zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip')
try {
Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $zip -UseBasicParsing
+226
View File
@@ -0,0 +1,226 @@
using System.Security.Cryptography;
using Amazon.S3;
using Amazon.S3.Model;
using Shared.Contracts.Api;
namespace Backend.Files;
/// <summary>
/// Locates the agent installer that the URL-install flow hands out.
///
/// Search order:
/// 1. AGENT_PACKAGE_PATH, when explicitly configured
/// 2. /opt/executer/agent — baked into the backend image by CI
/// 3. /data/agent — a manually seeded volume (legacy / air-gapped)
///
/// CI copies the Windows-built package into the image, so a stock deployment
/// serves the agent with no manual step. When S3 offload is enabled the same
/// package is uploaded once and served as a presigned URL instead, which keeps
/// large downloads off the control plane.
/// </summary>
public sealed class AgentPackageService(
IConfiguration configuration,
S3SettingsService s3Settings,
ILogger<AgentPackageService> logger)
{
public const string BakedInPath = "/opt/executer/agent";
public const string SeededPath = "/data/agent";
private static string FileNameFor(string packageType) => packageType == "zip" ? "Agent.zip" : "Agent.msi";
public static string NormalizeType(string? type)
=> string.Equals(type, "zip", StringComparison.OrdinalIgnoreCase) ? "zip" : "msi";
/// <summary>Directories searched, most specific first.</summary>
private IEnumerable<string> CandidateDirectories()
{
var configured = configuration["AGENT_PACKAGE_PATH"];
if (!string.IsNullOrWhiteSpace(configured))
{
yield return configured;
}
yield return BakedInPath;
yield return SeededPath;
}
/// <summary>Full path to the package on local disk, or null when absent.</summary>
public string? ResolveLocalPath(string packageType)
{
var fileName = FileNameFor(packageType);
foreach (var directory in CandidateDirectories())
{
var path = Path.Combine(directory, fileName);
if (File.Exists(path))
{
return path;
}
}
return null;
}
public async Task<AgentPackageStatusDto> GetStatusAsync(string packageType, CancellationToken cancellationToken)
{
var offloadEnabled = await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken);
var objectKey = await s3Settings.GetAgentObjectKeyAsync(packageType, cancellationToken);
var path = ResolveLocalPath(packageType);
if (path is null)
{
return new AgentPackageStatusDto(
Available: offloadEnabled && objectKey is not null,
Source: offloadEnabled && objectKey is not null ? "s3" : "none",
FileName: FileNameFor(packageType),
SizeBytes: null, Sha256: null, BuiltUtc: null, Version: null,
OffloadEnabled: offloadEnabled,
OffloadUploaded: objectKey is not null);
}
var info = new FileInfo(path);
return new AgentPackageStatusDto(
Available: true,
Source: offloadEnabled && objectKey is not null ? "s3" : DescribeSource(path),
FileName: info.Name,
SizeBytes: info.Length,
Sha256: await ComputeSha256Async(path, cancellationToken),
BuiltUtc: new DateTimeOffset(info.LastWriteTimeUtc, TimeSpan.Zero),
Version: ReadVersionMarker(info.DirectoryName),
OffloadEnabled: offloadEnabled,
OffloadUploaded: objectKey is not null);
}
private static string DescribeSource(string path)
=> path.Replace('\\', '/').StartsWith(BakedInPath, StringComparison.OrdinalIgnoreCase)
? "image"
: "volume";
/// <summary>CI writes a VERSION file beside the package.</summary>
private static string? ReadVersionMarker(string? directory)
{
if (directory is null)
{
return null;
}
var marker = Path.Combine(directory, "VERSION");
try
{
return File.Exists(marker) ? File.ReadAllText(marker).Trim() : null;
}
catch (IOException)
{
return null;
}
}
public static async Task<string> ComputeSha256Async(string path, CancellationToken cancellationToken)
{
await using var stream = File.OpenRead(path);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken));
}
/// <summary>
/// Uploads the local package to S3 and records its object key. Re-uploading
/// an unchanged package is skipped by comparing the stored hash.
/// </summary>
public async Task<(bool Ok, string Message)> UploadToS3Async(
string packageType, string? actor, CancellationToken cancellationToken)
{
var path = ResolveLocalPath(packageType);
if (path is null)
{
return (false, $"No {FileNameFor(packageType)} available to upload.");
}
var options = await s3Settings.GetEffectiveAsync(cancellationToken);
if (!options.IsUsable)
{
return (false, "S3 is not configured.");
}
var sha = await ComputeSha256Async(path, cancellationToken);
var objectKey = $"executer/agent/{sha[..12]}/{FileNameFor(packageType)}";
using var client = S3ClientFactory.Create(options);
try
{
// Skip the transfer when this exact build is already present.
try
{
var head = await client.GetObjectMetadataAsync(options.Bucket, objectKey, cancellationToken);
if (head.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
await s3Settings.SetAsync(
S3SettingsService.Keys.AgentObjectKeyPrefix + packageType, objectKey, false, actor, cancellationToken);
return (true, $"Already present in S3 ({objectKey}); nothing re-uploaded.");
}
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// Expected on first upload.
}
await client.PutObjectAsync(new PutObjectRequest
{
BucketName = options.Bucket,
Key = objectKey,
FilePath = path,
}, cancellationToken);
await s3Settings.SetAsync(
S3SettingsService.Keys.AgentObjectKeyPrefix + packageType, objectKey, false, actor, cancellationToken);
logger.LogInformation("Agent package {Type} uploaded to S3 as {Key}", packageType, objectKey);
return (true, $"Uploaded to {objectKey}.");
}
catch (Exception ex)
{
logger.LogError(ex, "Agent package upload to S3 failed");
return (false, ex is AmazonS3Exception s3 ? $"{s3.ErrorCode}: {s3.Message}" : ex.Message);
}
}
/// <summary>
/// Presigned URL for the offloaded package, or null when offload is off or
/// nothing has been uploaded yet.
/// </summary>
public async Task<string?> TryGetOffloadUrlAsync(string packageType, CancellationToken cancellationToken)
{
if (!await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken))
{
return null;
}
var objectKey = await s3Settings.GetAgentObjectKeyAsync(packageType, cancellationToken);
if (objectKey is null)
{
return null;
}
var options = await s3Settings.GetEffectiveAsync(cancellationToken);
if (!options.IsUsable)
{
return null;
}
try
{
using var client = S3ClientFactory.Create(options);
return client.GetPreSignedURL(new GetPreSignedUrlRequest
{
BucketName = options.Bucket,
Key = objectKey,
Verb = HttpVerb.GET,
Expires = DateTime.UtcNow.AddSeconds(options.PresignExpirySeconds),
});
}
catch (Exception ex)
{
// Never break installs because the offload path is unhealthy —
// the caller falls back to streaming from local disk.
logger.LogWarning(ex, "Presigning the offloaded agent package failed; falling back to local delivery");
return null;
}
}
}
+2 -2
View File
@@ -42,7 +42,7 @@ public static class FileDeliveryEndpoints
return Results.BadRequest(new { error = "clientId, objectKey and destinationPath are required." });
}
if (!s3.IsConfigured)
if (!await s3.IsConfiguredAsync(cancellationToken))
{
return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "S3 file delivery is not configured.");
}
@@ -53,7 +53,7 @@ public static class FileDeliveryEndpoints
return Results.NotFound();
}
var (url, expiresUtc) = s3.PresignGet(request.ObjectKey);
var (url, expiresUtc) = await s3.PresignGetAsync(request.ObjectKey, cancellationToken);
var actor = context.User.Identity?.Name;
var job = new JobEntity
+162
View File
@@ -0,0 +1,162 @@
using System.Diagnostics;
using System.Text;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
namespace Backend.Files;
/// <summary>One step of the connectivity test, surfaced individually in the UI.</summary>
public sealed record S3TestStep(string Name, bool Ok, string? Detail);
/// <summary>Result of a full S3 round-trip test.</summary>
public sealed record S3TestResult(bool Ok, IReadOnlyList<S3TestStep> Steps, long ElapsedMs);
/// <summary>
/// Builds S3 clients from a given set of options (not just the ambient ones),
/// so candidate settings can be validated before they are saved.
/// </summary>
public static class S3ClientFactory
{
public static IAmazonS3 Create(S3Options options)
{
var config = new AmazonS3Config
{
ForcePathStyle = options.ForcePathStyle,
RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region),
Timeout = TimeSpan.FromSeconds(20),
};
if (!string.IsNullOrWhiteSpace(options.Endpoint))
{
config.ServiceURL = options.Endpoint;
config.AuthenticationRegion = options.Region;
}
return new AmazonS3Client(options.AccessKey, options.SecretKey, config);
}
/// <summary>
/// Exercises the credentials for real: bucket reachable, then write, read
/// back, presign and delete a small probe object. Each step is reported
/// separately so a partial failure (e.g. read-only credentials) is obvious.
/// </summary>
public static async Task<S3TestResult> TestAsync(S3Options options, CancellationToken cancellationToken)
{
var steps = new List<S3TestStep>();
var stopwatch = Stopwatch.StartNew();
if (!options.IsUsable)
{
steps.Add(new S3TestStep("configuration", false,
"Enabled, bucket, access key and secret key are all required."));
return new S3TestResult(false, steps, stopwatch.ElapsedMilliseconds);
}
IAmazonS3? client = null;
var key = $"executer-connectivity-check/{Guid.NewGuid():N}.txt";
var payload = $"ExecuteR connectivity check {DateTimeOffset.UtcNow:O}";
try
{
client = Create(options);
// 1. Bucket reachable / credentials valid.
try
{
await client.GetBucketLocationAsync(options.Bucket, cancellationToken);
steps.Add(new S3TestStep("bucket", true, $"'{options.Bucket}' reachable"));
}
catch (AmazonS3Exception ex)
{
// Some S3-compatible stores do not implement GetBucketLocation;
// a listing probe is a fair substitute.
try
{
await client.ListObjectsV2Async(
new ListObjectsV2Request { BucketName = options.Bucket, MaxKeys = 1 }, cancellationToken);
steps.Add(new S3TestStep("bucket", true, $"'{options.Bucket}' reachable (via list)"));
}
catch (Exception inner)
{
steps.Add(new S3TestStep("bucket", false, Describe(ex, inner)));
return new S3TestResult(false, steps, stopwatch.ElapsedMilliseconds);
}
}
// 2. Write.
await client.PutObjectAsync(new PutObjectRequest
{
BucketName = options.Bucket,
Key = key,
ContentBody = payload,
}, cancellationToken);
steps.Add(new S3TestStep("write", true, "probe object uploaded"));
// 3. Read back and compare.
using (var response = await client.GetObjectAsync(options.Bucket, key, cancellationToken))
using (var reader = new StreamReader(response.ResponseStream, Encoding.UTF8))
{
var read = await reader.ReadToEndAsync(cancellationToken);
var matches = read == payload;
steps.Add(new S3TestStep("read", matches,
matches ? "content matches" : "content did not match what was written"));
}
// 4. Presign — this is the mechanism agents actually use.
var url = client.GetPreSignedURL(new GetPreSignedUrlRequest
{
BucketName = options.Bucket,
Key = key,
Verb = HttpVerb.GET,
Expires = DateTime.UtcNow.AddMinutes(5),
});
using (var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) })
{
var fetched = await http.GetAsync(url, cancellationToken);
steps.Add(new S3TestStep("presigned download", fetched.IsSuccessStatusCode,
fetched.IsSuccessStatusCode
? "presigned URL downloadable"
: $"presigned GET returned HTTP {(int)fetched.StatusCode} — check the endpoint is reachable from agents"));
}
// 5. Clean up.
await client.DeleteObjectAsync(options.Bucket, key, cancellationToken);
steps.Add(new S3TestStep("delete", true, "probe object removed"));
}
catch (Exception ex)
{
steps.Add(new S3TestStep("error", false, Describe(ex)));
try
{
if (client is not null)
{
await client.DeleteObjectAsync(options.Bucket, key, CancellationToken.None);
}
}
catch (Exception)
{
// Best-effort cleanup.
}
}
finally
{
client?.Dispose();
}
stopwatch.Stop();
return new S3TestResult(steps.All(s => s.Ok), steps, stopwatch.ElapsedMilliseconds);
}
private static string Describe(params Exception[] exceptions)
{
var ex = exceptions[^1];
return ex switch
{
AmazonS3Exception s3 => $"{s3.ErrorCode ?? "S3Error"}: {s3.Message}",
HttpRequestException http => $"Network: {http.Message}",
TaskCanceledException => "Timed out contacting the endpoint.",
_ => ex.Message,
};
}
}
+10 -33
View File
@@ -1,4 +1,3 @@
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
@@ -6,46 +5,26 @@ namespace Backend.Files;
/// <summary>
/// Issues short-lived presigned GET URLs so agents can download objects
/// without ever holding S3 credentials.
/// without ever holding S3 credentials. Settings are resolved per call, so
/// changes saved in the UI take effect without restarting the backend.
/// </summary>
public sealed class S3PresignService : IDisposable
public sealed class S3PresignService(S3SettingsService settings)
{
private readonly S3Options options;
private readonly IAmazonS3? client;
public async Task<bool> IsConfiguredAsync(CancellationToken cancellationToken)
=> (await settings.GetEffectiveAsync(cancellationToken)).IsUsable;
public S3PresignService(S3Options options)
public async Task<(string Url, DateTimeOffset ExpiresUtc)> PresignGetAsync(
string objectKey, CancellationToken cancellationToken)
{
this.options = options;
var options = await settings.GetEffectiveAsync(cancellationToken);
if (!options.IsUsable)
{
return;
}
var config = new AmazonS3Config
{
ForcePathStyle = options.ForcePathStyle,
RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region),
};
if (!string.IsNullOrWhiteSpace(options.Endpoint))
{
config.ServiceURL = options.Endpoint;
config.AuthenticationRegion = options.Region;
}
client = new AmazonS3Client(options.AccessKey, options.SecretKey, config);
}
public bool IsConfigured => client is not null;
public (string Url, DateTimeOffset ExpiresUtc) PresignGet(string objectKey)
{
if (client is null)
{
throw new InvalidOperationException("S3 is not configured.");
}
var expires = DateTime.UtcNow.AddSeconds(options.PresignExpirySeconds);
using var client = S3ClientFactory.Create(options);
var url = client.GetPreSignedURL(new GetPreSignedUrlRequest
{
BucketName = options.Bucket,
@@ -56,6 +35,4 @@ public sealed class S3PresignService : IDisposable
return (url, new DateTimeOffset(expires, TimeSpan.Zero));
}
public void Dispose() => client?.Dispose();
}
+87
View File
@@ -0,0 +1,87 @@
using Backend.Settings;
namespace Backend.Files;
/// <summary>
/// Resolves the effective S3 configuration: values saved from the UI override
/// the environment, which acts as the bootstrap default. Also creates clients
/// against the effective settings so a "Test" can validate candidate values
/// before they are saved.
/// </summary>
public sealed class S3SettingsService(SettingsStore store, S3Options environmentDefaults)
{
public const string Prefix = "s3.";
public static class Keys
{
public const string Enabled = Prefix + "enabled";
public const string Endpoint = Prefix + "endpoint";
public const string Region = Prefix + "region";
public const string Bucket = Prefix + "bucket";
public const string AccessKey = Prefix + "accessKey";
public const string SecretKey = Prefix + "secretKey";
public const string ForcePathStyle = Prefix + "forcePathStyle";
public const string PresignExpirySeconds = Prefix + "presignExpirySeconds";
/// <summary>Serve the agent package from S3 instead of local disk.</summary>
public const string AgentOffloadEnabled = Prefix + "agentOffloadEnabled";
/// <summary>Object key of the uploaded agent package.</summary>
public const string AgentObjectKeyPrefix = Prefix + "agentObjectKey.";
/// <summary>Last verified round-trip, ISO-8601.</summary>
public const string LastTestUtc = Prefix + "lastTestUtc";
}
/// <summary>Effective options: database overrides, environment defaults.</summary>
public async Task<S3Options> GetEffectiveAsync(CancellationToken cancellationToken)
{
var saved = await store.GetAllAsync(Prefix, cancellationToken);
return new S3Options
{
Enabled = Bool(saved, Keys.Enabled, environmentDefaults.Enabled),
Endpoint = Str(saved, Keys.Endpoint, environmentDefaults.Endpoint),
Region = Str(saved, Keys.Region, environmentDefaults.Region) ?? "us-east-1",
Bucket = Str(saved, Keys.Bucket, environmentDefaults.Bucket),
AccessKey = Str(saved, Keys.AccessKey, environmentDefaults.AccessKey),
SecretKey = Str(saved, Keys.SecretKey, environmentDefaults.SecretKey),
ForcePathStyle = Bool(saved, Keys.ForcePathStyle, environmentDefaults.ForcePathStyle),
PresignExpirySeconds = Int(saved, Keys.PresignExpirySeconds, environmentDefaults.PresignExpirySeconds),
};
}
public async Task<bool> GetAgentOffloadEnabledAsync(CancellationToken cancellationToken)
{
var saved = await store.GetAllAsync(Prefix, cancellationToken);
return Bool(saved, Keys.AgentOffloadEnabled, false);
}
public async Task<string?> GetAgentObjectKeyAsync(string packageType, CancellationToken cancellationToken)
{
var saved = await store.GetAllAsync(Prefix, cancellationToken);
return Str(saved, Keys.AgentObjectKeyPrefix + packageType, null);
}
public async Task<DateTimeOffset?> GetLastTestUtcAsync(CancellationToken cancellationToken)
{
var saved = await store.GetAllAsync(Prefix, cancellationToken);
var raw = Str(saved, Keys.LastTestUtc, null);
return DateTimeOffset.TryParse(raw, out var value) ? value : null;
}
public Task SetAsync(string key, string? value, bool isSecret, string? actor, CancellationToken cancellationToken)
=> store.SetAsync(key, value, isSecret, actor, cancellationToken);
/// <summary>True when the environment supplied a value, so the UI can show it as inherited.</summary>
public S3Options EnvironmentDefaults => environmentDefaults;
private static string? Str(IReadOnlyDictionary<string, string> saved, string key, string? fallback)
=> saved.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback;
private static bool Bool(IReadOnlyDictionary<string, string> saved, string key, bool fallback)
=> saved.TryGetValue(key, out var value) ? value is "1" or "true" or "True" : fallback;
private static int Int(IReadOnlyDictionary<string, string> saved, string key, int fallback)
=> saved.TryGetValue(key, out var value) && int.TryParse(value, out var parsed) && parsed > 0
? parsed
: fallback;
}
+22 -53
View File
@@ -17,8 +17,7 @@ namespace Backend.Groups;
public sealed class ScriptTriggerService(
AppDbContext db,
DeviceGroupService groups,
CommandDispatcher dispatcher,
BrowserEventBroadcaster broadcaster,
JobRunner runner,
ILogger<ScriptTriggerService> logger)
{
public async Task FireAsync(ScriptTriggerType triggerType, string clientId, CancellationToken cancellationToken)
@@ -61,17 +60,8 @@ public sealed class ScriptTriggerService(
continue;
}
var job = new JobEntity
{
JobId = Guid.NewGuid(),
ClientId = clientId,
ScriptId = script.Id,
ScriptName = script.Name,
State = JobState.Queued,
CreatedUtc = DateTimeOffset.UtcNow,
RequestedBy = $"trigger:{triggerType}",
};
db.Jobs.Add(job);
var job = await runner.CreateJobAsync(
script, clientId, $"trigger:{triggerType}", cancellationToken);
if (trigger.OncePerDevice)
{
@@ -82,31 +72,29 @@ public sealed class ScriptTriggerService(
JobId = job.JobId,
FiredUtc = DateTimeOffset.UtcNow,
});
}
await db.SaveChangesAsync(cancellationToken);
var parameters = ScriptEndpoints.DeserializeParameters(script.ParametersJson);
var moduleIds = ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson);
var prelude = await ComposePreludeAsync(moduleIds, cancellationToken);
var dispatched = await dispatcher.DispatchScriptAsync(clientId, new ScriptCommandPayload(
job.JobId, script.Id, script.Name, script.Content,
ProtocolDefaults.DefaultScriptTimeoutSeconds,
Prelude: prelude,
Parameters: parameters.Count > 0 ? parameters : null,
Arguments: null), cancellationToken);
if (dispatched)
{
job.State = JobState.Dispatched;
await db.SaveChangesAsync(cancellationToken);
}
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"job-created",
// The job row exists before secret resolution so a vault outage
// is visible as a failed job — triggers have no operator watching.
PreparedScript prepared;
try
{
prepared = await runner.PrepareAsync(script, cancellationToken);
}
catch (Backend.Secrets.SecretResolutionException ex)
{
await runner.MarkFailedAsync(job, ex.Message, cancellationToken);
logger.LogWarning(
"Trigger {TriggerId} job {JobId} failed: {Message}",
trigger.Id, job.JobId, ex.Message);
continue;
}
await runner.DispatchAsync(
prepared, job, arguments: null,
$"Trigger ({triggerType}) queued “{script.Name}” for {device.Hostname}",
clientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken);
cancellationToken);
logger.LogInformation(
"Trigger {TriggerId} ({TriggerType}) fired for {ClientId} as job {JobId}",
@@ -120,23 +108,4 @@ public sealed class ScriptTriggerService(
}
}
private async Task<string?> ComposePreludeAsync(IReadOnlyList<Guid> moduleIds, CancellationToken cancellationToken)
{
if (moduleIds.Count == 0)
{
return null;
}
var modules = await db.FunctionModules.AsNoTracking()
.Where(m => moduleIds.Contains(m.Id))
.ToListAsync(cancellationToken);
var ordered = moduleIds
.Select(id => modules.FirstOrDefault(m => m.Id == id))
.Where(m => m is not null)
.Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}")
.ToList();
return ordered.Count > 0 ? string.Join("\n\n", ordered) : null;
}
}
+80 -64
View File
@@ -76,12 +76,44 @@ public static class JobEndpoints
private static async Task<IResult> CreateAsync(
CreateJobRequest request,
AppDbContext db,
CommandDispatcher dispatcher,
BrowserEventBroadcaster broadcaster,
JobRunner runner,
Backend.Groups.DeviceGroupService groups,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
if ((request.ClientId is null) == (request.GroupId is null))
{
return Results.BadRequest(new { error = "Target exactly one of clientId or groupId." });
}
var script = await db.Scripts.AsNoTracking()
.SingleOrDefaultAsync(s => s.Id == request.ScriptId, cancellationToken);
if (script is null)
{
return Results.NotFound(new { error = "Script not found." });
}
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.
PreparedScript prepared;
try
{
prepared = await runner.PrepareAsync(script, cancellationToken);
}
catch (Backend.Secrets.SecretResolutionException ex)
{
return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway);
}
if (request.GroupId is { } groupId)
{
return await RunOnGroupAsync(
groupId, prepared, request, db, runner, groups, audit, actor, cancellationToken);
}
if (!SubjectIdentifier.IsValid(request.ClientId))
{
return Results.BadRequest(new { error = "Invalid client id." });
@@ -102,83 +134,67 @@ public static class JobEndpoints
});
}
var script = await db.Scripts.AsNoTracking()
.SingleOrDefaultAsync(s => s.Id == request.ScriptId, cancellationToken);
if (script is null)
{
return Results.NotFound(new { error = "Script not found." });
}
var actor = context.User.Identity?.Name;
var job = new JobEntity
{
JobId = Guid.NewGuid(),
ClientId = device.ClientId,
ScriptId = script.Id,
ScriptName = script.Name,
State = JobState.Queued,
CreatedUtc = DateTimeOffset.UtcNow,
RequestedBy = actor,
};
db.Jobs.Add(job);
await db.SaveChangesAsync(cancellationToken);
// Compose the prelude from attached function modules so the main script
// stays small; parameters/arguments drive typed variable injection.
var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson);
var moduleIds = Backend.Scripts.ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson);
var prelude = await ComposePreludeAsync(db, moduleIds, cancellationToken);
var dispatched = await dispatcher.DispatchScriptAsync(
device.ClientId,
new ScriptCommandPayload(
job.JobId, script.Id, script.Name, script.Content,
ProtocolDefaults.DefaultScriptTimeoutSeconds,
Prelude: prelude,
Parameters: parameters.Count > 0 ? parameters : null,
Arguments: request.Arguments),
cancellationToken);
if (dispatched)
{
job.State = JobState.Dispatched;
await db.SaveChangesAsync(cancellationToken);
}
var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken);
await runner.DispatchAsync(
prepared, job, request.Arguments,
$"Job “{script.Name}” queued for {device.Hostname}", cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "created", actor,
clientId: device.ClientId, detail: $"script={script.Name} job={job.JobId}",
cancellationToken: cancellationToken);
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"job-created",
$"Job “{script.Name}” queued for {device.Hostname}",
device.ClientId,
job.JobId,
DateTimeOffset.UtcNow), cancellationToken);
return Results.Created(ApiRoutes.For.Job(job.JobId), ToDto(job, device.Hostname));
}
private static async Task<string?> ComposePreludeAsync(
AppDbContext db, IReadOnlyList<Guid> moduleIds, CancellationToken cancellationToken)
/// <summary>One job per non-orphaned member; devices currently offline still
/// get one because dispatch is durable (JetStream holds it until they return).</summary>
private static async Task<IResult> RunOnGroupAsync(
Guid groupId,
PreparedScript prepared,
CreateJobRequest request,
AppDbContext db,
JobRunner runner,
Backend.Groups.DeviceGroupService groups,
AuditService audit,
string? actor,
CancellationToken cancellationToken)
{
if (moduleIds.Count == 0)
var group = await db.DeviceGroups.AsNoTracking()
.SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken);
if (group is null)
{
return null;
return Results.NotFound(new { error = "Group not found." });
}
var modules = await db.FunctionModules.AsNoTracking()
.Where(m => moduleIds.Contains(m.Id))
var memberIds = await groups.GetMembersAsync(group, cancellationToken);
var devices = await db.Devices.AsNoTracking()
.Where(d => memberIds.Contains(d.ClientId))
.ToListAsync(cancellationToken);
// Preserve the author's declared order.
var ordered = moduleIds
.Select(id => modules.FirstOrDefault(m => m.Id == id))
.Where(m => m is not null)
.Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}")
.ToList();
var jobs = new List<JobDto>();
var skipped = new List<string>();
return ordered.Count > 0 ? string.Join("\n\n", ordered) : null;
foreach (var device in devices)
{
if (device.IsOrphaned)
{
skipped.Add(device.Hostname);
continue;
}
var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken);
await runner.DispatchAsync(
prepared, job, request.Arguments,
$"Job “{prepared.Script.Name}” queued for {device.Hostname} (group “{group.Name}”)",
cancellationToken);
jobs.Add(ToDto(job, device.Hostname));
}
await audit.LogAsync(AuditCategories.Jobs, "group-run", actor,
detail: $"script={prepared.Script.Name} group={group.Name} jobs={jobs.Count} skipped={skipped.Count}",
cancellationToken: cancellationToken);
return Results.Ok(new GroupRunDto(jobs, skipped));
}
private static JobDto ToDto(JobEntity job, string? hostname) => new(
+133
View File
@@ -0,0 +1,133 @@
using System.Text.Json;
using Backend.Data;
using Backend.Messaging;
using Backend.Secrets;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Infrastructure.Constants;
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).
/// </summary>
public sealed record PreparedScript(
ScriptEntity Script,
string? Prelude,
IReadOnlyList<ScriptParameter>? Parameters,
IReadOnlyList<ScriptSecret>? Secrets);
/// <summary>
/// The one path from "run this script on this device" to a dispatched job.
/// Manual runs, group fan-outs, lifecycle triggers and schedules all go
/// through here so they share prelude composition, server-side secret
/// resolution, durable dispatch and activity broadcasting.
/// </summary>
public sealed class JobRunner(
AppDbContext db,
CommandDispatcher dispatcher,
BrowserEventBroadcaster broadcaster,
SecretsProviderService secretsService)
{
/// <summary>Composes the prelude and resolves secrets. Throws <see cref="SecretResolutionException"/>.</summary>
public async Task<PreparedScript> PrepareAsync(ScriptEntity script, CancellationToken cancellationToken)
{
var parameters = Backend.Scripts.ScriptEndpoints.DeserializeParameters(script.ParametersJson);
var moduleIds = Backend.Scripts.ScriptEndpoints.DeserializeModuleIds(script.FunctionModuleIdsJson);
var prelude = await ComposePreludeAsync(moduleIds, cancellationToken);
IReadOnlyList<ScriptSecret>? secrets = null;
var bindings = Backend.Scripts.ScriptEndpoints.DeserializeSecretBindings(script.SecretBindingsJson);
if (bindings.Count > 0)
{
secrets = await secretsService.ResolveAsync(bindings, cancellationToken);
}
return new PreparedScript(script, prelude, parameters.Count > 0 ? parameters : null, secrets);
}
public async Task<JobEntity> CreateJobAsync(
ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken)
{
var job = new JobEntity
{
JobId = Guid.NewGuid(),
ClientId = clientId,
ScriptId = script.Id,
ScriptName = script.Name,
State = JobState.Queued,
CreatedUtc = DateTimeOffset.UtcNow,
RequestedBy = requestedBy,
};
db.Jobs.Add(job);
await db.SaveChangesAsync(cancellationToken);
return job;
}
/// <summary>Publishes the durable command and broadcasts the activity item.</summary>
public async Task<bool> DispatchAsync(
PreparedScript prepared,
JobEntity job,
IReadOnlyDictionary<string, JsonElement>? arguments,
string activityText,
CancellationToken cancellationToken)
{
var script = prepared.Script;
var dispatched = await dispatcher.DispatchScriptAsync(
job.ClientId,
new ScriptCommandPayload(
job.JobId, script.Id, script.Name, script.Content,
ProtocolDefaults.DefaultScriptTimeoutSeconds,
Prelude: prepared.Prelude,
Parameters: prepared.Parameters,
Arguments: arguments,
SecretsVariableName: script.SecretsVariableName,
Secrets: prepared.Secrets),
cancellationToken);
if (dispatched)
{
job.State = JobState.Dispatched;
await db.SaveChangesAsync(cancellationToken);
}
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"job-created", activityText, job.ClientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken);
return dispatched;
}
/// <summary>Terminal failure before dispatch (e.g. the vault was unreachable).</summary>
public async Task MarkFailedAsync(JobEntity job, string message, CancellationToken cancellationToken)
{
job.State = JobState.Failed;
job.CompletedUtc = DateTimeOffset.UtcNow;
job.OutputSummary = message;
await db.SaveChangesAsync(cancellationToken);
}
private async Task<string?> ComposePreludeAsync(
IReadOnlyList<Guid> moduleIds, CancellationToken cancellationToken)
{
if (moduleIds.Count == 0)
{
return null;
}
var modules = await db.FunctionModules.AsNoTracking()
.Where(m => moduleIds.Contains(m.Id))
.ToListAsync(cancellationToken);
// Preserve the author's declared order.
var ordered = moduleIds
.Select(id => modules.FirstOrDefault(m => m.Id == id))
.Where(m => m is not null)
.Select(m => $"# --- function module: {m!.Name} ---\n{m.Content}")
.ToList();
return ordered.Count > 0 ? string.Join("\n\n", ordered) : null;
}
}
+70
View File
@@ -0,0 +1,70 @@
using Cronos;
namespace Backend.Jobs;
/// <summary>
/// Cron evaluation for schedules: standard 5-field expressions, evaluated in
/// the schedule's time zone (so "daily at 01:00" tracks DST there), with all
/// stored/compared instants in UTC.
/// </summary>
public static class ScheduleCron
{
/// <summary>Parses and validates; returns an error message or null when valid.</summary>
public static string? Validate(string cronExpression, string timeZoneId)
{
try
{
CronExpression.Parse(cronExpression);
}
catch (CronFormatException ex)
{
return $"Invalid cron expression: {ex.Message}";
}
try
{
TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
}
catch (TimeZoneNotFoundException)
{
return $"Unknown time zone “{timeZoneId}”.";
}
catch (InvalidTimeZoneException)
{
return $"Invalid time zone “{timeZoneId}”.";
}
return null;
}
public static DateTimeOffset? NextOccurrence(
string cronExpression, string timeZoneId, DateTimeOffset after)
{
var expression = CronExpression.Parse(cronExpression);
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
return expression.GetNextOccurrence(after, timeZone);
}
public static IReadOnlyList<DateTimeOffset> NextOccurrences(
string cronExpression, string timeZoneId, DateTimeOffset after, int count)
{
var expression = CronExpression.Parse(cronExpression);
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var result = new List<DateTimeOffset>(count);
var cursor = after;
for (var i = 0; i < count; i++)
{
var next = expression.GetNextOccurrence(cursor, timeZone);
if (next is null)
{
break;
}
result.Add(next.Value);
cursor = next.Value;
}
return result;
}
}
+400
View File
@@ -0,0 +1,400 @@
using Backend.Auth;
using Backend.Data;
using Backend.Security;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Serialization;
namespace Backend.Jobs;
/// <summary>
/// Schedules are reusable cadence objects; scripts honor them through
/// assignments (script + target + stored run values). The worker fires every
/// enabled assignment when its schedule comes due.
/// </summary>
public static class ScheduleEndpoints
{
public static void Map(WebApplication app)
{
app.MapGet(ApiRoutes.Schedules, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer);
app.MapPost(ApiRoutes.Schedules, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapPut(ApiRoutes.Schedule, UpdateAsync).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapDelete(ApiRoutes.Schedule, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapPost(ApiRoutes.SchedulePreview, Preview).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapGet(ApiRoutes.ScheduleAssignments, ListAssignmentsAsync).RequireAuthorization(AuthConstants.PolicyViewer);
app.MapPost(ApiRoutes.ScheduleAssignments, CreateAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapPut(ApiRoutes.ScheduleAssignment, UpdateAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator);
app.MapDelete(ApiRoutes.ScheduleAssignment, DeleteAssignmentAsync).RequireAuthorization(AuthConstants.PolicyOperator);
}
// ── Schedule objects ─────────────────────────────────────────────────
private static async Task<IResult> ListAsync(AppDbContext db, CancellationToken cancellationToken)
{
var schedules = await db.Schedules.AsNoTracking()
.OrderBy(s => s.NextRunUtc == null).ThenBy(s => s.NextRunUtc)
.ToListAsync(cancellationToken);
var assignments = await LoadAssignmentDtosAsync(db, null, null, cancellationToken);
return Results.Ok(schedules.Select(s => ToDto(
s, assignments.Where(a => a.ScheduleId == s.Id).ToList())).ToList());
}
private static async Task<IResult> CreateAsync(
SaveScheduleRequest request,
AppDbContext db,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
var (error, next) = Validate(request);
if (error is not null)
{
return Results.BadRequest(new { error });
}
if (await db.Schedules.AnyAsync(s => s.Name == request.Name.Trim(), cancellationToken))
{
return Results.BadRequest(new { error = "A schedule with that name already exists." });
}
var actor = context.User.Identity?.Name;
var schedule = new ScheduleEntity
{
Id = Guid.NewGuid(),
Name = request.Name.Trim(),
CreatedUtc = DateTimeOffset.UtcNow,
CreatedBy = actor,
};
Apply(schedule, request, next, actor);
db.Schedules.Add(schedule);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-created", actor,
detail: $"schedule={schedule.Name} next={schedule.NextRunUtc:O}", cancellationToken: cancellationToken);
return Results.Created(ApiRoutes.For.Schedule(schedule.Id), ToDto(schedule, []));
}
private static async Task<IResult> UpdateAsync(
Guid id,
SaveScheduleRequest request,
AppDbContext db,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
if (schedule is null)
{
return Results.NotFound();
}
var (error, next) = Validate(request);
if (error is not null)
{
return Results.BadRequest(new { error });
}
if (await db.Schedules.AnyAsync(
s => s.Id != id && s.Name == request.Name.Trim(), cancellationToken))
{
return Results.BadRequest(new { error = "A schedule with that name already exists." });
}
var actor = context.User.Identity?.Name;
schedule.Name = request.Name.Trim();
Apply(schedule, request, next, actor);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-updated", actor,
detail: $"schedule={schedule.Name} enabled={schedule.Enabled}", cancellationToken: cancellationToken);
var assignments = await LoadAssignmentDtosAsync(db, null, schedule.Id, cancellationToken);
return Results.Ok(ToDto(schedule, assignments));
}
private static async Task<IResult> DeleteAsync(
Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
var schedule = await db.Schedules.SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
if (schedule is null)
{
return Results.NotFound();
}
// Assignments cascade with the schedule.
db.Schedules.Remove(schedule);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-deleted", context.User.Identity?.Name,
detail: schedule.Name, cancellationToken: cancellationToken);
return Results.NoContent();
}
/// <summary>Validates a cron and returns its next occurrences — the UI's ground truth.</summary>
private static IResult Preview(SchedulePreviewRequest request)
{
var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId;
var error = ScheduleCron.Validate(request.CronExpression, timeZoneId);
if (error is not null)
{
return Results.Ok(new SchedulePreviewDto(false, error, []));
}
var next = ScheduleCron.NextOccurrences(
request.CronExpression, timeZoneId, DateTimeOffset.UtcNow, count: 5);
return Results.Ok(new SchedulePreviewDto(true, null, next));
}
// ── Assignments ──────────────────────────────────────────────────────
private static async Task<IResult> ListAssignmentsAsync(
AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken)
=> Results.Ok(await LoadAssignmentDtosAsync(db, scriptId, scheduleId, cancellationToken));
private static async Task<IResult> CreateAssignmentAsync(
SaveScheduleAssignmentRequest request,
AppDbContext db,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error)
{
return Results.BadRequest(new { error });
}
var actor = context.User.Identity?.Name;
var assignment = new ScriptScheduleEntity
{
Id = Guid.NewGuid(),
ScheduleId = request.ScheduleId,
ScriptId = request.ScriptId,
ClientId = request.ClientId,
GroupId = request.GroupId,
ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null,
Enabled = request.Enabled,
CreatedUtc = DateTimeOffset.UtcNow,
CreatedBy = actor,
};
db.ScriptSchedules.Add(assignment);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-attached", actor,
detail: $"schedule={request.ScheduleId} script={request.ScriptId}", cancellationToken: cancellationToken);
var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken);
return Results.Created(
ApiRoutes.For.ScheduleAssignment(assignment.Id),
dtos.Single(a => a.Id == assignment.Id));
}
private static async Task<IResult> UpdateAssignmentAsync(
Guid id,
SaveScheduleAssignmentRequest request,
AppDbContext db,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken);
if (assignment is null)
{
return Results.NotFound();
}
if (await ValidateAssignmentAsync(request, db, cancellationToken) is { } error)
{
return Results.BadRequest(new { error });
}
assignment.ScheduleId = request.ScheduleId;
assignment.ScriptId = request.ScriptId;
assignment.ClientId = request.ClientId;
assignment.GroupId = request.GroupId;
assignment.Enabled = request.Enabled;
// Null keeps stored values so enable/disable round-trips.
if (request.Arguments is { Count: > 0 })
{
assignment.ArgumentsJson = JsonDefaults.Serialize(request.Arguments);
}
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-assignment-updated", context.User.Identity?.Name,
detail: $"assignment={id} enabled={assignment.Enabled}", cancellationToken: cancellationToken);
var dtos = await LoadAssignmentDtosAsync(db, null, null, cancellationToken);
return Results.Ok(dtos.Single(a => a.Id == id));
}
private static async Task<IResult> DeleteAssignmentAsync(
Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
var assignment = await db.ScriptSchedules.SingleOrDefaultAsync(a => a.Id == id, cancellationToken);
if (assignment is null)
{
return Results.NotFound();
}
db.ScriptSchedules.Remove(assignment);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Jobs, "schedule-detached", context.User.Identity?.Name,
detail: $"assignment={id}", cancellationToken: cancellationToken);
return Results.NoContent();
}
// ── Helpers ──────────────────────────────────────────────────────────
private static (string? Error, DateTimeOffset? NextRunUtc) Validate(SaveScheduleRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
{
return ("Schedule name is required.", null);
}
var hasCron = !string.IsNullOrWhiteSpace(request.CronExpression);
if (hasCron == (request.RunOnceUtc is not null))
{
return ("Provide exactly one of cronExpression (recurring) or runOnceUtc (one-shot).", null);
}
var timeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId;
if (hasCron)
{
var error = ScheduleCron.Validate(request.CronExpression!, timeZoneId);
if (error is not null)
{
return (error, null);
}
var next = ScheduleCron.NextOccurrence(request.CronExpression!, timeZoneId, DateTimeOffset.UtcNow);
return next is null ? ("The cron expression never fires.", null) : (null, next);
}
return request.RunOnceUtc <= DateTimeOffset.UtcNow.AddMinutes(-1)
? ("The one-shot time is in the past.", null)
: (null, request.RunOnceUtc);
}
private static void Apply(
ScheduleEntity schedule, SaveScheduleRequest request, DateTimeOffset? next, string? actor)
{
schedule.CronExpression = string.IsNullOrWhiteSpace(request.CronExpression)
? null
: request.CronExpression.Trim();
schedule.RunOnceUtc = request.RunOnceUtc;
schedule.TimeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId;
schedule.Enabled = request.Enabled;
schedule.NextRunUtc = request.Enabled ? next : null;
schedule.UpdatedUtc = DateTimeOffset.UtcNow;
schedule.UpdatedBy = actor;
}
private static async Task<string?> ValidateAssignmentAsync(
SaveScheduleAssignmentRequest request, AppDbContext db, CancellationToken cancellationToken)
{
if ((request.ClientId is null) == (request.GroupId is null))
{
return "Target exactly one of clientId or groupId.";
}
if (!await db.Schedules.AnyAsync(s => s.Id == request.ScheduleId, cancellationToken))
{
return "Schedule not found.";
}
if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken))
{
return "Script not found.";
}
if (request.ClientId is { } clientId
&& !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken))
{
return "Device not found.";
}
if (request.GroupId is { } groupId
&& !await db.DeviceGroups.AnyAsync(g => g.Id == groupId, cancellationToken))
{
return "Group not found.";
}
return null;
}
private static async Task<List<ScheduleAssignmentDto>> LoadAssignmentDtosAsync(
AppDbContext db, Guid? scriptId, Guid? scheduleId, CancellationToken cancellationToken)
{
var query = db.ScriptSchedules.AsNoTracking().AsQueryable();
if (scriptId is { } sid)
{
query = query.Where(a => a.ScriptId == sid);
}
if (scheduleId is { } schedId)
{
query = query.Where(a => a.ScheduleId == schedId);
}
var assignments = await query.OrderBy(a => a.CreatedUtc).ToListAsync(cancellationToken);
var scheduleIds = assignments.Select(a => a.ScheduleId).Distinct().ToList();
var schedules = await db.Schedules.AsNoTracking()
.Where(s => scheduleIds.Contains(s.Id))
.ToDictionaryAsync(s => s.Id, cancellationToken);
var scriptIds = assignments.Select(a => a.ScriptId).Distinct().ToList();
var scriptNames = await db.Scripts.AsNoTracking()
.Where(s => scriptIds.Contains(s.Id))
.ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken);
var clientIds = assignments.Where(a => a.ClientId != null).Select(a => a.ClientId!).Distinct().ToList();
var hostnames = await db.Devices.AsNoTracking()
.Where(d => clientIds.Contains(d.ClientId))
.ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken);
var groupIds = assignments.Where(a => a.GroupId != null).Select(a => a.GroupId!.Value).Distinct().ToList();
var groupNames = await db.DeviceGroups.AsNoTracking()
.Where(g => groupIds.Contains(g.Id))
.ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken);
return assignments.Select(a =>
{
var schedule = schedules.GetValueOrDefault(a.ScheduleId);
return new ScheduleAssignmentDto(
a.Id,
a.ScheduleId,
schedule?.Name,
schedule?.CronExpression,
schedule?.RunOnceUtc,
schedule?.TimeZoneId ?? "UTC",
schedule?.Enabled ?? false,
schedule?.NextRunUtc,
a.ScriptId,
scriptNames.GetValueOrDefault(a.ScriptId),
a.ClientId,
a.ClientId is null ? null : hostnames.GetValueOrDefault(a.ClientId),
a.GroupId,
a.GroupId is null ? null : groupNames.GetValueOrDefault(a.GroupId.Value),
a.Enabled,
a.LastRunUtc,
a.LastResult);
}).ToList();
}
internal static ScheduleDto ToDto(ScheduleEntity s, IReadOnlyList<ScheduleAssignmentDto> assignments) => new(
s.Id,
s.Name,
s.CronExpression,
s.RunOnceUtc,
s.TimeZoneId,
s.Enabled,
s.NextRunUtc,
s.LastRunUtc,
s.UpdatedUtc,
s.UpdatedBy,
assignments);
}
+226
View File
@@ -0,0 +1,226 @@
using System.Text.Json;
using Backend.Data;
using Backend.Groups;
using Backend.Secrets;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Serialization;
namespace Backend.Jobs;
/// <summary>
/// Fires due schedules: every enabled assignment (script + target + stored run
/// values) honoring the schedule runs through the normal job pipeline.
/// Recurrence advances from "now" after each firing, so downtime never causes
/// a storm of catch-up runs — at most one late firing per schedule.
/// </summary>
public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger<ScheduleWorker> logger)
: BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(30);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await FireDueSchedulesAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
logger.LogError(ex, "Schedule sweep failed");
}
try
{
await Task.Delay(PollInterval, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
internal async Task FireDueSchedulesAsync(CancellationToken cancellationToken)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var runner = scope.ServiceProvider.GetRequiredService<JobRunner>();
var groups = scope.ServiceProvider.GetRequiredService<DeviceGroupService>();
var now = DateTimeOffset.UtcNow;
var due = await db.Schedules
.Where(s => s.Enabled && s.NextRunUtc != null && s.NextRunUtc <= now)
.ToListAsync(cancellationToken);
foreach (var schedule in due)
{
try
{
await FireAsync(schedule, db, runner, groups, cancellationToken);
}
catch (Exception ex)
{
logger.LogError(ex, "Schedule {ScheduleId} ({Name}) failed to fire", schedule.Id, schedule.Name);
}
Advance(schedule);
await db.SaveChangesAsync(cancellationToken);
}
}
private async Task FireAsync(
ScheduleEntity schedule,
AppDbContext db,
JobRunner runner,
DeviceGroupService groups,
CancellationToken cancellationToken)
{
var assignments = await db.ScriptSchedules
.Where(a => a.ScheduleId == schedule.Id && a.Enabled)
.ToListAsync(cancellationToken);
if (assignments.Count == 0)
{
return;
}
// One preparation (prelude + secrets) per script per firing, shared by
// every assignment and target using it.
var prepared = new Dictionary<Guid, PreparedScript>();
foreach (var assignment in assignments)
{
try
{
await FireAssignmentAsync(schedule, assignment, prepared, db, runner, groups, cancellationToken);
}
catch (Exception ex)
{
assignment.LastRunUtc = DateTimeOffset.UtcNow;
assignment.LastResult = ex.Message;
logger.LogError(ex,
"Schedule {Name}: assignment {AssignmentId} failed", schedule.Name, assignment.Id);
}
}
}
private async Task FireAssignmentAsync(
ScheduleEntity schedule,
ScriptScheduleEntity assignment,
Dictionary<Guid, PreparedScript> prepared,
AppDbContext db,
JobRunner runner,
DeviceGroupService groups,
CancellationToken cancellationToken)
{
assignment.LastRunUtc = DateTimeOffset.UtcNow;
var script = await db.Scripts.AsNoTracking()
.SingleOrDefaultAsync(s => s.Id == assignment.ScriptId, cancellationToken);
if (script is null)
{
assignment.Enabled = false;
assignment.LastResult = "Disabled: the script no longer exists.";
return;
}
var devices = await ResolveTargetsAsync(assignment, db, groups, cancellationToken);
if (devices.Count == 0)
{
assignment.LastResult = "No eligible devices at fire time.";
return;
}
if (!prepared.TryGetValue(script.Id, out var preparedScript))
{
try
{
preparedScript = await runner.PrepareAsync(script, cancellationToken);
prepared[script.Id] = preparedScript;
}
catch (SecretResolutionException ex)
{
assignment.LastResult = ex.Message;
logger.LogWarning("Schedule {Name}: {Message}", schedule.Name, ex.Message);
return;
}
}
var arguments = string.IsNullOrWhiteSpace(assignment.ArgumentsJson)
? null
: JsonDefaults.Deserialize<Dictionary<string, JsonElement>>(assignment.ArgumentsJson);
var queued = 0;
foreach (var device in devices)
{
var job = await runner.CreateJobAsync(
script, device.ClientId, $"schedule:{schedule.Name}", cancellationToken);
await runner.DispatchAsync(
prepared[script.Id], job, arguments,
$"Schedule “{schedule.Name}” queued “{script.Name}” for {device.Hostname}",
cancellationToken);
queued++;
}
assignment.LastResult = $"{queued} job(s) queued";
logger.LogInformation(
"Schedule {Name} queued {Count} job(s) of “{Script}”", schedule.Name, queued, script.Name);
}
private static async Task<List<DeviceEntity>> ResolveTargetsAsync(
ScriptScheduleEntity assignment,
AppDbContext db,
DeviceGroupService groups,
CancellationToken cancellationToken)
{
if (assignment.ClientId is { } clientId)
{
var device = await db.Devices.AsNoTracking()
.SingleOrDefaultAsync(d => d.ClientId == clientId && !d.IsOrphaned, cancellationToken);
return device is null ? [] : [device];
}
var group = await db.DeviceGroups.AsNoTracking()
.SingleOrDefaultAsync(g => g.Id == assignment.GroupId, cancellationToken);
if (group is null)
{
return [];
}
var memberIds = await groups.GetMembersAsync(group, cancellationToken);
return await db.Devices.AsNoTracking()
.Where(d => memberIds.Contains(d.ClientId) && !d.IsOrphaned)
.ToListAsync(cancellationToken);
}
private static void Advance(ScheduleEntity schedule)
{
schedule.LastRunUtc = DateTimeOffset.UtcNow;
if (schedule.CronExpression is { } cron)
{
try
{
schedule.NextRunUtc = ScheduleCron.NextOccurrence(
cron, schedule.TimeZoneId, DateTimeOffset.UtcNow);
}
catch (Exception)
{
// Stored expression went bad (should be impossible past validation).
schedule.Enabled = false;
schedule.NextRunUtc = null;
}
}
else
{
// One-shot: done.
schedule.Enabled = false;
schedule.NextRunUtc = null;
}
}
}
+35 -5
View File
@@ -11,7 +11,9 @@ using Backend.Nats;
using Backend.Proxy;
using Backend.Scripts;
using Backend.Security;
using Backend.Settings;
using Backend.Shell;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Serilog;
@@ -26,6 +28,13 @@ if (args.Length > 0 && args[0] == "nats-auth")
return NatsAuthCli.Run(args[1..]);
}
// CLI mode: lockout recovery — disable OIDC and restore local sign-in.
if (args.Length > 0 && args[0] == "auth-reset")
{
var cliConfig = new ConfigurationBuilder().AddEnvironmentVariables().Build();
return await AuthResetCli.RunAsync(args[1..], cliConfig);
}
var builder = WebApplication.CreateBuilder(args);
// ── Logging ──────────────────────────────────────────────────────────────
@@ -62,10 +71,11 @@ builder.Services.AddScoped<DeviceGroupService>();
builder.Services.AddScoped<ScriptTriggerService>();
// ── Authentication / authorization ─────────────────────────────────────────
var oidcOptions = OidcOptions.FromConfiguration(builder.Configuration);
builder.Services.AddSingleton(oidcOptions);
// Environment values bootstrap authentication; the Settings UI overrides them
// and the OIDC handler is rebuilt on save without a restart.
var authBootstrap = AuthBootstrap.FromConfiguration(builder.Configuration);
builder.Services.AddScoped<UserService>();
builder.AddControlPlaneAuth(oidcOptions);
builder.AddControlPlaneAuth(authBootstrap);
// ── Messaging ────────────────────────────────────────────────────────────
builder.Services.AddSingleton<NatsCredentialIssuer>();
@@ -74,10 +84,26 @@ builder.Services.AddSingleton<JetStreamProvisioner>();
builder.Services.AddSingleton<BrowserSessionRegistry>();
builder.Services.AddSingleton<BrowserEventBroadcaster>();
builder.Services.AddSingleton<CommandDispatcher>();
builder.Services.AddScoped<JobRunner>();
// S3: environment values are the bootstrap defaults; anything saved from the
// Settings UI overrides them, so these are resolved per-request.
builder.Services.AddSingleton(S3Options.FromConfiguration(builder.Configuration));
builder.Services.AddSingleton<S3PresignService>();
builder.Services.AddDataProtection().PersistKeysToFileSystem(
new DirectoryInfo(builder.Configuration["DATAPROTECTION_PATH"] is { Length: > 0 } dp
? dp
: Path.Combine(Path.GetDirectoryName(Path.GetFullPath(
builder.Configuration["DATABASE_PATH"] ?? "data/app.db")) ?? "data", "keys")));
builder.Services.AddScoped<SettingsStore>();
builder.Services.AddScoped<S3SettingsService>();
builder.Services.AddScoped<S3PresignService>();
builder.Services.AddScoped<AgentPackageService>();
// Secrets providers: pluggable drivers; add implementations here.
builder.Services.AddHttpClient();
builder.Services.AddSingleton<Backend.Secrets.ISecretsProviderDriver, Backend.Secrets.InfisicalDriver>();
builder.Services.AddScoped<Backend.Secrets.SecretsProviderService>();
builder.Services.AddSingleton<ShellBridge>();
builder.Services.AddHostedService<MessagingWorkers>();
builder.Services.AddHostedService<ScheduleWorker>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<ShellBridge>());
// ── Rate limiting ────────────────────────────────────────────────────────
@@ -237,19 +263,23 @@ app.MapGet(ApiRoutes.Ready, async (AppDbContext db, NatsHub hub, NatsCredentialI
return ready ? Results.Ok(payload) : Results.Json(payload, statusCode: StatusCodes.Status503ServiceUnavailable);
});
AuthEndpoints.Map(app, oidcOptions);
AuthEndpoints.Map(app);
AuthSettingsEndpoints.Map(app);
EnrollmentEndpoints.Map(app);
InstallEndpoints.Map(app);
DeviceEndpoints.Map(app);
ScriptEndpoints.Map(app);
FunctionEndpoints.Map(app);
JobEndpoints.Map(app);
ScheduleEndpoints.Map(app);
BootstrapTokenEndpoints.Map(app);
MessagingEndpoints.Map(app);
ShellEndpoints.Map(app);
FileDeliveryEndpoints.Map(app);
GroupEndpoints.Map(app);
TriggerEndpoints.Map(app);
SettingsEndpoints.Map(app);
Backend.Secrets.SecretsEndpoints.Map(app);
app.Run();
return 0;
+21
View File
@@ -0,0 +1,21 @@
namespace Backend.Proxy;
/// <summary>
/// The externally reachable base URL: <c>PUBLIC_SERVER_URL</c> when set,
/// otherwise derived from the request after the forwarded-headers middleware
/// applied scheme/host from trusted proxies. Used everywhere a URL is shown
/// to an operator or baked into an install command.
/// </summary>
public static class PublicUrl
{
public static string Resolve(HttpContext context, IConfiguration configuration)
{
var configured = configuration["PUBLIC_SERVER_URL"];
return !string.IsNullOrWhiteSpace(configured)
? configured.TrimEnd('/')
: $"{context.Request.Scheme}://{context.Request.Host}";
}
public static bool IsConfigured(IConfiguration configuration)
=> !string.IsNullOrWhiteSpace(configuration["PUBLIC_SERVER_URL"]);
}
+64 -2
View File
@@ -43,6 +43,11 @@ public static class ScriptEndpoints
return Results.BadRequest(new { error = "Script name is required." });
}
if (ValidateSecrets(request) is { } secretsProblem)
{
return secretsProblem;
}
var now = DateTimeOffset.UtcNow;
var actor = context.User.Identity?.Name;
var script = new ScriptEntity
@@ -54,6 +59,8 @@ public static class ScriptEndpoints
Content = request.Content ?? string.Empty,
ParametersJson = SerializeParameters(request.Parameters),
FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds),
SecretBindingsJson = SerializeSecretBindings(request.SecretBindings),
SecretsVariableName = NormalizeVariableName(request.SecretsVariableName),
CreatedUtc = now,
UpdatedUtc = now,
CreatedBy = actor,
@@ -80,11 +87,18 @@ public static class ScriptEndpoints
return Results.BadRequest(new { error = "Script name is required." });
}
if (ValidateSecrets(request) is { } secretsProblem)
{
return secretsProblem;
}
script.Name = request.Name.Trim();
script.Description = request.Description;
script.Content = request.Content ?? string.Empty;
script.ParametersJson = SerializeParameters(request.Parameters);
script.FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds);
script.SecretBindingsJson = SerializeSecretBindings(request.SecretBindings);
script.SecretsVariableName = NormalizeVariableName(request.SecretsVariableName);
script.UpdatedUtc = DateTimeOffset.UtcNow;
script.UpdatedBy = context.User.Identity?.Name;
await db.SaveChangesAsync(cancellationToken);
@@ -114,15 +128,63 @@ public static class ScriptEndpoints
script.Id, script.Name, script.Description, script.Language, script.Content,
DeserializeParameters(script.ParametersJson),
DeserializeModuleIds(script.FunctionModuleIdsJson),
script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy);
script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy,
DeserializeSecretBindings(script.SecretBindingsJson),
script.SecretsVariableName);
/// <summary>The injected dictionary must bind to a legal PowerShell variable name.</summary>
private static IResult? ValidateSecrets(SaveScriptRequest request)
{
var name = request.SecretsVariableName?.Trim();
if (!string.IsNullOrEmpty(name)
&& !System.Text.RegularExpressions.Regex.IsMatch(name, "^[A-Za-z_][A-Za-z0-9_]*$"))
{
return Results.BadRequest(new
{
error = "Secrets variable name must be a valid PowerShell variable name (letters, digits, underscore).",
});
}
if (request.SecretBindings?.Any(b => string.IsNullOrWhiteSpace(b.Name) || string.IsNullOrWhiteSpace(b.SecretName)) == true)
{
return Results.BadRequest(new { error = "Every secret binding needs a name and a secret to fetch." });
}
return null;
}
internal static string? NormalizeVariableName(string? name)
=> string.IsNullOrWhiteSpace(name) ? null : name.Trim();
internal static string? SerializeParameters(IReadOnlyList<ScriptParameter>? parameters)
=> parameters is null || parameters.Count == 0 ? null : JsonDefaults.Serialize(parameters);
internal static IReadOnlyList<ScriptParameter> DeserializeParameters(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonDefaults.Deserialize<List<ScriptParameter>>(json) ?? [];
}
catch (System.Text.Json.JsonException)
{
// Schema drift in stored definitions (e.g. removed enum values):
// degrade to "no parameters" instead of breaking every script read.
return [];
}
}
internal static string? SerializeSecretBindings(IReadOnlyList<SecretBinding>? bindings)
=> bindings is null || bindings.Count == 0 ? null : JsonDefaults.Serialize(bindings);
internal static IReadOnlyList<SecretBinding> DeserializeSecretBindings(string? json)
=> string.IsNullOrWhiteSpace(json)
? []
: JsonDefaults.Deserialize<List<ScriptParameter>>(json) ?? [];
: JsonDefaults.Deserialize<List<SecretBinding>>(json) ?? [];
internal static string? SerializeModuleIds(IReadOnlyList<Guid>? ids)
=> ids is null || ids.Count == 0 ? null : JsonDefaults.Serialize(ids);

Some files were not shown because too many files have changed in this diff Show More