diff --git a/.claude/COMPOSE-SPEC.md b/.claude/COMPOSE-SPEC.md new file mode 100644 index 0000000..753dfce --- /dev/null +++ b/.claude/COMPOSE-SPEC.md @@ -0,0 +1,222 @@ +# Docker Compose Stack Specification + +## File Header +```yaml +#============================================================================= +# {STACK_NAME} - {Description} +# {URL} +#============================================================================= +# +# CREDENTIALS: +# {credential format} +# +# PRODUCTION SETUP: +# 1. {step} +# 2. {step} +# +# ENDPOINTS: +# - {endpoint}: {url} +# +#============================================================================= + +name: '${STACK_NAME:-stk-{name}-00001}' +``` + +## Networks +```yaml +networks: + EXTERNAL: + name: {STACKNAME}-EXTERNAL + driver: bridge + internal: false + attachable: true + INTERNAL: + name: {STACKNAME}-INTERNAL + driver: bridge + internal: true + attachable: true +``` + +## Services + +### Container Naming +- Format: `{STACKNAME}-{TIER}-00001` +- Tiers: `DB`, `CACHE`, `APP`, `WORKER`, `PROXY` +- Example: `NETBOX-DB-00001`, `CLOUDREVE-APP-00001` + +### No Hostnames +- Do NOT use `hostname:` - use compose service names for internal networking +- Reference other services by service name: `DB`, `Cache`, `App` + +### Ports vs Expose +- Services on INTERNAL network only: use `expose:` — NO host `ports:` binding +- Services on EXTERNAL network (or needing host access): use `ports:` for host-bound ports +- Exception: if the Docker daemon must reach the container (e.g. syslog driver), a loopback `ports:` bind is required even on INTERNAL +```yaml +# INTERNAL-only service — expose only, no host port + expose: + - '{port}' + +# EXTERNAL service or host-accessible — bind to host + ports: + - '${APP_PORT:-18080}:8080' + +# Exception: loopback-only for Docker daemon access (e.g. syslog collector) + # NOTE: Host port required - Docker syslog driver sends from host daemon to this container + ports: + - '127.0.0.1:1514:10514' +``` + +### Published Port Selection +Host-published ports must avoid well-known/commonly-conflicting ports to prevent collisions +when multiple stacks coexist on the same host. +- DO NOT publish on `80`, `443`, `8080`, `8000`, `8443`, `3000`, `5000`, `9000`, `9090`, `9443` +- Pick a random uncommon port in the high range (e.g. `10000`–`29999`) that is not + already used by another stack in this repository +- The container-internal port stays at the application's native value + (e.g. `:80` for a webserver) — only the host-side is remapped +- Both the compose default and the `.env` value should use the same uncommon port + (port values are NOT secrets and need not differ) +```yaml +# Good — host-side mapped to an uncommon port, container-side untouched + ports: + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${HTTP_PORT:-18472}:80' + +# Bad — publishes on a commonly-used host port + ports: + - '${HTTP_PORT:-80}:80' +``` + +### Standard Service Block +```yaml + {ServiceName}: + image: '${IMAGE:-default/image}:${VERSION:-tag}' + container_name: {STACKNAME}-{TIER}-00001 + restart: unless-stopped + stop_signal: SIGTERM + stop_grace_period: 30s + user: "${PUID:-1000}:${PGID:-1000}" + logging: + driver: 'local' + networks: + INTERNAL: + expose: + - '{port}' + environment: + VAR_NAME: '${VAR_NAME:-DefaultValue}' + volumes: + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + - "${STACK_BINDMOUNTROOT:-/mnt/docker/stacks}/${STACK_NAME:-stk-name-00001}/{Tier}/Data:/container/path:rw" + healthcheck: + test: ["CMD", "command", "args"] + start_period: 30s + interval: 10s + retries: 5 + timeout: 5s + labels: + com.centurylinklabs.watchtower.enable: '${ENABLEAUTOMATICUPDATES:-false}' +``` + +## Bind Mounts +- Format: `"${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-name-00001}/{Tier}/Data:/container/path:rw"` +- Tiers: `App`, `DB`, `Cache` +- Always use `:rw` or `:ro` suffix + +## Secrets & Defaults +- Compose defaults MUST differ from .env values +- Both must be actual secure random strings (not placeholder text) +- Generate with: `openssl rand -base64 24` (passwords) or `openssl rand -base64 50` (keys) +- Compose: `${PASSWORD:-xK9mZ7vQ3wL8nP2jR5tY0uA4}` (random default) +- .env: `PASSWORD=bH3nF6kM9pL2sW5xY8cD1eG4` (different random value) + +## Image Variables +```yaml +image: '${IMAGE_NAME:-default/image}:${IMAGE_VERSION:-tag}' +``` +Examples: +- `'${POSTGRES_IMAGE:-postgres}:${POSTGRES_VERSION:-17-alpine}'` +- `'${VALKEY_IMAGE:-valkey/valkey}:${VALKEY_VERSION:-9.0-alpine}'` + +## SHA256 Image Pinning +Pin critical infrastructure images (DB, cache, message brokers, init/dependency +containers) to a specific digest for reproducibility and security: +```yaml +image: '${IMAGE:-default/image}:${VERSION:-tag@sha256:abc123...}' +``` +- Always pin: database images (Postgres, MySQL, MongoDB, MSSQL, etc.), + cache images (Valkey, Redis-compatible), message brokers (NATS, RabbitMQ), + search/index stores (Quickwit, Meilisearch, Elasticsearch), object stores + (MinIO), and any other dependency/init container where image drift could + cause data corruption, schema mismatches, or silent breakage +- The `@sha256:` digest goes AFTER the tag in the VERSION variable +- Compose default AND .env value must both include the same digest + +### Obtaining the Correct Digest +ONLY use a digest obtained from a successful local pull. NEVER copy a digest +from the Docker Hub web UI tag list — that view shows multiple manifests per +tag (per-arch images PLUS attestation manifests), and attestation manifests +are served with media type `application/octet-stream` / `application/vnd.in-toto+json` +which containerd cannot unpack as an image. Symptom: +``` +failed to unpack image on snapshotter overlayfs: unexpected media type +application/octet-stream for sha256:: not found +``` +Correct procedure: +```bash +# 1. Pull the tag (resolves the multi-arch index to your host's image manifest) +docker pull image:tag + +# 2. Read back the digest of the actual image manifest that was pulled +docker inspect --format='{{index .RepoDigests 0}}' image:tag +# -> image@sha256: + +# 3. Verify the digest is pullable on its own before committing it +docker pull image@sha256: +``` +Update workflow when bumping a pinned image: re-run the three steps above, +then update both the compose default and the matching `.env` value. + +Examples: +- `'${POSTGRES_VERSION:-17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527}'` +- `'${VALKEY_VERSION:-9.0-alpine@sha256:d1cc70645bbcef743615463a2fa4616e841407545e18f560aed0c49671a90147}'` +- `'${HARBOR_DB_VERSION:-v2.15.0@sha256:b54e48a70a7b...}'` + +## Cache (Valkey) +Always use Valkey, never Redis: +```yaml + Cache: + image: '${VALKEY_IMAGE:-valkey/valkey}:${VALKEY_VERSION:-9.0-alpine}' + container_name: {STACKNAME}-CACHE-00001 + command: ["valkey-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD:-DefaultCachePass123}"] +``` + +## Network References +- Internal services reference each other by **service name**: `DB`, `Cache`, `App` +- NOT by container name: ~~`NETBOX-DB-00001`~~ + +## Reverse Proxy / Nginx Inclusion +A dedicated `Proxy` (nginx) service is only included when it serves a real +runtime role in the stack. Do NOT add nginx solely to "front" an app that +already listens on HTTP — publish the app directly with an uncommon host port. + +Include an in-stack nginx (or equivalent) ONLY when: +- It acts as the application's **webserver** (e.g. serves static assets, + PHP-FPM upstream, runtime SSI/auth_request, app-specific URL rewrites that + the app image itself does not provide), OR +- It acts as an **internal reverse proxy that fans out edge requests** across + multiple in-stack services (e.g. routes `/api` → backend, `/` → frontend, + `/ws` → websocket service, or merges multiple sibling services behind a + single host port). + +Do NOT include nginx when: +- The app image already exposes a single HTTP port that can be published directly +- The only goal is TLS termination or a public hostname — that belongs to the + host-level edge proxy (NPM, Traefik, Caddy, etc.), not the stack +- The app embeds its own webserver/router and no fan-out is required + +When nginx is included, it follows the standard service block conventions: +- Service name `Proxy`, container `{STACKNAME}-PROXY-00001` +- Sits on `EXTERNAL` + `INTERNAL`, publishes on an uncommon host port +- Config is bind-mounted from `${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Config/...:ro` + diff --git a/.claude/DesignSpecification.MVP.md b/.claude/DesignSpecification.MVP.md new file mode 100644 index 0000000..39e6685 --- /dev/null +++ b/.claude/DesignSpecification.MVP.md @@ -0,0 +1,2785 @@ +# End-to-End MVP Specification +## .NET Agent + NATS over WebSocket + ASP.NET Core Backend + SvelteKit Web UI + +**Document purpose:** Build-ready MVP specification for Claude or another coding agent. + +**Primary goal:** Demonstrate a complete, methodical, secure management loop from Windows agent enrollment through live device inventory, near-real-time progress, remote interactive shell, PowerShell script authoring/execution, and near-live job output using NATS heavily as the real-time messaging fabric. + +**MVP constraint:** This specification intentionally excludes broad enterprise features that are not required to prove the architecture. Every feature listed here must work end-to-end before expanding scope. + +--- + +# 1. Required Technology Baseline + +Use the current supported .NET LTS/runtime available to the build environment, targeting **.NET 10** for the MVP unless an implementation blocker requires otherwise. + +Primary technologies: + +- .NET 10 / C# +- ASP.NET Core +- `Microsoft.Extensions.Hosting` +- `NATS.Net` current stable client +- NATS Server current stable 2.x +- NATS JetStream +- System.Management.Automation SDK for PowerShell execution +- Windows CIM/WMI APIs for stable hardware identity and inventory +- SvelteKit +- TypeScript +- Monaco Editor for browser script editing +- xterm.js for browser terminal rendering +- SQLite for MVP backend persistence +- Docker / Docker Compose +- Gitea Actions-compatible CI/CD +- ImageMagick during build only for icon generation +- MSI packaging for the Windows agent + +All .NET code belongs below `/src`. + +--- + +# 2. Repository Layout + +Use the following repository structure exactly unless a platform limitation requires a small variation: + +```text +/ +├── .gitea/ +│ └── workflows/ +│ ├── ci.yml +│ └── release.yml +├── .gitignore +├── .editorconfig +├── Directory.Build.props +├── Directory.Packages.props +├── global.json +├── README.md +├── LICENSE +├── docker-compose.yml +├── docker-compose.dev.yml +├── .env.example +├── assets/ +│ ├── icon-source.png +│ └── README.md +├── scripts/ +│ ├── Initialize-Repository.ps1 +│ ├── New-LocalSecrets.ps1 +│ ├── Build.ps1 +│ ├── Test.ps1 +│ ├── Package-Agent.ps1 +│ └── Generate-Icons.ps1 +├── secrets/ +│ └── README.md +├── src/ +│ ├── Agent/ +│ │ ├── Agent.csproj +│ │ ├── Program.cs +│ │ ├── Commands/ +│ │ ├── Configuration/ +│ │ ├── Enrollment/ +│ │ ├── Identity/ +│ │ ├── Inventory/ +│ │ ├── Messaging/ +│ │ ├── PowerShell/ +│ │ ├── Progress/ +│ │ ├── Service/ +│ │ ├── Shell/ +│ │ └── Storage/ +│ ├── Backend/ +│ │ ├── Backend.csproj +│ │ ├── Program.cs +│ │ ├── Api/ +│ │ ├── Auth/ +│ │ ├── Data/ +│ │ ├── Enrollment/ +│ │ ├── Jobs/ +│ │ ├── Messaging/ +│ │ ├── Nats/ +│ │ ├── Proxy/ +│ │ ├── Scripts/ +│ │ └── Security/ +│ ├── WebUI/ +│ │ ├── package.json +│ │ ├── svelte.config.js +│ │ ├── vite.config.ts +│ │ ├── src/ +│ │ │ ├── lib/ +│ │ │ │ ├── api/ +│ │ │ │ ├── auth/ +│ │ │ │ ├── components/ +│ │ │ │ ├── messaging/ +│ │ │ │ ├── stores/ +│ │ │ │ └── theme/ +│ │ │ └── routes/ +│ │ └── static/ +│ ├── Shared.Contracts/ +│ │ ├── Shared.Contracts.csproj +│ │ ├── Api/ +│ │ ├── Messages/ +│ │ ├── Models/ +│ │ └── Serialization/ +│ ├── Shared.Infrastructure/ +│ │ ├── Shared.Infrastructure.csproj +│ │ ├── Configuration/ +│ │ ├── Constants/ +│ │ ├── Nats/ +│ │ ├── Routing/ +│ │ ├── Security/ +│ │ └── Versioning/ +│ ├── Installer/ +│ │ ├── Agent.Installer.wixproj +│ │ └── Product.wxs +│ └── Infra/ +│ ├── nats/ +│ │ ├── nats.conf +│ │ └── resolver/ +│ ├── backend/ +│ │ └── Dockerfile +│ └── webui/ +│ └── Dockerfile +└── tests/ + ├── Agent.Tests/ + ├── Backend.Tests/ + ├── Shared.Tests/ + └── Integration.Tests/ +``` + +Do not scatter route strings, subject strings, registry paths, header names, claim names, or protocol constants throughout the solution. + +They must be centralized in shared code. + +--- + +# 3. Naming and Plumbing Rules + +The transport plumbing must remain generic and independent of a future product rename. + +Do not use product names in: + +- NATS subject names +- API route constants +- internal message type identifiers +- header names +- database table prefixes +- registry value names where avoidable +- internal service-to-service contracts + +Product branding may appear in UI text, executable names, Windows service display name, MSI metadata, and documentation only. + +Do not include `v1` in NATS subject names. + +API routes may use `/api/...`, but do not embed version segments for the MVP. + +--- + +# 4. Shared Route and Subject Definitions + +Create centralized strongly typed definitions. + +Example: + +```csharp +public static class ApiRoutes +{ + public const string Health = "/api/health"; + public const string Bootstrap = "/api/enrollment/bootstrap"; + public const string RefreshCredential = "/api/enrollment/credential"; + public const string Devices = "/api/devices"; + public const string Device = "/api/devices/{clientId}"; + public const string Scripts = "/api/scripts"; + public const string Jobs = "/api/jobs"; + public const string AuthLogin = "/api/auth/login"; + public const string AuthLogout = "/api/auth/logout"; + public const string AuthSession = "/api/auth/session"; + public const string AuthOidcLogin = "/api/auth/oidc/login"; + public const string AuthOidcCallback = "/api/auth/oidc/callback"; + public const string BrowserNatsCredential = "/api/messaging/credential"; +} +``` + +Create subject helpers instead of arbitrary interpolation throughout the application. + +Example conceptual subject map: + +```text +agent..presence +agent..inventory +agent..progress +agent..event + +agent..command.inventory +agent..command.script +agent..command.shell.open +agent..command.shell.input +agent..command.shell.resize +agent..command.shell.close + +agent..shell..output +agent..shell..state + +job..progress +job..output +job..state + +browser..event +browser..job. +browser..shell. + +system.agent.enrolled +system.agent.disconnected +system.job.created +system.job.completed +``` + +Use helper methods such as: + +```csharp +NatsSubjects.AgentPresence(clientId) +NatsSubjects.AgentInventory(clientId) +NatsSubjects.AgentScriptCommand(clientId) +NatsSubjects.JobProgress(jobId) +NatsSubjects.BrowserSession(sessionId) +``` + +Subject identifiers must be sanitized and validated centrally. + +--- + +# 5. Common Message Envelope + +All application NATS payloads must use JSON and a common envelope. + +```json +{ + "messageId": "uuid", + "correlationId": "uuid", + "causationId": "uuid", + "messageType": "job.progress", + "schemaVersion": 1, + "timestampUtc": "2026-08-06T21:00:00.000Z", + "source": { + "kind": "agent", + "id": "client-id" + }, + "target": { + "kind": "job", + "id": "uuid" + }, + "payload": {} +} +``` + +Rules: + +- `messageId` is always unique. +- `correlationId` stays constant for one logical operation. +- `causationId` references the message that caused the current message where applicable. +- `timestampUtc` is UTC ISO-8601. +- `schemaVersion` versions payload schema without versioning NATS subjects. +- unknown JSON properties must be ignored for forward compatibility. +- command handlers must be idempotent by `messageId` and/or durable `jobId`. + +--- + +# 6. Agent Binary + +## 6.1 Single Binary Behavior + +Produce one self-contained Windows x64 executable. + +Example executable name: + +```text +Agent.exe +``` + +Publish as: + +```text +win-x64 +self-contained=true +PublishSingleFile=true +``` + +The same binary must support: + +```text +Agent.exe foreground +Agent.exe install +Agent.exe remove +Agent.exe start +Agent.exe stop +Agent.exe initialize +Agent.exe status +Agent.exe version +``` + +Behavior: + +- `foreground`: run interactively using console logging. +- no command while launched by SCM: run as Windows service. +- `install`: idempotently create/update Windows service registration only. +- `start`: start installed service; no failure if already running. +- `stop`: stop service; no failure if already stopped. +- `initialize`: perform `install` followed by `start`. +- `remove`: stop if needed, remove service idempotently. +- `status`: output machine-readable and human-readable state. +- `version`: output unified build version. + +Service manipulation must use Windows APIs or managed service control APIs. Do not use `sc.exe` shell-outs. + +The service should use the .NET Generic Host and Windows Service integration. + +Default service account for MVP: + +```text +LocalSystem +``` + +Startup: + +```text +Automatic (Delayed Start) +``` + +Recovery policy: + +- restart service after first failure +- restart after second failure +- restart after subsequent failures +- reasonable delay such as 30 seconds + +Service install must update binary path and service metadata if the service already exists and the binary has moved. + +--- + +# 7. Agent Registry Configuration + +Use machine-level registry paths. + +Normal local configuration: + +```text +HKLM\SOFTWARE\\ +``` + +GPO policy path: + +```text +HKLM\SOFTWARE\Policies\\ +``` + +The actual company/product branding must be centralized in one constants file so it can be renamed later. + +Required values: + +```text +ServerURL REG_SZ +BootstrapToken REG_SZ +LogLevel REG_SZ +InventoryInterval REG_SZ +ReconnectMinDelay REG_SZ +ReconnectMaxDelay REG_SZ +AllowRemoteShell REG_DWORD +AllowScriptExecution REG_DWORD +``` + +Runtime-managed values belong below: + +```text +HKLM\SOFTWARE\\\Runtime +``` + +Examples: + +```text +ClientId +EnrollmentId +LastEnrollmentUtc +LastConnectedUtc +CredentialExpiresUtc +``` + +Do not store the NKey private seed as plain registry text. + +Use DPAPI LocalMachine protection for locally persisted credential material. + +--- + +# 8. Configuration Precedence + +The configuration resolver must support provenance and deterministic precedence. + +Highest to lowest: + +1. **GPO policy registry** +2. **normal machine registry** +3. **compiled defaults** + +MSI public properties write into the normal machine registry during installation, therefore GPO naturally remains authoritative. + +Environment variables may be supported for development/debugging but must not override GPO in production service mode. + +Each effective configuration value should internally expose: + +```csharp +Value +Source +IsPolicyControlled +``` + +Example source values: + +```text +GroupPolicy +Registry +EnvironmentDevelopmentOnly +Default +``` + +This is important for the future ADMX implementation. + +--- + +# 9. MSI Public Properties + +The MSI must accept these uppercase public properties: + +```text +SERVERURL +BOOTSTRAPTOKEN +LOGLEVEL +ALLOWREMOTESHELL +ALLOWSCRIPTEXECUTION +``` + +Example: + +```text +msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN= +``` + +Installer behavior: + +1. Install self-contained binary. +2. Write specified public property values to the normal registry path. +3. Do not write blank properties over existing nonblank registry values. +4. Configure Windows service. +5. Start service after successful install. +6. Preserve configured registry values during upgrade. +7. Remove runtime credentials during explicit full uninstall only if the uninstall is not an upgrade. +8. Bootstrap token must be erased after successful enrollment. + +The MSI must not include a hard-coded production bootstrap token. + +--- + +# 10. ServerURL Semantics + +Administrators configure only: + +```text +http://host +https://host +``` + +Do not require administrators to specify `ws://` or `wss://`. + +Agent conversion: + +```text +http:// -> ws:// +https:// -> wss:// +``` + +Examples: + +```text +https://control.example.com +``` + +becomes the NATS WebSocket endpoint: + +```text +wss://control.example.com/messaging/agent +``` + +and API calls remain: + +```text +https://control.example.com/api/... +``` + +If `ServerURL` contains a base path, normalize it centrally. + +Reject: + +- unsupported schemes +- embedded username/password +- fragments +- malformed hosts + +TLS certificate validation must be enabled by default and must not provide an MVP bypass switch. + +--- + +# 11. Deterministic Client Identity + +## 11.1 Goal + +Generate a client ID that remains stable across: + +- reboot +- IP change +- hostname change +- domain join/unjoin +- user change +- normal OS servicing +- agent reinstall + +Avoid using volatile values such as: + +- MAC address +- IP address +- hostname +- domain SID +- Windows installation ID +- current user +- disk volume serial + +## 11.2 CIM Inputs + +Use CIM/WMI from managed code. + +Preferred stable inputs, in order: + +1. `Win32_ComputerSystemProduct.UUID` +2. `Win32_BIOS.SerialNumber` +3. `Win32_BaseBoard.SerialNumber` +4. `Win32_ComputerSystemProduct.IdentifyingNumber` +5. `Win32_ComputerSystem.Manufacturer` +6. `Win32_ComputerSystem.Model` + +Normalize: + +- trim +- uppercase invariant +- remove obvious placeholder values +- reject known junk such as: + - `TO BE FILLED BY O.E.M.` + - `DEFAULT STRING` + - all zero UUID + - empty + - whitespace + - generic virtualization placeholders where better identifiers exist + +Construct a canonical identity string containing labeled values, for example: + +```text +UUID=|BIOS=|BOARD=|IDENT=|MFR=|MODEL= +``` + +Require at least one strong hardware identifier. + +Hash: + +```text +SHA-256 UTF-8(canonical identity) +``` + +Expose the client ID as lowercase base32 or lowercase hex. + +Recommended: + +```text +clientId = lowercase hex SHA-256 +``` + +Do not send the raw canonical fingerprint over NATS after enrollment unless specifically needed for diagnostics. + +Store the final client ID in runtime registry as a cache, but recompute it during initialization and verify it matches. + +If the recomputed identity materially differs after hardware replacement, treat the endpoint as a new device for MVP. + +--- + +# 12. Bootstrap and Enrollment Security + +## 12.1 Bootstrap Token Requirements + +Bootstrap token is: + +- one-time or use-limited +- server-generated +- random cryptographic value +- time-limited +- revocable +- never logged +- accepted only by HTTPS enrollment API +- deleted locally after successful enrollment + +Backend stores only a secure hash of the bootstrap token, not plaintext. + +Recommended minimum entropy: + +```text +32 random bytes +``` + +Encode URL-safe. + +## 12.2 Agent-Side NKey Generation + +Before bootstrap, the agent generates its own NATS user NKey key pair locally. + +Critical rule: + +**The agent private NKey seed never leaves the endpoint.** + +The bootstrap request sends the public NKey only. + +## 12.3 Bootstrap Request + +```http +POST /api/enrollment/bootstrap +Content-Type: application/json +``` + +Payload: + +```json +{ + "bootstrapToken": "", + "clientId": "", + "nkeyPublic": "", + "agentVersion": "2026.08.06.2151", + "device": { + "hostname": "PC-001", + "manufacturer": "...", + "model": "...", + "osCaption": "...", + "osVersion": "..." + } +} +``` + +## 12.4 Bootstrap Validation + +Backend: + +1. validate TLS/request normally +2. rate limit enrollment endpoint +3. hash supplied bootstrap token and locate matching active record +4. verify expiration +5. verify remaining use count +6. validate client ID syntax +7. validate NKey public key format +8. perform idempotent enrollment by client ID +9. bind public NKey to enrolled device +10. issue a NATS user JWT with scoped permissions +11. mark bootstrap token consumed when configured as one-time +12. audit enrollment +13. return enrollment result + +## 12.5 Agent NATS Permissions + +Agent user JWT may only publish/subscribe to subjects for its own client ID. + +Publish allow: + +```text +agent..presence +agent..inventory +agent..progress +agent..event +agent..shell.*.output +agent..shell.*.state +job.*.progress +job.*.output +job.*.state +_INBOX.> +``` + +The backend must further validate job/client ownership where wildcard job subjects are required. + +Subscribe allow: + +```text +agent..command.> +_INBOX.> +``` + +Prefer narrowing job subject permissions when practical. + +## 12.6 Credential Persistence + +Persist: + +- NATS user JWT +- local NKey private seed +- enrollment metadata + +Protect private seed using DPAPI LocalMachine. + +Recommended location: + +```text +%ProgramData%\\\credentials.dat +``` + +ACL: + +- SYSTEM: Full Control +- Administrators: Full Control +- no Users access + +The file content should be a versioned encrypted JSON blob. + +Do not write a plaintext `.creds` file to disk. + +Use `NatsAuthOpts` credential callbacks so JWT and signing material can be supplied from protected in-memory state. + +--- + +# 13. NATS Server MVP + +Run NATS in Docker for MVP. + +Required capabilities: + +- normal internal NATS TCP listener for backend/services +- WebSocket listener behind reverse proxy +- JetStream enabled +- operator/JWT mode +- file-backed resolver +- persistent JetStream volume +- persistent resolver volume + +The only required externally reachable route is standard HTTP/HTTPS via the selected reverse proxy. + +Suggested external path: + +```text +/messaging/agent +/messaging/browser +``` + +For MVP, both may terminate at the same NATS WebSocket listener if the proxy preserves WebSocket upgrade correctly. + +NATS must not expose port 4222 to the public network by default. + +Internal Docker services may use direct NATS TCP. + +--- + +# 14. Reverse Proxy Contract + +The system must assume it runs behind a reverse proxy. + +Public model: + +```text +Client + -> HTTP/HTTPS :443 + -> reverse proxy + -> Backend HTTP + -> WebUI HTTP + -> NATS WebSocket upgrade +``` + +Required forwarded headers: + +```text +X-Forwarded-For +X-Forwarded-Proto +X-Forwarded-Host +X-Forwarded-Prefix +``` + +Backend must: + +- use ASP.NET Core Forwarded Headers Middleware +- process forwarded headers before auth/redirect logic +- trust forwarded headers only from configured proxies/networks +- expose the effective real client IP through one centralized helper +- log both immediate peer IP and effective client IP where useful +- reject untrusted host headers +- support an allowlist of trusted hosts + +Environment configuration: + +```text +TRUST_PROXY=1 +TRUSTED_PROXIES= +TRUSTED_NETWORKS= +TRUSTED_HOSTS= +FORWARD_LIMIT=1 +``` + +Do not implement `TRUST_PROXY=1` as "trust every X-Forwarded-* header from anywhere." + +If proxy trust is enabled, at least one trusted proxy/network must be configured outside explicitly marked development mode. + +--- + +# 15. Agent NATS Connection + +The agent uses NATS over WebSocket by default. + +Agent takes: + +```text +ServerURL=https://control.example.com +``` + +and internally produces: + +```text +wss://control.example.com/messaging/agent +``` + +Features: + +- reconnect automatically +- exponential backoff +- jitter +- publish presence after reconnect +- publish fresh inventory summary after reconnect +- request/reply support +- graceful drain on service shutdown +- connection state exposed to local logs +- no busy loops +- cancellation token support throughout + +Suggested reconnect: + +```text +minimum: 1 second +maximum: 60 seconds +jitter: yes +``` + +Do not derive or probe a direct `4222` endpoint automatically. + +Direct NATS may be added later as an explicit configuration mode. + +--- + +# 16. Presence + +Agent publishes presence periodically via Core NATS. + +Payload: + +```json +{ + "clientId": "...", + "hostname": "...", + "agentVersion": "...", + "status": "online", + "timestampUtc": "...", + "uptimeSeconds": 12345, + "activeJobs": 1 +} +``` + +Interval: + +```text +30 seconds +``` + +Backend updates `LastSeenUtc`. + +Device considered: + +```text +Online = last seen <= 90 seconds +Stale = > 90 seconds and <= 5 minutes +Offline = > 5 minutes +``` + +These thresholds should be centralized constants/configuration. + +--- + +# 17. Inventory + +Inventory is intentionally limited for MVP but must be useful. + +Collect: + +## Identity +- Client ID +- Hostname +- manufacturer +- model +- serial +- BIOS version +- baseboard serial +- domain/workgroup +- system type + +## OS +- caption +- version +- build +- architecture +- install date +- last boot +- Windows edition + +## CPU +- name +- logical processors +- cores + +## Memory +- total physical memory +- DIMM capacity +- manufacturer +- speed where available + +## Storage +- physical disk model +- serial +- size +- bus type where available +- logical volume drive letter +- file system +- total size +- free space + +## Network +- enabled physical adapters +- adapter description +- MAC +- IPv4 addresses +- IPv6 addresses +- gateways +- DNS servers + +Use CIM and managed APIs. + +Inventory should be published: + +- immediately after enrollment +- immediately after reconnect +- every configurable interval +- when backend sends inventory command + +Default full inventory interval: + +```text +15 minutes +``` + +Backend stores latest snapshot only for MVP. + +--- + +# 18. PowerShell Execution + +PowerShell scripts must execute in-process through: + +```text +System.Management.Automation +``` + +Do not use: + +```text +powershell.exe +pwsh.exe +cmd.exe /c powershell ... +ProcessStartInfo to invoke PowerShell +``` + +Required execution model: + +1. create or obtain Runspace/RunspacePool +2. create `PowerShell` instance +3. associate Runspace/RunspacePool +4. add script using `AddScript` +5. add named parameters using `AddParameter` +6. allow structured helper commands with `AddCommand` +7. call `InvokeAsync` or supported SDK invocation +8. subscribe to output/error/warning/verbose/debug/information/progress streams +9. stream normalized records to NATS as they arrive +10. enforce cancellation +11. close/dispose cleanly + +The implementation should be structured around explicit classes such as: + +```text +PowerShellExecutionService +PowerShellRunspaceFactory +PowerShellOutputNormalizer +PowerShellJobHandler +``` + +For MVP, run under the agent service identity (`LocalSystem`). + +No user impersonation. + +--- + +# 19. Script Model + +Backend persists scripts. + +Fields: + +```text +Id +Name +Description +Language +Content +CreatedUtc +UpdatedUtc +CreatedBy +UpdatedBy +``` + +MVP language: + +```text +PowerShell +``` + +No script version history required for MVP. + +UI supports: + +- create +- edit +- save +- delete +- execute on one selected device + +Do not implement multi-device targeting yet. + +--- + +# 20. Job Model + +A script execution creates a job. + +Fields: + +```text +JobId +ClientId +ScriptId +ScriptName +State +CreatedUtc +StartedUtc +CompletedUtc +ExitCode +RequestedBy +OutputSummary +``` + +States: + +```text +Queued +Dispatched +Running +Succeeded +Failed +Cancelled +TimedOut +``` + +The `JobId` is generated by backend and is the idempotency key for agent execution. + +Use JetStream for durable script command dispatch. + +Agent must persist recently handled job IDs locally so reconnect/redelivery does not execute the same script twice. + +For MVP, retain at least the last 1,000 completed command IDs/jobs in a lightweight local SQLite or JSON store. + +Prefer SQLite if already used by shared data code. + +--- + +# 21. Near-Real-Time Script Output + +Output records: + +```json +{ + "jobId": "...", + "clientId": "...", + "sequence": 42, + "stream": "output", + "timestampUtc": "...", + "text": "..." +} +``` + +Stream values: + +```text +output +error +warning +verbose +debug +information +progress +``` + +Sequence must monotonically increase per job. + +Agent publishes output near-live through Core NATS while backend persists it asynchronously. + +Backend relays or republishes an authorized browser-specific stream. + +Browser displays output while job is running without polling. + +On reconnect, browser can use REST to retrieve stored output accumulated so far, then resume NATS updates. + +This is the MVP recovery model. + +--- + +# 22. Progress Demonstration + +The MVP must visibly demonstrate near-real-time progress. + +A script can emit PowerShell progress records. + +Agent converts PowerShell progress stream records into normalized progress messages: + +```json +{ + "jobId": "...", + "clientId": "...", + "activity": "Installing component", + "statusDescription": "Step 4 of 10", + "percentComplete": 40, + "secondsRemaining": 12, + "timestampUtc": "..." +} +``` + +Flow: + +```text +PowerShell ProgressRecord + -> Agent + -> NATS + -> Backend + -> browser-authorized NATS subject + -> Svelte store + -> live progress bar +``` + +The demo UI must update smoothly without REST polling. + +--- + +# 23. Remote Interactive Shell + +## 23.1 Scope + +MVP supports one interactive shell session at a time per browser/device pair. + +Use xterm.js in the browser. + +On Windows, implement terminal hosting using the Windows Pseudoconsole API (ConPTY). + +Do not bundle WinPTY unless ConPTY is unavailable on a supported target. + +Minimum supported Windows should therefore be a modern Windows version that includes ConPTY. + +Default shell: + +```text +powershell.exe or pwsh.exe +``` + +Important distinction: + +- automation script execution uses `System.Management.Automation` +- the interactive terminal is an actual terminal process attached to ConPTY + +This is acceptable because an interactive shell requires terminal process semantics. + +The default interactive shell should be configurable by server policy later; MVP may choose Windows PowerShell or PowerShell 7 when available. + +## 23.2 Shell Flow + +Browser: + +```text +POST /api/devices/{clientId}/shell +``` + +Backend: + +- authorizes user +- creates ShellSession ID +- publishes open command +- returns shell session metadata + +Agent: + +- creates ConPTY +- launches selected shell attached to pseudoconsole +- reads output +- publishes binary-safe/UTF-8 output over NATS +- subscribes to input and resize commands +- terminates session when browser closes or backend expires session + +Subjects: + +```text +agent..command.shell.open +agent..command.shell.input +agent..command.shell.resize +agent..command.shell.close +agent..shell..output +agent..shell..state +``` + +MVP timeout: + +```text +15 minutes idle +60 minutes absolute maximum +``` + +Remote shell is disabled unless `AllowRemoteShell=1`. + +--- + +# 24. Shell Security + +Backend authorization is mandatory before shell creation. + +The browser must never receive permission to directly publish arbitrary `agent..command.*` subjects. + +Instead: + +1. browser authenticates with backend +2. backend authorizes shell creation +3. backend creates session +4. backend issues a short-lived NATS browser credential scoped only to the generated browser session subjects +5. backend itself publishes privileged agent command subjects + +Browser publishes shell input to: + +```text +browser..shell..input +``` + +Backend messaging worker validates ownership and forwards input to the agent command subject. + +This prevents browser NATS credentials from becoming device command credentials. + +--- + +# 25. Browser NATS Model + +Browser connects over WebSocket to NATS. + +Configuration is derived from the same HTTP/HTTPS public server URL. + +Example: + +```text +https://control.example.com +``` + +becomes: + +```text +wss://control.example.com/messaging/browser +``` + +Browser first authenticates to backend. + +Then browser calls: + +```text +POST /api/messaging/credential +``` + +Backend issues short-lived browser NATS credentials. + +Credential lifetime: + +```text +5 minutes +``` + +Browser refreshes before expiration while its backend auth session remains valid. + +Browser NATS JWT permissions must be restricted to: + +```text +browser..> +_INBOX.> +``` + +No direct device command permissions. + +This keeps NATS heavily involved without bypassing backend RBAC. + +--- + +# 26. Backend Responsibilities + +Backend is the control plane. + +Responsibilities: + +- REST API +- local authentication +- OIDC authentication +- session management +- device persistence +- script persistence +- job persistence +- bootstrap token creation/consumption +- NATS JWT issuance +- browser credential issuance +- NATS subscription workers +- command dispatch +- browser event republishing +- trusted proxy processing +- authorization +- auditing +- health endpoints + +Use ASP.NET Core Minimal APIs or Controllers consistently. + +Do not mix patterns arbitrarily. + +Prefer vertical feature folders internally while keeping shared routes centralized. + +--- + +# 27. Backend Persistence + +Use SQLite for MVP. + +Database path: + +```text +/data/app.db +``` + +Use EF Core migrations. + +Tables: + +```text +Users +OidcProviders +Devices +DeviceInventory +Scripts +Jobs +JobOutput +BootstrapTokens +AuditEvents +``` + +Optional: + +```text +ShellSessions +``` + +Do not persist raw remote shell transcript by default for MVP. + +Persist metadata only unless explicitly enabled later. + +--- + +# 28. Local Authentication + +MVP must support local username/password authentication. + +On first startup: + +- if no user exists, create initial admin from environment secret +- never use a compiled default password + +Environment: + +```text +INITIAL_ADMIN_USERNAME +INITIAL_ADMIN_PASSWORD +``` + +Requirements: + +- hash passwords using ASP.NET Core PasswordHasher or modern equivalent +- secure HTTP-only cookies for browser session +- SameSite appropriate for OIDC compatibility +- anti-CSRF protection for state-changing cookie-authenticated REST routes +- login rate limiting +- logout revokes local session +- no password in logs + +The initial password should only be required for first bootstrap. + +After first admin exists, startup should not overwrite its password. + +--- + +# 29. OIDC Authentication + +Support generic OpenID Connect. + +Environment/config keys: + +```text +OIDC_ENABLED +OIDC_AUTHORITY +OIDC_CLIENT_ID +OIDC_CLIENT_SECRET +OIDC_CALLBACK_PATH +OIDC_SCOPES +OIDC_NAME_CLAIM +OIDC_ROLE_CLAIM +OIDC_ADMIN_ROLE +``` + +Defaults: + +```text +OIDC_CALLBACK_PATH=/signin-oidc +OIDC_SCOPES=openid profile email +``` + +Do not hard-code Authentik-specific endpoints. + +It should work with compliant providers such as: + +- Authentik +- Keycloak +- Entra ID +- Okta +- other standard OIDC providers + +MVP role behavior: + +- local admin is administrator +- OIDC user is allowed access after successful authentication +- if `OIDC_ADMIN_ROLE` is configured and matching role claim is present, grant Admin +- otherwise grant Operator + +Roles: + +```text +Admin +Operator +Viewer +``` + +MVP permissions: + +```text +Admin: + everything + +Operator: + view devices + view inventory + create/edit scripts + run scripts + remote shell + +Viewer: + view devices + view inventory + view jobs +``` + +--- + +# 30. Backend NATS Credential Issuer + +Backend holds the NATS account signing key required to issue user JWTs. + +Do not put the signing key in source control. + +Required secret: + +```text +NATS_ACCOUNT_SIGNING_SEED +``` + +Agent enrollment: + +- agent creates User NKey pair locally +- backend signs a user JWT for supplied User public NKey +- permissions are constrained to client ID + +Browser: + +- browser-side NKey may be generated in browser memory +- browser sends public key to credential API +- backend signs a short-lived user JWT for that key +- browser private seed stays in browser memory +- browser credential expires quickly + +This demonstrates correct NATS decentralized authentication without distributing a common shared secret. + +--- + +# 31. NATS Usage Policy + +Use **Core NATS** for transient real-time data: + +- presence +- live inventory event notification +- live job output +- progress +- shell input/output +- UI events + +Use **JetStream** for durable commands/state where loss is unacceptable: + +- script execution commands +- inventory refresh command if needed +- important job state transitions + +Do not put high-volume shell output into JetStream for MVP. + +JetStream stream examples: + +```text +COMMANDS + subjects: + agent.*.command.script + agent.*.command.inventory + +JOB_EVENTS + subjects: + job.*.state +``` + +Use explicit ack for durable agent commands. + +Agent only acknowledges script command after it has durably recorded the job ID as accepted. + +--- + +# 32. Web UI + +## 32.1 General Design + +SvelteKit UI should look polished rather than like an admin scaffold. + +Required visual characteristics: + +- compact enterprise dashboard +- strong spacing and typography hierarchy +- responsive desktop-first layout +- subtle motion for live state transitions +- cards only where semantically useful +- tables with sticky headers +- live connection indicator +- skeleton loading states +- empty states +- error states +- accessible keyboard navigation +- consistent focus states + +Theme: + +```text +System +Light +Dark +``` + +Default: + +```text +System +``` + +Persist user preference in browser local storage. + +Use CSS custom properties/tokens. + +Do not hard-code theme colors throughout components. + +--- + +# 33. Main Navigation + +Left navigation or compact application rail: + +```text +Dashboard +Devices +Scripts +Jobs +Settings +``` + +Top bar: + +- global title +- NATS live connection indicator +- current user +- theme switcher +- logout + +--- + +# 34. Dashboard Page + +Show MVP operational summary: + +- total devices +- online +- stale +- offline +- running jobs +- failed jobs +- latest enrollments + +Include a visually strong "Live Activity" stream populated from NATS. + +Examples: + +```text +PC-001 connected +PC-014 inventory updated +Job ... started on PC-007 +Job ... progress 65% +Job ... completed +``` + +The activity feed must update without polling. + +--- + +# 35. Devices Page + +Rich device table. + +Columns: + +```text +Status +Hostname +Manufacturer / Model +Operating System +Agent Version +IP +Last Seen +``` + +Features: + +- search +- online/offline filter +- sort +- row hover +- click row opens device detail + +Status should visibly update from NATS presence. + +--- + +# 36. Device Detail Page + +Use horizontal top-level sections/tabs and inner vertical sections where appropriate. + +Top: + +```text +Overview | Hardware | Network | Jobs | Actions +``` + +## Overview + +Vertical sections: + +```text +Identity +Operating System +Agent +Connectivity +``` + +## Hardware + +Horizontal or responsive cards: + +```text +Processor +Memory +Storage +Firmware +``` + +Storage is table-based. + +## Network + +Each adapter displayed as structured section with addresses, gateways and DNS. + +## Jobs + +Recent jobs with state, duration, result and click-through. + +## Actions + +Buttons: + +```text +Refresh Inventory +Run Script +Open Remote Shell +``` + +Actions disabled with explanatory tooltip if the agent is offline or policy disables them. + +--- + +# 37. Script Editor + +Route: + +```text +/scripts +/scripts/{id} +``` + +Use Monaco Editor configured for PowerShell syntax. + +Layout: + +```text +┌──────────────────────────────────────────────────────────┐ +│ script metadata / save / run │ +├─────────────────────────────┬────────────────────────────┤ +│ │ target / job panel │ +│ Monaco editor │ │ +│ │ progress │ +│ │ output │ +└─────────────────────────────┴────────────────────────────┘ +``` + +For smaller screens, side panel stacks below. + +Features: + +- script name +- description +- Save +- Run +- device selector +- editor +- live progress +- live structured output +- status badge +- cancel button if feasible + +MVP need not implement IntelliSense beyond Monaco defaults/basic PowerShell language support. + +--- + +# 38. Remote Shell UI + +Route: + +```text +/devices/{clientId}/shell +``` + +Use xterm.js. + +Features: + +- terminal resizes to viewport +- resize events forwarded to agent +- status indicator +- reconnect/closed state +- explicit Disconnect button +- visible target hostname +- idle timeout warning +- no browser-side command history persistence unless xterm naturally keeps current session buffer + +NATS carries terminal input/output after authorization. + +--- + +# 39. REST API MVP + +Required endpoints: + +```text +GET /api/health +GET /api/ready + +POST /api/auth/login +POST /api/auth/logout +GET /api/auth/session +GET /api/auth/oidc/login +GET /api/auth/oidc/callback + +POST /api/enrollment/bootstrap +POST /api/enrollment/credential + +GET /api/devices +GET /api/devices/{clientId} +POST /api/devices/{clientId}/inventory +POST /api/devices/{clientId}/shell + +GET /api/scripts +POST /api/scripts +GET /api/scripts/{id} +PUT /api/scripts/{id} +DELETE /api/scripts/{id} + +GET /api/jobs +POST /api/jobs +GET /api/jobs/{jobId} +GET /api/jobs/{jobId}/output + +POST /api/messaging/credential + +POST /api/admin/bootstrap-tokens +GET /api/admin/bootstrap-tokens +DELETE /api/admin/bootstrap-tokens/{id} +``` + +All routes come from centralized route definitions. + +--- + +# 40. Browser Event Authorization + +Never publish raw global backend events to every browser. + +For each authenticated browser session create: + +```text +browserSessionId +``` + +Backend maps browser session to authenticated user and authorization context. + +Backend republishes only authorized events to: + +```text +browser..event +browser..job. +browser..shell. +``` + +For MVP, all Admin/Operator users may see all devices. + +The architecture must still use session-specific subjects so future device/group RBAC does not require transport redesign. + +--- + +# 41. Logging + +All .NET services use `ILogger`. + +Console structured logs. + +Optional JSON log mode controlled by configuration. + +Every log event should include where relevant: + +```text +CorrelationId +ClientId +JobId +ShellSessionId +BrowserSessionId +RemoteIp +``` + +Never log: + +- bootstrap tokens +- passwords +- OIDC client secret +- NATS seeds +- signed credential material +- cookies +- authorization headers + +Agent can additionally write Windows Event Log when running as service if practical, but this is not required to pass MVP. + +--- + +# 42. Health and Readiness + +Backend: + +```text +/api/health +/api/ready +``` + +Health means process alive. + +Readiness verifies: + +- database accessible +- NATS connected +- required signing key loaded + +Do not expose secret values. + +NATS has its own container health check. + +WebUI container has HTTP health check. + +--- + +# 43. Docker Deployment + +Docker Compose services: + +```text +nats +backend +webui +``` + +Volumes: + +```text +nats-data +nats-resolver +backend-data +``` + +No reverse proxy is required inside the MVP Compose stack because an existing external reverse proxy is assumed. + +Expose configurable local ports for integration testing. + +Example: + +```text +backend: 8080 +webui: 3000 +nats websocket: 9222 +nats internal: 4222 only on Docker network by default +``` + +The external reverse proxy should map: + +```text +/ -> webui +/api/* -> backend +/messaging/agent -> nats websocket +/messaging/browser-> nats websocket +``` + +Exact path handling must be validated against NATS WebSocket configuration. + +If path-based proxying proves incompatible with the selected proxy/NATS configuration, use dedicated hostnames while retaining one public TCP/443 edge port. + +--- + +# 44. Backend Docker Image + +Multi-stage build. + +Runtime contains only required ASP.NET runtime and application. + +Run as non-root where practical. + +Environment: + +```text +ASPNETCORE_URLS=http://0.0.0.0:8080 +DATABASE_PATH=/data/app.db +NATS_URL=nats://nats:4222 + +TRUST_PROXY=1 +TRUSTED_PROXIES= +TRUSTED_NETWORKS= +TRUSTED_HOSTS= + +INITIAL_ADMIN_USERNAME= +INITIAL_ADMIN_PASSWORD= + +OIDC_ENABLED=0 +OIDC_AUTHORITY= +OIDC_CLIENT_ID= +OIDC_CLIENT_SECRET= +OIDC_CALLBACK_PATH=/signin-oidc +OIDC_SCOPES=openid profile email + +NATS_ACCOUNT_SIGNING_SEED= +``` + +--- + +# 45. WebUI Docker Image + +Build SvelteKit using Node during build stage. + +Use SvelteKit Node adapter or a minimal production Node runtime. + +Container listens on: + +```text +3000 +``` + +Browser must discover public API/NATS location from same origin where possible. + +Prefer same-origin deployment so no CORS complexity is required. + +WebUI should not contain NATS signing secrets. + +--- + +# 46. Secrets + +Commit: + +```text +.env.example +secrets/README.md +scripts/New-LocalSecrets.ps1 +``` + +Do not commit generated secret files. + +`.gitignore` must include: + +```text +.env +.env.* +!.env.example +secrets/* +!secrets/README.md +.local/ +artifacts/ +*.pfx +*.key +*.seed +*.creds +``` + +Required secrets: + +```text +INITIAL_ADMIN_PASSWORD +NATS_OPERATOR_SEED +NATS_ACCOUNT_SEED +NATS_ACCOUNT_SIGNING_SEED +OIDC_CLIENT_SECRET # only when OIDC enabled +GITEA_TOKEN # CI deployment/push automation where needed +CONTAINER_REGISTRY_PASSWORD # if different from Gitea token +CODE_SIGNING_CERT_PASSWORD # optional MVP release signing +``` + +Non-secret identifiers: + +```text +NATS_OPERATOR_PUBLIC_KEY +NATS_ACCOUNT_PUBLIC_KEY +GITEA_URL +GITEA_OWNER +GITEA_REPOSITORY +CONTAINER_REGISTRY +``` + +`New-LocalSecrets.ps1` should generate strong development values locally and write them into ignored files. + +It may invoke locally installed NATS tooling if available, but the repository must document how to generate NATS operator/account/signing keys. + +Do not fake cryptographic NATS seeds using arbitrary random text. + +--- + +# 47. GITEA_* Environment Variables + +Build/release scripts should discover as much context as possible using optional environment variables. + +Support: + +```text +GITEA_URL +GITEA_TOKEN +GITEA_OWNER +GITEA_REPOSITORY +GITEA_SHA +GITEA_REF +GITEA_REF_NAME +GITEA_RUN_NUMBER +GITEA_ACTOR +GITEA_CONTAINER_REGISTRY +GITEA_CONTAINER_REGISTRY_USERNAME +GITEA_CONTAINER_REGISTRY_PASSWORD +``` + +Scripts must fall back gracefully when running locally. + +When authenticated values are available, CI may: + +- push backend image +- push webui image +- attach agent ZIP/MSI to a release +- create/update release metadata +- push tags if explicitly configured + +Never print token values. + +--- + +# 48. Unified Versioning + +All build outputs use: + +```text +yyyy.MM.dd.HHmm +``` + +Example: + +```text +2026.08.06.2151 +``` + +Use UTC for CI-generated versions. + +The same version must be embedded into: + +- Agent executable +- Backend assembly +- MSI ProductVersion-compatible mapped version +- Docker image labels +- Docker image tags where allowed +- frontend build metadata +- release metadata + +Because MSI ProductVersion has constraints, create a deterministic compatible numeric transform while retaining the full unified version in MSI display metadata. + +`Directory.Build.props` should centralize assembly version properties. + +Generate a build metadata source file or MSBuild property once per build, not independently per project. + +--- + +# 49. Binary Icon + +Canonical source: + +```text +/assets/icon-source.png +``` + +CI/build script installs ImageMagick silently when required on Windows builder. + +Example expectation: + +```text +winget or package manager silent install +``` + +Then: + +```text +magick icon-source.png -define icon:auto-resize=256,128,64,48,32,16 app.ico +``` + +Generated `.ico` belongs under build artifacts and is not required to be committed. + +Embed the generated icon using the `.csproj` `ApplicationIcon` property. + +Agent executable and other Windows executables should use the same icon. + +MSI should also reference it where supported. + +If ImageMagick is already installed, do not reinstall it. + +Build must be idempotent. + +--- + +# 50. CI/CD Branch Model + +Repository branches: + +```text +main +dev +``` + +Initialize `dev` from `main`. + +CI triggers: + +```text +push: dev +push: main +pull_request: main +``` + +Behavior: + +## Pull request +- restore +- build +- unit tests +- integration tests where feasible +- Svelte check/build +- no image push +- no release + +## Push to dev +- restore/build/test +- build Agent self-contained binary +- build MSI +- build backend Docker image +- build webui Docker image +- optionally push images tagged: + - `dev` + - `-dev` + +## Push to main +- restore/build/test +- build Agent +- build MSI +- build backend Docker image +- build webui Docker image +- push: + - `` + - `latest` +- create Gitea release/tag for unified version if token is available +- attach: + - Agent executable ZIP + - Agent MSI + - checksums + +Do not automatically merge dev into main. + +--- + +# 51. Gitea Workflow Security + +Use repository secrets for: + +```text +GITEA_TOKEN +REGISTRY_USERNAME +REGISTRY_PASSWORD +NATS_* seeds only if required during integration test +``` + +Production NATS signing keys should not be embedded in released artifacts. + +CI integration tests may use ephemeral generated NATS operator/account keys. + +Release container receives production secrets only at runtime. + +--- + +# 52. Tests + +Minimum tests: + +## Shared +- API route constants unique +- NATS subject builder output +- subject identifier validation +- ServerURL HTTP->WS conversion +- ServerURL HTTPS->WSS conversion +- message serialization round trip + +## Agent +- configuration precedence +- registry parser +- policy override behavior +- deterministic fingerprint normalization +- stable client ID hash +- bootstrap token clearing +- command idempotency +- PowerShell output normalization +- progress normalization + +## Backend +- bootstrap token hashing/validation +- one-time token consumption +- NATS JWT permission generation +- local authentication +- role authorization +- forwarded header trust behavior +- device CRUD read model +- job state transitions + +## Integration +Spin up: + +```text +NATS +Backend +test agent in foreground +``` + +Validate: + +1. bootstrap +2. NATS connect over WebSocket +3. inventory received +4. presence received +5. dispatch PowerShell script +6. output received +7. progress received +8. job completes +9. duplicate command does not run twice + +Browser E2E may use Playwright if implementation effort remains reasonable. + +--- + +# 53. Demo Script + +Include a sample script in development seed data: + +```powershell +1..10 | ForEach-Object { + Write-Progress -Activity 'MVP Progress Demo' -Status "Step $_ of 10" -PercentComplete ($_ * 10) + Write-Output "Completed step $_" + Start-Sleep -Seconds 1 +} +``` + +This is specifically intended to visibly prove: + +```text +Browser -> Backend -> NATS -> Agent +Agent PowerShell SDK execution +Agent -> NATS -> Backend -> NATS -> Browser +``` + +with live output and progress. + +--- + +# 54. MVP End-to-End Demo Scenario + +A successful MVP demonstration must perform this exact sequence: + +1. Start Docker Compose. +2. Backend, NATS and WebUI become healthy. +3. Login locally as initial admin. +4. Generate a one-time bootstrap token from UI/API. +5. Install Agent MSI with: + - `SERVERURL=https://...` + - `BOOTSTRAPTOKEN=...` +6. Agent service starts. +7. Agent computes deterministic hardware client ID. +8. Agent generates local NKey pair. +9. Agent bootstraps over HTTPS. +10. Backend validates and consumes token. +11. Backend returns scoped NATS user JWT. +12. Agent clears bootstrap token from registry. +13. Agent connects to NATS using WSS through reverse proxy. +14. Device appears in browser within seconds. +15. Presence updates status without page refresh. +16. Inventory appears in device details. +17. Open script editor. +18. Save sample PowerShell script. +19. Select enrolled device. +20. Execute. +21. Job state becomes Running without polling. +22. output appears near-live. +23. progress bar advances near-live. +24. job becomes Succeeded. +25. open remote shell. +26. interactive terminal opens. +27. run: + ```text + hostname + whoami + Get-Process | Select-Object -First 5 + ``` +28. terminal output appears live. +29. resize browser and verify terminal resize. +30. disconnect terminal cleanly. +31. restart Agent service. +32. agent reconnects without bootstrap token. +33. device returns online. +34. rerun script. +35. verify no duplicate execution from NATS redelivery. + +The MVP is not complete until this sequence works reliably. + +--- + +# 55. Acceptance Criteria + +## Agent +- one self-contained executable +- foreground/service operation +- idempotent install/start/stop/remove/initialize +- no `sc.exe` dependency +- registry/GPO configuration +- MSI public properties +- deterministic hardware client ID +- secure one-time bootstrap +- local NKey private seed never transmitted +- bootstrap token removed after success +- NATS over WS/WSS derived from ServerURL +- automatic reconnect +- CIM inventory +- PowerShell SDK execution +- live progress/output +- ConPTY remote shell + +## Backend +- REST API +- SQLite persistence +- local auth +- generic OIDC +- role authorization +- trusted proxy support +- effective real client IP +- NATS operator/JWT integration +- scoped agent credentials +- scoped short-lived browser credentials +- NATS command/event workers +- JetStream durable script dispatch + +## Browser +- SvelteKit +- System/Light/Dark +- polished dashboard +- device list live status +- detailed inventory +- Monaco PowerShell editor +- script save/run +- live job output +- live progress +- xterm.js remote shell +- direct browser NATS WebSocket connection only to browser-scoped subjects + +## Delivery +- Dockerfiles +- Compose +- Gitea CI +- dev/main branch workflow +- MSI +- unified version +- generated icon +- ImageMagick build dependency automation +- `.env.example` +- ignored secrets +- documentation + +--- + +# 56. Explicit Non-Goals for MVP + +Do not implement these before the acceptance criteria above pass: + +- Linux/macOS agent +- multi-tenant organization model +- Intune integration +- ADMX file itself +- full GPO management UI +- software deployment +- patching +- file transfer +- screen sharing +- remote desktop +- multi-device script execution +- schedules +- dynamic groups +- advanced RBAC scopes +- script version history +- approvals +- secrets vault +- certificate PKI enrollment +- agent auto-update +- HA backend +- NATS cluster HA +- PostgreSQL +- Kafka +- SignalR +- SSE +- gRPC +- GraphQL +- direct public port 4222 +- arbitrary browser access to agent command subjects +- plaintext NATS seeds on disk +- PowerShell.exe shell-out for automation jobs +- telemetry platform integration + +These are follow-on features. + +--- + +# 57. Implementation Order + +Claude should build in this order and keep the repository runnable at each stage. + +## Milestone 1 — Foundation +- solution/repository +- shared constants +- shared routes +- shared NATS subjects +- versioning +- logging +- Compose NATS +- backend skeleton +- WebUI skeleton +- Agent foreground worker + +## Milestone 2 — Agent Service and Configuration +- Windows service integration +- service lifecycle commands +- registry configuration +- GPO precedence +- ServerURL normalization +- MSI + +## Milestone 3 — Identity and Bootstrap +- CIM fingerprint +- deterministic ClientId +- bootstrap token backend +- NKey local generation +- NATS JWT issuance +- encrypted credential persistence +- WSS connection + +## Milestone 4 — Presence and Inventory +- presence +- inventory +- backend persistence +- Devices UI +- live status + +## Milestone 5 — Script Jobs +- script CRUD +- Monaco +- JetStream command +- System.Management.Automation execution +- live streams +- output persistence +- progress UI + +## Milestone 6 — Remote Shell +- ConPTY +- xterm.js +- session authorization +- browser session NATS subjects +- idle timeout +- resize/input/output + +## Milestone 7 — Authentication +- local login +- cookie session +- roles +- OIDC +- browser NATS credential issuance + +## Milestone 8 — CI/CD and Polish +- ImageMagick icon +- self-contained artifacts +- MSI packaging +- Docker pushes +- Gitea release +- dev/main behavior +- final integration test +- documentation + +Do not start the next milestone while the prior milestone is broken. + +--- + +# 58. Coding Rules + +- Nullable reference types enabled. +- Treat warnings seriously. +- Async I/O for network/database operations. +- CancellationToken propagated. +- Dependency injection. +- interfaces only where they provide actual seams/testing value. +- avoid excessive abstraction. +- no service locator. +- no static mutable global state. +- records for immutable contracts where practical. +- `System.Text.Json`. +- UTC timestamps. +- GUID/UUID for jobs, sessions and messages. +- deterministic string constants centralized. +- no magic subject strings. +- no magic API paths. +- no secrets in source. +- no disabled TLS validation. +- no SignalR. +- no SSE. +- no browser polling for live state. +- no PowerShell automation shell-out. +- no direct browser authorization to privileged agent subjects. + +--- + +# 59. README Requirements + +The root README must document: + +1. architecture +2. prerequisites +3. local development +4. required secrets +5. generating local secrets +6. Docker Compose +7. reverse proxy routes +8. Agent foreground mode +9. Agent service lifecycle commands +10. MSI public properties +11. registry paths +12. GPO precedence +13. bootstrap workflow +14. local login +15. OIDC example configuration +16. CI/CD +17. GITEA_* variables +18. versioning +19. MVP demo sequence +20. troubleshooting + +Include Mermaid architecture diagrams. + +--- + +# 60. Architecture Diagram + +```mermaid +flowchart LR + A[Windows Agent] -->|HTTPS bootstrap| P[Reverse Proxy :443] + A -->|WSS NATS| P + B[Browser / SvelteKit] -->|HTTPS REST| P + B -->|WSS NATS| P + + P -->|/api| API[ASP.NET Core Backend] + P -->|/| UI[SvelteKit WebUI] + P -->|/messaging/agent| N[NATS WebSocket] + P -->|/messaging/browser| N + + API -->|NATS TCP internal| N + API --> DB[(SQLite)] + N --> JS[(JetStream)] + + N -->|commands| A + A -->|presence inventory output progress shell| N + N --> API + API -->|authorized browser session events| N + N --> B +``` + +--- + +# 61. Script Execution Sequence + +```mermaid +sequenceDiagram + participant U as Browser + participant API as Backend + participant N as NATS/JetStream + participant A as Agent + participant PS as System.Management.Automation + + U->>API: POST /api/jobs + API->>N: durable script command + N->>A: agent..command.script + A->>A: record JobId idempotently + A-->>N: Ack command + A->>PS: Runspace + AddScript + AddParameter + PS-->>A: Output / Progress / Errors + A->>N: job..output/progress + N->>API: consume job events + API->>N: browser..job. + N-->>U: live WebSocket event + PS-->>A: completion + A->>N: job..state = Succeeded/Failed + N->>API: persist state + API->>N: browser session update + N-->>U: final state +``` + +--- + +# 62. Enrollment Sequence + +```mermaid +sequenceDiagram + participant A as Agent + participant API as Backend + participant N as NATS + + A->>A: CIM stable hardware fingerprint + A->>A: SHA-256 deterministic ClientId + A->>A: Generate User NKey pair + A->>API: HTTPS bootstrap token + ClientId + public NKey + API->>API: Validate/consume bootstrap token + API->>API: Issue scoped NATS user JWT + API-->>A: EnrollmentId + User JWT + A->>A: DPAPI protect private seed/JWT + A->>A: Clear BootstrapToken registry value + A->>N: WSS connect using JWT + NKey proof + N-->>A: authenticated + A->>N: presence + inventory +``` + +--- + +# 63. Remote Shell Sequence + +```mermaid +sequenceDiagram + participant U as Browser/xterm + participant API as Backend + participant N as NATS + participant A as Agent + participant C as ConPTY + + U->>API: create shell for ClientId + API->>API: authorize + API->>N: privileged shell.open command + N->>A: shell.open + A->>C: create pseudoconsole + shell + A->>N: shell state=open + API->>N: browser session state/output bridge + N-->>U: shell open + U->>N: browser session shell input + N->>API: input + API->>N: authorized agent shell.input + N->>A: input + A->>C: write input + C-->>A: terminal output + A->>N: shell output + N->>API: output + API->>N: browser shell output + N-->>U: live terminal output +``` + +--- + +# 64. Final MVP Principle + +The system should prove one architectural idea cleanly: + +> A Windows management agent can enroll securely through ordinary HTTPS, establish scoped NATS communication over WebSocket through the same reverse-proxy edge, publish live state, accept durable work, run PowerShell in-process, and provide a secured interactive terminal while a browser uses WebSocket-connected NATS for near-real-time UI updates without SignalR or SSE. + +The implementation should favor correctness, explicit contracts, deterministic behavior, idempotency, and observable end-to-end flows over premature platform breadth. + +Once the complete demo scenario works reliably, the architecture is proven and can be expanded. diff --git a/.claude/ENV-SPEC.md b/.claude/ENV-SPEC.md new file mode 100644 index 0000000..8b1a82a --- /dev/null +++ b/.claude/ENV-SPEC.md @@ -0,0 +1,184 @@ +# Environment File Specification + +## File Header +```bash +#============================================================================= +# {STACK_NAME} - {Description} +#============================================================================= +# +# CREDENTIALS: +# {credential format} +# +# ACCESS URL: {url} +# +# PRODUCTION SETUP: +# 1. {step} +# 2. {step} +# +#============================================================================= +``` + +## Required Variables + +### Stack Identity +```bash +# Stack Identity +STACK_NAME=stk-{name}-00001 +STACK_BINDMOUNTROOT=/mnt/data/docker/stacks +``` + +### Container User/Group +```bash +# Container User/Group +PUID=0 +PGID=0 +``` +- Default in compose: `${PUID:-1000}:${PGID:-1000}` +- Set to `0` for root, or match host user UID/GID + +## Images +```bash +# Images +{APP}_IMAGE={default/image} +{APP}_VERSION={tag} +POSTGRES_IMAGE=postgres +POSTGRES_VERSION=17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527 +VALKEY_IMAGE=valkey/valkey +VALKEY_VERSION=9.0-alpine@sha256:{digest} +BUSYBOX_IMAGE=busybox +BUSYBOX_VERSION=latest +``` +- Always SHA256 pin dependency/infrastructure images for reproducibility: + databases (Postgres, MySQL, MongoDB, MSSQL), cache (Valkey), message brokers + (NATS, RabbitMQ), search/index stores (Quickwit, Meilisearch, Elasticsearch), + object stores (MinIO), and any init/sidecar container +- Format: `{tag}@sha256:{digest}` — the tag is retained for readability, the digest locks the exact build +- Obtain the digest via a real pull, NOT by copying from the Docker Hub web UI + (those listings include attestation manifests that are not pullable images + and fail at unpack with `unexpected media type application/octet-stream`): + ```bash + docker pull image:tag + docker inspect --format='{{index .RepoDigests 0}}' image:tag + docker pull image@sha256: # sanity-check the digest resolves + ``` +- When bumping a pinned image, repeat the three commands above and update both + the compose default and this `.env` value to the new digest in lockstep + +## Ports +```bash +# Ports +{APP}_PORT={port} +``` + +## Database +```bash +# Database +POSTGRES_USER={appname} +POSTGRES_PASSWORD={SecurePassword} +POSTGRES_DB={appname} +``` + +## Cache +```bash +# Cache (Valkey/Redis) +REDIS_PASSWORD={SecurePassword} +``` + +## Secrets +```bash +# Secrets (regenerate for production) +SECRET_KEY={50+ character random string} +``` +Generate with: `openssl rand -base64 50` + +## Automatic Updates +```bash +# Automatic Updates (Watchtower) +{APP}_ENABLEAUTOMATICUPDATES=false +POSTGRES_ENABLEAUTOMATICUPDATES=false +VALKEY_ENABLEAUTOMATICUPDATES=false +``` + +## Secret Value Rules + +### .env vs Compose Defaults +| Location | Purpose | Example | +|----------|---------|---------| +| .env | Actual random secret | `bH3nF6kM9pL2sW5xY8cD1eG4` | +| Compose default | Different random secret | `xK9mZ7vQ3wL8nP2jR5tY0uA4` | + +### Generation +```bash +# Passwords (24 chars) +openssl rand -base64 24 + +# Secret keys (50+ chars) +openssl rand -base64 50 + +# Hash salts (hex) +openssl rand -hex 16 +``` + +### Why Different? +- Both are real secrets, but different values +- If .env is missing, stack still runs but with different credentials +- Logs/debugging can identify which secret source is active + +## Example Complete .env +```bash +#============================================================================= +# NETBOX - Network Documentation & IPAM +#============================================================================= +# +# CREDENTIALS: +# Username: admin +# Password: Adm1n5ecur3P@ss2024 +# +# ACCESS URL: http://localhost:8000/ +# +#============================================================================= + +# Stack Identity +STACK_NAME=stk-netbox-00001 +STACK_BINDMOUNTROOT=/mnt/data/docker/stacks + +# Container User/Group +PUID=0 +PGID=0 + +# Images +NETBOX_IMAGE=netboxcommunity/netbox +NETBOX_VERSION=v4.2 +POSTGRES_IMAGE=postgres +POSTGRES_VERSION=17@sha256:2203e6282d9e7de7c24d7da234e2a744fb325df366a3fd8ed940e8abbee39527 +VALKEY_IMAGE=valkey/valkey +VALKEY_VERSION=9.0-alpine +BUSYBOX_IMAGE=busybox +BUSYBOX_VERSION=latest + +# Ports +NETBOX_PORT=8000 + +# Database +POSTGRES_USER=netbox +POSTGRES_PASSWORD=N3tb0x5ecur3P@ssw0rd2024 +POSTGRES_DB=netbox + +# Cache +REDIS_PASSWORD=V@lk3yN3tb0xP@ss2024 + +# Secrets +SECRET_KEY=Kx9mZ7vQ3wL8nP2jR5tY0uA4cF6hB1dE9sW3xN7mJ2kP5vT8yG0qC4rU6iO1aM3z + +# Superuser +SUPERUSER_NAME=admin +SUPERUSER_EMAIL=admin@example.com +SUPERUSER_PASSWORD=Adm1n5ecur3P@ss2024 +SKIP_SUPERUSER=false + +# Automatic Updates +NETBOX_ENABLEAUTOMATICUPDATES=true +POSTGRES_ENABLEAUTOMATICUPDATES=false +VALKEY_ENABLEAUTOMATICUPDATES=false +``` + diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..02d8557 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,38 @@ +root = true + +[*] +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space + +[*.{cs,csx}] +indent_size = 4 +end_of_line = crlf + +dotnet_sort_system_directives_first = true +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_require_accessibility_modifiers = always:warning +dotnet_style_readonly_field = true:warning + +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion +csharp_new_line_before_open_brace = all +csharp_prefer_braces = true:warning +csharp_style_prefer_primary_constructors = false:none + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.{js,ts,svelte,css,html}] +indent_size = 2 + +[*.{ps1,psm1}] +indent_size = 4 + +[*.{csproj,props,targets,wixproj,wxs}] +indent_size = 2 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..740c269 --- /dev/null +++ b/.env.example @@ -0,0 +1,146 @@ +#============================================================================= +# ExecuteR - Windows endpoint management control plane +#============================================================================= +# +# CREDENTIALS: +# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (below) +# NATS seeds: generated into secrets/nats by scripts/New-LocalSecrets.ps1 +# +# ACCESS URL: set PUBLIC_SERVER_URL to the public https URL served by your +# external reverse proxy (e.g. https://control.example.com) +# +# PRODUCTION SETUP: +# 1. cp .env.example .env (or run scripts/New-LocalSecrets.ps1) +# 2. Fill INITIAL_ADMIN_PASSWORD and NATS_ACCOUNT_SIGNING_SEED +# 3. docker compose up -d --build +# +#============================================================================= + +# ── Stack identity ───────────────────────────────────────────────────────── +# Compose project name and bind-mount root. Container and network names are +# static (EXECUTER-API-00001, EXECUTER-EXTERNAL, ...) and not derived from these. +STACK_NAME=stk-executer-00001 +STACK_BINDMOUNTROOT=/mnt/data/docker/stacks + +# ── Images ───────────────────────────────────────────────────────────────── +# Published by CI to Gitea's OWN container registry, which lives on the Gitea +# host itself. REGISTRY is "/", all lowercase — e.g. +# git.example.com/platform +# deploy.sh pulls these and builds from source only if the pull fails. +REGISTRY=git.example.com/owner +BACKEND_IMAGE=executer-backend +WEBUI_IMAGE=executer-webui +BACKEND_VERSION=latest +WEBUI_VERSION=latest +# missing = use local/pull once; always = re-pull every deploy; never = local only +IMAGE_PULL_POLICY=missing + +# Needed only to PULL from a private repo's packages. Any Gitea account token +# works as the password. CI does not need these — Actions injects its own. +REGISTRY_USERNAME= +REGISTRY_TOKEN= + +# Infrastructure images are pinned by digest. +NATS_IMAGE=nats +NATS_VERSION=2.12-alpine@sha256:7cef1bd3fed6034e95cf6e6bc9c28c5afa6dc58e9fb778dd7924a1ac62569f2d + +# Optional in-stack reverse proxy (docker-compose.proxy.yml, opt-in) +NGINX_IMAGE=nginx +NGINX_VERSION=1.29-alpine +PROXY_HTTP_PORT=18080 +PROXY_HTTPS_PORT=18443 +PROXY_PUBLIC_HOSTNAME=control.example.com + +# ── Host-published ports (uncommon range; front with the edge proxy) ─────── +BIND_EXTERNAL_ADDRESS=0.0.0.0 +WEBUI_PORT=13080 +BACKEND_PORT=19080 +NATS_WS_PORT=19222 + +# ── Public edge ──────────────────────────────────────────────────────────── +# The single public https URL served by your existing reverse proxy. +PUBLIC_SERVER_URL=https://control.example.com + +# ── Reverse proxy trust ──────────────────────────────────────────────────── +# At least one of TRUSTED_PROXIES / TRUSTED_NETWORKS is required when +# TRUST_PROXY=1 outside development mode. +TRUST_PROXY=1 +TRUSTED_PROXIES= +TRUSTED_NETWORKS=172.16.0.0/12 +TRUSTED_HOSTS=control.example.com +FORWARD_LIMIT=1 + +# ── Initial local admin (first startup only) ─────────────────────────────── +INITIAL_ADMIN_USERNAME=admin +# Generate: openssl rand -base64 24 +INITIAL_ADMIN_PASSWORD= + +# ── OIDC (optional) ──────────────────────────────────────────────────────── +OIDC_ENABLED=0 +OIDC_AUTHORITY= +OIDC_CLIENT_ID= +OIDC_CLIENT_SECRET= +OIDC_CALLBACK_PATH=/signin-oidc +OIDC_SCOPES=openid profile email +OIDC_NAME_CLAIM= +OIDC_ROLE_CLAIM= +OIDC_ADMIN_ROLE= + +# ── NATS decentralized auth (generated — do NOT hand-edit) ───────────────── +# These MUST be real Ed25519 NKeys from scripts/New-LocalSecrets.ps1 +# (or `dotnet run --project src/Backend -- nats-auth init`). A random string +# here will not work — the signing seed must match the resolver's account. +NATS_ACCOUNT_SIGNING_SEED= +NATS_ACCOUNT_PUBLIC_KEY= +NATS_OPERATOR_PUBLIC_KEY= + +# ── S3 file delivery (optional) ──────────────────────────────────────────── +# Enables presigned-URL file downloads to devices. Any S3-compatible store +# (AWS S3, MinIO, Backblaze B2, etc.). +S3_ENABLED=0 +S3_ENDPOINT= +S3_REGION=us-east-1 +S3_BUCKET= +S3_ACCESS_KEY= +S3_SECRET_KEY= +S3_FORCE_PATH_STYLE=1 +S3_PRESIGN_EXPIRY_SECONDS=900 + +# ── Database ─────────────────────────────────────────────────────────────── +# sqlite (default, uses DATABASE_PATH) | postgres | sqlserver +# For postgres/sqlserver set DATABASE_CONNECTION_STRING, e.g. +# postgres: Host=db;Port=5432;Database=executer;Username=executer;Password=... +# sqlserver: Server=db;Database=executer;User Id=sa;Password=...;TrustServerCertificate=True +DATABASE_PROVIDER=sqlite +DATABASE_CONNECTION_STRING= + +# ── Logging (Serilog: console + rolling file) ────────────────────────────── +# Server defaults: roll at 10 MB, keep the last 7 files (~70 MB ceiling). +# The agent defaults to 5 MB / 3 files and is configured via GPO or registry. +LOG_LEVEL=Information +LOG_JSON=0 +LOG_DIRECTORY=/data/logs +LOG_RETAIN_FILES=7 +LOG_MAX_BYTES=10485760 + +# ── Agent package for URL install (irm | iex) ────────────────────────────── +# Directory (inside the backend container) holding Agent.msi / Agent.zip that +# the URL install command downloads. Defaults to /data/agent (under API data). +AGENT_PACKAGE_PATH=/data/agent + +# ── Build / version ──────────────────────────────────────────────────────── +# Set by CI; local builds derive it via scripts/Build.ps1. +UNIFIED_VERSION= + +# ── Device lifecycle ─────────────────────────────────────────────────────── +# A device silent for this many days is orphaned: refused credential refresh +# and job dispatch until it re-enrolls with a fresh bootstrap token. +# Set to 0 to disable orphaning, so silent devices simply go Stale then +# Offline and reconnect on their own. Default (unset) is 30. +DEVICE_ORPHAN_AFTER_DAYS=30 + +# ── Automatic updates (Watchtower) ───────────────────────────────────────── +NATS_ENABLEAUTOMATICUPDATES=false +BACKEND_ENABLEAUTOMATICUPDATES=false +WEBUI_ENABLEAUTOMATICUPDATES=false +PROXY_ENABLEAUTOMATICUPDATES=false diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..ded0182 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,148 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [dev, main] + +jobs: + build-test: + # Windows is required to build/test the agent (CIM, ConPTY, DPAPI, service). + runs-on: windows + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET 10 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Compute unified version + id: ver + shell: pwsh + run: | + $v = & ./scripts/Get-UnifiedVersion.ps1 + "version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append + Write-Host "Unified version: $v" + + - name: Restore + run: dotnet restore ExecuteR.slnx + + - name: Build + run: dotnet build ExecuteR.slnx -c Release --no-restore "-p:UnifiedVersion=${{ steps.ver.outputs.version }}" + + - name: Unit tests + run: | + dotnet test tests/Shared.Tests -c Release --no-build --nologo + dotnet test tests/Agent.Tests -c Release --no-build --nologo + dotnet test tests/Backend.Tests -c Release --no-build --nologo + + - name: Integration tests + run: dotnet test tests/Integration.Tests -c Release --no-build --nologo + + - name: WebUI install + run: npm ci + working-directory: src/WebUI + + - name: WebUI check + run: npm run check + working-directory: src/WebUI + + - name: WebUI build + env: + PUBLIC_BUILD_VERSION: ${{ steps.ver.outputs.version }} + run: npm run build + working-directory: src/WebUI + + images: + # Build the backend + webui images and publish them to the Gitea container + # registry. Image names match what docker-compose.yml pulls: + # //executer-backend: + # //executer-webui: + needs: build-test + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-latest + 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 + # accepted as the registry password for the triggering actor. + # The REGISTRY_* secrets are only an override for an EXTERNAL registry. + REGISTRY_HOST: ${{ secrets.REGISTRY_HOST }} + REGISTRY_USER: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASS: ${{ secrets.REGISTRY_PASSWORD }} + SERVER_URL: ${{ github.server_url }} + ACTOR: ${{ github.actor }} + BUILTIN_TOKEN: ${{ secrets.GITEA_TOKEN }} + OWNER: ${{ github.repository_owner }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Resolve version and registry target + id: ver + shell: bash + run: | + set -e + echo "version=$(date -u +%Y.%m.%d.%H%M)" >> "$GITHUB_OUTPUT" + + # Default to Gitea's own registry on this instance; fall back to the + # REGISTRY_* secrets only when an external registry is configured. + if [ -n "$REGISTRY_HOST" ]; then + HOST="$REGISTRY_HOST"; USER="$REGISTRY_USER"; PASS="$REGISTRY_PASS" + echo "Using external registry $HOST" + else + HOST="$(echo "$SERVER_URL" | sed -E 's#^https?://##; s#/$##')" + USER="$ACTOR"; PASS="$BUILTIN_TOKEN" + echo "Using the built-in Gitea registry at $HOST" + fi + + # Gitea package paths are lowercase. + OWNER_LC="$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')" + + { + echo "host=$HOST" + echo "user=$USER" + echo "prefix=${HOST}/${OWNER_LC}/executer" + } >> "$GITHUB_OUTPUT" + echo "::add-mask::$PASS" + echo "REGISTRY_LOGIN_PASSWORD=$PASS" >> "$GITHUB_ENV" + + - name: Registry login + run: echo "$REGISTRY_LOGIN_PASSWORD" | docker login "${{ steps.ver.outputs.host }}" -u "${{ steps.ver.outputs.user }}" --password-stdin + + - name: Build images + env: + VERSION: ${{ steps.ver.outputs.version }} + PREFIX: ${{ steps.ver.outputs.prefix }} + run: | + set -e + docker build -f src/Infra/backend/Dockerfile --build-arg UNIFIED_VERSION="$VERSION" -t "${PREFIX}-backend:$VERSION" . + docker build -f src/Infra/webui/Dockerfile --build-arg UNIFIED_VERSION="$VERSION" -t "${PREFIX}-webui:$VERSION" . + + - name: Tag and push + env: + VERSION: ${{ steps.ver.outputs.version }} + PREFIX: ${{ steps.ver.outputs.prefix }} + REF_NAME: ${{ github.ref_name }} + run: | + set -e + for svc in backend webui; do + docker push "${PREFIX}-${svc}:$VERSION" + if [ "$REF_NAME" = "main" ]; then + docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:latest" + docker push "${PREFIX}-${svc}:latest" + else + docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:dev" + docker tag "${PREFIX}-${svc}:$VERSION" "${PREFIX}-${svc}:${VERSION}-dev" + docker push "${PREFIX}-${svc}:dev" + docker push "${PREFIX}-${svc}:${VERSION}-dev" + fi + done + echo "Published ${PREFIX}-backend and ${PREFIX}-webui" diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..1e3cbf8 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,47 @@ +name: Release + +on: + push: + branches: [main] + +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 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET 10 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Compute unified version + id: ver + shell: pwsh + run: | + $v = & ./scripts/Get-UnifiedVersion.ps1 + "version=$v" | Out-File -FilePath $env:GITHUB_OUTPUT -Append + + - name: Generate icon + shell: pwsh + run: ./scripts/Generate-Icons.ps1 + + - name: Package agent (exe zip + MSI + checksums) + shell: pwsh + run: ./scripts/Package-Agent.ps1 -Version ${{ steps.ver.outputs.version }} + + - name: Create Gitea release and upload assets + shell: pwsh + env: + # GITEA_TOKEN is injected automatically by Gitea Actions; SERVER_URL + # is seeded by scripts/Initialize-GiteaSecrets.ps1 and falls back to + # the instance URL the runner already knows. + GITEA_URL: ${{ vars.SERVER_URL || github.server_url }} + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITEA_OWNER: ${{ github.repository_owner }} + GITEA_REPOSITORY: ${{ github.event.repository.name }} + VERSION: ${{ steps.ver.outputs.version }} + run: ./scripts/Publish-Release.ps1 -Version $env:VERSION diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..08c1dfb --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Build results +bin/ +obj/ +artifacts/ +publish/ +TestResults/ +*.binlog + +# .NET tooling +.vs/ +.vscode/ +*.user +*.suo + +# Node / SvelteKit +node_modules/ +.svelte-kit/ +src/WebUI/build/ +npm-debug.log* + +# Local state +.local/ + +# Secrets — never commit generated secret material +.env +.env.* +!.env.example +secrets/* +!secrets/README.md +*.pfx +*.key +*.seed +*.creds + +# Generated icons (build artifacts) +assets/*.ico + +# OS noise +Thumbs.db +.DS_Store diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..872b1d3 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,27 @@ + + + + + $([System.DateTime]::get_UtcNow().ToString('yyyy.MM.dd.HHmm')) + $(UnifiedVersion) + $(UnifiedVersion) + $(UnifiedVersion) + $(UnifiedVersion) + + + + latest + enable + enable + true + true + false + true + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..d094619 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,57 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ExecuteR.slnx b/ExecuteR.slnx new file mode 100644 index 0000000..2fbd3a7 --- /dev/null +++ b/ExecuteR.slnx @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 1b04e77..67f3eb8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,792 @@ # ExecuteR +Secure Windows endpoint management: a self-contained .NET agent enrolls over +ordinary HTTPS, establishes **scoped NATS messaging over WebSocket** through the +same reverse-proxy edge, publishes live state, accepts durable work, runs +PowerShell in-process, and provides a secured interactive terminal — while the +browser uses a WebSocket-connected NATS client for near-real-time UI updates +with **no SignalR, SSE, or polling**. + +- **Agent** — single self-contained Windows x64 executable / Windows service + (.NET 10). Deterministic hardware identity, secure one-time bootstrap, + CIM inventory, in-process PowerShell (System.Management.Automation), ConPTY + remote shell, presigned-URL file delivery. +- **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC + auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live + event relay. +- **WebUI** — SvelteKit dashboard: live device status, Monaco PowerShell editor + with typed parameters and reusable function modules, live job output and + progress, xterm.js remote shell. + +![Dashboard](docs/screenshots/dashboard.png) + +--- + +## Table of contents + +1. [Architecture](#architecture) +2. [Component flow](#component-flow) +3. [Agent-to-component flow](#agent-to-component-flow) +4. [Prerequisites](#prerequisites) +5. [Local development](#local-development) +6. [Required secrets](#required-secrets) +7. [Generating local secrets](#generating-local-secrets) +8. [Docker Compose](#docker-compose) +9. [Reverse proxy routes](#reverse-proxy-routes) +10. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle) +11. [MSI public properties](#msi-public-properties) +12. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence) +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) + +--- + +## Architecture + +**Network topology** — every arrow crossing the edge is HTTP/HTTPS on port 443. +Agents and browsers never contact NATS directly: their NATS client speaks +WebSocket to the reverse proxy, which forwards to the NATS WebSocket listener. + +```mermaid +flowchart LR + A["Windows Agent"] + B["Browser / SvelteKit"] + P["Reverse Proxy :443"] + + A -->|"HTTPS: bootstrap, install"| P + A <-->|"WSS: NATS session"| P + B -->|"HTTPS: REST API"| P + B <-->|"WSS: NATS session"| P + + subgraph Stack ["Docker stack (private network)"] + UI["SvelteKit WebUI"] + API["ASP.NET Core Backend"] + N["NATS: WebSocket + TCP"] + DB[("SQLite / Postgres / SQL Server")] + JS[("JetStream")] + end + + P -->|"/"| UI + P -->|"/api/*"| API + P -->|"/messaging/agent"| N + P -->|"/messaging/browser"| N + + API <-->|"NATS TCP (internal only)"| N + API --> DB + N --- JS +``` + +The only externally reachable route is HTTP/HTTPS on the edge proxy. NATS TCP +(4222) is never published to the public network. + +**Message flow over those sessions** — once the WSS sessions above are +established, messages travel in both directions on them. The subjects each +party may use are enforced by its NATS JWT. + +```mermaid +flowchart LR + A["Agent"] + N["NATS"] + API["Backend"] + B["Browser"] + + A -->|"presence, inventory, job output/progress/state, shell output"| N + N -->|"durable commands: script, inventory, file, shell"| A + N <--> API + API -->|"republished, session-scoped events"| N + N -->|"browser.session.* only"| B + B -->|"browser.session.shell.input only"| N +``` + +Both agent and browser traffic in this second diagram physically rides the +proxied WebSocket session from the topology diagram. + +--- + +## Component flow + +How a request or event moves through the internal components. + +```mermaid +flowchart TB + subgraph Browser + UI["SvelteKit pages"] + BN["Browser NATS client (WSS)"] + end + + subgraph Backend + REST["REST API + Auth + RBAC"] + ISS["NATS credential issuer"] + DISP["Command dispatcher (JetStream)"] + WORK["Messaging workers"] + BR["Browser event broadcaster"] + SB["Shell bridge"] + S3["S3 presign service"] + EF[("EF Core / SQLite")] + end + + subgraph Fabric + CORE["NATS Core"] + JSS["JetStream: COMMANDS, JOB_EVENTS"] + end + + UI -->|"login, CRUD, run"| REST + UI -->|"POST /api/messaging/credential"| ISS + BN -->|"subscribe browser session subjects (via proxy)"| CORE + REST --> EF + REST --> DISP + DISP --> JSS + WORK -->|"consume presence/inventory/output/state"| CORE + WORK --> EF + WORK --> BR + BR -->|"publish browser session events"| CORE + CORE --> BN + SB -->|"forward shell input, relay output"| CORE + REST --> SB + REST --> S3 +``` + +--- + +## Agent-to-component flow + +What the agent does after it starts, and which backend component handles each +message. + +```mermaid +sequenceDiagram + participant A as "Agent" + participant API as "Backend REST" + participant N as "NATS / JetStream" + participant W as "Messaging workers" + participant DB as "SQLite" + participant U as "Browser" + + A->>A: "CIM fingerprint to deterministic ClientId" + A->>A: "Generate User NKey (seed stays local)" + A->>API: "POST /api/enrollment/bootstrap" + API->>DB: "Consume token, bind device, audit" + API-->>A: "Scoped NATS user JWT" + A->>N: "WSS connect (JWT + NKey)" + A->>N: "presence (30s), inventory (start + interval)" + N->>W: "presence / inventory" + W->>DB: "upsert device + inventory" + W->>U: "authorized browser session events" + API->>N: "durable script/file command (JetStream)" + N->>A: "command (explicit ack after durable record)" + A->>N: "job output / progress / state" + N->>W: "persist + relay" + W->>U: "live job updates" +``` + +Full script-execution, enrollment, and remote-shell sequence diagrams are in +[docs/sequences.md](docs/sequences.md). + +--- + +## Prerequisites + +- **.NET SDK 10** (`dotnet --version` gives 10.x) +- **Node.js LTS** (20+) and npm — for the WebUI +- **Docker + Docker Compose** — to run the stack +- **Windows** — required to build/run the agent (CIM, ConPTY, DPAPI, Windows + service). The backend and WebUI are cross-platform. +- **WiX Toolset v5** (restored automatically) — for the MSI +- **ImageMagick** — installed on demand by `scripts/Generate-Icons.ps1` + +--- + +## Local development + +```powershell +# One-time setup: restores packages, installs WebUI deps, generates secrets +./scripts/Initialize-Repository.ps1 + +# Build everything with one unified version +./scripts/Build.ps1 -IncludeWebUI + +# Run tests +./scripts/Test.ps1 # unit +./scripts/Test.ps1 -IncludeWebUI # + svelte-check +``` + +Run the stack: + +```powershell +docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build +``` + +On a server, deploy straight from the repository — no clone needed. This pulls +the published images and falls back to building only if the pull fails: + +```bash +curl -fsSL https://git.example.com/owner/ExecuteR/raw/branch/main/scripts/deploy.sh | bash + +# ...or let the stack run its own nginx edge (opt-in): +curl -fsSL https://.../deploy.sh | bash -s -- --with-proxy --host control.example.com +``` + +The script writes `.env` with a generated admin password, prepares the +bind-mount tree, and generates real NATS keys by running the backend image's +own `nats-auth` CLI, so the host needs nothing but Docker. + +Run pieces directly for a fast inner loop: + +```powershell +# Backend (Development seeds a demo script; DEV_SEED=1 adds sample devices/jobs) +$env:ASPNETCORE_ENVIRONMENT='Development'; $env:ASPNETCORE_URLS='http://127.0.0.1:19080' +$env:INITIAL_ADMIN_USERNAME='admin'; $env:INITIAL_ADMIN_PASSWORD='DemoPass123!' +dotnet run --project src/Backend + +# WebUI (proxies /api and /messaging to the backend + NATS) +npm --prefix src/WebUI run dev +``` + +--- + +## Required secrets + +Committed: `.env.example`, `secrets/README.md`, `scripts/New-LocalSecrets.ps1`. +Never commit generated secrets (enforced by `.gitignore`). + +| Secret | Purpose | +|--------|---------| +| `INITIAL_ADMIN_PASSWORD` | First-boot local admin password | +| `NATS_OPERATOR_SEED` | NATS operator identity | +| `NATS_ACCOUNT_SEED` | Application account identity | +| `NATS_ACCOUNT_SIGNING_SEED` | Backend signs user JWTs with this | +| `OIDC_CLIENT_SECRET` | Only when OIDC is enabled | +| `GITEA_TOKEN` | CI release/push automation | +| `S3_SECRET_KEY` | Only when S3 file delivery is enabled | + +Non-secret identifiers (`NATS_*_PUBLIC_KEY`, `GITEA_URL`, `GITEA_OWNER`, +`GITEA_REPOSITORY`, `CONTAINER_REGISTRY`) may live in `.env`. + +--- + +## Generating local secrets + +```powershell +./scripts/New-LocalSecrets.ps1 +``` + +This generates **real Ed25519 NATS keys** (operator, APP account, account +signing key, SYS account/user) and the resolver preload using the backend's +`nats-auth` CLI — the same NATS.Jwt/NATS.NKeys code the backend uses at runtime, +so no fake seeds: + +```powershell +dotnet run --project src/Backend -- nats-auth init --output secrets/nats +``` + +It writes `.env` (with a random admin password and the account signing seed) +and `secrets/nats/resolver.conf` (mounted into the NATS container). + +--- + +## Docker Compose + +Services follow the stack conventions: `EXTERNAL` + `INTERNAL` bridge networks, +container names `EXECUTER-{NATS,API,WEB}-00001`, service-name networking, and +uncommon host ports. + +| Service | Container | Host port | Internal | +|---------|-----------|-----------|----------| +| nats | `EXECUTER-NATS-00001` | `19222` (WebSocket) | 4222 TCP, 8222 monitor | +| backend | `EXECUTER-API-00001` | `19080` | 8080 | +| webui | `EXECUTER-WEB-00001` | `13080` | 3000 | + +Volumes bind under `${STACK_BINDMOUNTROOT}/${STACK_NAME}/{Tier}/Data`. The NATS +image is pinned by digest. See `.env.example` for every variable. + +```powershell +docker compose up -d --build +``` + +--- + +## Reverse proxy routes + +The stack assumes an existing external reverse proxy terminating TLS on `:443` +and forwarding to the host ports above: + +| Public path | Upstream | +|-------------|----------| +| `/` | webui `:13080` | +| `/api/*` | backend `:19080` | +| `/messaging/agent` | nats websocket `:19222` | +| `/messaging/browser` | nats websocket `:19222` | + +The proxy must preserve the WebSocket upgrade and send `X-Forwarded-For`, +`X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Prefix`. The backend +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). + +--- + +## Agent foreground mode and service lifecycle + +The one binary supports: + +```text +Agent.exe foreground run interactively (console logging) +Agent.exe install create/update the Windows service (idempotent) +Agent.exe start start the service +Agent.exe stop stop the service +Agent.exe initialize install + start +Agent.exe remove stop + remove the service +Agent.exe status machine- and human-readable state +Agent.exe version unified build version +``` + +Launched by the SCM with no argument, it runs as a service (`LocalSystem`, +Automatic Delayed Start, restart-on-failure recovery). Service manipulation uses +the Windows service APIs (`advapi32` / `ServiceController`) — never `sc.exe`. + +--- + +## MSI public properties + +```text +msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN= +``` + +| Property | Registry value | +|----------|----------------| +| `SERVERURL` | `ServerURL` | +| `BOOTSTRAPTOKEN` | `BootstrapToken` (erased after enrollment) | +| `LOGLEVEL` | `LogLevel` | +| `ALLOWREMOTESHELL` | `AllowRemoteShell` | +| `ALLOWSCRIPTEXECUTION` | `AllowScriptExecution` | + +The installer never overwrites a non-blank existing value with a blank property, +preserves configuration on upgrade, and removes runtime credentials only on a +real uninstall (never during an upgrade). + +--- + +## Registry paths and GPO precedence + +```text +Normal config: HKLM\SOFTWARE\ExecuteR +Runtime state: HKLM\SOFTWARE\ExecuteR\Runtime +GPO policy: HKLM\SOFTWARE\Policies\ExecuteR +``` + +Effective configuration precedence is **GroupPolicy > normal registry > +dev-only environment > compiled defaults** (each value carries its provenance). +Group Policy templates live in +[src/Installer/Policies](src/Installer/Policies) (`ExecuteR.admx` + +`en-US/ExecuteR.adml`). + +--- + +## Bootstrap and URL install + +1. Sign in as admin, open **Settings**, and generate a one-time bootstrap token. +2. Deploy the agent one of two ways. + +MSI: + +```text +msiexec /i Agent.msi /qn SERVERURL=https://control.example.com BOOTSTRAPTOKEN= +``` + +URL one-liner (elevated PowerShell on the target; requires `Agent.msi` in the +backend's `AGENT_PACKAGE_PATH`): + +```powershell +iwr https://control.example.com/api/enrollment/install?token= -UseBasicParsing | iex +``` + +The agent generates its NKey locally (the private seed never leaves the device), +bootstraps over HTTPS, receives a scoped NATS JWT, erases the token, and +connects over WSS. The device appears in the UI within seconds. + +--- + +## Local login and OIDC + +Local auth uses ASP.NET Core `PasswordHasher` (no compiled default password). +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): + +```text +OIDC_ENABLED=1 +OIDC_AUTHORITY=https://idp.example.com/application/o/executer/ +OIDC_CLIENT_ID=executer +OIDC_CLIENT_SECRET= +OIDC_SCOPES=openid profile email +OIDC_ROLE_CLAIM=groups +OIDC_ADMIN_ROLE=executer-admins +``` + +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. + +![Login](docs/screenshots/login.png) + +--- + +## 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. + +Reusable **function modules** (managed under **Functions**) can be attached to a +script; the backend prepends them as a prelude executed first in the same +runspace, so individual scripts stay small and duplication is avoided. + +![Script editor](docs/screenshots/script-editor.png) + +--- + +## Device groups and script triggers + +Groups are either **static** (an explicit member list) or **dynamic** (rules +evaluated against live device data). + +Rules are one or more **condition groups**. Conditions inside a group combine +with AND or OR, the groups themselves combine with AND or OR, groups can nest, +and both conditions and groups have an independent **NOT**. + +Operators: `equals`, `notEquals`, `contains`, `notContains`, `startsWith`, +`endsWith`, `regex`, `in`, `notIn`, `>`, `>=`, `<`, `<=`, `exists`, +`notExists`. + +Fields come from hardware inventory, tags, hostname/identity, and live status — +the full catalogue is served by `GET /api/groups/fields`, so the rule builder +always matches what the server can evaluate: + +| Category | Examples | +|----------|----------| +| Identity | `hostname`, `clientId`, `status`, `tags`, `agentVersion`, `domain` | +| Hardware | `manufacturer`, `model`, `serialNumber`, `cpu.cores`, `memory.totalGb` | +| Operating system | `os.caption`, `os.version`, `os.build`, `os.architecture` | +| Storage | `disk.count`, `disk.totalGb`, `volume.freeGb` | +| Network | `network.ipv4`, `network.mac`, `network.dns` | + +Multi-valued fields (tags, IPs, MACs, DNS) match when **any** value satisfies a +positive operator, and require **all** values for the negative ones. A missing +field satisfies only the negative operators. Invalid or runaway regex never +matches and never throws. + +**Preview** evaluates candidate rules against live devices before you save. + +![Group rule builder](docs/screenshots/groups-rule-builder.png) + +**Script triggers** run a script automatically on a device lifecycle event, +targeted at a group (or all devices): + +| Trigger | Fires when | +|---------|-----------| +| `onRegistration` | A device completes enrollment | +| `onAgentReady` | The agent is connected *and* its durable command consumer is bound — genuinely ready for jobs | + +Triggers default to **once per device** (recorded durably), and triggered runs +use the normal job pipeline, so they carry the script's function-module prelude +and typed parameters and appear alongside manual runs. + +--- + +## Database providers + +SQLite is the default and needs no configuration. Postgres and SQL Server are +selected with environment variables: + +```text +DATABASE_PROVIDER=sqlite # or: postgres | sqlserver +DATABASE_PATH=/data/app.db # sqlite only + +DATABASE_PROVIDER=postgres +DATABASE_CONNECTION_STRING=Host=db;Port=5432;Database=executer;Username=executer;Password=... + +DATABASE_PROVIDER=sqlserver +DATABASE_CONNECTION_STRING=Server=db;Database=executer;User Id=sa;Password=...;TrustServerCertificate=True +``` + +Each provider carries its own EF Core migration set, applied automatically at +startup. SQLite stores timestamps as UTC ticks (it cannot order +`DateTimeOffset` natively); Postgres and SQL Server use native timestamp +columns. + +Adding a migration touches all three: + +```powershell +dotnet ef migrations add --project src/Backend --context SqliteAppDbContext --output-dir Data/Migrations/Sqlite +dotnet ef migrations add --project src/Backend --context PostgresAppDbContext --output-dir Data/Migrations/Postgres +dotnet ef migrations add --project src/Backend --context SqlServerAppDbContext --output-dir Data/Migrations/SqlServer +``` + +--- + +## Logging + +All services share one Serilog pipeline (`Shared.Infrastructure/Logging`): +console plus a **daily rolling file** with a size cap and retention. + +Rotation defaults are set centrally per role in `LogDefaults`, because +endpoints are numerous and disk-constrained while the server is neither: + +| Role | Roll at | Keep | Ceiling | +|------|---------|------|---------| +| Agent | 5 MB | 3 files | ~15 MB | +| Backend | 10 MB | 7 files | ~70 MB | + +```text +LOG_LEVEL=Information # Verbose|Debug|Information|Warning|Error|Fatal +LOG_JSON=0 # 1 = compact JSON (for log shippers) +LOG_DIRECTORY=/data/logs # empty disables file logging +LOG_RETAIN_FILES=7 # server default; agent default is 3 +LOG_MAX_BYTES=10485760 # server default 10 MB; agent default 5 MB +``` + +Files also roll daily, so the size cap is an upper bound rather than the usual +trigger. + +Framework noise is pinned to Warning regardless of `LOG_LEVEL`, and health +probes log at Verbose so they do not flood the file. Requests are logged once +each with the effective (proxy-aware) client IP and the authenticated user. +Correlation fields (`CorrelationId`, `ClientId`, `JobId`, `ShellSessionId`, +`BrowserSessionId`, `RemoteIp`) flow through as structured properties. + +The agent takes its level from its own configuration precedence +(GPO > registry > default) and writes to `%ProgramData%\ExecuteR\logs`. A bad +log path degrades to console logging rather than failing startup. + +Secrets are never logged: tokens, passwords, client secrets, NKey seeds, JWTs, +cookies and authorization headers. + +--- + +## Device lifecycle: reconnect or orphan + +A device silent for longer than the orphan window is **orphaned**. The window +is centrally defaulted to **30 days** (`ProtocolDefaults.DefaultOrphanAfterDays`) +and controlled with one setting: + +```text +DEVICE_ORPHAN_AFTER_DAYS=30 # default when unset +DEVICE_ORPHAN_AFTER_DAYS=0 # disable orphaning entirely +``` + +With orphaning **disabled**, a device that stops checking in just ages through +**Online → Stale → Offline**, keeps its credentials, and reconnects entirely on +its own whenever it comes back — nothing to do. + +An orphaned device is refused credential refresh and job dispatch, and is *not* +resurrected merely by reappearing — presence from it is logged and ignored. +Recovery is deliberate: + +```mermaid +flowchart LR + O["Silent past the window"] --> M["Backend marks device orphaned"] + M --> R["Refuses credential refresh and job dispatch"] + R --> T["Admin pushes a new bootstrap token (GPO, MSI, URL install)"] + T --> E["Agent sees the token and re-enrolls"] + E --> B["Same device record, orphan flag cleared, back in service"] +``` + +The agent side needs no special mode: a bootstrap token is erased after every +successful enrollment, so the presence of one is by definition a deliberate +instruction. When an already-enrolled agent finds a token, it discards its +stored credentials and re-enrolls. Enrollment is idempotent by client id, so +the device keeps its history, groups and tags. + +--- + +## 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. + +```mermaid +sequenceDiagram + participant U as "Operator" + participant API as "Backend" + participant S3 as "S3 store" + participant N as "NATS / JetStream" + participant A as "Agent" + + U->>API: "POST /api/devices/{id}/files (objectKey, destination, sha256?)" + API->>S3: "presign GET (expires in S3_PRESIGN_EXPIRY_SECONDS)" + S3-->>API: "signed URL" + API->>N: "durable file command (URL, destination, hash)" + N->>A: "command.file" + A->>A: "already have it? (hash, then ETag)" + A->>S3: "GET signed URL (If-None-Match when cached)" + S3-->>A: "200 body, or 304 Not Modified" + A->>N: "progress, then Succeeded" + N->>API: "persist, relay to browser" +``` + +**Downloads are skipped when nothing changed**, in two escalating steps: + +1. **Hash match, no request at all.** If the destination already exists and the + caller supplied `sha256`, the agent hashes the local file; if it matches, + the job succeeds immediately with "Already up to date". +2. **Let S3 decide.** Otherwise the agent sends the ETag it stored last time as + `If-None-Match`. An unchanged object returns **304 Not Modified** and costs + no transfer; a changed object returns the new body. + +The agent keeps a small local cache (destination path → ETag, SHA-256, size) in +its SQLite store, so this survives restarts. Every completed download is hashed +regardless — verifying the transfer when an expected hash was given, and +seeding the cache when it was not. Writes are atomic (temp file, then move), so +a failed or interrupted download never leaves a half-written file in place. + +Configuration: + +```text +S3_ENABLED=1 +S3_ENDPOINT=https://s3.example.com # blank for AWS +S3_REGION=us-east-1 +S3_BUCKET=executer-payloads +S3_ACCESS_KEY=... +S3_SECRET_KEY=... +S3_FORCE_PATH_STYLE=1 # 1 for MinIO and most self-hosted +S3_PRESIGN_EXPIRY_SECONDS=900 +``` + +--- + +## CI/CD and GITEA_* variables + +Images are published to **Gitea's own container registry**, which lives on the +Gitea host itself — `//executer-backend` and +`…/executer-webui`. No registry configuration is required: Gitea Actions +injects a `GITEA_TOKEN` per run that the registry accepts as the triggering +actor's password, and the host is derived from the instance URL. + +Seed the remaining repository secrets and variables once (idempotent; never +prints values): + +```powershell +$env:GITEA_URL='https://git.example.com'; $env:GITEA_API_TOKEN='' +./scripts/Initialize-GiteaSecrets.ps1 +``` + +It derives owner/repo from the git remote, reads values from `.env` and +`secrets/nats`, and writes the NATS signing seed, admin password and OIDC/S3 +secrets, plus `REGISTRY` and `SERVER_URL` variables. The token needs +repository admin scope. + +To publish somewhere other than this Gitea instance, add `-ExternalRegistry` +(with `-RegistryUsername`/`-RegistryPassword`); CI then uses those credentials +instead of the built-in token. + +Two Gitea API quirks worth knowing if you script against it yourself: the +secrets endpoint takes `{"data": …}` while variables take `{"value": …}`, and +secret names may not begin with `GITEA_` or `GITHUB_`. + +Pulling images on a deployment host only needs credentials when the repository +is private — set `REGISTRY_USERNAME` and `REGISTRY_TOKEN` in `.env` and +`deploy.sh` logs in before pulling. + +Gitea Actions workflows live in `.gitea/workflows`: + +- **Pull request to `main`** — restore, build, unit + integration tests, Svelte + check. No image push, no release. +- **Push to `dev`** — build + test, agent binary + MSI, backend/webui images + tagged `dev` and `-dev`. +- **Push to `main`** — build + test, agent + MSI, images tagged `` and + `latest`, and a Gitea release with the agent ZIP, MSI and checksums. + +Scripts discover context from optional environment variables and fall back +gracefully when run locally: + +```text +GITEA_URL GITEA_TOKEN GITEA_OWNER GITEA_REPOSITORY GITEA_SHA GITEA_REF +GITEA_REF_NAME GITEA_RUN_NUMBER GITEA_ACTOR GITEA_CONTAINER_REGISTRY +GITEA_CONTAINER_REGISTRY_USERNAME GITEA_CONTAINER_REGISTRY_PASSWORD +``` + +Token values are never printed. `dev` is not merged into `main` automatically. + +--- + +## Versioning + +All artifacts share one unified version, `yyyy.MM.dd.HHmm` (UTC), computed once +per build (`scripts/Get-UnifiedVersion.ps1`) and embedded into the agent, the +backend assembly, Docker image labels/tags, the MSI (via a deterministic +MSI-compatible numeric transform, with the full version retained in display +metadata), and the frontend build metadata. + +--- + +## MVP demo sequence + +1. `docker compose up -d` — backend, NATS and WebUI become healthy. +2. Sign in locally as the initial admin. +3. Generate a one-time bootstrap token (Settings). +4. Install the agent (`SERVERURL`, `BOOTSTRAPTOKEN`) via MSI or the URL one-liner. +5. The device appears within seconds; presence keeps status live without refresh. +6. Inventory populates the device detail tabs. +7. Author/save a PowerShell script; select the device; run. +8. Job state goes Running, output and a progress bar advance live; job Succeeds. +9. Open the remote shell; run `hostname`, `whoami`, `Get-Process | Select -First 5`. +10. Resize and disconnect cleanly; restart the service — it reconnects without a + token; rerun and verify no duplicate execution from redelivery. + +--- + +## Troubleshooting + +| Symptom | Check | +|---------|-------| +| Device never appears | Agent log: bootstrap HTTP status; token not expired/consumed; `ServerURL` scheme is http/https (agent derives ws/wss) | +| `/api/ready` returns 503 | Database reachable, NATS connected, `NATS_ACCOUNT_SIGNING_SEED` loaded | +| Browser shows "Offline" | `POST /api/messaging/credential` succeeds; proxy preserves the WebSocket upgrade on `/messaging/browser` | +| Agent will not connect to NATS | `resolver.conf` account matches `NATS_ACCOUNT_*`; WSS path reachable through the proxy | +| Remote shell disabled | `AllowRemoteShell=1` (policy or registry) and the agent is online | +| Script "disabled by policy" | `AllowScriptExecution` not set to 0 by GPO/registry | +| CSRF 403 | The SPA sends `X-CSRF-Token`; ensure the `csrf_token` cookie is present | +| File delivery 503 | `S3_ENABLED=1` and S3 credentials/bucket configured | +| Job creation returns 409 | Device is orphaned — push a new bootstrap token so the agent re-enrolls | +| Download "skipped" unexpectedly | Local file already matches the supplied `sha256`, or S3 returned 304 for the stored ETag. Change the object (new ETag) or pass the new hash | +| `docker compose pull` fails | Set `REGISTRY` in `.env` and run `scripts/Initialize-GiteaSecrets.ps1` so CI has published images; `deploy.sh` falls back to building from source | + +--- + +## Screenshots + +| | | +|---|---| +| ![Dashboard](docs/screenshots/dashboard.png) **Dashboard** | ![Devices](docs/screenshots/devices.png) **Devices** | +| ![Device detail](docs/screenshots/device-detail.png) **Device overview, tags and groups** | ![Hardware](docs/screenshots/device-hardware.png) **Hardware inventory** | +| ![Network](docs/screenshots/device-network.png) **Network inventory** | ![Actions](docs/screenshots/device-actions.png) **Device actions and file delivery** | +| ![Groups](docs/screenshots/groups.png) **Groups** | ![Static members](docs/screenshots/groups-static-members.png) **Static group membership** | +| ![Script editor](docs/screenshots/script-editor.png) **Monaco PowerShell editor** | ![Parameters](docs/screenshots/script-parameters.png) **Typed parameters** | +| ![Jobs](docs/screenshots/jobs.png) **Jobs and stored output** | ![Functions](docs/screenshots/functions.png) **Function modules** | +| ![Settings](docs/screenshots/settings-install-command.png) **Bootstrap token and install command** | ![Light theme](docs/screenshots/dashboard-light.png) **Light theme** | + +--- + +Built to prove one idea cleanly: secure HTTPS enrollment, scoped NATS over +WebSocket through one proxy edge, durable work, in-process PowerShell, and a +secured terminal — with a browser that updates in real time over NATS, no +SignalR or SSE. diff --git a/assets/README.md b/assets/README.md new file mode 100644 index 0000000..16e7d33 --- /dev/null +++ b/assets/README.md @@ -0,0 +1,11 @@ +# assets/ + +`icon-source.png` is the canonical square icon source (512×512 or larger). + +`scripts/Generate-Icons.ps1` converts it to a multi-resolution +`artifacts/icons/app.ico` (256/128/64/48/32/16) using ImageMagick and the +build embeds it into the Agent executable via `ApplicationIcon`. The +script installs ImageMagick silently (winget) when missing; if it is +already installed nothing is reinstalled — generation is idempotent. + +Generated `.ico` files are build artifacts and are not committed. diff --git a/assets/icon-source.png b/assets/icon-source.png new file mode 100644 index 0000000..0c4c1c4 Binary files /dev/null and b/assets/icon-source.png differ diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..49158fe --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,15 @@ +# Development overrides: +# docker compose -f docker-compose.yml -f docker-compose.dev.yml up +# +# Exposes internal NATS TCP + monitoring on loopback for local tooling and +# integration tests, and runs the backend in Development mode. +services: + nats: + ports: + - '127.0.0.1:14222:4222' + - '127.0.0.1:18222:8222' + + backend: + environment: + ASPNETCORE_ENVIRONMENT: 'Development' + LOG_JSON: '0' diff --git a/docker-compose.proxy.yml b/docker-compose.proxy.yml new file mode 100644 index 0000000..6b8ea8a --- /dev/null +++ b/docker-compose.proxy.yml @@ -0,0 +1,51 @@ +# Optional in-stack reverse proxy. +# +# docker compose -f docker-compose.yml -f docker-compose.proxy.yml up -d +# ./scripts/deploy.sh --with-proxy +# +# NOT included by default: most deployments already have an edge proxy (NPM, +# Traefik, Caddy, an existing nginx). Use this only when you want the stack to +# own its own TLS edge. +# +# Provide certificates at: +# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Certs/fullchain.pem +# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Certs/private.key +# and a site config at: +# ${STACK_BINDMOUNTROOT}/${STACK_NAME}/Proxy/Config/executer.conf +# (deploy.sh writes one derived from src/Infra/nginx/executer.conf). + +services: + proxy: + image: '${NGINX_IMAGE:-nginx}:${NGINX_VERSION:-1.29-alpine}' + container_name: EXECUTER-PROXY-00001 + restart: unless-stopped + stop_signal: SIGQUIT + stop_grace_period: 30s + depends_on: + backend: + condition: service_healthy + webui: + condition: service_started + logging: + driver: 'local' + networks: + EXTERNAL: + INTERNAL: + ports: + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTP_PORT:-18080}:80' + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${PROXY_HTTPS_PORT:-18443}:443' + volumes: + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Config:/etc/nginx/conf.d:ro" + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Certs:/etc/nginx/ssl:ro" + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Logs:/var/log/nginx:rw" + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/Proxy/Acme:/var/www/acme:rw" + healthcheck: + test: ["CMD", "nginx", "-t"] + start_period: 15s + interval: 30s + retries: 3 + timeout: 5s + labels: + com.centurylinklabs.watchtower.enable: '${PROXY_ENABLEAUTOMATICUPDATES:-false}' diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..79071c7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,185 @@ +#============================================================================= +# ExecuteR - Windows endpoint management control plane +# Agent + NATS-over-WebSocket + ASP.NET Core backend + SvelteKit web UI +#============================================================================= +# +# CREDENTIALS: +# Initial admin: INITIAL_ADMIN_USERNAME / INITIAL_ADMIN_PASSWORD (.env) +# NATS decentralized auth: seeds generated by scripts/New-LocalSecrets.ps1 +# +# PRODUCTION SETUP: +# 1. ./scripts/New-LocalSecrets.ps1 # generate .env + NATS keys +# 2. docker compose up -d --build # start nats, backend, webui +# 3. Point the external reverse proxy at the published host ports below +# +# ENDPOINTS (host-published; front with your external reverse proxy): +# - WebUI: http://:${WEBUI_PORT} -> / +# - Backend API: http://:${BACKEND_PORT} -> /api/* +# - NATS WebSocket: ws://:${NATS_WS_PORT} -> /messaging/agent,/messaging/browser +# +#============================================================================= + +name: '${STACK_NAME:-stk-executer-00001}' + +networks: + EXTERNAL: + name: EXECUTER-EXTERNAL + driver: bridge + internal: false + attachable: true + INTERNAL: + name: EXECUTER-INTERNAL + driver: bridge + internal: true + attachable: true + +services: + + nats: + image: '${NATS_IMAGE:-nats}:${NATS_VERSION:-2.12-alpine@sha256:7cef1bd3fed6034e95cf6e6bc9c28c5afa6dc58e9fb778dd7924a1ac62569f2d}' + container_name: EXECUTER-NATS-00001 + command: ["-c", "/etc/nats/nats.conf"] + restart: unless-stopped + stop_signal: SIGTERM + stop_grace_period: 30s + logging: + driver: 'local' + networks: + INTERNAL: + EXTERNAL: + expose: + - '4222' + ports: + # WebSocket listener — the external reverse proxy maps /messaging/* here. + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${NATS_WS_PORT:-19222}:9222' + volumes: + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + - ./src/Infra/nats/nats.conf:/etc/nats/nats.conf:ro + - ./secrets/nats/resolver.conf:/etc/nats/resolver.conf:ro + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/NATS/JetStream:/data/jetstream:rw" + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/NATS/Resolver:/data/resolver:rw" + healthcheck: + test: ["CMD", "wget", "-q", "-O", "-", "http://127.0.0.1:8222/healthz"] + start_period: 20s + interval: 10s + retries: 5 + timeout: 5s + labels: + com.centurylinklabs.watchtower.enable: '${NATS_ENABLEAUTOMATICUPDATES:-false}' + + backend: + # Published image by default; `build` is the fallback used when the image + # is not present locally and cannot be pulled (pull_policy: missing). + # scripts/deploy.sh pulls first and builds only if the pull fails. + image: '${REGISTRY:-git.example.com/owner}/${BACKEND_IMAGE:-executer-backend}:${BACKEND_VERSION:-${UNIFIED_VERSION:-latest}}' + pull_policy: '${IMAGE_PULL_POLICY:-missing}' + container_name: EXECUTER-API-00001 + build: + context: . + dockerfile: src/Infra/backend/Dockerfile + args: + UNIFIED_VERSION: ${UNIFIED_VERSION:-0.0.0.0} + restart: unless-stopped + stop_signal: SIGTERM + stop_grace_period: 30s + depends_on: + nats: + condition: service_healthy + logging: + driver: 'local' + networks: + INTERNAL: + EXTERNAL: + expose: + - '8080' + ports: + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${BACKEND_PORT:-19080}:8080' + environment: + ASPNETCORE_URLS: 'http://0.0.0.0:8080' + DATABASE_PROVIDER: '${DATABASE_PROVIDER:-sqlite}' + DATABASE_PATH: '/data/app.db' + DATABASE_CONNECTION_STRING: '${DATABASE_CONNECTION_STRING:-}' + NATS_URL: 'nats://nats:4222' + LOG_LEVEL: '${LOG_LEVEL:-Information}' + LOG_JSON: '${LOG_JSON:-0}' + LOG_DIRECTORY: '${LOG_DIRECTORY:-/data/logs}' + LOG_RETAIN_FILES: '${LOG_RETAIN_FILES:-7}' + LOG_MAX_BYTES: '${LOG_MAX_BYTES:-10485760}' + DEVICE_ORPHAN_AFTER_DAYS: '${DEVICE_ORPHAN_AFTER_DAYS:-30}' + TRUST_PROXY: '${TRUST_PROXY:-1}' + TRUSTED_PROXIES: '${TRUSTED_PROXIES:-}' + TRUSTED_NETWORKS: '${TRUSTED_NETWORKS:-}' + TRUSTED_HOSTS: '${TRUSTED_HOSTS:-}' + FORWARD_LIMIT: '${FORWARD_LIMIT:-1}' + PUBLIC_SERVER_URL: '${PUBLIC_SERVER_URL:-}' + INITIAL_ADMIN_USERNAME: '${INITIAL_ADMIN_USERNAME:-}' + INITIAL_ADMIN_PASSWORD: '${INITIAL_ADMIN_PASSWORD:-}' + 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_SCOPES: '${OIDC_SCOPES:-openid profile email}' + OIDC_NAME_CLAIM: '${OIDC_NAME_CLAIM:-}' + OIDC_ROLE_CLAIM: '${OIDC_ROLE_CLAIM:-}' + OIDC_ADMIN_ROLE: '${OIDC_ADMIN_ROLE:-}' + NATS_ACCOUNT_SIGNING_SEED: '${NATS_ACCOUNT_SIGNING_SEED:-}' + NATS_ACCOUNT_PUBLIC_KEY: '${NATS_ACCOUNT_PUBLIC_KEY:-}' + AGENT_PACKAGE_PATH: '${AGENT_PACKAGE_PATH:-/data/agent}' + S3_ENABLED: '${S3_ENABLED:-0}' + S3_ENDPOINT: '${S3_ENDPOINT:-}' + S3_REGION: '${S3_REGION:-us-east-1}' + S3_BUCKET: '${S3_BUCKET:-}' + S3_ACCESS_KEY: '${S3_ACCESS_KEY:-}' + S3_SECRET_KEY: '${S3_SECRET_KEY:-}' + S3_FORCE_PATH_STYLE: '${S3_FORCE_PATH_STYLE:-1}' + S3_PRESIGN_EXPIRY_SECONDS: '${S3_PRESIGN_EXPIRY_SECONDS:-900}' + volumes: + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + - "${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}/${STACK_NAME:-stk-executer-00001}/API/Data:/data:rw" + healthcheck: + test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/api/health"] + start_period: 30s + interval: 10s + retries: 5 + timeout: 5s + labels: + com.centurylinklabs.watchtower.enable: '${BACKEND_ENABLEAUTOMATICUPDATES:-false}' + + webui: + image: '${REGISTRY:-git.example.com/owner}/${WEBUI_IMAGE:-executer-webui}:${WEBUI_VERSION:-${UNIFIED_VERSION:-latest}}' + pull_policy: '${IMAGE_PULL_POLICY:-missing}' + container_name: EXECUTER-WEB-00001 + build: + context: . + dockerfile: src/Infra/webui/Dockerfile + args: + UNIFIED_VERSION: ${UNIFIED_VERSION:-0.0.0.0} + restart: unless-stopped + stop_signal: SIGTERM + stop_grace_period: 30s + logging: + driver: 'local' + networks: + EXTERNAL: + expose: + - '3000' + ports: + - '${BIND_EXTERNAL_ADDRESS:-0.0.0.0}:${WEBUI_PORT:-13080}:3000' + environment: + PORT: '3000' + NODE_ENV: 'production' + ORIGIN: '${PUBLIC_SERVER_URL:-http://localhost:13080}' + volumes: + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + start_period: 20s + interval: 10s + retries: 5 + timeout: 5s + labels: + com.centurylinklabs.watchtower.enable: '${WEBUI_ENABLEAUTOMATICUPDATES:-false}' diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png new file mode 100644 index 0000000..e7400ee Binary files /dev/null and b/docs/screenshots/dashboard-light.png differ diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png new file mode 100644 index 0000000..732bb2b Binary files /dev/null and b/docs/screenshots/dashboard.png differ diff --git a/docs/screenshots/device-actions.png b/docs/screenshots/device-actions.png new file mode 100644 index 0000000..629f5ea Binary files /dev/null and b/docs/screenshots/device-actions.png differ diff --git a/docs/screenshots/device-detail.png b/docs/screenshots/device-detail.png new file mode 100644 index 0000000..788f724 Binary files /dev/null and b/docs/screenshots/device-detail.png differ diff --git a/docs/screenshots/device-hardware.png b/docs/screenshots/device-hardware.png new file mode 100644 index 0000000..4b7eecb Binary files /dev/null and b/docs/screenshots/device-hardware.png differ diff --git a/docs/screenshots/device-network.png b/docs/screenshots/device-network.png new file mode 100644 index 0000000..b4c0cc6 Binary files /dev/null and b/docs/screenshots/device-network.png differ diff --git a/docs/screenshots/devices.png b/docs/screenshots/devices.png new file mode 100644 index 0000000..519caf3 Binary files /dev/null and b/docs/screenshots/devices.png differ diff --git a/docs/screenshots/functions.png b/docs/screenshots/functions.png new file mode 100644 index 0000000..17d1fc5 Binary files /dev/null and b/docs/screenshots/functions.png differ diff --git a/docs/screenshots/groups-light.png b/docs/screenshots/groups-light.png new file mode 100644 index 0000000..2742bc1 Binary files /dev/null and b/docs/screenshots/groups-light.png differ diff --git a/docs/screenshots/groups-rule-builder.png b/docs/screenshots/groups-rule-builder.png new file mode 100644 index 0000000..374b054 Binary files /dev/null and b/docs/screenshots/groups-rule-builder.png differ diff --git a/docs/screenshots/groups-static-members.png b/docs/screenshots/groups-static-members.png new file mode 100644 index 0000000..c20fd2a Binary files /dev/null and b/docs/screenshots/groups-static-members.png differ diff --git a/docs/screenshots/groups.png b/docs/screenshots/groups.png new file mode 100644 index 0000000..9be6c7c Binary files /dev/null and b/docs/screenshots/groups.png differ diff --git a/docs/screenshots/jobs.png b/docs/screenshots/jobs.png new file mode 100644 index 0000000..2d9f40d Binary files /dev/null and b/docs/screenshots/jobs.png differ diff --git a/docs/screenshots/login.png b/docs/screenshots/login.png new file mode 100644 index 0000000..992f625 Binary files /dev/null and b/docs/screenshots/login.png differ diff --git a/docs/screenshots/script-editor.png b/docs/screenshots/script-editor.png new file mode 100644 index 0000000..6fc6935 Binary files /dev/null and b/docs/screenshots/script-editor.png differ diff --git a/docs/screenshots/script-parameters.png b/docs/screenshots/script-parameters.png new file mode 100644 index 0000000..0a96b63 Binary files /dev/null and b/docs/screenshots/script-parameters.png differ diff --git a/docs/screenshots/scripts.png b/docs/screenshots/scripts.png new file mode 100644 index 0000000..528a015 Binary files /dev/null and b/docs/screenshots/scripts.png differ diff --git a/docs/screenshots/settings-install-command.png b/docs/screenshots/settings-install-command.png new file mode 100644 index 0000000..9088a07 Binary files /dev/null and b/docs/screenshots/settings-install-command.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png new file mode 100644 index 0000000..eca4480 Binary files /dev/null and b/docs/screenshots/settings.png differ diff --git a/docs/sequences.md b/docs/sequences.md new file mode 100644 index 0000000..249e4de --- /dev/null +++ b/docs/sequences.md @@ -0,0 +1,81 @@ +# Sequence diagrams + +## Script execution + +```mermaid +sequenceDiagram + participant U as "Browser" + participant API as "Backend" + participant N as "NATS / JetStream" + participant A as "Agent" + participant PS as "System.Management.Automation" + + U->>API: "POST /api/jobs" + API->>N: "durable script command" + N->>A: "agent command.script" + A->>A: "record JobId idempotently" + A-->>N: "Ack command" + A->>PS: "Runspace + prelude + AddScript + AddParameter" + PS-->>A: "Output / Progress / Errors" + A->>N: "job output / progress" + N->>API: "consume job events" + API->>N: "browser session job event" + N-->>U: "live WebSocket event" + PS-->>A: "completion" + A->>N: "job state = Succeeded/Failed" + N->>API: "persist state" + API->>N: "browser session update" + N-->>U: "final state" +``` + +## Enrollment + +```mermaid +sequenceDiagram + participant A as "Agent" + participant API as "Backend" + participant N as "NATS" + + A->>A: "CIM stable hardware fingerprint" + A->>A: "SHA-256 deterministic ClientId" + A->>A: "Generate User NKey pair" + A->>API: "HTTPS bootstrap: token + ClientId + public NKey" + API->>API: "Validate/consume bootstrap token" + API->>API: "Issue scoped NATS user JWT" + API-->>A: "EnrollmentId + User JWT" + A->>A: "DPAPI protect private seed + JWT" + A->>A: "Clear BootstrapToken registry value" + A->>N: "WSS connect using JWT + NKey proof" + N-->>A: "authenticated" + A->>N: "presence + inventory" +``` + +## Remote shell + +```mermaid +sequenceDiagram + participant U as "Browser / xterm" + participant API as "Backend" + participant N as "NATS" + participant A as "Agent" + participant C as "ConPTY" + + U->>API: "create shell for ClientId" + API->>API: "authorize" + API->>N: "privileged shell.open command" + N->>A: "shell.open" + A->>C: "create pseudoconsole + shell" + A->>N: "shell state = open" + API->>N: "browser session state/output bridge" + N-->>U: "shell open" + U->>N: "browser session shell input" + N->>API: "input" + API->>N: "authorized agent shell.input" + N->>A: "input" + A->>C: "write input" + C-->>A: "terminal output" + A->>N: "shell output" + N->>API: "output" + API->>N: "browser shell output" + N-->>U: "live terminal output" +``` diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 0000000..69fc3e8 --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.10", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 0000000..383516c --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature" + } +} diff --git a/scripts/Build.ps1 b/scripts/Build.ps1 new file mode 100644 index 0000000..5f31e61 --- /dev/null +++ b/scripts/Build.ps1 @@ -0,0 +1,42 @@ +<# +.SYNOPSIS +Builds the full solution (and optionally the WebUI) with one unified version. + +.EXAMPLE +./scripts/Build.ps1 +./scripts/Build.ps1 -Configuration Release -IncludeWebUI +#> +[CmdletBinding()] +param( + [ValidateSet('Debug', 'Release')] + [string]$Configuration = 'Release', + [string]$Version, + [switch]$IncludeWebUI +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version + +Write-Host "Unified version: $Version" + +dotnet build (Join-Path $repoRoot 'ExecuteR.slnx') -c $Configuration --nologo "-p:UnifiedVersion=$Version" +if ($LASTEXITCODE -ne 0) { throw "dotnet build failed ($LASTEXITCODE)." } + +if ($IncludeWebUI) { + Push-Location (Join-Path $repoRoot 'src/WebUI') + try { + if (-not (Test-Path 'node_modules')) { + npm ci + if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." } + } + $env:PUBLIC_BUILD_VERSION = $Version + npm run build + if ($LASTEXITCODE -ne 0) { throw "WebUI build failed ($LASTEXITCODE)." } + } + finally { + Pop-Location + } +} + +Write-Host "Build complete ($Version)." diff --git a/scripts/Generate-Icons.ps1 b/scripts/Generate-Icons.ps1 new file mode 100644 index 0000000..7e78933 --- /dev/null +++ b/scripts/Generate-Icons.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS +Generates artifacts/icons/app.ico from assets/icon-source.png using ImageMagick. +Installs ImageMagick silently (winget) only when it is missing. Idempotent: +skips generation when the .ico is newer than the source. +#> +[CmdletBinding()] +param( + [switch]$Force +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$source = Join-Path $repoRoot 'assets/icon-source.png' +$outputDir = Join-Path $repoRoot 'artifacts/icons' +$output = Join-Path $outputDir 'app.ico' + +if (-not (Test-Path $source)) { + throw "Icon source not found: $source" +} + +if (-not $Force -and (Test-Path $output) -and + (Get-Item $output).LastWriteTimeUtc -ge (Get-Item $source).LastWriteTimeUtc) { + Write-Host "Icon already up to date: $output" + return +} + +$magick = Get-Command magick -ErrorAction SilentlyContinue +if (-not $magick) { + 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)." } + + # Refresh PATH for this session. + $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + + [Environment]::GetEnvironmentVariable('Path', 'User') + $magick = Get-Command magick -ErrorAction Stop +} + +New-Item -ItemType Directory -Force $outputDir | Out-Null +& $magick.Source $source -define icon:auto-resize=256,128,64,48,32,16 $output +if ($LASTEXITCODE -ne 0) { throw "ImageMagick icon generation failed ($LASTEXITCODE)." } + +Write-Host "Generated $output" diff --git a/scripts/Get-UnifiedVersion.ps1 b/scripts/Get-UnifiedVersion.ps1 new file mode 100644 index 0000000..2d87421 --- /dev/null +++ b/scripts/Get-UnifiedVersion.ps1 @@ -0,0 +1,21 @@ +<# +.SYNOPSIS +Computes the unified build version (yyyy.MM.dd.HHmm, UTC) exactly once per build. +Honors an explicit -Version argument or the UNIFIED_VERSION environment variable +(as set by CI) so every artifact in one pipeline shares the same version. +#> +[CmdletBinding()] +param( + [string]$Version +) + +$ErrorActionPreference = 'Stop' + +if (-not $Version) { $Version = $env:UNIFIED_VERSION } +if (-not $Version) { $Version = [DateTime]::UtcNow.ToString('yyyy.MM.dd.HHmm') } + +if ($Version -notmatch '^\d{4}\.\d{2}\.\d{2}\.\d{4}$') { + throw "Unified version '$Version' does not match yyyy.MM.dd.HHmm." +} + +$Version diff --git a/scripts/Initialize-GiteaSecrets.ps1 b/scripts/Initialize-GiteaSecrets.ps1 new file mode 100644 index 0000000..08ff79a --- /dev/null +++ b/scripts/Initialize-GiteaSecrets.ps1 @@ -0,0 +1,171 @@ +<# +.SYNOPSIS +Creates/updates the Gitea Actions repository secrets and variables that CI/CD +needs, using the Gitea REST API. Idempotent: re-running overwrites values. + +.DESCRIPTION +Secrets are read from the local .env / secrets directory (or parameters) and +pushed with: + PUT /api/v1/repos/{owner}/{repo}/actions/secrets/{name} + PUT /api/v1/repos/{owner}/{repo}/actions/variables/{name} + +Secret VALUES are never printed — only names and the resulting status. + +.EXAMPLE + $env:GITEA_URL='https://git.example.com'; $env:GITEA_API_TOKEN='...' + ./scripts/Initialize-GiteaSecrets.ps1 -Owner platform -Repository ExecuteR + +.NOTES +The token needs repository admin scope (write:repository) to manage secrets. +#> +[CmdletBinding(SupportsShouldProcess)] +param( + [string]$GiteaUrl = $env:GITEA_URL, + [string]$Token = $(if ($env:GITEA_TOKEN) { $env:GITEA_TOKEN } else { $env:GITEA_API_TOKEN }), + [string]$Owner = $env:GITEA_OWNER, + [string]$Repository = $env:GITEA_REPOSITORY, + [string]$RegistryUsername, + [string]$RegistryPassword, + # Publish to a registry other than this Gitea instance's built-in one. + # Without this switch no registry credentials are written at all — CI uses + # the token Gitea Actions injects automatically. + [switch]$ExternalRegistry, + [switch]$SkipNats +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot + +# ── Resolve context from git when not supplied ────────────────────────────── +if (-not $GiteaUrl -or -not $Owner -or -not $Repository) { + $remote = (git -C $repoRoot remote get-url origin 2>$null) + if ($remote -match '^(?https?://[^/]+)/(?[^/]+)/(?[^/]+?)(\.git)?$') { + if (-not $GiteaUrl) { $GiteaUrl = $Matches.base } + if (-not $Owner) { $Owner = $Matches.owner } + if (-not $Repository) { $Repository = $Matches.repo } + Write-Host "Derived from git remote: $GiteaUrl/$Owner/$Repository" + } +} + +if (-not $GiteaUrl) { throw 'GITEA_URL is required (or a git remote to derive it from).' } +if (-not $Token) { throw 'GITEA_TOKEN / GITEA_API_TOKEN is required.' } +if (-not $Owner) { throw 'GITEA_OWNER is required.' } +if (-not $Repository) { throw 'GITEA_REPOSITORY is required.' } + +$apiBase = "$($GiteaUrl.TrimEnd('/'))/api/v1/repos/$Owner/$Repository" +$headers = @{ Authorization = "token $Token" } + +# ── Collect values: .env first, then generated secrets, then parameters ───── +$values = @{} +$envFile = Join-Path $repoRoot '.env' +if (Test-Path $envFile) { + foreach ($line in Get-Content $envFile) { + if ($line -match '^\s*([A-Z0-9_]+)\s*=\s*(.*)$') { + $values[$Matches[1]] = $Matches[2].Trim() + } + } +} + +$natsDir = Join-Path $repoRoot 'secrets/nats' +if (-not $SkipNats -and (Test-Path $natsDir)) { + $signing = Join-Path $natsDir 'account-signing.nk' + $accountPub = Join-Path $natsDir 'account.pub' + if (Test-Path $signing) { $values['NATS_ACCOUNT_SIGNING_SEED'] = (Get-Content $signing -Raw).Trim() } + if (Test-Path $accountPub) { $values['NATS_ACCOUNT_PUBLIC_KEY'] = (Get-Content $accountPub -Raw).Trim() } +} + +# The registry credentials CI uses to push images. Default to the API token, +# which Gitea accepts as a container-registry password. +if (-not $RegistryUsername) { $RegistryUsername = if ($values['GITEA_ACTOR']) { $values['GITEA_ACTOR'] } else { $Owner } } +if (-not $RegistryPassword) { $RegistryPassword = $Token } + +$registryHost = ([Uri]$GiteaUrl).Host + +# ── Secrets (encrypted, never readable back) ──────────────────────────────── +# NOTE: Gitea reserves the GITEA_ and GITHUB_ prefixes for Actions secret +# names and rejects them with HTTP 400, so these use neutral names. +# +# Nothing here is needed for Gitea's OWN container registry: Actions injects a +# GITEA_TOKEN per run which the registry accepts as the actor's password, and +# the host is derived from the instance URL. REGISTRY_HOST/USERNAME/PASSWORD +# are written only with -ExternalRegistry, to publish somewhere else. +$secrets = @{} + +if ($ExternalRegistry) { + $secrets['REGISTRY_HOST'] = $registryHost + $secrets['REGISTRY_USERNAME'] = $RegistryUsername + $secrets['REGISTRY_PASSWORD'] = $RegistryPassword +} + +foreach ($name in @('NATS_ACCOUNT_SIGNING_SEED', 'INITIAL_ADMIN_PASSWORD', 'OIDC_CLIENT_SECRET', 'S3_SECRET_KEY')) { + if ($values[$name]) { $secrets[$name] = $values[$name] } +} + +# ── Variables (plain, readable in the UI) ─────────────────────────────────── +$variables = @{ + 'REGISTRY' = "$registryHost/$($Owner.ToLowerInvariant())" + 'SERVER_URL' = $GiteaUrl.TrimEnd('/') +} +foreach ($name in @('NATS_ACCOUNT_PUBLIC_KEY', 'NATS_OPERATOR_PUBLIC_KEY')) { + if ($values[$name]) { $variables[$name] = $values[$name] } +} + +function Set-GiteaItem { + param([string]$Kind, [string]$Name, [string]$Value) + + $uri = "$apiBase/actions/$Kind/$([uri]::EscapeDataString($Name))" + + # The two endpoints disagree on the payload field: secrets take "data", + # variables take "value". Sending the wrong one returns HTTP 422. + $body = if ($Kind -eq 'secrets') { + @{ data = $Value } | ConvertTo-Json -Compress + } + else { + @{ value = $Value } | ConvertTo-Json -Compress + } + + if (-not $PSCmdlet.ShouldProcess("$Kind/$Name", 'PUT')) { return } + + try { + Invoke-RestMethod -Method Put -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null + Write-Host (" {0,-36} set" -f $Name) + } + catch { + $status = $_.Exception.Response.StatusCode.value__ + if ($status -eq 404 -and $Kind -eq 'variables') { + # Older Gitea: variables endpoint may need POST to create. + try { + Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType 'application/json' -Body $body | Out-Null + Write-Host (" {0,-36} created" -f $Name) + return + } + catch { } + } + + Write-Warning (" {0,-36} FAILED (HTTP {1})" -f $Name, $status) + } +} + +Write-Host "Configuring Actions secrets on $Owner/$Repository" +if (-not $ExternalRegistry) { + Write-Host ' (built-in Gitea registry: no registry credentials needed)' +} + +foreach ($entry in $secrets.GetEnumerator() | Sort-Object Name) { + if ([string]::IsNullOrWhiteSpace($entry.Value)) { + Write-Host (" {0,-36} skipped (no value)" -f $entry.Name) + continue + } + + Set-GiteaItem -Kind 'secrets' -Name $entry.Name -Value $entry.Value +} + +Write-Host "Configuring Actions variables" +foreach ($entry in $variables.GetEnumerator() | Sort-Object Name) { + if ([string]::IsNullOrWhiteSpace($entry.Value)) { continue } + Set-GiteaItem -Kind 'variables' -Name $entry.Name -Value $entry.Value +} + +Write-Host '' +Write-Host 'Done. CI can now log in to the registry and publish images.' +Write-Host 'No secret values were printed.' diff --git a/scripts/Initialize-Repository.ps1 b/scripts/Initialize-Repository.ps1 new file mode 100644 index 0000000..0791f34 --- /dev/null +++ b/scripts/Initialize-Repository.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS +One-time developer setup: verifies prerequisites, restores dependencies and +generates local secrets when missing. +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot + +Write-Host '── Checking prerequisites ──' +$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue +if (-not $dotnet) { throw '.NET SDK 10.x is required (https://dotnet.microsoft.com).' } +Write-Host "dotnet $(dotnet --version)" + +$node = Get-Command node -ErrorAction SilentlyContinue +if (-not $node) { throw 'Node.js LTS is required (https://nodejs.org).' } +Write-Host "node $(node --version)" + +Write-Host '── Restoring .NET packages ──' +dotnet restore (Join-Path $repoRoot 'ExecuteR.slnx') +if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed ($LASTEXITCODE)." } + +Write-Host '── Installing WebUI packages ──' +Push-Location (Join-Path $repoRoot 'src/WebUI') +try { + npm ci + if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." } +} +finally { + Pop-Location +} + +if (-not (Test-Path (Join-Path $repoRoot '.env'))) { + Write-Host '── Generating local secrets ──' + & (Join-Path $PSScriptRoot 'New-LocalSecrets.ps1') +} + +Write-Host '' +Write-Host 'Repository initialized. Next steps:' +Write-Host ' docker compose up -d # NATS + backend + webui' +Write-Host ' ./scripts/Build.ps1 # build everything' +Write-Host ' ./scripts/Test.ps1 # run tests' diff --git a/scripts/New-LocalSecrets.ps1 b/scripts/New-LocalSecrets.ps1 new file mode 100644 index 0000000..7b92880 --- /dev/null +++ b/scripts/New-LocalSecrets.ps1 @@ -0,0 +1,61 @@ +<# +.SYNOPSIS +Generates strong local development secrets: +- .env (from .env.example) with a random initial admin password +- Real Ed25519 NATS operator/account/signing NKeys and JWTs via the backend's + nats-auth CLI (NATS.NKeys / NATS.Jwt — no fake seeds) +- secrets/nats/resolver.conf for the NATS container + +Idempotent: existing secrets are kept unless -Force is specified. +#> +[CmdletBinding()] +param( + [switch]$Force +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$envFile = Join-Path $repoRoot '.env' +$envExample = Join-Path $repoRoot '.env.example' +$natsSecretsDir = Join-Path $repoRoot 'secrets/nats' + +if ((Test-Path $envFile) -and (Test-Path (Join-Path $natsSecretsDir 'resolver.conf')) -and -not $Force) { + Write-Host 'Secrets already exist. Use -Force to regenerate.' + return +} + +New-Item -ItemType Directory -Force $natsSecretsDir | Out-Null + +# ── NATS operator/account keys via backend CLI ──────────────────────────── +Write-Host 'Generating NATS operator/account keys and resolver preload...' +dotnet run --project (Join-Path $repoRoot 'src/Backend') -- nats-auth init --output $natsSecretsDir +if ($LASTEXITCODE -ne 0) { throw "nats-auth init failed ($LASTEXITCODE)." } + +$accountSigningSeed = (Get-Content (Join-Path $natsSecretsDir 'account-signing.nk') -Raw).Trim() +$accountPublic = (Get-Content (Join-Path $natsSecretsDir 'account.pub') -Raw).Trim() +$operatorPublic = (Get-Content (Join-Path $natsSecretsDir 'operator.pub') -Raw).Trim() + +# ── .env ────────────────────────────────────────────────────────────────── +function New-RandomPassword { + param([int]$Length = 24) + $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#%^*-_=+' + $bytes = [byte[]]::new($Length) + [System.Security.Cryptography.RandomNumberGenerator]::Fill($bytes) + -join ($bytes | ForEach-Object { $alphabet[$_ % $alphabet.Length] }) +} + +$adminPassword = New-RandomPassword + +$content = Get-Content $envExample +$content = $content -replace '^INITIAL_ADMIN_PASSWORD=.*$', "INITIAL_ADMIN_PASSWORD=$adminPassword" +$content = $content -replace '^NATS_ACCOUNT_SIGNING_SEED=.*$', "NATS_ACCOUNT_SIGNING_SEED=$accountSigningSeed" +$content = $content -replace '^NATS_ACCOUNT_PUBLIC_KEY=.*$', "NATS_ACCOUNT_PUBLIC_KEY=$accountPublic" +$content = $content -replace '^NATS_OPERATOR_PUBLIC_KEY=.*$', "NATS_OPERATOR_PUBLIC_KEY=$operatorPublic" +$content = $content -replace '^PUBLIC_SERVER_URL=.*$', 'PUBLIC_SERVER_URL=http://localhost:8080' +$content = $content -replace '^TRUSTED_HOSTS=.*$', 'TRUSTED_HOSTS=localhost' +Set-Content -Path $envFile -Value $content -Encoding utf8NoBOM + +Write-Host '' +Write-Host "Wrote $envFile" +Write-Host "Initial admin: admin / $adminPassword" +Write-Host 'NATS material written below secrets/nats (seeds are SECRET).' diff --git a/scripts/Package-Agent.ps1 b/scripts/Package-Agent.ps1 new file mode 100644 index 0000000..3aba249 --- /dev/null +++ b/scripts/Package-Agent.ps1 @@ -0,0 +1,75 @@ +<# +.SYNOPSIS +Publishes the self-contained single-file Agent executable, zips it, and +builds the MSI when the WiX project is present. + +.EXAMPLE +./scripts/Package-Agent.ps1 +./scripts/Package-Agent.ps1 -Version 2026.08.06.2151 -SkipMsi +#> +[CmdletBinding()] +param( + [string]$Version, + [switch]$SkipMsi, + [switch]$SkipIcon +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version +$artifacts = Join-Path $repoRoot 'artifacts' +$publishDir = Join-Path $artifacts "agent/$Version" + +Write-Host "Packaging Agent $Version" + +if (-not $SkipIcon) { + & (Join-Path $PSScriptRoot 'Generate-Icons.ps1') +} + +dotnet publish (Join-Path $repoRoot 'src/Agent/Agent.csproj') ` + -c Release ` + -r win-x64 ` + --self-contained true ` + -p:PublishSingleFile=true ` + -p:IncludeNativeLibrariesForSelfExtract=true ` + -p:EnableCompressionInSingleFile=true ` + "-p:UnifiedVersion=$Version" ` + -o $publishDir +if ($LASTEXITCODE -ne 0) { throw "Agent publish failed ($LASTEXITCODE)." } + +$zipPath = Join-Path $artifacts "Agent-$Version-win-x64.zip" +if (Test-Path $zipPath) { Remove-Item $zipPath -Force } +Compress-Archive -Path (Join-Path $publishDir '*') -DestinationPath $zipPath +Write-Host "Created $zipPath" + +$wixProject = Join-Path $repoRoot 'src/Installer/Agent.Installer.wixproj' +if (-not $SkipMsi -and (Test-Path $wixProject)) { + # Deterministic MSI ProductVersion transform (see BuildVersion.ToMsiProductVersion): + # yyyy.MM.dd.HHmm -> (yyyy-2000).(MM).((dd-1)*1440 + HH*60 + mm) + $parts = $Version.Split('.') + $hhmm = [int]$parts[3] + $msiVersion = '{0}.{1}.{2}' -f ([int]$parts[0] - 2000), [int]$parts[1], + ((([int]$parts[2] - 1) * 1440) + ([math]::Floor($hhmm / 100) * 60) + ($hhmm % 100)) + Write-Host "MSI ProductVersion: $msiVersion" + + dotnet build $wixProject -c Release --nologo ` + "-p:UnifiedVersion=$Version" ` + "-p:MsiProductVersion=$msiVersion" ` + "-p:AgentPublishDir=$publishDir" + if ($LASTEXITCODE -ne 0) { throw "MSI build failed ($LASTEXITCODE)." } + + $msi = Get-ChildItem (Join-Path $repoRoot 'src/Installer/bin/Release') -Filter '*.msi' -Recurse | + Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 + if ($msi) { + $msiTarget = Join-Path $artifacts "Agent-$Version.msi" + Copy-Item $msi.FullName $msiTarget -Force + Write-Host "Created $msiTarget" + } +} + +# Checksums for release attachment. +$checksums = Join-Path $artifacts "Agent-$Version-checksums.txt" +Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Agent-$Version*" -and $_.Extension -ne '.txt' } | ForEach-Object { + "{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name +} | Set-Content $checksums -Encoding utf8NoBOM +Write-Host "Created $checksums" diff --git a/scripts/Publish-Release.ps1 b/scripts/Publish-Release.ps1 new file mode 100644 index 0000000..5dd07e3 --- /dev/null +++ b/scripts/Publish-Release.ps1 @@ -0,0 +1,66 @@ +<# +.SYNOPSIS +Creates (or reuses) a Gitea release for the unified version and uploads the +agent artifacts from ./artifacts. No-ops with a clear message when GITEA_TOKEN +or GITEA_URL are absent (local runs). Never prints the token. + +.NOTES +Uses the Gitea REST API: + POST /api/v1/repos/{owner}/{repo}/releases + POST /api/v1/repos/{owner}/{repo}/releases/{id}/assets +#> +[CmdletBinding()] +param( + [string]$Version +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version + +$giteaUrl = $env:GITEA_URL +$token = $env:GITEA_TOKEN +$owner = $env:GITEA_OWNER +$repo = $env:GITEA_REPOSITORY + +if (-not $giteaUrl -or -not $token -or -not $owner -or -not $repo) { + Write-Host 'GITEA_URL/TOKEN/OWNER/REPOSITORY not all set; skipping release publish.' + return +} + +$headers = @{ Authorization = "token $token" } +$apiBase = "$($giteaUrl.TrimEnd('/'))/api/v1/repos/$owner/$repo" +$tag = "v$Version" + +Write-Host "Creating release $tag on $owner/$repo" +$body = @{ + tag_name = $tag + target_commitish = 'main' + name = "ExecuteR $Version" + body = "Automated release for unified version $Version." + draft = $false + prerelease = $false +} | ConvertTo-Json + +try { + $release = Invoke-RestMethod -Method Post -Uri "$apiBase/releases" -Headers $headers ` + -ContentType 'application/json' -Body $body +} +catch { + # Release for this tag may already exist; fetch it. + $release = Invoke-RestMethod -Method Get -Uri "$apiBase/releases/tags/$tag" -Headers $headers +} + +$artifacts = Join-Path $repoRoot 'artifacts' +$assets = Get-ChildItem $artifacts -File | Where-Object { $_.Name -like "Agent-$Version*" } +if (-not $assets) { + throw "No artifacts matching Agent-$Version* under $artifacts." +} + +foreach ($asset in $assets) { + Write-Host "Uploading $($asset.Name)" + $uri = "$apiBase/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($asset.Name))" + Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -InFile $asset.FullName -ContentType 'application/octet-stream' | Out-Null +} + +Write-Host "Release $tag published with $($assets.Count) asset(s)." diff --git a/scripts/Test.ps1 b/scripts/Test.ps1 new file mode 100644 index 0000000..2de817f --- /dev/null +++ b/scripts/Test.ps1 @@ -0,0 +1,53 @@ +<# +.SYNOPSIS +Runs unit tests (and optionally the Svelte check + integration tests). + +.EXAMPLE +./scripts/Test.ps1 +./scripts/Test.ps1 -IncludeIntegration -IncludeWebUI +#> +[CmdletBinding()] +param( + [ValidateSet('Debug', 'Release')] + [string]$Configuration = 'Release', + [string]$Version, + [switch]$IncludeIntegration, + [switch]$IncludeWebUI +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$Version = & (Join-Path $PSScriptRoot 'Get-UnifiedVersion.ps1') -Version $Version + +$unitProjects = @( + 'tests/Shared.Tests', + 'tests/Agent.Tests', + 'tests/Backend.Tests' +) + +foreach ($project in $unitProjects) { + dotnet test (Join-Path $repoRoot $project) -c $Configuration --nologo "-p:UnifiedVersion=$Version" + if ($LASTEXITCODE -ne 0) { throw "Tests failed in $project ($LASTEXITCODE)." } +} + +if ($IncludeIntegration) { + dotnet test (Join-Path $repoRoot 'tests/Integration.Tests') -c $Configuration --nologo "-p:UnifiedVersion=$Version" + if ($LASTEXITCODE -ne 0) { throw "Integration tests failed ($LASTEXITCODE)." } +} + +if ($IncludeWebUI) { + Push-Location (Join-Path $repoRoot 'src/WebUI') + try { + if (-not (Test-Path 'node_modules')) { + npm ci + if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." } + } + npm run check + if ($LASTEXITCODE -ne 0) { throw "svelte-check failed ($LASTEXITCODE)." } + } + finally { + Pop-Location + } +} + +Write-Host 'All requested test suites passed.' diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100755 index 0000000..b299c6a --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,242 @@ +#!/usr/bin/env bash +#============================================================================= +# ExecuteR - server stack deployment +#============================================================================= +# +# Bootstrap straight from the repository (no clone required): +# +# curl -fsSL https://git.example.com/owner/ExecuteR/raw/branch/main/scripts/deploy.sh | bash +# curl -fsSL https://.../deploy.sh | bash -s -- --with-proxy --host control.example.com +# +# Or from a checkout: +# +# ./scripts/deploy.sh +# ./scripts/deploy.sh --with-proxy --host control.example.com +# +# Pulls the published images from the Gitea container registry and falls back +# to building from source when a pull is not possible. The in-stack reverse +# proxy is OPT-IN (--with-proxy); by default the stack assumes you already run +# an edge proxy. +#============================================================================= +set -Eeuo pipefail + +# ── Defaults (override with flags or environment) ─────────────────────────── +REPO_RAW_URL="${REPO_RAW_URL:-https://git.example.com/owner/ExecuteR/raw/branch/main}" +INSTALL_DIR="${INSTALL_DIR:-/opt/executer}" +WITH_PROXY=0 +PUBLIC_HOSTNAME="${PROXY_PUBLIC_HOSTNAME:-}" +FORCE_BUILD=0 +NO_PULL=0 +NO_START=0 + +log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; } +warn() { printf '\033[1;33mwarn:\033[0m %s\n' "$*" >&2; } +die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } + +usage() { + # Print the leading comment banner, stopping at the first code line. + awk 'NR>1 { if (/^#/) { sub(/^# ?/, ""); print } else { exit } }' "$0" + cat <<'USAGE' + +Options: + --with-proxy Also run the in-stack nginx reverse proxy (opt-in) + --host Public hostname for the proxy site config + --dir Install directory (default /opt/executer) + --repo-url Raw file base URL used when bootstrapping via curl + --build Always build from source, never pull + --no-pull Do not pull; use local images or build + --no-start Prepare files and images but do not start the stack + -h, --help Show this help +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --with-proxy) WITH_PROXY=1; shift ;; + --host) PUBLIC_HOSTNAME="${2:?--host needs a value}"; shift 2 ;; + --dir) INSTALL_DIR="${2:?--dir needs a value}"; shift 2 ;; + --repo-url) REPO_RAW_URL="${2:?--repo-url needs a value}"; shift 2 ;; + --build) FORCE_BUILD=1; shift ;; + --no-pull) NO_PULL=1; shift ;; + --no-start) NO_START=1; shift ;; + -h|--help) usage; exit 0 ;; + *) die "unknown option: $1 (try --help)" ;; + esac +done + +# ── Prerequisites ─────────────────────────────────────────────────────────── +command -v docker >/dev/null 2>&1 || die "docker is required" +docker compose version >/dev/null 2>&1 || die "docker compose v2 is required" +command -v curl >/dev/null 2>&1 || die "curl is required" +docker info >/dev/null 2>&1 || die "cannot talk to the Docker daemon (need root or docker group?)" + +# ── Locate or fetch the stack files ───────────────────────────────────────── +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || echo '')" +REPO_ROOT="" +if [[ -n "$SCRIPT_DIR" && -f "$SCRIPT_DIR/../docker-compose.yml" ]]; then + REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +fi + +if [[ -n "$REPO_ROOT" ]]; then + log "Deploying from checkout: $REPO_ROOT" + STACK_DIR="$REPO_ROOT" +else + log "Bootstrapping into $INSTALL_DIR from $REPO_RAW_URL" + mkdir -p "$INSTALL_DIR" + STACK_DIR="$INSTALL_DIR" + + fetch() { + local rel="$1" dest="$STACK_DIR/$1" + mkdir -p "$(dirname "$dest")" + if ! curl -fsSL "$REPO_RAW_URL/$rel" -o "$dest"; then + warn "could not fetch $rel" + return 1 + fi + } + + fetch docker-compose.yml || die "docker-compose.yml is required" + fetch .env.example || die ".env.example is required" + fetch src/Infra/nats/nats.conf || die "nats.conf is required" + [[ $WITH_PROXY -eq 1 ]] && { fetch docker-compose.proxy.yml; fetch src/Infra/nginx/executer.conf; } + # Optional; only needed when building from source. + fetch docker-compose.dev.yml || true +fi + +cd "$STACK_DIR" + +# ── .env ──────────────────────────────────────────────────────────────────── +if [[ ! -f .env ]]; then + log "Creating .env from .env.example" + cp .env.example .env + + # Generate the initial admin password so the stack is usable immediately. + ADMIN_PASSWORD="$(openssl rand -base64 24 2>/dev/null | tr -d '\n/+=' | cut -c1-24)" + [[ -n "$ADMIN_PASSWORD" ]] && sed -i "s|^INITIAL_ADMIN_PASSWORD=.*|INITIAL_ADMIN_PASSWORD=$ADMIN_PASSWORD|" .env + GENERATED_ADMIN_PASSWORD="$ADMIN_PASSWORD" +fi + +# shellcheck disable=SC1091 +set -a; source .env; set +a +STACK_NAME="${STACK_NAME:-stk-executer-00001}" +STACK_BINDMOUNTROOT="${STACK_BINDMOUNTROOT:-/mnt/data/docker/stacks}" + +# ── Bind-mount directories ────────────────────────────────────────────────── +log "Preparing data directories under $STACK_BINDMOUNTROOT/$STACK_NAME" +mkdir -p \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/NATS/JetStream" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/NATS/Resolver" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/API/Data/logs" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/API/Data/agent" +[[ $WITH_PROXY -eq 1 ]] && mkdir -p \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Config" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Certs" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Logs" \ + "$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Acme" + +# ── Compose file selection ────────────────────────────────────────────────── +COMPOSE_FILES=(-f docker-compose.yml) +if [[ $WITH_PROXY -eq 1 ]]; then + [[ -f docker-compose.proxy.yml ]] || die "--with-proxy needs docker-compose.proxy.yml" + COMPOSE_FILES+=(-f docker-compose.proxy.yml) +fi +compose() { docker compose "${COMPOSE_FILES[@]}" "$@"; } + +# ── Images: pull published, fall back to building ─────────────────────────── +BUILD_NEEDED=$FORCE_BUILD +if [[ $FORCE_BUILD -eq 0 && $NO_PULL -eq 0 ]]; then + # Packages published by a private repo need authentication. For Gitea's + # built-in registry any account token works as the password. + if [[ -n "${REGISTRY_USERNAME:-}" && -n "${REGISTRY_TOKEN:-}" && -n "${REGISTRY:-}" ]]; then + REGISTRY_LOGIN_HOST="${REGISTRY%%/*}" + log "Logging in to $REGISTRY_LOGIN_HOST as $REGISTRY_USERNAME" + if ! printf '%s' "$REGISTRY_TOKEN" \ + | docker login "$REGISTRY_LOGIN_HOST" -u "$REGISTRY_USERNAME" --password-stdin >/dev/null 2>&1; then + warn "registry login failed — continuing (public images may still pull)" + fi + fi + + log "Pulling images from ${REGISTRY:-}" + if ! compose pull --quiet 2>/dev/null; then + warn "pull failed or images unavailable — falling back to building from source" + BUILD_NEEDED=1 + fi +fi + +if [[ $BUILD_NEEDED -eq 1 ]]; then + [[ -f src/Infra/backend/Dockerfile ]] \ + || die "cannot build: source not present. Clone the repo, or make the registry reachable." + log "Building images from source" + UNIFIED_VERSION="${UNIFIED_VERSION:-$(date -u +%Y.%m.%d.%H%M)}" compose build +fi + +# ── NATS operator/account keys (generated by the backend image itself) ────── +if [[ ! -f secrets/nats/resolver.conf ]]; then + log "Generating NATS operator/account keys" + mkdir -p secrets/nats + BACKEND_IMAGE_REF="$(compose config --images 2>/dev/null | grep -E 'backend|executer-backend' | head -1 || true)" + [[ -n "$BACKEND_IMAGE_REF" ]] || die "could not resolve the backend image reference" + + docker run --rm -v "$PWD/secrets/nats:/out" "$BACKEND_IMAGE_REF" \ + nats-auth init --output /out \ + || die "NATS key generation failed" + + SIGNING_SEED="$(tr -d '\r\n' < secrets/nats/account-signing.nk)" + ACCOUNT_PUB="$(tr -d '\r\n' < secrets/nats/account.pub)" + OPERATOR_PUB="$(tr -d '\r\n' < secrets/nats/operator.pub)" + sed -i "s|^NATS_ACCOUNT_SIGNING_SEED=.*|NATS_ACCOUNT_SIGNING_SEED=$SIGNING_SEED|" .env + sed -i "s|^NATS_ACCOUNT_PUBLIC_KEY=.*|NATS_ACCOUNT_PUBLIC_KEY=$ACCOUNT_PUB|" .env + sed -i "s|^NATS_OPERATOR_PUBLIC_KEY=.*|NATS_OPERATOR_PUBLIC_KEY=$OPERATOR_PUB|" .env + chmod 600 secrets/nats/*.nk 2>/dev/null || true +fi + +# ── Proxy site config ─────────────────────────────────────────────────────── +if [[ $WITH_PROXY -eq 1 ]]; then + PROXY_CONF="$STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Config/executer.conf" + if [[ ! -f "$PROXY_CONF" ]]; then + [[ -f src/Infra/nginx/executer.conf ]] || die "src/Infra/nginx/executer.conf not found" + [[ -n "$PUBLIC_HOSTNAME" ]] || die "--host is required with --with-proxy" + log "Writing proxy site config for $PUBLIC_HOSTNAME" + + # In-stack proxy reaches services by compose service name, not host IP. + sed -e "s|control\.example\.com|$PUBLIC_HOSTNAME|g" \ + -e "s|server 10\.0\.0\.10:13080;|server webui:3000;|" \ + -e "s|server 10\.0\.0\.10:19080;|server backend:8080;|" \ + -e "s|server 10\.0\.0\.10:19222;|server nats:9222;|" \ + -e "s|/etc/nginx/ssl/$PUBLIC_HOSTNAME/fullchain.cer|/etc/nginx/ssl/fullchain.pem|" \ + -e "s|/etc/nginx/ssl/$PUBLIC_HOSTNAME/private.key|/etc/nginx/ssl/private.key|" \ + src/Infra/nginx/executer.conf > "$PROXY_CONF" + + warn "Place TLS files at $STACK_BINDMOUNTROOT/$STACK_NAME/Proxy/Certs/{fullchain.pem,private.key}" + fi +fi + +# ── Start ─────────────────────────────────────────────────────────────────── +if [[ $NO_START -eq 1 ]]; then + log "Prepared (not started, --no-start)." + exit 0 +fi + +log "Starting the stack" +compose up -d --remove-orphans + +log "Waiting for the backend to report healthy" +for _ in $(seq 1 60); do + if curl -fsS "http://127.0.0.1:${BACKEND_PORT:-19080}/api/health" >/dev/null 2>&1; then + break + fi + sleep 2 +done + +echo +compose ps +echo +log "ExecuteR is up." +echo " WebUI: http://:${WEBUI_PORT:-13080}" +echo " API: http://:${BACKEND_PORT:-19080}/api/health" +echo " NATS WS: ws://:${NATS_WS_PORT:-19222}" +[[ $WITH_PROXY -eq 1 ]] && echo " Proxy: https://${PUBLIC_HOSTNAME}:${PROXY_HTTPS_PORT:-18443}" +if [[ -n "${GENERATED_ADMIN_PASSWORD:-}" ]]; then + echo + echo " Initial admin: ${INITIAL_ADMIN_USERNAME:-admin} / ${GENERATED_ADMIN_PASSWORD}" + echo " (also stored in .env — change it after first sign-in)" +fi diff --git a/secrets/README.md b/secrets/README.md new file mode 100644 index 0000000..676c331 --- /dev/null +++ b/secrets/README.md @@ -0,0 +1,43 @@ +# secrets/ + +Generated secret material lives here and is **git-ignored** (only this +README is committed). + +Generate development secrets: + +```powershell +./scripts/New-LocalSecrets.ps1 +``` + +This produces: + +| File | Purpose | +|------|---------| +| `../.env` | Compose environment (initial admin password, NATS signing seed, …) | +| `nats/operator.nk` | NATS operator seed — SECRET | +| `nats/account.nk` | NATS application account seed — SECRET | +| `nats/account-signing.nk` | Account signing seed used by the backend to issue user JWTs — SECRET | +| `nats/sys-account.nk` / `nats/sys-user.nk` | System account/user seeds — SECRET | +| `nats/resolver.conf` | Operator JWT + account preload mounted into the NATS container | + +## How the NATS keys are generated + +Keys are real Ed25519 NKeys generated via the backend's `nats-auth` CLI +(`dotnet run --project src/Backend -- nats-auth init`), which uses the +official NATS.NKeys/NATS.Jwt libraries — the same code path the backend +uses at runtime to issue agent and browser user JWTs. If you prefer +`nsc`, an equivalent manual flow is documented in the root README. + +## Required secrets (production) + +- `INITIAL_ADMIN_PASSWORD` — first-boot local admin password +- `NATS_OPERATOR_SEED` — operator identity (kept offline after setup) +- `NATS_ACCOUNT_SEED` — application account identity +- `NATS_ACCOUNT_SIGNING_SEED` — given to the backend for user JWT issuance +- `OIDC_CLIENT_SECRET` — only when OIDC is enabled +- `GITEA_TOKEN` — CI release/push automation +- `CONTAINER_REGISTRY_PASSWORD` — if different from the Gitea token +- `CODE_SIGNING_CERT_PASSWORD` — optional release signing + +Never log or commit any of these. Rotate by re-running generation and +restarting the affected services. diff --git a/src/Agent/Agent.csproj b/src/Agent/Agent.csproj new file mode 100644 index 0000000..2a8f92d --- /dev/null +++ b/src/Agent/Agent.csproj @@ -0,0 +1,59 @@ + + + + Exe + net10.0-windows + Agent + Agent + win-x64 + + true + + en + + false + + $(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Agent/Commands/AgentCli.cs b/src/Agent/Commands/AgentCli.cs new file mode 100644 index 0000000..7233847 --- /dev/null +++ b/src/Agent/Commands/AgentCli.cs @@ -0,0 +1,108 @@ +using Agent.Service; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting.WindowsServices; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Versioning; + +namespace Agent.Commands; + +/// +/// Entry-point command dispatcher. One binary supports foreground operation, +/// Windows service operation (no argument, launched by SCM), and idempotent +/// service lifecycle commands. +/// +public static class AgentCli +{ + public static async Task RunAsync(string[] args) + { + var command = args.Length > 0 ? args[0].Trim().ToLowerInvariant() : null; + + try + { + switch (command) + { + case null when WindowsServiceHelpers.IsWindowsService(): + await AgentHost.Build(runAsService: true).RunAsync(); + return 0; + + case null: + PrintUsage(); + return 1; + + case "foreground": + await AgentHost.Build(runAsService: false).RunAsync(); + return 0; + + case "version": + Console.WriteLine(BuildVersion.Resolve(typeof(AgentCli).Assembly)); + return 0; + + case "install": + return ServiceLifecycle.Install(); + + case "remove": + return ServiceLifecycle.Remove(); + + case "start": + return ServiceLifecycle.Start(); + + case "stop": + return ServiceLifecycle.Stop(); + + case "initialize": + var installResult = ServiceLifecycle.Install(); + return installResult != 0 ? installResult : ServiceLifecycle.Start(); + + case "status": + return ServiceLifecycle.Status(); + + // Hidden: invoked by the MSI during explicit full uninstall + // (never during upgrade) to remove credentials and runtime state. + case "purge-credentials": + return PurgeCredentials(); + + default: + Console.Error.WriteLine($"Unknown command '{command}'."); + PrintUsage(); + return 1; + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"error: {ex.Message}"); + return 2; + } + } + + private static int PurgeCredentials() + { + var runtimeState = new Storage.RuntimeStateStore(new Configuration.WindowsRegistryStore()); + runtimeState.Purge(); + + var dataDirectory = Branding.AgentProgramDataDirectory; + if (Directory.Exists(dataDirectory)) + { + Directory.Delete(dataDirectory, recursive: true); + } + + Console.WriteLine("Runtime credentials and state removed."); + return 0; + } + + private static void PrintUsage() + { + Console.WriteLine($"{Branding.AgentServiceDisplayName} {BuildVersion.Resolve(typeof(AgentCli).Assembly)}"); + Console.WriteLine(); + Console.WriteLine("Usage: Agent.exe "); + Console.WriteLine(); + Console.WriteLine("Commands:"); + Console.WriteLine(" foreground Run interactively with console logging"); + Console.WriteLine(" install Create/update the Windows service registration"); + Console.WriteLine(" remove Stop and remove the Windows service"); + Console.WriteLine(" start Start the installed service"); + Console.WriteLine(" stop Stop the service"); + Console.WriteLine(" initialize install + start"); + Console.WriteLine(" status Show service and enrollment state"); + Console.WriteLine(" version Print the build version"); + } +} diff --git a/src/Agent/Commands/CommandProcessor.cs b/src/Agent/Commands/CommandProcessor.cs new file mode 100644 index 0000000..5b76bd8 --- /dev/null +++ b/src/Agent/Commands/CommandProcessor.cs @@ -0,0 +1,196 @@ +using Agent.Configuration; +using Agent.Files; +using Agent.Inventory; +using Agent.Messaging; +using Agent.PowerShell; +using Agent.Storage; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; +using NATS.Client.JetStream; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Nats; + +namespace Agent.Commands; + +/// +/// Consumes the agent's durable JetStream command feed with explicit acks. +/// A script command is acknowledged only after the job id has been durably +/// recorded, and duplicates are acknowledged without re-execution. +/// +public sealed class CommandProcessor( + NatsConnection connection, + AgentPublisher publisher, + InventoryPublisher inventory, + PowerShellJobHandler jobHandler, + FileDownloadHandler fileHandler, + JobHistoryStore jobHistory, + AgentConfiguration configuration, + ILogger logger) +{ + public async Task RunAsync(CancellationToken cancellationToken) + { + var js = new NatsJSContext(connection); + var consumerName = JetStreamDefaults.AgentCommandConsumerName(publisher.ClientId); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + var consumer = await js.GetConsumerAsync( + JetStreamDefaults.CommandStreamName, consumerName, cancellationToken); + + logger.LogInformation("Command consumer {Consumer} bound", consumerName); + + // The agent is now genuinely ready for jobs (connected AND + // consuming commands) — announce it so the backend can fire + // on-agent-ready triggers. + await publisher.PublishAsync( + NatsSubjects.AgentEvent(publisher.ClientId), + MessageTypes.AgentEvent, + new AgentEventPayload( + publisher.ClientId, AgentEventKinds.Ready, "command consumer bound", DateTimeOffset.UtcNow), + cancellationToken: cancellationToken); + + await foreach (var message in consumer.ConsumeAsync(cancellationToken: cancellationToken)) + { + await HandleMessageAsync(message, cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + logger.LogWarning(ex, + "Command consumer unavailable ({Message}); retrying in 15s", ex.Message); + try + { + await Task.Delay(TimeSpan.FromSeconds(15), cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + } + } + } + + private async Task HandleMessageAsync(INatsJSMsg message, CancellationToken cancellationToken) + { + MessageEnvelope? envelope = null; + try + { + envelope = message.Data is { Length: > 0 } ? MessageEnvelope.FromUtf8Bytes(message.Data) : null; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Malformed command envelope on {Subject}", message.Subject); + } + + if (envelope is null) + { + await message.AckTerminateAsync(cancellationToken: cancellationToken); + return; + } + + switch (envelope.MessageType) + { + case MessageTypes.CommandInventory: + await message.AckAsync(cancellationToken: cancellationToken); + await inventory.TriggerAsync("command", cancellationToken); + break; + + case MessageTypes.CommandScript: + await HandleScriptCommandAsync(envelope, message, cancellationToken); + break; + + case MessageTypes.CommandFileDownload: + await HandleFileCommandAsync(envelope, message, cancellationToken); + break; + + default: + logger.LogWarning("Unknown command type {MessageType}; terminating delivery", envelope.MessageType); + await message.AckTerminateAsync(cancellationToken: cancellationToken); + break; + } + } + + private async Task HandleScriptCommandAsync( + MessageEnvelope envelope, INatsJSMsg message, CancellationToken cancellationToken) + { + var command = envelope.GetPayload(); + if (command is null || command.JobId == Guid.Empty) + { + await message.AckTerminateAsync(cancellationToken: cancellationToken); + return; + } + + if (!configuration.AllowScriptExecution.Value) + { + logger.LogWarning("Script command {JobId} rejected: script execution disabled by policy", command.JobId); + await message.AckAsync(cancellationToken: cancellationToken); + await publisher.PublishAsync( + NatsSubjects.JobState(command.JobId), + MessageTypes.JobState, + new JobStatePayload( + command.JobId, publisher.ClientId, JobState.Failed, ExitCode: null, + DateTimeOffset.UtcNow, "Script execution is disabled by policy on this device."), + new EndpointRef(EndpointKinds.Job, command.JobId.ToString("D")), + envelope.CorrelationId, + envelope.MessageId, + cancellationToken); + return; + } + + // Idempotency: record durably BEFORE ack; duplicates ack and skip. + if (!jobHistory.TryRecordAccepted(command.JobId)) + { + logger.LogInformation("Duplicate delivery of job {JobId}; acknowledged without re-execution", command.JobId); + await message.AckAsync(cancellationToken: cancellationToken); + return; + } + + await message.AckAsync(cancellationToken: cancellationToken); + logger.LogInformation("Job {JobId} accepted ({ScriptName})", command.JobId, command.ScriptName); + + // Execute in the background so the consumer loop keeps flowing. + _ = Task.Run( + () => jobHandler.RunJobAsync(command, envelope.CorrelationId, envelope.MessageId, cancellationToken), + cancellationToken); + } + + private async Task HandleFileCommandAsync( + MessageEnvelope envelope, INatsJSMsg message, CancellationToken cancellationToken) + { + var command = envelope.GetPayload(); + if (command is null || command.JobId == Guid.Empty || string.IsNullOrWhiteSpace(command.Url)) + { + await message.AckTerminateAsync(cancellationToken: cancellationToken); + return; + } + + if (!jobHistory.TryRecordAccepted(command.JobId)) + { + await message.AckAsync(cancellationToken: cancellationToken); + return; + } + + await message.AckAsync(cancellationToken: cancellationToken); + logger.LogInformation("File download job {JobId} accepted", command.JobId); + + _ = Task.Run(async () => + { + try + { + await fileHandler.RunAsync(command, envelope.CorrelationId, envelope.MessageId, cancellationToken); + } + finally + { + jobHistory.MarkCompleted(command.JobId, "FileDownload"); + } + }, cancellationToken); + } +} + diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs new file mode 100644 index 0000000..30da32a --- /dev/null +++ b/src/Agent/Configuration/AgentConfiguration.cs @@ -0,0 +1,117 @@ +using Shared.Infrastructure.Configuration; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Routing; + +namespace Agent.Configuration; + +/// +/// Effective agent configuration with per-value provenance +/// (GPO policy > normal registry > dev-only environment > compiled default). +/// +public sealed class AgentConfiguration +{ + public required ConfigurationValue ServerUrlText { get; init; } + public required ConfigurationValue BootstrapToken { get; init; } + public required ConfigurationValue LogLevel { get; init; } + public required ConfigurationValue InventoryInterval { get; init; } + public required ConfigurationValue ReconnectMinDelay { get; init; } + public required ConfigurationValue ReconnectMaxDelay { get; init; } + public required ConfigurationValue AllowRemoteShell { get; init; } + public required ConfigurationValue AllowScriptExecution { get; init; } + + /// Parsed ServerURL; null when unset or invalid. + public ServerUrl? ServerUrl => + Shared.Infrastructure.Routing.ServerUrl.TryParse(ServerUrlText.Value, out var parsed, out _) ? parsed : null; + + public bool HasBootstrapToken => !string.IsNullOrWhiteSpace(BootstrapToken.Value); +} + +/// Loads effective configuration using deterministic precedence. +public sealed class AgentConfigurationLoader(IRegistryStore registry, bool allowEnvironment) +{ + /// + /// must only be true for foreground / + /// development runs — environment values never apply in service mode and + /// never override GPO in any mode. + /// + public AgentConfiguration Load() + { + return new AgentConfiguration + { + ServerUrlText = ResolveString(AgentConfigurationKeys.ServerUrl, AgentConfigurationKeys.EnvironmentNames.ServerUrl, null), + BootstrapToken = ResolveString(AgentConfigurationKeys.BootstrapToken, AgentConfigurationKeys.EnvironmentNames.BootstrapToken, null), + LogLevel = ResolveString(AgentConfigurationKeys.LogLevel, AgentConfigurationKeys.EnvironmentNames.LogLevel, "Information")!, + InventoryInterval = ResolveTimeSpan(AgentConfigurationKeys.InventoryInterval, ProtocolDefaults.DefaultInventoryInterval), + ReconnectMinDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMinDelay, ProtocolDefaults.ReconnectMinDelay), + ReconnectMaxDelay = ResolveTimeSpan(AgentConfigurationKeys.ReconnectMaxDelay, ProtocolDefaults.ReconnectMaxDelay), + AllowRemoteShell = ResolveBool(AgentConfigurationKeys.AllowRemoteShell, defaultValue: false), + AllowScriptExecution = ResolveBool(AgentConfigurationKeys.AllowScriptExecution, defaultValue: true), + }; + } + + private ConfigurationValue ResolveString(string valueName, string? environmentName, string? defaultValue) + { + var policy = Normalize(registry.ReadString(Branding.AgentPolicyRegistryKey, valueName)); + if (policy is not null) + { + return new ConfigurationValue(policy, ConfigurationSource.GroupPolicy); + } + + var normal = Normalize(registry.ReadString(Branding.AgentRegistryKey, valueName)); + if (normal is not null) + { + return new ConfigurationValue(normal, ConfigurationSource.Registry); + } + + if (allowEnvironment && environmentName is not null) + { + var env = Normalize(Environment.GetEnvironmentVariable(environmentName)); + if (env is not null) + { + return new ConfigurationValue(env, ConfigurationSource.EnvironmentDevelopmentOnly); + } + } + + return new ConfigurationValue(defaultValue, ConfigurationSource.Default); + } + + private ConfigurationValue ResolveTimeSpan(string valueName, TimeSpan defaultValue) + { + var raw = ResolveString(valueName, environmentName: null, defaultValue: null); + if (raw.Value is not null) + { + // Accept plain seconds ("90") or a TimeSpan literal ("00:01:30"). + if (int.TryParse(raw.Value, out var seconds) && seconds > 0) + { + return new ConfigurationValue(TimeSpan.FromSeconds(seconds), raw.Source); + } + + if (TimeSpan.TryParse(raw.Value, out var span) && span > TimeSpan.Zero) + { + return new ConfigurationValue(span, raw.Source); + } + } + + return new ConfigurationValue(defaultValue, ConfigurationSource.Default); + } + + private ConfigurationValue ResolveBool(string valueName, bool defaultValue) + { + var policy = registry.ReadDword(Branding.AgentPolicyRegistryKey, valueName); + if (policy is not null) + { + return new ConfigurationValue(policy != 0, ConfigurationSource.GroupPolicy); + } + + var normal = registry.ReadDword(Branding.AgentRegistryKey, valueName); + if (normal is not null) + { + return new ConfigurationValue(normal != 0, ConfigurationSource.Registry); + } + + return new ConfigurationValue(defaultValue, ConfigurationSource.Default); + } + + private static string? Normalize(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs new file mode 100644 index 0000000..db78ac7 --- /dev/null +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -0,0 +1,32 @@ +namespace Agent.Configuration; + +/// Registry value names for administrator configuration. +public static class AgentConfigurationKeys +{ + public const string ServerUrl = "ServerURL"; + public const string BootstrapToken = "BootstrapToken"; + public const string LogLevel = "LogLevel"; + public const string InventoryInterval = "InventoryInterval"; + public const string ReconnectMinDelay = "ReconnectMinDelay"; + public const string ReconnectMaxDelay = "ReconnectMaxDelay"; + public const string AllowRemoteShell = "AllowRemoteShell"; + public const string AllowScriptExecution = "AllowScriptExecution"; + + /// Development-only environment variable names (never override GPO). + public static class EnvironmentNames + { + public const string ServerUrl = "AGENT_SERVER_URL"; + public const string BootstrapToken = "AGENT_BOOTSTRAP_TOKEN"; + public const string LogLevel = "AGENT_LOG_LEVEL"; + } +} + +/// Registry value names for runtime-managed state. +public static class AgentRuntimeKeys +{ + public const string ClientId = "ClientId"; + public const string EnrollmentId = "EnrollmentId"; + public const string LastEnrollmentUtc = "LastEnrollmentUtc"; + public const string LastConnectedUtc = "LastConnectedUtc"; + public const string CredentialExpiresUtc = "CredentialExpiresUtc"; +} diff --git a/src/Agent/Configuration/RegistryStore.cs b/src/Agent/Configuration/RegistryStore.cs new file mode 100644 index 0000000..9ea9924 --- /dev/null +++ b/src/Agent/Configuration/RegistryStore.cs @@ -0,0 +1,49 @@ +using Microsoft.Win32; + +namespace Agent.Configuration; + +/// +/// Thin registry read/write seam so configuration precedence is unit-testable. +/// Paths are relative to HKLM. +/// +public interface IRegistryStore +{ + string? ReadString(string keyPath, string valueName); + int? ReadDword(string keyPath, string valueName); + void WriteString(string keyPath, string valueName, string value); + void DeleteValue(string keyPath, string valueName); + void DeleteKeyTree(string keyPath); +} + +/// HKLM-backed registry store used in production. +public sealed class WindowsRegistryStore : IRegistryStore +{ + public string? ReadString(string keyPath, string valueName) + { + using var key = Registry.LocalMachine.OpenSubKey(keyPath); + return key?.GetValue(valueName) as string; + } + + public int? ReadDword(string keyPath, string valueName) + { + using var key = Registry.LocalMachine.OpenSubKey(keyPath); + return key?.GetValue(valueName) is int value ? value : null; + } + + public void WriteString(string keyPath, string valueName, string value) + { + using var key = Registry.LocalMachine.CreateSubKey(keyPath); + key.SetValue(valueName, value, RegistryValueKind.String); + } + + public void DeleteValue(string keyPath, string valueName) + { + using var key = Registry.LocalMachine.OpenSubKey(keyPath, writable: true); + key?.DeleteValue(valueName, throwOnMissingValue: false); + } + + public void DeleteKeyTree(string keyPath) + { + Registry.LocalMachine.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false); + } +} diff --git a/src/Agent/Enrollment/CredentialStore.cs b/src/Agent/Enrollment/CredentialStore.cs new file mode 100644 index 0000000..0449ac8 --- /dev/null +++ b/src/Agent/Enrollment/CredentialStore.cs @@ -0,0 +1,126 @@ +using System.Security.AccessControl; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using Shared.Infrastructure.Constants; + +namespace Agent.Enrollment; + +/// Persisted agent credential material. The NKey seed never leaves this machine. +public sealed record AgentCredentials( + int Version, + string ClientId, + Guid EnrollmentId, + string UserJwt, + string NkeySeed, + DateTimeOffset? ExpiresUtc) +{ + public const int CurrentVersion = 1; +} + +/// +/// DPAPI(LocalMachine)-protected credential persistence in +/// %ProgramData%\<Company>\<Product>\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. +/// +public sealed class CredentialStore(ILogger logger) +{ + private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web); + + private static string FilePath => + Path.Combine(Branding.AgentProgramDataDirectory, Branding.CredentialFileName); + + public AgentCredentials? Load() + { + try + { + if (!File.Exists(FilePath)) + { + return null; + } + + var encrypted = File.ReadAllBytes(FilePath); + var plain = ProtectedData.Unprotect(encrypted, optionalEntropy: null, DataProtectionScope.LocalMachine); + var credentials = JsonSerializer.Deserialize(plain, SerializerOptions); + + if (credentials is null || credentials.Version != AgentCredentials.CurrentVersion) + { + logger.LogWarning("Credential file has unsupported version; ignoring"); + return null; + } + + return credentials; + } + catch (Exception ex) when (ex is CryptographicException or JsonException or IOException) + { + logger.LogWarning(ex, "Credential file unreadable; treating agent as unenrolled"); + return null; + } + } + + public void Save(AgentCredentials credentials) + { + var directory = EnsureProtectedDirectory(); + + var plain = JsonSerializer.SerializeToUtf8Bytes(credentials, SerializerOptions); + var encrypted = ProtectedData.Protect(plain, optionalEntropy: null, DataProtectionScope.LocalMachine); + + var path = Path.Combine(directory, Branding.CredentialFileName); + File.WriteAllBytes(path, encrypted); + ApplyRestrictedAcl(new FileInfo(path)); + + logger.LogInformation("Credentials persisted for client {ClientId}", credentials.ClientId); + } + + public void Delete() + { + if (File.Exists(FilePath)) + { + File.Delete(FilePath); + } + } + + private static string EnsureProtectedDirectory() + { + var directory = new DirectoryInfo(Branding.AgentProgramDataDirectory); + if (!directory.Exists) + { + directory.Create(); + } + + var security = new DirectorySecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), + FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, + AccessControlType.Allow)); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), + FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, + AccessControlType.Allow)); + directory.SetAccessControl(security); + + return directory.FullName; + } + + private static void ApplyRestrictedAcl(FileInfo file) + { + var security = new FileSecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), + FileSystemRights.FullControl, + AccessControlType.Allow)); + security.AddAccessRule(new FileSystemAccessRule( + new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), + FileSystemRights.FullControl, + AccessControlType.Allow)); + file.SetAccessControl(security); + } +} diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs new file mode 100644 index 0000000..a6bd4a0 --- /dev/null +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -0,0 +1,160 @@ +using System.Net.Http.Json; +using Agent.Configuration; +using Agent.Identity; +using Agent.Storage; +using Microsoft.Extensions.Logging; +using NATS.NKeys; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Versioning; + +namespace Agent.Enrollment; + +/// +/// Secure one-time bootstrap: generates the local user NKey pair (the private +/// seed never leaves the endpoint), sends the public key + bootstrap token +/// over HTTPS, persists the returned scoped user JWT with DPAPI, and erases +/// the bootstrap token from the registry. +/// +public sealed class EnrollmentService( + CredentialStore credentialStore, + RuntimeStateStore runtimeState, + IHardwareIdentitySource hardwareIdentity, + ILogger logger) +{ + /// + /// Returns valid credentials, either loaded from the protected store or + /// obtained by bootstrapping. Null when enrollment is currently impossible + /// (no bootstrap token / server rejection) — callers retry with backoff. + /// + public async Task EnsureEnrolledAsync(AgentConfiguration configuration, CancellationToken cancellationToken) + { + var clientId = ResolveClientId(); + + var stored = credentialStore.Load(); + if (stored is not null) + { + if (stored.ClientId != clientId) + { + // Hardware materially changed: treat as a new device (MVP rule). + logger.LogWarning( + "Stored credentials belong to client {StoredClientId} but recomputed identity is {ClientId}; re-enrolling as new device", + stored.ClientId, clientId); + credentialStore.Delete(); + } + else if (configuration.HasBootstrapToken) + { + // A token is only present because an administrator just placed + // one (it is erased after every successful enrollment), so it + // is an explicit instruction to re-enroll — this is how an + // orphaned device is brought back. + logger.LogInformation( + "Bootstrap token present for already-enrolled client {ClientId}; re-enrolling", clientId); + credentialStore.Delete(); + } + else + { + return stored; + } + } + + if (!configuration.HasBootstrapToken) + { + logger.LogError("Agent is not enrolled and no bootstrap token is configured"); + return null; + } + + var serverUrl = configuration.ServerUrl; + if (serverUrl is null) + { + logger.LogError("Agent cannot enroll: ServerURL is missing or invalid"); + return null; + } + + using var userKey = KeyPair.CreatePair(PrefixByte.User); + + var request = new BootstrapRequest( + BootstrapToken: configuration.BootstrapToken.Value!, + ClientId: clientId, + NkeyPublic: userKey.GetPublicKey(), + AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly), + Device: ReadDeviceInfo()); + + using var http = new HttpClient(); + var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap); + logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint); + + using var response = await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken); + if (!response.IsSuccessStatusCode) + { + logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode); + return null; + } + + var result = await response.Content.ReadFromJsonAsync(JsonDefaults.Options, cancellationToken); + if (result is null || string.IsNullOrWhiteSpace(result.UserJwt)) + { + logger.LogError("Bootstrap response was empty or invalid"); + return null; + } + + var credentials = new AgentCredentials( + Version: AgentCredentials.CurrentVersion, + ClientId: clientId, + EnrollmentId: result.EnrollmentId, + UserJwt: result.UserJwt, + NkeySeed: userKey.GetSeed(), + ExpiresUtc: result.CredentialExpiresUtc); + + credentialStore.Save(credentials); + + runtimeState.EnrollmentId = result.EnrollmentId.ToString("D"); + runtimeState.LastEnrollmentUtc = DateTimeOffset.UtcNow; + runtimeState.CredentialExpiresUtc = result.CredentialExpiresUtc; + runtimeState.ClearBootstrapToken(); + + logger.LogInformation("Enrollment {EnrollmentId} complete; bootstrap token cleared", result.EnrollmentId); + return credentials; + } + + /// + /// Computes the deterministic client id, verifies it against the cached + /// runtime value and refreshes the cache. + /// + public string ResolveClientId() + { + var clientId = ClientIdentityFactory.ComputeClientId(hardwareIdentity.Read()); + + var cached = runtimeState.ClientId; + if (cached is not null && cached != clientId) + { + logger.LogWarning("Recomputed client id differs from cached value; hardware may have changed"); + } + + runtimeState.ClientId = clientId; + return clientId; + } + + private EnrollDeviceInfo ReadDeviceInfo() + { + var identity = hardwareIdentity.Read(); + string? osCaption = null; + string? osVersion = null; + try + { + osCaption = Environment.OSVersion.VersionString; + osVersion = Environment.OSVersion.Version.ToString(); + } + catch (InvalidOperationException) + { + // Non-fatal; inventory supplies full OS details later. + } + + return new EnrollDeviceInfo( + Hostname: Environment.MachineName, + Manufacturer: identity.Manufacturer, + Model: identity.Model, + OsCaption: osCaption, + OsVersion: osVersion); + } +} diff --git a/src/Agent/Files/FileDownloadHandler.cs b/src/Agent/Files/FileDownloadHandler.cs new file mode 100644 index 0000000..c9fc3d2 --- /dev/null +++ b/src/Agent/Files/FileDownloadHandler.cs @@ -0,0 +1,169 @@ +using System.Security.Cryptography; +using Agent.Messaging; +using Agent.Storage; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Nats; + +namespace Agent.Files; + +/// +/// Downloads a file from a backend-presigned URL to a path on the device, +/// reporting Running/progress/output/state on the job subjects so it appears in +/// the live Jobs pipeline. S3 credentials never reach the agent — only the +/// short-lived presigned URL does. +/// +public sealed class FileDownloadHandler(AgentPublisher publisher, JobHistoryStore cache, ILogger logger) +{ + private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(30) }; + + public async Task RunAsync( + FileDownloadCommandPayload command, Guid correlationId, Guid? causationId, CancellationToken cancellationToken) + { + var jobId = command.JobId; + var jobTarget = new EndpointRef(EndpointKinds.Job, jobId.ToString("D")); + var sequence = 0L; + + async Task OutputAsync(OutputStreamKind stream, string text) => await publisher.PublishAsync( + NatsSubjects.JobOutput(jobId), MessageTypes.JobOutput, + new JobOutputPayload(jobId, publisher.ClientId, Interlocked.Increment(ref sequence), stream, DateTimeOffset.UtcNow, text), + jobTarget, correlationId, causationId); + + async Task StateAsync(JobState state, int? exitCode, string? message) => await publisher.PublishAsync( + NatsSubjects.JobState(jobId), MessageTypes.JobState, + new JobStatePayload(jobId, publisher.ClientId, state, exitCode, DateTimeOffset.UtcNow, message), + jobTarget, correlationId, causationId); + + async Task ProgressAsync(int percent, long done, long? total) => await publisher.PublishAsync( + NatsSubjects.JobProgress(jobId), MessageTypes.JobProgress, + new JobProgressPayload(jobId, publisher.ClientId, "Downloading file", + total is > 0 ? $"{done / 1024} / {total / 1024} KB" : $"{done / 1024} KB", percent, null, DateTimeOffset.UtcNow), + jobTarget, correlationId, causationId); + + try + { + await StateAsync(JobState.Running, null, null); + await OutputAsync(OutputStreamKind.Information, $"Downloading {command.SourceDescription ?? "file"} -> {command.DestinationPath}"); + + var directory = Path.GetDirectoryName(command.DestinationPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + var cached = cache.GetDownloadCache(command.DestinationPath); + var fileExists = File.Exists(command.DestinationPath); + + // 1. Strongest check: the caller told us the expected hash and the + // file on disk already matches it. No request at all. + if (fileExists && !string.IsNullOrWhiteSpace(command.Sha256)) + { + await using var existing = File.OpenRead(command.DestinationPath); + var actualHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(existing, cancellationToken)); + if (string.Equals(actualHash, command.Sha256.Trim(), StringComparison.OrdinalIgnoreCase)) + { + await OutputAsync(OutputStreamKind.Output, + $"Already present with matching SHA-256; skipped download of {command.DestinationPath}"); + await StateAsync(JobState.Succeeded, 0, "Already up to date."); + return; + } + } + + using var request = new HttpRequestMessage(HttpMethod.Get, command.Url); + + // 2. Otherwise let S3 decide: send the stored ETag so an unchanged + // object comes back as 304 and costs no transfer. + if (fileExists && !string.IsNullOrWhiteSpace(cached?.ETag)) + { + request.Headers.TryAddWithoutValidation("If-None-Match", cached.ETag); + } + + using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + + if (response.StatusCode == System.Net.HttpStatusCode.NotModified) + { + await OutputAsync(OutputStreamKind.Output, + $"Object unchanged (ETag {cached?.ETag}); skipped download of {command.DestinationPath}"); + await StateAsync(JobState.Succeeded, 0, "Already up to date."); + return; + } + + response.EnsureSuccessStatusCode(); + + var total = command.SizeBytes ?? response.Content.Headers.ContentLength; + var tempPath = command.DestinationPath + ".executer-partial"; + + using (var source = await response.Content.ReadAsStreamAsync(cancellationToken)) + await using (var target = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + var buffer = new byte[81920]; + long done = 0; + var lastPercent = -1; + int read; + while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0) + { + await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + done += read; + if (total is > 0) + { + var percent = (int)Math.Min(100, done * 100 / total.Value); + if (percent != lastPercent && percent % 5 == 0) + { + lastPercent = percent; + await ProgressAsync(percent, done, total); + } + } + } + + await ProgressAsync(100, done, total); + } + + // Always hash what we fetched: it verifies the transfer when an + // expected hash was supplied, and seeds the cache either way. + string downloadedHash; + await using (var verifyStream = File.OpenRead(tempPath)) + { + downloadedHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(verifyStream, cancellationToken)); + } + + if (!string.IsNullOrWhiteSpace(command.Sha256) + && !string.Equals(downloadedHash, command.Sha256.Trim(), StringComparison.OrdinalIgnoreCase)) + { + File.Delete(tempPath); + await OutputAsync(OutputStreamKind.Error, $"Hash mismatch (expected {command.Sha256}, got {downloadedHash})"); + await StateAsync(JobState.Failed, 1, "SHA-256 verification failed."); + return; + } + + if (!string.IsNullOrWhiteSpace(command.Sha256)) + { + await OutputAsync(OutputStreamKind.Information, "SHA-256 verified."); + } + + File.Move(tempPath, command.DestinationPath, overwrite: true); + + var etag = response.Headers.ETag?.Tag; + cache.RecordDownload( + command.DestinationPath, + command.SourceDescription, + etag, + downloadedHash, + new FileInfo(command.DestinationPath).Length); + + await OutputAsync(OutputStreamKind.Output, $"Saved to {command.DestinationPath}"); + await StateAsync(JobState.Succeeded, 0, null); + logger.LogInformation("File download job {JobId} succeeded (etag {ETag})", jobId, etag ?? "none"); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + await StateAsync(JobState.Cancelled, -1, "Cancelled."); + } + catch (Exception ex) + { + logger.LogError(ex, "File download job {JobId} failed", jobId); + await OutputAsync(OutputStreamKind.Error, ex.Message); + await StateAsync(JobState.Failed, 1, ex.Message); + } + } +} diff --git a/src/Agent/Identity/CimHardwareIdentitySource.cs b/src/Agent/Identity/CimHardwareIdentitySource.cs new file mode 100644 index 0000000..52c49e9 --- /dev/null +++ b/src/Agent/Identity/CimHardwareIdentitySource.cs @@ -0,0 +1,55 @@ +using System.Management; + +namespace Agent.Identity; + +/// Reads stable hardware identifiers from CIM/WMI via managed APIs. +public sealed class CimHardwareIdentitySource : IHardwareIdentitySource +{ + public HardwareIdentity Read() + { + string? uuid = null; + string? identifyingNumber = null; + Query("SELECT UUID, IdentifyingNumber FROM Win32_ComputerSystemProduct", obj => + { + uuid = obj["UUID"] as string; + identifyingNumber = obj["IdentifyingNumber"] as string; + }); + + string? biosSerial = null; + Query("SELECT SerialNumber FROM Win32_BIOS", obj => biosSerial = obj["SerialNumber"] as string); + + string? boardSerial = null; + Query("SELECT SerialNumber FROM Win32_BaseBoard", obj => boardSerial = obj["SerialNumber"] as string); + + string? manufacturer = null; + string? model = null; + Query("SELECT Manufacturer, Model FROM Win32_ComputerSystem", obj => + { + manufacturer = obj["Manufacturer"] as string; + model = obj["Model"] as string; + }); + + return new HardwareIdentity(uuid, biosSerial, boardSerial, identifyingNumber, manufacturer, model); + } + + private static void Query(string wql, Action onFirst) + { + try + { + using var searcher = new ManagementObjectSearcher(wql); + using var results = searcher.Get(); + foreach (var obj in results) + { + using (obj) + { + onFirst(obj); + return; + } + } + } + catch (ManagementException) + { + // Missing WMI class/values — treated as absent identifiers. + } + } +} diff --git a/src/Agent/Identity/ClientIdentityFactory.cs b/src/Agent/Identity/ClientIdentityFactory.cs new file mode 100644 index 0000000..2473ee2 --- /dev/null +++ b/src/Agent/Identity/ClientIdentityFactory.cs @@ -0,0 +1,85 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Agent.Identity; + +/// +/// Builds the deterministic client id: normalized labeled canonical string +/// over stable hardware identifiers, hashed with SHA-256, exposed as +/// lowercase hex. Requires at least one strong identifier. +/// +public static class ClientIdentityFactory +{ + private static readonly string[] JunkValues = + [ + "TO BE FILLED BY O.E.M.", + "DEFAULT STRING", + "SYSTEM SERIAL NUMBER", + "SYSTEM PRODUCT NAME", + "SYSTEM MANUFACTURER", + "NONE", + "N/A", + "NA", + "UNKNOWN", + "NOT SPECIFIED", + "NOT APPLICABLE", + "NO ENCLOSURE", + "CHASSIS SERIAL NUMBER", + "0", + "00000000-0000-0000-0000-000000000000", + "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", + "03000200-0400-0500-0006-000700080009", // widely-cloned AMI placeholder UUID + "12345678-1234-5678-90AB-CDDEEFAABBCC", + ]; + + /// Normalizes one raw identifier; null when placeholder/junk. + public static string? Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + var normalized = value.Trim().ToUpperInvariant(); + + if (JunkValues.Contains(normalized)) + { + return null; + } + + // Reject strings that are entirely zeros/punctuation (e.g. "0000000"). + if (normalized.All(c => c is '0' or '-' or '.' or ' ' or '_')) + { + return null; + } + + return normalized; + } + + /// Builds the labeled canonical identity string, e.g. UUID=…|BIOS=…|…. + public static string BuildCanonicalIdentity(HardwareIdentity identity) + { + var uuid = Normalize(identity.SystemProductUuid); + var bios = Normalize(identity.BiosSerialNumber); + var board = Normalize(identity.BaseboardSerialNumber); + var ident = Normalize(identity.IdentifyingNumber); + var manufacturer = Normalize(identity.Manufacturer); + var model = Normalize(identity.Model); + + var hasStrongIdentifier = uuid is not null || bios is not null || board is not null || ident is not null; + if (!hasStrongIdentifier) + { + throw new InvalidOperationException( + "No strong hardware identifier available (UUID/BIOS/baseboard/identifying number all missing or placeholders)."); + } + + return $"UUID={uuid}|BIOS={bios}|BOARD={board}|IDENT={ident}|MFR={manufacturer}|MODEL={model}"; + } + + /// Lowercase-hex SHA-256 of the canonical identity string. + public static string ComputeClientId(HardwareIdentity identity) + { + var canonical = BuildCanonicalIdentity(identity); + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(canonical))); + } +} diff --git a/src/Agent/Identity/HardwareIdentity.cs b/src/Agent/Identity/HardwareIdentity.cs new file mode 100644 index 0000000..d435dbc --- /dev/null +++ b/src/Agent/Identity/HardwareIdentity.cs @@ -0,0 +1,16 @@ +namespace Agent.Identity; + +/// Raw hardware identity values read from CIM/WMI. +public sealed record HardwareIdentity( + string? SystemProductUuid, + string? BiosSerialNumber, + string? BaseboardSerialNumber, + string? IdentifyingNumber, + string? Manufacturer, + string? Model); + +/// Seam for reading hardware identity (CIM in production, fixed values in tests). +public interface IHardwareIdentitySource +{ + HardwareIdentity Read(); +} diff --git a/src/Agent/Inventory/InventoryCollector.cs b/src/Agent/Inventory/InventoryCollector.cs new file mode 100644 index 0000000..75a626b --- /dev/null +++ b/src/Agent/Inventory/InventoryCollector.cs @@ -0,0 +1,211 @@ +using System.Management; +using Agent.Identity; +using Shared.Contracts.Models; + +namespace Agent.Inventory; + +/// Collects the MVP inventory snapshot from CIM/WMI and managed APIs. +public sealed class InventoryCollector(IHardwareIdentitySource identitySource) +{ + public InventoryReport Collect(string clientId) + { + var hardware = identitySource.Read(); + + string? domain = null; + var partOfDomain = false; + string? systemType = null; + long totalMemory = 0; + QueryFirst("SELECT Domain, PartOfDomain, SystemType, TotalPhysicalMemory FROM Win32_ComputerSystem", obj => + { + domain = obj["Domain"] as string; + partOfDomain = obj["PartOfDomain"] as bool? ?? false; + systemType = obj["SystemType"] as string; + totalMemory = (long?)(obj["TotalPhysicalMemory"] as ulong?) ?? 0; + }); + + string? biosVersion = null; + QueryFirst("SELECT SMBIOSBIOSVersion FROM Win32_BIOS", obj => biosVersion = obj["SMBIOSBIOSVersion"] as string); + + var identity = new InventoryIdentity( + ClientId: clientId, + Hostname: Environment.MachineName, + Manufacturer: hardware.Manufacturer?.Trim(), + Model: hardware.Model?.Trim(), + SerialNumber: hardware.BiosSerialNumber?.Trim(), + BiosVersion: biosVersion?.Trim(), + BaseboardSerial: hardware.BaseboardSerialNumber?.Trim(), + DomainOrWorkgroup: domain, + PartOfDomain: partOfDomain, + SystemType: systemType); + + var os = CollectOs(); + var cpu = CollectCpu(); + var memory = CollectMemory(); + var disks = CollectDisks(); + var volumes = CollectVolumes(); + var network = CollectNetwork(); + + return new InventoryReport( + Identity: identity, + Os: os, + Cpu: cpu, + Memory: memory, + TotalPhysicalMemoryBytes: totalMemory, + Disks: disks, + Volumes: volumes, + Network: network, + CollectedUtc: DateTimeOffset.UtcNow); + } + + private static InventoryOs CollectOs() + { + string? caption = null; + string? version = null; + string? build = null; + string? architecture = null; + DateTimeOffset? installDate = null; + DateTimeOffset? lastBoot = null; + string? edition = null; + + QueryFirst( + "SELECT Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime, OperatingSystemSKU FROM Win32_OperatingSystem", + obj => + { + caption = (obj["Caption"] as string)?.Trim(); + version = obj["Version"] as string; + build = obj["BuildNumber"] as string; + architecture = obj["OSArchitecture"] as string; + installDate = ConvertCimDate(obj["InstallDate"] as string); + lastBoot = ConvertCimDate(obj["LastBootUpTime"] as string); + edition = obj["OperatingSystemSKU"]?.ToString(); + }); + + return new InventoryOs(caption, version, build, architecture, installDate, lastBoot, edition); + } + + private static InventoryCpu CollectCpu() + { + string? name = null; + var logical = 0; + var cores = 0; + Query("SELECT Name, NumberOfLogicalProcessors, NumberOfCores FROM Win32_Processor", obj => + { + name ??= (obj["Name"] as string)?.Trim(); + logical += (int?)(obj["NumberOfLogicalProcessors"] as uint?) ?? 0; + cores += (int?)(obj["NumberOfCores"] as uint?) ?? 0; + }); + + return new InventoryCpu(name, logical, cores); + } + + private static List CollectMemory() + { + var modules = new List(); + Query("SELECT DeviceLocator, Capacity, Manufacturer, Speed FROM Win32_PhysicalMemory", obj => + { + modules.Add(new InventoryMemoryModule( + DeviceLocator: obj["DeviceLocator"] as string, + CapacityBytes: (long?)(obj["Capacity"] as ulong?) ?? 0, + Manufacturer: (obj["Manufacturer"] as string)?.Trim(), + SpeedMhz: (int?)(obj["Speed"] as uint?))); + }); + return modules; + } + + private static List CollectDisks() + { + var disks = new List(); + Query("SELECT 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)); + }); + return disks; + } + + private static List CollectVolumes() + { + var volumes = new List(); + Query("SELECT DeviceID, FileSystem, Size, FreeSpace FROM Win32_LogicalDisk WHERE DriveType = 3", obj => + { + volumes.Add(new InventoryVolume( + DriveLetter: obj["DeviceID"] as string ?? string.Empty, + FileSystem: obj["FileSystem"] as string, + TotalSizeBytes: (long?)(obj["Size"] as ulong?) ?? 0, + FreeSpaceBytes: (long?)(obj["FreeSpace"] as ulong?) ?? 0)); + }); + return volumes; + } + + private static List CollectNetwork() + { + var adapters = new List(); + Query( + "SELECT Description, MACAddress, IPAddress, DefaultIPGateway, DNSServerSearchOrder FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE", + obj => + { + var addresses = obj["IPAddress"] as string[] ?? []; + adapters.Add(new InventoryNetworkAdapter( + Description: obj["Description"] as string, + MacAddress: obj["MACAddress"] as string, + Ipv4Addresses: [.. addresses.Where(a => !a.Contains(':'))], + Ipv6Addresses: [.. addresses.Where(a => a.Contains(':'))], + Gateways: [.. obj["DefaultIPGateway"] as string[] ?? []], + DnsServers: [.. obj["DNSServerSearchOrder"] as string[] ?? []])); + }); + return adapters; + } + + private static DateTimeOffset? ConvertCimDate(string? cimDate) + { + if (string.IsNullOrWhiteSpace(cimDate)) + { + return null; + } + + try + { + return new DateTimeOffset(ManagementDateTimeConverter.ToDateTime(cimDate).ToUniversalTime(), TimeSpan.Zero); + } + catch (ArgumentException) + { + return null; + } + } + + private static void Query(string wql, Action onEach) + { + try + { + using var searcher = new ManagementObjectSearcher(wql); + using var results = searcher.Get(); + foreach (var obj in results) + { + using (obj) + { + onEach(obj); + } + } + } + catch (ManagementException) + { + // Missing class/namespace — section stays empty. + } + } + + private static void QueryFirst(string wql, Action onFirst) + { + var seen = false; + Query(wql, obj => + { + if (!seen) + { + seen = true; + onFirst(obj); + } + }); + } +} diff --git a/src/Agent/Inventory/InventoryPublisher.cs b/src/Agent/Inventory/InventoryPublisher.cs new file mode 100644 index 0000000..69e36d0 --- /dev/null +++ b/src/Agent/Inventory/InventoryPublisher.cs @@ -0,0 +1,65 @@ +using Agent.Messaging; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Infrastructure.Nats; + +namespace Agent.Inventory; + +/// +/// Publishes the full inventory snapshot: immediately at session start +/// (covers enrollment and reconnect), on the configured interval, and on +/// demand when the backend sends an inventory command. +/// +public sealed class InventoryPublisher( + InventoryCollector collector, + AgentPublisher publisher, + TimeSpan interval, + ILogger logger) +{ + private readonly SemaphoreSlim publishLock = new(1, 1); + + public async Task RunAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + await TriggerAsync("interval", cancellationToken); + + try + { + await Task.Delay(interval, cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + } + } + + public async Task TriggerAsync(string reason, CancellationToken cancellationToken) + { + await publishLock.WaitAsync(cancellationToken); + try + { + var report = collector.Collect(publisher.ClientId); + await publisher.PublishAsync( + NatsSubjects.AgentInventory(publisher.ClientId), + MessageTypes.AgentInventory, + new InventoryPayload(report), + cancellationToken: cancellationToken); + + logger.LogInformation("Inventory published ({Reason})", reason); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Inventory collection/publish failed ({Reason})", reason); + } + finally + { + publishLock.Release(); + } + } +} diff --git a/src/Agent/Messaging/AgentNatsOptionsFactory.cs b/src/Agent/Messaging/AgentNatsOptionsFactory.cs new file mode 100644 index 0000000..87da97e --- /dev/null +++ b/src/Agent/Messaging/AgentNatsOptionsFactory.cs @@ -0,0 +1,40 @@ +using Agent.Configuration; +using Agent.Enrollment; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; +using Shared.Infrastructure.Routing; + +namespace Agent.Messaging; + +/// +/// Builds the NATS client options for the WSS connection derived from +/// ServerURL. Credentials are supplied from protected in-memory state — +/// no .creds file is ever written. +/// +public static class AgentNatsOptionsFactory +{ + public static NatsOpts Build( + ServerUrl serverUrl, + AgentCredentials credentials, + AgentConfiguration configuration, + ILoggerFactory loggerFactory) + { + return NatsOpts.Default with + { + Url = serverUrl.AgentWebSocketEndpoint.ToString(), + Name = $"agent-{credentials.ClientId}", + AuthOpts = NatsAuthOpts.Default with + { + Jwt = credentials.UserJwt, + Seed = credentials.NkeySeed, + }, + ReconnectWaitMin = configuration.ReconnectMinDelay.Value, + ReconnectWaitMax = configuration.ReconnectMaxDelay.Value, + ReconnectJitter = TimeSpan.FromMilliseconds(500), + MaxReconnectRetry = -1, + RetryOnInitialConnect = true, + DrainSubscriptionsOnDispose = true, + LoggerFactory = loggerFactory, + }; + } +} diff --git a/src/Agent/Messaging/AgentPublisher.cs b/src/Agent/Messaging/AgentPublisher.cs new file mode 100644 index 0000000..d88829b --- /dev/null +++ b/src/Agent/Messaging/AgentPublisher.cs @@ -0,0 +1,25 @@ +using NATS.Client.Core; +using Shared.Contracts.Messages; + +namespace Agent.Messaging; + +/// Publishes enveloped messages from this agent. +public sealed class AgentPublisher(NatsConnection connection, string clientId) +{ + public EndpointRef Source { get; } = new(EndpointKinds.Agent, clientId); + + public string ClientId => clientId; + + public async ValueTask PublishAsync( + string subject, + string messageType, + TPayload payload, + EndpointRef? target = null, + Guid? correlationId = null, + Guid? causationId = null, + CancellationToken cancellationToken = default) + { + var envelope = MessageEnvelope.Create(messageType, Source, payload, target, correlationId, causationId); + await connection.PublishAsync(subject, envelope.ToUtf8Bytes(), cancellationToken: cancellationToken); + } +} diff --git a/src/Agent/PowerShell/PowerShellExecutionService.cs b/src/Agent/PowerShell/PowerShellExecutionService.cs new file mode 100644 index 0000000..4b4c7e6 --- /dev/null +++ b/src/Agent/PowerShell/PowerShellExecutionService.cs @@ -0,0 +1,108 @@ +using System.Management.Automation; +using System.Management.Automation.Runspaces; + +namespace Agent.PowerShell; + +/// Result of one in-process PowerShell execution. +public sealed record PowerShellExecutionResult(bool HadErrors, bool WasCancelled, string? FailureMessage); + +/// +/// Executes scripts in-process through System.Management.Automation: +/// runspace + AddScript/AddParameter, async invocation, live subscription to +/// every stream, cooperative cancellation, clean disposal. +/// +public sealed class PowerShellExecutionService +{ + public Task ExecuteAsync( + string scriptContent, + IReadOnlyDictionary? parameters, + Action onRecord, + Action onProgress, + CancellationToken cancellationToken) + => ExecuteAsync(scriptContent, parameters, prelude: null, onRecord, onProgress, cancellationToken); + + /// + /// Runs (reusable function definitions), if any, + /// then the main in the same runspace, so + /// the main script keeps its param() block first while still calling + /// shared functions. + /// + public async Task ExecuteAsync( + string scriptContent, + IReadOnlyDictionary? parameters, + string? prelude, + Action onRecord, + Action onProgress, + CancellationToken cancellationToken) + { + using var runspace = PowerShellRunspaceFactory.Create(); + using var powerShell = System.Management.Automation.PowerShell.Create(); + powerShell.Runspace = runspace; + + if (!string.IsNullOrWhiteSpace(prelude)) + { + powerShell.AddScript(prelude); + powerShell.AddStatement(); + } + + powerShell.AddScript(scriptContent); + if (parameters is not null) + { + foreach (var (name, value) in parameters) + { + powerShell.AddParameter(name, value); + } + } + + var output = new PSDataCollection(); + output.DataAdded += (_, e) => onRecord(PowerShellOutputNormalizer.FromOutput(output[e.Index])); + + powerShell.Streams.Error.DataAdded += (_, e) => + onRecord(PowerShellOutputNormalizer.FromError(powerShell.Streams.Error[e.Index])); + powerShell.Streams.Warning.DataAdded += (_, e) => + onRecord(PowerShellOutputNormalizer.FromWarning(powerShell.Streams.Warning[e.Index])); + powerShell.Streams.Verbose.DataAdded += (_, e) => + onRecord(PowerShellOutputNormalizer.FromVerbose(powerShell.Streams.Verbose[e.Index])); + powerShell.Streams.Debug.DataAdded += (_, e) => + onRecord(PowerShellOutputNormalizer.FromDebug(powerShell.Streams.Debug[e.Index])); + powerShell.Streams.Information.DataAdded += (_, e) => + onRecord(PowerShellOutputNormalizer.FromInformation(powerShell.Streams.Information[e.Index])); + powerShell.Streams.Progress.DataAdded += (_, e) => + onProgress(PowerShellOutputNormalizer.FromProgress(powerShell.Streams.Progress[e.Index])); + + var wasCancelled = false; + await using var registration = cancellationToken.Register(() => + { + wasCancelled = true; + try + { + powerShell.BeginStop(null, null); + } + catch (ObjectDisposedException) + { + // Execution already completed. + } + }); + + string? failureMessage = null; + try + { + await powerShell.InvokeAsync(input: null, output: output).ConfigureAwait(false); + } + catch (PipelineStoppedException) + { + wasCancelled = true; + } + catch (RuntimeException ex) + { + // Terminating error: surface as an error record + failed result. + failureMessage = ex.Message; + onRecord(new NormalizedOutputRecord(Shared.Contracts.Models.OutputStreamKind.Error, ex.Message)); + } + + return new PowerShellExecutionResult( + HadErrors: powerShell.HadErrors || failureMessage is not null, + WasCancelled: wasCancelled, + FailureMessage: failureMessage); + } +} diff --git a/src/Agent/PowerShell/PowerShellJobHandler.cs b/src/Agent/PowerShell/PowerShellJobHandler.cs new file mode 100644 index 0000000..f68c4d5 --- /dev/null +++ b/src/Agent/PowerShell/PowerShellJobHandler.cs @@ -0,0 +1,154 @@ +using Agent.Messaging; +using Agent.Storage; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Agent.PowerShell; + +/// +/// Runs one script job: streams normalized output/progress records to Core +/// NATS with a per-job monotonic sequence and publishes job state transitions. +/// +public sealed class PowerShellJobHandler( + PowerShellExecutionService executionService, + AgentPublisher publisher, + JobHistoryStore jobHistory, + ILogger logger) +{ + private int activeJobs; + + public int ActiveJobs => Volatile.Read(ref activeJobs); + + public async Task RunJobAsync(ScriptCommandPayload command, Guid correlationId, Guid? causationId, CancellationToken cancellationToken) + { + var jobId = command.JobId; + var jobTarget = new EndpointRef(EndpointKinds.Job, jobId.ToString("D")); + var sequence = 0L; + + Interlocked.Increment(ref activeJobs); + try + { + await PublishStateAsync(JobState.Running, exitCode: null, message: null); + + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var timeout = TimeSpan.FromSeconds(command.TimeoutSeconds is > 0 + ? command.TimeoutSeconds.Value + : ProtocolDefaults.DefaultScriptTimeoutSeconds); + timeoutCts.CancelAfter(timeout); + + var pending = new List(); + + var boundParameters = ScriptArgumentBinder.Bind(command.Parameters, command.Arguments); + + var result = await executionService.ExecuteAsync( + command.Content, + boundParameters, + command.Prelude, + onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))), + onProgress: progress => pending.Add(PublishProgressAsync(progress)), + cancellationToken: timeoutCts.Token); + + await Task.WhenAll(pending); + + JobState finalState; + int exitCode; + string? message = null; + + if (result.WasCancelled && cancellationToken.IsCancellationRequested) + { + finalState = JobState.Cancelled; + exitCode = -1; + message = "Execution cancelled."; + } + else if (result.WasCancelled) + { + finalState = JobState.TimedOut; + exitCode = -1; + message = $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout."; + } + else if (result.HadErrors) + { + finalState = JobState.Failed; + exitCode = 1; + message = result.FailureMessage; + } + else + { + finalState = JobState.Succeeded; + exitCode = 0; + } + + jobHistory.MarkCompleted(jobId, finalState.ToString()); + await PublishStateAsync(finalState, exitCode, message); + + logger.LogInformation("Job {JobId} finished: {State}", jobId, finalState); + } + catch (Exception ex) + { + logger.LogError(ex, "Job {JobId} crashed", jobId); + jobHistory.MarkCompleted(jobId, JobState.Failed.ToString()); + await PublishStateAsync(JobState.Failed, exitCode: 1, message: ex.Message); + } + finally + { + Interlocked.Decrement(ref activeJobs); + } + + async Task PublishOutputAsync(NormalizedOutputRecord record, long seq) + { + try + { + await publisher.PublishAsync( + NatsSubjects.JobOutput(jobId), + MessageTypes.JobOutput, + new JobOutputPayload(jobId, publisher.ClientId, seq, record.Stream, DateTimeOffset.UtcNow, record.Text), + jobTarget, + correlationId, + causationId); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to publish output record for job {JobId}", jobId); + } + } + + async Task PublishProgressAsync(NormalizedProgressRecord progress) + { + try + { + await publisher.PublishAsync( + NatsSubjects.JobProgress(jobId), + MessageTypes.JobProgress, + new JobProgressPayload( + jobId, + publisher.ClientId, + progress.Activity, + progress.StatusDescription, + progress.PercentComplete, + progress.SecondsRemaining, + DateTimeOffset.UtcNow), + jobTarget, + correlationId, + causationId); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to publish progress for job {JobId}", jobId); + } + } + + async Task PublishStateAsync(JobState state, int? exitCode, string? message) + { + await publisher.PublishAsync( + NatsSubjects.JobState(jobId), + MessageTypes.JobState, + new JobStatePayload(jobId, publisher.ClientId, state, exitCode, DateTimeOffset.UtcNow, message), + jobTarget, + correlationId, + causationId); + } + } +} diff --git a/src/Agent/PowerShell/PowerShellOutputNormalizer.cs b/src/Agent/PowerShell/PowerShellOutputNormalizer.cs new file mode 100644 index 0000000..cfd1b6a --- /dev/null +++ b/src/Agent/PowerShell/PowerShellOutputNormalizer.cs @@ -0,0 +1,61 @@ +using System.Management.Automation; +using Shared.Contracts.Models; + +namespace Agent.PowerShell; + +/// One normalized record from any PowerShell stream. +public sealed record NormalizedOutputRecord(OutputStreamKind Stream, string Text); + +/// Normalized PowerShell progress record. +public sealed record NormalizedProgressRecord( + string Activity, + string? StatusDescription, + int? PercentComplete, + int? SecondsRemaining); + +/// Converts PowerShell stream objects into wire-friendly records. +public static class PowerShellOutputNormalizer +{ + public static NormalizedOutputRecord FromOutput(PSObject? value) + => new(OutputStreamKind.Output, ToText(value)); + + public static NormalizedOutputRecord FromError(ErrorRecord record) + { + var text = record.Exception?.Message ?? record.ToString(); + if (record.InvocationInfo?.PositionMessage is { Length: > 0 } position) + { + text = $"{text}{Environment.NewLine}{position}"; + } + + return new NormalizedOutputRecord(OutputStreamKind.Error, text); + } + + public static NormalizedOutputRecord FromWarning(WarningRecord record) + => new(OutputStreamKind.Warning, record.Message); + + public static NormalizedOutputRecord FromVerbose(VerboseRecord record) + => new(OutputStreamKind.Verbose, record.Message); + + public static NormalizedOutputRecord FromDebug(DebugRecord record) + => new(OutputStreamKind.Debug, record.Message); + + public static NormalizedOutputRecord FromInformation(InformationRecord record) + => new(OutputStreamKind.Information, record.MessageData?.ToString() ?? string.Empty); + + public static NormalizedProgressRecord FromProgress(ProgressRecord record) + => new( + Activity: record.Activity, + StatusDescription: string.IsNullOrEmpty(record.StatusDescription) ? null : record.StatusDescription, + PercentComplete: record.PercentComplete >= 0 ? record.PercentComplete : null, + SecondsRemaining: record.SecondsRemaining >= 0 ? record.SecondsRemaining : null); + + private static string ToText(PSObject? value) + { + if (value?.BaseObject is null) + { + return string.Empty; + } + + return value.ToString() ?? string.Empty; + } +} diff --git a/src/Agent/PowerShell/PowerShellRunspaceFactory.cs b/src/Agent/PowerShell/PowerShellRunspaceFactory.cs new file mode 100644 index 0000000..bd63ddb --- /dev/null +++ b/src/Agent/PowerShell/PowerShellRunspaceFactory.cs @@ -0,0 +1,17 @@ +using System.Management.Automation.Runspaces; + +namespace Agent.PowerShell; + +/// Creates runspaces for in-process PowerShell execution (SDK-hosted, never powershell.exe). +public static class PowerShellRunspaceFactory +{ + public static Runspace Create() + { + var initialSessionState = InitialSessionState.CreateDefault(); + initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass; + + var runspace = RunspaceFactory.CreateRunspace(initialSessionState); + runspace.Open(); + return runspace; + } +} diff --git a/src/Agent/PowerShell/ScriptArgumentBinder.cs b/src/Agent/PowerShell/ScriptArgumentBinder.cs new file mode 100644 index 0000000..dc12a40 --- /dev/null +++ b/src/Agent/PowerShell/ScriptArgumentBinder.cs @@ -0,0 +1,163 @@ +using System.Collections; +using System.Text.Json; +using Shared.Contracts.Models; + +namespace Agent.PowerShell; + +/// +/// Coerces JSON argument values into CLR types matching each declared +/// , so PowerShell binds strongly typed values +/// (string/number/bool/array/hashtable, with typed hashtable keys). +/// +public static class ScriptArgumentBinder +{ + public static Dictionary Bind( + IReadOnlyList? parameters, + IReadOnlyDictionary? arguments) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (parameters is null) + { + return result; + } + + foreach (var parameter in parameters) + { + JsonElement value; + var hasValue = arguments is not null && arguments.TryGetValue(parameter.Name, out value); + if (!hasValue) + { + if (parameter.DefaultValue is { } def && def.ValueKind is not JsonValueKind.Undefined) + { + value = def; + } + else + { + continue; // Let PowerShell apply its own default / prompt suppression. + } + } + else + { + value = arguments![parameter.Name]; + } + + result[parameter.Name] = Convert(parameter, value); + } + + return result; + } + + private static object? Convert(ScriptParameter parameter, JsonElement value) + => parameter.Type switch + { + ScriptParameterType.String => value.ValueKind == JsonValueKind.Null ? null : value.ToString(), + 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), + _ => value.ToString(), + }; + + private static object? ConvertPrimitive(PrimitiveType type, JsonElement value) => type switch + { + PrimitiveType.Number => ConvertNumber(value), + PrimitiveType.Boolean => ConvertBoolean(value), + _ => value.ValueKind == JsonValueKind.Null ? null : value.ToString(), + }; + + private static object? ConvertNumber(JsonElement value) + { + if (value.ValueKind == JsonValueKind.Number) + { + if (value.TryGetInt64(out var l)) + { + return l is >= int.MinValue and <= int.MaxValue ? (int)l : l; + } + + return value.GetDouble(); + } + + if (value.ValueKind == JsonValueKind.String && double.TryParse(value.GetString(), out var parsed)) + { + return parsed == Math.Floor(parsed) && !double.IsInfinity(parsed) ? (long)parsed : parsed; + } + + return 0; + } + + private static bool ConvertBoolean(JsonElement value) => value.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + JsonValueKind.String => bool.TryParse(value.GetString(), out var b) && b, + JsonValueKind.Number => value.TryGetInt64(out var n) && n != 0, + _ => false, + }; + + private static object?[] ConvertArray(PrimitiveType elementType, JsonElement value) + { + if (value.ValueKind != JsonValueKind.Array) + { + return []; + } + + var items = new List(); + foreach (var element in value.EnumerateArray()) + { + items.Add(ConvertPrimitive(elementType, element)); + } + + return items.ToArray(); + } + + /// + /// Accepts either a JSON object (string keys) or an array of + /// { "key": ..., "value": ... } pairs (typed keys) and returns a + /// PowerShell with coerced keys and values. + /// + private static Hashtable ConvertHashtable(PrimitiveType keyType, PrimitiveType valueType, JsonElement value) + { + var table = new Hashtable(); + + if (value.ValueKind == JsonValueKind.Object) + { + foreach (var property in value.EnumerateObject()) + { + var key = ConvertPrimitiveKey(keyType, property.Name); + if (key is not null) + { + table[key] = ConvertPrimitive(valueType, property.Value); + } + } + } + else if (value.ValueKind == JsonValueKind.Array) + { + foreach (var entry in value.EnumerateArray()) + { + if (entry.ValueKind != JsonValueKind.Object + || !entry.TryGetProperty("key", out var keyElement) + || !entry.TryGetProperty("value", out var valueElement)) + { + continue; + } + + var key = ConvertPrimitive(keyType, keyElement); + if (key is not null) + { + table[key] = ConvertPrimitive(valueType, valueElement); + } + } + } + + 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, + }; +} diff --git a/src/Agent/Program.cs b/src/Agent/Program.cs new file mode 100644 index 0000000..9f6abe1 --- /dev/null +++ b/src/Agent/Program.cs @@ -0,0 +1,3 @@ +using Agent.Commands; + +return await AgentCli.RunAsync(args); diff --git a/src/Agent/Progress/PresencePublisher.cs b/src/Agent/Progress/PresencePublisher.cs new file mode 100644 index 0000000..6dea4f7 --- /dev/null +++ b/src/Agent/Progress/PresencePublisher.cs @@ -0,0 +1,56 @@ +using Agent.Messaging; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; +using Shared.Infrastructure.Versioning; + +namespace Agent.Progress; + +/// Publishes the periodic presence heartbeat over Core NATS. +public sealed class PresencePublisher( + AgentPublisher publisher, + Func activeJobCounter, + ILogger logger) +{ + private static readonly string AgentVersion = BuildVersion.Resolve(typeof(PresencePublisher).Assembly); + + public async Task RunAsync(CancellationToken cancellationToken) + { + var subject = NatsSubjects.AgentPresence(publisher.ClientId); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + var payload = new PresencePayload( + ClientId: publisher.ClientId, + Hostname: Environment.MachineName, + AgentVersion: AgentVersion, + Status: "online", + TimestampUtc: DateTimeOffset.UtcNow, + UptimeSeconds: Environment.TickCount64 / 1000, + ActiveJobs: activeJobCounter()); + + await publisher.PublishAsync(subject, MessageTypes.AgentPresence, payload, cancellationToken: cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Presence publish failed; retrying on next interval"); + } + + try + { + await Task.Delay(ProtocolDefaults.PresenceInterval, cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + } + } +} diff --git a/src/Agent/Service/AgentHost.cs b/src/Agent/Service/AgentHost.cs new file mode 100644 index 0000000..ddde893 --- /dev/null +++ b/src/Agent/Service/AgentHost.cs @@ -0,0 +1,67 @@ +using Agent.Configuration; +using Agent.Enrollment; +using Agent.Identity; +using Agent.Storage; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Serilog; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Logging; + +namespace Agent.Service; + +/// Builds the Generic Host used for both foreground and service operation. +public static class AgentHost +{ + public static IHost Build(bool runAsService) + { + var settings = new HostApplicationBuilderSettings + { + // The SCM starts services with an arbitrary current directory. + ContentRootPath = AppContext.BaseDirectory, + }; + + var builder = Host.CreateApplicationBuilder(settings); + + // Centralized Serilog: console + daily rolling file with retention. + // Log level honors the agent's own configuration precedence + // (GPO > registry > default) rather than only environment variables. + var registry = new WindowsRegistryStore(); + var agentConfiguration = new AgentConfigurationLoader(registry, allowEnvironment: !runAsService).Load(); + + var logSettings = LogSettings.FromConfiguration( + builder.Configuration, + LogDefaults.Agent, + defaultDirectory: Path.Combine(Branding.AgentProgramDataDirectory, "logs")) with + { + // The agent's level comes from its own precedence chain + // (GPO > registry > default), not from the environment. + Level = agentConfiguration.LogLevel.Value, + }; + + builder.Logging.ClearProviders(); + builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "agent"), dispose: true); + + if (runAsService) + { + builder.Services.AddWindowsService(options => options.ServiceName = Branding.AgentServiceName); + } + + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + + // Environment variables are development-only and never apply in + // service mode (and never override GPO in any mode). + builder.Services.AddSingleton(new AgentConfigurationLoader(registry, allowEnvironment: !runAsService)); + + builder.Services.AddHostedService(); + + return builder.Build(); + } +} diff --git a/src/Agent/Service/AgentSession.cs b/src/Agent/Service/AgentSession.cs new file mode 100644 index 0000000..6f86e0b --- /dev/null +++ b/src/Agent/Service/AgentSession.cs @@ -0,0 +1,104 @@ +using Agent.Commands; +using Agent.Configuration; +using Agent.Enrollment; +using Agent.Files; +using Agent.Identity; +using Agent.Inventory; +using Agent.Messaging; +using Agent.PowerShell; +using Agent.Progress; +using Agent.Shell; +using Agent.Storage; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; + +namespace Agent.Service; + +/// Creates the per-connection agent session. +public interface IAgentSessionFactory +{ + IAgentSession Create(NatsConnection connection, AgentCredentials credentials, AgentConfiguration configuration); +} + +/// One logical session bound to a connected NATS client. +public interface IAgentSession +{ + Task RunAsync(CancellationToken cancellationToken); +} + +public sealed class AgentSessionFactory( + IHardwareIdentitySource hardwareIdentity, + JobHistoryStore jobHistory, + ILoggerFactory loggerFactory) : IAgentSessionFactory +{ + public IAgentSession Create(NatsConnection connection, AgentCredentials credentials, AgentConfiguration configuration) + => new AgentSession(connection, credentials, configuration, hardwareIdentity, jobHistory, loggerFactory); +} + +/// +/// Runs the concurrent per-connection components: presence heartbeat, +/// inventory publishing and durable command processing. +/// +public sealed class AgentSession : IAgentSession +{ + private readonly PresencePublisher presence; + private readonly InventoryPublisher inventory; + private readonly CommandProcessor commands; + private readonly ShellCommandListener shell; + private readonly ILogger logger; + private readonly AgentCredentials credentials; + private readonly AgentConfiguration configuration; + + public AgentSession( + NatsConnection connection, + AgentCredentials credentials, + AgentConfiguration configuration, + IHardwareIdentitySource hardwareIdentity, + JobHistoryStore jobHistory, + ILoggerFactory loggerFactory) + { + this.credentials = credentials; + this.configuration = configuration; + logger = loggerFactory.CreateLogger(); + + var publisher = new AgentPublisher(connection, credentials.ClientId); + var collector = new InventoryCollector(hardwareIdentity); + var executionService = new PowerShellExecutionService(); + var jobHandler = new PowerShellJobHandler( + executionService, publisher, jobHistory, loggerFactory.CreateLogger()); + var fileHandler = new FileDownloadHandler(publisher, jobHistory, loggerFactory.CreateLogger()); + + presence = new PresencePublisher( + publisher, () => jobHandler.ActiveJobs, loggerFactory.CreateLogger()); + inventory = new InventoryPublisher( + collector, publisher, configuration.InventoryInterval.Value, loggerFactory.CreateLogger()); + commands = new CommandProcessor( + connection, publisher, inventory, jobHandler, fileHandler, jobHistory, configuration, + loggerFactory.CreateLogger()); + shell = new ShellCommandListener( + connection, publisher, configuration, loggerFactory.CreateLogger()); + } + + public async Task RunAsync(CancellationToken cancellationToken) + { + logger.LogInformation( + "Session started for client {ClientId} (remote shell {RemoteShell}, script execution {ScriptExecution})", + credentials.ClientId, + configuration.AllowRemoteShell.Value ? "enabled" : "disabled", + configuration.AllowScriptExecution.Value ? "enabled" : "disabled"); + + // Inventory publishes immediately (enrollment/reconnect), then on interval. + try + { + await Task.WhenAll( + presence.RunAsync(cancellationToken), + inventory.RunAsync(cancellationToken), + commands.RunAsync(cancellationToken), + shell.RunAsync(cancellationToken)); + } + finally + { + shell.Dispose(); + } + } +} diff --git a/src/Agent/Service/AgentWorker.cs b/src/Agent/Service/AgentWorker.cs new file mode 100644 index 0000000..3022a0f --- /dev/null +++ b/src/Agent/Service/AgentWorker.cs @@ -0,0 +1,92 @@ +using Agent.Configuration; +using Agent.Enrollment; +using Agent.Messaging; +using Agent.Storage; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; +using Shared.Infrastructure.Versioning; + +namespace Agent.Service; + +/// +/// Root background worker: loads configuration, ensures enrollment, keeps a +/// resilient NATS-over-WebSocket connection and runs the agent session +/// (presence, inventory, command handling) on top of it. +/// +public sealed class AgentWorker( + AgentConfigurationLoader configurationLoader, + EnrollmentService enrollment, + RuntimeStateStore runtimeState, + IAgentSessionFactory sessionFactory, + ILoggerFactory loggerFactory, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.LogInformation("Agent {Version} starting", BuildVersion.Resolve(typeof(AgentWorker).Assembly)); + + var retryDelay = TimeSpan.FromSeconds(10); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + // Reload configuration every cycle so registry/GPO changes + // (e.g. a newly written bootstrap token) are picked up. + var configuration = configurationLoader.Load(); + + var credentials = await enrollment.EnsureEnrolledAsync(configuration, stoppingToken); + if (credentials is null || configuration.ServerUrl is null) + { + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + continue; + } + + var opts = AgentNatsOptionsFactory.Build(configuration.ServerUrl, credentials, configuration, loggerFactory); + + await using var nats = new NatsConnection(opts); + + nats.ConnectionOpened += (_, _) => + { + logger.LogInformation("NATS connected to {Url}", opts.Url); + runtimeState.LastConnectedUtc = DateTimeOffset.UtcNow; + return default; + }; + nats.ConnectionDisconnected += (_, _) => + { + logger.LogWarning("NATS disconnected; automatic reconnect in progress"); + return default; + }; + nats.ReconnectFailed += (_, _) => + { + logger.LogWarning("NATS reconnect attempt failed; will retry with backoff"); + return default; + }; + + await nats.ConnectAsync(); + + var session = sessionFactory.Create(nats, credentials, configuration); + await session.RunAsync(stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + logger.LogError(ex, "Agent session failed; restarting in {Delay}", retryDelay); + try + { + await Task.Delay(retryDelay, stoppingToken); + } + catch (OperationCanceledException) + { + break; + } + } + } + + logger.LogInformation("Agent stopping"); + } +} diff --git a/src/Agent/Service/ServiceControlApi.cs b/src/Agent/Service/ServiceControlApi.cs new file mode 100644 index 0000000..eab298f --- /dev/null +++ b/src/Agent/Service/ServiceControlApi.cs @@ -0,0 +1,113 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace Agent.Service; + +/// +/// Minimal advapi32 service-control interop for install/update/remove. +/// Start/stop/query use . +/// +internal static partial class ServiceControlApi +{ + internal const uint SC_MANAGER_ALL_ACCESS = 0xF003F; + internal const uint SERVICE_ALL_ACCESS = 0xF01FF; + internal const uint SERVICE_WIN32_OWN_PROCESS = 0x10; + internal const uint SERVICE_AUTO_START = 0x2; + internal const uint SERVICE_ERROR_NORMAL = 0x1; + internal const uint SERVICE_NO_CHANGE = 0xFFFFFFFF; + + internal const int SERVICE_CONFIG_DESCRIPTION = 1; + internal const int SERVICE_CONFIG_FAILURE_ACTIONS = 2; + internal const int SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3; + + internal const int SC_ACTION_RESTART = 1; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SERVICE_DESCRIPTION + { + public string lpDescription; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SERVICE_DELAYED_AUTO_START_INFO + { + public bool fDelayedAutostart; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SC_ACTION + { + public int Type; + public uint Delay; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SERVICE_FAILURE_ACTIONS + { + public uint dwResetPeriod; + public string? lpRebootMsg; + public string? lpCommand; + public uint cActions; + public IntPtr lpsaActions; + } + + [LibraryImport("advapi32.dll", EntryPoint = "OpenSCManagerW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr OpenSCManager(string? machineName, string? databaseName, uint access); + + [LibraryImport("advapi32.dll", EntryPoint = "OpenServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr OpenService(IntPtr scManager, string serviceName, uint access); + + [LibraryImport("advapi32.dll", EntryPoint = "CreateServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr CreateService( + IntPtr scManager, + string serviceName, + string displayName, + uint desiredAccess, + uint serviceType, + uint startType, + uint errorControl, + string binaryPathName, + string? loadOrderGroup, + IntPtr tagId, + string? dependencies, + string? serviceStartName, + string? password); + + [LibraryImport("advapi32.dll", EntryPoint = "ChangeServiceConfigW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool ChangeServiceConfig( + IntPtr service, + uint serviceType, + uint startType, + uint errorControl, + string? binaryPathName, + string? loadOrderGroup, + IntPtr tagId, + string? dependencies, + string? serviceStartName, + string? password, + string? displayName); + + [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_DESCRIPTION info); + + [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_DELAYED_AUTO_START_INFO info); + + [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_FAILURE_ACTIONS info); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool DeleteService(IntPtr service); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseServiceHandle(IntPtr handle); + + internal static Win32Exception LastError(string operation) + => new(Marshal.GetLastPInvokeError(), $"{operation} failed"); +} diff --git a/src/Agent/Service/ServiceLifecycle.cs b/src/Agent/Service/ServiceLifecycle.cs new file mode 100644 index 0000000..9eafa4b --- /dev/null +++ b/src/Agent/Service/ServiceLifecycle.cs @@ -0,0 +1,263 @@ +using System.Runtime.InteropServices; +using System.ServiceProcess; +using Shared.Infrastructure.Constants; +using static Agent.Service.ServiceControlApi; + +namespace Agent.Service; + +/// +/// Idempotent Windows service lifecycle operations using Windows APIs +/// (never sc.exe). Install creates or updates the registration, sets +/// Automatic (Delayed Start), description, and a restart recovery policy. +/// +public static class ServiceLifecycle +{ + private static readonly TimeSpan StateChangeTimeout = TimeSpan.FromSeconds(60); + private static readonly TimeSpan RecoveryRestartDelay = TimeSpan.FromSeconds(30); + + public static int Install() + { + var binaryPath = $"\"{Environment.ProcessPath ?? throw new InvalidOperationException("Cannot determine executable path.")}\""; + + var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); + if (scm == IntPtr.Zero) + { + throw LastError("OpenSCManager (administrator rights required)"); + } + + try + { + var service = OpenService(scm, Branding.AgentServiceName, SERVICE_ALL_ACCESS); + if (service == IntPtr.Zero) + { + service = CreateService( + scm, + Branding.AgentServiceName, + Branding.AgentServiceDisplayName, + SERVICE_ALL_ACCESS, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + binaryPath, + loadOrderGroup: null, + tagId: IntPtr.Zero, + dependencies: null, + serviceStartName: null, // LocalSystem + password: null); + + if (service == IntPtr.Zero) + { + throw LastError("CreateService"); + } + + Console.WriteLine($"Service '{Branding.AgentServiceName}' created."); + } + else + { + // Update binary path/display name in case the binary moved. + if (!ChangeServiceConfig( + service, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + binaryPath, + loadOrderGroup: null, + tagId: IntPtr.Zero, + dependencies: null, + serviceStartName: null, + password: null, + Branding.AgentServiceDisplayName)) + { + throw LastError("ChangeServiceConfig"); + } + + Console.WriteLine($"Service '{Branding.AgentServiceName}' updated."); + } + + try + { + ApplyMetadata(service); + } + finally + { + CloseServiceHandle(service); + } + + return 0; + } + finally + { + CloseServiceHandle(scm); + } + } + + private static void ApplyMetadata(IntPtr service) + { + var description = new SERVICE_DESCRIPTION { lpDescription = Branding.AgentServiceDescription }; + if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, ref description)) + { + throw LastError("ChangeServiceConfig2(description)"); + } + + var delayed = new SERVICE_DELAYED_AUTO_START_INFO { fDelayedAutostart = true }; + if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, ref delayed)) + { + throw LastError("ChangeServiceConfig2(delayed auto start)"); + } + + // Recovery: restart on first, second and subsequent failures. + var actions = new SC_ACTION[] + { + new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds }, + new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds }, + new() { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds }, + }; + + var actionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf() * actions.Length); + try + { + for (var i = 0; i < actions.Length; i++) + { + Marshal.StructureToPtr(actions[i], actionsPtr + i * Marshal.SizeOf(), false); + } + + var failureActions = new SERVICE_FAILURE_ACTIONS + { + dwResetPeriod = (uint)TimeSpan.FromDays(1).TotalSeconds, + lpRebootMsg = null, + lpCommand = null, + cActions = (uint)actions.Length, + lpsaActions = actionsPtr, + }; + + if (!ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS, ref failureActions)) + { + throw LastError("ChangeServiceConfig2(failure actions)"); + } + } + finally + { + Marshal.FreeHGlobal(actionsPtr); + } + } + + public static int Remove() + { + if (!Exists()) + { + Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed."); + return 0; + } + + Stop(); + + var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); + if (scm == IntPtr.Zero) + { + throw LastError("OpenSCManager (administrator rights required)"); + } + + try + { + var service = OpenService(scm, Branding.AgentServiceName, SERVICE_ALL_ACCESS); + if (service == IntPtr.Zero) + { + Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed."); + return 0; + } + + try + { + if (!DeleteService(service)) + { + throw LastError("DeleteService"); + } + } + finally + { + CloseServiceHandle(service); + } + + Console.WriteLine($"Service '{Branding.AgentServiceName}' removed."); + return 0; + } + finally + { + CloseServiceHandle(scm); + } + } + + public static int Start() + { + if (!Exists()) + { + Console.Error.WriteLine($"Service '{Branding.AgentServiceName}' is not installed."); + return 1; + } + + using var controller = new ServiceController(Branding.AgentServiceName); + if (controller.Status is ServiceControllerStatus.Running) + { + Console.WriteLine("Service is already running."); + return 0; + } + + if (controller.Status is not ServiceControllerStatus.StartPending) + { + controller.Start(); + } + + controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout); + Console.WriteLine("Service started."); + return 0; + } + + public static int Stop() + { + if (!Exists()) + { + Console.WriteLine($"Service '{Branding.AgentServiceName}' is not installed."); + return 0; + } + + using var controller = new ServiceController(Branding.AgentServiceName); + if (controller.Status is ServiceControllerStatus.Stopped) + { + Console.WriteLine("Service is already stopped."); + return 0; + } + + if (controller.CanStop) + { + controller.Stop(); + } + + controller.WaitForStatus(ServiceControllerStatus.Stopped, StateChangeTimeout); + Console.WriteLine("Service stopped."); + return 0; + } + + public static int Status() + { + string state; + var installed = Exists(); + if (installed) + { + using var controller = new ServiceController(Branding.AgentServiceName); + state = controller.Status.ToString(); + } + else + { + state = "NotInstalled"; + } + + // Machine-readable line first, human-readable after. + Console.WriteLine($"{{\"service\":\"{Branding.AgentServiceName}\",\"installed\":{(installed ? "true" : "false")},\"state\":\"{state}\"}}"); + Console.WriteLine($"Service '{Branding.AgentServiceDisplayName}': {state}"); + return 0; + } + + private static bool Exists() + => ServiceController.GetServices().Any(s => + string.Equals(s.ServiceName, Branding.AgentServiceName, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/Agent/Shell/ConPtyInterop.cs b/src/Agent/Shell/ConPtyInterop.cs new file mode 100644 index 0000000..d1336e1 --- /dev/null +++ b/src/Agent/Shell/ConPtyInterop.cs @@ -0,0 +1,119 @@ +using System.Runtime.InteropServices; + +namespace Agent.Shell; + +/// +/// Win32 Pseudoconsole (ConPTY) + process-creation interop. ConPTY ships in +/// all supported modern Windows versions, so no WinPTY fallback is bundled. +/// +internal static partial class ConPtyInterop +{ + internal const int STARTF_USESTDHANDLES = 0x00000100; + internal const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; + internal const int PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016; + + [StructLayout(LayoutKind.Sequential)] + internal struct COORD + { + public short X; + public short Y; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct STARTUPINFOEX + { + public STARTUPINFO StartupInfo; + public IntPtr lpAttributeList; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct STARTUPINFO + { + public int cb; + public string? lpReserved; + public string? lpDesktop; + public string? lpTitle; + public int dwX; + public int dwY; + public int dwXSize; + public int dwYSize; + public int dwXCountChars; + public int dwYCountChars; + public int dwFillAttribute; + public int dwFlags; + public short wShowWindow; + public short cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public int dwProcessId; + public int dwThreadId; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SECURITY_ATTRIBUTES + { + public int nLength; + public IntPtr lpSecurityDescriptor; + public int bInheritHandle; + } + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial int CreatePseudoConsole(COORD size, IntPtr hInput, IntPtr hOutput, uint dwFlags, out IntPtr phPC); + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial int ResizePseudoConsole(IntPtr hPC, COORD size); + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial void ClosePseudoConsole(IntPtr hPC); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, IntPtr lpPipeAttributes, int nSize); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseHandle(IntPtr hObject); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern bool CreateProcessW( + string? lpApplicationName, + string lpCommandLine, + IntPtr lpProcessAttributes, + IntPtr lpThreadAttributes, + [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, + uint dwCreationFlags, + IntPtr lpEnvironment, + string? lpCurrentDirectory, + ref STARTUPINFOEX lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool InitializeProcThreadAttributeList( + IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize); + + [DllImport("kernel32.dll", SetLastError = true)] + internal static extern bool UpdateProcThreadAttribute( + IntPtr lpAttributeList, uint dwFlags, IntPtr attribute, IntPtr lpValue, + IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool DeleteProcThreadAttributeList(IntPtr lpAttributeList); + + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool TerminateProcess(IntPtr hProcess, uint uExitCode); +} diff --git a/src/Agent/Shell/ConPtySession.cs b/src/Agent/Shell/ConPtySession.cs new file mode 100644 index 0000000..7f4eaaf --- /dev/null +++ b/src/Agent/Shell/ConPtySession.cs @@ -0,0 +1,215 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +using static Agent.Shell.ConPtyInterop; + +namespace Agent.Shell; + +/// +/// A live ConPTY-backed shell process. Terminal output is delivered via +/// ; input is written with . +/// +public sealed class ConPtySession : IDisposable +{ + private IntPtr pseudoConsole = IntPtr.Zero; + private IntPtr attributeList = IntPtr.Zero; + private PROCESS_INFORMATION processInfo; + + private SafeFileHandle? inputWriteHandle; + private FileStream? inputStream; + private FileStream? outputStream; + + private readonly CancellationTokenSource lifetime = new(); + private bool disposed; + + /// Raised with raw terminal output bytes as they arrive. + public event Action>? OutputReceived; + + /// Raised when the shell process exits. + public event Action? Exited; + + public void Start(string commandLine, int cols, int rows) + { + // Two pipes: one the PTY reads input from, one it writes output to. + if (!CreatePipe(out var inputRead, out var inputWrite, IntPtr.Zero, 0)) + { + throw new InvalidOperationException("CreatePipe(input) failed."); + } + + if (!CreatePipe(out var outputRead, out var outputWrite, IntPtr.Zero, 0)) + { + throw new InvalidOperationException("CreatePipe(output) failed."); + } + + var size = new COORD { X = (short)Math.Clamp(cols, 1, short.MaxValue), Y = (short)Math.Clamp(rows, 1, short.MaxValue) }; + var hr = CreatePseudoConsole(size, inputRead, outputWrite, 0, out pseudoConsole); + if (hr != 0) + { + throw new InvalidOperationException($"CreatePseudoConsole failed (HRESULT 0x{hr:X8})."); + } + + // The PTY owns these ends now. + CloseHandle(inputRead); + CloseHandle(outputWrite); + + inputWriteHandle = new SafeFileHandle(inputWrite, ownsHandle: true); + inputStream = new FileStream(inputWriteHandle, FileAccess.Write); + outputStream = new FileStream(new SafeFileHandle(outputRead, ownsHandle: true), FileAccess.Read); + + StartProcess(commandLine); + + _ = Task.Run(PumpOutputAsync); + _ = Task.Run(WatchProcessAsync); + } + + private void StartProcess(string commandLine) + { + var startupInfo = new STARTUPINFOEX(); + startupInfo.StartupInfo.cb = Marshal.SizeOf(); + + var size = IntPtr.Zero; + InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size); + attributeList = Marshal.AllocHGlobal(size); + startupInfo.lpAttributeList = attributeList; + + if (!InitializeProcThreadAttributeList(attributeList, 1, 0, ref size)) + { + throw new InvalidOperationException("InitializeProcThreadAttributeList failed."); + } + + if (!UpdateProcThreadAttribute( + attributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, + pseudoConsole, IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) + { + throw new InvalidOperationException("UpdateProcThreadAttribute failed."); + } + + if (!CreateProcessW( + lpApplicationName: null, + lpCommandLine: commandLine, + lpProcessAttributes: IntPtr.Zero, + lpThreadAttributes: IntPtr.Zero, + bInheritHandles: false, + dwCreationFlags: EXTENDED_STARTUPINFO_PRESENT, + lpEnvironment: IntPtr.Zero, + lpCurrentDirectory: null, + lpStartupInfo: ref startupInfo, + lpProcessInformation: out processInfo)) + { + throw new InvalidOperationException($"CreateProcess failed (Win32 {Marshal.GetLastWin32Error()})."); + } + } + + private async Task PumpOutputAsync() + { + var buffer = new byte[4096]; + try + { + while (!lifetime.IsCancellationRequested) + { + var read = await outputStream!.ReadAsync(buffer, lifetime.Token); + if (read == 0) + { + break; + } + + OutputReceived?.Invoke(buffer.AsMemory(0, read).ToArray()); + } + } + catch (Exception) + { + // Pipe closed on shutdown. + } + } + + private async Task WatchProcessAsync() + { + try + { + while (!lifetime.IsCancellationRequested) + { + if (WaitForSingleObject(processInfo.hProcess, 250) == 0) + { + break; + } + + await Task.Delay(50, lifetime.Token); + } + } + catch (OperationCanceledException) + { + return; + } + + Exited?.Invoke(); + } + + public async Task WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) + { + if (inputStream is null) + { + return; + } + + await inputStream.WriteAsync(data, cancellationToken); + await inputStream.FlushAsync(cancellationToken); + } + + public void Resize(int cols, int rows) + { + if (pseudoConsole != IntPtr.Zero) + { + ResizePseudoConsole(pseudoConsole, new COORD + { + X = (short)Math.Clamp(cols, 1, short.MaxValue), + Y = (short)Math.Clamp(rows, 1, short.MaxValue), + }); + } + } + + public void Dispose() + { + if (disposed) + { + return; + } + + disposed = true; + lifetime.Cancel(); + + if (pseudoConsole != IntPtr.Zero) + { + ClosePseudoConsole(pseudoConsole); + pseudoConsole = IntPtr.Zero; + } + + try + { + inputStream?.Dispose(); + outputStream?.Dispose(); + } + catch (IOException) + { + // Pipe already closed. + } + + if (processInfo.hProcess != IntPtr.Zero) + { + if (WaitForSingleObject(processInfo.hProcess, 0) != 0) + { + TerminateProcess(processInfo.hProcess, 0); + } + + CloseHandle(processInfo.hThread); + CloseHandle(processInfo.hProcess); + } + + if (attributeList != IntPtr.Zero) + { + DeleteProcThreadAttributeList(attributeList); + Marshal.FreeHGlobal(attributeList); + attributeList = IntPtr.Zero; + } + + lifetime.Dispose(); + } +} diff --git a/src/Agent/Shell/ShellCommandListener.cs b/src/Agent/Shell/ShellCommandListener.cs new file mode 100644 index 0000000..2bdac43 --- /dev/null +++ b/src/Agent/Shell/ShellCommandListener.cs @@ -0,0 +1,100 @@ +using Agent.Configuration; +using Agent.Messaging; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; +using Shared.Contracts.Messages; +using Shared.Infrastructure.Nats; + +namespace Agent.Shell; + +/// +/// Subscribes to Core NATS shell commands (open/input/resize/close) and drives +/// the . Shell traffic stays on Core NATS — never +/// JetStream. Honors the AllowRemoteShell policy. +/// +public sealed class ShellCommandListener( + NatsConnection connection, + AgentPublisher publisher, + AgentConfiguration configuration, + ILogger logger) : IDisposable +{ + private readonly ShellManager manager = new(publisher, logger); + + public async Task RunAsync(CancellationToken cancellationToken) + { + if (!configuration.AllowRemoteShell.Value) + { + logger.LogInformation("Remote shell disabled by policy; not listening for shell commands"); + return; + } + + // command.shell.open | command.shell.input | command.shell.resize | command.shell.close + var subject = $"agent.{publisher.ClientId}.command.shell.*"; + + await foreach (var msg in connection.SubscribeAsync(subject, cancellationToken: cancellationToken)) + { + if (msg.Data is null || msg.Data.Length == 0) + { + continue; + } + + try + { + await HandleAsync(MessageEnvelope.FromUtf8Bytes(msg.Data), cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to handle shell command on {Subject}", msg.Subject); + } + } + } + + private async Task HandleAsync(MessageEnvelope? envelope, CancellationToken cancellationToken) + { + if (envelope is null) + { + return; + } + + switch (envelope.MessageType) + { + case MessageTypes.CommandShellOpen: + var open = envelope.GetPayload(); + if (open is not null) + { + manager.Open(open, cancellationToken); + } + + break; + + case MessageTypes.CommandShellInput: + var input = envelope.GetPayload(); + if (input is not null) + { + await manager.WriteAsync(input, cancellationToken); + } + + break; + + case MessageTypes.CommandShellResize: + var resize = envelope.GetPayload(); + if (resize is not null) + { + manager.Resize(resize); + } + + break; + + case MessageTypes.CommandShellClose: + var close = envelope.GetPayload(); + if (close is not null) + { + manager.Close(close.SessionId, close.Reason ?? "closed by backend"); + } + + break; + } + } + + public void Dispose() => manager.Dispose(); +} diff --git a/src/Agent/Shell/ShellManager.cs b/src/Agent/Shell/ShellManager.cs new file mode 100644 index 0000000..4782f89 --- /dev/null +++ b/src/Agent/Shell/ShellManager.cs @@ -0,0 +1,192 @@ +using Agent.Messaging; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Agent.Shell; + +/// +/// Manages interactive ConPTY shell sessions for one agent. MVP allows a +/// single active session per device; opening a new one closes the previous. +/// Output is published as base64 over Core NATS with a monotonic sequence. +/// +public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDisposable +{ + private readonly Lock gate = new(); + private ActiveShell? current; + + private sealed class ActiveShell + { + public required Guid SessionId { get; init; } + public required ConPtySession Pty { get; init; } + public required Timer IdleTimer { get; init; } + public required Timer MaxLifetimeTimer { get; init; } + public long Sequence; + public DateTimeOffset LastActivityUtc = DateTimeOffset.UtcNow; + } + + public void Open(ShellOpenCommandPayload command, CancellationToken cancellationToken) + { + CloseCurrent("superseded by new session"); + + var shell = ResolveShellCommand(); + var pty = new ConPtySession(); + Guid sessionId = command.SessionId; + + var active = new ActiveShell + { + SessionId = sessionId, + Pty = pty, + IdleTimer = new Timer(_ => OnIdleTimeout(sessionId), null, ProtocolDefaults.ShellIdleTimeout, Timeout.InfiniteTimeSpan), + MaxLifetimeTimer = new Timer(_ => OnMaxLifetime(sessionId), null, ProtocolDefaults.ShellMaxLifetime, Timeout.InfiniteTimeSpan), + }; + + pty.OutputReceived += data => PublishOutput(active, data); + pty.Exited += () => Close(sessionId, "shell process exited"); + + lock (gate) + { + current = active; + } + + try + { + pty.Start(shell, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1)); + PublishState(sessionId, ShellSessionState.Open, null); + logger.LogInformation("Shell session {SessionId} opened ({Shell})", sessionId, shell); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to open shell session {SessionId}", sessionId); + PublishState(sessionId, ShellSessionState.Failed, ex.Message); + Close(sessionId, "open failed"); + } + } + + public async Task WriteAsync(ShellInputPayload input, CancellationToken cancellationToken) + { + ActiveShell? active; + lock (gate) + { + active = current?.SessionId == input.SessionId ? current : null; + } + + if (active is null) + { + return; + } + + active.LastActivityUtc = DateTimeOffset.UtcNow; + active.IdleTimer.Change(ProtocolDefaults.ShellIdleTimeout, Timeout.InfiniteTimeSpan); + + try + { + var bytes = Convert.FromBase64String(input.DataBase64); + await active.Pty.WriteAsync(bytes, cancellationToken); + } + catch (FormatException) + { + logger.LogWarning("Discarded malformed shell input for {SessionId}", input.SessionId); + } + } + + public void Resize(ShellResizePayload resize) + { + lock (gate) + { + if (current?.SessionId == resize.SessionId) + { + current.Pty.Resize(resize.Cols, resize.Rows); + } + } + } + + public void Close(Guid sessionId, string reason) + { + ActiveShell? active; + lock (gate) + { + if (current?.SessionId != sessionId) + { + return; + } + + active = current; + current = null; + } + + DisposeShell(active, reason); + PublishState(sessionId, ShellSessionState.Closed, reason); + logger.LogInformation("Shell session {SessionId} closed: {Reason}", sessionId, reason); + } + + private void CloseCurrent(string reason) + { + Guid? sessionId; + lock (gate) + { + sessionId = current?.SessionId; + } + + if (sessionId is not null) + { + Close(sessionId.Value, reason); + } + } + + private void OnIdleTimeout(Guid sessionId) => Close(sessionId, "idle timeout"); + + private void OnMaxLifetime(Guid sessionId) => Close(sessionId, "maximum session lifetime reached"); + + private void PublishOutput(ActiveShell active, ReadOnlyMemory data) + { + var sequence = Interlocked.Increment(ref active.Sequence); + var payload = new ShellOutputPayload(active.SessionId, sequence, Convert.ToBase64String(data.Span)); + + _ = publisher.PublishAsync( + NatsSubjects.AgentShellOutput(publisher.ClientId, active.SessionId), + MessageTypes.ShellOutput, + payload); + } + + private void PublishState(Guid sessionId, ShellSessionState state, string? message) + { + _ = publisher.PublishAsync( + NatsSubjects.AgentShellState(publisher.ClientId, sessionId), + MessageTypes.ShellState, + new ShellStatePayload(sessionId, state, message)); + } + + private static void DisposeShell(ActiveShell? active, string reason) + { + if (active is null) + { + return; + } + + active.IdleTimer.Dispose(); + active.MaxLifetimeTimer.Dispose(); + active.Pty.Dispose(); + _ = reason; + } + + /// Prefers PowerShell 7 (pwsh) when present, else Windows PowerShell. + private static string ResolveShellCommand() + { + var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + var pwsh = Path.Combine(programFiles, "PowerShell", "7", "pwsh.exe"); + if (File.Exists(pwsh)) + { + return $"\"{pwsh}\" -NoLogo"; + } + + var windowsPowerShell = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.System), + "WindowsPowerShell", "v1.0", "powershell.exe"); + return $"\"{windowsPowerShell}\" -NoLogo"; + } + + public void Dispose() => CloseCurrent("agent shutting down"); +} diff --git a/src/Agent/Storage/JobHistoryStore.cs b/src/Agent/Storage/JobHistoryStore.cs new file mode 100644 index 0000000..796822d --- /dev/null +++ b/src/Agent/Storage/JobHistoryStore.cs @@ -0,0 +1,152 @@ +using Microsoft.Data.Sqlite; +using Shared.Infrastructure.Constants; + +namespace Agent.Storage; + +/// +/// Durable local record of handled job ids so JetStream redelivery or agent +/// restart never executes the same script twice. Retains the most recent +/// completed entries (bounded) in a lightweight SQLite database. +/// +public sealed class JobHistoryStore : IDisposable +{ + private readonly SqliteConnection connection; + private readonly Lock writeLock = new(); + + public JobHistoryStore() + : this(Path.Combine(Branding.AgentProgramDataDirectory, Branding.JobHistoryFileName)) + { + } + + public JobHistoryStore(string databasePath) + { + var directory = Path.GetDirectoryName(databasePath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + connection = new SqliteConnection($"Data Source={databasePath}"); + connection.Open(); + + using var command = connection.CreateCommand(); + command.CommandText = """ + CREATE TABLE IF NOT EXISTS HandledJobs ( + JobId TEXT PRIMARY KEY, + AcceptedUtc TEXT NOT NULL, + CompletedUtc TEXT NULL, + State TEXT NULL + ); + + CREATE TABLE IF NOT EXISTS DownloadCache ( + DestinationPath TEXT PRIMARY KEY, + ObjectKey TEXT NULL, + ETag TEXT NULL, + Sha256 TEXT NULL, + SizeBytes INTEGER NULL, + DownloadedUtc TEXT NOT NULL + ); + """; + command.ExecuteNonQuery(); + } + + /// What the agent knows about a previously downloaded file. + public sealed record DownloadCacheEntry(string? ETag, string? Sha256, long? SizeBytes); + + public DownloadCacheEntry? GetDownloadCache(string destinationPath) + { + using var command = connection.CreateCommand(); + command.CommandText = + "SELECT ETag, Sha256, SizeBytes FROM DownloadCache WHERE DestinationPath = $path;"; + command.Parameters.AddWithValue("$path", destinationPath); + + using var reader = command.ExecuteReader(); + if (!reader.Read()) + { + return null; + } + + return new DownloadCacheEntry( + reader.IsDBNull(0) ? null : reader.GetString(0), + reader.IsDBNull(1) ? null : reader.GetString(1), + reader.IsDBNull(2) ? null : reader.GetInt64(2)); + } + + public void RecordDownload(string destinationPath, string? objectKey, string? etag, string? sha256, long sizeBytes) + { + lock (writeLock) + { + using var command = connection.CreateCommand(); + command.CommandText = """ + INSERT INTO DownloadCache (DestinationPath, ObjectKey, ETag, Sha256, SizeBytes, DownloadedUtc) + VALUES ($path, $key, $etag, $sha, $size, $utc) + ON CONFLICT(DestinationPath) DO UPDATE SET + ObjectKey = excluded.ObjectKey, + ETag = excluded.ETag, + Sha256 = excluded.Sha256, + SizeBytes = excluded.SizeBytes, + DownloadedUtc = excluded.DownloadedUtc; + """; + command.Parameters.AddWithValue("$path", destinationPath); + command.Parameters.AddWithValue("$key", (object?)objectKey ?? DBNull.Value); + command.Parameters.AddWithValue("$etag", (object?)etag ?? DBNull.Value); + command.Parameters.AddWithValue("$sha", (object?)sha256 ?? DBNull.Value); + command.Parameters.AddWithValue("$size", sizeBytes); + command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O")); + command.ExecuteNonQuery(); + } + } + + /// + /// Durably records a job as accepted. Returns false when the job was + /// already recorded (duplicate delivery) — the caller must not execute it. + /// + public bool TryRecordAccepted(Guid jobId) + { + lock (writeLock) + { + using var command = connection.CreateCommand(); + command.CommandText = "INSERT OR IGNORE INTO HandledJobs (JobId, AcceptedUtc) VALUES ($id, $utc);"; + command.Parameters.AddWithValue("$id", jobId.ToString("D")); + command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O")); + return command.ExecuteNonQuery() == 1; + } + } + + public void MarkCompleted(Guid jobId, string state) + { + lock (writeLock) + { + using var command = connection.CreateCommand(); + command.CommandText = "UPDATE HandledJobs SET CompletedUtc = $utc, State = $state WHERE JobId = $id;"; + command.Parameters.AddWithValue("$utc", DateTimeOffset.UtcNow.ToString("O")); + command.Parameters.AddWithValue("$state", state); + command.Parameters.AddWithValue("$id", jobId.ToString("D")); + command.ExecuteNonQuery(); + + Prune(); + } + } + + public bool IsHandled(Guid jobId) + { + using var command = connection.CreateCommand(); + command.CommandText = "SELECT 1 FROM HandledJobs WHERE JobId = $id;"; + command.Parameters.AddWithValue("$id", jobId.ToString("D")); + return command.ExecuteScalar() is not null; + } + + private void Prune() + { + using var command = connection.CreateCommand(); + command.CommandText = """ + DELETE FROM HandledJobs WHERE JobId NOT IN ( + SELECT JobId FROM HandledJobs ORDER BY AcceptedUtc DESC LIMIT $keep + ); + """; + command.Parameters.AddWithValue("$keep", Shared.Infrastructure.Constants.ProtocolDefaults.JobIdempotencyRetention); + command.ExecuteNonQuery(); + } + + public void Dispose() => connection.Dispose(); +} diff --git a/src/Agent/Storage/RuntimeStateStore.cs b/src/Agent/Storage/RuntimeStateStore.cs new file mode 100644 index 0000000..c2aa28d --- /dev/null +++ b/src/Agent/Storage/RuntimeStateStore.cs @@ -0,0 +1,73 @@ +using Agent.Configuration; +using Shared.Infrastructure.Constants; + +namespace Agent.Storage; + +/// +/// Runtime-managed registry state below the Runtime subkey, plus secure +/// deletion of the bootstrap token after successful enrollment. +/// +public sealed class RuntimeStateStore(IRegistryStore registry) +{ + public string? ClientId + { + get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.ClientId); + set => WriteOrDelete(AgentRuntimeKeys.ClientId, value); + } + + public string? EnrollmentId + { + get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.EnrollmentId); + set => WriteOrDelete(AgentRuntimeKeys.EnrollmentId, value); + } + + public DateTimeOffset? LastEnrollmentUtc + { + get => ReadTimestamp(AgentRuntimeKeys.LastEnrollmentUtc); + set => WriteTimestamp(AgentRuntimeKeys.LastEnrollmentUtc, value); + } + + public DateTimeOffset? LastConnectedUtc + { + get => ReadTimestamp(AgentRuntimeKeys.LastConnectedUtc); + set => WriteTimestamp(AgentRuntimeKeys.LastConnectedUtc, value); + } + + public DateTimeOffset? CredentialExpiresUtc + { + get => ReadTimestamp(AgentRuntimeKeys.CredentialExpiresUtc); + set => WriteTimestamp(AgentRuntimeKeys.CredentialExpiresUtc, value); + } + + /// Removes the one-time bootstrap token from the normal registry key. + public void ClearBootstrapToken() + => registry.DeleteValue(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken); + + /// Removes all runtime state (explicit full uninstall only). + public void Purge() + => registry.DeleteKeyTree(Branding.AgentRuntimeRegistryKey); + + private DateTimeOffset? ReadTimestamp(string name) + => DateTimeOffset.TryParse( + registry.ReadString(Branding.AgentRuntimeRegistryKey, name), + null, + System.Globalization.DateTimeStyles.RoundtripKind, + out var value) + ? value + : null; + + private void WriteTimestamp(string name, DateTimeOffset? value) + => WriteOrDelete(name, value?.ToUniversalTime().ToString("O")); + + private void WriteOrDelete(string name, string? value) + { + if (value is null) + { + registry.DeleteValue(Branding.AgentRuntimeRegistryKey, name); + } + else + { + registry.WriteString(Branding.AgentRuntimeRegistryKey, name, value); + } + } +} diff --git a/src/Backend/Api/BootstrapTokenEndpoints.cs b/src/Backend/Api/BootstrapTokenEndpoints.cs new file mode 100644 index 0000000..98831f8 --- /dev/null +++ b/src/Backend/Api/BootstrapTokenEndpoints.cs @@ -0,0 +1,83 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Security; + +namespace Backend.Api; + +public static class BootstrapTokenEndpoints +{ + public static void Map(WebApplication app) + { + app.MapPost(ApiRoutes.AdminBootstrapTokens, CreateAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapGet(ApiRoutes.AdminBootstrapTokens, ListAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + app.MapDelete(ApiRoutes.AdminBootstrapToken, RevokeAsync).RequireAuthorization(AuthConstants.PolicyAdmin); + } + + private static async Task CreateAsync( + CreateBootstrapTokenRequest? request, + AppDbContext db, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var lifetime = request?.ValidMinutes is > 0 + ? TimeSpan.FromMinutes(request.ValidMinutes.Value) + : ProtocolDefaults.BootstrapTokenDefaultLifetime; + var maxUses = request?.MaxUses is > 0 ? request.MaxUses.Value : ProtocolDefaults.BootstrapTokenDefaultMaxUses; + + // Plaintext exists exactly once: in this response. Only the hash is stored. + var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes); + var actor = context.User.Identity?.Name; + + var entity = new BootstrapTokenEntity + { + Id = Guid.NewGuid(), + TokenHash = TokenHashing.Sha256Hex(token), + CreatedUtc = DateTimeOffset.UtcNow, + ExpiresUtc = DateTimeOffset.UtcNow + lifetime, + MaxUses = maxUses, + Note = request?.Note, + CreatedBy = actor, + }; + db.BootstrapTokens.Add(entity); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "bootstrap-token-created", actor, + detail: $"id={entity.Id} maxUses={maxUses}", cancellationToken: cancellationToken); + + return Results.Ok(ToDto(entity, token)); + } + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var tokens = await db.BootstrapTokens.AsNoTracking() + .OrderByDescending(t => t.CreatedUtc) + .Take(100) + .ToListAsync(cancellationToken); + return Results.Ok(tokens.Select(t => ToDto(t, token: null)).ToList()); + } + + private static async Task RevokeAsync( + Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var entity = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + entity.Revoked = true; + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "bootstrap-token-revoked", context.User.Identity?.Name, + detail: $"id={id}", cancellationToken: cancellationToken); + + return Results.NoContent(); + } + + private static BootstrapTokenDto ToDto(BootstrapTokenEntity entity, string? token) => new( + entity.Id, token, entity.CreatedUtc, entity.ExpiresUtc, + entity.MaxUses, entity.Uses, entity.Revoked, entity.Note, entity.CreatedBy); +} diff --git a/src/Backend/Api/DeviceEndpoints.cs b/src/Backend/Api/DeviceEndpoints.cs new file mode 100644 index 0000000..f62c11e --- /dev/null +++ b/src/Backend/Api/DeviceEndpoints.cs @@ -0,0 +1,108 @@ +using System.Text.Json; +using Backend.Auth; +using Backend.Data; +using Backend.Jobs; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Api; + +public static class DeviceEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Devices, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapGet(ApiRoutes.Device, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.DeviceInventory, RefreshInventoryAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var devices = await db.Devices.AsNoTracking() + .OrderBy(d => d.Hostname) + .ToListAsync(cancellationToken); + + var now = DateTimeOffset.UtcNow; + return Results.Ok(devices.Select(d => ToDto(d, now)).ToList()); + } + + private static async Task GetAsync( + string clientId, AppDbContext db, Groups.DeviceGroupService groups, CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId)) + { + return Results.BadRequest(); + } + + var device = await db.Devices.AsNoTracking() + .Include(d => d.Inventory) + .SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return Results.NotFound(); + } + + InventoryReport? report = null; + if (device.Inventory is not null) + { + report = JsonDefaults.Deserialize(device.Inventory.ReportJson); + } + + return Results.Ok(new DeviceDetailDto( + ToDto(device, DateTimeOffset.UtcNow), + report, + device.Inventory?.UpdatedUtc, + await groups.GetGroupsForDeviceAsync(clientId, cancellationToken))); + } + + private static async Task RefreshInventoryAsync( + string clientId, + AppDbContext db, + CommandDispatcher dispatcher, + CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId)) + { + return Results.BadRequest(); + } + + var exists = await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken); + if (!exists) + { + return Results.NotFound(); + } + + var dispatched = await dispatcher.DispatchInventoryRefreshAsync(clientId, "manual refresh", cancellationToken); + return dispatched + ? Results.Accepted() + : Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Messaging unavailable."); + } + + internal static DeviceDto ToDto(DeviceEntity device, DateTimeOffset now) + { + IReadOnlyList addresses = []; + if (!string.IsNullOrEmpty(device.IpAddressesJson)) + { + addresses = JsonDefaults.Deserialize>(device.IpAddressesJson) ?? []; + } + + return new DeviceDto( + ClientId: device.ClientId, + Hostname: device.Hostname, + Manufacturer: device.Manufacturer, + Model: device.Model, + OsCaption: device.OsCaption, + OsVersion: device.OsVersion, + AgentVersion: device.AgentVersion, + IpAddresses: addresses, + Status: ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now), + LastSeenUtc: device.LastSeenUtc, + EnrolledUtc: device.EnrolledUtc, + Tags: Groups.DeviceGroupService.ParseTags(device.TagsJson), + IsOrphaned: device.IsOrphaned); + } +} diff --git a/src/Backend/Api/DeviceLifecycleOptions.cs b/src/Backend/Api/DeviceLifecycleOptions.cs new file mode 100644 index 0000000..237a3e3 --- /dev/null +++ b/src/Backend/Api/DeviceLifecycleOptions.cs @@ -0,0 +1,41 @@ +using Shared.Infrastructure.Constants; + +namespace Backend.Api; + +/// +/// What happens to devices that stop checking in. +/// +/// A device silent for longer than the window is orphaned: its +/// credential refresh is refused and no work is dispatched to it, even if it +/// reappears. Recovery is deliberate — push a fresh bootstrap token to the +/// endpoint and the agent re-enrolls, which clears the flag and reuses the +/// same device record. +/// +/// The window is centrally defaulted by +/// (30 days) and +/// overridden with DEVICE_ORPHAN_AFTER_DAYS. Set that to 0 to +/// disable orphaning entirely, so silent devices simply go Stale then Offline +/// and reconnect on their own. +/// +public sealed class DeviceLifecycleOptions +{ + public int OrphanAfterDays { get; init; } = ProtocolDefaults.DefaultOrphanAfterDays; + + public bool OrphaningEnabled => OrphanAfterDays > 0; + + public TimeSpan OrphanAfter => TimeSpan.FromDays(OrphanAfterDays); + + public static DeviceLifecycleOptions FromConfiguration(IConfiguration configuration) + { + var raw = configuration["DEVICE_ORPHAN_AFTER_DAYS"]; + + // Unset falls back to the central default; 0 explicitly disables. + var days = string.IsNullOrWhiteSpace(raw) + ? ProtocolDefaults.DefaultOrphanAfterDays + : int.TryParse(raw, out var parsed) && parsed >= 0 + ? parsed + : ProtocolDefaults.DefaultOrphanAfterDays; + + return new DeviceLifecycleOptions { OrphanAfterDays = days }; + } +} diff --git a/src/Backend/Auth/AuthConstants.cs b/src/Backend/Auth/AuthConstants.cs new file mode 100644 index 0000000..d6ae124 --- /dev/null +++ b/src/Backend/Auth/AuthConstants.cs @@ -0,0 +1,23 @@ +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// Auth scheme names, claim types and authorization policy names. +public static class AuthConstants +{ + public const string CookieScheme = "ExecuteRCookie"; + public const string OidcScheme = "oidc"; + + public const string RoleClaim = "role"; + public const string ProviderClaim = "auth_provider"; + + public const string ProviderLocal = "local"; + public const string ProviderOidc = "oidc"; + + // Policy names (generic — no product branding). + public const string PolicyViewer = "viewer"; + public const string PolicyOperator = "operator"; + public const string PolicyAdmin = "admin"; + + public static string RoleName(UserRole role) => role.ToString(); +} diff --git a/src/Backend/Auth/AuthEndpoints.cs b/src/Backend/Auth/AuthEndpoints.cs new file mode 100644 index 0000000..3bfe2f4 --- /dev/null +++ b/src/Backend/Auth/AuthEndpoints.cs @@ -0,0 +1,93 @@ +using System.Security.Claims; +using Backend.Proxy; +using Backend.Security; +using Microsoft.AspNetCore.Authentication; +using Shared.Contracts.Api; +using Shared.Contracts.Models; + +namespace Backend.Auth; + +public static class AuthEndpoints +{ + public static void Map(WebApplication app, OidcOptions oidc) + { + app.MapPost(ApiRoutes.AuthLogin, LoginAsync) + .RequireRateLimiting(RateLimitPolicies.Auth) + .AllowAnonymous(); + + app.MapPost(ApiRoutes.AuthLogout, (Delegate)LogoutAsync); + + 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." })) + .AllowAnonymous(); + + // OIDC completes at CallbackPath (handler-owned); this route lets the + // SPA finalize the app cookie mapping if needed. + app.MapGet(ApiRoutes.AuthOidcCallback, () => Results.Redirect("/")).AllowAnonymous(); + } + + private static async Task LoginAsync( + LoginRequest request, + UserService users, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + var remoteIp = ClientIp.EffectiveText(context); + + var user = await users.ValidateCredentialsAsync(request.Username, request.Password, cancellationToken); + if (user is null) + { + await audit.LogAsync(AuditCategories.Auth, "login-failed", + actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + return Results.Unauthorized(); + } + + var principal = AuthExtensions.BuildPrincipal( + user.Username, user.DisplayName, user.Role, AuthConstants.ProviderLocal); + await context.SignInAsync(AuthConstants.CookieScheme, principal); + CsrfProtection.IssueToken(context); + + await audit.LogAsync(AuditCategories.Auth, "login-succeeded", + actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); + + return Results.Ok(new SessionResponse( + true, user.Username, user.DisplayName, user.Role, AuthConstants.ProviderLocal)); + } + + private static async Task LogoutAsync(HttpContext context) + { + await context.SignOutAsync(AuthConstants.CookieScheme); + context.Response.Cookies.Delete(CsrfProtection.CookieName); + return Results.Ok(); + } + + private static IResult GetSession(HttpContext context) + { + var user = context.User; + if (user.Identity?.IsAuthenticated != true) + { + return Results.Ok(new SessionResponse(false, null, null, null, null)); + } + + // Ensure a CSRF token exists for this authenticated session. + if (!context.Request.Cookies.ContainsKey(CsrfProtection.CookieName)) + { + CsrfProtection.IssueToken(context); + } + + var roleName = user.FindFirstValue(ClaimTypes.Role); + _ = Enum.TryParse(roleName, out var role); + + return Results.Ok(new SessionResponse( + true, + user.Identity.Name, + user.FindFirstValue("display_name") ?? user.Identity.Name, + role, + user.FindFirstValue(AuthConstants.ProviderClaim) ?? AuthConstants.ProviderLocal)); + } +} diff --git a/src/Backend/Auth/AuthExtensions.cs b/src/Backend/Auth/AuthExtensions.cs new file mode 100644 index 0000000..a67dd49 --- /dev/null +++ b/src/Backend/Auth/AuthExtensions.cs @@ -0,0 +1,148 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// Wires cookie + optional OIDC authentication and role-based authorization. +public static class AuthExtensions +{ + public static void AddControlPlaneAuth(this WebApplicationBuilder builder, OidcOptions oidc) + { + var authBuilder = builder.Services + .AddAuthentication(options => + { + options.DefaultScheme = AuthConstants.CookieScheme; + options.DefaultChallengeScheme = oidc.IsUsable ? AuthConstants.OidcScheme : 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; + return Task.CompletedTask; + }; + options.Events.OnRedirectToAccessDenied = context => + { + 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(); + 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)); + } + }; + }); + } + + builder.Services.AddAuthorization(options => + { + options.AddPolicy(AuthConstants.PolicyViewer, policy => + policy.RequireRole(nameof(UserRole.Viewer), nameof(UserRole.Operator), nameof(UserRole.Admin))); + options.AddPolicy(AuthConstants.PolicyOperator, policy => + policy.RequireRole(nameof(UserRole.Operator), nameof(UserRole.Admin))); + options.AddPolicy(AuthConstants.PolicyAdmin, policy => + policy.RequireRole(nameof(UserRole.Admin))); + }); + } + + /// Builds the cookie principal for an authenticated user. + public static ClaimsPrincipal BuildPrincipal(string username, string? displayName, UserRole role, string provider) + { + var identity = new ClaimsIdentity(AuthConstants.CookieScheme, ClaimTypes.Name, ClaimTypes.Role); + identity.AddClaim(new Claim(ClaimTypes.Name, username)); + identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); + identity.AddClaim(new Claim(AuthConstants.ProviderClaim, provider)); + if (!string.IsNullOrWhiteSpace(displayName)) + { + identity.AddClaim(new Claim("display_name", displayName)); + } + + return new ClaimsPrincipal(identity); + } +} diff --git a/src/Backend/Auth/CsrfProtection.cs b/src/Backend/Auth/CsrfProtection.cs new file mode 100644 index 0000000..4e8291e --- /dev/null +++ b/src/Backend/Auth/CsrfProtection.cs @@ -0,0 +1,78 @@ +using System.Security.Cryptography; + +namespace Backend.Auth; + +/// +/// Double-submit-cookie CSRF protection for cookie-authenticated, +/// state-changing REST calls. The browser reads the non-HttpOnly +/// csrf_token cookie and echoes it in the X-CSRF-Token header; +/// the middleware requires the two to match. Bearer/enrollment endpoints and +/// safe methods are exempt. +/// +public static class CsrfProtection +{ + public const string CookieName = "csrf_token"; + public const string HeaderName = "X-CSRF-Token"; + + public static string IssueToken(HttpContext context) + { + var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + context.Response.Cookies.Append(CookieName, token, new CookieOptions + { + HttpOnly = false, // Must be readable by the SPA. + SameSite = SameSiteMode.Lax, + Secure = context.Request.IsHttps, + Path = "/", + }); + return token; + } + + public static RequestDelegate Middleware(RequestDelegate next) => async context => + { + if (RequiresValidation(context)) + { + var cookie = context.Request.Cookies[CookieName]; + var header = context.Request.Headers[HeaderName].ToString(); + + if (string.IsNullOrEmpty(cookie) + || string.IsNullOrEmpty(header) + || !CryptographicOperations.FixedTimeEquals( + System.Text.Encoding.UTF8.GetBytes(cookie), + System.Text.Encoding.UTF8.GetBytes(header))) + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + await context.Response.WriteAsJsonAsync(new { error = "CSRF validation failed." }); + return; + } + } + + await next(context); + }; + + private static bool RequiresValidation(HttpContext context) + { + var method = context.Request.Method; + if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method)) + { + return false; + } + + var path = context.Request.Path; + + // Enrollment endpoints are agent-to-server (no cookie); exempt. + if (path.StartsWithSegments("/api/enrollment")) + { + return false; + } + + // Login establishes the session; protected by rate limiting + credentials. + if (path.StartsWithSegments("/api/auth/login")) + { + return false; + } + + // Only guard cookie-authenticated API calls. + return path.StartsWithSegments("/api") + && context.Request.Cookies.ContainsKey("executer_session"); + } +} diff --git a/src/Backend/Auth/OidcOptions.cs b/src/Backend/Auth/OidcOptions.cs new file mode 100644 index 0000000..b8075e0 --- /dev/null +++ b/src/Backend/Auth/OidcOptions.cs @@ -0,0 +1,36 @@ +namespace Backend.Auth; + +/// Generic OIDC configuration (works with any compliant provider). +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"], + }; +} diff --git a/src/Backend/Auth/UserService.cs b/src/Backend/Auth/UserService.cs new file mode 100644 index 0000000..352195d --- /dev/null +++ b/src/Backend/Auth/UserService.cs @@ -0,0 +1,108 @@ +using Backend.Data; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Models; + +namespace Backend.Auth; + +/// +/// Local user lifecycle and password verification. Passwords are hashed with +/// ASP.NET Core's ; there is no compiled default +/// password. Rehashes transparently when the hasher recommends it. +/// +public sealed class UserService(AppDbContext db, ILogger logger) +{ + private readonly PasswordHasher hasher = new(); + + /// + /// Creates the initial admin from environment secrets on first startup only. + /// Never overwrites an existing admin's password. + /// + public async Task EnsureInitialAdminAsync(string? username, string? password, CancellationToken cancellationToken) + { + if (await db.Users.AnyAsync(cancellationToken)) + { + return; + } + + if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) + { + logger.LogWarning( + "No users exist and INITIAL_ADMIN_USERNAME/PASSWORD are not set; create an admin to enable sign-in"); + return; + } + + var admin = new UserEntity + { + Id = Guid.NewGuid(), + Username = username.Trim(), + DisplayName = username.Trim(), + Role = UserRole.Admin, + AuthProvider = AuthConstants.ProviderLocal, + CreatedUtc = DateTimeOffset.UtcNow, + }; + admin.PasswordHash = hasher.HashPassword(admin, password); + db.Users.Add(admin); + await db.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Initial admin '{Username}' created", admin.Username); + } + + public async Task ValidateCredentialsAsync(string username, string password, CancellationToken cancellationToken) + { + var user = await db.Users.SingleOrDefaultAsync( + u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal, cancellationToken); + if (user?.PasswordHash is null) + { + return null; + } + + var result = hasher.VerifyHashedPassword(user, user.PasswordHash, password); + if (result == PasswordVerificationResult.Failed) + { + return null; + } + + if (result == PasswordVerificationResult.SuccessRehashNeeded) + { + user.PasswordHash = hasher.HashPassword(user, password); + } + + user.LastLoginUtc = DateTimeOffset.UtcNow; + await db.SaveChangesAsync(cancellationToken); + return user; + } + + /// Upserts an OIDC-authenticated user, assigning role from claims. + public async Task UpsertOidcUserAsync( + string externalId, string username, string? displayName, UserRole role, CancellationToken cancellationToken) + { + var user = await db.Users.SingleOrDefaultAsync( + u => u.ExternalId == externalId && u.AuthProvider == AuthConstants.ProviderOidc, cancellationToken); + + if (user is null) + { + user = new UserEntity + { + Id = Guid.NewGuid(), + Username = username, + DisplayName = displayName ?? username, + Role = role, + AuthProvider = AuthConstants.ProviderOidc, + ExternalId = externalId, + CreatedUtc = DateTimeOffset.UtcNow, + }; + db.Users.Add(user); + } + else + { + user.Username = username; + user.DisplayName = displayName ?? username; + user.Role = role; + } + + user.LastLoginUtc = DateTimeOffset.UtcNow; + await db.SaveChangesAsync(cancellationToken); + return user; + } +} diff --git a/src/Backend/Backend.csproj b/src/Backend/Backend.csproj new file mode 100644 index 0000000..9df7a52 --- /dev/null +++ b/src/Backend/Backend.csproj @@ -0,0 +1,30 @@ + + + + net10.0 + Backend + backend-dev-secrets + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs new file mode 100644 index 0000000..33f0232 --- /dev/null +++ b/src/Backend/Data/AppDbContext.cs @@ -0,0 +1,160 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Shared.Contracts.Models; + +namespace Backend.Data; + +public class AppDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Users => Set(); + public DbSet OidcProviders => Set(); + public DbSet Devices => Set(); + public DbSet DeviceInventory => Set(); + public DbSet Scripts => Set(); + public DbSet FunctionModules => Set(); + public DbSet Jobs => Set(); + public DbSet JobOutput => Set(); + public DbSet BootstrapTokens => Set(); + public DbSet AuditEvents => Set(); + public DbSet ShellSessions => Set(); + public DbSet DeviceGroups => Set(); + public DbSet DeviceGroupMembers => Set(); + public DbSet ScriptTriggers => Set(); + public DbSet ScriptTriggerRuns => Set(); + + /// + /// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores + /// timestamps as UTC ticks. Postgres and SQL Server use native timestamp + /// columns. All application timestamps are UTC either way. + /// + protected virtual bool StoreTimestampsAsTicks => false; + + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + if (StoreTimestampsAsTicks) + { + configurationBuilder.Properties().HaveConversion(); + } + } + + private sealed class UtcTicksConverter() : ValueConverter( + value => value.UtcTicks, + ticks => new DateTimeOffset(ticks, TimeSpan.Zero)); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.ToTable("Users"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Username).IsUnique(); + entity.Property(e => e.Role).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("OidcProviders"); + entity.HasKey(e => e.Id); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("Devices"); + entity.HasKey(e => e.ClientId); + entity.HasIndex(e => e.Hostname); + entity.HasOne(e => e.Inventory) + .WithOne() + .HasForeignKey(e => e.ClientId) + .OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("DeviceInventory"); + entity.HasKey(e => e.ClientId); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("Scripts"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Name); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("FunctionModules"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Name); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("Jobs"); + entity.HasKey(e => e.JobId); + entity.HasIndex(e => e.ClientId); + entity.HasIndex(e => e.CreatedUtc); + entity.Property(e => e.State).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("JobOutput"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => new { e.JobId, e.Sequence }).IsUnique(); + entity.Property(e => e.Stream).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("BootstrapTokens"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.TokenHash).IsUnique(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("AuditEvents"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.TimestampUtc); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ShellSessions"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.ClientId); + entity.Property(e => e.State).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("DeviceGroups"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Name).IsUnique(); + entity.Property(e => e.Kind).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("DeviceGroupMembers"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => new { e.GroupId, e.ClientId }).IsUnique(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ScriptTriggers"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.TriggerType); + entity.Property(e => e.TriggerType).HasConversion(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ScriptTriggerRuns"); + entity.HasKey(e => e.Id); + entity.HasIndex(e => new { e.TriggerId, e.ClientId }).IsUnique(); + }); + } +} diff --git a/src/Backend/Data/DatabaseOptions.cs b/src/Backend/Data/DatabaseOptions.cs new file mode 100644 index 0000000..fe1961b --- /dev/null +++ b/src/Backend/Data/DatabaseOptions.cs @@ -0,0 +1,58 @@ +namespace Backend.Data; + +/// Supported relational providers. SQLite is the default. +public enum DatabaseProvider +{ + Sqlite, + Postgres, + SqlServer, +} + +/// +/// Database selection. SQLite uses DATABASE_PATH; the server providers +/// use DATABASE_CONNECTION_STRING. +/// +public sealed class DatabaseOptions +{ + public DatabaseProvider Provider { get; init; } = DatabaseProvider.Sqlite; + public required string ConnectionString { get; init; } + + public static DatabaseOptions FromConfiguration(IConfiguration configuration) + { + var provider = (configuration["DATABASE_PROVIDER"] ?? "sqlite").Trim().ToLowerInvariant() switch + { + "postgres" or "postgresql" or "npgsql" => DatabaseProvider.Postgres, + "sqlserver" or "mssql" => DatabaseProvider.SqlServer, + _ => DatabaseProvider.Sqlite, + }; + + var connectionString = configuration["DATABASE_CONNECTION_STRING"]; + + if (provider == DatabaseProvider.Sqlite) + { + if (string.IsNullOrWhiteSpace(connectionString)) + { + var path = configuration["DATABASE_PATH"]; + if (string.IsNullOrWhiteSpace(path)) + { + path = Path.Combine("data", "app.db"); + } + + var directory = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + connectionString = $"Data Source={path}"; + } + } + else if (string.IsNullOrWhiteSpace(connectionString)) + { + throw new InvalidOperationException( + $"DATABASE_PROVIDER={provider} requires DATABASE_CONNECTION_STRING."); + } + + return new DatabaseOptions { Provider = provider, ConnectionString = connectionString! }; + } +} diff --git a/src/Backend/Data/DevSeeder.cs b/src/Backend/Data/DevSeeder.cs new file mode 100644 index 0000000..813efa0 --- /dev/null +++ b/src/Backend/Data/DevSeeder.cs @@ -0,0 +1,167 @@ +using System.Text.Json; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Backend.Data; + +/// +/// Development-only sample data (DEV_SEED=1) so the UI has devices, inventory +/// and jobs to render without a live agent. Never runs outside Development. +/// +public static class DevSeeder +{ + public static async Task SeedAsync(AppDbContext db, CancellationToken cancellationToken = default) + { + if (db.Devices.Any()) + { + return; + } + + var now = DateTimeOffset.UtcNow; + + var samples = new[] + { + ("PC-ENG-014", "Dell Inc.", "OptiPlex 7090", "Windows 11 Pro", TimeSpan.FromSeconds(12), new[] { "10.20.4.14" }, new[] { "engineering", "workstation" }), + ("PC-FIN-003", "LENOVO", "ThinkCentre M90q", "Windows 11 Enterprise", TimeSpan.FromMinutes(3), new[] { "10.20.6.3" }, new[] { "finance", "workstation" }), + ("LAB-VM-27", "Microsoft Corporation", "Virtual Machine", "Windows Server 2022", TimeSpan.FromMinutes(20), new[] { "10.30.9.27" }, new[] { "lab", "server" }), + }; + + var i = 0; + foreach (var (hostname, mfr, model, os, seenAgo, ips, tags) in samples) + { + var clientId = (Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"))[..64]; + var device = new DeviceEntity + { + ClientId = clientId, + Hostname = hostname, + Manufacturer = mfr, + Model = model, + OsCaption = os, + OsVersion = "10.0.26100", + AgentVersion = "2026.08.06.2151", + NkeyPublic = "UADEVSEED" + i, + EnrollmentId = Guid.NewGuid(), + EnrolledUtc = now.AddDays(-i - 1), + LastSeenUtc = now - seenAgo, + IpAddressesJson = JsonSerializer.Serialize(ips, JsonDefaults.Options), + TagsJson = JsonSerializer.Serialize(tags, JsonDefaults.Options), + }; + db.Devices.Add(device); + + var report = new InventoryReport( + new InventoryIdentity(clientId, hostname, mfr, model, $"SN{1000 + i}", "1.14.3", $"BB{2000 + i}", "GRACE", true, "x64-based PC"), + new InventoryOs(os, "10.0.26100", "26100", "64-bit", now.AddMonths(-6), now - seenAgo - TimeSpan.FromHours(9), "Professional"), + new 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 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); + + db.DeviceInventory.Add(new DeviceInventoryEntity + { + ClientId = clientId, + ReportJson = JsonDefaults.Serialize(report), + UpdatedUtc = now - seenAgo, + }); + i++; + } + + await db.SaveChangesAsync(cancellationToken); + + // Sample groups: one dynamic (rules) and one static. + var dynamicRules = new GroupRuleSet(RuleCombine.And, [ + new RuleGroup(RuleCombine.Or, [ + new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc."), + new RuleCondition("manufacturer", RuleOperator.Equals, "LENOVO"), + ]), + new RuleGroup(RuleCombine.And, [ + new RuleCondition("memory.totalGb", RuleOperator.GreaterOrEqual, "16"), + new RuleCondition("tags", RuleOperator.Contains, "workstation"), + ]), + ]); + + db.DeviceGroups.Add(new DeviceGroupEntity + { + Id = Guid.NewGuid(), + Name = "Physical workstations (16 GB+)", + Description = "Dell or Lenovo workstations with at least 16 GB of memory.", + Kind = GroupKind.Dynamic, + RulesJson = JsonDefaults.Serialize(dynamicRules), + CreatedUtc = now, + UpdatedUtc = now, + UpdatedBy = "seed", + }); + + var labGroup = new DeviceGroupEntity + { + Id = Guid.NewGuid(), + Name = "Lab machines", + Description = "Hand-picked lab devices.", + Kind = GroupKind.Static, + CreatedUtc = now, + UpdatedUtc = now, + UpdatedBy = "seed", + }; + db.DeviceGroups.Add(labGroup); + await db.SaveChangesAsync(cancellationToken); + + var labDevice = db.Devices.FirstOrDefault(d => d.Hostname == "LAB-VM-27"); + if (labDevice is not null) + { + db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity + { + GroupId = labGroup.Id, + ClientId = labDevice.ClientId, + AddedUtc = now, + }); + await db.SaveChangesAsync(cancellationToken); + } + + var firstDevice = db.Devices.First(); + var script = db.Scripts.FirstOrDefault(); + if (script is not null) + { + var jobs = new[] + { + (JobState.Succeeded, now.AddMinutes(-8), now.AddMinutes(-7), 0), + (JobState.Running, now.AddMinutes(-1), (DateTimeOffset?)null, (int?)null), + (JobState.Failed, now.AddHours(-2), now.AddHours(-2).AddSeconds(4), 1), + }; + + foreach (var (state, started, completed, exit) in jobs) + { + var job = new JobEntity + { + JobId = Guid.NewGuid(), + ClientId = firstDevice.ClientId, + ScriptId = script.Id, + ScriptName = script.Name, + State = state, + CreatedUtc = started.AddSeconds(-1), + StartedUtc = started, + CompletedUtc = completed, + ExitCode = exit, + RequestedBy = "admin", + OutputSummary = state == JobState.Failed ? "Access to the path is denied." : null, + }; + db.Jobs.Add(job); + + for (var s = 1; s <= 5; s++) + { + db.JobOutput.Add(new JobOutputEntity + { + JobId = job.JobId, + Sequence = s, + Stream = OutputStreamKind.Output, + TimestampUtc = started.AddSeconds(s), + Text = $"Completed step {s}", + }); + } + } + + await db.SaveChangesAsync(cancellationToken); + } + } +} diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs new file mode 100644 index 0000000..e0af7c5 --- /dev/null +++ b/src/Backend/Data/Entities.cs @@ -0,0 +1,207 @@ +using Shared.Contracts.Models; + +namespace Backend.Data; + +public sealed class UserEntity +{ + public Guid Id { get; set; } + public required string Username { get; set; } + public string? DisplayName { get; set; } + public string? PasswordHash { get; set; } + public UserRole Role { get; set; } + /// "local" or "oidc". + public required string AuthProvider { get; set; } + /// OIDC subject claim for external users. + public string? ExternalId { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset? LastLoginUtc { get; set; } +} + +public sealed class OidcProviderEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + public required string Authority { get; set; } + public required string ClientId { get; set; } + public bool Enabled { get; set; } +} + +public sealed class DeviceEntity +{ + public required string ClientId { get; set; } + public required string Hostname { get; set; } + public string? Manufacturer { get; set; } + public string? Model { get; set; } + public string? OsCaption { get; set; } + public string? OsVersion { get; set; } + public string? AgentVersion { get; set; } + /// Enrolled NATS user public key bound to this device. + public required string NkeyPublic { get; set; } + public Guid EnrollmentId { get; set; } + public DateTimeOffset EnrolledUtc { get; set; } + public DateTimeOffset? LastSeenUtc { get; set; } + /// JSON array of current IP addresses (from presence/inventory). + public string? IpAddressesJson { get; set; } + /// JSON array of operator-assigned tags (usable in group rules). + public string? TagsJson { get; set; } + /// Set once the agent has reported it is connected and consuming commands. + public DateTimeOffset? ReadyUtc { get; set; } + /// + /// Silent past the configured orphan window: credential refresh and job + /// dispatch are refused until the device re-enrolls with a fresh token. + /// + public bool IsOrphaned { get; set; } + public DateTimeOffset? OrphanedUtc { get; set; } + + public DeviceInventoryEntity? Inventory { get; set; } +} + +/// A static or rule-based dynamic device group. +public sealed class DeviceGroupEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + public string? Description { get; set; } + public GroupKind Kind { get; set; } + /// Serialized GroupRuleSet; only meaningful for dynamic groups. + public string? RulesJson { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? UpdatedBy { get; set; } +} + +/// Explicit membership row for static groups. +public sealed class DeviceGroupMemberEntity +{ + public long Id { get; set; } + public Guid GroupId { get; set; } + public required string ClientId { get; set; } + public DateTimeOffset AddedUtc { get; set; } +} + +/// +/// Runs a script automatically when a lifecycle event occurs for a device in +/// the target group (or every device when GroupId is null). +/// +public sealed class ScriptTriggerEntity +{ + public Guid Id { get; set; } + public Guid ScriptId { get; set; } + public Guid? GroupId { get; set; } + public ScriptTriggerType TriggerType { get; set; } + public bool Enabled { get; set; } = true; + /// Run at most once per device (default) or every time the event fires. + public bool OncePerDevice { get; set; } = true; + public DateTimeOffset CreatedUtc { get; set; } + public string? CreatedBy { get; set; } +} + +/// Records that a trigger already fired for a device (OncePerDevice). +public sealed class ScriptTriggerRunEntity +{ + public long Id { get; set; } + public Guid TriggerId { get; set; } + public required string ClientId { get; set; } + public Guid JobId { get; set; } + public DateTimeOffset FiredUtc { get; set; } +} + +public sealed class DeviceInventoryEntity +{ + public required string ClientId { get; set; } + /// Latest full InventoryReport snapshot as JSON (MVP keeps latest only). + public required string ReportJson { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } +} + +public sealed class ScriptEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + public string? Description { get; set; } + public required string Language { get; set; } + public required string Content { get; set; } + /// JSON array of ScriptParameter definitions. + public string? ParametersJson { get; set; } + /// JSON array of attached FunctionModule ids (prepended at run time). + public string? FunctionModuleIdsJson { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? CreatedBy { get; set; } + public string? UpdatedBy { get; set; } +} + +/// Reusable PowerShell function library prepended to referencing scripts. +public sealed class FunctionModuleEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + public string? Description { get; set; } + public required string Content { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public string? UpdatedBy { get; set; } +} + +public sealed class JobEntity +{ + public Guid JobId { get; set; } + public required string ClientId { get; set; } + public Guid ScriptId { get; set; } + public required string ScriptName { get; set; } + public JobState State { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset? StartedUtc { get; set; } + public DateTimeOffset? CompletedUtc { get; set; } + public int? ExitCode { get; set; } + public string? RequestedBy { get; set; } + public string? OutputSummary { get; set; } +} + +public sealed class JobOutputEntity +{ + public long Id { get; set; } + public Guid JobId { get; set; } + public long Sequence { get; set; } + public OutputStreamKind Stream { get; set; } + public DateTimeOffset TimestampUtc { get; set; } + public required string Text { get; set; } +} + +public sealed class BootstrapTokenEntity +{ + public Guid Id { get; set; } + /// SHA-256 hex of the token; plaintext is never stored. + public required string TokenHash { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset ExpiresUtc { get; set; } + public int MaxUses { get; set; } + public int Uses { get; set; } + public bool Revoked { get; set; } + public string? Note { get; set; } + public string? CreatedBy { get; set; } +} + +public sealed class AuditEventEntity +{ + public long Id { get; set; } + public DateTimeOffset TimestampUtc { get; set; } + public required string Category { get; set; } + public required string Action { get; set; } + public string? Actor { get; set; } + public string? ClientId { get; set; } + public string? Detail { get; set; } + public string? RemoteIp { get; set; } +} + +public sealed class ShellSessionEntity +{ + public Guid Id { get; set; } + public required string ClientId { get; set; } + public string? RequestedBy { get; set; } + public ShellSessionState State { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset? ClosedUtc { get; set; } + /// Metadata only — shell transcripts are not persisted in the MVP. + public string? CloseReason { get; set; } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.Designer.cs new file mode 100644 index 0000000..782767e --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.Designer.cs @@ -0,0 +1,445 @@ +// +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("20260807013241_InitialCreate")] + partial class InitialCreate + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.cs b/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.cs new file mode 100644 index 0000000..01dca02 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807013241_InitialCreate.cs @@ -0,0 +1,312 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditEvents", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + TimestampUtc = table.Column(type: "timestamp with time zone", nullable: false), + Category = table.Column(type: "text", nullable: false), + Action = table.Column(type: "text", nullable: false), + Actor = table.Column(type: "text", nullable: true), + ClientId = table.Column(type: "text", nullable: true), + Detail = table.Column(type: "text", nullable: true), + RemoteIp = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditEvents", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "BootstrapTokens", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + TokenHash = table.Column(type: "text", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresUtc = table.Column(type: "timestamp with time zone", nullable: false), + MaxUses = table.Column(type: "integer", nullable: false), + Uses = table.Column(type: "integer", nullable: false), + Revoked = table.Column(type: "boolean", nullable: false), + Note = table.Column(type: "text", nullable: true), + CreatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BootstrapTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Devices", + columns: table => new + { + ClientId = table.Column(type: "text", nullable: false), + Hostname = table.Column(type: "text", nullable: false), + Manufacturer = table.Column(type: "text", nullable: true), + Model = table.Column(type: "text", nullable: true), + OsCaption = table.Column(type: "text", nullable: true), + OsVersion = table.Column(type: "text", nullable: true), + AgentVersion = table.Column(type: "text", nullable: true), + NkeyPublic = table.Column(type: "text", nullable: false), + EnrollmentId = table.Column(type: "uuid", nullable: false), + EnrolledUtc = table.Column(type: "timestamp with time zone", nullable: false), + LastSeenUtc = table.Column(type: "timestamp with time zone", nullable: true), + IpAddressesJson = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Devices", x => x.ClientId); + }); + + migrationBuilder.CreateTable( + name: "FunctionModules", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + Description = table.Column(type: "text", nullable: true), + Content = table.Column(type: "text", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_FunctionModules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "JobOutput", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + JobId = table.Column(type: "uuid", nullable: false), + Sequence = table.Column(type: "bigint", nullable: false), + Stream = table.Column(type: "text", nullable: false), + TimestampUtc = table.Column(type: "timestamp with time zone", nullable: false), + Text = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_JobOutput", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Jobs", + columns: table => new + { + JobId = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false), + ScriptName = table.Column(type: "text", nullable: false), + State = table.Column(type: "text", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + StartedUtc = table.Column(type: "timestamp with time zone", nullable: true), + CompletedUtc = table.Column(type: "timestamp with time zone", nullable: true), + ExitCode = table.Column(type: "integer", nullable: true), + RequestedBy = table.Column(type: "text", nullable: true), + OutputSummary = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Jobs", x => x.JobId); + }); + + migrationBuilder.CreateTable( + name: "OidcProviders", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + Authority = table.Column(type: "text", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OidcProviders", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Scripts", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + Description = table.Column(type: "text", nullable: true), + Language = table.Column(type: "text", nullable: false), + Content = table.Column(type: "text", nullable: false), + ParametersJson = table.Column(type: "text", nullable: true), + FunctionModuleIdsJson = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Scripts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShellSessions", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + RequestedBy = table.Column(type: "text", nullable: true), + State = table.Column(type: "text", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + ClosedUtc = table.Column(type: "timestamp with time zone", nullable: true), + CloseReason = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ShellSessions", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Username = table.Column(type: "text", nullable: false), + DisplayName = table.Column(type: "text", nullable: true), + PasswordHash = table.Column(type: "text", nullable: true), + Role = table.Column(type: "text", nullable: false), + AuthProvider = table.Column(type: "text", nullable: false), + ExternalId = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + LastLoginUtc = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceInventory", + columns: table => new + { + ClientId = table.Column(type: "text", nullable: false), + ReportJson = table.Column(type: "text", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceInventory", x => x.ClientId); + table.ForeignKey( + name: "FK_DeviceInventory_Devices_ClientId", + column: x => x.ClientId, + principalTable: "Devices", + principalColumn: "ClientId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AuditEvents_TimestampUtc", + table: "AuditEvents", + column: "TimestampUtc"); + + migrationBuilder.CreateIndex( + name: "IX_BootstrapTokens_TokenHash", + table: "BootstrapTokens", + column: "TokenHash", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Devices_Hostname", + table: "Devices", + column: "Hostname"); + + migrationBuilder.CreateIndex( + name: "IX_FunctionModules_Name", + table: "FunctionModules", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_JobOutput_JobId_Sequence", + table: "JobOutput", + columns: new[] { "JobId", "Sequence" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ClientId", + table: "Jobs", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_CreatedUtc", + table: "Jobs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Scripts_Name", + table: "Scripts", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_ShellSessions_ClientId", + table: "ShellSessions", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditEvents"); + + migrationBuilder.DropTable( + name: "BootstrapTokens"); + + migrationBuilder.DropTable( + name: "DeviceInventory"); + + migrationBuilder.DropTable( + name: "FunctionModules"); + + migrationBuilder.DropTable( + name: "JobOutput"); + + migrationBuilder.DropTable( + name: "Jobs"); + + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropTable( + name: "Scripts"); + + migrationBuilder.DropTable( + name: "ShellSessions"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.Designer.cs new file mode 100644 index 0000000..368c2f4 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.Designer.cs @@ -0,0 +1,578 @@ +// +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("20260807014116_AddGroupsAndTriggers")] + partial class AddGroupsAndTriggers + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.cs b/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.cs new file mode 100644 index 0000000..61a075e --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807014116_AddGroupsAndTriggers.cs @@ -0,0 +1,142 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddGroupsAndTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ReadyUtc", + table: "Devices", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "TagsJson", + table: "Devices", + type: "text", + nullable: true); + + migrationBuilder.CreateTable( + name: "DeviceGroupMembers", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + GroupId = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + AddedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroupMembers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceGroups", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + Description = table.Column(type: "text", nullable: true), + Kind = table.Column(type: "text", nullable: false), + RulesJson = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggerRuns", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + TriggerId = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + JobId = table.Column(type: "uuid", nullable: false), + FiredUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggerRuns", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggers", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false), + GroupId = table.Column(type: "uuid", nullable: true), + TriggerType = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + OncePerDevice = table.Column(type: "boolean", nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggers", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroupMembers_GroupId_ClientId", + table: "DeviceGroupMembers", + columns: new[] { "GroupId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroups_Name", + table: "DeviceGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggerRuns_TriggerId_ClientId", + table: "ScriptTriggerRuns", + columns: new[] { "TriggerId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_TriggerType", + table: "ScriptTriggers", + column: "TriggerType"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DeviceGroupMembers"); + + migrationBuilder.DropTable( + name: "DeviceGroups"); + + migrationBuilder.DropTable( + name: "ScriptTriggerRuns"); + + migrationBuilder.DropTable( + name: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ReadyUtc", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "TagsJson", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.Designer.cs new file mode 100644 index 0000000..5062424 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.Designer.cs @@ -0,0 +1,584 @@ +// +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("20260807021715_AddDeviceOrphanState")] + partial class AddDeviceOrphanState + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.cs b/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.cs new file mode 100644 index 0000000..3b83f6c --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260807021715_AddDeviceOrphanState.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddDeviceOrphanState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsOrphaned", + table: "Devices", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "OrphanedUtc", + table: "Devices", + type: "timestamp with time zone", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsOrphaned", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "OrphanedUtc", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs new file mode 100644 index 0000000..486fd78 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -0,0 +1,581 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + partial class PostgresAppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.Designer.cs new file mode 100644 index 0000000..b1b8bdd --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.Designer.cs @@ -0,0 +1,445 @@ +// +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("20260807013247_InitialCreate")] + partial class InitialCreate + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.cs b/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.cs new file mode 100644 index 0000000..671b7ed --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807013247_InitialCreate.cs @@ -0,0 +1,311 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditEvents", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + TimestampUtc = table.Column(type: "datetimeoffset", nullable: false), + Category = table.Column(type: "nvarchar(max)", nullable: false), + Action = table.Column(type: "nvarchar(max)", nullable: false), + Actor = table.Column(type: "nvarchar(max)", nullable: true), + ClientId = table.Column(type: "nvarchar(max)", nullable: true), + Detail = table.Column(type: "nvarchar(max)", nullable: true), + RemoteIp = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditEvents", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "BootstrapTokens", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + TokenHash = table.Column(type: "nvarchar(450)", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + ExpiresUtc = table.Column(type: "datetimeoffset", nullable: false), + MaxUses = table.Column(type: "int", nullable: false), + Uses = table.Column(type: "int", nullable: false), + Revoked = table.Column(type: "bit", nullable: false), + Note = table.Column(type: "nvarchar(max)", nullable: true), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BootstrapTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Devices", + columns: table => new + { + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + Hostname = table.Column(type: "nvarchar(450)", nullable: false), + Manufacturer = table.Column(type: "nvarchar(max)", nullable: true), + Model = table.Column(type: "nvarchar(max)", nullable: true), + OsCaption = table.Column(type: "nvarchar(max)", nullable: true), + OsVersion = table.Column(type: "nvarchar(max)", nullable: true), + AgentVersion = table.Column(type: "nvarchar(max)", nullable: true), + NkeyPublic = table.Column(type: "nvarchar(max)", nullable: false), + EnrollmentId = table.Column(type: "uniqueidentifier", nullable: false), + EnrolledUtc = table.Column(type: "datetimeoffset", nullable: false), + LastSeenUtc = table.Column(type: "datetimeoffset", nullable: true), + IpAddressesJson = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Devices", x => x.ClientId); + }); + + migrationBuilder.CreateTable( + name: "FunctionModules", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + Description = table.Column(type: "nvarchar(max)", nullable: true), + Content = table.Column(type: "nvarchar(max)", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_FunctionModules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "JobOutput", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + JobId = table.Column(type: "uniqueidentifier", nullable: false), + Sequence = table.Column(type: "bigint", nullable: false), + Stream = table.Column(type: "nvarchar(max)", nullable: false), + TimestampUtc = table.Column(type: "datetimeoffset", nullable: false), + Text = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_JobOutput", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Jobs", + columns: table => new + { + JobId = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + ScriptName = table.Column(type: "nvarchar(max)", nullable: false), + State = table.Column(type: "nvarchar(max)", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + StartedUtc = table.Column(type: "datetimeoffset", nullable: true), + CompletedUtc = table.Column(type: "datetimeoffset", nullable: true), + ExitCode = table.Column(type: "int", nullable: true), + RequestedBy = table.Column(type: "nvarchar(max)", nullable: true), + OutputSummary = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Jobs", x => x.JobId); + }); + + migrationBuilder.CreateTable( + name: "OidcProviders", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(max)", nullable: false), + Authority = table.Column(type: "nvarchar(max)", nullable: false), + ClientId = table.Column(type: "nvarchar(max)", nullable: false), + Enabled = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OidcProviders", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Scripts", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + Description = table.Column(type: "nvarchar(max)", nullable: true), + Language = table.Column(type: "nvarchar(max)", nullable: false), + Content = table.Column(type: "nvarchar(max)", nullable: false), + ParametersJson = table.Column(type: "nvarchar(max)", nullable: true), + FunctionModuleIdsJson = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Scripts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShellSessions", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + RequestedBy = table.Column(type: "nvarchar(max)", nullable: true), + State = table.Column(type: "nvarchar(max)", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + ClosedUtc = table.Column(type: "datetimeoffset", nullable: true), + CloseReason = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ShellSessions", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Username = table.Column(type: "nvarchar(450)", nullable: false), + DisplayName = table.Column(type: "nvarchar(max)", nullable: true), + PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), + Role = table.Column(type: "nvarchar(max)", nullable: false), + AuthProvider = table.Column(type: "nvarchar(max)", nullable: false), + ExternalId = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + LastLoginUtc = table.Column(type: "datetimeoffset", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceInventory", + columns: table => new + { + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + ReportJson = table.Column(type: "nvarchar(max)", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceInventory", x => x.ClientId); + table.ForeignKey( + name: "FK_DeviceInventory_Devices_ClientId", + column: x => x.ClientId, + principalTable: "Devices", + principalColumn: "ClientId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AuditEvents_TimestampUtc", + table: "AuditEvents", + column: "TimestampUtc"); + + migrationBuilder.CreateIndex( + name: "IX_BootstrapTokens_TokenHash", + table: "BootstrapTokens", + column: "TokenHash", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Devices_Hostname", + table: "Devices", + column: "Hostname"); + + migrationBuilder.CreateIndex( + name: "IX_FunctionModules_Name", + table: "FunctionModules", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_JobOutput_JobId_Sequence", + table: "JobOutput", + columns: new[] { "JobId", "Sequence" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ClientId", + table: "Jobs", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_CreatedUtc", + table: "Jobs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Scripts_Name", + table: "Scripts", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_ShellSessions_ClientId", + table: "ShellSessions", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditEvents"); + + migrationBuilder.DropTable( + name: "BootstrapTokens"); + + migrationBuilder.DropTable( + name: "DeviceInventory"); + + migrationBuilder.DropTable( + name: "FunctionModules"); + + migrationBuilder.DropTable( + name: "JobOutput"); + + migrationBuilder.DropTable( + name: "Jobs"); + + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropTable( + name: "Scripts"); + + migrationBuilder.DropTable( + name: "ShellSessions"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.Designer.cs new file mode 100644 index 0000000..68e3373 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.Designer.cs @@ -0,0 +1,578 @@ +// +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("20260807014122_AddGroupsAndTriggers")] + partial class AddGroupsAndTriggers + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.cs b/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.cs new file mode 100644 index 0000000..1cbe5ae --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807014122_AddGroupsAndTriggers.cs @@ -0,0 +1,141 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddGroupsAndTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ReadyUtc", + table: "Devices", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "TagsJson", + table: "Devices", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.CreateTable( + name: "DeviceGroupMembers", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + GroupId = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + AddedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroupMembers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceGroups", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(450)", nullable: false), + Description = table.Column(type: "nvarchar(max)", nullable: true), + Kind = table.Column(type: "nvarchar(max)", nullable: false), + RulesJson = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggerRuns", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + TriggerId = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + JobId = table.Column(type: "uniqueidentifier", nullable: false), + FiredUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggerRuns", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggers", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + GroupId = table.Column(type: "uniqueidentifier", nullable: true), + TriggerType = table.Column(type: "nvarchar(450)", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + OncePerDevice = table.Column(type: "bit", nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggers", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroupMembers_GroupId_ClientId", + table: "DeviceGroupMembers", + columns: new[] { "GroupId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroups_Name", + table: "DeviceGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggerRuns_TriggerId_ClientId", + table: "ScriptTriggerRuns", + columns: new[] { "TriggerId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_TriggerType", + table: "ScriptTriggers", + column: "TriggerType"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DeviceGroupMembers"); + + migrationBuilder.DropTable( + name: "DeviceGroups"); + + migrationBuilder.DropTable( + name: "ScriptTriggerRuns"); + + migrationBuilder.DropTable( + name: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ReadyUtc", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "TagsJson", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.Designer.cs new file mode 100644 index 0000000..e8cf514 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.Designer.cs @@ -0,0 +1,584 @@ +// +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("20260807021721_AddDeviceOrphanState")] + partial class AddDeviceOrphanState + { + /// + 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.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.cs b/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.cs new file mode 100644 index 0000000..98697be --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260807021721_AddDeviceOrphanState.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddDeviceOrphanState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsOrphaned", + table: "Devices", + type: "bit", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "OrphanedUtc", + table: "Devices", + type: "datetimeoffset", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsOrphaned", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "OrphanedUtc", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs new file mode 100644 index 0000000..03e23f5 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -0,0 +1,581 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + partial class SqlServerAppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.Designer.cs new file mode 100644 index 0000000..8248a20 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.Designer.cs @@ -0,0 +1,436 @@ +// +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("20260807013235_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.cs b/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.cs new file mode 100644 index 0000000..71cf692 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807013235_InitialCreate.cs @@ -0,0 +1,311 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AuditEvents", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + TimestampUtc = table.Column(type: "INTEGER", nullable: false), + Category = table.Column(type: "TEXT", nullable: false), + Action = table.Column(type: "TEXT", nullable: false), + Actor = table.Column(type: "TEXT", nullable: true), + ClientId = table.Column(type: "TEXT", nullable: true), + Detail = table.Column(type: "TEXT", nullable: true), + RemoteIp = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AuditEvents", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "BootstrapTokens", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + TokenHash = table.Column(type: "TEXT", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + ExpiresUtc = table.Column(type: "INTEGER", nullable: false), + MaxUses = table.Column(type: "INTEGER", nullable: false), + Uses = table.Column(type: "INTEGER", nullable: false), + Revoked = table.Column(type: "INTEGER", nullable: false), + Note = table.Column(type: "TEXT", nullable: true), + CreatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BootstrapTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Devices", + columns: table => new + { + ClientId = table.Column(type: "TEXT", nullable: false), + Hostname = table.Column(type: "TEXT", nullable: false), + Manufacturer = table.Column(type: "TEXT", nullable: true), + Model = table.Column(type: "TEXT", nullable: true), + OsCaption = table.Column(type: "TEXT", nullable: true), + OsVersion = table.Column(type: "TEXT", nullable: true), + AgentVersion = table.Column(type: "TEXT", nullable: true), + NkeyPublic = table.Column(type: "TEXT", nullable: false), + EnrollmentId = table.Column(type: "TEXT", nullable: false), + EnrolledUtc = table.Column(type: "INTEGER", nullable: false), + LastSeenUtc = table.Column(type: "INTEGER", nullable: true), + IpAddressesJson = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Devices", x => x.ClientId); + }); + + migrationBuilder.CreateTable( + name: "FunctionModules", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Description = table.Column(type: "TEXT", nullable: true), + Content = table.Column(type: "TEXT", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_FunctionModules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "JobOutput", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + JobId = table.Column(type: "TEXT", nullable: false), + Sequence = table.Column(type: "INTEGER", nullable: false), + Stream = table.Column(type: "TEXT", nullable: false), + TimestampUtc = table.Column(type: "INTEGER", nullable: false), + Text = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_JobOutput", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Jobs", + columns: table => new + { + JobId = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false), + ScriptName = table.Column(type: "TEXT", nullable: false), + State = table.Column(type: "TEXT", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + StartedUtc = table.Column(type: "INTEGER", nullable: true), + CompletedUtc = table.Column(type: "INTEGER", nullable: true), + ExitCode = table.Column(type: "INTEGER", nullable: true), + RequestedBy = table.Column(type: "TEXT", nullable: true), + OutputSummary = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Jobs", x => x.JobId); + }); + + migrationBuilder.CreateTable( + name: "OidcProviders", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Authority = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OidcProviders", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Scripts", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Description = table.Column(type: "TEXT", nullable: true), + Language = table.Column(type: "TEXT", nullable: false), + Content = table.Column(type: "TEXT", nullable: false), + ParametersJson = table.Column(type: "TEXT", nullable: true), + FunctionModuleIdsJson = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Scripts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShellSessions", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + RequestedBy = table.Column(type: "TEXT", nullable: true), + State = table.Column(type: "TEXT", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + ClosedUtc = table.Column(type: "INTEGER", nullable: true), + CloseReason = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ShellSessions", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Username = table.Column(type: "TEXT", nullable: false), + DisplayName = table.Column(type: "TEXT", nullable: true), + PasswordHash = table.Column(type: "TEXT", nullable: true), + Role = table.Column(type: "TEXT", nullable: false), + AuthProvider = table.Column(type: "TEXT", nullable: false), + ExternalId = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + LastLoginUtc = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceInventory", + columns: table => new + { + ClientId = table.Column(type: "TEXT", nullable: false), + ReportJson = table.Column(type: "TEXT", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceInventory", x => x.ClientId); + table.ForeignKey( + name: "FK_DeviceInventory_Devices_ClientId", + column: x => x.ClientId, + principalTable: "Devices", + principalColumn: "ClientId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AuditEvents_TimestampUtc", + table: "AuditEvents", + column: "TimestampUtc"); + + migrationBuilder.CreateIndex( + name: "IX_BootstrapTokens_TokenHash", + table: "BootstrapTokens", + column: "TokenHash", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Devices_Hostname", + table: "Devices", + column: "Hostname"); + + migrationBuilder.CreateIndex( + name: "IX_FunctionModules_Name", + table: "FunctionModules", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_JobOutput_JobId_Sequence", + table: "JobOutput", + columns: new[] { "JobId", "Sequence" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ClientId", + table: "Jobs", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_CreatedUtc", + table: "Jobs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Scripts_Name", + table: "Scripts", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_ShellSessions_ClientId", + table: "ShellSessions", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AuditEvents"); + + migrationBuilder.DropTable( + name: "BootstrapTokens"); + + migrationBuilder.DropTable( + name: "DeviceInventory"); + + migrationBuilder.DropTable( + name: "FunctionModules"); + + migrationBuilder.DropTable( + name: "JobOutput"); + + migrationBuilder.DropTable( + name: "Jobs"); + + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropTable( + name: "Scripts"); + + migrationBuilder.DropTable( + name: "ShellSessions"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.Designer.cs new file mode 100644 index 0000000..d5dc2de --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.Designer.cs @@ -0,0 +1,565 @@ +// +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("20260807014110_AddGroupsAndTriggers")] + partial class AddGroupsAndTriggers + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.cs b/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.cs new file mode 100644 index 0000000..a768118 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807014110_AddGroupsAndTriggers.cs @@ -0,0 +1,141 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddGroupsAndTriggers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ReadyUtc", + table: "Devices", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "TagsJson", + table: "Devices", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateTable( + name: "DeviceGroupMembers", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + GroupId = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + AddedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroupMembers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "DeviceGroups", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + Description = table.Column(type: "TEXT", nullable: true), + Kind = table.Column(type: "TEXT", nullable: false), + RulesJson = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DeviceGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggerRuns", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + TriggerId = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + JobId = table.Column(type: "TEXT", nullable: false), + FiredUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggerRuns", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScriptTriggers", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false), + GroupId = table.Column(type: "TEXT", nullable: true), + TriggerType = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + OncePerDevice = table.Column(type: "INTEGER", nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScriptTriggers", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroupMembers_GroupId_ClientId", + table: "DeviceGroupMembers", + columns: new[] { "GroupId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_DeviceGroups_Name", + table: "DeviceGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggerRuns_TriggerId_ClientId", + table: "ScriptTriggerRuns", + columns: new[] { "TriggerId", "ClientId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ScriptTriggers_TriggerType", + table: "ScriptTriggers", + column: "TriggerType"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DeviceGroupMembers"); + + migrationBuilder.DropTable( + name: "DeviceGroups"); + + migrationBuilder.DropTable( + name: "ScriptTriggerRuns"); + + migrationBuilder.DropTable( + name: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "ReadyUtc", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "TagsJson", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.Designer.cs new file mode 100644 index 0000000..b9f573d --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.Designer.cs @@ -0,0 +1,571 @@ +// +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("20260807021710_AddDeviceOrphanState")] + partial class AddDeviceOrphanState + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.cs b/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.cs new file mode 100644 index 0000000..a4a00b8 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260807021710_AddDeviceOrphanState.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddDeviceOrphanState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsOrphaned", + table: "Devices", + type: "INTEGER", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "OrphanedUtc", + table: "Devices", + type: "INTEGER", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsOrphaned", + table: "Devices"); + + migrationBuilder.DropColumn( + name: "OrphanedUtc", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs new file mode 100644 index 0000000..c58afd0 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -0,0 +1,568 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + partial class SqliteAppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/ProviderContexts.cs b/src/Backend/Data/ProviderContexts.cs new file mode 100644 index 0000000..ffe0f38 --- /dev/null +++ b/src/Backend/Data/ProviderContexts.cs @@ -0,0 +1,85 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace Backend.Data; + +// EF Core keeps one migration history per DbContext type. Each provider gets a +// thin derived context so `dotnet ef migrations add -c ` produces an +// independent, provider-correct migration set inside this one assembly. +// Application code always injects the base AppDbContext, which is registered +// as an alias of whichever derived context the configured provider selected. + +public sealed class SqliteAppDbContext(DbContextOptions options) + : AppDbContext(options.WithBase()) +{ + // SQLite has no native DateTimeOffset ordering; store UTC ticks instead. + protected override bool StoreTimestampsAsTicks => true; +} + +public sealed class PostgresAppDbContext(DbContextOptions options) + : AppDbContext(options.WithBase()); + +public sealed class SqlServerAppDbContext(DbContextOptions options) + : AppDbContext(options.WithBase()); + +internal static class DbContextOptionsExtensions +{ + /// Re-types provider options as base-context options for the shared constructor. + public static DbContextOptions WithBase(this DbContextOptions options) + where TContext : DbContext + => new(options.Extensions.ToDictionary(e => e.GetType(), e => e)); +} + +/// +/// Design-time factories so `dotnet ef` can build each provider's model without +/// a live database. Connection strings here are placeholders used only for +/// migration scaffolding. +/// +public sealed class SqliteContextFactory : IDesignTimeDbContextFactory +{ + public SqliteAppDbContext CreateDbContext(string[] args) + => new(new DbContextOptionsBuilder() + .UseSqlite("Data Source=design.db").Options); +} + +public sealed class PostgresContextFactory : IDesignTimeDbContextFactory +{ + public PostgresAppDbContext CreateDbContext(string[] args) + => new(new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=executer;Username=postgres;Password=design").Options); +} + +public sealed class SqlServerContextFactory : IDesignTimeDbContextFactory +{ + public SqlServerAppDbContext CreateDbContext(string[] args) + => new(new DbContextOptionsBuilder() + .UseSqlServer("Server=localhost;Database=executer;User Id=sa;Password=design;TrustServerCertificate=True").Options); +} + +public static class DatabaseRegistration +{ + /// + /// Registers the provider-specific context and aliases AppDbContext to it, + /// so every injection site keeps taking AppDbContext. + /// + public static void AddApplicationDatabase(this IServiceCollection services, DatabaseOptions options) + { + switch (options.Provider) + { + case DatabaseProvider.Postgres: + services.AddDbContext(b => b.UseNpgsql(options.ConnectionString)); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + case DatabaseProvider.SqlServer: + services.AddDbContext(b => b.UseSqlServer(options.ConnectionString)); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + default: + services.AddDbContext(b => b.UseSqlite(options.ConnectionString)); + services.AddScoped(sp => sp.GetRequiredService()); + break; + } + } +} diff --git a/src/Backend/Enrollment/EnrollmentEndpoints.cs b/src/Backend/Enrollment/EnrollmentEndpoints.cs new file mode 100644 index 0000000..3bfdbb8 --- /dev/null +++ b/src/Backend/Enrollment/EnrollmentEndpoints.cs @@ -0,0 +1,231 @@ +using System.Text; +using Backend.Data; +using Backend.Nats; +using Backend.Proxy; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using NATS.NKeys; +using Shared.Contracts.Api; +using Shared.Infrastructure.Nats; +using Shared.Infrastructure.Security; + +namespace Backend.Enrollment; + +/// +/// Agent bootstrap and credential refresh. Bootstrap validates and consumes a +/// one-time token, binds the agent's public NKey to the device and returns a +/// scoped NATS user JWT. Refresh proves possession of the enrolled NKey by +/// verifying a signature over {clientId}|{timestampUtc:O}. +/// +public static class EnrollmentEndpoints +{ + private static readonly TimeSpan RefreshTimestampTolerance = TimeSpan.FromMinutes(5); + + public static void Map(WebApplication app) + { + app.MapPost(ApiRoutes.Bootstrap, HandleBootstrapAsync) + .RequireRateLimiting(RateLimitPolicies.Enrollment) + .AllowAnonymous(); + + app.MapPost(ApiRoutes.RefreshCredential, HandleRefreshAsync) + .RequireRateLimiting(RateLimitPolicies.Enrollment) + .AllowAnonymous(); + } + + private static async Task HandleBootstrapAsync( + BootstrapRequest request, + AppDbContext db, + NatsCredentialIssuer issuer, + JetStreamProvisioner provisioner, + Messaging.BrowserEventBroadcaster broadcaster, + Groups.ScriptTriggerService triggers, + AuditService audit, + HttpContext context, + ILoggerFactory loggerFactory, + CancellationToken cancellationToken) + { + var logger = loggerFactory.CreateLogger("Enrollment"); + var remoteIp = ClientIp.EffectiveText(context); + + if (string.IsNullOrWhiteSpace(request.BootstrapToken) + || !SubjectIdentifier.IsValid(request.ClientId) + || string.IsNullOrWhiteSpace(request.NkeyPublic) + || string.IsNullOrWhiteSpace(request.Device?.Hostname)) + { + return Results.BadRequest(new { error = "Invalid enrollment request." }); + } + + if (!IsValidUserPublicKey(request.NkeyPublic)) + { + return Results.BadRequest(new { error = "Invalid NKey public key." }); + } + + if (!issuer.IsConfigured) + { + logger.LogError("Enrollment rejected: NATS credential issuer is not configured"); + return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Credential issuer unavailable."); + } + + var tokenHash = TokenHashing.Sha256Hex(request.BootstrapToken); + var now = DateTimeOffset.UtcNow; + + var token = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken); + if (token is null || token.Revoked || token.ExpiresUtc <= now || token.Uses >= token.MaxUses) + { + await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-rejected", + clientId: request.ClientId, detail: "invalid, expired or consumed token", remoteIp: remoteIp, + cancellationToken: cancellationToken); + logger.LogWarning("Bootstrap rejected for client {ClientId} from {RemoteIp}", request.ClientId, remoteIp); + return Results.Unauthorized(); + } + + // Idempotent enrollment by client id: re-enrollment rebinds the NKey. + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); + var enrollmentId = Guid.NewGuid(); + + if (device is null) + { + device = new DeviceEntity + { + ClientId = request.ClientId, + Hostname = request.Device.Hostname, + NkeyPublic = request.NkeyPublic, + EnrollmentId = enrollmentId, + EnrolledUtc = now, + }; + db.Devices.Add(device); + } + else + { + device.EnrollmentId = enrollmentId; + device.NkeyPublic = request.NkeyPublic; + device.EnrolledUtc = now; + } + + // Re-enrollment is the sanctioned way back for an orphaned device. + if (device.IsOrphaned) + { + logger.LogInformation("Orphaned device {ClientId} restored by re-enrollment", request.ClientId); + } + + device.IsOrphaned = false; + device.OrphanedUtc = null; + device.Hostname = request.Device.Hostname; + device.Manufacturer = request.Device.Manufacturer; + device.Model = request.Device.Model; + device.OsCaption = request.Device.OsCaption; + device.OsVersion = request.Device.OsVersion; + device.AgentVersion = request.AgentVersion; + + token.Uses++; + + var userJwt = issuer.IssueAgentCredential(request.ClientId, request.NkeyPublic); + + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-succeeded", + clientId: request.ClientId, + detail: $"hostname={request.Device.Hostname} agentVersion={request.AgentVersion}", + remoteIp: remoteIp, + cancellationToken: cancellationToken); + + logger.LogInformation("Device {ClientId} ({Hostname}) enrolled from {RemoteIp}", + request.ClientId, request.Device.Hostname, remoteIp); + + // Durable command consumer for this agent, plus enrollment fan-out. + try + { + await provisioner.EnsureAgentConsumerAsync(request.ClientId, cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Could not create durable consumer for {ClientId}; agent will retry binding", request.ClientId); + } + + await broadcaster.BroadcastActivityAsync(new Shared.Contracts.Messages.ActivityEventPayload( + "device-enrolled", + $"{request.Device.Hostname} enrolled", + request.ClientId, + null, + DateTimeOffset.UtcNow), cancellationToken); + + // Fire on-registration scripts for groups this device now matches. + await triggers.FireAsync( + Shared.Contracts.Models.ScriptTriggerType.OnRegistration, request.ClientId, cancellationToken); + + return Results.Ok(new BootstrapResponse(enrollmentId, request.ClientId, userJwt, CredentialExpiresUtc: null)); + } + + private static bool IsValidUserPublicKey(string candidate) + { + try + { + return KeyPair.IsValidPublicKey(PrefixByte.User, candidate); + } + catch (Exception) + { + // Malformed base32/CRC input — not a valid key. + return false; + } + } + + private static async Task HandleRefreshAsync( + CredentialRefreshRequest request, + AppDbContext db, + NatsCredentialIssuer issuer, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(request.ClientId) || string.IsNullOrWhiteSpace(request.NkeyPublic)) + { + return Results.BadRequest(new { error = "Invalid refresh request." }); + } + + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); + if (device is null + || !string.Equals(device.NkeyPublic, request.NkeyPublic, StringComparison.Ordinal) + || !issuer.IsConfigured) + { + return Results.Unauthorized(); + } + + // Orphaned devices must re-enroll with a fresh bootstrap token; a + // refresh alone does not bring them back. + if (device.IsOrphaned) + { + await audit.LogAsync(AuditCategories.Enrollment, "credential-refresh-refused", + clientId: request.ClientId, detail: "device is orphaned", + remoteIp: ClientIp.EffectiveText(context), cancellationToken: cancellationToken); + return Results.Unauthorized(); + } + + var skew = DateTimeOffset.UtcNow - request.TimestampUtc; + if (skew.Duration() > RefreshTimestampTolerance) + { + return Results.Unauthorized(); + } + + byte[] signature; + try + { + signature = Convert.FromBase64String(request.SignatureBase64); + } + catch (FormatException) + { + return Results.Unauthorized(); + } + + var payload = Encoding.UTF8.GetBytes($"{request.ClientId}|{request.TimestampUtc:O}"); + using var verifier = KeyPair.FromPublicKey(device.NkeyPublic); + if (!verifier.Verify(payload, signature)) + { + await audit.LogAsync(AuditCategories.Enrollment, "credential-refresh-rejected", + clientId: request.ClientId, detail: "signature verification failed", + remoteIp: ClientIp.EffectiveText(context), cancellationToken: cancellationToken); + return Results.Unauthorized(); + } + + var userJwt = issuer.IssueAgentCredential(request.ClientId, request.NkeyPublic); + return Results.Ok(new CredentialRefreshResponse(userJwt, CredentialExpiresUtc: null)); + } +} diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs new file mode 100644 index 0000000..da3974c --- /dev/null +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -0,0 +1,131 @@ +using Backend.Proxy; +using Backend.Security; +using Shared.Contracts.Api; + +namespace Backend.Enrollment; + +/// +/// URL-driven agent deployment. An operator runs a one-liner on the target: +/// +/// iwr https://control.example.com/api/enrollment/install?token=<token> -UseBasicParsing | iex +/// +/// The returned PowerShell downloads the agent package from this same origin +/// and installs it with SERVERURL + BOOTSTRAPTOKEN. The package is served from +/// AGENT_PACKAGE_PATH (default /data/agent). +/// +public static class InstallEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.InstallScript, GetInstallScript) + .RequireRateLimiting(RateLimitPolicies.Enrollment) + .AllowAnonymous(); + + app.MapGet(ApiRoutes.AgentPackage, GetAgentPackage) + .RequireRateLimiting(RateLimitPolicies.Enrollment) + .AllowAnonymous(); + } + + private static IResult GetInstallScript(HttpContext context, IConfiguration configuration, string? token, string? type) + { + if (string.IsNullOrWhiteSpace(token)) + { + return Results.BadRequest("A bootstrap token is required: ?token="); + } + + var baseUrl = ResolveBaseUrl(context, configuration); + var packageType = type?.ToLowerInvariant() == "zip" ? "zip" : "msi"; + var packageUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type={packageType}"; + + // Token is embedded so the operator can paste one command; knowledge of a + // valid token is itself the enrollment gate. + var script = packageType == "zip" + ? BuildZipScript(baseUrl, token!, packageUrl) + : BuildMsiScript(baseUrl, token!, packageUrl); + + return Results.Text(script, "text/plain; charset=utf-8"); + } + + private static async Task GetAgentPackage(HttpContext context, IConfiguration configuration, string? type) + { + var directory = configuration["AGENT_PACKAGE_PATH"]; + if (string.IsNullOrWhiteSpace(directory)) + { + directory = "/data/agent"; + } + + 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)) + { + return Results.NotFound(new + { + error = $"Agent package '{fileName}' is not available. " + + "Place the built package in AGENT_PACKAGE_PATH (default /data/agent).", + }); + } + + var contentType = packageType == "zip" ? "application/zip" : "application/x-msi"; + var stream = File.OpenRead(path); + return Results.Stream(stream, contentType, fileDownloadName: fileName, enableRangeProcessing: true); + } + + 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}"; + } + + // NOTE: $$""" — interpolations are {{ }}, single braces are literal PowerShell. + private static string BuildMsiScript(string baseUrl, string token, string packageUrl) => $$""" + #Requires -RunAsAdministrator + $ErrorActionPreference = 'Stop' + Write-Host 'Installing ExecuteR Agent...' + $server = '{{baseUrl}}' + $token = '{{token}}' + $msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi') + try { + Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $msi -UseBasicParsing + $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") + $p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" } + Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.' + } + finally { + Remove-Item $msi -ErrorAction SilentlyContinue + } + """; + + private static string BuildZipScript(string baseUrl, string token, string packageUrl) => $$""" + #Requires -RunAsAdministrator + $ErrorActionPreference = 'Stop' + Write-Host 'Installing ExecuteR Agent (portable)...' + $server = '{{baseUrl}}' + $token = '{{token}}' + $dest = Join-Path $env:ProgramFiles 'Grace Solution\ExecuteR Agent' + $zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip') + try { + Invoke-WebRequest -Uri '{{packageUrl}}' -OutFile $zip -UseBasicParsing + New-Item -ItemType Directory -Force -Path $dest | Out-Null + Expand-Archive -Path $zip -DestinationPath $dest -Force + $exe = Join-Path $dest 'Agent.exe' + # Seed configuration then install + start the service via the agent's own APIs. + New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null + Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server + Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token + & $exe initialize + Write-Host 'ExecuteR Agent installed and starting.' + } + finally { + Remove-Item $zip -ErrorAction SilentlyContinue + } + """; +} diff --git a/src/Backend/Files/FileDeliveryEndpoints.cs b/src/Backend/Files/FileDeliveryEndpoints.cs new file mode 100644 index 0000000..f8770de --- /dev/null +++ b/src/Backend/Files/FileDeliveryEndpoints.cs @@ -0,0 +1,94 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Jobs; +using Backend.Messaging; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Nats; + +namespace Backend.Files; + +/// +/// POST /api/devices/{clientId}/files — pushes an S3 object to a device. The +/// backend presigns a short-lived GET URL (credentials never leave the server), +/// records a job, and dispatches a durable file-download command. Progress and +/// result flow through the normal live job pipeline. +/// +public static class FileDeliveryEndpoints +{ + public static void Map(WebApplication app) + { + app.MapPost(ApiRoutes.DeviceFiles, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task CreateAsync( + string clientId, + CreateFileDeliveryRequest request, + AppDbContext db, + S3PresignService s3, + CommandDispatcher dispatcher, + BrowserEventBroadcaster broadcaster, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId) + || string.IsNullOrWhiteSpace(request.ObjectKey) + || string.IsNullOrWhiteSpace(request.DestinationPath)) + { + return Results.BadRequest(new { error = "clientId, objectKey and destinationPath are required." }); + } + + if (!s3.IsConfigured) + { + return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "S3 file delivery is not configured."); + } + + var device = await db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return Results.NotFound(); + } + + var (url, expiresUtc) = s3.PresignGet(request.ObjectKey); + var actor = context.User.Identity?.Name; + + var job = new JobEntity + { + JobId = Guid.NewGuid(), + ClientId = clientId, + ScriptId = Guid.Empty, + ScriptName = $"File delivery: {request.ObjectKey}", + State = JobState.Queued, + CreatedUtc = DateTimeOffset.UtcNow, + RequestedBy = actor, + }; + db.Jobs.Add(job); + await db.SaveChangesAsync(cancellationToken); + + var dispatched = await dispatcher.DispatchFileDownloadAsync(clientId, new FileDownloadCommandPayload( + job.JobId, url, request.DestinationPath, request.Sha256, SizeBytes: null, + SourceDescription: request.ObjectKey), cancellationToken); + + if (dispatched) + { + job.State = JobState.Dispatched; + await db.SaveChangesAsync(cancellationToken); + } + + await audit.LogAsync(AuditCategories.Jobs, "file-delivery", actor, + clientId: clientId, detail: $"key={request.ObjectKey} dest={request.DestinationPath} job={job.JobId}", + cancellationToken: cancellationToken); + + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "job-created", $"File “{request.ObjectKey}” queued for {device.Hostname}", + clientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + + return Results.Ok(new JobDto( + job.JobId, clientId, device.Hostname, job.ScriptId, job.ScriptName, job.State, + job.CreatedUtc, null, null, null, actor, null)); + } +} diff --git a/src/Backend/Files/S3Options.cs b/src/Backend/Files/S3Options.cs new file mode 100644 index 0000000..1aa25f0 --- /dev/null +++ b/src/Backend/Files/S3Options.cs @@ -0,0 +1,31 @@ +namespace Backend.Files; + +/// S3-compatible object store configuration (AWS S3, MinIO, B2, …). +public sealed class S3Options +{ + public bool Enabled { get; init; } + public string? Endpoint { get; init; } + public string Region { get; init; } = "us-east-1"; + public string? Bucket { get; init; } + public string? AccessKey { get; init; } + public string? SecretKey { get; init; } + public bool ForcePathStyle { get; init; } = true; + public int PresignExpirySeconds { get; init; } = 900; + + public bool IsUsable => Enabled + && !string.IsNullOrWhiteSpace(Bucket) + && !string.IsNullOrWhiteSpace(AccessKey) + && !string.IsNullOrWhiteSpace(SecretKey); + + public static S3Options FromConfiguration(IConfiguration configuration) => new() + { + Enabled = configuration["S3_ENABLED"] == "1", + Endpoint = configuration["S3_ENDPOINT"], + Region = string.IsNullOrWhiteSpace(configuration["S3_REGION"]) ? "us-east-1" : configuration["S3_REGION"]!, + Bucket = configuration["S3_BUCKET"], + AccessKey = configuration["S3_ACCESS_KEY"], + SecretKey = configuration["S3_SECRET_KEY"], + ForcePathStyle = configuration["S3_FORCE_PATH_STYLE"] != "0", + PresignExpirySeconds = int.TryParse(configuration["S3_PRESIGN_EXPIRY_SECONDS"], out var s) && s > 0 ? s : 900, + }; +} diff --git a/src/Backend/Files/S3PresignService.cs b/src/Backend/Files/S3PresignService.cs new file mode 100644 index 0000000..be605ad --- /dev/null +++ b/src/Backend/Files/S3PresignService.cs @@ -0,0 +1,61 @@ +using Amazon; +using Amazon.S3; +using Amazon.S3.Model; + +namespace Backend.Files; + +/// +/// Issues short-lived presigned GET URLs so agents can download objects +/// without ever holding S3 credentials. +/// +public sealed class S3PresignService : IDisposable +{ + private readonly S3Options options; + private readonly IAmazonS3? client; + + public S3PresignService(S3Options options) + { + this.options = options; + 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); + var url = client.GetPreSignedURL(new GetPreSignedUrlRequest + { + BucketName = options.Bucket, + Key = objectKey, + Verb = HttpVerb.GET, + Expires = expires, + }); + + return (url, new DateTimeOffset(expires, TimeSpan.Zero)); + } + + public void Dispose() => client?.Dispose(); +} diff --git a/src/Backend/Groups/DeviceGroupService.cs b/src/Backend/Groups/DeviceGroupService.cs new file mode 100644 index 0000000..f4b5b8a --- /dev/null +++ b/src/Backend/Groups/DeviceGroupService.cs @@ -0,0 +1,186 @@ +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Grouping; + +namespace Backend.Groups; + +/// +/// Resolves group membership. Static groups use the explicit member table; +/// dynamic groups evaluate their rules against each device's field bag +/// (inventory + tags + status + identity). +/// +public sealed class DeviceGroupService(AppDbContext db) +{ + /// Builds the rule field bag for one device. + public static DeviceFieldBag BuildFields(DeviceEntity device, string? inventoryJson, DateTimeOffset now) + { + InventoryReport? inventory = null; + if (!string.IsNullOrWhiteSpace(inventoryJson)) + { + try + { + inventory = JsonDefaults.Deserialize(inventoryJson); + } + catch (Exception) + { + // Corrupt snapshot: evaluate on identity fields only. + } + } + + return DeviceFieldBag.Build( + device.ClientId, + device.Hostname, + ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now), + device.AgentVersion, + ParseTags(device.TagsJson), + inventory); + } + + public static IReadOnlyList ParseTags(string? tagsJson) + => string.IsNullOrWhiteSpace(tagsJson) + ? [] + : JsonDefaults.Deserialize>(tagsJson) ?? []; + + public static GroupRuleSet? ParseRules(string? rulesJson) + { + if (string.IsNullOrWhiteSpace(rulesJson)) + { + return null; + } + + try + { + return JsonDefaults.Deserialize(rulesJson); + } + catch (Exception) + { + return null; + } + } + + /// Client ids belonging to a group. + public async Task> GetMembersAsync(DeviceGroupEntity group, CancellationToken cancellationToken) + { + if (group.Kind == GroupKind.Static) + { + return await db.DeviceGroupMembers.AsNoTracking() + .Where(m => m.GroupId == group.Id) + .Select(m => m.ClientId) + .ToListAsync(cancellationToken); + } + + var rules = ParseRules(group.RulesJson); + if (rules is null) + { + return []; + } + + return await EvaluateAsync(rules, cancellationToken); + } + + /// Evaluates a rule set against every enrolled device. + public async Task> EvaluateAsync(GroupRuleSet rules, CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + var rows = await db.Devices.AsNoTracking() + .GroupJoin( + db.DeviceInventory.AsNoTracking(), + d => d.ClientId, + i => i.ClientId, + (d, inv) => new { Device = d, Inventory = inv.Select(x => x.ReportJson).FirstOrDefault() }) + .ToListAsync(cancellationToken); + + return rows + .Where(r => RuleEvaluator.Matches(rules, BuildFields(r.Device, r.Inventory, now))) + .Select(r => r.Device.ClientId) + .ToList(); + } + + /// Groups (static and dynamic) that a single device currently belongs to. + public async Task> GetGroupsForDeviceAsync( + string clientId, CancellationToken cancellationToken) + { + var groups = await db.DeviceGroups.AsNoTracking().ToListAsync(cancellationToken); + if (groups.Count == 0) + { + return []; + } + + var device = await db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return []; + } + + var inventoryJson = await db.DeviceInventory.AsNoTracking() + .Where(i => i.ClientId == clientId) + .Select(i => i.ReportJson) + .FirstOrDefaultAsync(cancellationToken); + + var staticGroupIds = await db.DeviceGroupMembers.AsNoTracking() + .Where(m => m.ClientId == clientId) + .Select(m => m.GroupId) + .ToListAsync(cancellationToken); + + var fields = BuildFields(device, inventoryJson, DateTimeOffset.UtcNow); + var result = new List(); + + foreach (var group in groups) + { + var isMember = group.Kind == GroupKind.Static + ? staticGroupIds.Contains(group.Id) + : ParseRules(group.RulesJson) is { } rules && RuleEvaluator.Matches(rules, fields); + + if (isMember) + { + result.Add(new DeviceGroupRefDto(group.Id, group.Name, group.Kind)); + } + } + + return result; + } + + /// True when the device is in the group (null group means "all devices"). + public async Task IsMemberAsync(Guid? groupId, string clientId, CancellationToken cancellationToken) + { + if (groupId is null) + { + return true; + } + + var group = await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); + if (group is null) + { + return false; + } + + if (group.Kind == GroupKind.Static) + { + return await db.DeviceGroupMembers.AsNoTracking() + .AnyAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken); + } + + var rules = ParseRules(group.RulesJson); + if (rules is null) + { + return false; + } + + var device = await db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return false; + } + + var inventoryJson = await db.DeviceInventory.AsNoTracking() + .Where(i => i.ClientId == clientId) + .Select(i => i.ReportJson) + .FirstOrDefaultAsync(cancellationToken); + + return RuleEvaluator.Matches(rules, BuildFields(device, inventoryJson, DateTimeOffset.UtcNow)); + } +} diff --git a/src/Backend/Groups/GroupEndpoints.cs b/src/Backend/Groups/GroupEndpoints.cs new file mode 100644 index 0000000..c5029ab --- /dev/null +++ b/src/Backend/Groups/GroupEndpoints.cs @@ -0,0 +1,240 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Nats; + +namespace Backend.Groups; + +public static class GroupEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Groups, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.Groups, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapGet(ApiRoutes.Group, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPut(ApiRoutes.Group, UpdateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.Group, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator); + + app.MapGet(ApiRoutes.GroupMembers, MembersAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.GroupMembers, UpdateMembersAsync).RequireAuthorization(AuthConstants.PolicyOperator); + + app.MapPost(ApiRoutes.GroupPreview, PreviewAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapGet(ApiRoutes.GroupFields, () => Results.Ok(GroupFields.All)) + .RequireAuthorization(AuthConstants.PolicyViewer); + + app.MapPut(ApiRoutes.DeviceTags, UpdateTagsAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListAsync( + AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) + { + var entities = await db.DeviceGroups.AsNoTracking().OrderBy(g => g.Name).ToListAsync(cancellationToken); + var result = new List(entities.Count); + foreach (var entity in entities) + { + var members = await groups.GetMembersAsync(entity, cancellationToken); + result.Add(ToDto(entity, members.Count)); + } + + return Results.Ok(result); + } + + private static async Task GetAsync( + Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var members = await groups.GetMembersAsync(entity, cancellationToken); + return Results.Ok(ToDto(entity, members.Count)); + } + + private static async Task CreateAsync( + SaveDeviceGroupRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Group name is required." }); + } + + var now = DateTimeOffset.UtcNow; + var entity = new DeviceGroupEntity + { + Id = Guid.NewGuid(), + Name = request.Name.Trim(), + Description = request.Description, + Kind = request.Kind, + RulesJson = request.Kind == GroupKind.Dynamic && request.Rules is not null + ? JsonDefaults.Serialize(request.Rules) + : null, + CreatedUtc = now, + UpdatedUtc = now, + UpdatedBy = context.User.Identity?.Name, + }; + + db.DeviceGroups.Add(entity); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "group-created", entity.UpdatedBy, + detail: $"{entity.Name} ({entity.Kind})", cancellationToken: cancellationToken); + + return Results.Created(ApiRoutes.For.Group(entity.Id), ToDto(entity, 0)); + } + + private static async Task UpdateAsync( + Guid id, SaveDeviceGroupRequest request, AppDbContext db, DeviceGroupService groups, + HttpContext context, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Group name is required." }); + } + + entity.Name = request.Name.Trim(); + entity.Description = request.Description; + entity.Kind = request.Kind; + entity.RulesJson = request.Kind == GroupKind.Dynamic && request.Rules is not null + ? JsonDefaults.Serialize(request.Rules) + : null; + entity.UpdatedUtc = DateTimeOffset.UtcNow; + entity.UpdatedBy = context.User.Identity?.Name; + + await db.SaveChangesAsync(cancellationToken); + var members = await groups.GetMembersAsync(entity, cancellationToken); + return Results.Ok(ToDto(entity, members.Count)); + } + + private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var members = db.DeviceGroupMembers.Where(m => m.GroupId == id); + db.DeviceGroupMembers.RemoveRange(members); + db.DeviceGroups.Remove(entity); + await db.SaveChangesAsync(cancellationToken); + return Results.NoContent(); + } + + private static async Task MembersAsync( + Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var clientIds = await groups.GetMembersAsync(entity, cancellationToken); + var devices = await db.Devices.AsNoTracking() + .Where(d => clientIds.Contains(d.ClientId)) + .ToListAsync(cancellationToken); + + var now = DateTimeOffset.UtcNow; + return Results.Ok(devices.Select(d => Api.DeviceEndpoints.ToDto(d, now)).ToList()); + } + + private static async Task UpdateMembersAsync( + Guid id, UpdateGroupMembersRequest request, AppDbContext db, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + if (entity.Kind != GroupKind.Static) + { + return Results.BadRequest(new { error = "Membership of a dynamic group is determined by its rules." }); + } + + foreach (var clientId in request.Remove ?? []) + { + var existing = await db.DeviceGroupMembers + .Where(m => m.GroupId == id && m.ClientId == clientId) + .ToListAsync(cancellationToken); + db.DeviceGroupMembers.RemoveRange(existing); + } + + foreach (var clientId in request.Add ?? []) + { + if (!SubjectIdentifier.IsValid(clientId)) + { + continue; + } + + var already = await db.DeviceGroupMembers + .AnyAsync(m => m.GroupId == id && m.ClientId == clientId, cancellationToken); + if (!already) + { + db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity + { + GroupId = id, + ClientId = clientId, + AddedUtc = DateTimeOffset.UtcNow, + }); + } + } + + await db.SaveChangesAsync(cancellationToken); + return Results.NoContent(); + } + + /// Evaluates a candidate rule set without saving it (live preview). + private static async Task PreviewAsync( + PreviewGroupRequest request, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) + { + var clientIds = await groups.EvaluateAsync(request.Rules, cancellationToken); + var devices = await db.Devices.AsNoTracking() + .Where(d => clientIds.Contains(d.ClientId)) + .ToListAsync(cancellationToken); + + var now = DateTimeOffset.UtcNow; + return Results.Ok(devices.Select(d => Api.DeviceEndpoints.ToDto(d, now)).ToList()); + } + + private static async Task UpdateTagsAsync( + string clientId, UpdateDeviceTagsRequest request, AppDbContext db, CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId)) + { + return Results.BadRequest(); + } + + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return Results.NotFound(); + } + + var tags = (request.Tags ?? []) + .Select(t => t.Trim()) + .Where(t => t.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + device.TagsJson = tags.Count > 0 ? JsonDefaults.Serialize(tags) : null; + await db.SaveChangesAsync(cancellationToken); + return Results.Ok(tags); + } + + private static DeviceGroupDto ToDto(DeviceGroupEntity entity, int memberCount) => new( + entity.Id, entity.Name, entity.Description, entity.Kind, + DeviceGroupService.ParseRules(entity.RulesJson), + memberCount, entity.CreatedUtc, entity.UpdatedUtc, entity.UpdatedBy); +} diff --git a/src/Backend/Groups/ScriptTriggerService.cs b/src/Backend/Groups/ScriptTriggerService.cs new file mode 100644 index 0000000..0fcb95c --- /dev/null +++ b/src/Backend/Groups/ScriptTriggerService.cs @@ -0,0 +1,142 @@ +using Backend.Data; +using Backend.Jobs; +using Backend.Messaging; +using Backend.Scripts; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; + +namespace Backend.Groups; + +/// +/// Fires configured scripts on device lifecycle events (registration, agent +/// ready). Honors group targeting and once-per-device semantics, and reuses the +/// normal job pipeline so triggered runs appear alongside manual ones. +/// +public sealed class ScriptTriggerService( + AppDbContext db, + DeviceGroupService groups, + CommandDispatcher dispatcher, + BrowserEventBroadcaster broadcaster, + ILogger logger) +{ + public async Task FireAsync(ScriptTriggerType triggerType, string clientId, CancellationToken cancellationToken) + { + var triggers = await db.ScriptTriggers.AsNoTracking() + .Where(t => t.TriggerType == triggerType && t.Enabled) + .ToListAsync(cancellationToken); + + if (triggers.Count == 0) + { + return; + } + + var device = await db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return; + } + + foreach (var trigger in triggers) + { + try + { + if (trigger.OncePerDevice + && await db.ScriptTriggerRuns.AnyAsync( + r => r.TriggerId == trigger.Id && r.ClientId == clientId, cancellationToken)) + { + continue; + } + + if (!await groups.IsMemberAsync(trigger.GroupId, clientId, cancellationToken)) + { + continue; + } + + var script = await db.Scripts.AsNoTracking() + .SingleOrDefaultAsync(s => s.Id == trigger.ScriptId, cancellationToken); + if (script is null) + { + 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); + + if (trigger.OncePerDevice) + { + db.ScriptTriggerRuns.Add(new ScriptTriggerRunEntity + { + TriggerId = trigger.Id, + ClientId = clientId, + 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", + $"Trigger ({triggerType}) queued “{script.Name}” for {device.Hostname}", + clientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + + logger.LogInformation( + "Trigger {TriggerId} ({TriggerType}) fired for {ClientId} as job {JobId}", + trigger.Id, triggerType, clientId, job.JobId); + } + catch (Exception ex) + { + // One bad trigger must not stop the others. + logger.LogError(ex, "Trigger {TriggerId} failed for {ClientId}", trigger.Id, clientId); + } + } + } + + private async Task ComposePreludeAsync(IReadOnlyList 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; + } +} diff --git a/src/Backend/Groups/TriggerEndpoints.cs b/src/Backend/Groups/TriggerEndpoints.cs new file mode 100644 index 0000000..39ecd8f --- /dev/null +++ b/src/Backend/Groups/TriggerEndpoints.cs @@ -0,0 +1,75 @@ +using Backend.Auth; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; + +namespace Backend.Groups; + +public static class TriggerEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Triggers, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.Triggers, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.Trigger, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var triggers = await db.ScriptTriggers.AsNoTracking() + .OrderBy(t => t.TriggerType) + .ToListAsync(cancellationToken); + + var scriptNames = await db.Scripts.AsNoTracking().ToDictionaryAsync(s => s.Id, s => s.Name, cancellationToken); + var groupNames = await db.DeviceGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => g.Name, cancellationToken); + + return Results.Ok(triggers.Select(t => new ScriptTriggerDto( + t.Id, t.ScriptId, scriptNames.GetValueOrDefault(t.ScriptId, "(deleted script)"), + t.GroupId, t.GroupId is null ? "All devices" : groupNames.GetValueOrDefault(t.GroupId.Value, "(deleted group)"), + t.TriggerType, t.Enabled, t.OncePerDevice, t.CreatedUtc)).ToList()); + } + + private static async Task CreateAsync( + SaveScriptTriggerRequest request, AppDbContext db, HttpContext context, CancellationToken cancellationToken) + { + if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken)) + { + return Results.NotFound(new { error = "Script not found." }); + } + + if (request.GroupId is not null + && !await db.DeviceGroups.AnyAsync(g => g.Id == request.GroupId, cancellationToken)) + { + return Results.NotFound(new { error = "Group not found." }); + } + + var entity = new ScriptTriggerEntity + { + Id = Guid.NewGuid(), + ScriptId = request.ScriptId, + GroupId = request.GroupId, + TriggerType = request.TriggerType, + Enabled = request.Enabled, + OncePerDevice = request.OncePerDevice, + CreatedUtc = DateTimeOffset.UtcNow, + CreatedBy = context.User.Identity?.Name, + }; + + db.ScriptTriggers.Add(entity); + await db.SaveChangesAsync(cancellationToken); + return Results.Created(ApiRoutes.For.Trigger(entity.Id), new { id = entity.Id }); + } + + private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + { + var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + db.ScriptTriggers.Remove(entity); + await db.SaveChangesAsync(cancellationToken); + return Results.NoContent(); + } +} diff --git a/src/Backend/Jobs/CommandDispatcher.cs b/src/Backend/Jobs/CommandDispatcher.cs new file mode 100644 index 0000000..316d8a9 --- /dev/null +++ b/src/Backend/Jobs/CommandDispatcher.cs @@ -0,0 +1,71 @@ +using Backend.Nats; +using NATS.Client.JetStream; +using Shared.Contracts.Messages; +using Shared.Infrastructure.Nats; + +namespace Backend.Jobs; + +/// +/// Publishes durable agent commands through JetStream (awaiting stream acks) +/// so script dispatch survives agent disconnects and backend restarts. +/// +public sealed class CommandDispatcher(NatsHub hub, ILogger logger) +{ + private static readonly EndpointRef BackendSource = new(EndpointKinds.Backend, "backend"); + + public async Task DispatchScriptAsync( + string clientId, ScriptCommandPayload command, CancellationToken cancellationToken) + { + var envelope = MessageEnvelope.Create( + MessageTypes.CommandScript, + BackendSource, + command, + new EndpointRef(EndpointKinds.Agent, clientId)); + + return await PublishAsync(NatsSubjects.AgentCommandScript(clientId), envelope, cancellationToken); + } + + public async Task DispatchFileDownloadAsync( + string clientId, FileDownloadCommandPayload command, CancellationToken cancellationToken) + { + var envelope = MessageEnvelope.Create( + MessageTypes.CommandFileDownload, + BackendSource, + command, + new EndpointRef(EndpointKinds.Agent, clientId)); + + return await PublishAsync(NatsSubjects.AgentCommandFile(clientId), envelope, cancellationToken); + } + + public async Task DispatchInventoryRefreshAsync(string clientId, string? reason, CancellationToken cancellationToken) + { + var envelope = MessageEnvelope.Create( + MessageTypes.CommandInventory, + BackendSource, + new InventoryCommandPayload(reason), + new EndpointRef(EndpointKinds.Agent, clientId)); + + return await PublishAsync(NatsSubjects.AgentCommandInventory(clientId), envelope, cancellationToken); + } + + private async Task PublishAsync(string subject, MessageEnvelope envelope, CancellationToken cancellationToken) + { + if (!hub.IsConfigured) + { + return false; + } + + try + { + var js = new NatsJSContext(hub.Require()); + var ack = await js.PublishAsync(subject, envelope.ToUtf8Bytes(), cancellationToken: cancellationToken); + ack.EnsureSuccess(); + return true; + } + catch (Exception ex) + { + logger.LogError(ex, "Durable command publish to {Subject} failed", subject); + return false; + } + } +} diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs new file mode 100644 index 0000000..ebb04b6 --- /dev/null +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -0,0 +1,187 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Messaging; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Jobs; + +public static class JobEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Jobs, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.Jobs, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapGet(ApiRoutes.Job, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapGet(ApiRoutes.JobOutput, GetOutputAsync).RequireAuthorization(AuthConstants.PolicyViewer); + } + + private static async Task ListAsync( + AppDbContext db, string? clientId, int? limit, CancellationToken cancellationToken) + { + var query = db.Jobs.AsNoTracking().OrderByDescending(j => j.CreatedUtc).AsQueryable(); + if (!string.IsNullOrEmpty(clientId)) + { + query = query.Where(j => j.ClientId == clientId); + } + + var jobs = await query.Take(Math.Clamp(limit ?? 100, 1, 500)).ToListAsync(cancellationToken); + var hostnames = await db.Devices.AsNoTracking() + .Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId)) + .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); + + return Results.Ok(jobs.Select(j => ToDto(j, hostnames.GetValueOrDefault(j.ClientId))).ToList()); + } + + private static async Task GetAsync(Guid jobId, AppDbContext db, CancellationToken cancellationToken) + { + var job = await db.Jobs.AsNoTracking().SingleOrDefaultAsync(j => j.JobId == jobId, cancellationToken); + if (job is null) + { + return Results.NotFound(); + } + + var hostname = await db.Devices.AsNoTracking() + .Where(d => d.ClientId == job.ClientId) + .Select(d => d.Hostname) + .SingleOrDefaultAsync(cancellationToken); + + return Results.Ok(ToDto(job, hostname)); + } + + private static async Task GetOutputAsync( + Guid jobId, AppDbContext db, long? afterSequence, CancellationToken cancellationToken) + { + var exists = await db.Jobs.AnyAsync(j => j.JobId == jobId, cancellationToken); + if (!exists) + { + return Results.NotFound(); + } + + var records = await db.JobOutput.AsNoTracking() + .Where(o => o.JobId == jobId && o.Sequence > (afterSequence ?? 0)) + .OrderBy(o => o.Sequence) + .Take(10_000) + .Select(o => new JobOutputRecordDto(o.Sequence, o.Stream, o.TimestampUtc, o.Text)) + .ToListAsync(cancellationToken); + + return Results.Ok(records); + } + + private static async Task CreateAsync( + CreateJobRequest request, + AppDbContext db, + CommandDispatcher dispatcher, + BrowserEventBroadcaster broadcaster, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(request.ClientId)) + { + return Results.BadRequest(new { error = "Invalid client id." }); + } + + var device = await db.Devices.AsNoTracking() + .SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); + if (device is null) + { + return Results.NotFound(new { error = "Device not found." }); + } + + if (device.IsOrphaned) + { + return Results.Conflict(new + { + error = "Device is orphaned. Push a new bootstrap token to the endpoint so the agent re-enrolls.", + }); + } + + 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); + } + + 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 ComposePreludeAsync( + AppDbContext db, IReadOnlyList 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; + } + + private static JobDto ToDto(JobEntity job, string? hostname) => new( + job.JobId, job.ClientId, hostname, job.ScriptId, job.ScriptName, job.State, + job.CreatedUtc, job.StartedUtc, job.CompletedUtc, job.ExitCode, job.RequestedBy, job.OutputSummary); +} diff --git a/src/Backend/Messaging/BrowserEventBroadcaster.cs b/src/Backend/Messaging/BrowserEventBroadcaster.cs new file mode 100644 index 0000000..495f839 --- /dev/null +++ b/src/Backend/Messaging/BrowserEventBroadcaster.cs @@ -0,0 +1,82 @@ +using Backend.Nats; +using Shared.Contracts.Messages; +using Shared.Infrastructure.Nats; + +namespace Backend.Messaging; + +/// +/// Republishes authorized events to per-session browser subjects. Raw +/// agent/job subjects are never exposed to browsers; for the MVP every +/// active session may see all device/job events (session-scoped subjects +/// keep the transport ready for finer RBAC later). +/// +public sealed class BrowserEventBroadcaster(NatsHub hub, BrowserSessionRegistry sessions, ILogger logger) +{ + private static readonly EndpointRef BackendSource = new(EndpointKinds.Backend, "backend"); + + /// Dashboard activity feed entry for every active session. + public ValueTask BroadcastActivityAsync(ActivityEventPayload payload, CancellationToken cancellationToken) + => FanOutAsync( + session => NatsSubjects.BrowserEvent(session.SessionId), + MessageTypes.BrowserEvent, + payload, + cancellationToken); + + /// Job stream event (output/progress/state) for every active session. + public ValueTask BroadcastJobEventAsync(Guid jobId, string messageType, TPayload payload, CancellationToken cancellationToken) + => FanOutAsync( + session => NatsSubjects.BrowserJob(session.SessionId, jobId), + messageType, + payload, + cancellationToken); + + /// Shell stream event delivered only to the owning session. + public async ValueTask SendShellEventAsync( + string ownerSessionId, Guid shellId, string messageType, TPayload payload, CancellationToken cancellationToken) + { + if (!hub.IsConfigured) + { + return; + } + + var envelope = MessageEnvelope.Create(messageType, BackendSource, payload); + await hub.Require().PublishAsync( + NatsSubjects.BrowserShell(ownerSessionId, shellId), + envelope.ToUtf8Bytes(), + cancellationToken: cancellationToken); + } + + private async ValueTask FanOutAsync( + Func subjectSelector, + string messageType, + TPayload payload, + CancellationToken cancellationToken) + { + if (!hub.IsConfigured) + { + return; + } + + var active = sessions.Active(); + if (active.Count == 0) + { + return; + } + + var envelope = MessageEnvelope.Create(messageType, BackendSource, payload); + var bytes = envelope.ToUtf8Bytes(); + var connection = hub.Require(); + + foreach (var session in active) + { + try + { + await connection.PublishAsync(subjectSelector(session), bytes, cancellationToken: cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to publish browser event to session {SessionId}", session.SessionId); + } + } + } +} diff --git a/src/Backend/Messaging/BrowserSessionRegistry.cs b/src/Backend/Messaging/BrowserSessionRegistry.cs new file mode 100644 index 0000000..3aaf4f9 --- /dev/null +++ b/src/Backend/Messaging/BrowserSessionRegistry.cs @@ -0,0 +1,66 @@ +using System.Collections.Concurrent; +using Shared.Contracts.Models; + +namespace Backend.Messaging; + +/// One authenticated browser session with a scoped NATS credential. +public sealed record BrowserSession( + string SessionId, + string? Username, + UserRole Role, + DateTimeOffset CreatedUtc) +{ + public DateTimeOffset LastRefreshUtc { get; set; } = DateTimeOffset.UtcNow; +} + +/// +/// Tracks live browser sessions so backend workers can republish authorized +/// events to session-specific subjects. Sessions expire when the browser +/// stops refreshing its short-lived credential. +/// +public sealed class BrowserSessionRegistry +{ + private static readonly TimeSpan SessionIdleExpiry = TimeSpan.FromMinutes(10); + + private readonly ConcurrentDictionary sessions = new(); + + public BrowserSession Register(string sessionId, string? username, UserRole role) + { + var session = new BrowserSession(sessionId, username, role, DateTimeOffset.UtcNow); + sessions[sessionId] = session; + return session; + } + + public BrowserSession? Touch(string sessionId) + { + if (sessions.TryGetValue(sessionId, out var session)) + { + session.LastRefreshUtc = DateTimeOffset.UtcNow; + return session; + } + + return null; + } + + public void Remove(string sessionId) => sessions.TryRemove(sessionId, out _); + + /// Active (non-expired) sessions; prunes expired entries as a side effect. + public IReadOnlyList Active() + { + var now = DateTimeOffset.UtcNow; + var result = new List(); + foreach (var (id, session) in sessions) + { + if (now - session.LastRefreshUtc > SessionIdleExpiry) + { + sessions.TryRemove(id, out _); + } + else + { + result.Add(session); + } + } + + return result; + } +} diff --git a/src/Backend/Messaging/MessagingEndpoints.cs b/src/Backend/Messaging/MessagingEndpoints.cs new file mode 100644 index 0000000..4497b7b --- /dev/null +++ b/src/Backend/Messaging/MessagingEndpoints.cs @@ -0,0 +1,75 @@ +using Backend.Auth; +using Backend.Nats; +using NATS.NKeys; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Messaging; + +/// +/// Issues short-lived, session-scoped browser NATS credentials. The browser +/// generates its NKey pair in memory and sends only the public key; the JWT +/// it gets back can publish/subscribe exclusively below its own +/// browser.<sessionId>.> subjects. +/// +public static class MessagingEndpoints +{ + public static void Map(WebApplication app) + { + app.MapPost(ApiRoutes.BrowserNatsCredential, IssueAsync).RequireAuthorization(AuthConstants.PolicyViewer); + } + + private static IResult IssueAsync( + BrowserCredentialRequest request, + NatsCredentialIssuer issuer, + BrowserSessionRegistry sessions, + HttpContext context) + { + if (!issuer.IsConfigured) + { + return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Messaging unavailable."); + } + + if (!IsValidUserPublicKey(request.NkeyPublic)) + { + return Results.BadRequest(new { error = "Invalid NKey public key." }); + } + + // Reuse the caller's session when it is still alive so its subjects + // stay stable across credential refreshes; otherwise mint a new one. + string sessionId; + if (!string.IsNullOrEmpty(request.BrowserSessionId) + && SubjectIdentifier.IsValid(request.BrowserSessionId) + && sessions.Touch(request.BrowserSessionId) is not null) + { + sessionId = request.BrowserSessionId; + } + else + { + sessionId = Guid.NewGuid().ToString("N"); + sessions.Register(sessionId, context.User.Identity?.Name, UserRole.Operator); + } + + var (jwt, expires) = issuer.IssueBrowserCredential(sessionId, request.NkeyPublic); + return Results.Ok(new BrowserCredentialResponse(jwt, expires, sessionId, MessagingPaths.Browser)); + } + + private static bool IsValidUserPublicKey(string? candidate) + { + if (string.IsNullOrWhiteSpace(candidate)) + { + return false; + } + + try + { + return KeyPair.IsValidPublicKey(PrefixByte.User, candidate); + } + catch (Exception) + { + return false; + } + } +} diff --git a/src/Backend/Messaging/MessagingWorkers.cs b/src/Backend/Messaging/MessagingWorkers.cs new file mode 100644 index 0000000..03681f0 --- /dev/null +++ b/src/Backend/Messaging/MessagingWorkers.cs @@ -0,0 +1,443 @@ +using System.Text.Json; +using Backend.Data; +using Backend.Nats; +using Microsoft.EntityFrameworkCore; +using NATS.Client.Core; +using NATS.Client.JetStream; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Messaging; + +/// +/// Backend NATS subscription workers: presence and inventory ingest (Core +/// NATS), near-live job output/progress relay, durable job state consumption +/// (JetStream) and offline-transition sweeping. +/// +public sealed class MessagingWorkers( + NatsHub hub, + BrowserEventBroadcaster broadcaster, + Api.DeviceLifecycleOptions lifecycle, + IServiceScopeFactory scopeFactory, + ILogger logger) : BackgroundService +{ + private readonly Dictionary lastKnownStatus = []; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!hub.IsConfigured) + { + logger.LogWarning("Messaging workers idle: NATS not configured"); + return; + } + + await Task.WhenAll( + RunLoopAsync("presence", () => ConsumePresenceAsync(stoppingToken), stoppingToken), + RunLoopAsync("inventory", () => ConsumeInventoryAsync(stoppingToken), stoppingToken), + RunLoopAsync("agent-events", () => ConsumeAgentEventsAsync(stoppingToken), stoppingToken), + RunLoopAsync("job-output", () => ConsumeJobOutputAsync(stoppingToken), stoppingToken), + RunLoopAsync("job-progress", () => ConsumeJobProgressAsync(stoppingToken), stoppingToken), + RunLoopAsync("job-state", () => ConsumeJobStateAsync(stoppingToken), stoppingToken), + RunLoopAsync("status-sweep", () => SweepStatusesAsync(stoppingToken), stoppingToken)); + } + + private async Task RunLoopAsync(string name, Func loop, CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await loop(); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + logger.LogError(ex, "Messaging worker '{Worker}' failed; restarting in 5s", name); + try + { + await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } + } + + private async Task ConsumePresenceAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllAgentPresence, cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + if (payload is null || !SubjectIdentifier.IsValid(payload.ClientId)) + { + continue; + } + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == payload.ClientId, cancellationToken); + if (device is null) + { + continue; // Presence from a device we have no enrollment for. + } + + if (device.IsOrphaned) + { + // An orphaned device does not come back just by reappearing — + // recovery is deliberate re-enrollment with a fresh token. + logger.LogWarning( + "Ignoring presence from orphaned device {ClientId} ({Hostname}); push a bootstrap token to re-enroll it", + device.ClientId, device.Hostname); + continue; + } + + var previous = ProtocolDefaults.CalculateStatus(device.LastSeenUtc, DateTimeOffset.UtcNow); + device.LastSeenUtc = DateTimeOffset.UtcNow; + device.Hostname = payload.Hostname; + device.AgentVersion = payload.AgentVersion; + await db.SaveChangesAsync(cancellationToken); + + lock (lastKnownStatus) + { + lastKnownStatus[device.ClientId] = DeviceStatus.Online; + } + + if (previous != DeviceStatus.Online) + { + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + Kind: "device-online", + Text: $"{payload.Hostname} connected", + ClientId: payload.ClientId, + JobId: null, + TimestampUtc: DateTimeOffset.UtcNow), cancellationToken); + } + else + { + // Lightweight status tick so device tables refresh "last seen". + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + Kind: "device-presence", + Text: string.Empty, + ClientId: payload.ClientId, + JobId: null, + TimestampUtc: DateTimeOffset.UtcNow), cancellationToken); + } + } + } + + private async Task ConsumeInventoryAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllAgentInventory, cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + var report = payload?.Report; + if (report is null || !SubjectIdentifier.IsValid(report.Identity.ClientId)) + { + continue; + } + + var clientId = report.Identity.ClientId; + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + continue; + } + + device.Hostname = report.Identity.Hostname; + device.Manufacturer = report.Identity.Manufacturer; + device.Model = report.Identity.Model; + device.OsCaption = report.Os.Caption; + device.OsVersion = report.Os.Version; + device.LastSeenUtc = DateTimeOffset.UtcNow; + + var addresses = report.Network + .SelectMany(a => a.Ipv4Addresses) + .Where(ip => !ip.StartsWith("169.254.", StringComparison.Ordinal) && ip != "127.0.0.1") + .Distinct() + .ToList(); + device.IpAddressesJson = JsonSerializer.Serialize(addresses, JsonDefaults.Options); + + var inventoryRow = await db.DeviceInventory.SingleOrDefaultAsync(i => i.ClientId == clientId, cancellationToken); + var reportJson = JsonDefaults.Serialize(report); + if (inventoryRow is null) + { + db.DeviceInventory.Add(new DeviceInventoryEntity + { + ClientId = clientId, + ReportJson = reportJson, + UpdatedUtc = DateTimeOffset.UtcNow, + }); + } + else + { + inventoryRow.ReportJson = reportJson; + inventoryRow.UpdatedUtc = DateTimeOffset.UtcNow; + } + + await db.SaveChangesAsync(cancellationToken); + + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + Kind: "inventory-updated", + Text: $"{report.Identity.Hostname} inventory updated", + ClientId: clientId, + JobId: null, + TimestampUtc: DateTimeOffset.UtcNow), cancellationToken); + } + } + + /// + /// Agent lifecycle events. A "ready" notice means the agent is connected + /// and consuming job commands, which fires OnAgentReady script triggers. + /// + private async Task ConsumeAgentEventsAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllAgentEvents, cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + if (payload is null + || !SubjectIdentifier.IsValid(payload.ClientId) + || payload.Kind != AgentEventKinds.Ready) + { + continue; + } + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == payload.ClientId, cancellationToken); + if (device is null) + { + continue; + } + + device.ReadyUtc = payload.TimestampUtc; + device.LastSeenUtc = DateTimeOffset.UtcNow; + await db.SaveChangesAsync(cancellationToken); + + var triggers = scope.ServiceProvider.GetRequiredService(); + await triggers.FireAsync(ScriptTriggerType.OnAgentReady, payload.ClientId, cancellationToken); + } + } + + private async Task ConsumeJobOutputAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllJobOutput, cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + if (payload is null) + { + continue; + } + + // Relay to browsers first (near-live), persist asynchronously after. + await broadcaster.BroadcastJobEventAsync(payload.JobId, MessageTypes.JobOutput, payload, cancellationToken); + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Ownership check: the job must belong to the claiming client. + var jobExists = await db.Jobs.AnyAsync( + j => j.JobId == payload.JobId && j.ClientId == payload.ClientId, cancellationToken); + if (!jobExists) + { + continue; + } + + db.JobOutput.Add(new JobOutputEntity + { + JobId = payload.JobId, + Sequence = payload.Sequence, + Stream = payload.Stream, + TimestampUtc = payload.TimestampUtc, + Text = payload.Text, + }); + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Duplicate sequence (redelivery) — already stored. + } + } + } + + private async Task ConsumeJobProgressAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllJobProgress, cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + if (payload is null) + { + continue; + } + + await broadcaster.BroadcastJobEventAsync(payload.JobId, MessageTypes.JobProgress, payload, cancellationToken); + } + } + + private async Task ConsumeJobStateAsync(CancellationToken cancellationToken) + { + var js = new NatsJSContext(hub.Require()); + var consumer = await js.GetConsumerAsync( + JetStreamDefaults.JobEventsStreamName, + JetStreamDefaults.BackendJobEventsConsumerName, + cancellationToken); + + await foreach (var msg in consumer.ConsumeAsync(cancellationToken: cancellationToken)) + { + var payload = Parse(msg.Data); + if (payload is null) + { + await msg.AckTerminateAsync(cancellationToken: cancellationToken); + continue; + } + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var job = await db.Jobs.SingleOrDefaultAsync( + j => j.JobId == payload.JobId && j.ClientId == payload.ClientId, cancellationToken); + if (job is not null) + { + ApplyJobState(job, payload); + await db.SaveChangesAsync(cancellationToken); + + await broadcaster.BroadcastJobEventAsync(payload.JobId, MessageTypes.JobState, payload, cancellationToken); + + if (payload.State is JobState.Running) + { + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "job-started", $"Job “{job.ScriptName}” started on {job.ClientId[..8]}…", + job.ClientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + } + else if (payload.State is JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.TimedOut) + { + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "job-completed", $"Job “{job.ScriptName}” {payload.State.ToString().ToLowerInvariant()}", + job.ClientId, job.JobId, DateTimeOffset.UtcNow), cancellationToken); + } + } + + await msg.AckAsync(cancellationToken: cancellationToken); + } + } + + private static void ApplyJobState(JobEntity job, JobStatePayload payload) + { + // Never regress a terminal state (redelivery safety). + if (job.State is JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.TimedOut) + { + return; + } + + job.State = payload.State; + switch (payload.State) + { + case JobState.Running: + job.StartedUtc ??= payload.TimestampUtc; + break; + case JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.TimedOut: + job.CompletedUtc = payload.TimestampUtc; + job.ExitCode = payload.ExitCode; + job.OutputSummary = payload.Message; + break; + } + } + + private async Task SweepStatusesAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(60), cancellationToken); + + using var scope = scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var now = DateTimeOffset.UtcNow; + + // Orphan devices that have been silent past the configured window. + if (lifecycle.OrphaningEnabled) + { + var cutoff = now - lifecycle.OrphanAfter; + var stale = await db.Devices + .Where(d => !d.IsOrphaned && d.LastSeenUtc != null && d.LastSeenUtc < cutoff) + .ToListAsync(cancellationToken); + + foreach (var device in stale) + { + device.IsOrphaned = true; + device.OrphanedUtc = now; + logger.LogWarning( + "Device {ClientId} ({Hostname}) orphaned after {Days} day(s) without check-in", + device.ClientId, device.Hostname, lifecycle.OrphanAfterDays); + + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "device-orphaned", + $"{device.Hostname} orphaned after {lifecycle.OrphanAfterDays} day(s) offline", + device.ClientId, null, now), cancellationToken); + } + + if (stale.Count > 0) + { + await db.SaveChangesAsync(cancellationToken); + } + } + + var devices = await db.Devices + .Select(d => new { d.ClientId, d.Hostname, d.LastSeenUtc }) + .ToListAsync(cancellationToken); + + foreach (var device in devices) + { + var current = ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now); + DeviceStatus? previous; + lock (lastKnownStatus) + { + previous = lastKnownStatus.TryGetValue(device.ClientId, out var p) ? p : null; + lastKnownStatus[device.ClientId] = current; + } + + if (previous is DeviceStatus.Online && current is not DeviceStatus.Online) + { + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + "device-offline", + $"{device.Hostname} disconnected", + device.ClientId, + null, + now), cancellationToken); + } + } + } + } + + private T? Parse(byte[]? data) where T : class + { + if (data is null || data.Length == 0) + { + return null; + } + + try + { + return MessageEnvelope.FromUtf8Bytes(data)?.GetPayload(); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to parse message envelope"); + return null; + } + } +} diff --git a/src/Backend/Nats/JetStreamProvisioner.cs b/src/Backend/Nats/JetStreamProvisioner.cs new file mode 100644 index 0000000..ccf3d2e --- /dev/null +++ b/src/Backend/Nats/JetStreamProvisioner.cs @@ -0,0 +1,77 @@ +using NATS.Client.JetStream; +using NATS.Client.JetStream.Models; +using Shared.Infrastructure.Nats; + +namespace Backend.Nats; + +/// +/// Ensures the durable streams exist and creates each agent's durable +/// command consumer (agents cannot manage JetStream themselves — their JWTs +/// only allow pulling from their own consumer). +/// +public sealed class JetStreamProvisioner(NatsHub hub, ILogger logger) +{ + public async Task EnsureStreamsAsync(CancellationToken cancellationToken) + { + if (!hub.IsConfigured) + { + return; + } + + var js = new NatsJSContext(hub.Require()); + + await js.CreateOrUpdateStreamAsync(new StreamConfig( + JetStreamDefaults.CommandStreamName, + JetStreamDefaults.CommandStreamSubjects) + { + Retention = StreamConfigRetention.Limits, + Storage = StreamConfigStorage.File, + MaxAge = JetStreamDefaults.CommandMaxAge, + }, cancellationToken); + + await js.CreateOrUpdateStreamAsync(new StreamConfig( + JetStreamDefaults.JobEventsStreamName, + JetStreamDefaults.JobEventsStreamSubjects) + { + Retention = StreamConfigRetention.Limits, + Storage = StreamConfigStorage.File, + MaxAge = JetStreamDefaults.JobEventsMaxAge, + }, cancellationToken); + + await js.CreateOrUpdateConsumerAsync( + JetStreamDefaults.JobEventsStreamName, + new ConsumerConfig(JetStreamDefaults.BackendJobEventsConsumerName) + { + DurableName = JetStreamDefaults.BackendJobEventsConsumerName, + AckPolicy = ConsumerConfigAckPolicy.Explicit, + AckWait = JetStreamDefaults.CommandAckWait, + FilterSubject = JetStreamDefaults.JobEventsStreamSubjects[0], + }, cancellationToken); + + logger.LogInformation("JetStream streams provisioned"); + } + + /// Creates/refreshes the durable command consumer for one agent. + public async Task EnsureAgentConsumerAsync(string clientId, CancellationToken cancellationToken) + { + if (!hub.IsConfigured) + { + return; + } + + var js = new NatsJSContext(hub.Require()); + var name = JetStreamDefaults.AgentCommandConsumerName(clientId); + + await js.CreateOrUpdateConsumerAsync( + JetStreamDefaults.CommandStreamName, + new ConsumerConfig(name) + { + DurableName = name, + AckPolicy = ConsumerConfigAckPolicy.Explicit, + AckWait = JetStreamDefaults.CommandAckWait, + FilterSubject = JetStreamDefaults.AgentCommandFilterSubject(clientId), + }, cancellationToken); + + logger.LogInformation("Durable command consumer ensured for {ClientId}", clientId); + } +} diff --git a/src/Backend/Nats/NatsAuthCli.cs b/src/Backend/Nats/NatsAuthCli.cs new file mode 100644 index 0000000..e4fee57 --- /dev/null +++ b/src/Backend/Nats/NatsAuthCli.cs @@ -0,0 +1,119 @@ +using NATS.Jwt; +using NATS.Jwt.Models; +using NATS.NKeys; + +namespace Backend.Nats; + +/// +/// Backend nats-auth init --output <dir> — generates a complete +/// operator/account key set for the file-backed NATS resolver using the same +/// NATS.Jwt/NATS.NKeys code the backend uses at runtime: +/// operator (self-signed), APP account with a dedicated signing key, +/// SYS account + sys user, and resolver.conf with the account preload. +/// Seeds are written to files only — never printed or logged. +/// +public static class NatsAuthCli +{ + public static int Run(string[] args) + { + if (args.Length == 0 || args[0] != "init") + { + Console.Error.WriteLine("Usage: Backend nats-auth init --output "); + return 1; + } + + var outputIndex = Array.IndexOf(args, "--output"); + var outputDir = outputIndex >= 0 && outputIndex + 1 < args.Length + ? args[outputIndex + 1] + : Path.Combine("secrets", "nats"); + + Directory.CreateDirectory(outputDir); + + var now = DateTimeOffset.UtcNow; + + using var operatorKey = KeyPair.CreatePair(PrefixByte.Operator); + using var accountKey = KeyPair.CreatePair(PrefixByte.Account); + using var accountSigningKey = KeyPair.CreatePair(PrefixByte.Account); + using var sysAccountKey = KeyPair.CreatePair(PrefixByte.Account); + using var sysUserKey = KeyPair.CreatePair(PrefixByte.User); + + // Operator: self-signed, declares the system account. + var operatorClaims = NatsJwt.NewOperatorClaims(operatorKey.GetPublicKey()); + operatorClaims.Name = "local-operator"; + operatorClaims.Operator.SystemAccount = sysAccountKey.GetPublicKey(); + var operatorJwt = NatsJwt.EncodeOperatorClaims(operatorClaims, operatorKey, now); + + // APP account: signing key registered, JetStream enabled, generous limits. + var accountClaims = NatsJwt.NewAccountClaims(accountKey.GetPublicKey()); + accountClaims.Name = "APP"; + accountClaims.Account.SigningKeys = [accountSigningKey.GetPublicKey()]; + accountClaims.Account.Limits.Conn = -1; + accountClaims.Account.Limits.LeafNodeConn = -1; + accountClaims.Account.Limits.Subs = -1; + accountClaims.Account.Limits.Data = -1; + accountClaims.Account.Limits.Payload = -1; + accountClaims.Account.Limits.Imports = -1; + accountClaims.Account.Limits.Exports = -1; + accountClaims.Account.Limits.WildcardExports = true; + accountClaims.Account.Limits.MemoryStorage = -1; + accountClaims.Account.Limits.DiskStorage = -1; + accountClaims.Account.Limits.Streams = -1; + accountClaims.Account.Limits.Consumer = -1; + var accountJwt = NatsJwt.EncodeAccountClaims(accountClaims, operatorKey, now); + + // SYS account + user (server monitoring / debugging). + var sysAccountClaims = NatsJwt.NewAccountClaims(sysAccountKey.GetPublicKey()); + sysAccountClaims.Name = "SYS"; + var sysAccountJwt = NatsJwt.EncodeAccountClaims(sysAccountClaims, operatorKey, now); + + var sysUserClaims = NatsJwt.NewUserClaims(sysUserKey.GetPublicKey()); + sysUserClaims.Name = "sys"; + var sysUserJwt = NatsJwt.EncodeUserClaims(sysUserClaims, sysAccountKey, now); + + WriteSecret(outputDir, "operator.nk", operatorKey.GetSeed()); + WritePublic(outputDir, "operator.pub", operatorKey.GetPublicKey()); + WriteSecret(outputDir, "account.nk", accountKey.GetSeed()); + WritePublic(outputDir, "account.pub", accountKey.GetPublicKey()); + WriteSecret(outputDir, "account-signing.nk", accountSigningKey.GetSeed()); + WritePublic(outputDir, "account-signing.pub", accountSigningKey.GetPublicKey()); + WriteSecret(outputDir, "sys-account.nk", sysAccountKey.GetSeed()); + WritePublic(outputDir, "sys-account.pub", sysAccountKey.GetPublicKey()); + WriteSecret(outputDir, "sys-user.nk", sysUserKey.GetSeed()); + WritePublic(outputDir, "sys-user.pub", sysUserKey.GetPublicKey()); + WriteSecret(outputDir, "sys.creds", NatsJwt.FormatUserConfig(sysUserJwt, sysUserKey.GetSeed())); + + var resolverConf = $$""" + # Generated by `Backend nats-auth init` — do not commit. + operator: {{operatorJwt}} + system_account: {{sysAccountKey.GetPublicKey()}} + + resolver { + type: full + dir: '/data/resolver' + allow_delete: true + interval: "2m" + } + + resolver_preload { + {{accountKey.GetPublicKey()}}: {{accountJwt}} + {{sysAccountKey.GetPublicKey()}}: {{sysAccountJwt}} + } + """; + File.WriteAllText(Path.Combine(outputDir, "resolver.conf"), resolverConf); + + Console.WriteLine($"NATS auth material written to {Path.GetFullPath(outputDir)}"); + Console.WriteLine($" operator: {operatorKey.GetPublicKey()}"); + Console.WriteLine($" account (APP): {accountKey.GetPublicKey()}"); + Console.WriteLine($" account signing key: {accountSigningKey.GetPublicKey()}"); + Console.WriteLine($" system account: {sysAccountKey.GetPublicKey()}"); + Console.WriteLine("Seeds were written to *.nk files only — keep them secret."); + return 0; + } + + private static void WriteSecret(string dir, string name, string content) + => File.WriteAllText(Path.Combine(dir, name), content + Environment.NewLine); + + private static void WritePublic(string dir, string name, string content) + => File.WriteAllText(Path.Combine(dir, name), content + Environment.NewLine); +} + diff --git a/src/Backend/Nats/NatsCredentialIssuer.cs b/src/Backend/Nats/NatsCredentialIssuer.cs new file mode 100644 index 0000000..1b1efb1 --- /dev/null +++ b/src/Backend/Nats/NatsCredentialIssuer.cs @@ -0,0 +1,83 @@ +using NATS.Jwt; +using NATS.NKeys; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Nats; + +/// +/// Issues scoped NATS user JWTs signed with the account signing key +/// (NATS_ACCOUNT_SIGNING_SEED). Agents get long-lived credentials restricted +/// to their own client id; browsers get short-lived credentials restricted to +/// their session subjects. The signing seed never appears in logs or responses. +/// +public sealed class NatsCredentialIssuer : IDisposable +{ + private readonly KeyPair? signingKey; + private readonly string? accountPublicKey; + + public NatsCredentialIssuer(IConfiguration configuration) + { + var seed = configuration["NATS_ACCOUNT_SIGNING_SEED"]; + var accountKey = configuration["NATS_ACCOUNT_PUBLIC_KEY"]; + + if (!string.IsNullOrWhiteSpace(seed) && !string.IsNullOrWhiteSpace(accountKey)) + { + signingKey = KeyPair.FromSeed(seed.Trim()); + accountPublicKey = accountKey.Trim(); + } + } + + public bool IsConfigured => signingKey is not null; + + public string IssueAgentCredential(string clientId, string userPublicKey) + { + var (key, account) = RequireConfiguration(); + + var claims = NatsJwt.NewUserClaims(userPublicKey); + claims.Name = $"agent-{clientId}"; + claims.User.IssuerAccount = account; + claims.User.Pub.Allow = [.. NatsSubjects.AgentPublishPermissions(clientId)]; + claims.User.Sub.Allow = [.. NatsSubjects.AgentSubscribePermissions(clientId)]; + + return NatsJwt.EncodeUserClaims(claims, key); + } + + public (string Jwt, DateTimeOffset ExpiresUtc) IssueBrowserCredential(string browserSessionId, string userPublicKey) + { + var (key, account) = RequireConfiguration(); + var expires = DateTimeOffset.UtcNow + ProtocolDefaults.BrowserCredentialLifetime; + + var claims = NatsJwt.NewUserClaims(userPublicKey); + claims.Name = $"browser-{browserSessionId}"; + claims.Expires = expires; + claims.User.IssuerAccount = account; + claims.User.Pub.Allow = [.. NatsSubjects.BrowserPublishPermissions(browserSessionId)]; + claims.User.Sub.Allow = [.. NatsSubjects.BrowserSubscribePermissions(browserSessionId)]; + + return (NatsJwt.EncodeUserClaims(claims, key), expires); + } + + /// Full-access credential for the backend's own workers. + public string IssueBackendCredential(string userPublicKey) + { + var (key, account) = RequireConfiguration(); + + var claims = NatsJwt.NewUserClaims(userPublicKey); + claims.Name = "backend"; + claims.User.IssuerAccount = account; + claims.User.Pub.Allow = [">"]; + claims.User.Sub.Allow = [">"]; + + return NatsJwt.EncodeUserClaims(claims, key); + } + + private (KeyPair Key, string Account) RequireConfiguration() + => signingKey is not null && accountPublicKey is not null + ? (signingKey, accountPublicKey) + : throw new InvalidOperationException( + "NATS credential issuer is not configured (NATS_ACCOUNT_SIGNING_SEED / NATS_ACCOUNT_PUBLIC_KEY)."); + + public void Dispose() => signingKey?.Dispose(); +} + diff --git a/src/Backend/Nats/NatsHub.cs b/src/Backend/Nats/NatsHub.cs new file mode 100644 index 0000000..0763c1b --- /dev/null +++ b/src/Backend/Nats/NatsHub.cs @@ -0,0 +1,83 @@ +using NATS.Client.Core; +using NATS.NKeys; + +namespace Backend.Nats; + +/// +/// Owns the backend's NATS connection. The backend self-issues a full-access +/// user JWT with the account signing key at startup (nothing is read from a +/// .creds file). Connection is optional so the API can still start — and +/// report not-ready — when messaging is not configured yet. +/// +public sealed class NatsHub : IAsyncDisposable +{ + private readonly ILogger logger; + + public NatsHub(IConfiguration configuration, NatsCredentialIssuer issuer, ILoggerFactory loggerFactory) + { + logger = loggerFactory.CreateLogger(); + var url = configuration["NATS_URL"]; + + if (string.IsNullOrWhiteSpace(url) || !issuer.IsConfigured) + { + logger.LogWarning("NATS is not configured (NATS_URL / signing seed missing); messaging disabled"); + return; + } + + using var backendKey = KeyPair.CreatePair(PrefixByte.User); + var jwt = issuer.IssueBackendCredential(backendKey.GetPublicKey()); + + var opts = NatsOpts.Default with + { + Url = url.Trim(), + Name = "backend", + AuthOpts = NatsAuthOpts.Default with + { + Jwt = jwt, + Seed = backendKey.GetSeed(), + }, + MaxReconnectRetry = -1, + RetryOnInitialConnect = true, + LoggerFactory = loggerFactory, + }; + + Connection = new NatsConnection(opts); + } + + public NatsConnection? Connection { get; } + + public bool IsConfigured => Connection is not null; + + public bool IsConnected => Connection?.ConnectionState == NatsConnectionState.Open; + + /// Returns the connection or throws when messaging is not configured. + public NatsConnection Require() + => Connection ?? throw new InvalidOperationException("NATS messaging is not configured."); + + public async Task StartAsync(CancellationToken cancellationToken) + { + if (Connection is null) + { + return; + } + + try + { + await Connection.ConnectAsync(); + logger.LogInformation("Backend connected to NATS"); + } + catch (Exception ex) + { + // RetryOnInitialConnect keeps trying in the background. + logger.LogWarning(ex, "Initial NATS connection failed; retrying in background"); + } + } + + public async ValueTask DisposeAsync() + { + if (Connection is not null) + { + await Connection.DisposeAsync(); + } + } +} diff --git a/src/Backend/Program.cs b/src/Backend/Program.cs new file mode 100644 index 0000000..967bb97 --- /dev/null +++ b/src/Backend/Program.cs @@ -0,0 +1,257 @@ +using System.Threading.RateLimiting; +using Backend.Api; +using Backend.Auth; +using Backend.Data; +using Backend.Enrollment; +using Backend.Files; +using Backend.Groups; +using Backend.Jobs; +using Backend.Messaging; +using Backend.Nats; +using Backend.Proxy; +using Backend.Scripts; +using Backend.Security; +using Backend.Shell; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; +using Serilog; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Logging; +using Shared.Infrastructure.Versioning; + +// CLI mode: NATS operator/account key generation for the resolver. +if (args.Length > 0 && args[0] == "nats-auth") +{ + return NatsAuthCli.Run(args[1..]); +} + +var builder = WebApplication.CreateBuilder(args); + +// ── Logging ────────────────────────────────────────────────────────────── +// Centralized Serilog (console + daily rolling file with size cap/retention). +var logSettings = LogSettings.FromConfiguration( + builder.Configuration, LogDefaults.Server, defaultDirectory: "/data/logs"); +builder.Logging.ClearProviders(); +builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "backend"), dispose: true); + +builder.Services.ConfigureHttpJsonOptions(options => +{ + options.SerializerOptions.PropertyNamingPolicy = JsonDefaults.Options.PropertyNamingPolicy; + options.SerializerOptions.DefaultIgnoreCondition = JsonDefaults.Options.DefaultIgnoreCondition; + foreach (var converter in JsonDefaults.Options.Converters) + { + options.SerializerOptions.Converters.Add(converter); + } +}); + +var proxySettings = ProxySettings.FromConfiguration(builder.Configuration); +builder.Services.AddSingleton(proxySettings); + +// ── Persistence ────────────────────────────────────────────────────────── +// SQLite by default; Postgres and SQL Server are selected with +// DATABASE_PROVIDER + DATABASE_CONNECTION_STRING. Each provider carries its +// own migration set; application code always injects AppDbContext. +var databaseOptions = DatabaseOptions.FromConfiguration(builder.Configuration); +builder.Services.AddSingleton(databaseOptions); +builder.Services.AddApplicationDatabase(databaseOptions); + +builder.Services.AddScoped(); +builder.Services.AddSingleton(DeviceLifecycleOptions.FromConfiguration(builder.Configuration)); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// ── Authentication / authorization ───────────────────────────────────────── +var oidcOptions = OidcOptions.FromConfiguration(builder.Configuration); +builder.Services.AddSingleton(oidcOptions); +builder.Services.AddScoped(); +builder.AddControlPlaneAuth(oidcOptions); + +// ── Messaging ──────────────────────────────────────────────────────────── +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(S3Options.FromConfiguration(builder.Configuration)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); + +// ── Rate limiting ──────────────────────────────────────────────────────── +var rateLimitPerMinute = int.TryParse(builder.Configuration["RATE_LIMIT_PER_MINUTE"], out var configuredLimit) && configuredLimit > 0 + ? configuredLimit + : 10; + +builder.Services.AddRateLimiter(options => +{ + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + + options.AddPolicy(RateLimitPolicies.Enrollment, context => + RateLimitPartition.GetFixedWindowLimiter(ClientIp.EffectiveText(context), _ => + new FixedWindowRateLimiterOptions + { + Window = TimeSpan.FromMinutes(1), + PermitLimit = rateLimitPerMinute, + QueueLimit = 0, + })); + + options.AddPolicy(RateLimitPolicies.Auth, context => + RateLimitPartition.GetFixedWindowLimiter(ClientIp.EffectiveText(context), _ => + new FixedWindowRateLimiterOptions + { + Window = TimeSpan.FromMinutes(1), + PermitLimit = rateLimitPerMinute, + QueueLimit = 0, + })); +}); + +var app = builder.Build(); + +// Apply EF migrations at startup; seed the demo script in development. +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + app.Logger.LogInformation("Database ready ({Provider})", databaseOptions.Provider); + + // First-boot initial admin from environment secrets (never a default password). + await scope.ServiceProvider.GetRequiredService().EnsureInitialAdminAsync( + builder.Configuration["INITIAL_ADMIN_USERNAME"], + builder.Configuration["INITIAL_ADMIN_PASSWORD"], + CancellationToken.None); + + if (app.Environment.IsDevelopment() && !db.Scripts.Any()) + { + var now = DateTimeOffset.UtcNow; + db.Scripts.Add(new ScriptEntity + { + Id = Guid.NewGuid(), + Name = "MVP Progress Demo", + Description = "Demonstrates live output and progress end to end.", + Language = ScriptEndpoints.ScriptLanguage, + Content = """ + 1..10 | ForEach-Object { + Write-Progress -Activity 'MVP Progress Demo' -Status "Step $_ of 10" -PercentComplete ($_ * 10) + Write-Output "Completed step $_" + Start-Sleep -Seconds 1 + } + """, + CreatedUtc = now, + UpdatedUtc = now, + CreatedBy = "seed", + UpdatedBy = "seed", + }); + db.SaveChanges(); + } + + if (app.Environment.IsDevelopment() && builder.Configuration["DEV_SEED"] == "1") + { + await DevSeeder.SeedAsync(db, CancellationToken.None); + } +} + +// Forwarded headers must run before anything that inspects scheme/host/IP. +if (proxySettings.TrustProxy) +{ + if (!proxySettings.HasExplicitTrustSources && !app.Environment.IsDevelopment()) + { + throw new InvalidOperationException( + "TRUST_PROXY=1 requires TRUSTED_PROXIES or TRUSTED_NETWORKS outside development mode. " + + "Refusing to trust X-Forwarded-* headers from anywhere."); + } + + app.UseForwardedHeaders(proxySettings.ToForwardedHeadersOptions()); +} + +// Structured request logging: one line per request, enriched with the +// effective (proxy-aware) client IP and the authenticated user. +app.UseSerilogRequestLogging(options => +{ + options.GetLevel = (httpContext, elapsed, ex) => + ex is not null || httpContext.Response.StatusCode >= 500 + ? Serilog.Events.LogEventLevel.Error + : httpContext.Request.Path.StartsWithSegments("/api/health") + || httpContext.Request.Path.StartsWithSegments("/api/ready") + ? Serilog.Events.LogEventLevel.Verbose + : Serilog.Events.LogEventLevel.Information; + + options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => + { + diagnosticContext.Set(LoggingSetup.Fields.RemoteIp, ClientIp.EffectiveText(httpContext)); + if (httpContext.User.Identity?.IsAuthenticated == true) + { + diagnosticContext.Set("User", httpContext.User.Identity.Name); + } + }; +}); + +app.UseRateLimiter(); +app.UseAuthentication(); +app.UseAuthorization(); +app.Use(CsrfProtection.Middleware); + +// Connect the backend NATS client (non-blocking retry when unavailable). +var natsHub = app.Services.GetRequiredService(); +await natsHub.StartAsync(CancellationToken.None); + +if (natsHub.IsConfigured) +{ + try + { + await app.Services.GetRequiredService().EnsureStreamsAsync(CancellationToken.None); + } + catch (Exception ex) + { + app.Logger.LogWarning(ex, "JetStream provisioning failed at startup; will be retried on demand"); + } +} + +// ── Health/readiness ───────────────────────────────────────────────────── +app.MapGet(ApiRoutes.Health, () => Results.Ok(new +{ + status = "ok", + version = BuildVersion.Resolve(typeof(Program).Assembly), +})); + +app.MapGet(ApiRoutes.Ready, async (AppDbContext db, NatsHub hub, NatsCredentialIssuer issuer) => +{ + var databaseReady = await db.Database.CanConnectAsync(); + var signingKeyLoaded = issuer.IsConfigured; + var natsConnected = hub.IsConnected; + + var ready = databaseReady && signingKeyLoaded && natsConnected; + var payload = new + { + status = ready ? "ready" : "not-ready", + checks = new + { + database = databaseReady, + natsConnected, + signingKeyLoaded, + }, + }; + + return ready ? Results.Ok(payload) : Results.Json(payload, statusCode: StatusCodes.Status503ServiceUnavailable); +}); + +AuthEndpoints.Map(app, oidcOptions); +EnrollmentEndpoints.Map(app); +InstallEndpoints.Map(app); +DeviceEndpoints.Map(app); +ScriptEndpoints.Map(app); +FunctionEndpoints.Map(app); +JobEndpoints.Map(app); +BootstrapTokenEndpoints.Map(app); +MessagingEndpoints.Map(app); +ShellEndpoints.Map(app); +FileDeliveryEndpoints.Map(app); +GroupEndpoints.Map(app); +TriggerEndpoints.Map(app); + +app.Run(); +return 0; + +public partial class Program; diff --git a/src/Backend/Proxy/ClientIp.cs b/src/Backend/Proxy/ClientIp.cs new file mode 100644 index 0000000..86fa22e --- /dev/null +++ b/src/Backend/Proxy/ClientIp.cs @@ -0,0 +1,17 @@ +using System.Net; + +namespace Backend.Proxy; + +/// +/// The single place the effective real client IP is resolved. After the +/// Forwarded Headers Middleware has run, RemoteIpAddress already reflects +/// the forwarded client when the immediate peer was trusted. +/// +public static class ClientIp +{ + public static IPAddress? Effective(HttpContext context) + => context.Connection.RemoteIpAddress; + + public static string EffectiveText(HttpContext context) + => context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; +} diff --git a/src/Backend/Proxy/ProxySettings.cs b/src/Backend/Proxy/ProxySettings.cs new file mode 100644 index 0000000..0333da5 --- /dev/null +++ b/src/Backend/Proxy/ProxySettings.cs @@ -0,0 +1,91 @@ +using System.Net; +using Microsoft.AspNetCore.HttpOverrides; + +namespace Backend.Proxy; + +/// +/// Reverse-proxy trust configuration. TRUST_PROXY=1 alone is not enough: +/// outside development mode at least one trusted proxy or network must be +/// configured, otherwise forwarded headers are ignored. +/// +public sealed class ProxySettings +{ + public bool TrustProxy { get; init; } + public IReadOnlyList TrustedProxies { get; init; } = []; + public IReadOnlyList<(IPAddress Prefix, int PrefixLength)> TrustedNetworks { get; init; } = []; + public IReadOnlyList TrustedHosts { get; init; } = []; + public int ForwardLimit { get; init; } = 1; + + public bool HasExplicitTrustSources => TrustedProxies.Count > 0 || TrustedNetworks.Count > 0; + + public static ProxySettings FromConfiguration(IConfiguration configuration) + { + var trustProxy = configuration["TRUST_PROXY"] == "1"; + + var proxies = SplitList(configuration["TRUSTED_PROXIES"]) + .Select(value => IPAddress.TryParse(value, out var ip) ? ip : null) + .Where(ip => ip is not null) + .Select(ip => ip!) + .ToList(); + + var networks = new List<(IPAddress, int)>(); + foreach (var value in SplitList(configuration["TRUSTED_NETWORKS"])) + { + var slash = value.IndexOf('/'); + if (slash > 0 + && IPAddress.TryParse(value[..slash], out var prefix) + && int.TryParse(value[(slash + 1)..], out var length)) + { + networks.Add((prefix, length)); + } + } + + var forwardLimit = int.TryParse(configuration["FORWARD_LIMIT"], out var limit) && limit > 0 ? limit : 1; + + return new ProxySettings + { + TrustProxy = trustProxy, + TrustedProxies = proxies, + TrustedNetworks = networks, + TrustedHosts = SplitList(configuration["TRUSTED_HOSTS"]), + ForwardLimit = forwardLimit, + }; + } + + public ForwardedHeadersOptions ToForwardedHeadersOptions() + { + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor + | ForwardedHeaders.XForwardedProto + | ForwardedHeaders.XForwardedHost + | ForwardedHeaders.XForwardedPrefix, + ForwardLimit = ForwardLimit, + }; + + // Do NOT trust every source: clear defaults, add configured ones only. + options.KnownProxies.Clear(); + options.KnownIPNetworks.Clear(); + foreach (var proxy in TrustedProxies) + { + options.KnownProxies.Add(proxy); + } + + foreach (var (prefix, length) in TrustedNetworks) + { + options.KnownIPNetworks.Add(new System.Net.IPNetwork(prefix, length)); + } + + if (TrustedHosts.Count > 0) + { + options.AllowedHosts = TrustedHosts.ToList(); + } + + return options; + } + + private static List SplitList(string? value) + => string.IsNullOrWhiteSpace(value) + ? [] + : value.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); +} diff --git a/src/Backend/Scripts/FunctionEndpoints.cs b/src/Backend/Scripts/FunctionEndpoints.cs new file mode 100644 index 0000000..6f8e95a --- /dev/null +++ b/src/Backend/Scripts/FunctionEndpoints.cs @@ -0,0 +1,98 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; + +namespace Backend.Scripts; + +/// CRUD for reusable PowerShell function modules. +public static class FunctionEndpoints +{ + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.FunctionModules, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.FunctionModules, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapGet(ApiRoutes.FunctionModule, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPut(ApiRoutes.FunctionModule, UpdateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.FunctionModule, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var modules = await db.FunctionModules.AsNoTracking().OrderBy(m => m.Name).ToListAsync(cancellationToken); + return Results.Ok(modules.Select(ToDto).ToList()); + } + + private static async Task GetAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + { + var module = await db.FunctionModules.AsNoTracking().SingleOrDefaultAsync(m => m.Id == id, cancellationToken); + return module is null ? Results.NotFound() : Results.Ok(ToDto(module)); + } + + private static async Task CreateAsync( + SaveFunctionModuleRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Name is required." }); + } + + var now = DateTimeOffset.UtcNow; + var module = new FunctionModuleEntity + { + Id = Guid.NewGuid(), + Name = request.Name.Trim(), + Description = request.Description, + Content = request.Content ?? string.Empty, + CreatedUtc = now, + UpdatedUtc = now, + UpdatedBy = context.User.Identity?.Name, + }; + db.FunctionModules.Add(module); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Scripts, "function-created", context.User.Identity?.Name, + detail: module.Name, cancellationToken: cancellationToken); + + return Results.Created(ApiRoutes.For.FunctionModule(module.Id), ToDto(module)); + } + + private static async Task UpdateAsync( + Guid id, SaveFunctionModuleRequest request, AppDbContext db, HttpContext context, CancellationToken cancellationToken) + { + var module = await db.FunctionModules.SingleOrDefaultAsync(m => m.Id == id, cancellationToken); + if (module is null) + { + return Results.NotFound(); + } + + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Name is required." }); + } + + module.Name = request.Name.Trim(); + module.Description = request.Description; + module.Content = request.Content ?? string.Empty; + module.UpdatedUtc = DateTimeOffset.UtcNow; + module.UpdatedBy = context.User.Identity?.Name; + await db.SaveChangesAsync(cancellationToken); + return Results.Ok(ToDto(module)); + } + + private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + { + var module = await db.FunctionModules.SingleOrDefaultAsync(m => m.Id == id, cancellationToken); + if (module is null) + { + return Results.NotFound(); + } + + db.FunctionModules.Remove(module); + await db.SaveChangesAsync(cancellationToken); + return Results.NoContent(); + } + + private static FunctionModuleDto ToDto(FunctionModuleEntity m) => + new(m.Id, m.Name, m.Description, m.Content, m.CreatedUtc, m.UpdatedUtc, m.UpdatedBy); +} diff --git a/src/Backend/Scripts/ScriptEndpoints.cs b/src/Backend/Scripts/ScriptEndpoints.cs new file mode 100644 index 0000000..ca04f43 --- /dev/null +++ b/src/Backend/Scripts/ScriptEndpoints.cs @@ -0,0 +1,134 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Backend.Scripts; + +public static class ScriptEndpoints +{ + public const string ScriptLanguage = "PowerShell"; + + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.Scripts, ListAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPost(ApiRoutes.Scripts, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapGet(ApiRoutes.Script, GetAsync).RequireAuthorization(AuthConstants.PolicyViewer); + app.MapPut(ApiRoutes.Script, UpdateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + app.MapDelete(ApiRoutes.Script, DeleteAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) + { + var scripts = await db.Scripts.AsNoTracking() + .OrderBy(s => s.Name) + .ToListAsync(cancellationToken); + return Results.Ok(scripts.Select(ToDto).ToList()); + } + + private static async Task GetAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + { + var script = await db.Scripts.AsNoTracking().SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + return script is null ? Results.NotFound() : Results.Ok(ToDto(script)); + } + + private static async Task CreateAsync( + SaveScriptRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Script name is required." }); + } + + var now = DateTimeOffset.UtcNow; + var actor = context.User.Identity?.Name; + var script = new ScriptEntity + { + Id = Guid.NewGuid(), + Name = request.Name.Trim(), + Description = request.Description, + Language = ScriptLanguage, + Content = request.Content ?? string.Empty, + ParametersJson = SerializeParameters(request.Parameters), + FunctionModuleIdsJson = SerializeModuleIds(request.FunctionModuleIds), + CreatedUtc = now, + UpdatedUtc = now, + CreatedBy = actor, + UpdatedBy = actor, + }; + db.Scripts.Add(script); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Scripts, "created", actor, detail: script.Name, cancellationToken: cancellationToken); + + return Results.Created(ApiRoutes.For.Script(script.Id), ToDto(script)); + } + + private static async Task UpdateAsync( + Guid id, SaveScriptRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var script = await db.Scripts.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + if (script is null) + { + return Results.NotFound(); + } + + if (string.IsNullOrWhiteSpace(request.Name)) + { + return Results.BadRequest(new { error = "Script name is required." }); + } + + 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.UpdatedUtc = DateTimeOffset.UtcNow; + script.UpdatedBy = context.User.Identity?.Name; + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Scripts, "updated", script.UpdatedBy, detail: script.Name, cancellationToken: cancellationToken); + + return Results.Ok(ToDto(script)); + } + + private static async Task DeleteAsync( + Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var script = await db.Scripts.SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + if (script is null) + { + return Results.NotFound(); + } + + db.Scripts.Remove(script); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync( + AuditCategories.Scripts, "deleted", context.User.Identity?.Name, detail: script.Name, cancellationToken: cancellationToken); + + return Results.NoContent(); + } + + private static ScriptDto ToDto(ScriptEntity script) => new( + script.Id, script.Name, script.Description, script.Language, script.Content, + DeserializeParameters(script.ParametersJson), + DeserializeModuleIds(script.FunctionModuleIdsJson), + script.CreatedUtc, script.UpdatedUtc, script.CreatedBy, script.UpdatedBy); + + internal static string? SerializeParameters(IReadOnlyList? parameters) + => parameters is null || parameters.Count == 0 ? null : JsonDefaults.Serialize(parameters); + + internal static IReadOnlyList DeserializeParameters(string? json) + => string.IsNullOrWhiteSpace(json) + ? [] + : JsonDefaults.Deserialize>(json) ?? []; + + internal static string? SerializeModuleIds(IReadOnlyList? ids) + => ids is null || ids.Count == 0 ? null : JsonDefaults.Serialize(ids); + + internal static IReadOnlyList DeserializeModuleIds(string? json) + => string.IsNullOrWhiteSpace(json) + ? [] + : JsonDefaults.Deserialize>(json) ?? []; +} diff --git a/src/Backend/Security/AuditService.cs b/src/Backend/Security/AuditService.cs new file mode 100644 index 0000000..97db65d --- /dev/null +++ b/src/Backend/Security/AuditService.cs @@ -0,0 +1,40 @@ +using Backend.Data; + +namespace Backend.Security; + +/// Append-only audit trail. Never write secret material into Detail. +public sealed class AuditService(AppDbContext db) +{ + public async Task LogAsync( + string category, + string action, + string? actor = null, + string? clientId = null, + string? detail = null, + string? remoteIp = null, + CancellationToken cancellationToken = default) + { + db.AuditEvents.Add(new AuditEventEntity + { + TimestampUtc = DateTimeOffset.UtcNow, + Category = category, + Action = action, + Actor = actor, + ClientId = clientId, + Detail = detail, + RemoteIp = remoteIp, + }); + await db.SaveChangesAsync(cancellationToken); + } +} + +/// Audit category/action constants. +public static class AuditCategories +{ + public const string Enrollment = "enrollment"; + public const string Auth = "auth"; + public const string Jobs = "jobs"; + public const string Scripts = "scripts"; + public const string Shell = "shell"; + public const string Admin = "admin"; +} diff --git a/src/Backend/Security/RateLimitPolicies.cs b/src/Backend/Security/RateLimitPolicies.cs new file mode 100644 index 0000000..86048af --- /dev/null +++ b/src/Backend/Security/RateLimitPolicies.cs @@ -0,0 +1,8 @@ +namespace Backend.Security; + +/// Named rate-limit policies. +public static class RateLimitPolicies +{ + public const string Enrollment = "enrollment"; + public const string Auth = "auth"; +} diff --git a/src/Backend/Shell/ShellBridge.cs b/src/Backend/Shell/ShellBridge.cs new file mode 100644 index 0000000..27a29b0 --- /dev/null +++ b/src/Backend/Shell/ShellBridge.cs @@ -0,0 +1,217 @@ +using System.Collections.Concurrent; +using Backend.Messaging; +using Backend.Nats; +using NATS.Client.Core; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Nats; + +namespace Backend.Shell; + +/// Tracks a live shell session's ownership and endpoints. +public sealed record ShellBinding( + Guid ShellId, + string ClientId, + string OwnerBrowserSessionId); + +/// +/// Bridges browser ⇄ agent shell traffic. The browser never gets permission to +/// publish agent command subjects: it publishes to its own +/// browser.<sid>.shell.<shellId>.input, the backend validates +/// ownership and republishes to the privileged agent command subject. Agent +/// output/state is relayed to the owning browser session only. +/// +public sealed class ShellBridge( + NatsHub hub, + BrowserEventBroadcaster broadcaster, + ILogger logger) : BackgroundService +{ + private static readonly EndpointRef BackendSource = new(EndpointKinds.Backend, "backend"); + private readonly ConcurrentDictionary bindings = new(); + + public ShellBinding Register(Guid shellId, string clientId, string ownerBrowserSessionId) + { + var binding = new ShellBinding(shellId, clientId, ownerBrowserSessionId); + bindings[shellId] = binding; + return binding; + } + + /// Publishes the privileged shell.open command to the agent. + public async Task OpenAsync(ShellBinding binding, int cols, int rows, CancellationToken cancellationToken) + { + var envelope = MessageEnvelope.Create( + MessageTypes.CommandShellOpen, + BackendSource, + new ShellOpenCommandPayload(binding.ShellId, cols, rows), + new EndpointRef(EndpointKinds.Agent, binding.ClientId)); + + await hub.Require().PublishAsync( + NatsSubjects.AgentCommandShellOpen(binding.ClientId), envelope.ToUtf8Bytes(), + cancellationToken: cancellationToken); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!hub.IsConfigured) + { + return; + } + + await Task.WhenAll( + RunLoopAsync("browser-shell-input", () => RelayBrowserInputAsync(stoppingToken), stoppingToken), + RunLoopAsync("agent-shell-output", () => RelayAgentOutputAsync(stoppingToken), stoppingToken)); + } + + private async Task RunLoopAsync(string name, Func loop, CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await loop(); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + logger.LogError(ex, "Shell bridge loop '{Loop}' failed; restarting in 5s", name); + await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); + } + } + } + + /// Browser → agent: input/resize/close forwarded after ownership check. + private async Task RelayBrowserInputAsync(CancellationToken cancellationToken) + { + // browser.*.shell.*.input — the only browser→backend shell channel. + await foreach (var msg in hub.Require().SubscribeAsync("browser.*.shell.*.input", cancellationToken: cancellationToken)) + { + var parts = msg.Subject.Split('.'); + if (parts.Length < 5 || !Guid.TryParse(parts[3], out var shellId)) + { + continue; + } + + var browserSessionId = parts[1]; + if (!bindings.TryGetValue(shellId, out var binding) || binding.OwnerBrowserSessionId != browserSessionId) + { + logger.LogWarning("Rejected shell input for {ShellId} from unauthorized session", shellId); + continue; + } + + var envelope = msg.Data is { Length: > 0 } ? MessageEnvelope.FromUtf8Bytes(msg.Data) : null; + if (envelope is null) + { + continue; + } + + await ForwardToAgentAsync(binding, envelope, cancellationToken); + } + } + + private async Task ForwardToAgentAsync(ShellBinding binding, MessageEnvelope envelope, CancellationToken cancellationToken) + { + var connection = hub.Require(); + var target = new EndpointRef(EndpointKinds.Agent, binding.ClientId); + + switch (envelope.MessageType) + { + case MessageTypes.ShellInput or MessageTypes.CommandShellInput: + var input = envelope.GetPayload(); + if (input is not null) + { + var forward = MessageEnvelope.Create( + MessageTypes.CommandShellInput, BackendSource, + new ShellInputPayload(binding.ShellId, input.DataBase64), target); + await connection.PublishAsync( + NatsSubjects.AgentCommandShellInput(binding.ClientId), forward.ToUtf8Bytes(), + cancellationToken: cancellationToken); + } + + break; + + case MessageTypes.CommandShellResize: + var resize = envelope.GetPayload(); + if (resize is not null) + { + var forward = MessageEnvelope.Create( + MessageTypes.CommandShellResize, BackendSource, + new ShellResizePayload(binding.ShellId, resize.Cols, resize.Rows), target); + await connection.PublishAsync( + NatsSubjects.AgentCommandShellResize(binding.ClientId), forward.ToUtf8Bytes(), + cancellationToken: cancellationToken); + } + + break; + + case MessageTypes.CommandShellClose: + await CloseAsync(binding, "closed by browser", cancellationToken); + break; + } + } + + public async Task CloseAsync(ShellBinding binding, string reason, CancellationToken cancellationToken) + { + bindings.TryRemove(binding.ShellId, out _); + var envelope = MessageEnvelope.Create( + MessageTypes.CommandShellClose, BackendSource, + new ShellClosePayload(binding.ShellId, reason), + new EndpointRef(EndpointKinds.Agent, binding.ClientId)); + + await hub.Require().PublishAsync( + NatsSubjects.AgentCommandShellClose(binding.ClientId), envelope.ToUtf8Bytes(), + cancellationToken: cancellationToken); + } + + /// Agent → browser: output/state relayed to the owning session only. + private async Task RelayAgentOutputAsync(CancellationToken cancellationToken) + { + await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllAgentShellStreams, cancellationToken: cancellationToken)) + { + // agent..shell..output|state + var parts = msg.Subject.Split('.'); + if (parts.Length < 5 || !Guid.TryParse(parts[3], out var shellId)) + { + continue; + } + + if (!bindings.TryGetValue(shellId, out var binding)) + { + continue; + } + + var envelope = msg.Data is { Length: > 0 } ? MessageEnvelope.FromUtf8Bytes(msg.Data) : null; + if (envelope is null) + { + continue; + } + + var kind = parts[4]; + if (kind == "output") + { + var payload = envelope.GetPayload(); + if (payload is not null) + { + await broadcaster.SendShellEventAsync( + binding.OwnerBrowserSessionId, shellId, MessageTypes.ShellOutput, payload, cancellationToken); + } + } + else if (kind == "state") + { + var payload = envelope.GetPayload(); + if (payload is not null) + { + await broadcaster.SendShellEventAsync( + binding.OwnerBrowserSessionId, shellId, MessageTypes.ShellState, payload, cancellationToken); + + if (payload.State is ShellSessionState.Closed or ShellSessionState.Failed) + { + bindings.TryRemove(shellId, out _); + } + } + } + } + } +} diff --git a/src/Backend/Shell/ShellEndpoints.cs b/src/Backend/Shell/ShellEndpoints.cs new file mode 100644 index 0000000..b12a046 --- /dev/null +++ b/src/Backend/Shell/ShellEndpoints.cs @@ -0,0 +1,75 @@ +using Backend.Auth; +using Backend.Data; +using Backend.Messaging; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; + +namespace Backend.Shell; + +/// +/// POST /api/devices/{clientId}/shell — backend authorizes, creates the shell +/// session, binds it to the requesting browser session, records metadata +/// (transcripts are never persisted) and publishes the privileged open command. +/// +public static class ShellEndpoints +{ + public static void Map(WebApplication app) + { + app.MapPost(ApiRoutes.DeviceShell, CreateAsync).RequireAuthorization(AuthConstants.PolicyOperator); + } + + private static async Task CreateAsync( + string clientId, + CreateShellRequest request, + AppDbContext db, + ShellBridge bridge, + BrowserSessionRegistry sessions, + AuditService audit, + HttpContext context, + CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId) || !SubjectIdentifier.IsValid(request.BrowserSessionId)) + { + return Results.BadRequest(new { error = "Invalid request." }); + } + + // The browser session must be live (proves the caller owns that credential). + if (sessions.Touch(request.BrowserSessionId) is null) + { + return Results.BadRequest(new { error = "Unknown or expired browser session." }); + } + + var device = await db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + if (device is null) + { + return Results.NotFound(); + } + + var shellId = Guid.NewGuid(); + var actor = context.User.Identity?.Name; + + db.ShellSessions.Add(new ShellSessionEntity + { + Id = shellId, + ClientId = clientId, + RequestedBy = actor, + State = ShellSessionState.Requested, + CreatedUtc = DateTimeOffset.UtcNow, + }); + await db.SaveChangesAsync(cancellationToken); + + var binding = bridge.Register(shellId, clientId, request.BrowserSessionId); + await bridge.OpenAsync(binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), cancellationToken); + + await audit.LogAsync(AuditCategories.Shell, "opened", actor, + clientId: clientId, detail: $"shell={shellId}", + remoteIp: Proxy.ClientIp.EffectiveText(context), cancellationToken: cancellationToken); + + return Results.Ok(new CreateShellResponse( + shellId, clientId, device.Hostname, DateTimeOffset.UtcNow + ProtocolDefaults.ShellMaxLifetime)); + } +} diff --git a/src/Infra/backend/Dockerfile b/src/Infra/backend/Dockerfile new file mode 100644 index 0000000..d47b191 --- /dev/null +++ b/src/Infra/backend/Dockerfile @@ -0,0 +1,43 @@ +# syntax=docker/dockerfile:1 +# Build context is the repository root. + +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG UNIFIED_VERSION=0.0.0.0 +WORKDIR /source + +# Restore layer: copy only project/props files first for build caching. +COPY global.json Directory.Build.props Directory.Packages.props ./ +COPY src/Shared.Contracts/Shared.Contracts.csproj src/Shared.Contracts/ +COPY src/Shared.Infrastructure/Shared.Infrastructure.csproj src/Shared.Infrastructure/ +COPY src/Backend/Backend.csproj src/Backend/ +RUN dotnet restore src/Backend/Backend.csproj + +COPY src/Shared.Contracts/ src/Shared.Contracts/ +COPY src/Shared.Infrastructure/ src/Shared.Infrastructure/ +COPY src/Backend/ src/Backend/ +RUN dotnet publish src/Backend/Backend.csproj -c Release -o /app --no-restore \ + -p:UnifiedVersion=${UNIFIED_VERSION} + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime +ARG UNIFIED_VERSION=0.0.0.0 +LABEL org.opencontainers.image.title="Control Plane Backend" \ + org.opencontainers.image.version="${UNIFIED_VERSION}" + +# curl is used by the compose health check. +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /data \ + && chown app:app /data + +WORKDIR /app +COPY --from=build /app . + +ENV ASPNETCORE_URLS=http://0.0.0.0:8080 \ + DATABASE_PATH=/data/app.db + +VOLUME /data +EXPOSE 8080 +USER app + +ENTRYPOINT ["dotnet", "Backend.dll"] diff --git a/src/Infra/nats/nats.conf b/src/Infra/nats/nats.conf new file mode 100644 index 0000000..163e124 --- /dev/null +++ b/src/Infra/nats/nats.conf @@ -0,0 +1,26 @@ +# NATS server configuration for the MVP stack. +# Operator/JWT mode with a file-backed full resolver. The operator JWT and +# account preload live in resolver.conf, generated by scripts/New-LocalSecrets.ps1 +# (never committed) and mounted at /etc/nats/resolver.conf. + +server_name: control-nats + +# Internal NATS TCP for backend/services (Docker network only; never public). +port: 4222 + +# Monitoring endpoint used by the container health check (internal only). +http_port: 8222 + +jetstream { + store_dir: /data/jetstream +} + +# WebSocket listener terminated behind the reverse proxy. +# TLS is terminated at the proxy, so the listener itself is plaintext and +# must never be exposed directly to the public network. +websocket { + port: 9222 + no_tls: true +} + +include /etc/nats/resolver.conf diff --git a/src/Infra/nats/resolver/README.md b/src/Infra/nats/resolver/README.md new file mode 100644 index 0000000..9b6639f --- /dev/null +++ b/src/Infra/nats/resolver/README.md @@ -0,0 +1,14 @@ +# NATS resolver + +The file-backed full resolver stores account JWTs below `/data/resolver` +(the `nats-resolver` Docker volume). + +`resolver.conf` — containing the operator JWT, system account and the +account preload — is **generated**, not committed. Run: + +```powershell +./scripts/New-LocalSecrets.ps1 +``` + +which writes `secrets/nats/resolver.conf`; docker-compose mounts it at +`/etc/nats/resolver.conf`. diff --git a/src/Infra/nginx/README.md b/src/Infra/nginx/README.md new file mode 100644 index 0000000..eac57d2 --- /dev/null +++ b/src/Infra/nginx/README.md @@ -0,0 +1,54 @@ +# nginx sample configuration + +`executer.conf` fronts the whole stack on one TLS edge. It is a single +self-contained file — no `include`/snippet files needed. + +## Install + +```bash +cp executer.conf /etc/nginx/sites-available/executer.conf +ln -s /etc/nginx/sites-available/executer.conf /etc/nginx/sites-enabled/ +nginx -t && systemctl reload nginx +``` + +With nginx-ui, paste the whole file in as a new site. + +## Replace before use + +| Placeholder | Meaning | +|-------------|---------| +| `control.example.com` | Your public hostname | +| `10.0.0.10` | The Docker host running the ExecuteR stack | +| `/etc/nginx/ssl/...` | Your certificate and key paths | + +Ports match `.env` defaults: WebUI `13080`, backend `19080`, NATS WebSocket +`19222`. + +## What the config does + +- Redirects HTTP to HTTPS, leaving `/.well-known/acme-challenge/` reachable +- Routes `/` to the WebUI, `/api/` to the backend, and both + `/messaging/agent` and `/messaging/browser` to the NATS WebSocket listener +- Keeps WebSockets alive (1h read/send timeouts, buffering off) — without this + agents and browsers reconnect every 60s +- Rate limits enrollment and sign-in at the edge, on top of the backend's own + limits +- Sends the forwarded headers the backend needs, and sets common security + headers + +## Two things that will bite you + +1. **Trusted proxies.** The backend only honors `X-Forwarded-*` from IPs in + `TRUSTED_PROXIES` / `TRUSTED_NETWORKS`. Add this nginx host, or every + request will look like it came from the proxy. +2. **Duplicate `http{}` directives.** The `map $http_upgrade` and the two + `limit_req_zone` lines at the top of the file belong at `http{}` level. If + your `nginx.conf` already defines `$connection_upgrade` or those zones, + delete the duplicates or nginx will refuse to start. + +## IP allow-lists + +Commented `allow` / `deny` blocks are included at three levels — whole site, +`/messaging/agent`, and `/api/enrollment/`. Uncomment and edit the ones you +want. Enrollment is the most valuable to restrict: it is the anonymous +endpoint agents use to join. diff --git a/src/Infra/nginx/executer.conf b/src/Infra/nginx/executer.conf new file mode 100644 index 0000000..6a09662 --- /dev/null +++ b/src/Infra/nginx/executer.conf @@ -0,0 +1,188 @@ +#============================================================================= +# ExecuteR - nginx site (single self-contained file, nginx-ui friendly) +#============================================================================= +# +# Fronts the three stack services on one public TLS edge: +# / -> WebUI (host port 13080) +# /api/ -> Backend API (host port 19080) +# /messaging/agent -> NATS WebSocket (host port 19222) +# /messaging/browser -> NATS WebSocket (host port 19222) +# +# BEFORE USE, replace: +# control.example.com your public hostname +# 10.0.0.10 the Docker host running the ExecuteR stack +# /etc/nginx/ssl/... your certificate paths +# +# Self-contained: no include/snippet files required. +#============================================================================= + +# --- http{} level directives ------------------------------------------------ +# These three must live at http{} level. If your nginx.conf already defines +# any of them, delete the duplicate here or nginx will refuse to start. + +limit_req_zone $binary_remote_addr zone=executer_enroll:10m rate=10r/m; +limit_req_zone $binary_remote_addr zone=executer_auth:10m rate=20r/m; + +# "upgrade" for WebSocket requests, "close" otherwise. +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} + +# --- Upstreams -------------------------------------------------------------- +upstream executer_webui { + server 10.0.0.10:13080; + keepalive 16; +} + +upstream executer_api { + server 10.0.0.10:19080; + keepalive 16; +} + +upstream executer_nats { + server 10.0.0.10:19222; + keepalive 32; +} + +# --- HTTP: redirect to HTTPS ------------------------------------------------ +server { + listen 80; + listen [::]:80; + server_name control.example.com; + + # Allow ACME HTTP-01 challenges to pass through un-redirected. + location ^~ /.well-known/acme-challenge/ { + root /var/www/acme; + default_type "text/plain"; + } + + location / { + return 301 https://$server_name$request_uri; + } +} + +# --- HTTPS ------------------------------------------------------------------ +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name control.example.com; + + ssl_certificate /etc/nginx/ssl/control.example.com/fullchain.cer; + ssl_certificate_key /etc/nginx/ssl/control.example.com/private.key; + + access_log /var/log/nginx/control.example.com_access.log; + error_log /var/log/nginx/control.example.com_error.log; + + # --- Forwarded headers --------------------------------------------------- + # The backend only honors these from IPs listed in TRUSTED_PROXIES / + # TRUSTED_NETWORKS, so make sure THIS host is included there — otherwise + # every request appears to originate from the proxy itself. + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header X-Forwarded-Port $server_port; + # Set this if you mount the app under a sub-path instead of the site root. + proxy_set_header X-Forwarded-Prefix /; + + # --- WebSocket upgrade (safe site-wide; $connection_upgrade is "close" + # for ordinary requests) ----------------------------------------------- + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + + # Agent job output and file uploads can be large; scripts are small but + # inventory payloads are not. Disable the body cap for the API instead of + # guessing a number. + client_max_body_size 0; + + # Security headers (the app is same-origin; adjust CSP if you embed it). + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header Referrer-Policy "same-origin" always; + add_header Strict-Transport-Security "max-age=31536000" always; + + # ---------------------------------------------------------------------- + # Optional: restrict the whole site to known networks. + # Uncomment and edit, then reload nginx. + # ---------------------------------------------------------------------- + # allow 10.0.0.0/8; # RFC1918 - internal + # allow 172.16.0.0/12; # RFC1918 - internal + # allow 192.168.0.0/16; # RFC1918 - internal + # allow 203.0.113.0/24; # office egress + # allow 2001:db8::/32; # office egress (IPv6) + # deny all; + + # ── NATS WebSocket: agents ──────────────────────────────────────────── + # Agents connect here with wss:// derived from their ServerURL. + location = /messaging/agent { + proxy_pass http://executer_nats; + + # WebSockets are long-lived: do not let nginx time them out. + proxy_read_timeout 1h; + proxy_send_timeout 1h; + proxy_buffering off; + + # Optional: agents only from trusted networks. + # allow 10.0.0.0/8; + # deny all; + } + + # ── NATS WebSocket: browsers ────────────────────────────────────────── + location = /messaging/browser { + proxy_pass http://executer_nats; + + proxy_read_timeout 1h; + proxy_send_timeout 1h; + proxy_buffering off; + } + + # ── Enrollment: rate limited, no caching ────────────────────────────── + location ^~ /api/enrollment/ { + limit_req zone=executer_enroll burst=5 nodelay; + proxy_pass http://executer_api; + proxy_http_version 1.1; + proxy_set_header Connection ""; + + # The agent package download can be tens of MB. + proxy_read_timeout 300s; + proxy_buffering off; + + # Optional: only let known networks enroll. + # allow 10.0.0.0/8; + # deny all; + } + + # ── Sign-in: rate limited ───────────────────────────────────────────── + location ^~ /api/auth/ { + limit_req zone=executer_auth burst=10 nodelay; + proxy_pass http://executer_api; + proxy_http_version 1.1; + proxy_set_header Connection ""; + } + + # ── Backend API ─────────────────────────────────────────────────────── + location ^~ /api/ { + proxy_pass http://executer_api; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_read_timeout 120s; + } + + # ── OIDC callback (handled by the backend) ──────────────────────────── + location = /signin-oidc { + proxy_pass http://executer_api; + proxy_http_version 1.1; + proxy_set_header Connection ""; + } + + # ── WebUI (everything else) ─────────────────────────────────────────── + location / { + proxy_pass http://executer_webui; + proxy_http_version 1.1; + proxy_set_header Connection ""; + } +} diff --git a/src/Infra/webui/Dockerfile b/src/Infra/webui/Dockerfile new file mode 100644 index 0000000..8b38627 --- /dev/null +++ b/src/Infra/webui/Dockerfile @@ -0,0 +1,31 @@ +# syntax=docker/dockerfile:1 +# Build context is the repository root. + +FROM node:24-alpine AS build +ARG UNIFIED_VERSION=0.0.0.0 +WORKDIR /app + +COPY src/WebUI/package.json src/WebUI/package-lock.json ./ +RUN npm ci + +COPY src/WebUI/ . +ENV PUBLIC_BUILD_VERSION=${UNIFIED_VERSION} +RUN npm run build && npm prune --omit=dev + +FROM node:24-alpine +ARG UNIFIED_VERSION=0.0.0.0 +LABEL org.opencontainers.image.title="Control Plane WebUI" \ + org.opencontainers.image.version="${UNIFIED_VERSION}" + +WORKDIR /app +COPY --from=build /app/build ./build +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/package.json . + +ENV PORT=3000 \ + NODE_ENV=production + +EXPOSE 3000 +USER node + +CMD ["node", "build"] diff --git a/src/Installer/Agent.Installer.wixproj b/src/Installer/Agent.Installer.wixproj new file mode 100644 index 0000000..c7b1269 --- /dev/null +++ b/src/Installer/Agent.Installer.wixproj @@ -0,0 +1,24 @@ + + + + + Agent + x64 + + ICE61 + + 0.0.0 + + $(MSBuildThisFileDirectory)..\Agent\bin\Release\net10.0-windows\win-x64\publish + $(MSBuildThisFileDirectory)..\..\artifacts\icons\app.ico + $(DefineConstants);UnifiedVersion=$(UnifiedVersion);MsiProductVersion=$(MsiProductVersion);AgentPublishDir=$(AgentPublishDir) + $(DefineConstants);AppIconPath=$(AppIconPath) + + + + + + + diff --git a/src/Installer/Policies/ExecuteR.admx b/src/Installer/Policies/ExecuteR.admx new file mode 100644 index 0000000..81344be --- /dev/null +++ b/src/Installer/Policies/ExecuteR.admx @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Trace + Debug + Information + Warning + Error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Installer/Policies/README.md b/src/Installer/Policies/README.md new file mode 100644 index 0000000..23bf0b6 --- /dev/null +++ b/src/Installer/Policies/README.md @@ -0,0 +1,44 @@ +# ExecuteR Group Policy templates + +`ExecuteR.admx` + `en-US/ExecuteR.adml` configure the agent through Group Policy. +They write to the policy key the agent reads with highest precedence: + +``` +HKLM\SOFTWARE\Policies\ExecuteR +``` + +Precedence in the agent is **GroupPolicy > normal registry > compiled defaults**, +so a policy value always wins over an MSI/registry value. + +## Install (single machine) + +``` +copy ExecuteR.admx %WINDIR%\PolicyDefinitions\ +copy en-US\ExecuteR.adml %WINDIR%\PolicyDefinitions\en-US\ +``` + +Then open `gpedit.msc` → Computer Configuration → Administrative Templates → +Grace Solution → ExecuteR Agent. + +## Install (domain central store) + +``` +copy ExecuteR.admx \\\SYSVOL\\Policies\PolicyDefinitions\ +copy en-US\ExecuteR.adml \\\SYSVOL\\Policies\PolicyDefinitions\en-US\ +``` + +## Settings + +| Policy | Registry value | Type | Notes | +|--------|----------------|------|-------| +| Server URL | `ServerURL` | REG_SZ | `https://host`; agent derives `wss://…/messaging/agent` | +| Log level | `LogLevel` | REG_SZ | Trace/Debug/Information/Warning/Error | +| Inventory interval (seconds) | `InventoryInterval` | REG_SZ | default 900 | +| Reconnect minimum delay (seconds) | `ReconnectMinDelay` | REG_SZ | default 1 | +| Reconnect maximum delay (seconds) | `ReconnectMaxDelay` | REG_SZ | default 60 | +| Allow remote interactive shell | `AllowRemoteShell` | REG_DWORD | default off | +| Allow PowerShell script execution | `AllowScriptExecution` | REG_DWORD | default on | + +The one-time **bootstrap token** is deliberately not a policy — it is a secret +delivered via the MSI `BOOTSTRAPTOKEN` property or the URL install command, and +is erased from the registry after successful enrollment. diff --git a/src/Installer/Policies/en-US/ExecuteR.adml b/src/Installer/Policies/en-US/ExecuteR.adml new file mode 100644 index 0000000..9b4b907 --- /dev/null +++ b/src/Installer/Policies/en-US/ExecuteR.adml @@ -0,0 +1,67 @@ + + + ExecuteR Agent + Administrative template for the ExecuteR endpoint management agent. + + + ExecuteR Agent 1.0 or later + Grace Solution + ExecuteR Agent + + Server URL + The control-plane base URL the agent connects to, for example https://control.example.com. The agent derives the NATS WebSocket endpoint (https -> wss) automatically. Do not include ws:// or wss://. + + Log level + Minimum severity written to the agent log. + Trace + Debug + Information + Warning + Error + + Inventory interval (seconds) + How often the agent publishes a full inventory snapshot, in seconds. Default is 900 (15 minutes). + + Reconnect minimum delay (seconds) + Minimum backoff delay before a NATS reconnect attempt, in seconds. Default is 1. + + Reconnect maximum delay (seconds) + Maximum backoff delay between NATS reconnect attempts, in seconds. Default is 60. + + Allow remote interactive shell + When enabled, operators may open an interactive ConPTY shell on this device. When disabled, shell open commands are refused. Default is disabled. + + Allow PowerShell script execution + When enabled, the agent runs dispatched PowerShell jobs. When disabled, script commands are refused. Default is enabled. + + + + + + + + + + Log level + + + + + + + + + + + + + + + + + + + diff --git a/src/Installer/Product.wxs b/src/Installer/Product.wxs new file mode 100644 index 0000000..bab60b9 --- /dev/null +++ b/src/Installer/Product.wxs @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Shared.Contracts/Api/ApiRoutes.cs b/src/Shared.Contracts/Api/ApiRoutes.cs new file mode 100644 index 0000000..52e1115 --- /dev/null +++ b/src/Shared.Contracts/Api/ApiRoutes.cs @@ -0,0 +1,72 @@ +namespace Shared.Contracts.Api; + +/// +/// Single source of truth for every REST route in the system. +/// Route templates use ASP.NET Core parameter syntax; use the For +/// helpers to build concrete request paths from clients. +/// +public static class ApiRoutes +{ + public const string Health = "/api/health"; + public const string Ready = "/api/ready"; + + public const string AuthLogin = "/api/auth/login"; + public const string AuthLogout = "/api/auth/logout"; + public const string AuthSession = "/api/auth/session"; + public const string AuthOidcLogin = "/api/auth/oidc/login"; + public const string AuthOidcCallback = "/api/auth/oidc/callback"; + + public const string Bootstrap = "/api/enrollment/bootstrap"; + public const string RefreshCredential = "/api/enrollment/credential"; + public const string InstallScript = "/api/enrollment/install"; + public const string AgentPackage = "/api/enrollment/agent-package"; + + public const string Devices = "/api/devices"; + public const string Device = "/api/devices/{clientId}"; + public const string DeviceInventory = "/api/devices/{clientId}/inventory"; + public const string DeviceShell = "/api/devices/{clientId}/shell"; + public const string DeviceFiles = "/api/devices/{clientId}/files"; + + public const string Scripts = "/api/scripts"; + public const string Script = "/api/scripts/{id}"; + + public const string FunctionModules = "/api/functions"; + public const string FunctionModule = "/api/functions/{id}"; + + public const string Groups = "/api/groups"; + public const string Group = "/api/groups/{id}"; + public const string GroupMembers = "/api/groups/{id}/members"; + public const string GroupPreview = "/api/groups/preview"; + public const string GroupFields = "/api/groups/fields"; + public const string DeviceTags = "/api/devices/{clientId}/tags"; + + public const string Triggers = "/api/triggers"; + public const string Trigger = "/api/triggers/{id}"; + + public const string Jobs = "/api/jobs"; + public const string Job = "/api/jobs/{jobId}"; + public const string JobOutput = "/api/jobs/{jobId}/output"; + + public const string BrowserNatsCredential = "/api/messaging/credential"; + + public const string AdminBootstrapTokens = "/api/admin/bootstrap-tokens"; + public const string AdminBootstrapToken = "/api/admin/bootstrap-tokens/{id}"; + + /// Builds concrete paths from the route templates. + public static class For + { + public static string Device(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}"; + public static string DeviceInventory(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/inventory"; + public static string DeviceShell(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/shell"; + public static string DeviceFiles(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/files"; + public static string Script(Guid id) => $"/api/scripts/{id:D}"; + public static string FunctionModule(Guid id) => $"/api/functions/{id:D}"; + public static string Group(Guid id) => $"/api/groups/{id:D}"; + public static string GroupMembers(Guid id) => $"/api/groups/{id:D}/members"; + public static string DeviceTags(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/tags"; + public static string Trigger(Guid id) => $"/api/triggers/{id:D}"; + public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}"; + public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output"; + public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}"; + } +} diff --git a/src/Shared.Contracts/Api/AuthDtos.cs b/src/Shared.Contracts/Api/AuthDtos.cs new file mode 100644 index 0000000..a5a04ac --- /dev/null +++ b/src/Shared.Contracts/Api/AuthDtos.cs @@ -0,0 +1,28 @@ +using Shared.Contracts.Models; + +namespace Shared.Contracts.Api; + +/// POST /api/auth/login request body. +public sealed record LoginRequest(string Username, string Password); + +/// GET /api/auth/session response body. +public sealed record SessionResponse( + bool Authenticated, + string? Username, + string? DisplayName, + UserRole? Role, + string? AuthProvider); + +/// +/// POST /api/messaging/credential request body. Pass the previously issued +/// to refresh a credential while keeping +/// the same session-scoped subjects. +/// +public sealed record BrowserCredentialRequest(string NkeyPublic, string? BrowserSessionId = null); + +/// POST /api/messaging/credential response body. +public sealed record BrowserCredentialResponse( + string Jwt, + DateTimeOffset ExpiresUtc, + string BrowserSessionId, + string WebSocketPath); diff --git a/src/Shared.Contracts/Api/EnrollmentDtos.cs b/src/Shared.Contracts/Api/EnrollmentDtos.cs new file mode 100644 index 0000000..cd9c170 --- /dev/null +++ b/src/Shared.Contracts/Api/EnrollmentDtos.cs @@ -0,0 +1,40 @@ +namespace Shared.Contracts.Api; + +/// Device facts sent with the bootstrap request. +public sealed record EnrollDeviceInfo( + string Hostname, + string? Manufacturer, + string? Model, + string? OsCaption, + string? OsVersion); + +/// POST /api/enrollment/bootstrap request body. +public sealed record BootstrapRequest( + string BootstrapToken, + string ClientId, + string NkeyPublic, + string AgentVersion, + EnrollDeviceInfo Device); + +/// POST /api/enrollment/bootstrap response body. +public sealed record BootstrapResponse( + Guid EnrollmentId, + string ClientId, + string UserJwt, + DateTimeOffset? CredentialExpiresUtc); + +/// +/// POST /api/enrollment/credential request body. The agent proves possession of +/// its enrolled NKey by signing {clientId}|{timestampUtc:O} (UTF-8) with +/// the private seed; the backend verifies with the stored public key. +/// +public sealed record CredentialRefreshRequest( + string ClientId, + string NkeyPublic, + DateTimeOffset TimestampUtc, + string SignatureBase64); + +/// POST /api/enrollment/credential response body. +public sealed record CredentialRefreshResponse( + string UserJwt, + DateTimeOffset? CredentialExpiresUtc); diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs new file mode 100644 index 0000000..f20f1cb --- /dev/null +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -0,0 +1,183 @@ +using Shared.Contracts.Models; + +namespace Shared.Contracts.Api; + +/// Device row for GET /api/devices. +public sealed record DeviceDto( + string ClientId, + string Hostname, + string? Manufacturer, + string? Model, + string? OsCaption, + string? OsVersion, + string? AgentVersion, + IReadOnlyList IpAddresses, + DeviceStatus Status, + DateTimeOffset? LastSeenUtc, + DateTimeOffset EnrolledUtc, + IReadOnlyList? Tags = null, + bool IsOrphaned = false); + +/// Device group resource. +public sealed record DeviceGroupDto( + Guid Id, + string Name, + string? Description, + GroupKind Kind, + GroupRuleSet? Rules, + int MemberCount, + DateTimeOffset CreatedUtc, + DateTimeOffset UpdatedUtc, + string? UpdatedBy); + +/// POST/PUT /api/groups request body. +public sealed record SaveDeviceGroupRequest( + string Name, + string? Description, + GroupKind Kind, + GroupRuleSet? Rules); + +/// POST /api/groups/{id}/members request body (static groups). +public sealed record UpdateGroupMembersRequest( + IReadOnlyList Add, + IReadOnlyList Remove); + +/// POST /api/groups/preview request body: evaluate rules without saving. +public sealed record PreviewGroupRequest(GroupRuleSet Rules); + +/// PUT /api/devices/{clientId}/tags request body. +public sealed record UpdateDeviceTagsRequest(IReadOnlyList Tags); + +/// Script trigger resource. +public sealed record ScriptTriggerDto( + Guid Id, + Guid ScriptId, + string ScriptName, + Guid? GroupId, + string? GroupName, + ScriptTriggerType TriggerType, + bool Enabled, + bool OncePerDevice, + DateTimeOffset CreatedUtc); + +/// POST /api/triggers request body. +public sealed record SaveScriptTriggerRequest( + Guid ScriptId, + Guid? GroupId, + ScriptTriggerType TriggerType, + bool Enabled = true, + bool OncePerDevice = true); + +/// Device detail for GET /api/devices/{clientId}. +public sealed record DeviceDetailDto( + DeviceDto Device, + InventoryReport? Inventory, + DateTimeOffset? InventoryUpdatedUtc, + IReadOnlyList? Groups = null); + +/// A group a device belongs to. +public sealed record DeviceGroupRefDto(Guid Id, string Name, GroupKind Kind); + +/// Script resource. +public sealed record ScriptDto( + Guid Id, + string Name, + string? Description, + string Language, + string Content, + IReadOnlyList Parameters, + IReadOnlyList FunctionModuleIds, + DateTimeOffset CreatedUtc, + DateTimeOffset UpdatedUtc, + string? CreatedBy, + string? UpdatedBy); + +/// POST/PUT /api/scripts request body. +public sealed record SaveScriptRequest( + string Name, + string? Description, + string Content, + IReadOnlyList? Parameters = null, + IReadOnlyList? FunctionModuleIds = null); + +/// Reusable PowerShell function module (prepended to scripts that reference it). +public sealed record FunctionModuleDto( + Guid Id, + string Name, + string? Description, + string Content, + DateTimeOffset CreatedUtc, + DateTimeOffset UpdatedUtc, + string? UpdatedBy); + +/// POST/PUT /api/functions request body. +public sealed record SaveFunctionModuleRequest( + string Name, + string? Description, + string Content); + +/// Job resource. +public sealed record JobDto( + Guid JobId, + string ClientId, + string? Hostname, + Guid ScriptId, + string ScriptName, + JobState State, + DateTimeOffset CreatedUtc, + DateTimeOffset? StartedUtc, + DateTimeOffset? CompletedUtc, + int? ExitCode, + string? RequestedBy, + string? OutputSummary); + +/// POST /api/jobs request body. maps +/// parameter name → typed JSON value per the script's parameter schema. +public sealed record CreateJobRequest( + string ClientId, + Guid ScriptId, + IReadOnlyDictionary? Arguments = null); + +/// One stored output record for GET /api/jobs/{jobId}/output. +public sealed record JobOutputRecordDto( + long Sequence, + OutputStreamKind Stream, + DateTimeOffset TimestampUtc, + string Text); + +/// POST /api/devices/{clientId}/shell request body. +public sealed record CreateShellRequest( + string BrowserSessionId, + int Cols, + int Rows); + +/// POST /api/devices/{clientId}/shell response body. +public sealed record CreateShellResponse( + Guid ShellSessionId, + string ClientId, + string Hostname, + DateTimeOffset ExpiresUtc); + +/// POST /api/devices/{clientId}/files request body: push an S3 object to the device. +public sealed record CreateFileDeliveryRequest( + string ObjectKey, + string DestinationPath, + string? Sha256); + +/// POST /api/admin/bootstrap-tokens request body. +public sealed record CreateBootstrapTokenRequest( + int? ValidMinutes, + int? MaxUses, + string? Note); + +/// Bootstrap token metadata. Token value only present in the creation response. +public sealed record BootstrapTokenDto( + Guid Id, + string? Token, + DateTimeOffset CreatedUtc, + DateTimeOffset ExpiresUtc, + int MaxUses, + int Uses, + bool Revoked, + string? Note, + string? CreatedBy); diff --git a/src/Shared.Contracts/Messages/MessageEnvelope.cs b/src/Shared.Contracts/Messages/MessageEnvelope.cs new file mode 100644 index 0000000..4a071c2 --- /dev/null +++ b/src/Shared.Contracts/Messages/MessageEnvelope.cs @@ -0,0 +1,64 @@ +using System.Text.Json; +using Shared.Contracts.Serialization; + +namespace Shared.Contracts.Messages; + +/// An endpoint reference inside the message envelope. +public sealed record EndpointRef(string Kind, string Id); + +/// +/// Common envelope for every application NATS payload. +/// CorrelationId stays constant for one logical operation; +/// CausationId references the message that caused this one. +/// Unknown JSON properties are ignored on read for forward compatibility. +/// +public sealed record MessageEnvelope( + Guid MessageId, + Guid CorrelationId, + Guid? CausationId, + string MessageType, + int SchemaVersion, + DateTimeOffset TimestampUtc, + EndpointRef Source, + EndpointRef? Target, + JsonElement Payload) +{ + public const int CurrentSchemaVersion = 1; + + public static MessageEnvelope Create( + string messageType, + EndpointRef source, + TPayload payload, + EndpointRef? target = null, + Guid? correlationId = null, + Guid? causationId = null) + { + var messageId = Guid.NewGuid(); + return new MessageEnvelope( + MessageId: messageId, + CorrelationId: correlationId ?? messageId, + CausationId: causationId, + MessageType: messageType, + SchemaVersion: CurrentSchemaVersion, + TimestampUtc: DateTimeOffset.UtcNow, + Source: source, + Target: target, + Payload: JsonSerializer.SerializeToElement(payload, JsonDefaults.Options)); + } + + /// Creates a follow-up envelope that preserves correlation and records causation. + public MessageEnvelope CreateNext( + string messageType, + EndpointRef source, + TPayload payload, + EndpointRef? target = null) + => Create(messageType, source, payload, target, CorrelationId, MessageId); + + public TPayload? GetPayload() + => Payload.Deserialize(JsonDefaults.Options); + + public byte[] ToUtf8Bytes() => JsonDefaults.SerializeToUtf8Bytes(this); + + public static MessageEnvelope? FromUtf8Bytes(ReadOnlySpan utf8Json) + => JsonDefaults.Deserialize(utf8Json); +} diff --git a/src/Shared.Contracts/Messages/MessageTypes.cs b/src/Shared.Contracts/Messages/MessageTypes.cs new file mode 100644 index 0000000..ad1239a --- /dev/null +++ b/src/Shared.Contracts/Messages/MessageTypes.cs @@ -0,0 +1,46 @@ +namespace Shared.Contracts.Messages; + +/// +/// Internal message type identifiers carried in the envelope's +/// messageType property. Generic by design — no product names. +/// +public static class MessageTypes +{ + public const string AgentPresence = "agent.presence"; + public const string AgentInventory = "agent.inventory"; + public const string AgentEvent = "agent.event"; + + public const string CommandInventory = "command.inventory"; + public const string CommandScript = "command.script"; + public const string CommandFileDownload = "command.file.download"; + public const string CommandShellOpen = "command.shell.open"; + public const string CommandShellInput = "command.shell.input"; + public const string CommandShellResize = "command.shell.resize"; + public const string CommandShellClose = "command.shell.close"; + + public const string ShellOutput = "shell.output"; + public const string ShellState = "shell.state"; + public const string ShellInput = "shell.input"; + + public const string JobProgress = "job.progress"; + public const string JobOutput = "job.output"; + public const string JobState = "job.state"; + + public const string SystemAgentEnrolled = "system.agent.enrolled"; + public const string SystemAgentDisconnected = "system.agent.disconnected"; + public const string SystemJobCreated = "system.job.created"; + public const string SystemJobCompleted = "system.job.completed"; + + public const string BrowserEvent = "browser.event"; +} + +/// Values used in envelope source.kind / target.kind. +public static class EndpointKinds +{ + public const string Agent = "agent"; + public const string Backend = "backend"; + public const string Browser = "browser"; + public const string Job = "job"; + public const string Shell = "shell"; + public const string System = "system"; +} diff --git a/src/Shared.Contracts/Messages/Payloads.cs b/src/Shared.Contracts/Messages/Payloads.cs new file mode 100644 index 0000000..e3e6b4d --- /dev/null +++ b/src/Shared.Contracts/Messages/Payloads.cs @@ -0,0 +1,162 @@ +using Shared.Contracts.Models; + +namespace Shared.Contracts.Messages; + +/// Periodic agent heartbeat published on agent.<clientId>.presence. +public sealed record PresencePayload( + string ClientId, + string Hostname, + string AgentVersion, + string Status, + DateTimeOffset TimestampUtc, + long UptimeSeconds, + int ActiveJobs); + +/// Inventory snapshot published on agent.<clientId>.inventory. +public sealed record InventoryPayload(InventoryReport Report); + +/// +/// Lifecycle notice on agent.<clientId>.event. Kind uses +/// ; "ready" means the agent is connected and +/// consuming job commands. +/// +public sealed record AgentEventPayload( + string ClientId, + string Kind, + string? Detail, + DateTimeOffset TimestampUtc); + +/// Values for . +public static class AgentEventKinds +{ + /// Agent is connected and its durable command consumer is bound. + public const string Ready = "ready"; +} + +/// +/// Durable script execution command on agent.<clientId>.command.script. +/// holds reusable function-module content run first in the +/// same runspace (so the main keeps its param() block +/// first). declares typed parameters and +/// supplies their values (coerced by the agent). +/// +public sealed record ScriptCommandPayload( + Guid JobId, + Guid ScriptId, + string ScriptName, + string Content, + int? TimeoutSeconds, + string? Prelude = null, + IReadOnlyList? Parameters = null, + IReadOnlyDictionary? Arguments = null); + +/// Inventory refresh command on agent.<clientId>.command.inventory. +public sealed record InventoryCommandPayload(string? Reason); + +/// +/// File delivery command on agent.<clientId>.command.file. The backend +/// presigns the URL so S3 credentials never reach the endpoint; the agent +/// streams the URL to DestinationPath and optionally verifies the hash. +/// +public sealed record FileDownloadCommandPayload( + Guid JobId, + string Url, + string DestinationPath, + string? Sha256, + long? SizeBytes, + string? SourceDescription); + +/// Near-live job output record on job.<jobId>.output. +public sealed record JobOutputPayload( + Guid JobId, + string ClientId, + long Sequence, + OutputStreamKind Stream, + DateTimeOffset TimestampUtc, + string Text); + +/// Normalized progress record on job.<jobId>.progress. +public sealed record JobProgressPayload( + Guid JobId, + string ClientId, + string Activity, + string? StatusDescription, + int? PercentComplete, + int? SecondsRemaining, + DateTimeOffset TimestampUtc); + +/// Job state transition on job.<jobId>.state. +public sealed record JobStatePayload( + Guid JobId, + string ClientId, + JobState State, + int? ExitCode, + DateTimeOffset TimestampUtc, + string? Message); + +/// Opens a remote shell; sent on agent.<clientId>.command.shell.open. +public sealed record ShellOpenCommandPayload( + Guid SessionId, + int Cols, + int Rows); + +/// Terminal input bytes (base64) for an open shell session. +public sealed record ShellInputPayload( + Guid SessionId, + string DataBase64); + +/// Terminal resize for an open shell session. +public sealed record ShellResizePayload( + Guid SessionId, + int Cols, + int Rows); + +/// Closes a shell session. +public sealed record ShellClosePayload( + Guid SessionId, + string? Reason); + +/// Terminal output bytes (base64) on agent.<clientId>.shell.<sessionId>.output. +public sealed record ShellOutputPayload( + Guid SessionId, + long Sequence, + string DataBase64); + +/// Shell session state on agent.<clientId>.shell.<sessionId>.state. +public sealed record ShellStatePayload( + Guid SessionId, + ShellSessionState State, + string? Message); + +/// System event: a device enrolled. +public sealed record AgentEnrolledEvent( + string ClientId, + string Hostname, + DateTimeOffset TimestampUtc); + +/// System event: a device was marked disconnected/offline. +public sealed record AgentDisconnectedEvent( + string ClientId, + DateTimeOffset TimestampUtc); + +/// System event: a job was created. +public sealed record JobCreatedEvent( + Guid JobId, + string ClientId, + string ScriptName, + DateTimeOffset TimestampUtc); + +/// System event: a job reached a terminal state. +public sealed record JobCompletedEvent( + Guid JobId, + string ClientId, + JobState State, + DateTimeOffset TimestampUtc); + +/// Human-readable activity item republished to authorized browser sessions. +public sealed record ActivityEventPayload( + string Kind, + string Text, + string? ClientId, + Guid? JobId, + DateTimeOffset TimestampUtc); diff --git a/src/Shared.Contracts/Models/Enums.cs b/src/Shared.Contracts/Models/Enums.cs new file mode 100644 index 0000000..f590c49 --- /dev/null +++ b/src/Shared.Contracts/Models/Enums.cs @@ -0,0 +1,60 @@ +namespace Shared.Contracts.Models; + +/// Job lifecycle states. +public enum JobState +{ + Queued, + Dispatched, + Running, + Succeeded, + Failed, + Cancelled, + TimedOut, +} + +/// Derived device connectivity status based on last-seen thresholds. +public enum DeviceStatus +{ + Online, + Stale, + Offline, +} + +/// PowerShell output stream classification for job output records. +public enum OutputStreamKind +{ + Output, + Error, + Warning, + Verbose, + Debug, + Information, + Progress, +} + +/// Application roles. +public enum UserRole +{ + Admin, + Operator, + Viewer, +} + +/// Lifecycle events that can automatically launch a script. +public enum ScriptTriggerType +{ + /// Fires the first time a device completes enrollment. + OnRegistration, + + /// Fires when the agent is connected and consuming job commands. + OnAgentReady, +} + +/// Remote shell session lifecycle states. +public enum ShellSessionState +{ + Requested, + Open, + Closed, + Failed, +} diff --git a/src/Shared.Contracts/Models/GroupRules.cs b/src/Shared.Contracts/Models/GroupRules.cs new file mode 100644 index 0000000..ce40661 --- /dev/null +++ b/src/Shared.Contracts/Models/GroupRules.cs @@ -0,0 +1,112 @@ +namespace Shared.Contracts.Models; + +/// Static groups hold an explicit member list; dynamic groups evaluate rules. +public enum GroupKind +{ + Static, + Dynamic, +} + +/// How sibling conditions (or sibling groups) combine. +public enum RuleCombine +{ + And, + Or, +} + +/// Comparison performed by a single condition. +public enum RuleOperator +{ + Equals, + NotEquals, + Contains, + NotContains, + StartsWith, + EndsWith, + Regex, + In, + NotIn, + GreaterThan, + GreaterOrEqual, + LessThan, + LessOrEqual, + Exists, + NotExists, +} + +/// +/// One comparison against a device field. inverts the +/// result, so any operator can be expressed in its negative form. +/// For multi-valued fields (tags, IP addresses) a condition matches when ANY +/// value satisfies it — except the inherently negative operators +/// (NotEquals/NotContains/NotIn), which require ALL values to satisfy them. +/// +public sealed record RuleCondition( + string Field, + RuleOperator Operator, + string? Value = null, + bool Negate = false); + +/// +/// A group of conditions (and optionally nested groups) combined with AND/OR. +/// inverts the whole group. +/// +public sealed record RuleGroup( + RuleCombine Combine = RuleCombine.And, + IReadOnlyList? Conditions = null, + IReadOnlyList? Groups = null, + bool Negate = false); + +/// +/// A dynamic group's membership rules: one or more condition groups combined +/// with AND/OR. +/// +public sealed record GroupRuleSet( + RuleCombine Combine = RuleCombine.And, + IReadOnlyList? Groups = null) +{ + public static GroupRuleSet Empty { get; } = new(RuleCombine.And, []); +} + +/// Field names usable in rules, with the kind of comparison they support. +public sealed record GroupFieldDescriptor( + string Field, + string DisplayName, + string Category, + bool Numeric = false, + bool MultiValue = false); + +/// The catalogue of rule-addressable device fields (also drives the UI). +public static class GroupFields +{ + public static readonly IReadOnlyList All = + [ + new("hostname", "Hostname", "Identity"), + new("clientId", "Client ID", "Identity"), + new("status", "Status (online/stale/offline)", "Identity"), + new("tags", "Tags", "Identity", MultiValue: true), + new("agentVersion", "Agent version", "Identity"), + new("manufacturer", "Manufacturer", "Hardware"), + new("model", "Model", "Hardware"), + new("serialNumber", "Serial number", "Hardware"), + new("biosVersion", "BIOS version", "Hardware"), + new("systemType", "System type", "Hardware"), + new("domain", "Domain / workgroup", "Identity"), + new("partOfDomain", "Domain joined", "Identity"), + new("os.caption", "OS name", "Operating system"), + new("os.version", "OS version", "Operating system"), + new("os.build", "OS build", "Operating system"), + new("os.architecture", "OS architecture", "Operating system"), + new("os.edition", "OS edition", "Operating system"), + new("cpu.name", "CPU name", "Hardware"), + new("cpu.cores", "CPU cores", "Hardware", Numeric: true), + new("cpu.logicalProcessors", "CPU logical processors", "Hardware", Numeric: true), + new("memory.totalGb", "Memory total (GB)", "Hardware", Numeric: true), + new("disk.count", "Disk count", "Storage", Numeric: true), + new("disk.totalGb", "Disk total (GB)", "Storage", Numeric: true), + new("volume.freeGb", "Smallest volume free (GB)", "Storage", Numeric: true), + new("network.ipv4", "IPv4 address", "Network", MultiValue: true), + new("network.mac", "MAC address", "Network", MultiValue: true), + new("network.dns", "DNS server", "Network", MultiValue: true), + ]; +} diff --git a/src/Shared.Contracts/Models/InventoryReport.cs b/src/Shared.Contracts/Models/InventoryReport.cs new file mode 100644 index 0000000..4f1207c --- /dev/null +++ b/src/Shared.Contracts/Models/InventoryReport.cs @@ -0,0 +1,65 @@ +namespace Shared.Contracts.Models; + +/// Full device inventory snapshot published by the agent. +public sealed record InventoryReport( + InventoryIdentity Identity, + InventoryOs Os, + InventoryCpu Cpu, + IReadOnlyList Memory, + long TotalPhysicalMemoryBytes, + IReadOnlyList Disks, + IReadOnlyList Volumes, + IReadOnlyList Network, + DateTimeOffset CollectedUtc); + +public sealed record InventoryIdentity( + string ClientId, + string Hostname, + string? Manufacturer, + string? Model, + string? SerialNumber, + string? BiosVersion, + string? BaseboardSerial, + string? DomainOrWorkgroup, + bool PartOfDomain, + string? SystemType); + +public sealed record InventoryOs( + string? Caption, + string? Version, + string? Build, + string? Architecture, + DateTimeOffset? InstallDateUtc, + DateTimeOffset? LastBootUtc, + string? Edition); + +public sealed record InventoryCpu( + string? Name, + int LogicalProcessors, + int Cores); + +public sealed record InventoryMemoryModule( + string? DeviceLocator, + long CapacityBytes, + string? Manufacturer, + int? SpeedMhz); + +public sealed record InventoryDisk( + string? Model, + string? SerialNumber, + long SizeBytes, + string? BusType); + +public sealed record InventoryVolume( + string DriveLetter, + string? FileSystem, + long TotalSizeBytes, + long FreeSpaceBytes); + +public sealed record InventoryNetworkAdapter( + string? Description, + string? MacAddress, + IReadOnlyList Ipv4Addresses, + IReadOnlyList Ipv6Addresses, + IReadOnlyList Gateways, + IReadOnlyList DnsServers); diff --git a/src/Shared.Contracts/Models/ScriptParameter.cs b/src/Shared.Contracts/Models/ScriptParameter.cs new file mode 100644 index 0000000..a8377dd --- /dev/null +++ b/src/Shared.Contracts/Models/ScriptParameter.cs @@ -0,0 +1,37 @@ +using System.Text.Json; + +namespace Shared.Contracts.Models; + +/// Primitive value types selectable for scalars, array elements and hashtable keys/values. +public enum PrimitiveType +{ + String, + Number, + Boolean, +} + +/// The kind of a script parameter; drives the editor input in the UI. +public enum ScriptParameterType +{ + String, + Number, + Boolean, + Array, + Hashtable, +} + +/// +/// One declared parameter of a script. For , +/// applies; for , +/// and apply (hashtable keys carry +/// their own primitive type selection). +/// +public sealed record ScriptParameter( + string Name, + ScriptParameterType Type, + bool Required = false, + string? Description = null, + PrimitiveType? ElementType = null, + PrimitiveType? KeyType = null, + PrimitiveType? ValueType = null, + JsonElement? DefaultValue = null); diff --git a/src/Shared.Contracts/Serialization/JsonDefaults.cs b/src/Shared.Contracts/Serialization/JsonDefaults.cs new file mode 100644 index 0000000..18ff3b5 --- /dev/null +++ b/src/Shared.Contracts/Serialization/JsonDefaults.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Shared.Contracts.Serialization; + +/// +/// Canonical JSON settings for every wire payload (REST bodies and NATS messages). +/// camelCase properties, camelCase enum strings, null suppression, and tolerant +/// reading (unknown properties are ignored for forward compatibility). +/// +public static class JsonDefaults +{ + public static JsonSerializerOptions Options { get; } = Create(); + + private static JsonSerializerOptions Create() + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); + return options; + } + + public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); + + public static T? Deserialize(string json) => JsonSerializer.Deserialize(json, Options); + + public static T? Deserialize(ReadOnlySpan utf8Json) => JsonSerializer.Deserialize(utf8Json, Options); + + public static byte[] SerializeToUtf8Bytes(T value) => JsonSerializer.SerializeToUtf8Bytes(value, Options); +} diff --git a/src/Shared.Contracts/Shared.Contracts.csproj b/src/Shared.Contracts/Shared.Contracts.csproj new file mode 100644 index 0000000..4abab42 --- /dev/null +++ b/src/Shared.Contracts/Shared.Contracts.csproj @@ -0,0 +1,8 @@ + + + + net10.0 + Shared.Contracts + + + diff --git a/src/Shared.Infrastructure/Configuration/ConfigurationValue.cs b/src/Shared.Infrastructure/Configuration/ConfigurationValue.cs new file mode 100644 index 0000000..93638ed --- /dev/null +++ b/src/Shared.Infrastructure/Configuration/ConfigurationValue.cs @@ -0,0 +1,21 @@ +namespace Shared.Infrastructure.Configuration; + +/// Where an effective configuration value came from (highest wins). +public enum ConfigurationSource +{ + GroupPolicy, + Registry, + EnvironmentDevelopmentOnly, + Default, +} + +/// +/// An effective configuration value with provenance, so policy-controlled +/// values can be surfaced (important for the future ADMX implementation). +/// +public sealed record ConfigurationValue(T Value, ConfigurationSource Source) +{ + public bool IsPolicyControlled => Source == ConfigurationSource.GroupPolicy; + + public override string ToString() => $"{Value} ({Source})"; +} diff --git a/src/Shared.Infrastructure/Constants/Branding.cs b/src/Shared.Infrastructure/Constants/Branding.cs new file mode 100644 index 0000000..0b5de4c --- /dev/null +++ b/src/Shared.Infrastructure/Constants/Branding.cs @@ -0,0 +1,46 @@ +namespace Shared.Infrastructure.Constants; + +/// +/// The ONLY place product/company branding may appear in code. Branding is +/// allowed in UI text, executable names, service display names, MSI metadata, +/// registry paths and documentation — never in NATS subjects, API routes, +/// message types, headers or table names (those stay generic). +/// +public static class Branding +{ + public const string CompanyName = "Grace Solution"; + + /// Registry/file-system safe company key (no spaces). + public const string CompanyKey = "GraceSolution"; + + public const string ProductName = "ExecuteR"; + + /// Registry/file-system safe product key. + public const string ProductKey = "ExecuteR"; + + public const string AgentServiceName = "ExecuteRAgent"; + public const string AgentServiceDisplayName = "ExecuteR Agent"; + public const string AgentServiceDescription = + "ExecuteR endpoint management agent. Maintains a secure connection to the ExecuteR control plane " + + "for inventory, script execution and remote management."; + + public const string AgentExecutableName = "Agent.exe"; + + /// Normal machine configuration key below HKLM. + public const string AgentRegistryKey = @"SOFTWARE\" + ProductKey; + + /// Runtime-managed values below HKLM. + public const string AgentRuntimeRegistryKey = AgentRegistryKey + @"\Runtime"; + + /// GPO policy key below HKLM; always wins over normal configuration. + public const string AgentPolicyRegistryKey = @"SOFTWARE\Policies\" + ProductKey; + + /// Agent data directory below %ProgramData%. + public static string AgentProgramDataDirectory => + Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), + ProductKey); + + public const string CredentialFileName = "credentials.dat"; + public const string JobHistoryFileName = "jobs.db"; +} diff --git a/src/Shared.Infrastructure/Constants/ProtocolDefaults.cs b/src/Shared.Infrastructure/Constants/ProtocolDefaults.cs new file mode 100644 index 0000000..1e162d7 --- /dev/null +++ b/src/Shared.Infrastructure/Constants/ProtocolDefaults.cs @@ -0,0 +1,66 @@ +using Shared.Contracts.Models; + +namespace Shared.Infrastructure.Constants; + +/// Public WebSocket entry paths exposed by the reverse proxy. +public static class MessagingPaths +{ + public const string Agent = "/messaging/agent"; + public const string Browser = "/messaging/browser"; +} + +/// Centralized protocol timings, thresholds and limits. +public static class ProtocolDefaults +{ + public static readonly TimeSpan PresenceInterval = TimeSpan.FromSeconds(30); + + /// Last seen within this window ⇒ Online. + public static readonly TimeSpan OnlineThreshold = TimeSpan.FromSeconds(90); + + /// Last seen within this window (but past Online) ⇒ Stale; beyond ⇒ Offline. + public static readonly TimeSpan StaleThreshold = TimeSpan.FromMinutes(5); + + public static readonly TimeSpan DefaultInventoryInterval = TimeSpan.FromMinutes(15); + + public static readonly TimeSpan ReconnectMinDelay = TimeSpan.FromSeconds(1); + public static readonly TimeSpan ReconnectMaxDelay = TimeSpan.FromSeconds(60); + + public static readonly TimeSpan BrowserCredentialLifetime = TimeSpan.FromMinutes(5); + + public static readonly TimeSpan ShellIdleTimeout = TimeSpan.FromMinutes(15); + public static readonly TimeSpan ShellMaxLifetime = TimeSpan.FromMinutes(60); + + public static readonly TimeSpan BootstrapTokenDefaultLifetime = TimeSpan.FromHours(24); + public const int BootstrapTokenDefaultMaxUses = 1; + public const int BootstrapTokenEntropyBytes = 32; + + /// How many completed job ids the agent retains for idempotency. + public const int JobIdempotencyRetention = 1000; + + public const int DefaultScriptTimeoutSeconds = 3600; + + /// + /// How long a device may stay silent before it is orphaned (refused + /// credential refresh and job dispatch until it re-enrolls). + /// Override with DEVICE_ORPHAN_AFTER_DAYS; set that to 0 to disable + /// orphaning entirely and let silent devices reconnect on their own. + /// + public const int DefaultOrphanAfterDays = 30; + + /// Central last-seen → status mapping (Online ≤ 90s, Stale ≤ 5m, else Offline). + public static DeviceStatus CalculateStatus(DateTimeOffset? lastSeenUtc, DateTimeOffset nowUtc) + { + if (lastSeenUtc is null) + { + return DeviceStatus.Offline; + } + + var age = nowUtc - lastSeenUtc.Value; + if (age <= OnlineThreshold) + { + return DeviceStatus.Online; + } + + return age <= StaleThreshold ? DeviceStatus.Stale : DeviceStatus.Offline; + } +} diff --git a/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs b/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs new file mode 100644 index 0000000..6023d37 --- /dev/null +++ b/src/Shared.Infrastructure/Grouping/DeviceFieldBag.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using Shared.Contracts.Models; + +namespace Shared.Infrastructure.Grouping; + +/// +/// A device flattened into rule-addressable fields. Values are kept as strings +/// (possibly several per field) with an optional numeric form so comparisons +/// can be numeric where it makes sense. +/// +public sealed class DeviceFieldBag +{ + private readonly Dictionary> values = new(StringComparer.OrdinalIgnoreCase); + + public void Set(string field, string? value) + { + if (value is null) + { + return; + } + + values[field] = [value]; + } + + public void Set(string field, double? value) + { + if (value is null) + { + return; + } + + values[field] = [value.Value.ToString("R", CultureInfo.InvariantCulture)]; + } + + public void SetMany(string field, IEnumerable? items) + { + var list = items?.Where(i => !string.IsNullOrWhiteSpace(i)).ToList(); + if (list is { Count: > 0 }) + { + values[field] = list; + } + } + + public bool TryGet(string field, out IReadOnlyList result) + { + if (values.TryGetValue(field, out var list)) + { + result = list; + return true; + } + + result = []; + return false; + } + + public bool Has(string field) => values.ContainsKey(field); + + /// + /// Builds the field bag from a device row and its latest inventory + /// snapshot. Inventory may be null (device enrolled but not yet reported). + /// + public static DeviceFieldBag Build( + string clientId, + string hostname, + DeviceStatus status, + string? agentVersion, + IEnumerable? tags, + InventoryReport? inventory) + { + var bag = new DeviceFieldBag(); + bag.Set("clientId", clientId); + bag.Set("hostname", hostname); + bag.Set("status", status.ToString().ToLowerInvariant()); + bag.Set("agentVersion", agentVersion); + bag.SetMany("tags", tags); + + if (inventory is null) + { + return bag; + } + + bag.Set("manufacturer", inventory.Identity.Manufacturer); + bag.Set("model", inventory.Identity.Model); + bag.Set("serialNumber", inventory.Identity.SerialNumber); + bag.Set("biosVersion", inventory.Identity.BiosVersion); + bag.Set("systemType", inventory.Identity.SystemType); + bag.Set("domain", inventory.Identity.DomainOrWorkgroup); + bag.Set("partOfDomain", inventory.Identity.PartOfDomain ? "true" : "false"); + + bag.Set("os.caption", inventory.Os.Caption); + bag.Set("os.version", inventory.Os.Version); + bag.Set("os.build", inventory.Os.Build); + bag.Set("os.architecture", inventory.Os.Architecture); + bag.Set("os.edition", inventory.Os.Edition); + + bag.Set("cpu.name", inventory.Cpu.Name); + bag.Set("cpu.cores", inventory.Cpu.Cores); + bag.Set("cpu.logicalProcessors", inventory.Cpu.LogicalProcessors); + + if (inventory.TotalPhysicalMemoryBytes > 0) + { + bag.Set("memory.totalGb", Math.Round(inventory.TotalPhysicalMemoryBytes / 1024d / 1024 / 1024, 2)); + } + + bag.Set("disk.count", inventory.Disks.Count); + if (inventory.Disks.Count > 0) + { + bag.Set("disk.totalGb", Math.Round(inventory.Disks.Sum(d => d.SizeBytes) / 1024d / 1024 / 1024, 2)); + } + + if (inventory.Volumes.Count > 0) + { + bag.Set("volume.freeGb", Math.Round(inventory.Volumes.Min(v => v.FreeSpaceBytes) / 1024d / 1024 / 1024, 2)); + } + + bag.SetMany("network.ipv4", inventory.Network.SelectMany(n => n.Ipv4Addresses)); + bag.SetMany("network.mac", inventory.Network.Select(n => n.MacAddress).Where(m => m is not null)!); + bag.SetMany("network.dns", inventory.Network.SelectMany(n => n.DnsServers)); + + return bag; + } +} diff --git a/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs b/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs new file mode 100644 index 0000000..e468b5c --- /dev/null +++ b/src/Shared.Infrastructure/Grouping/RuleEvaluator.cs @@ -0,0 +1,166 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Shared.Contracts.Models; + +namespace Shared.Infrastructure.Grouping; + +/// +/// Evaluates dynamic group rules against a device field bag. Deterministic and +/// side-effect free so the same rules can be previewed in the UI, evaluated on +/// the server, and unit tested. +/// +public static class RuleEvaluator +{ + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250); + + /// Operators that are inherently negative and so must hold for ALL values. + private static bool IsUniversal(RuleOperator op) + => op is RuleOperator.NotEquals or RuleOperator.NotContains or RuleOperator.NotIn or RuleOperator.NotExists; + + public static bool Matches(GroupRuleSet? ruleSet, DeviceFieldBag fields) + { + var groups = ruleSet?.Groups; + if (groups is null || groups.Count == 0) + { + // A dynamic group with no rules matches nothing (safer than everything). + return false; + } + + return Combine(ruleSet!.Combine, groups.Select(g => Matches(g, fields))); + } + + public static bool Matches(RuleGroup group, DeviceFieldBag fields) + { + var results = new List(); + + if (group.Conditions is { Count: > 0 }) + { + results.AddRange(group.Conditions.Select(c => Matches(c, fields))); + } + + if (group.Groups is { Count: > 0 }) + { + results.AddRange(group.Groups.Select(g => Matches(g, fields))); + } + + if (results.Count == 0) + { + return false; + } + + var result = Combine(group.Combine, results); + return group.Negate ? !result : result; + } + + public static bool Matches(RuleCondition condition, DeviceFieldBag fields) + { + var present = fields.TryGet(condition.Field, out var values); + + bool result; + switch (condition.Operator) + { + case RuleOperator.Exists: + result = present && values.Count > 0; + break; + + case RuleOperator.NotExists: + result = !present || values.Count == 0; + break; + + default: + if (!present || values.Count == 0) + { + // A missing field satisfies only the negative operators. + result = IsUniversal(condition.Operator); + break; + } + + result = IsUniversal(condition.Operator) + ? values.All(v => Compare(v, condition)) + : values.Any(v => Compare(v, condition)); + break; + } + + return condition.Negate ? !result : result; + } + + private static bool Combine(RuleCombine combine, IEnumerable results) + => combine == RuleCombine.Or ? results.Any(r => r) : results.All(r => r); + + private static bool Compare(string actual, RuleCondition condition) + { + var expected = condition.Value ?? string.Empty; + + switch (condition.Operator) + { + case RuleOperator.Equals: + return string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase); + case RuleOperator.NotEquals: + return !string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase); + case RuleOperator.Contains: + return actual.Contains(expected, StringComparison.OrdinalIgnoreCase); + case RuleOperator.NotContains: + return !actual.Contains(expected, StringComparison.OrdinalIgnoreCase); + case RuleOperator.StartsWith: + return actual.StartsWith(expected, StringComparison.OrdinalIgnoreCase); + case RuleOperator.EndsWith: + return actual.EndsWith(expected, StringComparison.OrdinalIgnoreCase); + + case RuleOperator.Regex: + try + { + return Regex.IsMatch(actual, expected, RegexOptions.IgnoreCase, RegexTimeout); + } + catch (Exception ex) when (ex is ArgumentException or RegexMatchTimeoutException) + { + // Invalid or runaway pattern never matches (and never throws + // out of evaluation, which would break the whole group). + return false; + } + + case RuleOperator.In: + return SplitList(expected).Any(item => string.Equals(actual, item, StringComparison.OrdinalIgnoreCase)); + case RuleOperator.NotIn: + return !SplitList(expected).Any(item => string.Equals(actual, item, StringComparison.OrdinalIgnoreCase)); + + case RuleOperator.GreaterThan: + case RuleOperator.GreaterOrEqual: + case RuleOperator.LessThan: + case RuleOperator.LessOrEqual: + return CompareNumeric(actual, expected, condition.Operator); + + default: + return false; + } + } + + private static bool CompareNumeric(string actual, string expected, RuleOperator op) + { + if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var left) + || !double.TryParse(expected, NumberStyles.Float, CultureInfo.InvariantCulture, out var right)) + { + // Fall back to ordinal text comparison so version-ish strings still order. + var comparison = string.Compare(actual, expected, StringComparison.OrdinalIgnoreCase); + return op switch + { + RuleOperator.GreaterThan => comparison > 0, + RuleOperator.GreaterOrEqual => comparison >= 0, + RuleOperator.LessThan => comparison < 0, + RuleOperator.LessOrEqual => comparison <= 0, + _ => false, + }; + } + + return op switch + { + RuleOperator.GreaterThan => left > right, + RuleOperator.GreaterOrEqual => left >= right, + RuleOperator.LessThan => left < right, + RuleOperator.LessOrEqual => left <= right, + _ => false, + }; + } + + private static IEnumerable SplitList(string value) + => value.Split([',', ';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); +} diff --git a/src/Shared.Infrastructure/Logging/LogSettings.cs b/src/Shared.Infrastructure/Logging/LogSettings.cs new file mode 100644 index 0000000..5c36706 --- /dev/null +++ b/src/Shared.Infrastructure/Logging/LogSettings.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Configuration; + +namespace Shared.Infrastructure.Logging; + +/// +/// Centralized logging configuration shared by every service. Values come from +/// configuration/environment with sane defaults; nothing is hard-coded at a +/// call site. +/// +public sealed record LogSettings +{ + /// Minimum level: Verbose/Debug/Information/Warning/Error/Fatal. + public string Level { get; init; } = "Information"; + + /// Emit compact JSON instead of human-readable console text. + public bool Json { get; init; } + + /// Directory for rolling log files. Empty disables file logging. + public string? Directory { get; init; } + + /// Base file name (a date is inserted by the rolling policy). + public string FileName { get; init; } = "app.log"; + + /// How many rolled files to keep (the rolling limit, not days). + public int RetainedFileCount { get; init; } = LogDefaults.Server.RetainedFileCount; + + /// Size cap per file before rolling to the next sequence number. + public long FileSizeLimitBytes { get; init; } = LogDefaults.Server.FileSizeLimitBytes; + + public bool FileEnabled => !string.IsNullOrWhiteSpace(Directory); + + /// + /// Reads LOG_LEVEL / LOG_JSON / LOG_DIRECTORY / LOG_RETAIN_FILES / + /// LOG_MAX_BYTES, falling back to the supplied per-role + /// . + /// + public static LogSettings FromConfiguration( + IConfiguration configuration, + LogRoleDefaults defaults, + string? defaultDirectory = null) + { + var directory = configuration["LOG_DIRECTORY"]; + if (string.IsNullOrWhiteSpace(directory)) + { + directory = defaultDirectory; + } + + return new LogSettings + { + Level = string.IsNullOrWhiteSpace(configuration["LOG_LEVEL"]) ? "Information" : configuration["LOG_LEVEL"]!, + Json = configuration["LOG_JSON"] == "1", + Directory = directory, + FileName = defaults.FileName, + RetainedFileCount = int.TryParse(configuration["LOG_RETAIN_FILES"], out var count) && count > 0 + ? count + : defaults.RetainedFileCount, + FileSizeLimitBytes = long.TryParse(configuration["LOG_MAX_BYTES"], out var bytes) && bytes > 0 + ? bytes + : defaults.FileSizeLimitBytes, + }; + } +} + +/// Per-role rolling-file defaults. +public sealed record LogRoleDefaults(string FileName, long FileSizeLimitBytes, int RetainedFileCount); + +/// +/// Central logging defaults. Endpoints are disk-constrained and numerous, so +/// the agent keeps a smaller footprint than the server. +/// +public static class LogDefaults +{ + /// Agent: roll at 5 MB, keep the last 3 files (15 MB ceiling). + public static readonly LogRoleDefaults Agent = new("agent.log", 5L * 1024 * 1024, 3); + + /// Backend: roll at 10 MB, keep the last 7 files (70 MB ceiling). + public static readonly LogRoleDefaults Server = new("backend.log", 10L * 1024 * 1024, 7); +} diff --git a/src/Shared.Infrastructure/Logging/LoggingSetup.cs b/src/Shared.Infrastructure/Logging/LoggingSetup.cs new file mode 100644 index 0000000..2fdf1d0 --- /dev/null +++ b/src/Shared.Infrastructure/Logging/LoggingSetup.cs @@ -0,0 +1,117 @@ +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Compact; + +namespace Shared.Infrastructure.Logging; + +/// +/// Builds the one Serilog pipeline every service uses: console (text or compact +/// JSON) plus a daily rolling file with size caps and retention. Correlation +/// fields (CorrelationId, ClientId, JobId, ShellSessionId, BrowserSessionId, +/// RemoteIp) flow through as structured properties from log scopes. +/// Secret material is never logged — see . +/// +public static class LoggingSetup +{ + /// Human-readable console/file template including correlation context. + private const string TextTemplate = + "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}" + + "{#if CorrelationId is not null} correlation={CorrelationId}{#end}" + + "{NewLine}{Exception}"; + + private const string SimpleTemplate = + "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"; + + public static Logger CreateLogger(LogSettings settings, string application) + { + var configuration = new LoggerConfiguration() + .MinimumLevel.Is(ParseLevel(settings.Level)) + // Framework noise stays at Warning regardless of the app level. + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning) + .Enrich.FromLogContext() + .Enrich.WithMachineName() + .Enrich.WithProperty("Application", application); + + if (settings.Json) + { + configuration.WriteTo.Console(new CompactJsonFormatter()); + } + else + { + configuration.WriteTo.Console(outputTemplate: SimpleTemplate); + } + + if (settings.FileEnabled) + { + var path = Path.Combine(settings.Directory!, settings.FileName); + try + { + Directory.CreateDirectory(settings.Directory!); + + if (settings.Json) + { + configuration.WriteTo.File( + new CompactJsonFormatter(), + path, + rollingInterval: RollingInterval.Day, + rollOnFileSizeLimit: true, + fileSizeLimitBytes: settings.FileSizeLimitBytes, + retainedFileCountLimit: settings.RetainedFileCount, + shared: true); + } + else + { + configuration.WriteTo.File( + path, + outputTemplate: SimpleTemplate, + rollingInterval: RollingInterval.Day, + rollOnFileSizeLimit: true, + fileSizeLimitBytes: settings.FileSizeLimitBytes, + retainedFileCountLimit: settings.RetainedFileCount, + shared: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A bad log path must never prevent the service from starting; + // console logging still applies. + Console.Error.WriteLine($"warning: file logging disabled ({ex.Message})"); + } + } + + return configuration.CreateLogger(); + } + + private static LogEventLevel ParseLevel(string level) + => Enum.TryParse(level, ignoreCase: true, out var parsed) + ? parsed + : LogEventLevel.Information; + + /// Structured-log property names used for correlation. + public static class Fields + { + public const string CorrelationId = "CorrelationId"; + public const string ClientId = "ClientId"; + public const string JobId = "JobId"; + public const string ShellSessionId = "ShellSessionId"; + public const string BrowserSessionId = "BrowserSessionId"; + public const string RemoteIp = "RemoteIp"; + } +} + +/// +/// Names that must never be written to logs. Kept next to the logging setup so +/// the rule is discoverable where logging is configured. +/// +public static class Redaction +{ + public static readonly string[] NeverLog = + [ + "bootstrapToken", "password", "clientSecret", "seed", "nkeySeed", + "jwt", "cookie", "authorization", "signingSeed", "secretKey", + ]; +} diff --git a/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs b/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs new file mode 100644 index 0000000..36b580a --- /dev/null +++ b/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs @@ -0,0 +1,40 @@ +namespace Shared.Infrastructure.Nats; + +/// +/// JetStream stream and consumer definitions. Durable commands use explicit +/// ack; the agent acks a script command only after durably recording the job +/// id as accepted. High-volume output/shell traffic stays on Core NATS. +/// +public static class JetStreamDefaults +{ + public const string CommandStreamName = "COMMANDS"; + + public static readonly string[] CommandStreamSubjects = + [ + "agent.*.command.script", + "agent.*.command.inventory", + "agent.*.command.file", + ]; + + public const string JobEventsStreamName = "JOB_EVENTS"; + + public static readonly string[] JobEventsStreamSubjects = + [ + "job.*.state", + ]; + + /// Durable consumer name for one agent's command feed. + public static string AgentCommandConsumerName(string clientId) + => $"agent-commands-{SubjectIdentifier.Require(clientId)}"; + + /// Filter subject for one agent's durable command consumer. + public static string AgentCommandFilterSubject(string clientId) + => $"agent.{SubjectIdentifier.Require(clientId)}.command.*"; + + /// Durable consumer used by the backend to persist job state transitions. + public const string BackendJobEventsConsumerName = "backend-job-events"; + + public static readonly TimeSpan CommandAckWait = TimeSpan.FromSeconds(30); + public static readonly TimeSpan CommandMaxAge = TimeSpan.FromDays(2); + public static readonly TimeSpan JobEventsMaxAge = TimeSpan.FromDays(7); +} diff --git a/src/Shared.Infrastructure/Nats/NatsSubjects.cs b/src/Shared.Infrastructure/Nats/NatsSubjects.cs new file mode 100644 index 0000000..a67981b --- /dev/null +++ b/src/Shared.Infrastructure/Nats/NatsSubjects.cs @@ -0,0 +1,121 @@ +namespace Shared.Infrastructure.Nats; + +/// +/// Single source of truth for every NATS subject in the system. +/// Never interpolate subject strings elsewhere — add a helper here. +/// Subjects are generic by design: no product names, no version segments. +/// +public static class NatsSubjects +{ + // ── Agent-published state ──────────────────────────────────────────── + public static string AgentPresence(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.presence"; + public static string AgentInventory(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.inventory"; + public static string AgentProgress(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.progress"; + public static string AgentEvent(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.event"; + + // ── Backend → agent commands ───────────────────────────────────────── + public static string AgentCommandInventory(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.inventory"; + public static string AgentCommandScript(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.script"; + public static string AgentCommandFile(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.file"; + public static string AgentCommandShellOpen(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.open"; + public static string AgentCommandShellInput(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.input"; + public static string AgentCommandShellResize(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.resize"; + public static string AgentCommandShellClose(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.close"; + + /// Wildcard the agent subscribes to for all of its commands. + public static string AgentCommandWildcard(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.>"; + + // ── Agent-published shell streams ──────────────────────────────────── + public static string AgentShellOutput(string clientId, Guid sessionId) + => $"agent.{SubjectIdentifier.Require(clientId)}.shell.{SubjectIdentifier.FromGuid(sessionId)}.output"; + + public static string AgentShellState(string clientId, Guid sessionId) + => $"agent.{SubjectIdentifier.Require(clientId)}.shell.{SubjectIdentifier.FromGuid(sessionId)}.state"; + + // ── Job streams ────────────────────────────────────────────────────── + public static string JobProgress(Guid jobId) => $"job.{SubjectIdentifier.FromGuid(jobId)}.progress"; + public static string JobOutput(Guid jobId) => $"job.{SubjectIdentifier.FromGuid(jobId)}.output"; + public static string JobState(Guid jobId) => $"job.{SubjectIdentifier.FromGuid(jobId)}.state"; + + // ── Browser session subjects (backend republishes; browser scoped) ── + public static string BrowserEvent(string browserSessionId) + => $"browser.{SubjectIdentifier.Require(browserSessionId)}.event"; + + public static string BrowserJob(string browserSessionId, Guid jobId) + => $"browser.{SubjectIdentifier.Require(browserSessionId)}.job.{SubjectIdentifier.FromGuid(jobId)}"; + + public static string BrowserShell(string browserSessionId, Guid shellId) + => $"browser.{SubjectIdentifier.Require(browserSessionId)}.shell.{SubjectIdentifier.FromGuid(shellId)}"; + + /// Browser-published shell input, forwarded by the backend after ownership checks. + public static string BrowserShellInput(string browserSessionId, Guid shellId) + => $"browser.{SubjectIdentifier.Require(browserSessionId)}.shell.{SubjectIdentifier.FromGuid(shellId)}.input"; + + /// Everything a browser session may subscribe/publish below. + public static string BrowserSessionWildcard(string browserSessionId) + => $"browser.{SubjectIdentifier.Require(browserSessionId)}.>"; + + // ── System events (backend internal fan-out) ───────────────────────── + public const string SystemAgentEnrolled = "system.agent.enrolled"; + public const string SystemAgentDisconnected = "system.agent.disconnected"; + public const string SystemJobCreated = "system.job.created"; + public const string SystemJobCompleted = "system.job.completed"; + + // ── Wildcards used by backend workers / permissions ───────────────── + public const string AllAgentPresence = "agent.*.presence"; + public const string AllAgentInventory = "agent.*.inventory"; + public const string AllAgentProgress = "agent.*.progress"; + public const string AllAgentEvents = "agent.*.event"; + public const string AllAgentShellStreams = "agent.*.shell.>"; + public const string AllJobProgress = "job.*.progress"; + public const string AllJobOutput = "job.*.output"; + public const string AllJobState = "job.*.state"; + public const string AllBrowserSubjects = "browser.>"; + public const string InboxWildcard = "_INBOX.>"; + + /// + /// Publish permissions granted to an enrolled agent's NATS user JWT. + /// Includes the narrowly scoped JetStream API subjects needed to bind and + /// pull from the agent's own durable command consumer. + /// + public static string[] AgentPublishPermissions(string clientId) + { + var id = SubjectIdentifier.Require(clientId); + var consumer = JetStreamDefaults.AgentCommandConsumerName(id); + return + [ + $"agent.{id}.presence", + $"agent.{id}.inventory", + $"agent.{id}.progress", + $"agent.{id}.event", + $"agent.{id}.shell.*.output", + $"agent.{id}.shell.*.state", + AllJobProgress, + AllJobOutput, + AllJobState, + $"$JS.API.CONSUMER.INFO.{JetStreamDefaults.CommandStreamName}.{consumer}", + $"$JS.API.CONSUMER.MSG.NEXT.{JetStreamDefaults.CommandStreamName}.{consumer}", + $"$JS.ACK.{JetStreamDefaults.CommandStreamName}.{consumer}.>", + InboxWildcard, + ]; + } + + /// Subscribe permissions granted to an enrolled agent's NATS user JWT. + public static string[] AgentSubscribePermissions(string clientId) + { + var id = SubjectIdentifier.Require(clientId); + return + [ + $"agent.{id}.command.>", + InboxWildcard, + ]; + } + + /// Publish permissions granted to a browser session's NATS user JWT. + public static string[] BrowserPublishPermissions(string browserSessionId) + => [BrowserSessionWildcard(browserSessionId), InboxWildcard]; + + /// Subscribe permissions granted to a browser session's NATS user JWT. + public static string[] BrowserSubscribePermissions(string browserSessionId) + => [BrowserSessionWildcard(browserSessionId), InboxWildcard]; +} diff --git a/src/Shared.Infrastructure/Nats/SubjectIdentifier.cs b/src/Shared.Infrastructure/Nats/SubjectIdentifier.cs new file mode 100644 index 0000000..67b67bc --- /dev/null +++ b/src/Shared.Infrastructure/Nats/SubjectIdentifier.cs @@ -0,0 +1,32 @@ +using System.Text.RegularExpressions; + +namespace Shared.Infrastructure.Nats; + +/// +/// Central validation for identifiers embedded in NATS subjects +/// (client ids, job ids, session ids). Prevents subject injection. +/// +public static partial class SubjectIdentifier +{ + [GeneratedRegex("^[a-z0-9][a-z0-9-]{0,127}$")] + private static partial Regex ValidPattern(); + + public static bool IsValid(string? value) + => value is not null && ValidPattern().IsMatch(value); + + /// Returns the value unchanged or throws if it is not subject-safe. + public static string Require(string value) + { + if (!IsValid(value)) + { + throw new ArgumentException( + "Identifier is not subject-safe (expected lowercase alphanumeric/hyphen, max 128 chars).", + nameof(value)); + } + + return value; + } + + /// Canonical subject-safe form for GUID identifiers (lowercase, hyphenated). + public static string FromGuid(Guid id) => id.ToString("D").ToLowerInvariant(); +} diff --git a/src/Shared.Infrastructure/Routing/ServerUrl.cs b/src/Shared.Infrastructure/Routing/ServerUrl.cs new file mode 100644 index 0000000..1b6a3ac --- /dev/null +++ b/src/Shared.Infrastructure/Routing/ServerUrl.cs @@ -0,0 +1,106 @@ +using Shared.Infrastructure.Constants; + +namespace Shared.Infrastructure.Routing; + +/// +/// Canonical parsing of the administrator-configured ServerURL. +/// Admins configure only http://host or https://host (optional +/// base path); WebSocket endpoints are derived (http→ws, https→wss). +/// +public sealed class ServerUrl +{ + private ServerUrl(Uri httpBase) + { + HttpBase = httpBase; + var wsScheme = httpBase.Scheme == Uri.UriSchemeHttps ? "wss" : "ws"; + var builder = new UriBuilder(httpBase) { Scheme = wsScheme, Port = httpBase.IsDefaultPort ? -1 : httpBase.Port }; + WebSocketBase = builder.Uri; + } + + /// Normalized HTTP(S) base including any base path, always ending with '/'. + public Uri HttpBase { get; } + + /// Derived ws(s) base including any base path, always ending with '/'. + public Uri WebSocketBase { get; } + + public Uri AgentWebSocketEndpoint => Append(WebSocketBase, MessagingPaths.Agent); + + public Uri BrowserWebSocketEndpoint => Append(WebSocketBase, MessagingPaths.Browser); + + /// Builds an absolute API URI from a rooted route such as /api/health. + public Uri ApiEndpoint(string rootedRoute) => Append(HttpBase, rootedRoute); + + private static Uri Append(Uri baseUri, string rootedRoute) + => new(baseUri, rootedRoute.TrimStart('/')); + + public static ServerUrl Parse(string value) + { + if (!TryParse(value, out var result, out var error)) + { + throw new FormatException($"Invalid ServerURL '{value}': {error}"); + } + + return result; + } + + public static bool TryParse(string? value, out ServerUrl result, out string error) + { + result = null!; + error = string.Empty; + + if (string.IsNullOrWhiteSpace(value)) + { + error = "value is empty."; + return false; + } + + if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri)) + { + error = "value is not an absolute URL."; + return false; + } + + if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) + { + error = $"unsupported scheme '{uri.Scheme}' (only http/https)."; + return false; + } + + if (!string.IsNullOrEmpty(uri.UserInfo)) + { + error = "embedded credentials are not allowed."; + return false; + } + + if (!string.IsNullOrEmpty(uri.Fragment)) + { + error = "fragments are not allowed."; + return false; + } + + if (!string.IsNullOrEmpty(uri.Query)) + { + error = "query strings are not allowed."; + return false; + } + + if (uri.HostNameType is not (UriHostNameType.Dns or UriHostNameType.IPv4 or UriHostNameType.IPv6)) + { + error = "host is malformed."; + return false; + } + + // Normalize: keep any base path, ensure it ends with '/'. + var path = uri.AbsolutePath; + if (!path.EndsWith('/')) + { + path += "/"; + } + + var builder = new UriBuilder(uri.Scheme, uri.Host, uri.IsDefaultPort ? -1 : uri.Port, path); + result = new ServerUrl(builder.Uri); + return true; + } + + public override string ToString() => HttpBase.ToString(); +} diff --git a/src/Shared.Infrastructure/Security/TokenHashing.cs b/src/Shared.Infrastructure/Security/TokenHashing.cs new file mode 100644 index 0000000..3aa2dc2 --- /dev/null +++ b/src/Shared.Infrastructure/Security/TokenHashing.cs @@ -0,0 +1,36 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Shared.Infrastructure.Security; + +/// +/// Bootstrap-token helpers. The backend stores only the SHA-256 hash of a +/// token; the plaintext exists once, in the creation response. +/// +public static class TokenHashing +{ + /// Lowercase hex SHA-256 of the UTF-8 token text. + public static string Sha256Hex(string token) + => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + + /// Constant-time comparison of a candidate token against a stored hash. + public static bool Matches(string candidateToken, string storedHashHex) + { + var candidate = Encoding.UTF8.GetBytes(Sha256Hex(candidateToken)); + var stored = Encoding.UTF8.GetBytes(storedHashHex.ToLowerInvariant()); + return candidate.Length == stored.Length && CryptographicOperations.FixedTimeEquals(candidate, stored); + } +} + +/// Cryptographically random, URL-safe token generation. +public static class TokenGenerator +{ + public static string CreateUrlSafeToken(int entropyBytes) + { + var bytes = RandomNumberGenerator.GetBytes(entropyBytes); + return Convert.ToBase64String(bytes) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + } +} diff --git a/src/Shared.Infrastructure/Shared.Infrastructure.csproj b/src/Shared.Infrastructure/Shared.Infrastructure.csproj new file mode 100644 index 0000000..428e389 --- /dev/null +++ b/src/Shared.Infrastructure/Shared.Infrastructure.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + Shared.Infrastructure + + + + + + + + + + + + + + + + + diff --git a/src/Shared.Infrastructure/Versioning/BuildVersion.cs b/src/Shared.Infrastructure/Versioning/BuildVersion.cs new file mode 100644 index 0000000..32f5dc6 --- /dev/null +++ b/src/Shared.Infrastructure/Versioning/BuildVersion.cs @@ -0,0 +1,59 @@ +using System.Globalization; +using System.Reflection; + +namespace Shared.Infrastructure.Versioning; + +/// +/// Unified build version (yyyy.MM.dd.HHmm, UTC) shared by every artifact. +/// The value is stamped at build time via the UnifiedVersion MSBuild property. +/// +public static class BuildVersion +{ + /// The unified version of the running application's entry assembly. + public static string Current { get; } = Resolve(Assembly.GetEntryAssembly()); + + public static string Resolve(Assembly? assembly) + { + var informational = assembly? + .GetCustomAttribute()? + .InformationalVersion; + + if (string.IsNullOrWhiteSpace(informational)) + { + return "0.0.0.0"; + } + + // Strip any source-revision suffix MSBuild may append (+sha). + var plus = informational.IndexOf('+'); + return plus >= 0 ? informational[..plus] : informational; + } + + /// + /// Deterministic MSI ProductVersion transform. MSI limits: major ≤ 255, + /// minor ≤ 255, build ≤ 65535. Mapping keeps ordering within a year: + /// yyyy.MM.dd.HHmm → (yyyy-2000).(MM).((dd-1)*1440 + HH*60 + mm). + /// The full unified version is retained in MSI display metadata. + /// + public static string ToMsiProductVersion(string unifiedVersion) + { + var parts = unifiedVersion.Split('.'); + if (parts.Length != 4 + || !int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var year) + || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var month) + || !int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out var day) + || !int.TryParse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture, out var hhmm)) + { + throw new FormatException($"'{unifiedVersion}' is not a unified yyyy.MM.dd.HHmm version."); + } + + var major = year - 2000; + var build = (day - 1) * 1440 + (hhmm / 100) * 60 + hhmm % 100; + + if (major is < 0 or > 255 || month is < 1 or > 12 || build is < 0 or > 65535) + { + throw new FormatException($"'{unifiedVersion}' cannot be mapped to an MSI ProductVersion."); + } + + return $"{major}.{month}.{build}"; + } +} diff --git a/src/WebUI/.gitignore b/src/WebUI/.gitignore new file mode 100644 index 0000000..079b463 --- /dev/null +++ b/src/WebUI/.gitignore @@ -0,0 +1,23 @@ +node_modules + +# Output +.output +.vercel +.netlify +.wrangler +/.svelte-kit +/build + +# OS +.DS_Store +Thumbs.db + +# Env +.env +.env.* +!.env.example +!.env.test + +# Vite +vite.config.js.timestamp-* +vite.config.ts.timestamp-* diff --git a/src/WebUI/.npmrc b/src/WebUI/.npmrc new file mode 100644 index 0000000..abf580c --- /dev/null +++ b/src/WebUI/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/src/WebUI/README.md b/src/WebUI/README.md new file mode 100644 index 0000000..c665ef0 --- /dev/null +++ b/src/WebUI/README.md @@ -0,0 +1,42 @@ +# sv + +Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli). + +## Creating a project + +If you're seeing this, you've probably already done this step. Congrats! + +```sh +# create a new project +npx sv create my-app +``` + +To recreate this project with the same configuration: + +```sh +# recreate this project +npx sv@0.17.0 create --template minimal --types ts --install npm src/WebUI +``` + +## Developing + +Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server: + +```sh +npm run dev + +# or start the server and open the app in a new browser tab +npm run dev -- --open +``` + +## Building + +To create a production version of your app: + +```sh +npm run build +``` + +You can preview the production build with `npm run preview`. + +> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment. diff --git a/src/WebUI/package-lock.json b/src/WebUI/package-lock.json new file mode 100644 index 0000000..2586fc6 --- /dev/null +++ b/src/WebUI/package-lock.json @@ -0,0 +1,2145 @@ +{ + "name": "webui", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webui", + "version": "0.0.1", + "dependencies": { + "@nats-io/nats-core": "^3.4.0", + "@nats-io/nkeys": "^2.0.3", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", + "monaco-editor": "^0.56.0" + }, + "devDependencies": { + "@sveltejs/adapter-node": "^5.5.7", + "@sveltejs/kit": "^2.63.0", + "@sveltejs/vite-plugin-svelte": "^7.1.2", + "@types/node": "^26.1.2", + "svelte": "^5.56.1", + "svelte-check": "^4.6.0", + "typescript": "^6.0.3", + "vite": "^8.0.16" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@nats-io/nats-core": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@nats-io/nats-core/-/nats-core-3.4.0.tgz", + "integrity": "sha512-QMDM86EUNm+wudlKC67HLar/KHHQUvJGLfb4jbahje3pUk3K9afeck9fwsxBZF0eUFox6T/TA6m/t+lQqf+QsQ==", + "license": "Apache-2.0", + "dependencies": { + "@nats-io/nkeys": "2.0.3", + "@nats-io/nuid": "3.0.0" + } + }, + "node_modules/@nats-io/nkeys": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@nats-io/nkeys/-/nkeys-2.0.3.tgz", + "integrity": "sha512-JVt56GuE6Z89KUkI4TXUbSI9fmIfAmk6PMPknijmuL72GcD+UgIomTcRWiNvvJKxA01sBbmIPStqJs5cMRBC3A==", + "license": "Apache-2.0", + "dependencies": { + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@nats-io/nuid": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nats-io/nuid/-/nuid-3.0.0.tgz", + "integrity": "sha512-QbXZDrxmYlrn5AD06gYcUTmEHwxn96HBQMIk7XTjDlEcx6FPzVBBPjp4AMRh1lEv6B4iJ6Xb/Uz61JugPXFRQg==", + "license": "Apache-2.0", + "engines": { + "node": ">= 22.x" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.143.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.143.0.tgz", + "integrity": "sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.29", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", + "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz", + "integrity": "sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.3.tgz", + "integrity": "sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.3.tgz", + "integrity": "sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.3.tgz", + "integrity": "sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.3.tgz", + "integrity": "sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.3.tgz", + "integrity": "sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.3.tgz", + "integrity": "sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.3.tgz", + "integrity": "sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.3.tgz", + "integrity": "sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.3.tgz", + "integrity": "sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.3.tgz", + "integrity": "sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.3.tgz", + "integrity": "sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.3.tgz", + "integrity": "sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.3.tgz", + "integrity": "sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz", + "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.1.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-replace": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.3.tgz", + "integrity": "sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "magic-string": "^0.30.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.4.tgz", + "integrity": "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.4.tgz", + "integrity": "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.4.tgz", + "integrity": "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.4.tgz", + "integrity": "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.4.tgz", + "integrity": "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.4.tgz", + "integrity": "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.4.tgz", + "integrity": "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.4.tgz", + "integrity": "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.4.tgz", + "integrity": "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.4.tgz", + "integrity": "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.4.tgz", + "integrity": "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.4.tgz", + "integrity": "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.4.tgz", + "integrity": "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.4.tgz", + "integrity": "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.4.tgz", + "integrity": "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.4.tgz", + "integrity": "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.4.tgz", + "integrity": "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.4.tgz", + "integrity": "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.4.tgz", + "integrity": "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.4.tgz", + "integrity": "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.4.tgz", + "integrity": "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.4.tgz", + "integrity": "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.4.tgz", + "integrity": "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.4.tgz", + "integrity": "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.4.tgz", + "integrity": "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.12.tgz", + "integrity": "sha512-J1jNYG23QWd67UfrQSFHtjhV37r9mVi0gdc12A3MWPldOjRK35Xk+um+qACPVjgw3AleiqoyEAhok8Wm3q46NA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/adapter-node": { + "version": "5.5.7", + "resolved": "https://registry.npmjs.org/@sveltejs/adapter-node/-/adapter-node-5.5.7.tgz", + "integrity": "sha512-uOfc9eVlI3A37RRSaKcgrheBYPrfJwC9VMqDp8x/O6tlKdcLLvHThSWD0KNIbjQ/d+7bwLGx3vx6aowAcRfd2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/plugin-commonjs": "^29.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.0", + "@rollup/plugin-replace": "^6.0.3", + "rollup": "^4.59.0" + }, + "peerDependencies": { + "@sveltejs/kit": "^2.4.0" + } + }, + "node_modules/@sveltejs/kit": { + "version": "2.70.2", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.2.tgz", + "integrity": "sha512-RzRoRpuR2KXqc5yMO0akQHDZeT4AslOlznGITURsqHaVbtyYP4Wn3eE3gxj9JcDyNYO0crkxhdwFHc+2vkVm6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@sveltejs/acorn-typescript": "^1.0.9", + "@types/cookie": "^0.6.0", + "acorn": "^8.16.0", + "cookie": "^0.6.0", + "devalue": "^5.8.1", + "esm-env": "^1.2.2", + "kleur": "^4.1.5", + "magic-string": "^0.30.5", + "mrmime": "^2.0.0", + "set-cookie-parser": "^3.0.0", + "sirv": "^3.0.0" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "engines": { + "node": ">=18.13" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0", + "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0", + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.3.3 || ^6.0.0", + "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@sveltejs/load-config": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz", + "integrity": "sha512-5m3B2cbqQ4TbwW6Xkh66Ntw6dD7gNc77cCxABTTesWcq9jxIzMgTk97pZx5vEtvQx8iokgi7GIphqZe+PGwcZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-7.2.0.tgz", + "integrity": "sha512-1SpkuMSRLfugrVX+IrKfE1RUegzo8AQzKQ6qQPfVzbcWi5IhuTPaKb5ZrLpucleFznkc4/RTeSPoRnGWFxX+EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "deepmerge": "^4.3.1", + "magic-string": "^0.30.21", + "obug": "^2.1.0", + "vitefu": "^1.1.2" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24" + }, + "peerDependencies": { + "svelte": "^5.46.4", + "vite": "^8.0.0-beta.7 || ^8.0.0" + } + }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.1.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", + "integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.3.0" + } + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/devalue": { + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz", + "integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==", + "dev": true, + "license": "MIT" + }, + "node_modules/dompurify": { + "version": "3.4.8", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.8.tgz", + "integrity": "sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.1.tgz", + "integrity": "sha512-MXjVkrBAjuwIZ8xq9+a1MOOnLIwANZOx/4gtdWHfSJtXOrUh2QQK2I5mMC3urLli559jTlq2j+kSqht80uRgog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/marked": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", + "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/monaco-editor": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.56.0.tgz", + "integrity": "sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==", + "license": "MIT", + "dependencies": { + "dompurify": "3.4.8", + "marked": "14.0.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/mrmime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", + "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/nanoid": { + "version": "3.3.17", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz", + "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.26", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", + "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.17", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rolldown": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.3.tgz", + "integrity": "sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.143.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.2.3", + "@rolldown/binding-darwin-arm64": "1.2.3", + "@rolldown/binding-darwin-x64": "1.2.3", + "@rolldown/binding-freebsd-x64": "1.2.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.3", + "@rolldown/binding-linux-arm64-gnu": "1.2.3", + "@rolldown/binding-linux-arm64-musl": "1.2.3", + "@rolldown/binding-linux-ppc64-gnu": "1.2.3", + "@rolldown/binding-linux-s390x-gnu": "1.2.3", + "@rolldown/binding-linux-x64-gnu": "1.2.3", + "@rolldown/binding-linux-x64-musl": "1.2.3", + "@rolldown/binding-openharmony-arm64": "1.2.3", + "@rolldown/binding-win32-arm64-msvc": "1.2.3", + "@rolldown/binding-win32-x64-msvc": "1.2.3" + } + }, + "node_modules/rollup": { + "version": "4.62.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.4.tgz", + "integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.62.4", + "@rollup/rollup-android-arm64": "4.62.4", + "@rollup/rollup-darwin-arm64": "4.62.4", + "@rollup/rollup-darwin-x64": "4.62.4", + "@rollup/rollup-freebsd-arm64": "4.62.4", + "@rollup/rollup-freebsd-x64": "4.62.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", + "@rollup/rollup-linux-arm-musleabihf": "4.62.4", + "@rollup/rollup-linux-arm64-gnu": "4.62.4", + "@rollup/rollup-linux-arm64-musl": "4.62.4", + "@rollup/rollup-linux-loong64-gnu": "4.62.4", + "@rollup/rollup-linux-loong64-musl": "4.62.4", + "@rollup/rollup-linux-ppc64-gnu": "4.62.4", + "@rollup/rollup-linux-ppc64-musl": "4.62.4", + "@rollup/rollup-linux-riscv64-gnu": "4.62.4", + "@rollup/rollup-linux-riscv64-musl": "4.62.4", + "@rollup/rollup-linux-s390x-gnu": "4.62.4", + "@rollup/rollup-linux-x64-gnu": "4.62.4", + "@rollup/rollup-linux-x64-musl": "4.62.4", + "@rollup/rollup-openbsd-x64": "4.62.4", + "@rollup/rollup-openharmony-arm64": "4.62.4", + "@rollup/rollup-win32-arm64-msvc": "4.62.4", + "@rollup/rollup-win32-ia32-msvc": "4.62.4", + "@rollup/rollup-win32-x64-gnu": "4.62.4", + "@rollup/rollup-win32-x64-msvc": "4.62.4", + "fsevents": "~2.3.2" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/set-cookie-parser": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz", + "integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/sirv": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", + "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svelte": { + "version": "5.56.8", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz", + "integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.10", + "@types/estree": "^1.0.5", + "@types/trusted-types": "^2.0.7", + "acorn": "^8.12.1", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.8.1", + "esm-env": "^1.2.1", + "esrap": "^2.2.12", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte-check": { + "version": "4.7.4", + "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.7.4.tgz", + "integrity": "sha512-IW9ot9YqAoyv8FvyN+eb4ZTe8zgcKZrJLNYU6dzSKkGwEBsSPc4K7lmQ8bKn8W2YMXM6WDfZSSVOaGtekyUfOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "@sveltejs/load-config": "^0.2.1", + "chokidar": "^4.0.1", + "fdir": "^6.2.0", + "picocolors": "^1.0.0", + "sade": "^1.7.4" + }, + "bin": { + "svelte-check": "bin/svelte-check" + }, + "engines": { + "node": ">= 18.0.0" + }, + "peerDependencies": { + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.0.0 || ^6.0.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz", + "integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.25", + "rolldown": "~1.2.1", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.4.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/zimmerframe": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", + "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/src/WebUI/package.json b/src/WebUI/package.json new file mode 100644 index 0000000..f19595d --- /dev/null +++ b/src/WebUI/package.json @@ -0,0 +1,31 @@ +{ + "name": "webui", + "private": true, + "version": "0.0.1", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "preview": "vite preview", + "prepare": "svelte-kit sync || echo ''", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" + }, + "devDependencies": { + "@sveltejs/adapter-node": "^5.5.7", + "@sveltejs/kit": "^2.63.0", + "@sveltejs/vite-plugin-svelte": "^7.1.2", + "@types/node": "^26.1.2", + "svelte": "^5.56.1", + "svelte-check": "^4.6.0", + "typescript": "^6.0.3", + "vite": "^8.0.16" + }, + "dependencies": { + "@nats-io/nats-core": "^3.4.0", + "@nats-io/nkeys": "^2.0.3", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", + "monaco-editor": "^0.56.0" + } +} diff --git a/src/WebUI/src/app.css b/src/WebUI/src/app.css new file mode 100644 index 0000000..ad0cea6 --- /dev/null +++ b/src/WebUI/src/app.css @@ -0,0 +1,343 @@ +/* ── Design tokens ─────────────────────────────────────────────────── */ +:root { + --font-sans: + 'Segoe UI Variable', 'Segoe UI', system-ui, -apple-system, 'Inter', Roboto, sans-serif; + --font-mono: 'Cascadia Code', 'Cascadia Mono', Consolas, 'JetBrains Mono', monospace; + + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 24px; + --space-6: 32px; + + --bg: #f4f6fa; + --bg-elevated: #ffffff; + --surface: #ffffff; + --surface-muted: #eef1f6; + --border: #dde3ec; + --border-strong: #c3ccd9; + --text: #16202e; + --text-muted: #5b6a7f; + --text-faint: #8b98ab; + + --accent: #2563eb; + --accent-hover: #1d4fd7; + --accent-soft: #dbe7ff; + --accent-contrast: #ffffff; + + --success: #16a34a; + --success-soft: #d7f2e0; + --warning: #d97706; + --warning-soft: #fdeed3; + --danger: #dc2626; + --danger-soft: #fde3e3; + --info: #0891b2; + --info-soft: #d8f1f7; + + --shadow-sm: 0 1px 2px rgb(15 23 42 / 0.06); + --shadow-md: 0 4px 16px rgb(15 23 42 / 0.08); + + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --bg: #0d1420; + --bg-elevated: #131c2b; + --surface: #17212f; + --surface-muted: #1d2938; + --border: #263447; + --border-strong: #35465e; + --text: #e6ecf5; + --text-muted: #9aabc2; + --text-faint: #64748c; + + --accent: #4c8dff; + --accent-hover: #6ba1ff; + --accent-soft: #1b2f52; + --accent-contrast: #0b1220; + + --success: #34d27b; + --success-soft: #12331f; + --warning: #f5a623; + --warning-soft: #3a2a10; + --danger: #f26565; + --danger-soft: #3d1717; + --info: #38c3dd; + --info-soft: #10303a; + + --shadow-sm: 0 1px 2px rgb(0 0 0 / 0.4); + --shadow-md: 0 4px 18px rgb(0 0 0 / 0.45); + + color-scheme: dark; + } +} + +:root[data-theme='dark'] { + --bg: #0d1420; + --bg-elevated: #131c2b; + --surface: #17212f; + --surface-muted: #1d2938; + --border: #263447; + --border-strong: #35465e; + --text: #e6ecf5; + --text-muted: #9aabc2; + --text-faint: #64748c; + + --accent: #4c8dff; + --accent-hover: #6ba1ff; + --accent-soft: #1b2f52; + --accent-contrast: #0b1220; + + --success: #34d27b; + --success-soft: #12331f; + --warning: #f5a623; + --warning-soft: #3a2a10; + --danger: #f26565; + --danger-soft: #3d1717; + --info: #38c3dd; + --info-soft: #10303a; + + --shadow-sm: 0 1px 2px rgb(0 0 0 / 0.4); + --shadow-md: 0 4px 18px rgb(0 0 0 / 0.45); + + color-scheme: dark; +} + +/* ── Base ──────────────────────────────────────────────────────────── */ +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; + height: 100%; +} + +body { + font-family: var(--font-sans); + font-size: 14px; + line-height: 1.5; + background: var(--bg); + color: var(--text); + -webkit-font-smoothing: antialiased; +} + +h1, +h2, +h3 { + margin: 0; + font-weight: 600; + letter-spacing: -0.01em; +} + +h1 { + font-size: 20px; +} + +h2 { + font-size: 16px; +} + +h3 { + font-size: 13px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text-muted); + font-weight: 600; +} + +a { + color: var(--accent); + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +code, +pre { + font-family: var(--font-mono); + font-size: 12.5px; +} + +button { + font-family: inherit; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: var(--radius-sm); +} + +/* ── Shared primitives ─────────────────────────────────────────────── */ +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow-sm); +} + +.btn { + display: inline-flex; + align-items: center; + gap: var(--space-2); + padding: 7px 14px; + border-radius: var(--radius-sm); + border: 1px solid var(--border-strong); + background: var(--surface); + color: var(--text); + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: + background 0.12s ease, + border-color 0.12s ease, + opacity 0.12s ease; +} + +.btn:hover:not(:disabled) { + background: var(--surface-muted); +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn.primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-contrast); +} + +.btn.primary:hover:not(:disabled) { + background: var(--accent-hover); +} + +.btn.danger { + color: var(--danger); + border-color: var(--danger); +} + +.input, +.select, +textarea.input { + padding: 7px 10px; + border-radius: var(--radius-sm); + border: 1px solid var(--border-strong); + background: var(--bg-elevated); + color: var(--text); + font-size: 13px; + font-family: inherit; +} + +.input:focus, +.select:focus { + outline: 2px solid var(--accent); + outline-offset: 0; + border-color: transparent; +} + +/* ── Tables ────────────────────────────────────────────────────────── */ +.table-wrap { + overflow: auto; + border-radius: var(--radius-md); +} + +table.data { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +table.data thead th { + position: sticky; + top: 0; + z-index: 1; + background: var(--surface-muted); + color: var(--text-muted); + font-weight: 600; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.05em; + text-align: left; + padding: 10px 14px; + border-bottom: 1px solid var(--border); + white-space: nowrap; +} + +table.data tbody td { + padding: 10px 14px; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} + +table.data tbody tr { + transition: background 0.1s ease; +} + +table.data tbody tr:hover { + background: var(--surface-muted); +} + +table.data tbody tr.clickable { + cursor: pointer; +} + +/* ── Utility ───────────────────────────────────────────────────────── */ +.muted { + color: var(--text-muted); +} + +.faint { + color: var(--text-faint); +} + +.mono { + font-family: var(--font-mono); +} + +.skeleton { + background: linear-gradient( + 100deg, + var(--surface-muted) 40%, + var(--border) 50%, + var(--surface-muted) 60% + ); + background-size: 200% 100%; + animation: shimmer 1.4s infinite linear; + border-radius: var(--radius-sm); + color: transparent; + user-select: none; +} + +@keyframes shimmer { + to { + background-position: -200% 0; + } +} + +@keyframes pulse-in { + from { + opacity: 0; + transform: translateY(-3px); + } + to { + opacity: 1; + transform: none; + } +} + +.pulse-in { + animation: pulse-in 0.22s ease; +} diff --git a/src/WebUI/src/app.d.ts b/src/WebUI/src/app.d.ts new file mode 100644 index 0000000..0dea0d9 --- /dev/null +++ b/src/WebUI/src/app.d.ts @@ -0,0 +1,13 @@ +// See https://svelte.dev/docs/kit/types#app.d.ts +// for information about these interfaces +declare global { + namespace App { + // interface Error {} + // interface Locals {} + // interface PageData {} + // interface PageState {} + // interface Platform {} + } +} + +export {}; diff --git a/src/WebUI/src/app.html b/src/WebUI/src/app.html new file mode 100644 index 0000000..0d4f5db --- /dev/null +++ b/src/WebUI/src/app.html @@ -0,0 +1,22 @@ + + + + + + + %sveltekit.head% + + +
%sveltekit.body%
+ + diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts new file mode 100644 index 0000000..6cc9341 --- /dev/null +++ b/src/WebUI/src/lib/api/client.ts @@ -0,0 +1,221 @@ +import type { + BootstrapTokenDto, + BrowserCredentialResponse, + CreateShellResponse, + DeviceDetailDto, + DeviceDto, + DeviceGroupDto, + FunctionModuleDto, + GroupFieldDescriptor, + GroupKind, + GroupRuleSet, + JobDto, + JobOutputRecordDto, + ScriptDto, + ScriptParameter, + ScriptTriggerDto, + ScriptTriggerType, + SessionResponse +} from './types'; + +interface SaveScriptBody { + name: string; + description?: string; + content: string; + parameters?: ScriptParameter[]; + functionModuleIds?: string[]; +} + +interface SaveGroupBody { + name: string; + description?: string; + kind: GroupKind; + rules?: GroupRuleSet; +} + +export class ApiError extends Error { + constructor( + public status: number, + message: string + ) { + super(message); + } +} + +function readCookie(name: string): string | undefined { + if (typeof document === 'undefined') return undefined; + return document.cookie + .split('; ') + .find((c) => c.startsWith(`${name}=`)) + ?.split('=')[1]; +} + +async function request(path: string, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const headers: Record = {}; + if (init?.body) { + headers['Content-Type'] = 'application/json'; + } + // Double-submit CSRF token for state-changing cookie-authenticated calls. + if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) { + const csrf = readCookie('csrf_token'); + if (csrf) headers['X-CSRF-Token'] = csrf; + } + + const response = await fetch(path, { + credentials: 'same-origin', + ...init, + headers: { ...headers, ...(init?.headers as Record) } + }); + + if (!response.ok) { + // Session expired: bounce to login (except while checking the session). + if ( + response.status === 401 && + typeof window !== 'undefined' && + !path.endsWith('/api/auth/session') && + !window.location.pathname.startsWith('/login') + ) { + window.location.href = '/login'; + } + + let detail = response.statusText; + try { + const body = await response.json(); + detail = body?.error ?? body?.title ?? detail; + } catch { + // Non-JSON error body. + } + throw new ApiError(response.status, detail); + } + + if (response.status === 204) { + return undefined as T; + } + + return (await response.json()) as T; +} + +export const api = { + // Auth + session: () => request('/api/auth/session'), + login: (username: string, password: string) => + request('/api/auth/login', { + method: 'POST', + body: JSON.stringify({ username, password }) + }), + logout: () => request('/api/auth/logout', { method: 'POST' }), + + // Devices + devices: () => request('/api/devices'), + device: (clientId: string) => request(`/api/devices/${clientId}`), + refreshInventory: (clientId: string) => + request(`/api/devices/${clientId}/inventory`, { method: 'POST' }), + openShell: ( + clientId: string, + body: { browserSessionId: string; cols: number; rows: number } + ) => + request(`/api/devices/${clientId}/shell`, { + method: 'POST', + body: JSON.stringify(body) + }), + sendFile: ( + clientId: string, + body: { objectKey: string; destinationPath: string; sha256?: string } + ) => + request(`/api/devices/${clientId}/files`, { + method: 'POST', + body: JSON.stringify(body) + }), + + // Scripts + scripts: () => request('/api/scripts'), + script: (id: string) => request(`/api/scripts/${id}`), + createScript: (body: SaveScriptBody) => + request('/api/scripts', { method: 'POST', body: JSON.stringify(body) }), + updateScript: (id: string, body: SaveScriptBody) => + request(`/api/scripts/${id}`, { method: 'PUT', body: JSON.stringify(body) }), + deleteScript: (id: string) => request(`/api/scripts/${id}`, { method: 'DELETE' }), + + // Function modules + functions: () => request('/api/functions'), + functionModule: (id: string) => request(`/api/functions/${id}`), + createFunction: (body: { name: string; description?: string; content: string }) => + request('/api/functions', { method: 'POST', body: JSON.stringify(body) }), + updateFunction: (id: string, body: { name: string; description?: string; content: string }) => + request(`/api/functions/${id}`, { method: 'PUT', body: JSON.stringify(body) }), + deleteFunction: (id: string) => request(`/api/functions/${id}`, { method: 'DELETE' }), + + // Jobs + jobs: (clientId?: string, limit?: number) => { + const params = new URLSearchParams(); + if (clientId) params.set('clientId', clientId); + if (limit) params.set('limit', String(limit)); + const qs = params.size > 0 ? `?${params}` : ''; + return request(`/api/jobs${qs}`); + }, + job: (jobId: string) => request(`/api/jobs/${jobId}`), + jobOutput: (jobId: string, afterSequence?: number) => + request( + `/api/jobs/${jobId}/output${afterSequence ? `?afterSequence=${afterSequence}` : ''}` + ), + createJob: (clientId: string, scriptId: string, args?: Record) => + request('/api/jobs', { + method: 'POST', + body: JSON.stringify({ clientId, scriptId, arguments: args }) + }), + + // Groups + groups: () => request('/api/groups'), + group: (id: string) => request(`/api/groups/${id}`), + createGroup: (body: SaveGroupBody) => + request('/api/groups', { method: 'POST', body: JSON.stringify(body) }), + updateGroup: (id: string, body: SaveGroupBody) => + request(`/api/groups/${id}`, { method: 'PUT', body: JSON.stringify(body) }), + deleteGroup: (id: string) => request(`/api/groups/${id}`, { method: 'DELETE' }), + groupMembers: (id: string) => request(`/api/groups/${id}/members`), + updateGroupMembers: (id: string, add: string[], remove: string[]) => + request(`/api/groups/${id}/members`, { + method: 'POST', + body: JSON.stringify({ add, remove }) + }), + previewGroup: (rules: GroupRuleSet) => + request('/api/groups/preview', { + method: 'POST', + body: JSON.stringify({ rules }) + }), + groupFields: () => request('/api/groups/fields'), + updateDeviceTags: (clientId: string, tags: string[]) => + request(`/api/devices/${clientId}/tags`, { + method: 'PUT', + body: JSON.stringify({ tags }) + }), + + // Script triggers + triggers: () => request('/api/triggers'), + createTrigger: (body: { + scriptId: string; + groupId?: string; + triggerType: ScriptTriggerType; + enabled?: boolean; + oncePerDevice?: boolean; + }) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }), + deleteTrigger: (id: string) => request(`/api/triggers/${id}`, { method: 'DELETE' }), + + // Messaging + messagingCredential: (nkeyPublic: string, browserSessionId?: string) => + request('/api/messaging/credential', { + method: 'POST', + body: JSON.stringify({ nkeyPublic, browserSessionId }) + }), + + // Admin + bootstrapTokens: () => request('/api/admin/bootstrap-tokens'), + createBootstrapToken: (body: { validMinutes?: number; maxUses?: number; note?: string }) => + request('/api/admin/bootstrap-tokens', { + method: 'POST', + body: JSON.stringify(body) + }), + revokeBootstrapToken: (id: string) => + request(`/api/admin/bootstrap-tokens/${id}`, { method: 'DELETE' }) +}; diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts new file mode 100644 index 0000000..e2b29d8 --- /dev/null +++ b/src/WebUI/src/lib/api/types.ts @@ -0,0 +1,329 @@ +// DTO mirror of Shared.Contracts (camelCase wire format). + +export type DeviceStatus = 'online' | 'stale' | 'offline'; + +export type JobState = + | 'queued' + | 'dispatched' + | 'running' + | 'succeeded' + | 'failed' + | 'cancelled' + | 'timedOut'; + +export type OutputStreamKind = + | 'output' + | 'error' + | 'warning' + | 'verbose' + | 'debug' + | 'information' + | 'progress'; + +export type UserRole = 'admin' | 'operator' | 'viewer'; + +export interface DeviceDto { + clientId: string; + hostname: string; + manufacturer?: string; + model?: string; + osCaption?: string; + osVersion?: string; + agentVersion?: string; + ipAddresses: string[]; + status: DeviceStatus; + lastSeenUtc?: string; + enrolledUtc: string; + tags?: string[]; +} + +// ── Device grouping ─────────────────────────────────────────────────── + +export type GroupKind = 'static' | 'dynamic'; +export type RuleCombine = 'and' | 'or'; +export type RuleOperator = + | 'equals' + | 'notEquals' + | 'contains' + | 'notContains' + | 'startsWith' + | 'endsWith' + | 'regex' + | 'in' + | 'notIn' + | 'greaterThan' + | 'greaterOrEqual' + | 'lessThan' + | 'lessOrEqual' + | 'exists' + | 'notExists'; + +export interface RuleCondition { + field: string; + operator: RuleOperator; + value?: string; + negate?: boolean; +} + +export interface RuleGroup { + combine: RuleCombine; + conditions?: RuleCondition[]; + groups?: RuleGroup[]; + negate?: boolean; +} + +export interface GroupRuleSet { + combine: RuleCombine; + groups?: RuleGroup[]; +} + +export interface GroupFieldDescriptor { + field: string; + displayName: string; + category: string; + numeric: boolean; + multiValue: boolean; +} + +export interface DeviceGroupDto { + id: string; + name: string; + description?: string; + kind: GroupKind; + rules?: GroupRuleSet; + memberCount: number; + createdUtc: string; + updatedUtc: string; + updatedBy?: string; +} + +export interface DeviceGroupRefDto { + id: string; + name: string; + kind: GroupKind; +} + +export type ScriptTriggerType = 'onRegistration' | 'onAgentReady'; + +export interface ScriptTriggerDto { + id: string; + scriptId: string; + scriptName: string; + groupId?: string; + groupName?: string; + triggerType: ScriptTriggerType; + enabled: boolean; + oncePerDevice: boolean; + createdUtc: string; +} + +export interface InventoryReport { + identity: { + clientId: string; + hostname: string; + manufacturer?: string; + model?: string; + serialNumber?: string; + biosVersion?: string; + baseboardSerial?: string; + domainOrWorkgroup?: string; + partOfDomain: boolean; + systemType?: string; + }; + os: { + caption?: string; + version?: string; + build?: string; + architecture?: string; + installDateUtc?: string; + lastBootUtc?: string; + edition?: string; + }; + cpu: { name?: string; logicalProcessors: number; cores: number }; + memory: { + deviceLocator?: string; + capacityBytes: number; + manufacturer?: string; + speedMhz?: number; + }[]; + totalPhysicalMemoryBytes: number; + disks: { model?: string; serialNumber?: string; sizeBytes: number; busType?: string }[]; + volumes: { + driveLetter: string; + fileSystem?: string; + totalSizeBytes: number; + freeSpaceBytes: number; + }[]; + network: { + description?: string; + macAddress?: string; + ipv4Addresses: string[]; + ipv6Addresses: string[]; + gateways: string[]; + dnsServers: string[]; + }[]; + collectedUtc: string; +} + +export interface DeviceDetailDto { + device: DeviceDto; + inventory?: InventoryReport; + inventoryUpdatedUtc?: string; + groups?: DeviceGroupRefDto[]; +} + +export type PrimitiveType = 'string' | 'number' | 'boolean'; +export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'hashtable'; + +export interface ScriptParameter { + name: string; + type: ScriptParameterType; + required?: boolean; + description?: string; + elementType?: PrimitiveType; + keyType?: PrimitiveType; + valueType?: PrimitiveType; + defaultValue?: unknown; +} + +export interface ScriptDto { + id: string; + name: string; + description?: string; + language: string; + content: string; + parameters: ScriptParameter[]; + functionModuleIds: string[]; + createdUtc: string; + updatedUtc: string; + createdBy?: string; + updatedBy?: string; +} + +export interface FunctionModuleDto { + id: string; + name: string; + description?: string; + content: string; + createdUtc: string; + updatedUtc: string; + updatedBy?: string; +} + +export interface JobDto { + jobId: string; + clientId: string; + hostname?: string; + scriptId: string; + scriptName: string; + state: JobState; + createdUtc: string; + startedUtc?: string; + completedUtc?: string; + exitCode?: number; + requestedBy?: string; + outputSummary?: string; +} + +export interface JobOutputRecordDto { + sequence: number; + stream: OutputStreamKind; + timestampUtc: string; + text: string; +} + +export interface SessionResponse { + authenticated: boolean; + username?: string; + displayName?: string; + role?: UserRole; + authProvider?: string; +} + +export interface BrowserCredentialResponse { + jwt: string; + expiresUtc: string; + browserSessionId: string; + webSocketPath: string; +} + +export interface BootstrapTokenDto { + id: string; + token?: string; + createdUtc: string; + expiresUtc: string; + maxUses: number; + uses: number; + revoked: boolean; + note?: string; + createdBy?: string; +} + +export interface CreateShellResponse { + shellSessionId: string; + clientId: string; + hostname: string; + expiresUtc: string; +} + +// ── Envelope + live payloads ────────────────────────────────────────── + +export interface MessageEnvelope { + messageId: string; + correlationId: string; + causationId?: string; + messageType: string; + schemaVersion: number; + timestampUtc: string; + source: { kind: string; id: string }; + target?: { kind: string; id: string }; + payload: T; +} + +export interface ActivityEventPayload { + kind: string; + text: string; + clientId?: string; + jobId?: string; + timestampUtc: string; +} + +export interface JobOutputPayload { + jobId: string; + clientId: string; + sequence: number; + stream: OutputStreamKind; + timestampUtc: string; + text: string; +} + +export interface JobProgressPayload { + jobId: string; + clientId: string; + activity: string; + statusDescription?: string; + percentComplete?: number; + secondsRemaining?: number; + timestampUtc: string; +} + +export interface JobStatePayload { + jobId: string; + clientId: string; + state: JobState; + exitCode?: number; + timestampUtc: string; + message?: string; +} + +export interface ShellOutputPayload { + sessionId: string; + sequence: number; + dataBase64: string; +} + +export interface ShellStatePayload { + sessionId: string; + state: 'requested' | 'open' | 'closed' | 'failed'; + message?: string; +} diff --git a/src/WebUI/src/lib/assets/favicon.svg b/src/WebUI/src/lib/assets/favicon.svg new file mode 100644 index 0000000..f6d91de --- /dev/null +++ b/src/WebUI/src/lib/assets/favicon.svg @@ -0,0 +1 @@ +svelte-logo \ No newline at end of file diff --git a/src/WebUI/src/lib/auth/session.ts b/src/WebUI/src/lib/auth/session.ts new file mode 100644 index 0000000..cc45244 --- /dev/null +++ b/src/WebUI/src/lib/auth/session.ts @@ -0,0 +1,54 @@ +import { writable } from 'svelte/store'; +import { goto } from '$app/navigation'; +import { api, ApiError } from '$lib/api/client'; +import type { SessionResponse } from '$lib/api/types'; +import { nats } from '$lib/messaging/nats'; + +export interface SessionState extends SessionResponse { + loaded: boolean; +} + +function createSessionStore() { + const { subscribe, set } = writable({ authenticated: false, loaded: false }); + + return { + subscribe, + + /** Loads the current session; redirects to /login when unauthenticated. */ + async initialize(): Promise { + try { + const current = await api.session(); + set({ ...current, loaded: true }); + if (!current.authenticated) { + await goto('/login'); + return false; + } + return true; + } catch (error) { + set({ authenticated: false, loaded: true }); + if (error instanceof ApiError && error.status === 401) { + await goto('/login'); + } + return false; + } + }, + + async login(username: string, password: string): Promise { + const result = await api.login(username, password); + set({ ...result, loaded: true }); + return result; + }, + + async logout(): Promise { + await nats.stop(); + try { + await api.logout(); + } finally { + set({ authenticated: false, loaded: true }); + await goto('/login'); + } + } + }; +} + +export const session = createSessionStore(); diff --git a/src/WebUI/src/lib/components/ConnectionIndicator.svelte b/src/WebUI/src/lib/components/ConnectionIndicator.svelte new file mode 100644 index 0000000..130335a --- /dev/null +++ b/src/WebUI/src/lib/components/ConnectionIndicator.svelte @@ -0,0 +1,56 @@ + + + + + {labels[$live]} + + + diff --git a/src/WebUI/src/lib/components/EmptyState.svelte b/src/WebUI/src/lib/components/EmptyState.svelte new file mode 100644 index 0000000..1068862 --- /dev/null +++ b/src/WebUI/src/lib/components/EmptyState.svelte @@ -0,0 +1,51 @@ + + +
+ +
{title}
+ {#if detail} +
{detail}
+ {/if} + {#if children} +
{@render children()}
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/components/JobStateBadge.svelte b/src/WebUI/src/lib/components/JobStateBadge.svelte new file mode 100644 index 0000000..56060c0 --- /dev/null +++ b/src/WebUI/src/lib/components/JobStateBadge.svelte @@ -0,0 +1,68 @@ + + +{entry.label} + + diff --git a/src/WebUI/src/lib/components/ParameterInputs.svelte b/src/WebUI/src/lib/components/ParameterInputs.svelte new file mode 100644 index 0000000..d9e1205 --- /dev/null +++ b/src/WebUI/src/lib/components/ParameterInputs.svelte @@ -0,0 +1,199 @@ + + +{#if parameters.length > 0} +
+ {#each parameters as p (p.name)} +
+ + {#if p.description}
{p.description}
{/if} + + {#if p.type === 'boolean'} + + {:else if p.type === 'number'} + + {:else if p.type === 'string'} + + {:else if p.type === 'array'} +
+ {#each arrays[p.name] ?? [] as _, i (i)} +
+ {#if p.elementType === 'boolean'} + + {:else} + + {/if} + +
+ {/each} + +
+ {:else if p.type === 'hashtable'} +
+ {#each hashes[p.name] ?? [] as _, i (i)} +
+ + {#if p.valueType === 'boolean'} + + {:else} + + {/if} + +
+ {/each} + +
+ {/if} +
+ {/each} +
+{/if} + + diff --git a/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte b/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte new file mode 100644 index 0000000..4a40199 --- /dev/null +++ b/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte @@ -0,0 +1,107 @@ + + +
+
+

Parameters

+ +
+ + {#if parameters.length === 0} +

No parameters. Add one to prompt for a typed value at run time.

+ {:else} +
+ {#each parameters as param, i (i)} +
+ + + + {#if param.type === 'array'} + + {:else if param.type === 'hashtable'} + + + {/if} + + + +
+ {/each} +
+ {/if} +
+ + diff --git a/src/WebUI/src/lib/components/RelativeTime.svelte b/src/WebUI/src/lib/components/RelativeTime.svelte new file mode 100644 index 0000000..70b243b --- /dev/null +++ b/src/WebUI/src/lib/components/RelativeTime.svelte @@ -0,0 +1,27 @@ + + +{text} diff --git a/src/WebUI/src/lib/components/RuleBuilder.svelte b/src/WebUI/src/lib/components/RuleBuilder.svelte new file mode 100644 index 0000000..f67e509 --- /dev/null +++ b/src/WebUI/src/lib/components/RuleBuilder.svelte @@ -0,0 +1,227 @@ + + +
+
+ Match + +
+ +
+ + {#if (rules.groups ?? []).length === 0} +

+ No condition groups yet. A dynamic group with no rules matches no devices. +

+ {:else} + {#each rules.groups ?? [] as group, gi (gi)} +
+
+ Group {gi + 1} + + +
+ + +
+ + {#each group.conditions ?? [] as condition, ci (ci)} +
+ + + + + {#if needsValue(condition.operator)} + + {:else} + + {/if} + + + +
+ {/each} + + {#if (group.conditions ?? []).length === 0} +

No conditions — this group matches nothing.

+ {/if} +
+ {/each} + {/if} +
+ + diff --git a/src/WebUI/src/lib/components/StatusBadge.svelte b/src/WebUI/src/lib/components/StatusBadge.svelte new file mode 100644 index 0000000..7c18a5e --- /dev/null +++ b/src/WebUI/src/lib/components/StatusBadge.svelte @@ -0,0 +1,64 @@ + + + + + {labels[status]} + + + diff --git a/src/WebUI/src/lib/index.ts b/src/WebUI/src/lib/index.ts new file mode 100644 index 0000000..8ca99b4 --- /dev/null +++ b/src/WebUI/src/lib/index.ts @@ -0,0 +1 @@ +// place files you want to import through the `$lib` alias in this folder. diff --git a/src/WebUI/src/lib/messaging/nats.ts b/src/WebUI/src/lib/messaging/nats.ts new file mode 100644 index 0000000..8d4e68f --- /dev/null +++ b/src/WebUI/src/lib/messaging/nats.ts @@ -0,0 +1,209 @@ +// Browser-side NATS-over-WebSocket connection. +// +// The NKey pair is generated in browser memory (the seed never leaves this +// tab). The backend issues a short-lived JWT restricted to this session's +// browser..> subjects; we refresh it before expiry while the +// backend auth session remains valid. + +import { writable, type Readable } from 'svelte/store'; +import { wsconnect, jwtAuthenticator, type NatsConnection, type Subscription } from '@nats-io/nats-core'; +import { createUser, type KeyPair } from '@nats-io/nkeys'; +import { api } from '$lib/api/client'; +import type { + ActivityEventPayload, + JobOutputPayload, + JobProgressPayload, + JobStatePayload, + MessageEnvelope, + ShellOutputPayload, + ShellStatePayload +} from '$lib/api/types'; + +export type LiveState = 'disconnected' | 'connecting' | 'connected'; + +export type JobEvent = + | { type: 'job.output'; payload: JobOutputPayload } + | { type: 'job.progress'; payload: JobProgressPayload } + | { type: 'job.state'; payload: JobStatePayload }; + +export type ShellEvent = + | { type: 'shell.output'; payload: ShellOutputPayload } + | { type: 'shell.state'; payload: ShellStatePayload }; + +type ActivityHandler = (event: ActivityEventPayload) => void; +type JobHandler = (jobId: string, event: JobEvent) => void; +type ShellHandler = (shellId: string, event: ShellEvent) => void; + +const liveState = writable('disconnected'); +export const live: Readable = liveState; + +class NatsService { + private connection: NatsConnection | null = null; + private keyPair: KeyPair | null = null; + private jwt = ''; + private sessionId = ''; + private refreshTimer: ReturnType | null = null; + private subscription: Subscription | null = null; + private starting: Promise | null = null; + + private activityHandlers = new Set(); + private jobHandlers = new Set(); + private shellHandlers = new Set(); + + get browserSessionId(): string { + return this.sessionId; + } + + onActivity(handler: ActivityHandler): () => void { + this.activityHandlers.add(handler); + return () => this.activityHandlers.delete(handler); + } + + onJobEvent(handler: JobHandler): () => void { + this.jobHandlers.add(handler); + return () => this.jobHandlers.delete(handler); + } + + onShellEvent(handler: ShellHandler): () => void { + this.shellHandlers.add(handler); + return () => this.shellHandlers.delete(handler); + } + + /** Publishes raw bytes to a subject inside this session's namespace. */ + publish(subject: string, data: Uint8Array): void { + this.connection?.publish(subject, data); + } + + shellInputSubject(shellId: string): string { + return `browser.${this.sessionId}.shell.${shellId}.input`; + } + + async start(): Promise { + this.starting ??= this.startCore().catch((error) => { + this.starting = null; + liveState.set('disconnected'); + throw error; + }); + return this.starting; + } + + private async startCore(): Promise { + liveState.set('connecting'); + + this.keyPair ??= createUser(); + const credential = await api.messagingCredential( + this.keyPair.getPublicKey(), + this.sessionId || undefined + ); + this.jwt = credential.jwt; + this.sessionId = credential.browserSessionId; + this.scheduleRefresh(credential.expiresUtc); + + const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; + const url = `${scheme}://${location.host}${credential.webSocketPath}`; + + this.connection = await wsconnect({ + servers: [url], + name: `browser-${this.sessionId}`, + authenticator: jwtAuthenticator(() => this.jwt, this.keyPair.getSeed()), + maxReconnectAttempts: -1, + waitOnFirstConnect: true + }); + + liveState.set('connected'); + this.monitorStatus(); + this.subscribeSession(); + } + + private monitorStatus(): void { + if (!this.connection) return; + void (async () => { + for await (const status of this.connection!.status()) { + if (status.type === 'disconnect') { + liveState.set('connecting'); + } else if (status.type === 'reconnect') { + liveState.set('connected'); + } + } + })(); + } + + private subscribeSession(): void { + if (!this.connection) return; + this.subscription?.unsubscribe(); + this.subscription = this.connection.subscribe(`browser.${this.sessionId}.>`); + + void (async () => { + for await (const message of this.subscription!) { + try { + this.dispatch(message.subject, message.json()); + } catch { + // Ignore malformed payloads. + } + } + })(); + } + + private dispatch(subject: string, envelope: MessageEnvelope): void { + // browser..event | browser..job. | browser..shell. + const parts = subject.split('.'); + const kind = parts[2]; + + if (kind === 'event') { + const payload = envelope.payload as ActivityEventPayload; + for (const handler of this.activityHandlers) handler(payload); + return; + } + + if (kind === 'job' && parts.length >= 4) { + const jobId = parts[3]; + const event = { type: envelope.messageType, payload: envelope.payload } as JobEvent; + for (const handler of this.jobHandlers) handler(jobId, event); + return; + } + + if (kind === 'shell' && parts.length >= 4) { + const shellId = parts[3]; + const event = { type: envelope.messageType, payload: envelope.payload } as ShellEvent; + for (const handler of this.shellHandlers) handler(shellId, event); + } + } + + private scheduleRefresh(expiresUtc: string): void { + if (this.refreshTimer) clearTimeout(this.refreshTimer); + const msUntilRefresh = Math.max(new Date(expiresUtc).getTime() - Date.now() - 60_000, 15_000); + this.refreshTimer = setTimeout(() => void this.refreshCredential(), msUntilRefresh); + } + + private async refreshCredential(): Promise { + try { + if (!this.keyPair) return; + const credential = await api.messagingCredential(this.keyPair.getPublicKey(), this.sessionId); + this.jwt = credential.jwt; + if (credential.browserSessionId !== this.sessionId) { + // Session expired server-side; rebind subscriptions to the new one. + this.sessionId = credential.browserSessionId; + this.subscribeSession(); + } + this.scheduleRefresh(credential.expiresUtc); + } catch { + // Auth session likely gone; retry shortly (page will redirect on 401). + this.refreshTimer = setTimeout(() => void this.refreshCredential(), 30_000); + } + } + + async stop(): Promise { + if (this.refreshTimer) clearTimeout(this.refreshTimer); + this.refreshTimer = null; + this.subscription?.unsubscribe(); + this.subscription = null; + this.starting = null; + if (this.connection) { + await this.connection.close().catch(() => undefined); + this.connection = null; + } + liveState.set('disconnected'); + } +} + +export const nats = new NatsService(); diff --git a/src/WebUI/src/lib/theme/theme.ts b/src/WebUI/src/lib/theme/theme.ts new file mode 100644 index 0000000..edfbc04 --- /dev/null +++ b/src/WebUI/src/lib/theme/theme.ts @@ -0,0 +1,25 @@ +import { writable } from 'svelte/store'; +import { browser } from '$app/environment'; + +export type ThemePreference = 'system' | 'light' | 'dark'; + +function initial(): ThemePreference { + if (!browser) return 'system'; + const stored = localStorage.getItem('theme'); + return stored === 'light' || stored === 'dark' ? stored : 'system'; +} + +export const theme = writable(initial()); + +export function setTheme(preference: ThemePreference): void { + theme.set(preference); + if (!browser) return; + + if (preference === 'system') { + localStorage.removeItem('theme'); + document.documentElement.removeAttribute('data-theme'); + } else { + localStorage.setItem('theme', preference); + document.documentElement.setAttribute('data-theme', preference); + } +} diff --git a/src/WebUI/src/routes/+layout.svelte b/src/WebUI/src/routes/+layout.svelte new file mode 100644 index 0000000..c20d8e2 --- /dev/null +++ b/src/WebUI/src/routes/+layout.svelte @@ -0,0 +1,257 @@ + + + + + ExecuteR Control + + +{#if isLoginPage} + {@render children()} +{:else} +
+ + +
+
+

ExecuteR Control

+
+ + + {#if $session.authenticated} + {$session.displayName ?? $session.username} + + {/if} +
+
+
+ {@render children()} +
+
+
+{/if} + + diff --git a/src/WebUI/src/routes/+page.svelte b/src/WebUI/src/routes/+page.svelte new file mode 100644 index 0000000..e08b244 --- /dev/null +++ b/src/WebUI/src/routes/+page.svelte @@ -0,0 +1,270 @@ + + +
+
+ {#if devices === null} + {#each Array(6) as _, i (i)} +
loading…
+ {/each} + {:else} +
+
{counts.total}
+
Devices
+
+
+
{counts.online}
+
Online
+
+
+
{counts.stale}
+
Stale
+
+
+
{counts.offline}
+
Offline
+
+
+
{jobCounts.running}
+
Running jobs
+
+
+
{jobCounts.failed}
+
Failed jobs
+
+ {/if} +
+ +
+
+

Live activity

+
+ {#if activity.length === 0} + + {:else} +
    + {#each activity as event, i (event.timestampUtc + event.text + i)} +
  • + + {event.text} + {new Date(event.timestampUtc).toLocaleTimeString()} +
  • + {/each} +
+ {/if} +
+ +
+
+

Latest enrollments

+
+ {#if latestEnrollments.length === 0} + + {:else} +
    + {#each latestEnrollments as device (device.clientId)} +
  • + {device.hostname} + {new Date(device.enrolledUtc).toLocaleString()} +
  • + {/each} +
+ {/if} +
+
+ + diff --git a/src/WebUI/src/routes/devices/+page.svelte b/src/WebUI/src/routes/devices/+page.svelte new file mode 100644 index 0000000..0e52e3f --- /dev/null +++ b/src/WebUI/src/routes/devices/+page.svelte @@ -0,0 +1,180 @@ + + +
+

Devices

+
+ + +
+
+ +
+ {#if devices === null} +
+ {#each Array(4) as _, i (i)} +
loading device row…
+ {/each} +
+ {:else if filtered.length === 0} + + {:else} + + + + + + + + + + + + + + {#each filtered as device (device.clientId)} + goto(`/devices/${device.clientId}`)} + onkeydown={(e) => e.key === 'Enter' && goto(`/devices/${device.clientId}`)} + tabindex="0" + > + + + + + + + + + {/each} + +
StatusManufacturer / ModelAgentIP
{device.hostname} + {[device.manufacturer, device.model].filter(Boolean).join(' · ') || '—'} + {device.osCaption ?? '—'}{device.agentVersion ?? '—'}{device.ipAddresses[0] ?? '—'}
+ {/if} +
+ + diff --git a/src/WebUI/src/routes/devices/[clientId]/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/+page.svelte new file mode 100644 index 0000000..14a93be --- /dev/null +++ b/src/WebUI/src/routes/devices/[clientId]/+page.svelte @@ -0,0 +1,602 @@ + + +{#if error} + + Back to devices + +{:else if !device} +
loading device…
+{:else} +
+
+
Devices / {clientId.slice(0, 12)}…
+
+

{device.hostname}

+ +
+
+ {[device.manufacturer, device.model].filter(Boolean).join(' · ')} +
+
+
+ + +
+
+ + + + {#if tab === 'overview'} +
+
+

Identity

+
+
Client ID
+
{clientId}
+
Hostname
+
{device.hostname}
+
Serial number
+
{inventory?.identity.serialNumber ?? '—'}
+
Domain / workgroup
+
{inventory?.identity.domainOrWorkgroup ?? '—'}
+
System type
+
{inventory?.identity.systemType ?? '—'}
+
+
+
+

Operating system

+
+
OS
+
{inventory?.os.caption ?? device.osCaption ?? '—'}
+
Version / build
+
{inventory?.os.version ?? '—'} (build {inventory?.os.build ?? '—'})
+
Architecture
+
{inventory?.os.architecture ?? '—'}
+
Installed
+
{inventory?.os.installDateUtc ? new Date(inventory.os.installDateUtc).toLocaleDateString() : '—'}
+
Last boot
+
{inventory?.os.lastBootUtc ? new Date(inventory.os.lastBootUtc).toLocaleString() : '—'}
+
+
+
+

Agent

+
+
Version
+
{device.agentVersion ?? '—'}
+
Enrolled
+
{new Date(device.enrolledUtc).toLocaleString()}
+
+
+
+

Tags & groups

+
+ {#each device.tags ?? [] as tag (tag)} + + {tag} + + + {/each} + {#if (device.tags ?? []).length === 0} + No tags + {/if} +
+
+ e.key === 'Enter' && addTag()} + /> + +
+
+ {#each detail?.groups ?? [] as g (g.id)} + {g.name} · {g.kind} + {/each} + {#if (detail?.groups ?? []).length === 0} + Not in any group + {/if} +
+
+ +
+

Connectivity

+
+
Last seen
+
+
IP addresses
+
{device.ipAddresses.join(', ') || '—'}
+
Inventory updated
+
+
+
+
+ {:else if tab === 'hardware'} + {#if !inventory} + + {:else} +
+
+

Processor

+
+
Name
+
{inventory.cpu.name ?? '—'}
+
Cores / logical
+
{inventory.cpu.cores} cores, {inventory.cpu.logicalProcessors} logical
+
+
+
+

Memory

+
+
Total
+
{formatBytes(inventory.totalPhysicalMemoryBytes)}
+
+ {#each inventory.memory as dimm, i (i)} +
+ {dimm.deviceLocator ?? `DIMM ${i + 1}`}: {formatBytes(dimm.capacityBytes)} + {dimm.speedMhz ? ` @ ${dimm.speedMhz} MHz` : ''} + {dimm.manufacturer ? ` (${dimm.manufacturer})` : ''} +
+ {/each} +
+
+

Firmware

+
+
BIOS version
+
{inventory.identity.biosVersion ?? '—'}
+
Baseboard serial
+
{inventory.identity.baseboardSerial ?? '—'}
+
+
+
+

Storage

+
+ + + + + + {#each inventory.disks as disk, i (i)} + + + + + + + {/each} + +
DiskSerialBusSize
{disk.model ?? '—'}{disk.serialNumber ?? '—'}{disk.busType ?? '—'}{formatBytes(disk.sizeBytes)}
+
+
+ + + + + + {#each inventory.volumes as vol (vol.driveLetter)} + + + + + + + {/each} + +
VolumeFile systemSizeFree
{vol.driveLetter}{vol.fileSystem ?? '—'}{formatBytes(vol.totalSizeBytes)}{formatBytes(vol.freeSpaceBytes)}
+
+
+
+ {/if} + {:else if tab === 'network'} + {#if !inventory || inventory.network.length === 0} + + {:else} +
+ {#each inventory.network as adapter, i (i)} +
+

{adapter.description ?? `Adapter ${i + 1}`}

+
+
MAC
+
{adapter.macAddress ?? '—'}
+
IPv4
+
{adapter.ipv4Addresses.join(', ') || '—'}
+
IPv6
+
{adapter.ipv6Addresses.join(', ') || '—'}
+
Gateways
+
{adapter.gateways.join(', ') || '—'}
+
DNS
+
{adapter.dnsServers.join(', ') || '—'}
+
+
+ {/each} +
+ {/if} + {:else if tab === 'jobs'} +
+ {#if jobs.length === 0} + + {:else} + + + + + + {#each jobs as job (job.jobId)} + goto(`/jobs?job=${job.jobId}`)}> + + + + + + + {/each} + +
StateScriptCreatedDurationExit
{job.scriptName} + {job.startedUtc && job.completedUtc + ? `${Math.round((new Date(job.completedUtc).getTime() - new Date(job.startedUtc).getTime()) / 1000)}s` + : '—'} + {job.exitCode ?? '—'}
+ {/if} +
+ {:else if tab === 'actions'} +
+
+

Actions

+
+ + ▶ Run script + +
+ {#if actionMessage} +

{actionMessage}

+ {/if} + {#if !online} +

Actions are disabled while the agent is offline.

+ {/if} +
+ +
+

Send file (S3)

+

+ Delivers an object from the configured S3 store to the device using a short-lived + presigned URL. +

+
+ + + + +
+
+
+ {/if} +{/if} + + diff --git a/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte new file mode 100644 index 0000000..7617c3c --- /dev/null +++ b/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte @@ -0,0 +1,219 @@ + + + + Shell · {hostname || clientId} · ExecuteR + + +
+
+ +
+

Remote shell

+ + {statusText} + +
+
+ +
+ +
+ + diff --git a/src/WebUI/src/routes/functions/+page.svelte b/src/WebUI/src/routes/functions/+page.svelte new file mode 100644 index 0000000..20a880a --- /dev/null +++ b/src/WebUI/src/routes/functions/+page.svelte @@ -0,0 +1,221 @@ + + +
+

Function modules

+ +
+ +

+ Reusable PowerShell functions. Attach a module to a script and its definitions are prepended at + run time — keeping individual scripts small and free of duplication. +

+ +
+
+ {#if modules === null} +
+ {#each Array(3) as _, i (i)}
loading…
{/each} +
+ {:else if modules.length === 0} + + {:else} +
    + {#each modules as m (m.id)} +
  • + +
  • + {/each} +
+ {/if} +
+ +
+
+ + {#if statusText}{statusText}{/if} +
+ {#if selected}{/if} + +
+ + +
+
+ + diff --git a/src/WebUI/src/routes/groups/+page.svelte b/src/WebUI/src/routes/groups/+page.svelte new file mode 100644 index 0000000..669b2b6 --- /dev/null +++ b/src/WebUI/src/routes/groups/+page.svelte @@ -0,0 +1,495 @@ + + +
+

Device groups

+ +
+ +
+
+ {#if groups === null} +
+ {#each Array(3) as _, i (i)}
loading…
{/each} +
+ {:else if groups.length === 0} + + {:else} +
    + {#each groups as g (g.id)} +
  • + +
  • + {/each} +
+ {/if} +
+ +
+
+
+ + +
+ {#if statusText}{statusText}{/if} + {#if selected}{/if} + +
+ +
+ + {#if kind === 'dynamic'} +
+
+

Membership rules

+ +
+ + + {#if preview !== null} +
+

Preview — {preview.length} device(s)

+ {#if preview.length > 0} +
    + {#each preview as d (d.clientId)} +
  • {d.hostname}
  • + {/each} +
+ {:else} +

No devices match these rules.

+ {/if} +
+ {/if} +
+ {:else} +
+

Members

+

Tick devices to include them in this static group.

+ {#if !selected} +

Save the group first, then choose members.

+ {:else} +
    + {#each devices as d (d.clientId)} +
  • + +
  • + {/each} +
+ {/if} +
+ {/if} + +
+

Script triggers

+

+ Run a script automatically when a device registers, or when its agent connects and is ready + for jobs. +

+ +
+ + + + + +
+ + {#if triggers.length > 0} +
+ + + + + + {#each triggers as t (t.id)} + + + + + + + + {/each} + +
ScriptWhenTargetOnce
{t.scriptName}{triggerLabels[t.triggerType]}{t.groupName}{t.oncePerDevice ? 'yes' : 'no'}
+
+ {/if} +
+
+
+ + diff --git a/src/WebUI/src/routes/jobs/+page.svelte b/src/WebUI/src/routes/jobs/+page.svelte new file mode 100644 index 0000000..75b1356 --- /dev/null +++ b/src/WebUI/src/routes/jobs/+page.svelte @@ -0,0 +1,243 @@ + + +
+

Jobs

+
+ +
+
+ {#if jobs === null} +
+ {#each Array(4) as _, i (i)} +
loading…
+ {/each} +
+ {:else if jobs.length === 0} + + {:else} + + + + + + + + + + + + {#each jobs as job (job.jobId)} + select(job)} + onkeydown={(e) => e.key === 'Enter' && select(job)} + tabindex="0" + > + + + + + + + {/each} + +
StateScriptDeviceCreatedDuration
{job.scriptName}{job.hostname ?? job.clientId.slice(0, 10)}{duration(job)}
+ {/if} +
+ + +
+ + diff --git a/src/WebUI/src/routes/login/+page.svelte b/src/WebUI/src/routes/login/+page.svelte new file mode 100644 index 0000000..4ffc952 --- /dev/null +++ b/src/WebUI/src/routes/login/+page.svelte @@ -0,0 +1,127 @@ + + + + Sign in · ExecuteR + + +
+
+
+ X + ExecuteR +
+

Sign in

+ + + + + {#if error} + + {/if} + + + + Sign in with single sign-on +
+
+ + diff --git a/src/WebUI/src/routes/scripts/+page.svelte b/src/WebUI/src/routes/scripts/+page.svelte new file mode 100644 index 0000000..b111d13 --- /dev/null +++ b/src/WebUI/src/routes/scripts/+page.svelte @@ -0,0 +1,85 @@ + + +
+

Scripts

+ + New script +
+ +
+ {#if scripts === null} +
+ {#each Array(3) as _, i (i)} +
loading…
+ {/each} +
+ {:else if scripts.length === 0} + + Create script + + {:else} + + + + + + + + + + + + {#each scripts as script (script.id)} + goto(`/scripts/${script.id}`)} + onkeydown={(e) => e.key === 'Enter' && goto(`/scripts/${script.id}`)} + tabindex="0" + > + + + + + + + {/each} + +
NameDescriptionLanguageUpdatedBy
{script.name}{script.description ?? '—'}{script.language}{script.updatedBy ?? '—'}
+ {/if} +
+ + diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte new file mode 100644 index 0000000..1cb418f --- /dev/null +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -0,0 +1,512 @@ + + +
+
+
Scripts / {isNew ? 'New' : name || '…'}
+ + +
+
+ {#if statusText} + {statusText} + {/if} + {#if !isNew} + + {/if} + + +
+
+ +
+
+ {#if !loaded} +
loading editor…
+ {/if} +
+
+ + +
+ + diff --git a/src/WebUI/src/routes/settings/+page.svelte b/src/WebUI/src/routes/settings/+page.svelte new file mode 100644 index 0000000..4c0e9c9 --- /dev/null +++ b/src/WebUI/src/routes/settings/+page.svelte @@ -0,0 +1,259 @@ + + +
+

Settings

+
+ +
+
+

Appearance

+
+ {#each themes as option (option.value)} + + {/each} +
+
+ +
+

Bootstrap tokens

+

+ One-time tokens for agent enrollment. The token value is shown once at creation — install with + msiexec /i Agent.msi /qn SERVERURL=… BOOTSTRAPTOKEN=… +

+ +
+ + + + +
+ + {#if newToken?.token} +
+
New token (copy it now — it will not be shown again):
+
{newToken.token}
+ +
+
+
Deploy on a target device (run in an elevated PowerShell):
+
{installCommand}
+ +
+ Requires Agent.msi in the backend’s AGENT_PACKAGE_PATH. Also usable: + msiexec /i Agent.msi /qn SERVERURL=… BOOTSTRAPTOKEN=… +
+
+ {/if} + + {#if tokens.length === 0} + + {:else} +
+ + + + + + + + + + + + + {#each tokens as token (token.id)} + + + + + + + + + {/each} + +
CreatedExpiresUsesNoteStatus
{new Date(token.createdUtc).toLocaleString()}{new Date(token.expiresUtc).toLocaleString()}{token.uses} / {token.maxUses}{token.note ?? '—'} + {#if token.revoked} + Revoked + {:else if new Date(token.expiresUtc) < new Date()} + Expired + {:else if token.uses >= token.maxUses} + Consumed + {:else} + Active + {/if} + + {#if !token.revoked && token.uses < token.maxUses && new Date(token.expiresUtc) > new Date()} + + {/if} +
+
+ {/if} +
+
+ + diff --git a/src/WebUI/static/robots.txt b/src/WebUI/static/robots.txt new file mode 100644 index 0000000..4d94012 --- /dev/null +++ b/src/WebUI/static/robots.txt @@ -0,0 +1,3 @@ +# allow crawling everything by default +User-agent: * +Disallow: diff --git a/src/WebUI/tsconfig.json b/src/WebUI/tsconfig.json new file mode 100644 index 0000000..7225a94 --- /dev/null +++ b/src/WebUI/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "rewriteRelativeImportExtensions": true, + "allowJs": true, + "checkJs": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "moduleResolution": "bundler" + } + // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias + // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files + // + // To make changes to top-level options such as include and exclude, we recommend extending + // the generated config; see https://svelte.dev/docs/kit/configuration#typescript +} diff --git a/src/WebUI/vite.config.ts b/src/WebUI/vite.config.ts new file mode 100644 index 0000000..22ee48a --- /dev/null +++ b/src/WebUI/vite.config.ts @@ -0,0 +1,31 @@ +import adapter from '@sveltejs/adapter-node'; +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [ + sveltekit({ + compilerOptions: { + // Force runes mode for the project, except for libraries. Can be removed in svelte 6. + runes: ({ filename }) => + filename.split(/[/\\]/).includes('node_modules') ? undefined : true + }, + + adapter: adapter() + }) + ], + server: { + // Local development against `docker compose -f docker-compose.yml -f docker-compose.dev.yml up` + // (or a locally running backend + NATS). Production is same-origin via the reverse proxy. + proxy: { + '/api': { + target: process.env.DEV_BACKEND_URL ?? 'http://localhost:19080', + changeOrigin: false + }, + '/messaging': { + target: process.env.DEV_NATS_WS_URL ?? 'ws://localhost:19222', + ws: true + } + } + } +}); diff --git a/tests/Agent.Tests/Agent.Tests.csproj b/tests/Agent.Tests/Agent.Tests.csproj new file mode 100644 index 0000000..f704f0d --- /dev/null +++ b/tests/Agent.Tests/Agent.Tests.csproj @@ -0,0 +1,22 @@ + + + + net10.0-windows + Exe + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/tests/Agent.Tests/AgentConfigurationTests.cs b/tests/Agent.Tests/AgentConfigurationTests.cs new file mode 100644 index 0000000..9bb8d34 --- /dev/null +++ b/tests/Agent.Tests/AgentConfigurationTests.cs @@ -0,0 +1,151 @@ +using Agent.Configuration; +using Agent.Storage; +using Shared.Infrastructure.Configuration; +using Shared.Infrastructure.Constants; +using Xunit; + +namespace Agent.Tests; + +public class AgentConfigurationTests +{ + private readonly InMemoryRegistryStore registry = new(); + + [Fact] + public void GroupPolicyOverridesNormalRegistry() + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://normal.example.com"); + registry.SetString(Branding.AgentPolicyRegistryKey, AgentConfigurationKeys.ServerUrl, "https://policy.example.com"); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.Equal("https://policy.example.com", config.ServerUrlText.Value); + Assert.Equal(ConfigurationSource.GroupPolicy, config.ServerUrlText.Source); + Assert.True(config.ServerUrlText.IsPolicyControlled); + } + + [Fact] + public void NormalRegistryUsedWhenNoPolicy() + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://normal.example.com"); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.Equal("https://normal.example.com", config.ServerUrlText.Value); + Assert.Equal(ConfigurationSource.Registry, config.ServerUrlText.Source); + } + + [Fact] + public void EnvironmentNeverOverridesGroupPolicyOrRegistry() + { + Environment.SetEnvironmentVariable(AgentConfigurationKeys.EnvironmentNames.ServerUrl, "https://env.example.com"); + try + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://normal.example.com"); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: true).Load(); + Assert.Equal("https://normal.example.com", config.ServerUrlText.Value); + } + finally + { + Environment.SetEnvironmentVariable(AgentConfigurationKeys.EnvironmentNames.ServerUrl, null); + } + } + + [Fact] + public void EnvironmentAppliesOnlyInDevelopmentMode() + { + Environment.SetEnvironmentVariable(AgentConfigurationKeys.EnvironmentNames.ServerUrl, "https://env.example.com"); + try + { + var dev = new AgentConfigurationLoader(registry, allowEnvironment: true).Load(); + Assert.Equal("https://env.example.com", dev.ServerUrlText.Value); + Assert.Equal(ConfigurationSource.EnvironmentDevelopmentOnly, dev.ServerUrlText.Source); + + var service = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + Assert.Null(service.ServerUrlText.Value); + Assert.Equal(ConfigurationSource.Default, service.ServerUrlText.Source); + } + finally + { + Environment.SetEnvironmentVariable(AgentConfigurationKeys.EnvironmentNames.ServerUrl, null); + } + } + + [Fact] + public void DefaultsApplyWhenNothingConfigured() + { + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.Equal(ProtocolDefaults.DefaultInventoryInterval, config.InventoryInterval.Value); + Assert.Equal(ProtocolDefaults.ReconnectMinDelay, config.ReconnectMinDelay.Value); + Assert.Equal(ProtocolDefaults.ReconnectMaxDelay, config.ReconnectMaxDelay.Value); + Assert.False(config.AllowRemoteShell.Value); + Assert.True(config.AllowScriptExecution.Value); + Assert.Equal("Information", config.LogLevel.Value); + } + + [Fact] + public void IntervalAcceptsSecondsAndTimeSpanFormats() + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.InventoryInterval, "300"); + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ReconnectMinDelay, "00:00:05"); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.Equal(TimeSpan.FromMinutes(5), config.InventoryInterval.Value); + Assert.Equal(TimeSpan.FromSeconds(5), config.ReconnectMinDelay.Value); + } + + [Fact] + public void PolicyDwordControlsRemoteShell() + { + registry.SetDword(Branding.AgentRegistryKey, AgentConfigurationKeys.AllowRemoteShell, 1); + registry.SetDword(Branding.AgentPolicyRegistryKey, AgentConfigurationKeys.AllowRemoteShell, 0); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.False(config.AllowRemoteShell.Value); + Assert.True(config.AllowRemoteShell.IsPolicyControlled); + } + + [Fact] + public void InvalidServerUrlYieldsNullParsedUrl() + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "ftp://bad.example.com"); + + var config = new AgentConfigurationLoader(registry, allowEnvironment: false).Load(); + + Assert.NotNull(config.ServerUrlText.Value); + Assert.Null(config.ServerUrl); + } + + [Fact] + public void ClearBootstrapTokenRemovesOnlyThatValue() + { + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken, "secret-token"); + registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://control.example.com"); + + var store = new RuntimeStateStore(registry); + store.ClearBootstrapToken(); + + Assert.False(registry.Contains(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken)); + Assert.True(registry.Contains(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl)); + } + + [Fact] + public void RuntimeStateRoundTrips() + { + var store = new RuntimeStateStore(registry); + var now = DateTimeOffset.UtcNow; + + store.ClientId = "abc123"; + store.LastEnrollmentUtc = now; + + Assert.Equal("abc123", store.ClientId); + Assert.Equal(now, store.LastEnrollmentUtc); + + store.Purge(); + Assert.Null(store.ClientId); + Assert.Null(store.LastEnrollmentUtc); + } +} diff --git a/tests/Agent.Tests/ClientIdentityTests.cs b/tests/Agent.Tests/ClientIdentityTests.cs new file mode 100644 index 0000000..51d2ca3 --- /dev/null +++ b/tests/Agent.Tests/ClientIdentityTests.cs @@ -0,0 +1,93 @@ +using Agent.Identity; +using Xunit; + +namespace Agent.Tests; + +public class ClientIdentityTests +{ + private static readonly HardwareIdentity FullIdentity = new( + SystemProductUuid: "4c4c4544-0032-3510-8051-b4c04f4a3532", + BiosSerialNumber: "ABC1234", + BaseboardSerialNumber: "/ABC1234/CNWS123456789/", + IdentifyingNumber: "ABC1234", + Manufacturer: "Dell Inc.", + Model: "OptiPlex 7090"); + + [Theory] + [InlineData(null, null)] + [InlineData("", null)] + [InlineData(" ", null)] + [InlineData("To Be Filled By O.E.M.", null)] + [InlineData("Default string", null)] + [InlineData("00000000-0000-0000-0000-000000000000", null)] + [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", null)] + [InlineData("0000000", null)] + [InlineData("None", null)] + [InlineData(" abc123 ", "ABC123")] + [InlineData("serial-1", "SERIAL-1")] + public void NormalizationRejectsPlaceholdersAndUppercases(string? input, string? expected) + { + Assert.Equal(expected, ClientIdentityFactory.Normalize(input)); + } + + [Fact] + public void CanonicalIdentityIsLabeledAndOrdered() + { + var canonical = ClientIdentityFactory.BuildCanonicalIdentity(FullIdentity); + + Assert.StartsWith("UUID=4C4C4544-0032-3510-8051-B4C04F4A3532|BIOS=ABC1234|", canonical); + Assert.Contains("|MFR=DELL INC.|MODEL=OPTIPLEX 7090", canonical); + } + + [Fact] + public void ClientIdIsDeterministicLowercaseHexSha256() + { + var first = ClientIdentityFactory.ComputeClientId(FullIdentity); + var second = ClientIdentityFactory.ComputeClientId(FullIdentity); + + Assert.Equal(first, second); + Assert.Equal(64, first.Length); + Assert.Matches("^[0-9a-f]{64}$", first); + } + + [Fact] + public void ClientIdIgnoresVolatileValueChanges() + { + // Same hardware, different hostname/user/IP — not part of the identity at all. + var a = ClientIdentityFactory.ComputeClientId(FullIdentity); + var b = ClientIdentityFactory.ComputeClientId(FullIdentity with { }); + Assert.Equal(a, b); + } + + [Fact] + public void DifferentHardwareYieldsDifferentClientId() + { + var other = FullIdentity with { SystemProductUuid = "11111111-2222-3333-4444-555555555555" }; + Assert.NotEqual( + ClientIdentityFactory.ComputeClientId(FullIdentity), + ClientIdentityFactory.ComputeClientId(other)); + } + + [Fact] + public void PlaceholderUuidFallsBackToOtherIdentifiers() + { + var identity = FullIdentity with { SystemProductUuid = "03000200-0400-0500-0006-000700080009" }; + var canonical = ClientIdentityFactory.BuildCanonicalIdentity(identity); + + Assert.StartsWith("UUID=|BIOS=ABC1234|", canonical); + } + + [Fact] + public void MissingAllStrongIdentifiersThrows() + { + var junk = new HardwareIdentity( + SystemProductUuid: "00000000-0000-0000-0000-000000000000", + BiosSerialNumber: "To Be Filled By O.E.M.", + BaseboardSerialNumber: null, + IdentifyingNumber: "Default string", + Manufacturer: "Generic", + Model: "Board"); + + Assert.Throws(() => ClientIdentityFactory.BuildCanonicalIdentity(junk)); + } +} diff --git a/tests/Agent.Tests/DownloadCacheTests.cs b/tests/Agent.Tests/DownloadCacheTests.cs new file mode 100644 index 0000000..837bb08 --- /dev/null +++ b/tests/Agent.Tests/DownloadCacheTests.cs @@ -0,0 +1,86 @@ +using Agent.Storage; +using Xunit; + +namespace Agent.Tests; + +public class DownloadCacheTests : IDisposable +{ + private readonly string databasePath = Path.Combine(Path.GetTempPath(), $"dl-{Guid.NewGuid():N}.db"); + private readonly JobHistoryStore store; + + public DownloadCacheTests() => store = new JobHistoryStore(databasePath); + + [Fact] + public void UnknownDestinationHasNoCacheEntry() + { + Assert.Null(store.GetDownloadCache(@"C:\ProgramData\ExecuteR\downloads\nothing.exe")); + } + + [Fact] + public void RecordedDownloadIsReadBack() + { + const string path = @"C:\ProgramData\ExecuteR\downloads\setup.exe"; + store.RecordDownload(path, "installers/setup.exe", "\"abc123\"", "deadbeef", 4096); + + var entry = store.GetDownloadCache(path); + + Assert.NotNull(entry); + Assert.Equal("\"abc123\"", entry.ETag); + Assert.Equal("deadbeef", entry.Sha256); + Assert.Equal(4096, entry.SizeBytes); + } + + [Fact] + public void RecordingSameDestinationTwiceUpdatesInPlace() + { + const string path = @"C:\ProgramData\ExecuteR\downloads\setup.exe"; + store.RecordDownload(path, "installers/setup.exe", "\"v1\"", "hash1", 100); + store.RecordDownload(path, "installers/setup.exe", "\"v2\"", "hash2", 200); + + var entry = store.GetDownloadCache(path); + + Assert.NotNull(entry); + Assert.Equal("\"v2\"", entry.ETag); + Assert.Equal("hash2", entry.Sha256); + Assert.Equal(200, entry.SizeBytes); + } + + [Fact] + public void CacheSurvivesReopeningTheStore() + { + const string path = @"C:\ProgramData\ExecuteR\downloads\tool.zip"; + store.RecordDownload(path, "tools/tool.zip", "\"etag\"", "hash", 10); + store.Dispose(); + + using var reopened = new JobHistoryStore(databasePath); + var entry = reopened.GetDownloadCache(path); + + Assert.NotNull(entry); + Assert.Equal("\"etag\"", entry.ETag); + } + + [Fact] + public void DownloadCacheIsSeparateFromJobIdempotency() + { + var jobId = Guid.NewGuid(); + Assert.True(store.TryRecordAccepted(jobId)); + Assert.False(store.TryRecordAccepted(jobId)); + + store.RecordDownload(@"C:\x\y.bin", "k", null, "h", 1); + Assert.NotNull(store.GetDownloadCache(@"C:\x\y.bin")); + Assert.True(store.IsHandled(jobId)); + } + + public void Dispose() + { + store.Dispose(); + try + { + File.Delete(databasePath); + } + catch (IOException) + { + // Best effort. + } + } +} diff --git a/tests/Agent.Tests/InMemoryRegistryStore.cs b/tests/Agent.Tests/InMemoryRegistryStore.cs new file mode 100644 index 0000000..e2b5082 --- /dev/null +++ b/tests/Agent.Tests/InMemoryRegistryStore.cs @@ -0,0 +1,45 @@ +using Agent.Configuration; + +namespace Agent.Tests; + +/// In-memory IRegistryStore for configuration tests. +public sealed class InMemoryRegistryStore : IRegistryStore +{ + private readonly Dictionary<(string Key, string Name), object> values = new( + EqualityComparer<(string, string)>.Create( + (a, b) => string.Equals(a.Item1, b.Item1, StringComparison.OrdinalIgnoreCase) + && string.Equals(a.Item2, b.Item2, StringComparison.OrdinalIgnoreCase), + key => HashCode.Combine( + key.Item1.ToUpperInvariant(), + key.Item2.ToUpperInvariant()))); + + public void SetString(string keyPath, string valueName, string value) + => values[(keyPath, valueName)] = value; + + public void SetDword(string keyPath, string valueName, int value) + => values[(keyPath, valueName)] = value; + + public string? ReadString(string keyPath, string valueName) + => values.TryGetValue((keyPath, valueName), out var value) ? value as string : null; + + public int? ReadDword(string keyPath, string valueName) + => values.TryGetValue((keyPath, valueName), out var value) && value is int i ? i : null; + + public void WriteString(string keyPath, string valueName, string value) + => values[(keyPath, valueName)] = value; + + public void DeleteValue(string keyPath, string valueName) + => values.Remove((keyPath, valueName)); + + public void DeleteKeyTree(string keyPath) + { + foreach (var key in values.Keys.Where(k => + k.Key.StartsWith(keyPath, StringComparison.OrdinalIgnoreCase)).ToList()) + { + values.Remove(key); + } + } + + public bool Contains(string keyPath, string valueName) + => values.ContainsKey((keyPath, valueName)); +} diff --git a/tests/Agent.Tests/PowerShellExecutionTests.cs b/tests/Agent.Tests/PowerShellExecutionTests.cs new file mode 100644 index 0000000..bc2b073 --- /dev/null +++ b/tests/Agent.Tests/PowerShellExecutionTests.cs @@ -0,0 +1,105 @@ +using Agent.PowerShell; +using Shared.Contracts.Models; +using Xunit; + +namespace Agent.Tests; + +public class PowerShellExecutionTests +{ + private static async Task<(List Records, List Progress, PowerShellExecutionResult Result)> + RunAsync(string script, CancellationToken cancellationToken = default) + { + var records = new List(); + var progress = new List(); + var service = new PowerShellExecutionService(); + var result = await service.ExecuteAsync( + script, parameters: null, + onRecord: r => { lock (records) records.Add(r); }, + onProgress: p => { lock (progress) progress.Add(p); }, + cancellationToken); + return (records, progress, result); + } + + [Fact] + public async Task OutputStreamIsCapturedAndNormalized() + { + var (records, _, result) = await RunAsync("Write-Output 'hello world'"); + + Assert.False(result.HadErrors); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Output && r.Text.Contains("hello world")); + } + + [Fact] + public async Task CoreModulesResolveHeadless() + { + // Exercises Microsoft.PowerShell.Utility (Select-Object) and .Management + // (Get-Process) — the modules the agent intentionally retains. + var (records, _, result) = await RunAsync( + "Get-Process | Select-Object -First 1 | ForEach-Object { $_.ProcessName }"); + + Assert.False(result.HadErrors); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Output && !string.IsNullOrWhiteSpace(r.Text)); + } + + [Fact] + public async Task ProgressRecordsAreNormalized() + { + var (_, progress, _) = await RunAsync( + "Write-Progress -Activity 'Test' -Status 'Half' -PercentComplete 50"); + + Assert.Contains(progress, p => p.Activity == "Test" && p.PercentComplete == 50 && p.StatusDescription == "Half"); + } + + [Fact] + public async Task ErrorStreamIsCaptured() + { + var (records, _, result) = await RunAsync("Write-Error 'boom'"); + + Assert.True(result.HadErrors); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Error && r.Text.Contains("boom")); + } + + [Fact] + public async Task WarningAndVerboseStreamsAreClassified() + { + var (records, _, _) = await RunAsync( + "$WarningPreference='Continue'; $VerbosePreference='Continue'; Write-Warning 'w'; Write-Verbose 'v'"); + + Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning && r.Text.Contains('w')); + Assert.Contains(records, r => r.Stream == OutputStreamKind.Verbose && r.Text.Contains('v')); + } + + [Fact] + public async Task CancellationStopsExecution() + { + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(400)); + var (_, _, result) = await RunAsync("Start-Sleep -Seconds 30", cts.Token); + + Assert.True(result.WasCancelled); + } + + [Fact] + public async Task TypedParametersBindToScript() + { + // Named typed parameters, including a hashtable — proves the binding + // path used by variable injection. + var records = new List(); + var service = new PowerShellExecutionService(); + var parameters = new Dictionary + { + ["Count"] = 3, + ["Label"] = "widget", + ["Map"] = new Dictionary { ["a"] = 1, ["b"] = true }, + }; + + var result = await service.ExecuteAsync( + "param([int]$Count,[string]$Label,[hashtable]$Map) Write-Output \"$Label x$Count map=$($Map.a),$($Map.b)\"", + parameters, + r => { lock (records) records.Add(r); }, + _ => { }, + CancellationToken.None); + + Assert.False(result.HadErrors); + Assert.Contains(records, r => r.Text.Contains("widget x3 map=1,True")); + } +} diff --git a/tests/Backend.Tests/AuthTests.cs b/tests/Backend.Tests/AuthTests.cs new file mode 100644 index 0000000..1422451 --- /dev/null +++ b/tests/Backend.Tests/AuthTests.cs @@ -0,0 +1,125 @@ +using System.Net; +using System.Net.Http.Json; +using Backend.Data; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Shared.Contracts.Api; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Xunit; + +namespace Backend.Tests; + +public class AuthTests : IClassFixture +{ + private readonly BackendTestFixture fixture; + + public AuthTests(BackendTestFixture fixture) => this.fixture = fixture; + + private async Task SeedUserAsync(string username, string password, UserRole role) + { + await fixture.WithDbAsync(async db => + { + var existing = db.Users.FirstOrDefault(u => u.Username == username); + if (existing is not null) + { + return; + } + + var user = new UserEntity + { + Id = Guid.NewGuid(), + Username = username, + DisplayName = username, + Role = role, + AuthProvider = "local", + CreatedUtc = DateTimeOffset.UtcNow, + }; + user.PasswordHash = new PasswordHasher().HashPassword(user, password); + db.Users.Add(user); + await db.SaveChangesAsync(); + }); + } + + [Fact] + public async Task UnauthenticatedRequestsAreRejected() + { + using var client = fixture.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false + }); + + var response = await client.GetAsync(ApiRoutes.Devices); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task ValidLoginEstablishesSessionAndAllowsAccess() + { + await SeedUserAsync("operator1", "Str0ng-Pass!", UserRole.Operator); + using var client = fixture.CreateClient(); + + var login = await client.PostAsJsonAsync( + ApiRoutes.AuthLogin, new LoginRequest("operator1", "Str0ng-Pass!"), JsonDefaults.Options); + Assert.Equal(HttpStatusCode.OK, login.StatusCode); + + var session = await client.GetFromJsonAsync(ApiRoutes.AuthSession, JsonDefaults.Options); + Assert.NotNull(session); + Assert.True(session.Authenticated); + Assert.Equal(UserRole.Operator, session.Role); + + var devices = await client.GetAsync(ApiRoutes.Devices); + Assert.Equal(HttpStatusCode.OK, devices.StatusCode); + } + + [Fact] + public async Task WrongPasswordIsRejected() + { + await SeedUserAsync("operator2", "correct-horse", UserRole.Operator); + using var client = fixture.CreateClient(); + + var login = await client.PostAsJsonAsync( + ApiRoutes.AuthLogin, new LoginRequest("operator2", "wrong-password"), JsonDefaults.Options); + Assert.Equal(HttpStatusCode.Unauthorized, login.StatusCode); + } + + [Fact] + public async Task OperatorCannotAccessAdminEndpoints() + { + await SeedUserAsync("operator3", "Str0ng-Pass!", UserRole.Operator); + using var client = fixture.CreateClient(); + + await client.PostAsJsonAsync(ApiRoutes.AuthLogin, new LoginRequest("operator3", "Str0ng-Pass!"), JsonDefaults.Options); + + var response = await client.GetAsync(ApiRoutes.AdminBootstrapTokens); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task AdminCanAccessAdminEndpoints() + { + await SeedUserAsync("admin1", "Str0ng-Pass!", UserRole.Admin); + using var client = fixture.CreateClient(); + + await client.PostAsJsonAsync(ApiRoutes.AuthLogin, new LoginRequest("admin1", "Str0ng-Pass!"), JsonDefaults.Options); + + var response = await client.GetAsync(ApiRoutes.AdminBootstrapTokens); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task StateChangingRequestWithoutCsrfTokenIsRejected() + { + await SeedUserAsync("admin2", "Str0ng-Pass!", UserRole.Admin); + // The default factory client persists cookies across requests. + using var client = fixture.CreateClient(); + + await client.PostAsJsonAsync(ApiRoutes.AuthLogin, new LoginRequest("admin2", "Str0ng-Pass!"), JsonDefaults.Options); + + // Session + csrf cookies are attached automatically, but no X-CSRF-Token + // header is present — the double-submit check must reject this. + var response = await client.PostAsJsonAsync( + ApiRoutes.AdminBootstrapTokens, new CreateBootstrapTokenRequest(60, 1, "no-csrf"), JsonDefaults.Options); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } +} diff --git a/tests/Backend.Tests/Backend.Tests.csproj b/tests/Backend.Tests/Backend.Tests.csproj new file mode 100644 index 0000000..8b2c8b6 --- /dev/null +++ b/tests/Backend.Tests/Backend.Tests.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + Exe + false + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/tests/Backend.Tests/BackendTestFixture.cs b/tests/Backend.Tests/BackendTestFixture.cs new file mode 100644 index 0000000..1057299 --- /dev/null +++ b/tests/Backend.Tests/BackendTestFixture.cs @@ -0,0 +1,61 @@ +using Backend.Data; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using NATS.NKeys; + +namespace Backend.Tests; + +/// +/// Boots the backend with an isolated SQLite database and a freshly generated +/// account signing key. NATS itself is not required for these tests. +/// +public sealed class BackendTestFixture : WebApplicationFactory +{ + public KeyPair AccountKey { get; } = KeyPair.CreatePair(PrefixByte.Account); + public KeyPair SigningKey { get; } = KeyPair.CreatePair(PrefixByte.Account); + public string DatabasePath { get; } = + Path.Combine(Path.GetTempPath(), $"backend-tests-{Guid.NewGuid():N}.db"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseSetting("DATABASE_PATH", DatabasePath); + builder.UseSetting("NATS_ACCOUNT_SIGNING_SEED", SigningKey.GetSeed()); + builder.UseSetting("NATS_ACCOUNT_PUBLIC_KEY", AccountKey.GetPublicKey()); + builder.UseSetting("NATS_URL", string.Empty); + builder.UseSetting("RATE_LIMIT_PER_MINUTE", "10000"); + builder.UseEnvironment("Development"); + } + + public async Task WithDbAsync(Func> action) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await action(db); + } + + public Task WithDbAsync(Func action) + => WithDbAsync(async db => + { + await action(db); + return true; + }); + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + AccountKey.Dispose(); + SigningKey.Dispose(); + try + { + File.Delete(DatabasePath); + } + catch (IOException) + { + // Best effort. + } + } + } +} diff --git a/tests/Backend.Tests/BootstrapEndpointTests.cs b/tests/Backend.Tests/BootstrapEndpointTests.cs new file mode 100644 index 0000000..1534b9a --- /dev/null +++ b/tests/Backend.Tests/BootstrapEndpointTests.cs @@ -0,0 +1,183 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using Backend.Data; +using NATS.Jwt; +using NATS.NKeys; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Security; +using Xunit; + +namespace Backend.Tests; + +public class BootstrapEndpointTests : IClassFixture +{ + private const string ClientId = "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; + + private readonly BackendTestFixture fixture; + + public BootstrapEndpointTests(BackendTestFixture fixture) => this.fixture = fixture; + + private async Task CreateTokenAsync( + TimeSpan? lifetime = null, int maxUses = 1, bool revoked = false) + { + var token = TokenGenerator.CreateUrlSafeToken(32); + await fixture.WithDbAsync(async db => + { + db.BootstrapTokens.Add(new BootstrapTokenEntity + { + Id = Guid.NewGuid(), + TokenHash = TokenHashing.Sha256Hex(token), + CreatedUtc = DateTimeOffset.UtcNow, + ExpiresUtc = DateTimeOffset.UtcNow + (lifetime ?? TimeSpan.FromHours(1)), + MaxUses = maxUses, + Revoked = revoked, + }); + await db.SaveChangesAsync(); + }); + return token; + } + + private static BootstrapRequest MakeRequest(string token, string clientId, string nkeyPublic) + => new( + BootstrapToken: token, + ClientId: clientId, + NkeyPublic: nkeyPublic, + AgentVersion: "2026.08.06.0000", + Device: new EnrollDeviceInfo("PC-001", "Dell Inc.", "OptiPlex", "Windows 11", "10.0.26200")); + + [Fact] + public async Task ValidBootstrapIssuesScopedJwtAndConsumesToken() + { + var token = await CreateTokenAsync(); + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await response.Content.ReadFromJsonAsync(JsonDefaults.Options); + Assert.NotNull(body); + Assert.Equal(ClientId, body.ClientId); + + // JWT is scoped to exactly this client id and signed by the signing key. + var claims = NatsJwt.DecodeUserClaims(body.UserJwt); + Assert.Equal(userKey.GetPublicKey(), claims.Subject); + Assert.Equal(fixture.SigningKey.GetPublicKey(), claims.Issuer); + Assert.Equal(fixture.AccountKey.GetPublicKey(), claims.User.IssuerAccount); + Assert.Contains($"agent.{ClientId}.presence", claims.User.Pub.Allow); + Assert.Contains($"agent.{ClientId}.command.>", claims.User.Sub.Allow); + Assert.DoesNotContain(claims.User.Pub.Allow, p => p == ">"); + + // Device persisted. + var device = await fixture.WithDbAsync(db => db.Devices.FindAsync(ClientId).AsTask()); + Assert.NotNull(device); + Assert.Equal("PC-001", device.Hostname); + Assert.Equal(userKey.GetPublicKey(), device.NkeyPublic); + + // One-time token: a second use is rejected. + var second = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options); + Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode); + } + + [Fact] + public async Task ExpiredTokenIsRejected() + { + var token = await CreateTokenAsync(lifetime: TimeSpan.FromMinutes(-5)); + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task RevokedTokenIsRejected() + { + var token = await CreateTokenAsync(revoked: true); + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task UnknownTokenIsRejected() + { + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest("never-issued", ClientId, userKey.GetPublicKey()), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Theory] + [InlineData("Has.Dots")] + [InlineData("has*star")] + [InlineData("")] + public async Task InvalidClientIdIsRejected(string clientId) + { + var token = await CreateTokenAsync(); + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, clientId, userKey.GetPublicKey()), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task InvalidNkeyIsRejected() + { + var token = await CreateTokenAsync(); + using var client = fixture.CreateClient(); + + var response = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, ClientId, "not-a-real-nkey"), JsonDefaults.Options); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task CredentialRefreshVerifiesPossessionOfEnrolledKey() + { + var token = await CreateTokenAsync(); + var clientId = "1111aaaa2222bbbb3333cccc4444dddd5555eeee6666ffff7777888899990000"; + using var userKey = KeyPair.CreatePair(PrefixByte.User); + using var client = fixture.CreateClient(); + + var enroll = await client.PostAsJsonAsync( + ApiRoutes.Bootstrap, MakeRequest(token, clientId, userKey.GetPublicKey()), JsonDefaults.Options); + Assert.Equal(HttpStatusCode.OK, enroll.StatusCode); + + // Correctly signed refresh succeeds. + var timestamp = DateTimeOffset.UtcNow; + var payload = Encoding.UTF8.GetBytes($"{clientId}|{timestamp:O}"); + var signature = new byte[64]; + userKey.Sign(payload, signature); + + var refresh = await client.PostAsJsonAsync(ApiRoutes.RefreshCredential, + new CredentialRefreshRequest(clientId, userKey.GetPublicKey(), timestamp, Convert.ToBase64String(signature)), + JsonDefaults.Options); + Assert.Equal(HttpStatusCode.OK, refresh.StatusCode); + + // A different key cannot refresh. + using var wrongKey = KeyPair.CreatePair(PrefixByte.User); + wrongKey.Sign(payload, signature); + var forged = await client.PostAsJsonAsync(ApiRoutes.RefreshCredential, + new CredentialRefreshRequest(clientId, userKey.GetPublicKey(), timestamp, Convert.ToBase64String(signature)), + JsonDefaults.Options); + Assert.Equal(HttpStatusCode.Unauthorized, forged.StatusCode); + } +} diff --git a/tests/Backend.Tests/InstallEndpointTests.cs b/tests/Backend.Tests/InstallEndpointTests.cs new file mode 100644 index 0000000..9ef54b7 --- /dev/null +++ b/tests/Backend.Tests/InstallEndpointTests.cs @@ -0,0 +1,56 @@ +using System.Net; +using Shared.Contracts.Api; +using Xunit; + +namespace Backend.Tests; + +public class InstallEndpointTests : IClassFixture +{ + private readonly BackendTestFixture fixture; + + public InstallEndpointTests(BackendTestFixture fixture) => this.fixture = fixture; + + [Fact] + public async Task InstallScriptEmbedsTokenAndInstallCommand() + { + using var client = fixture.CreateClient(); + + var response = await client.GetAsync($"{ApiRoutes.InstallScript}?token=test-token-123"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var script = await response.Content.ReadAsStringAsync(); + Assert.Contains("test-token-123", script); + Assert.Contains("msiexec.exe", script); + Assert.Contains("BOOTSTRAPTOKEN=$token", script); + Assert.Contains("/api/enrollment/agent-package", script); + } + + [Fact] + public async Task InstallScriptRequiresToken() + { + using var client = fixture.CreateClient(); + var response = await client.GetAsync(ApiRoutes.InstallScript); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task ZipInstallScriptUsesInitializeCommand() + { + using var client = fixture.CreateClient(); + + var response = await client.GetAsync($"{ApiRoutes.InstallScript}?token=t&type=zip"); + var script = await response.Content.ReadAsStringAsync(); + + Assert.Contains("Expand-Archive", script); + Assert.Contains("initialize", script); + Assert.Contains("type=zip", script); + } + + [Fact] + public async Task AgentPackageReturns404WhenAbsent() + { + using var client = fixture.CreateClient(); + var response = await client.GetAsync($"{ApiRoutes.AgentPackage}?type=msi"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } +} diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props new file mode 100644 index 0000000..782d92b --- /dev/null +++ b/tests/Directory.Build.props @@ -0,0 +1,10 @@ + + + + + + + $(NoWarn);xUnit1051 + + + diff --git a/tests/Integration.Tests/Integration.Tests.csproj b/tests/Integration.Tests/Integration.Tests.csproj new file mode 100644 index 0000000..b432fe2 --- /dev/null +++ b/tests/Integration.Tests/Integration.Tests.csproj @@ -0,0 +1,25 @@ + + + + net10.0-windows + Exe + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/tests/Integration.Tests/JobPipelineIntegrationTests.cs b/tests/Integration.Tests/JobPipelineIntegrationTests.cs new file mode 100644 index 0000000..e9aab7c --- /dev/null +++ b/tests/Integration.Tests/JobPipelineIntegrationTests.cs @@ -0,0 +1,171 @@ +using System.Collections.Concurrent; +using Agent.Commands; +using Agent.Configuration; +using Agent.Files; +using Agent.Inventory; +using Agent.Identity; +using Agent.Messaging; +using Agent.PowerShell; +using Agent.Storage; +using Microsoft.Extensions.Logging.Abstractions; +using NATS.Client.Core; +using NATS.Client.JetStream; +using NATS.Client.JetStream.Models; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Configuration; +using Shared.Infrastructure.Nats; +using Xunit; + +namespace Integration.Tests; + +/// +/// End-to-end over a real NATS+JetStream server: a durable script command is +/// dispatched, the agent executes it in-process, and output/progress/state flow +/// back on the job subjects. Also proves a duplicate delivery does not execute +/// twice. Requires a no-auth JetStream NATS at NATS_URL (default +/// nats://127.0.0.1:4222); skipped when unreachable so local runs stay green. +/// +public class JobPipelineIntegrationTests +{ + private static string NatsUrl => Environment.GetEnvironmentVariable("NATS_URL") ?? "nats://127.0.0.1:4222"; + + private static async Task TryConnectAsync() + { + var connection = new NatsConnection(NatsOpts.Default with + { + Url = NatsUrl, + ConnectTimeout = TimeSpan.FromSeconds(2), + MaxReconnectRetry = 0, + }); + + try + { + await connection.ConnectAsync(); + return connection; + } + catch (Exception) + { + await connection.DisposeAsync(); + return null; + } + } + + private static AgentConfiguration Config() => new() + { + ServerUrlText = new(null, ConfigurationSource.Default), + BootstrapToken = new(null, ConfigurationSource.Default), + LogLevel = new("Information", ConfigurationSource.Default), + InventoryInterval = new(TimeSpan.FromMinutes(15), ConfigurationSource.Default), + ReconnectMinDelay = new(TimeSpan.FromSeconds(1), ConfigurationSource.Default), + ReconnectMaxDelay = new(TimeSpan.FromSeconds(60), ConfigurationSource.Default), + AllowRemoteShell = new(false, ConfigurationSource.Default), + AllowScriptExecution = new(true, ConfigurationSource.Default), + }; + + private sealed class FixedIdentity : IHardwareIdentitySource + { + public HardwareIdentity Read() => new("uuid", "bios", "board", "ident", "Contoso", "Model"); + } + + [Fact] + public async Task ScriptCommand_Executes_AndDuplicateDoesNotRunTwice() + { + var connection = await TryConnectAsync(); + if (connection is null) + { + Assert.Skip($"No NATS server reachable at {NatsUrl}; set NATS_URL to run this test."); + return; + } + + await using var _ = connection; + var clientId = "itest" + Guid.NewGuid().ToString("N")[..16]; + var jobId = Guid.NewGuid(); + var jobHistoryPath = Path.Combine(Path.GetTempPath(), $"jobs-{Guid.NewGuid():N}.db"); + using var jobHistory = new JobHistoryStore(jobHistoryPath); + + // Collect job events published by the agent on the job.* subjects. + var outputs = new ConcurrentBag(); + var states = new ConcurrentBag(); + var runningCount = 0; + using var collectorCts = new CancellationTokenSource(); + + var outputSub = Task.Run(async () => + { + await foreach (var msg in connection.SubscribeAsync(NatsSubjects.JobOutput(jobId), cancellationToken: collectorCts.Token)) + { + var p = MessageEnvelope.FromUtf8Bytes(msg.Data!)!.GetPayload(); + if (p is not null) outputs.Add(p); + } + }); + var stateSub = Task.Run(async () => + { + await foreach (var msg in connection.SubscribeAsync(NatsSubjects.JobState(jobId), cancellationToken: collectorCts.Token)) + { + var p = MessageEnvelope.FromUtf8Bytes(msg.Data!)!.GetPayload(); + if (p is not null) + { + states.Add(p); + if (p.State == JobState.Running) Interlocked.Increment(ref runningCount); + } + } + }); + + // Provision the durable command stream + this agent's consumer. + var js = new NatsJSContext(connection); + await js.CreateOrUpdateStreamAsync(new StreamConfig(JetStreamDefaults.CommandStreamName, JetStreamDefaults.CommandStreamSubjects) + { + Storage = StreamConfigStorage.Memory, + }); + var consumerName = JetStreamDefaults.AgentCommandConsumerName(clientId); + await js.CreateOrUpdateConsumerAsync(JetStreamDefaults.CommandStreamName, new ConsumerConfig(consumerName) + { + DurableName = consumerName, + AckPolicy = ConsumerConfigAckPolicy.Explicit, + FilterSubject = JetStreamDefaults.AgentCommandFilterSubject(clientId), + }); + + // Start the agent command processor. + var publisher = new AgentPublisher(connection, clientId); + var jobHandler = new PowerShellJobHandler(new PowerShellExecutionService(), publisher, jobHistory, NullLogger.Instance); + var fileHandler = new FileDownloadHandler(publisher, jobHistory, NullLogger.Instance); + var inventory = new InventoryPublisher(new InventoryCollector(new FixedIdentity()), publisher, TimeSpan.FromHours(1), NullLogger.Instance); + var processor = new CommandProcessor(connection, publisher, inventory, jobHandler, fileHandler, jobHistory, Config(), NullLogger.Instance); + + using var processorCts = new CancellationTokenSource(); + var processorTask = Task.Run(() => processor.RunAsync(processorCts.Token)); + + // Give subscriptions time to register. + await Task.Delay(500); + + // Dispatch a script command twice (same job id => duplicate). + var command = new ScriptCommandPayload(jobId, Guid.NewGuid(), "Integration Demo", + "1..3 | ForEach-Object { Write-Output \"line $_\"; Write-Progress -Activity 'x' -PercentComplete ($_ * 30) }", 60); + var envelope = MessageEnvelope.Create(MessageTypes.CommandScript, new EndpointRef(EndpointKinds.Backend, "backend"), + command, new EndpointRef(EndpointKinds.Agent, clientId)); + + var subject = NatsSubjects.AgentCommandScript(clientId); + (await js.PublishAsync(subject, envelope.ToUtf8Bytes())).EnsureSuccess(); + (await js.PublishAsync(subject, envelope.ToUtf8Bytes())).EnsureSuccess(); // duplicate + + // Wait for terminal state. + var deadline = DateTime.UtcNow.AddSeconds(30); + while (DateTime.UtcNow < deadline && !states.Any(s => s.State is JobState.Succeeded or JobState.Failed)) + { + await Task.Delay(200); + } + + await processorCts.CancelAsync(); + await collectorCts.CancelAsync(); + await Task.WhenAny(processorTask, Task.Delay(2000)); + + Assert.Contains(states, s => s.State == JobState.Succeeded); + Assert.Contains(outputs, o => o.Text.Contains("line 1")); + Assert.Contains(outputs, o => o.Text.Contains("line 3")); + + // Idempotency: the job ran exactly once despite duplicate delivery. + Assert.Equal(1, runningCount); + + try { File.Delete(jobHistoryPath); } catch (IOException) { } + } +} diff --git a/tests/Shared.Tests/ApiRoutesTests.cs b/tests/Shared.Tests/ApiRoutesTests.cs new file mode 100644 index 0000000..59f2681 --- /dev/null +++ b/tests/Shared.Tests/ApiRoutesTests.cs @@ -0,0 +1,44 @@ +using System.Reflection; +using Shared.Contracts.Api; +using Xunit; + +namespace Shared.Tests; + +public class ApiRoutesTests +{ + [Fact] + public void AllRouteConstantsAreUnique() + { + var routes = typeof(ApiRoutes) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.IsLiteral && f.FieldType == typeof(string)) + .Select(f => (string)f.GetRawConstantValue()!) + .ToList(); + + Assert.NotEmpty(routes); + Assert.Equal(routes.Count, routes.Distinct(StringComparer.OrdinalIgnoreCase).Count()); + } + + [Fact] + public void AllRoutesStartWithApiPrefixAndHaveNoVersionSegment() + { + var routes = typeof(ApiRoutes) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.IsLiteral && f.FieldType == typeof(string)) + .Select(f => (string)f.GetRawConstantValue()!); + + foreach (var route in routes) + { + Assert.StartsWith("/api/", route); + Assert.DoesNotContain("/v1/", route); + } + } + + [Fact] + public void ConcreteRouteBuildersMatchTemplates() + { + Assert.Equal("/api/devices/abc123", ApiRoutes.For.Device("abc123")); + var id = Guid.Parse("11111111-2222-3333-4444-555555555555"); + Assert.Equal($"/api/jobs/{id:D}/output", ApiRoutes.For.JobOutput(id)); + } +} diff --git a/tests/Shared.Tests/BuildVersionTests.cs b/tests/Shared.Tests/BuildVersionTests.cs new file mode 100644 index 0000000..940272e --- /dev/null +++ b/tests/Shared.Tests/BuildVersionTests.cs @@ -0,0 +1,36 @@ +using Shared.Infrastructure.Versioning; +using Xunit; + +namespace Shared.Tests; + +public class BuildVersionTests +{ + [Theory] + [InlineData("2026.08.06.2151", "26.8.8511")] + [InlineData("2026.01.01.0000", "26.1.0")] + [InlineData("2026.12.31.2359", "26.12.44639")] + public void MsiProductVersionTransformIsDeterministic(string unified, string expected) + { + Assert.Equal(expected, BuildVersion.ToMsiProductVersion(unified)); + } + + [Fact] + public void MsiProductVersionIsMonotonicWithinAMonth() + { + var earlier = BuildVersion.ToMsiProductVersion("2026.08.06.2151"); + var later = BuildVersion.ToMsiProductVersion("2026.08.07.0001"); + + var earlierBuild = int.Parse(earlier.Split('.')[2]); + var laterBuild = int.Parse(later.Split('.')[2]); + Assert.True(laterBuild > earlierBuild); + } + + [Theory] + [InlineData("not-a-version")] + [InlineData("2026.08.06")] + [InlineData("1.2.3.4.5")] + public void InvalidUnifiedVersionsAreRejected(string value) + { + Assert.Throws(() => BuildVersion.ToMsiProductVersion(value)); + } +} diff --git a/tests/Shared.Tests/MessageEnvelopeTests.cs b/tests/Shared.Tests/MessageEnvelopeTests.cs new file mode 100644 index 0000000..ab04c1f --- /dev/null +++ b/tests/Shared.Tests/MessageEnvelopeTests.cs @@ -0,0 +1,92 @@ +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Xunit; + +namespace Shared.Tests; + +public class MessageEnvelopeTests +{ + [Fact] + public void RoundTripPreservesEnvelopeAndPayload() + { + var payload = new JobProgressPayload( + JobId: Guid.NewGuid(), + ClientId: "abc123", + Activity: "Installing component", + StatusDescription: "Step 4 of 10", + PercentComplete: 40, + SecondsRemaining: 12, + TimestampUtc: DateTimeOffset.UtcNow); + + var envelope = MessageEnvelope.Create( + MessageTypes.JobProgress, + new EndpointRef(EndpointKinds.Agent, "abc123"), + payload, + new EndpointRef(EndpointKinds.Job, payload.JobId.ToString("D"))); + + var bytes = envelope.ToUtf8Bytes(); + var restored = MessageEnvelope.FromUtf8Bytes(bytes); + + Assert.NotNull(restored); + Assert.Equal(envelope.MessageId, restored.MessageId); + Assert.Equal(envelope.CorrelationId, restored.CorrelationId); + Assert.Equal(MessageTypes.JobProgress, restored.MessageType); + Assert.Equal(MessageEnvelope.CurrentSchemaVersion, restored.SchemaVersion); + Assert.Equal(EndpointKinds.Agent, restored.Source.Kind); + + var restoredPayload = restored.GetPayload(); + Assert.NotNull(restoredPayload); + Assert.Equal(payload.Activity, restoredPayload.Activity); + Assert.Equal(payload.PercentComplete, restoredPayload.PercentComplete); + } + + [Fact] + public void UnknownJsonPropertiesAreIgnored() + { + const string json = """ + { + "messageId": "11111111-1111-1111-1111-111111111111", + "correlationId": "22222222-2222-2222-2222-222222222222", + "messageType": "job.progress", + "schemaVersion": 7, + "timestampUtc": "2026-08-06T21:00:00.000Z", + "source": { "kind": "agent", "id": "client-1", "futureField": true }, + "payload": {}, + "someNewTopLevelThing": { "x": 1 } + } + """; + + var envelope = JsonDefaults.Deserialize(json); + Assert.NotNull(envelope); + Assert.Equal(7, envelope.SchemaVersion); + Assert.Null(envelope.CausationId); + } + + [Fact] + public void CreateNextPreservesCorrelationAndSetsCausation() + { + var first = MessageEnvelope.Create( + MessageTypes.CommandScript, + new EndpointRef(EndpointKinds.Backend, "backend"), + new InventoryCommandPayload("test")); + + var next = first.CreateNext( + MessageTypes.JobState, + new EndpointRef(EndpointKinds.Agent, "client-1"), + new { }); + + Assert.Equal(first.CorrelationId, next.CorrelationId); + Assert.Equal(first.MessageId, next.CausationId); + Assert.NotEqual(first.MessageId, next.MessageId); + } + + [Fact] + public void EnumsSerializeAsCamelCaseStrings() + { + var json = JsonDefaults.Serialize(new JobOutputPayload( + Guid.NewGuid(), "c1", 1, OutputStreamKind.Warning, DateTimeOffset.UtcNow, "text")); + + Assert.Contains("\"stream\":\"warning\"", json); + } +} diff --git a/tests/Shared.Tests/NatsSubjectsTests.cs b/tests/Shared.Tests/NatsSubjectsTests.cs new file mode 100644 index 0000000..a6008bb --- /dev/null +++ b/tests/Shared.Tests/NatsSubjectsTests.cs @@ -0,0 +1,90 @@ +using Shared.Infrastructure.Nats; +using Xunit; + +namespace Shared.Tests; + +public class NatsSubjectsTests +{ + private const string ClientId = "0a1b2c3d4e5f"; + + [Fact] + public void AgentSubjectsAreBuiltCorrectly() + { + Assert.Equal($"agent.{ClientId}.presence", NatsSubjects.AgentPresence(ClientId)); + Assert.Equal($"agent.{ClientId}.inventory", NatsSubjects.AgentInventory(ClientId)); + Assert.Equal($"agent.{ClientId}.command.script", NatsSubjects.AgentCommandScript(ClientId)); + Assert.Equal($"agent.{ClientId}.command.>", NatsSubjects.AgentCommandWildcard(ClientId)); + } + + [Fact] + public void ShellSubjectsIncludeSessionId() + { + var session = Guid.Parse("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); + Assert.Equal( + $"agent.{ClientId}.shell.aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee.output", + NatsSubjects.AgentShellOutput(ClientId, session)); + } + + [Fact] + public void JobSubjectsUseLowercaseGuids() + { + var jobId = Guid.Parse("AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"); + Assert.Equal("job.aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee.progress", NatsSubjects.JobProgress(jobId)); + } + + [Theory] + [InlineData("valid-id-123", true)] + [InlineData("0a1b2c3d", true)] + [InlineData("", false)] + [InlineData(null, false)] + [InlineData("has.dot", false)] + [InlineData("has*star", false)] + [InlineData("has>gt", false)] + [InlineData("has space", false)] + [InlineData("UPPER", false)] + [InlineData("-leading-hyphen", false)] + public void SubjectIdentifierValidation(string? value, bool expected) + { + Assert.Equal(expected, SubjectIdentifier.IsValid(value)); + } + + [Fact] + public void InvalidIdentifierThrowsWhenBuildingSubject() + { + Assert.Throws(() => NatsSubjects.AgentPresence("bad.client.id")); + } + + [Fact] + public void NoSubjectContainsProductNameOrVersionSegment() + { + var samples = new[] + { + NatsSubjects.AgentPresence(ClientId), + NatsSubjects.AgentCommandScript(ClientId), + NatsSubjects.JobOutput(Guid.NewGuid()), + NatsSubjects.BrowserEvent("session1"), + NatsSubjects.SystemAgentEnrolled, + }; + + foreach (var subject in samples) + { + Assert.DoesNotContain("executer", subject, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(".v1.", subject); + } + } + + [Fact] + public void AgentPermissionsAreScopedToClientId() + { + var publish = NatsSubjects.AgentPublishPermissions(ClientId); + var subscribe = NatsSubjects.AgentSubscribePermissions(ClientId); + + Assert.Contains($"agent.{ClientId}.presence", publish); + Assert.Contains($"agent.{ClientId}.command.>", subscribe); + Assert.DoesNotContain(publish, p => p.StartsWith("agent.") && !p.Contains(ClientId)); + + // JetStream API access limited to the agent's own durable consumer. + Assert.Contains($"$JS.API.CONSUMER.MSG.NEXT.COMMANDS.agent-commands-{ClientId}", publish); + Assert.DoesNotContain(publish, p => p.StartsWith("$JS.") && !p.Contains(ClientId) && !p.StartsWith("$JS.ACK")); + } +} diff --git a/tests/Shared.Tests/RuleEvaluatorTests.cs b/tests/Shared.Tests/RuleEvaluatorTests.cs new file mode 100644 index 0000000..b0dae4f --- /dev/null +++ b/tests/Shared.Tests/RuleEvaluatorTests.cs @@ -0,0 +1,192 @@ +using Shared.Contracts.Models; +using Shared.Infrastructure.Grouping; +using Xunit; + +namespace Shared.Tests; + +public class RuleEvaluatorTests +{ + private static InventoryReport Inventory( + string manufacturer = "Dell Inc.", + string os = "Windows 11 Pro", + int cores = 8, + long memoryBytes = 34_359_738_368, + string[]? ips = null) + => new( + new InventoryIdentity("c1", "PC-001", manufacturer, "OptiPlex 7090", "SN1", "1.2.3", "BB1", "CORP", true, "x64-based PC"), + new InventoryOs(os, "10.0.26100", "26100", "64-bit", null, null, "Professional"), + new InventoryCpu("Intel Core i7", cores * 2, cores), + [], + memoryBytes, + [new InventoryDisk("SSD", "S1", 1_000_000_000_000, "NVMe")], + [new InventoryVolume("C:", "NTFS", 1_000_000_000_000, 500_000_000_000)], + [new InventoryNetworkAdapter("NIC", "00:11:22:33:44:55", ips ?? ["10.20.4.14"], [], ["10.20.0.1"], ["10.20.0.10"])], + DateTimeOffset.UtcNow); + + private static DeviceFieldBag Bag( + DeviceStatus status = DeviceStatus.Online, + string[]? tags = null, + InventoryReport? inventory = null, + string hostname = "PC-001") + => DeviceFieldBag.Build("c1", hostname, status, "2026.08.06.2151", tags, inventory ?? Inventory()); + + private static GroupRuleSet Rules(RuleCombine combine, params RuleGroup[] groups) => new(combine, groups); + + private static RuleGroup Group(RuleCombine combine, params RuleCondition[] conditions) + => new(combine, conditions); + + [Theory] + [InlineData(RuleOperator.Equals, "PC-001", true)] + [InlineData(RuleOperator.Equals, "pc-001", true)] // case-insensitive + [InlineData(RuleOperator.Equals, "PC-002", false)] + [InlineData(RuleOperator.NotEquals, "PC-002", true)] + [InlineData(RuleOperator.Contains, "C-00", true)] + [InlineData(RuleOperator.NotContains, "XYZ", true)] + [InlineData(RuleOperator.StartsWith, "PC", true)] + [InlineData(RuleOperator.EndsWith, "001", true)] + [InlineData(RuleOperator.Regex, "^PC-\\d+$", true)] + [InlineData(RuleOperator.Regex, "^SRV", false)] + [InlineData(RuleOperator.In, "PC-001,PC-002", true)] + [InlineData(RuleOperator.NotIn, "PC-002;PC-003", true)] + [InlineData(RuleOperator.Exists, null, true)] + [InlineData(RuleOperator.NotExists, null, false)] + public void StringOperators(RuleOperator op, string? value, bool expected) + { + var condition = new RuleCondition("hostname", op, value); + Assert.Equal(expected, RuleEvaluator.Matches(condition, Bag())); + } + + [Theory] + [InlineData(RuleOperator.GreaterThan, "4", true)] + [InlineData(RuleOperator.GreaterThan, "8", false)] + [InlineData(RuleOperator.GreaterOrEqual, "8", true)] + [InlineData(RuleOperator.LessThan, "16", true)] + [InlineData(RuleOperator.LessOrEqual, "8", true)] + public void NumericOperators(RuleOperator op, string value, bool expected) + { + var condition = new RuleCondition("cpu.cores", op, value); + Assert.Equal(expected, RuleEvaluator.Matches(condition, Bag())); + } + + [Fact] + public void NegationInvertsAnyOperator() + { + var positive = new RuleCondition("hostname", RuleOperator.Equals, "PC-001"); + var negated = positive with { Negate = true }; + + Assert.True(RuleEvaluator.Matches(positive, Bag())); + Assert.False(RuleEvaluator.Matches(negated, Bag())); + } + + [Fact] + public void MultiValueFieldMatchesWhenAnyValueMatches() + { + var bag = Bag(tags: ["kiosk", "finance"]); + + Assert.True(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.Equals, "finance"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.Contains, "kio"), bag)); + Assert.False(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.Equals, "lab"), bag)); + } + + [Fact] + public void NegativeOperatorOnMultiValueRequiresAllValues() + { + var bag = Bag(tags: ["kiosk", "finance"]); + + // "not finance" is false because one tag IS finance. + Assert.False(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.NotEquals, "finance"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.NotEquals, "lab"), bag)); + } + + [Fact] + public void MissingFieldSatisfiesOnlyNegativeOperators() + { + var bag = Bag(tags: null); + + Assert.False(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.Equals, "kiosk"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.NotEquals, "kiosk"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("tags", RuleOperator.NotExists), bag)); + } + + [Fact] + public void AndCombinesConditionsWithinAGroup() + { + var rules = Rules(RuleCombine.And, Group(RuleCombine.And, + new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc."), + new RuleCondition("cpu.cores", RuleOperator.GreaterOrEqual, "8"))); + + Assert.True(RuleEvaluator.Matches(rules, Bag())); + Assert.False(RuleEvaluator.Matches(rules, Bag(inventory: Inventory(manufacturer: "LENOVO")))); + } + + [Fact] + public void OrCombinesConditionsWithinAGroup() + { + var rules = Rules(RuleCombine.And, Group(RuleCombine.Or, + new RuleCondition("manufacturer", RuleOperator.Equals, "LENOVO"), + new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc."))); + + Assert.True(RuleEvaluator.Matches(rules, Bag())); + } + + [Fact] + public void MultipleGroupsCombineWithTheTopLevelOperator() + { + var dell = Group(RuleCombine.And, new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc.")); + var offline = Group(RuleCombine.And, new RuleCondition("status", RuleOperator.Equals, "offline")); + + // AND: manufacturer matches but status does not. + Assert.False(RuleEvaluator.Matches(Rules(RuleCombine.And, dell, offline), Bag())); + // OR: manufacturer alone is enough. + Assert.True(RuleEvaluator.Matches(Rules(RuleCombine.Or, dell, offline), Bag())); + } + + [Fact] + public void GroupNegationInvertsTheWholeGroup() + { + var group = Group(RuleCombine.And, new RuleCondition("status", RuleOperator.Equals, "online")) with { Negate = true }; + Assert.False(RuleEvaluator.Matches(Rules(RuleCombine.And, group), Bag())); + Assert.True(RuleEvaluator.Matches(Rules(RuleCombine.And, group), Bag(status: DeviceStatus.Offline))); + } + + [Fact] + public void NestedGroupsEvaluateRecursively() + { + // manufacturer = Dell AND (status = offline OR tags contains kiosk) + var nested = new RuleGroup(RuleCombine.Or, [ + new RuleCondition("status", RuleOperator.Equals, "offline"), + new RuleCondition("tags", RuleOperator.Contains, "kiosk"), + ]); + var outer = new RuleGroup(RuleCombine.And, + [new RuleCondition("manufacturer", RuleOperator.Equals, "Dell Inc.")], + [nested]); + + Assert.True(RuleEvaluator.Matches(Rules(RuleCombine.And, outer), Bag(tags: ["kiosk"]))); + Assert.False(RuleEvaluator.Matches(Rules(RuleCombine.And, outer), Bag(tags: ["finance"]))); + } + + [Fact] + public void EmptyRuleSetMatchesNothing() + { + Assert.False(RuleEvaluator.Matches(GroupRuleSet.Empty, Bag())); + Assert.False(RuleEvaluator.Matches((GroupRuleSet?)null, Bag())); + } + + [Fact] + public void InvalidRegexNeverMatchesAndDoesNotThrow() + { + var condition = new RuleCondition("hostname", RuleOperator.Regex, "([unclosed"); + Assert.False(RuleEvaluator.Matches(condition, Bag())); + } + + [Fact] + public void StatusAndDerivedInventoryFieldsArePopulated() + { + var bag = Bag(status: DeviceStatus.Stale, inventory: Inventory(memoryBytes: 17_179_869_184)); + + Assert.True(RuleEvaluator.Matches(new RuleCondition("status", RuleOperator.Equals, "stale"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("memory.totalGb", RuleOperator.GreaterOrEqual, "15"), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("network.ipv4", RuleOperator.StartsWith, "10.20."), bag)); + Assert.True(RuleEvaluator.Matches(new RuleCondition("os.caption", RuleOperator.Contains, "Windows 11"), bag)); + } +} diff --git a/tests/Shared.Tests/ServerUrlTests.cs b/tests/Shared.Tests/ServerUrlTests.cs new file mode 100644 index 0000000..e42dfe8 --- /dev/null +++ b/tests/Shared.Tests/ServerUrlTests.cs @@ -0,0 +1,58 @@ +using Shared.Infrastructure.Routing; +using Xunit; + +namespace Shared.Tests; + +public class ServerUrlTests +{ + [Fact] + public void HttpsBecomesWss() + { + var url = ServerUrl.Parse("https://control.example.com"); + Assert.Equal("wss://control.example.com/messaging/agent", url.AgentWebSocketEndpoint.ToString()); + Assert.Equal("wss://control.example.com/messaging/browser", url.BrowserWebSocketEndpoint.ToString()); + } + + [Fact] + public void HttpBecomesWs() + { + var url = ServerUrl.Parse("http://control.example.com"); + Assert.Equal("ws://control.example.com/messaging/agent", url.AgentWebSocketEndpoint.ToString()); + } + + [Fact] + public void NonDefaultPortIsPreserved() + { + var url = ServerUrl.Parse("https://control.example.com:8443"); + Assert.Equal("wss://control.example.com:8443/messaging/agent", url.AgentWebSocketEndpoint.ToString()); + } + + [Fact] + public void BasePathIsNormalizedAndPreserved() + { + var url = ServerUrl.Parse("https://control.example.com/base"); + Assert.Equal("wss://control.example.com/base/messaging/agent", url.AgentWebSocketEndpoint.ToString()); + Assert.Equal("https://control.example.com/base/api/health", url.ApiEndpoint("/api/health").ToString()); + } + + [Fact] + public void ApiEndpointsComeFromHttpBase() + { + var url = ServerUrl.Parse("https://control.example.com"); + Assert.Equal("https://control.example.com/api/enrollment/bootstrap", url.ApiEndpoint("/api/enrollment/bootstrap").ToString()); + } + + [Theory] + [InlineData("ftp://control.example.com")] + [InlineData("wss://control.example.com")] + [InlineData("https://user:pass@control.example.com")] + [InlineData("https://control.example.com/#fragment")] + [InlineData("https://control.example.com/?query=1")] + [InlineData("not a url")] + [InlineData("")] + public void InvalidValuesAreRejected(string value) + { + Assert.False(ServerUrl.TryParse(value, out _, out var error)); + Assert.NotEmpty(error); + } +} diff --git a/tests/Shared.Tests/Shared.Tests.csproj b/tests/Shared.Tests/Shared.Tests.csproj new file mode 100644 index 0000000..8de24b6 --- /dev/null +++ b/tests/Shared.Tests/Shared.Tests.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + Exe + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + +